Home | History | Annotate | Download | only in orig
      1 /******************************************************************************
      2 ** This file is an amalgamation of many separate C source files from SQLite
      3 ** version 3.22.0.  By combining all the individual C code files into this
      4 ** single large file, the entire code can be compiled as a single translation
      5 ** unit.  This allows many compilers to do optimizations that would not be
      6 ** possible if the files were compiled separately.  Performance improvements
      7 ** of 5% or more are commonly seen when SQLite is compiled as a single
      8 ** translation unit.
      9 **
     10 ** This file is all you need to compile SQLite.  To use SQLite in other
     11 ** programs, you need this file and the "sqlite3.h" header file that defines
     12 ** the programming interface to the SQLite library.  (If you do not have
     13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
     14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
     15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
     16 ** if you want a wrapper to interface SQLite with your choice of programming
     17 ** language. The code for the "sqlite3" command-line shell is also in a
     18 ** separate file. This file contains only code for the core SQLite library.
     19 */
     20 #define SQLITE_CORE 1
     21 #define SQLITE_AMALGAMATION 1
     22 #ifndef SQLITE_PRIVATE
     23 # define SQLITE_PRIVATE static
     24 #endif
     25 /************** Begin file ctime.c *******************************************/
     26 /*
     27 ** 2010 February 23
     28 **
     29 ** The author disclaims copyright to this source code.  In place of
     30 ** a legal notice, here is a blessing:
     31 **
     32 **    May you do good and not evil.
     33 **    May you find forgiveness for yourself and forgive others.
     34 **    May you share freely, never taking more than you give.
     35 **
     36 *************************************************************************
     37 **
     38 ** This file implements routines used to report what compile-time options
     39 ** SQLite was built with.
     40 */
     41 
     42 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
     43 
     44 /*
     45 ** Include the configuration header output by 'configure' if we're using the
     46 ** autoconf-based build
     47 */
     48 #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
     49 #include "config.h"
     50 #define SQLITECONFIG_H 1
     51 #endif
     52 
     53 /* These macros are provided to "stringify" the value of the define
     54 ** for those options in which the value is meaningful. */
     55 #define CTIMEOPT_VAL_(opt) #opt
     56 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
     57 
     58 /*
     59 ** An array of names of all compile-time options.  This array should
     60 ** be sorted A-Z.
     61 **
     62 ** This array looks large, but in a typical installation actually uses
     63 ** only a handful of compile-time options, so most times this array is usually
     64 ** rather short and uses little memory space.
     65 */
     66 static const char * const sqlite3azCompileOpt[] = {
     67 
     68 /*
     69 ** BEGIN CODE GENERATED BY tool/mkctime.tcl
     70 */
     71 #if SQLITE_32BIT_ROWID
     72   "32BIT_ROWID",
     73 #endif
     74 #if SQLITE_4_BYTE_ALIGNED_MALLOC
     75   "4_BYTE_ALIGNED_MALLOC",
     76 #endif
     77 #if SQLITE_64BIT_STATS
     78   "64BIT_STATS",
     79 #endif
     80 #if SQLITE_ALLOW_COVERING_INDEX_SCAN
     81   "ALLOW_COVERING_INDEX_SCAN",
     82 #endif
     83 #if SQLITE_ALLOW_URI_AUTHORITY
     84   "ALLOW_URI_AUTHORITY",
     85 #endif
     86 #ifdef SQLITE_BITMASK_TYPE
     87   "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
     88 #endif
     89 #if SQLITE_BUG_COMPATIBLE_20160819
     90   "BUG_COMPATIBLE_20160819",
     91 #endif
     92 #if SQLITE_CASE_SENSITIVE_LIKE
     93   "CASE_SENSITIVE_LIKE",
     94 #endif
     95 #if SQLITE_CHECK_PAGES
     96   "CHECK_PAGES",
     97 #endif
     98 #if defined(__clang__) && defined(__clang_major__)
     99   "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
    100                     CTIMEOPT_VAL(__clang_minor__) "."
    101                     CTIMEOPT_VAL(__clang_patchlevel__),
    102 #elif defined(_MSC_VER)
    103   "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
    104 #elif defined(__GNUC__) && defined(__VERSION__)
    105   "COMPILER=gcc-" __VERSION__,
    106 #endif
    107 #if SQLITE_COVERAGE_TEST
    108   "COVERAGE_TEST",
    109 #endif
    110 #if SQLITE_DEBUG
    111   "DEBUG",
    112 #endif
    113 #if SQLITE_DEFAULT_AUTOMATIC_INDEX
    114   "DEFAULT_AUTOMATIC_INDEX",
    115 #endif
    116 #if SQLITE_DEFAULT_AUTOVACUUM
    117   "DEFAULT_AUTOVACUUM",
    118 #endif
    119 #ifdef SQLITE_DEFAULT_CACHE_SIZE
    120   "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
    121 #endif
    122 #if SQLITE_DEFAULT_CKPTFULLFSYNC
    123   "DEFAULT_CKPTFULLFSYNC",
    124 #endif
    125 #ifdef SQLITE_DEFAULT_FILE_FORMAT
    126   "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
    127 #endif
    128 #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
    129   "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
    130 #endif
    131 #if SQLITE_DEFAULT_FOREIGN_KEYS
    132   "DEFAULT_FOREIGN_KEYS",
    133 #endif
    134 #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
    135   "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
    136 #endif
    137 #ifdef SQLITE_DEFAULT_LOCKING_MODE
    138   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
    139 #endif
    140 #ifdef SQLITE_DEFAULT_LOOKASIDE
    141   "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOOKASIDE),
    142 #endif
    143 #if SQLITE_DEFAULT_MEMSTATUS
    144   "DEFAULT_MEMSTATUS",
    145 #endif
    146 #ifdef SQLITE_DEFAULT_MMAP_SIZE
    147   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
    148 #endif
    149 #ifdef SQLITE_DEFAULT_PAGE_SIZE
    150   "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
    151 #endif
    152 #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
    153   "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
    154 #endif
    155 #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
    156   "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
    157 #endif
    158 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
    159   "DEFAULT_RECURSIVE_TRIGGERS",
    160 #endif
    161 #ifdef SQLITE_DEFAULT_ROWEST
    162   "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
    163 #endif
    164 #ifdef SQLITE_DEFAULT_SECTOR_SIZE
    165   "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
    166 #endif
    167 #ifdef SQLITE_DEFAULT_SYNCHRONOUS
    168   "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
    169 #endif
    170 #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
    171   "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
    172 #endif
    173 #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
    174   "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
    175 #endif
    176 #ifdef SQLITE_DEFAULT_WORKER_THREADS
    177   "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
    178 #endif
    179 #if SQLITE_DIRECT_OVERFLOW_READ
    180   "DIRECT_OVERFLOW_READ",
    181 #endif
    182 #if SQLITE_DISABLE_DIRSYNC
    183   "DISABLE_DIRSYNC",
    184 #endif
    185 #if SQLITE_DISABLE_FTS3_UNICODE
    186   "DISABLE_FTS3_UNICODE",
    187 #endif
    188 #if SQLITE_DISABLE_FTS4_DEFERRED
    189   "DISABLE_FTS4_DEFERRED",
    190 #endif
    191 #if SQLITE_DISABLE_INTRINSIC
    192   "DISABLE_INTRINSIC",
    193 #endif
    194 #if SQLITE_DISABLE_LFS
    195   "DISABLE_LFS",
    196 #endif
    197 #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
    198   "DISABLE_PAGECACHE_OVERFLOW_STATS",
    199 #endif
    200 #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
    201   "DISABLE_SKIPAHEAD_DISTINCT",
    202 #endif
    203 #ifdef SQLITE_ENABLE_8_3_NAMES
    204   "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
    205 #endif
    206 #if SQLITE_ENABLE_API_ARMOR
    207   "ENABLE_API_ARMOR",
    208 #endif
    209 #if SQLITE_ENABLE_ATOMIC_WRITE
    210   "ENABLE_ATOMIC_WRITE",
    211 #endif
    212 #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
    213   "ENABLE_BATCH_ATOMIC_WRITE",
    214 #endif
    215 #if SQLITE_ENABLE_CEROD
    216   "ENABLE_CEROD",
    217 #endif
    218 #if SQLITE_ENABLE_COLUMN_METADATA
    219   "ENABLE_COLUMN_METADATA",
    220 #endif
    221 #if SQLITE_ENABLE_COLUMN_USED_MASK
    222   "ENABLE_COLUMN_USED_MASK",
    223 #endif
    224 #if SQLITE_ENABLE_COSTMULT
    225   "ENABLE_COSTMULT",
    226 #endif
    227 #if SQLITE_ENABLE_CURSOR_HINTS
    228   "ENABLE_CURSOR_HINTS",
    229 #endif
    230 #if SQLITE_ENABLE_DBSTAT_VTAB
    231   "ENABLE_DBSTAT_VTAB",
    232 #endif
    233 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
    234   "ENABLE_EXPENSIVE_ASSERT",
    235 #endif
    236 #if SQLITE_ENABLE_FTS1
    237   "ENABLE_FTS1",
    238 #endif
    239 #if SQLITE_ENABLE_FTS2
    240   "ENABLE_FTS2",
    241 #endif
    242 #if SQLITE_ENABLE_FTS3
    243   "ENABLE_FTS3",
    244 #endif
    245 #if SQLITE_ENABLE_FTS3_PARENTHESIS
    246   "ENABLE_FTS3_PARENTHESIS",
    247 #endif
    248 #if SQLITE_ENABLE_FTS3_TOKENIZER
    249   "ENABLE_FTS3_TOKENIZER",
    250 #endif
    251 #if SQLITE_ENABLE_FTS4
    252   "ENABLE_FTS4",
    253 #endif
    254 #if SQLITE_ENABLE_FTS5
    255   "ENABLE_FTS5",
    256 #endif
    257 #if SQLITE_ENABLE_HIDDEN_COLUMNS
    258   "ENABLE_HIDDEN_COLUMNS",
    259 #endif
    260 #if SQLITE_ENABLE_ICU
    261   "ENABLE_ICU",
    262 #endif
    263 #if SQLITE_ENABLE_IOTRACE
    264   "ENABLE_IOTRACE",
    265 #endif
    266 #if SQLITE_ENABLE_JSON1
    267   "ENABLE_JSON1",
    268 #endif
    269 #if SQLITE_ENABLE_LOAD_EXTENSION
    270   "ENABLE_LOAD_EXTENSION",
    271 #endif
    272 #ifdef SQLITE_ENABLE_LOCKING_STYLE
    273   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
    274 #endif
    275 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
    276   "ENABLE_MEMORY_MANAGEMENT",
    277 #endif
    278 #if SQLITE_ENABLE_MEMSYS3
    279   "ENABLE_MEMSYS3",
    280 #endif
    281 #if SQLITE_ENABLE_MEMSYS5
    282   "ENABLE_MEMSYS5",
    283 #endif
    284 #if SQLITE_ENABLE_MULTIPLEX
    285   "ENABLE_MULTIPLEX",
    286 #endif
    287 #if SQLITE_ENABLE_NULL_TRIM
    288   "ENABLE_NULL_TRIM",
    289 #endif
    290 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
    291   "ENABLE_OVERSIZE_CELL_CHECK",
    292 #endif
    293 #if SQLITE_ENABLE_PREUPDATE_HOOK
    294   "ENABLE_PREUPDATE_HOOK",
    295 #endif
    296 #if SQLITE_ENABLE_QPSG
    297   "ENABLE_QPSG",
    298 #endif
    299 #if SQLITE_ENABLE_RBU
    300   "ENABLE_RBU",
    301 #endif
    302 #if SQLITE_ENABLE_RTREE
    303   "ENABLE_RTREE",
    304 #endif
    305 #if SQLITE_ENABLE_SELECTTRACE
    306   "ENABLE_SELECTTRACE",
    307 #endif
    308 #if SQLITE_ENABLE_SESSION
    309   "ENABLE_SESSION",
    310 #endif
    311 #if SQLITE_ENABLE_SNAPSHOT
    312   "ENABLE_SNAPSHOT",
    313 #endif
    314 #if SQLITE_ENABLE_SQLLOG
    315   "ENABLE_SQLLOG",
    316 #endif
    317 #if defined(SQLITE_ENABLE_STAT4)
    318   "ENABLE_STAT4",
    319 #elif defined(SQLITE_ENABLE_STAT3)
    320   "ENABLE_STAT3",
    321 #endif
    322 #if SQLITE_ENABLE_STMTVTAB
    323   "ENABLE_STMTVTAB",
    324 #endif
    325 #if SQLITE_ENABLE_STMT_SCANSTATUS
    326   "ENABLE_STMT_SCANSTATUS",
    327 #endif
    328 #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
    329   "ENABLE_UNKNOWN_SQL_FUNCTION",
    330 #endif
    331 #if SQLITE_ENABLE_UNLOCK_NOTIFY
    332   "ENABLE_UNLOCK_NOTIFY",
    333 #endif
    334 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
    335   "ENABLE_UPDATE_DELETE_LIMIT",
    336 #endif
    337 #if SQLITE_ENABLE_URI_00_ERROR
    338   "ENABLE_URI_00_ERROR",
    339 #endif
    340 #if SQLITE_ENABLE_VFSTRACE
    341   "ENABLE_VFSTRACE",
    342 #endif
    343 #if SQLITE_ENABLE_WHERETRACE
    344   "ENABLE_WHERETRACE",
    345 #endif
    346 #if SQLITE_ENABLE_ZIPVFS
    347   "ENABLE_ZIPVFS",
    348 #endif
    349 #if SQLITE_EXPLAIN_ESTIMATED_ROWS
    350   "EXPLAIN_ESTIMATED_ROWS",
    351 #endif
    352 #if SQLITE_EXTRA_IFNULLROW
    353   "EXTRA_IFNULLROW",
    354 #endif
    355 #ifdef SQLITE_EXTRA_INIT
    356   "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
    357 #endif
    358 #ifdef SQLITE_EXTRA_SHUTDOWN
    359   "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
    360 #endif
    361 #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
    362   "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
    363 #endif
    364 #if SQLITE_FTS5_ENABLE_TEST_MI
    365   "FTS5_ENABLE_TEST_MI",
    366 #endif
    367 #if SQLITE_FTS5_NO_WITHOUT_ROWID
    368   "FTS5_NO_WITHOUT_ROWID",
    369 #endif
    370 #if SQLITE_HAS_CODEC
    371   "HAS_CODEC",
    372 #endif
    373 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
    374   "HAVE_ISNAN",
    375 #endif
    376 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
    377   "HOMEGROWN_RECURSIVE_MUTEX",
    378 #endif
    379 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
    380   "IGNORE_AFP_LOCK_ERRORS",
    381 #endif
    382 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
    383   "IGNORE_FLOCK_LOCK_ERRORS",
    384 #endif
    385 #if SQLITE_INLINE_MEMCPY
    386   "INLINE_MEMCPY",
    387 #endif
    388 #if SQLITE_INT64_TYPE
    389   "INT64_TYPE",
    390 #endif
    391 #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
    392   "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
    393 #endif
    394 #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
    395   "LIKE_DOESNT_MATCH_BLOBS",
    396 #endif
    397 #if SQLITE_LOCK_TRACE
    398   "LOCK_TRACE",
    399 #endif
    400 #if SQLITE_LOG_CACHE_SPILL
    401   "LOG_CACHE_SPILL",
    402 #endif
    403 #ifdef SQLITE_MALLOC_SOFT_LIMIT
    404   "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
    405 #endif
    406 #ifdef SQLITE_MAX_ATTACHED
    407   "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
    408 #endif
    409 #ifdef SQLITE_MAX_COLUMN
    410   "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
    411 #endif
    412 #ifdef SQLITE_MAX_COMPOUND_SELECT
    413   "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
    414 #endif
    415 #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
    416   "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
    417 #endif
    418 #ifdef SQLITE_MAX_EXPR_DEPTH
    419   "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
    420 #endif
    421 #ifdef SQLITE_MAX_FUNCTION_ARG
    422   "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
    423 #endif
    424 #ifdef SQLITE_MAX_LENGTH
    425   "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
    426 #endif
    427 #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
    428   "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
    429 #endif
    430 #ifdef SQLITE_MAX_MEMORY
    431   "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
    432 #endif
    433 #ifdef SQLITE_MAX_MMAP_SIZE
    434   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
    435 #endif
    436 #ifdef SQLITE_MAX_MMAP_SIZE_
    437   "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
    438 #endif
    439 #ifdef SQLITE_MAX_PAGE_COUNT
    440   "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
    441 #endif
    442 #ifdef SQLITE_MAX_PAGE_SIZE
    443   "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
    444 #endif
    445 #ifdef SQLITE_MAX_SCHEMA_RETRY
    446   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
    447 #endif
    448 #ifdef SQLITE_MAX_SQL_LENGTH
    449   "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
    450 #endif
    451 #ifdef SQLITE_MAX_TRIGGER_DEPTH
    452   "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
    453 #endif
    454 #ifdef SQLITE_MAX_VARIABLE_NUMBER
    455   "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
    456 #endif
    457 #ifdef SQLITE_MAX_VDBE_OP
    458   "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
    459 #endif
    460 #ifdef SQLITE_MAX_WORKER_THREADS
    461   "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
    462 #endif
    463 #if SQLITE_MEMDEBUG
    464   "MEMDEBUG",
    465 #endif
    466 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
    467   "MIXED_ENDIAN_64BIT_FLOAT",
    468 #endif
    469 #if SQLITE_MMAP_READWRITE
    470   "MMAP_READWRITE",
    471 #endif
    472 #if SQLITE_MUTEX_NOOP
    473   "MUTEX_NOOP",
    474 #endif
    475 #if SQLITE_MUTEX_NREF
    476   "MUTEX_NREF",
    477 #endif
    478 #if SQLITE_MUTEX_OMIT
    479   "MUTEX_OMIT",
    480 #endif
    481 #if SQLITE_MUTEX_PTHREADS
    482   "MUTEX_PTHREADS",
    483 #endif
    484 #if SQLITE_MUTEX_W32
    485   "MUTEX_W32",
    486 #endif
    487 #if SQLITE_NEED_ERR_NAME
    488   "NEED_ERR_NAME",
    489 #endif
    490 #if SQLITE_NOINLINE
    491   "NOINLINE",
    492 #endif
    493 #if SQLITE_NO_SYNC
    494   "NO_SYNC",
    495 #endif
    496 #if SQLITE_OMIT_ALTERTABLE
    497   "OMIT_ALTERTABLE",
    498 #endif
    499 #if SQLITE_OMIT_ANALYZE
    500   "OMIT_ANALYZE",
    501 #endif
    502 #if SQLITE_OMIT_ATTACH
    503   "OMIT_ATTACH",
    504 #endif
    505 #if SQLITE_OMIT_AUTHORIZATION
    506   "OMIT_AUTHORIZATION",
    507 #endif
    508 #if SQLITE_OMIT_AUTOINCREMENT
    509   "OMIT_AUTOINCREMENT",
    510 #endif
    511 #if SQLITE_OMIT_AUTOINIT
    512   "OMIT_AUTOINIT",
    513 #endif
    514 #if SQLITE_OMIT_AUTOMATIC_INDEX
    515   "OMIT_AUTOMATIC_INDEX",
    516 #endif
    517 #if SQLITE_OMIT_AUTORESET
    518   "OMIT_AUTORESET",
    519 #endif
    520 #if SQLITE_OMIT_AUTOVACUUM
    521   "OMIT_AUTOVACUUM",
    522 #endif
    523 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
    524   "OMIT_BETWEEN_OPTIMIZATION",
    525 #endif
    526 #if SQLITE_OMIT_BLOB_LITERAL
    527   "OMIT_BLOB_LITERAL",
    528 #endif
    529 #if SQLITE_OMIT_BTREECOUNT
    530   "OMIT_BTREECOUNT",
    531 #endif
    532 #if SQLITE_OMIT_CAST
    533   "OMIT_CAST",
    534 #endif
    535 #if SQLITE_OMIT_CHECK
    536   "OMIT_CHECK",
    537 #endif
    538 #if SQLITE_OMIT_COMPLETE
    539   "OMIT_COMPLETE",
    540 #endif
    541 #if SQLITE_OMIT_COMPOUND_SELECT
    542   "OMIT_COMPOUND_SELECT",
    543 #endif
    544 #if SQLITE_OMIT_CONFLICT_CLAUSE
    545   "OMIT_CONFLICT_CLAUSE",
    546 #endif
    547 #if SQLITE_OMIT_CTE
    548   "OMIT_CTE",
    549 #endif
    550 #if SQLITE_OMIT_DATETIME_FUNCS
    551   "OMIT_DATETIME_FUNCS",
    552 #endif
    553 #if SQLITE_OMIT_DECLTYPE
    554   "OMIT_DECLTYPE",
    555 #endif
    556 #if SQLITE_OMIT_DEPRECATED
    557   "OMIT_DEPRECATED",
    558 #endif
    559 #if SQLITE_OMIT_DISKIO
    560   "OMIT_DISKIO",
    561 #endif
    562 #if SQLITE_OMIT_EXPLAIN
    563   "OMIT_EXPLAIN",
    564 #endif
    565 #if SQLITE_OMIT_FLAG_PRAGMAS
    566   "OMIT_FLAG_PRAGMAS",
    567 #endif
    568 #if SQLITE_OMIT_FLOATING_POINT
    569   "OMIT_FLOATING_POINT",
    570 #endif
    571 #if SQLITE_OMIT_FOREIGN_KEY
    572   "OMIT_FOREIGN_KEY",
    573 #endif
    574 #if SQLITE_OMIT_GET_TABLE
    575   "OMIT_GET_TABLE",
    576 #endif
    577 #if SQLITE_OMIT_HEX_INTEGER
    578   "OMIT_HEX_INTEGER",
    579 #endif
    580 #if SQLITE_OMIT_INCRBLOB
    581   "OMIT_INCRBLOB",
    582 #endif
    583 #if SQLITE_OMIT_INTEGRITY_CHECK
    584   "OMIT_INTEGRITY_CHECK",
    585 #endif
    586 #if SQLITE_OMIT_LIKE_OPTIMIZATION
    587   "OMIT_LIKE_OPTIMIZATION",
    588 #endif
    589 #if SQLITE_OMIT_LOAD_EXTENSION
    590   "OMIT_LOAD_EXTENSION",
    591 #endif
    592 #if SQLITE_OMIT_LOCALTIME
    593   "OMIT_LOCALTIME",
    594 #endif
    595 #if SQLITE_OMIT_LOOKASIDE
    596   "OMIT_LOOKASIDE",
    597 #endif
    598 #if SQLITE_OMIT_MEMORYDB
    599   "OMIT_MEMORYDB",
    600 #endif
    601 #if SQLITE_OMIT_OR_OPTIMIZATION
    602   "OMIT_OR_OPTIMIZATION",
    603 #endif
    604 #if SQLITE_OMIT_PAGER_PRAGMAS
    605   "OMIT_PAGER_PRAGMAS",
    606 #endif
    607 #if SQLITE_OMIT_PARSER_TRACE
    608   "OMIT_PARSER_TRACE",
    609 #endif
    610 #if SQLITE_OMIT_POPEN
    611   "OMIT_POPEN",
    612 #endif
    613 #if SQLITE_OMIT_PRAGMA
    614   "OMIT_PRAGMA",
    615 #endif
    616 #if SQLITE_OMIT_PROGRESS_CALLBACK
    617   "OMIT_PROGRESS_CALLBACK",
    618 #endif
    619 #if SQLITE_OMIT_QUICKBALANCE
    620   "OMIT_QUICKBALANCE",
    621 #endif
    622 #if SQLITE_OMIT_REINDEX
    623   "OMIT_REINDEX",
    624 #endif
    625 #if SQLITE_OMIT_SCHEMA_PRAGMAS
    626   "OMIT_SCHEMA_PRAGMAS",
    627 #endif
    628 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
    629   "OMIT_SCHEMA_VERSION_PRAGMAS",
    630 #endif
    631 #if SQLITE_OMIT_SHARED_CACHE
    632   "OMIT_SHARED_CACHE",
    633 #endif
    634 #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
    635   "OMIT_SHUTDOWN_DIRECTORIES",
    636 #endif
    637 #if SQLITE_OMIT_SUBQUERY
    638   "OMIT_SUBQUERY",
    639 #endif
    640 #if SQLITE_OMIT_TCL_VARIABLE
    641   "OMIT_TCL_VARIABLE",
    642 #endif
    643 #if SQLITE_OMIT_TEMPDB
    644   "OMIT_TEMPDB",
    645 #endif
    646 #if SQLITE_OMIT_TEST_CONTROL
    647   "OMIT_TEST_CONTROL",
    648 #endif
    649 #if SQLITE_OMIT_TRACE
    650   "OMIT_TRACE",
    651 #endif
    652 #if SQLITE_OMIT_TRIGGER
    653   "OMIT_TRIGGER",
    654 #endif
    655 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
    656   "OMIT_TRUNCATE_OPTIMIZATION",
    657 #endif
    658 #if SQLITE_OMIT_UTF16
    659   "OMIT_UTF16",
    660 #endif
    661 #if SQLITE_OMIT_VACUUM
    662   "OMIT_VACUUM",
    663 #endif
    664 #if SQLITE_OMIT_VIEW
    665   "OMIT_VIEW",
    666 #endif
    667 #if SQLITE_OMIT_VIRTUALTABLE
    668   "OMIT_VIRTUALTABLE",
    669 #endif
    670 #if SQLITE_OMIT_WAL
    671   "OMIT_WAL",
    672 #endif
    673 #if SQLITE_OMIT_WSD
    674   "OMIT_WSD",
    675 #endif
    676 #if SQLITE_OMIT_XFER_OPT
    677   "OMIT_XFER_OPT",
    678 #endif
    679 #if SQLITE_PCACHE_SEPARATE_HEADER
    680   "PCACHE_SEPARATE_HEADER",
    681 #endif
    682 #if SQLITE_PERFORMANCE_TRACE
    683   "PERFORMANCE_TRACE",
    684 #endif
    685 #if SQLITE_POWERSAFE_OVERWRITE
    686   "POWERSAFE_OVERWRITE",
    687 #endif
    688 #if SQLITE_PREFER_PROXY_LOCKING
    689   "PREFER_PROXY_LOCKING",
    690 #endif
    691 #if SQLITE_PROXY_DEBUG
    692   "PROXY_DEBUG",
    693 #endif
    694 #if SQLITE_REVERSE_UNORDERED_SELECTS
    695   "REVERSE_UNORDERED_SELECTS",
    696 #endif
    697 #if SQLITE_RTREE_INT_ONLY
    698   "RTREE_INT_ONLY",
    699 #endif
    700 #if SQLITE_SECURE_DELETE
    701   "SECURE_DELETE",
    702 #endif
    703 #if SQLITE_SMALL_STACK
    704   "SMALL_STACK",
    705 #endif
    706 #ifdef SQLITE_SORTER_PMASZ
    707   "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
    708 #endif
    709 #if SQLITE_SOUNDEX
    710   "SOUNDEX",
    711 #endif
    712 #ifdef SQLITE_STAT4_SAMPLES
    713   "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
    714 #endif
    715 #ifdef SQLITE_STMTJRNL_SPILL
    716   "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
    717 #endif
    718 #if SQLITE_SUBSTR_COMPATIBILITY
    719   "SUBSTR_COMPATIBILITY",
    720 #endif
    721 #if SQLITE_SYSTEM_MALLOC
    722   "SYSTEM_MALLOC",
    723 #endif
    724 #if SQLITE_TCL
    725   "TCL",
    726 #endif
    727 #ifdef SQLITE_TEMP_STORE
    728   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
    729 #endif
    730 #if SQLITE_TEST
    731   "TEST",
    732 #endif
    733 #if defined(SQLITE_THREADSAFE)
    734   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
    735 #elif defined(THREADSAFE)
    736   "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
    737 #else
    738   "THREADSAFE=1",
    739 #endif
    740 #if SQLITE_UNLINK_AFTER_CLOSE
    741   "UNLINK_AFTER_CLOSE",
    742 #endif
    743 #if SQLITE_UNTESTABLE
    744   "UNTESTABLE",
    745 #endif
    746 #if SQLITE_USER_AUTHENTICATION
    747   "USER_AUTHENTICATION",
    748 #endif
    749 #if SQLITE_USE_ALLOCA
    750   "USE_ALLOCA",
    751 #endif
    752 #if SQLITE_USE_FCNTL_TRACE
    753   "USE_FCNTL_TRACE",
    754 #endif
    755 #if SQLITE_USE_URI
    756   "USE_URI",
    757 #endif
    758 #if SQLITE_VDBE_COVERAGE
    759   "VDBE_COVERAGE",
    760 #endif
    761 #if SQLITE_WIN32_MALLOC
    762   "WIN32_MALLOC",
    763 #endif
    764 #if SQLITE_ZERO_MALLOC
    765   "ZERO_MALLOC",
    766 #endif
    767 /*
    768 ** END CODE GENERATED BY tool/mkctime.tcl
    769 */
    770 };
    771 
    772 SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
    773   *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
    774   return (const char**)sqlite3azCompileOpt;
    775 }
    776 
    777 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
    778 
    779 /************** End of ctime.c ***********************************************/
    780 /************** Begin file sqliteInt.h ***************************************/
    781 /*
    782 ** 2001 September 15
    783 **
    784 ** The author disclaims copyright to this source code.  In place of
    785 ** a legal notice, here is a blessing:
    786 **
    787 **    May you do good and not evil.
    788 **    May you find forgiveness for yourself and forgive others.
    789 **    May you share freely, never taking more than you give.
    790 **
    791 *************************************************************************
    792 ** Internal interface definitions for SQLite.
    793 **
    794 */
    795 #ifndef SQLITEINT_H
    796 #define SQLITEINT_H
    797 
    798 /* Special Comments:
    799 **
    800 ** Some comments have special meaning to the tools that measure test
    801 ** coverage:
    802 **
    803 **    NO_TEST                     - The branches on this line are not
    804 **                                  measured by branch coverage.  This is
    805 **                                  used on lines of code that actually
    806 **                                  implement parts of coverage testing.
    807 **
    808 **    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
    809 **                                  and the correct answer is still obtained,
    810 **                                  though perhaps more slowly.
    811 **
    812 **    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
    813 **                                  and the correct answer is still obtained,
    814 **                                  though perhaps more slowly.
    815 **
    816 **    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
    817 **                                  that would be harmless and undetectable
    818 **                                  if it did occur.
    819 **
    820 ** In all cases, the special comment must be enclosed in the usual
    821 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
    822 ** asterisks and the comment text.
    823 */
    824 
    825 /*
    826 ** Make sure the Tcl calling convention macro is defined.  This macro is
    827 ** only used by test code and Tcl integration code.
    828 */
    829 #ifndef SQLITE_TCLAPI
    830 #  define SQLITE_TCLAPI
    831 #endif
    832 
    833 /*
    834 ** Include the header file used to customize the compiler options for MSVC.
    835 ** This should be done first so that it can successfully prevent spurious
    836 ** compiler warnings due to subsequent content in this file and other files
    837 ** that are included by this file.
    838 */
    839 /************** Include msvc.h in the middle of sqliteInt.h ******************/
    840 /************** Begin file msvc.h ********************************************/
    841 /*
    842 ** 2015 January 12
    843 **
    844 ** The author disclaims copyright to this source code.  In place of
    845 ** a legal notice, here is a blessing:
    846 **
    847 **    May you do good and not evil.
    848 **    May you find forgiveness for yourself and forgive others.
    849 **    May you share freely, never taking more than you give.
    850 **
    851 ******************************************************************************
    852 **
    853 ** This file contains code that is specific to MSVC.
    854 */
    855 #ifndef SQLITE_MSVC_H
    856 #define SQLITE_MSVC_H
    857 
    858 #if defined(_MSC_VER)
    859 #pragma warning(disable : 4054)
    860 #pragma warning(disable : 4055)
    861 #pragma warning(disable : 4100)
    862 #pragma warning(disable : 4127)
    863 #pragma warning(disable : 4130)
    864 #pragma warning(disable : 4152)
    865 #pragma warning(disable : 4189)
    866 #pragma warning(disable : 4206)
    867 #pragma warning(disable : 4210)
    868 #pragma warning(disable : 4232)
    869 #pragma warning(disable : 4244)
    870 #pragma warning(disable : 4305)
    871 #pragma warning(disable : 4306)
    872 #pragma warning(disable : 4702)
    873 #pragma warning(disable : 4706)
    874 #endif /* defined(_MSC_VER) */
    875 
    876 #endif /* SQLITE_MSVC_H */
    877 
    878 /************** End of msvc.h ************************************************/
    879 /************** Continuing where we left off in sqliteInt.h ******************/
    880 
    881 /*
    882 ** Special setup for VxWorks
    883 */
    884 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
    885 /************** Begin file vxworks.h *****************************************/
    886 /*
    887 ** 2015-03-02
    888 **
    889 ** The author disclaims copyright to this source code.  In place of
    890 ** a legal notice, here is a blessing:
    891 **
    892 **    May you do good and not evil.
    893 **    May you find forgiveness for yourself and forgive others.
    894 **    May you share freely, never taking more than you give.
    895 **
    896 ******************************************************************************
    897 **
    898 ** This file contains code that is specific to Wind River's VxWorks
    899 */
    900 #if defined(__RTP__) || defined(_WRS_KERNEL)
    901 /* This is VxWorks.  Set up things specially for that OS
    902 */
    903 #include <vxWorks.h>
    904 #include <pthread.h>  /* amalgamator: dontcache */
    905 #define OS_VXWORKS 1
    906 #define SQLITE_OS_OTHER 0
    907 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
    908 #define SQLITE_OMIT_LOAD_EXTENSION 1
    909 #define SQLITE_ENABLE_LOCKING_STYLE 0
    910 #define HAVE_UTIME 1
    911 #else
    912 /* This is not VxWorks. */
    913 #define OS_VXWORKS 0
    914 #define HAVE_FCHOWN 1
    915 #define HAVE_READLINK 1
    916 #define HAVE_LSTAT 1
    917 #endif /* defined(_WRS_KERNEL) */
    918 
    919 /************** End of vxworks.h *********************************************/
    920 /************** Continuing where we left off in sqliteInt.h ******************/
    921 
    922 /*
    923 ** These #defines should enable >2GB file support on POSIX if the
    924 ** underlying operating system supports it.  If the OS lacks
    925 ** large file support, or if the OS is windows, these should be no-ops.
    926 **
    927 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
    928 ** system #includes.  Hence, this block of code must be the very first
    929 ** code in all source files.
    930 **
    931 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
    932 ** on the compiler command line.  This is necessary if you are compiling
    933 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
    934 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
    935 ** without this option, LFS is enable.  But LFS does not exist in the kernel
    936 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
    937 ** portability you should omit LFS.
    938 **
    939 ** The previous paragraph was written in 2005.  (This paragraph is written
    940 ** on 2008-11-28.) These days, all Linux kernels support large files, so
    941 ** you should probably leave LFS enabled.  But some embedded platforms might
    942 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
    943 **
    944 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
    945 */
    946 #ifndef SQLITE_DISABLE_LFS
    947 # define _LARGE_FILE       1
    948 # ifndef _FILE_OFFSET_BITS
    949 #   define _FILE_OFFSET_BITS 64
    950 # endif
    951 # define _LARGEFILE_SOURCE 1
    952 #endif
    953 
    954 /* The GCC_VERSION and MSVC_VERSION macros are used to
    955 ** conditionally include optimizations for each of these compilers.  A
    956 ** value of 0 means that compiler is not being used.  The
    957 ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
    958 ** optimizations, and hence set all compiler macros to 0
    959 **
    960 ** There was once also a CLANG_VERSION macro.  However, we learn that the
    961 ** version numbers in clang are for "marketing" only and are inconsistent
    962 ** and unreliable.  Fortunately, all versions of clang also recognize the
    963 ** gcc version numbers and have reasonable settings for gcc version numbers,
    964 ** so the GCC_VERSION macro will be set to a correct non-zero value even
    965 ** when compiling with clang.
    966 */
    967 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
    968 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
    969 #else
    970 # define GCC_VERSION 0
    971 #endif
    972 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
    973 # define MSVC_VERSION _MSC_VER
    974 #else
    975 # define MSVC_VERSION 0
    976 #endif
    977 
    978 /* Needed for various definitions... */
    979 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
    980 # define _GNU_SOURCE
    981 #endif
    982 
    983 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
    984 # define _BSD_SOURCE
    985 #endif
    986 
    987 /*
    988 ** For MinGW, check to see if we can include the header file containing its
    989 ** version information, among other things.  Normally, this internal MinGW
    990 ** header file would [only] be included automatically by other MinGW header
    991 ** files; however, the contained version information is now required by this
    992 ** header file to work around binary compatibility issues (see below) and
    993 ** this is the only known way to reliably obtain it.  This entire #if block
    994 ** would be completely unnecessary if there was any other way of detecting
    995 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
    996 ** some MinGW-specific macros).  When compiling for MinGW, either the
    997 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
    998 ** defined; otherwise, detection of conditions specific to MinGW will be
    999 ** disabled.
   1000 */
   1001 #if defined(_HAVE_MINGW_H)
   1002 # include "mingw.h"
   1003 #elif defined(_HAVE__MINGW_H)
   1004 # include "_mingw.h"
   1005 #endif
   1006 
   1007 /*
   1008 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
   1009 ** define is required to maintain binary compatibility with the MSVC runtime
   1010 ** library in use (e.g. for Windows XP).
   1011 */
   1012 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
   1013     defined(_WIN32) && !defined(_WIN64) && \
   1014     defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
   1015     defined(__MSVCRT__)
   1016 # define _USE_32BIT_TIME_T
   1017 #endif
   1018 
   1019 /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
   1020 ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
   1021 ** MinGW.
   1022 */
   1023 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
   1024 /************** Begin file sqlite3.h *****************************************/
   1025 /*
   1026 ** 2001-09-15
   1027 **
   1028 ** The author disclaims copyright to this source code.  In place of
   1029 ** a legal notice, here is a blessing:
   1030 **
   1031 **    May you do good and not evil.
   1032 **    May you find forgiveness for yourself and forgive others.
   1033 **    May you share freely, never taking more than you give.
   1034 **
   1035 *************************************************************************
   1036 ** This header file defines the interface that the SQLite library
   1037 ** presents to client programs.  If a C-function, structure, datatype,
   1038 ** or constant definition does not appear in this file, then it is
   1039 ** not a published API of SQLite, is subject to change without
   1040 ** notice, and should not be referenced by programs that use SQLite.
   1041 **
   1042 ** Some of the definitions that are in this file are marked as
   1043 ** "experimental".  Experimental interfaces are normally new
   1044 ** features recently added to SQLite.  We do not anticipate changes
   1045 ** to experimental interfaces but reserve the right to make minor changes
   1046 ** if experience from use "in the wild" suggest such changes are prudent.
   1047 **
   1048 ** The official C-language API documentation for SQLite is derived
   1049 ** from comments in this file.  This file is the authoritative source
   1050 ** on how SQLite interfaces are supposed to operate.
   1051 **
   1052 ** The name of this file under configuration management is "sqlite.h.in".
   1053 ** The makefile makes some minor changes to this file (such as inserting
   1054 ** the version number) and changes its name to "sqlite3.h" as
   1055 ** part of the build process.
   1056 */
   1057 #ifndef SQLITE3_H
   1058 #define SQLITE3_H
   1059 #include <stdarg.h>     /* Needed for the definition of va_list */
   1060 
   1061 /*
   1062 ** Make sure we can call this stuff from C++.
   1063 */
   1064 #if 0
   1065 extern "C" {
   1066 #endif
   1067 
   1068 
   1069 /*
   1070 ** Provide the ability to override linkage features of the interface.
   1071 */
   1072 #ifndef SQLITE_EXTERN
   1073 # define SQLITE_EXTERN extern
   1074 #endif
   1075 #ifndef SQLITE_API
   1076 # define SQLITE_API
   1077 #endif
   1078 #ifndef SQLITE_CDECL
   1079 # define SQLITE_CDECL
   1080 #endif
   1081 #ifndef SQLITE_APICALL
   1082 # define SQLITE_APICALL
   1083 #endif
   1084 #ifndef SQLITE_STDCALL
   1085 # define SQLITE_STDCALL SQLITE_APICALL
   1086 #endif
   1087 #ifndef SQLITE_CALLBACK
   1088 # define SQLITE_CALLBACK
   1089 #endif
   1090 #ifndef SQLITE_SYSAPI
   1091 # define SQLITE_SYSAPI
   1092 #endif
   1093 
   1094 /*
   1095 ** These no-op macros are used in front of interfaces to mark those
   1096 ** interfaces as either deprecated or experimental.  New applications
   1097 ** should not use deprecated interfaces - they are supported for backwards
   1098 ** compatibility only.  Application writers should be aware that
   1099 ** experimental interfaces are subject to change in point releases.
   1100 **
   1101 ** These macros used to resolve to various kinds of compiler magic that
   1102 ** would generate warning messages when they were used.  But that
   1103 ** compiler magic ended up generating such a flurry of bug reports
   1104 ** that we have taken it all out and gone back to using simple
   1105 ** noop macros.
   1106 */
   1107 #define SQLITE_DEPRECATED
   1108 #define SQLITE_EXPERIMENTAL
   1109 
   1110 /*
   1111 ** Ensure these symbols were not defined by some previous header file.
   1112 */
   1113 #ifdef SQLITE_VERSION
   1114 # undef SQLITE_VERSION
   1115 #endif
   1116 #ifdef SQLITE_VERSION_NUMBER
   1117 # undef SQLITE_VERSION_NUMBER
   1118 #endif
   1119 
   1120 /*
   1121 ** CAPI3REF: Compile-Time Library Version Numbers
   1122 **
   1123 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
   1124 ** evaluates to a string literal that is the SQLite version in the
   1125 ** format "X.Y.Z" where X is the major version number (always 3 for
   1126 ** SQLite3) and Y is the minor version number and Z is the release number.)^
   1127 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
   1128 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
   1129 ** numbers used in [SQLITE_VERSION].)^
   1130 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
   1131 ** be larger than the release from which it is derived.  Either Y will
   1132 ** be held constant and Z will be incremented or else Y will be incremented
   1133 ** and Z will be reset to zero.
   1134 **
   1135 ** Since [version 3.6.18] ([dateof:3.6.18]),
   1136 ** SQLite source code has been stored in the
   1137 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
   1138 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
   1139 ** a string which identifies a particular check-in of SQLite
   1140 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
   1141 ** string contains the date and time of the check-in (UTC) and a SHA1
   1142 ** or SHA3-256 hash of the entire source tree.  If the source code has
   1143 ** been edited in any way since it was last checked in, then the last
   1144 ** four hexadecimal digits of the hash may be modified.
   1145 **
   1146 ** See also: [sqlite3_libversion()],
   1147 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
   1148 ** [sqlite_version()] and [sqlite_source_id()].
   1149 */
   1150 #define SQLITE_VERSION        "3.22.0"
   1151 #define SQLITE_VERSION_NUMBER 3022000
   1152 #define SQLITE_SOURCE_ID      "2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2171d"
   1153 
   1154 /*
   1155 ** CAPI3REF: Run-Time Library Version Numbers
   1156 ** KEYWORDS: sqlite3_version sqlite3_sourceid
   1157 **
   1158 ** These interfaces provide the same information as the [SQLITE_VERSION],
   1159 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
   1160 ** but are associated with the library instead of the header file.  ^(Cautious
   1161 ** programmers might include assert() statements in their application to
   1162 ** verify that values returned by these interfaces match the macros in
   1163 ** the header, and thus ensure that the application is
   1164 ** compiled with matching library and header files.
   1165 **
   1166 ** <blockquote><pre>
   1167 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
   1168 ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
   1169 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
   1170 ** </pre></blockquote>)^
   1171 **
   1172 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
   1173 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
   1174 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
   1175 ** function is provided for use in DLLs since DLL users usually do not have
   1176 ** direct access to string constants within the DLL.  ^The
   1177 ** sqlite3_libversion_number() function returns an integer equal to
   1178 ** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns
   1179 ** a pointer to a string constant whose value is the same as the
   1180 ** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built
   1181 ** using an edited copy of [the amalgamation], then the last four characters
   1182 ** of the hash might be different from [SQLITE_SOURCE_ID].)^
   1183 **
   1184 ** See also: [sqlite_version()] and [sqlite_source_id()].
   1185 */
   1186 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   1187 SQLITE_API const char *sqlite3_libversion(void);
   1188 SQLITE_API const char *sqlite3_sourceid(void);
   1189 SQLITE_API int sqlite3_libversion_number(void);
   1190 
   1191 /*
   1192 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
   1193 **
   1194 ** ^The sqlite3_compileoption_used() function returns 0 or 1
   1195 ** indicating whether the specified option was defined at
   1196 ** compile time.  ^The SQLITE_ prefix may be omitted from the
   1197 ** option name passed to sqlite3_compileoption_used().
   1198 **
   1199 ** ^The sqlite3_compileoption_get() function allows iterating
   1200 ** over the list of options that were defined at compile time by
   1201 ** returning the N-th compile time option string.  ^If N is out of range,
   1202 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
   1203 ** prefix is omitted from any strings returned by
   1204 ** sqlite3_compileoption_get().
   1205 **
   1206 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
   1207 ** and sqlite3_compileoption_get() may be omitted by specifying the
   1208 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
   1209 **
   1210 ** See also: SQL functions [sqlite_compileoption_used()] and
   1211 ** [sqlite_compileoption_get()] and the [compile_options pragma].
   1212 */
   1213 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   1214 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
   1215 SQLITE_API const char *sqlite3_compileoption_get(int N);
   1216 #endif
   1217 
   1218 /*
   1219 ** CAPI3REF: Test To See If The Library Is Threadsafe
   1220 **
   1221 ** ^The sqlite3_threadsafe() function returns zero if and only if
   1222 ** SQLite was compiled with mutexing code omitted due to the
   1223 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
   1224 **
   1225 ** SQLite can be compiled with or without mutexes.  When
   1226 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
   1227 ** are enabled and SQLite is threadsafe.  When the
   1228 ** [SQLITE_THREADSAFE] macro is 0,
   1229 ** the mutexes are omitted.  Without the mutexes, it is not safe
   1230 ** to use SQLite concurrently from more than one thread.
   1231 **
   1232 ** Enabling mutexes incurs a measurable performance penalty.
   1233 ** So if speed is of utmost importance, it makes sense to disable
   1234 ** the mutexes.  But for maximum safety, mutexes should be enabled.
   1235 ** ^The default behavior is for mutexes to be enabled.
   1236 **
   1237 ** This interface can be used by an application to make sure that the
   1238 ** version of SQLite that it is linking against was compiled with
   1239 ** the desired setting of the [SQLITE_THREADSAFE] macro.
   1240 **
   1241 ** This interface only reports on the compile-time mutex setting
   1242 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
   1243 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
   1244 ** can be fully or partially disabled using a call to [sqlite3_config()]
   1245 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
   1246 ** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
   1247 ** sqlite3_threadsafe() function shows only the compile-time setting of
   1248 ** thread safety, not any run-time changes to that setting made by
   1249 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
   1250 ** is unchanged by calls to sqlite3_config().)^
   1251 **
   1252 ** See the [threading mode] documentation for additional information.
   1253 */
   1254 SQLITE_API int sqlite3_threadsafe(void);
   1255 
   1256 /*
   1257 ** CAPI3REF: Database Connection Handle
   1258 ** KEYWORDS: {database connection} {database connections}
   1259 **
   1260 ** Each open SQLite database is represented by a pointer to an instance of
   1261 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
   1262 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
   1263 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
   1264 ** and [sqlite3_close_v2()] are its destructors.  There are many other
   1265 ** interfaces (such as
   1266 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
   1267 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
   1268 ** sqlite3 object.
   1269 */
   1270 typedef struct sqlite3 sqlite3;
   1271 
   1272 /*
   1273 ** CAPI3REF: 64-Bit Integer Types
   1274 ** KEYWORDS: sqlite_int64 sqlite_uint64
   1275 **
   1276 ** Because there is no cross-platform way to specify 64-bit integer types
   1277 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
   1278 **
   1279 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
   1280 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
   1281 ** compatibility only.
   1282 **
   1283 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
   1284 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
   1285 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
   1286 ** between 0 and +18446744073709551615 inclusive.
   1287 */
   1288 #ifdef SQLITE_INT64_TYPE
   1289   typedef SQLITE_INT64_TYPE sqlite_int64;
   1290 # ifdef SQLITE_UINT64_TYPE
   1291     typedef SQLITE_UINT64_TYPE sqlite_uint64;
   1292 # else
   1293     typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
   1294 # endif
   1295 #elif defined(_MSC_VER) || defined(__BORLANDC__)
   1296   typedef __int64 sqlite_int64;
   1297   typedef unsigned __int64 sqlite_uint64;
   1298 #else
   1299   typedef long long int sqlite_int64;
   1300   typedef unsigned long long int sqlite_uint64;
   1301 #endif
   1302 typedef sqlite_int64 sqlite3_int64;
   1303 typedef sqlite_uint64 sqlite3_uint64;
   1304 
   1305 /*
   1306 ** If compiling for a processor that lacks floating point support,
   1307 ** substitute integer for floating-point.
   1308 */
   1309 #ifdef SQLITE_OMIT_FLOATING_POINT
   1310 # define double sqlite3_int64
   1311 #endif
   1312 
   1313 /*
   1314 ** CAPI3REF: Closing A Database Connection
   1315 ** DESTRUCTOR: sqlite3
   1316 **
   1317 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
   1318 ** for the [sqlite3] object.
   1319 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
   1320 ** the [sqlite3] object is successfully destroyed and all associated
   1321 ** resources are deallocated.
   1322 **
   1323 ** ^If the database connection is associated with unfinalized prepared
   1324 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
   1325 ** will leave the database connection open and return [SQLITE_BUSY].
   1326 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
   1327 ** and/or unfinished sqlite3_backups, then the database connection becomes
   1328 ** an unusable "zombie" which will automatically be deallocated when the
   1329 ** last prepared statement is finalized or the last sqlite3_backup is
   1330 ** finished.  The sqlite3_close_v2() interface is intended for use with
   1331 ** host languages that are garbage collected, and where the order in which
   1332 ** destructors are called is arbitrary.
   1333 **
   1334 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
   1335 ** [sqlite3_blob_close | close] all [BLOB handles], and
   1336 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
   1337 ** with the [sqlite3] object prior to attempting to close the object.  ^If
   1338 ** sqlite3_close_v2() is called on a [database connection] that still has
   1339 ** outstanding [prepared statements], [BLOB handles], and/or
   1340 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
   1341 ** of resources is deferred until all [prepared statements], [BLOB handles],
   1342 ** and [sqlite3_backup] objects are also destroyed.
   1343 **
   1344 ** ^If an [sqlite3] object is destroyed while a transaction is open,
   1345 ** the transaction is automatically rolled back.
   1346 **
   1347 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
   1348 ** must be either a NULL
   1349 ** pointer or an [sqlite3] object pointer obtained
   1350 ** from [sqlite3_open()], [sqlite3_open16()], or
   1351 ** [sqlite3_open_v2()], and not previously closed.
   1352 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
   1353 ** argument is a harmless no-op.
   1354 */
   1355 SQLITE_API int sqlite3_close(sqlite3*);
   1356 SQLITE_API int sqlite3_close_v2(sqlite3*);
   1357 
   1358 /*
   1359 ** The type for a callback function.
   1360 ** This is legacy and deprecated.  It is included for historical
   1361 ** compatibility and is not documented.
   1362 */
   1363 typedef int (*sqlite3_callback)(void*,int,char**, char**);
   1364 
   1365 /*
   1366 ** CAPI3REF: One-Step Query Execution Interface
   1367 ** METHOD: sqlite3
   1368 **
   1369 ** The sqlite3_exec() interface is a convenience wrapper around
   1370 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
   1371 ** that allows an application to run multiple statements of SQL
   1372 ** without having to use a lot of C code.
   1373 **
   1374 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
   1375 ** semicolon-separate SQL statements passed into its 2nd argument,
   1376 ** in the context of the [database connection] passed in as its 1st
   1377 ** argument.  ^If the callback function of the 3rd argument to
   1378 ** sqlite3_exec() is not NULL, then it is invoked for each result row
   1379 ** coming out of the evaluated SQL statements.  ^The 4th argument to
   1380 ** sqlite3_exec() is relayed through to the 1st argument of each
   1381 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
   1382 ** is NULL, then no callback is ever invoked and result rows are
   1383 ** ignored.
   1384 **
   1385 ** ^If an error occurs while evaluating the SQL statements passed into
   1386 ** sqlite3_exec(), then execution of the current statement stops and
   1387 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
   1388 ** is not NULL then any error message is written into memory obtained
   1389 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
   1390 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
   1391 ** on error message strings returned through the 5th parameter of
   1392 ** sqlite3_exec() after the error message string is no longer needed.
   1393 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
   1394 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
   1395 ** NULL before returning.
   1396 **
   1397 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
   1398 ** routine returns SQLITE_ABORT without invoking the callback again and
   1399 ** without running any subsequent SQL statements.
   1400 **
   1401 ** ^The 2nd argument to the sqlite3_exec() callback function is the
   1402 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
   1403 ** callback is an array of pointers to strings obtained as if from
   1404 ** [sqlite3_column_text()], one for each column.  ^If an element of a
   1405 ** result row is NULL then the corresponding string pointer for the
   1406 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
   1407 ** sqlite3_exec() callback is an array of pointers to strings where each
   1408 ** entry represents the name of corresponding result column as obtained
   1409 ** from [sqlite3_column_name()].
   1410 **
   1411 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
   1412 ** to an empty string, or a pointer that contains only whitespace and/or
   1413 ** SQL comments, then no SQL statements are evaluated and the database
   1414 ** is not changed.
   1415 **
   1416 ** Restrictions:
   1417 **
   1418 ** <ul>
   1419 ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
   1420 **      is a valid and open [database connection].
   1421 ** <li> The application must not close the [database connection] specified by
   1422 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
   1423 ** <li> The application must not modify the SQL statement text passed into
   1424 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
   1425 ** </ul>
   1426 */
   1427 SQLITE_API int sqlite3_exec(
   1428   sqlite3*,                                  /* An open database */
   1429   const char *sql,                           /* SQL to be evaluated */
   1430   int (*callback)(void*,int,char**,char**),  /* Callback function */
   1431   void *,                                    /* 1st argument to callback */
   1432   char **errmsg                              /* Error msg written here */
   1433 );
   1434 
   1435 /*
   1436 ** CAPI3REF: Result Codes
   1437 ** KEYWORDS: {result code definitions}
   1438 **
   1439 ** Many SQLite functions return an integer result code from the set shown
   1440 ** here in order to indicate success or failure.
   1441 **
   1442 ** New error codes may be added in future versions of SQLite.
   1443 **
   1444 ** See also: [extended result code definitions]
   1445 */
   1446 #define SQLITE_OK           0   /* Successful result */
   1447 /* beginning-of-error-codes */
   1448 #define SQLITE_ERROR        1   /* Generic error */
   1449 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
   1450 #define SQLITE_PERM         3   /* Access permission denied */
   1451 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
   1452 #define SQLITE_BUSY         5   /* The database file is locked */
   1453 #define SQLITE_LOCKED       6   /* A table in the database is locked */
   1454 #define SQLITE_NOMEM        7   /* A malloc() failed */
   1455 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
   1456 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
   1457 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
   1458 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
   1459 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
   1460 #define SQLITE_FULL        13   /* Insertion failed because database is full */
   1461 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
   1462 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
   1463 #define SQLITE_EMPTY       16   /* Internal use only */
   1464 #define SQLITE_SCHEMA      17   /* The database schema changed */
   1465 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
   1466 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
   1467 #define SQLITE_MISMATCH    20   /* Data type mismatch */
   1468 #define SQLITE_MISUSE      21   /* Library used incorrectly */
   1469 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
   1470 #define SQLITE_AUTH        23   /* Authorization denied */
   1471 #define SQLITE_FORMAT      24   /* Not used */
   1472 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
   1473 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
   1474 #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
   1475 #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
   1476 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
   1477 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
   1478 /* end-of-error-codes */
   1479 
   1480 /*
   1481 ** CAPI3REF: Extended Result Codes
   1482 ** KEYWORDS: {extended result code definitions}
   1483 **
   1484 ** In its default configuration, SQLite API routines return one of 30 integer
   1485 ** [result codes].  However, experience has shown that many of
   1486 ** these result codes are too coarse-grained.  They do not provide as
   1487 ** much information about problems as programmers might like.  In an effort to
   1488 ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
   1489 ** and later) include
   1490 ** support for additional result codes that provide more detailed information
   1491 ** about errors. These [extended result codes] are enabled or disabled
   1492 ** on a per database connection basis using the
   1493 ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
   1494 ** the most recent error can be obtained using
   1495 ** [sqlite3_extended_errcode()].
   1496 */
   1497 #define SQLITE_ERROR_MISSING_COLLSEQ   (SQLITE_ERROR | (1<<8))
   1498 #define SQLITE_ERROR_RETRY             (SQLITE_ERROR | (2<<8))
   1499 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
   1500 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
   1501 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
   1502 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
   1503 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
   1504 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
   1505 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
   1506 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
   1507 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
   1508 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
   1509 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
   1510 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
   1511 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
   1512 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
   1513 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
   1514 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
   1515 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
   1516 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
   1517 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
   1518 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
   1519 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
   1520 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
   1521 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
   1522 #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
   1523 #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
   1524 #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
   1525 #define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
   1526 #define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
   1527 #define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
   1528 #define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
   1529 #define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
   1530 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
   1531 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
   1532 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
   1533 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
   1534 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
   1535 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
   1536 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
   1537 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
   1538 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
   1539 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
   1540 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
   1541 #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
   1542 #define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))
   1543 #define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))
   1544 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
   1545 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
   1546 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
   1547 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
   1548 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
   1549 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
   1550 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
   1551 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
   1552 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
   1553 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
   1554 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
   1555 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
   1556 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
   1557 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
   1558 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
   1559 #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
   1560 
   1561 /*
   1562 ** CAPI3REF: Flags For File Open Operations
   1563 **
   1564 ** These bit values are intended for use in the
   1565 ** 3rd parameter to the [sqlite3_open_v2()] interface and
   1566 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
   1567 */
   1568 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
   1569 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
   1570 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
   1571 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
   1572 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
   1573 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
   1574 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
   1575 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
   1576 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
   1577 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
   1578 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
   1579 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
   1580 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
   1581 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
   1582 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
   1583 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
   1584 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
   1585 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
   1586 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
   1587 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
   1588 
   1589 /* Reserved:                         0x00F00000 */
   1590 
   1591 /*
   1592 ** CAPI3REF: Device Characteristics
   1593 **
   1594 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
   1595 ** object returns an integer which is a vector of these
   1596 ** bit values expressing I/O characteristics of the mass storage
   1597 ** device that holds the file that the [sqlite3_io_methods]
   1598 ** refers to.
   1599 **
   1600 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1601 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1602 ** mean that writes of blocks that are nnn bytes in size and
   1603 ** are aligned to an address which is an integer multiple of
   1604 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1605 ** that when data is appended to a file, the data is appended
   1606 ** first then the size of the file is extended, never the other
   1607 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1608 ** information is written to disk in the same order as calls
   1609 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
   1610 ** after reboot following a crash or power loss, the only bytes in a
   1611 ** file that were written at the application level might have changed
   1612 ** and that adjacent bytes, even bytes within the same sector are
   1613 ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   1614 ** flag indicates that a file cannot be deleted when open.  The
   1615 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
   1616 ** read-only media and cannot be changed even by processes with
   1617 ** elevated privileges.
   1618 **
   1619 ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
   1620 ** filesystem supports doing multiple write operations atomically when those
   1621 ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
   1622 ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
   1623 */
   1624 #define SQLITE_IOCAP_ATOMIC                 0x00000001
   1625 #define SQLITE_IOCAP_ATOMIC512              0x00000002
   1626 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
   1627 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
   1628 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
   1629 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
   1630 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
   1631 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
   1632 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
   1633 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
   1634 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
   1635 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
   1636 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
   1637 #define SQLITE_IOCAP_IMMUTABLE              0x00002000
   1638 #define SQLITE_IOCAP_BATCH_ATOMIC           0x00004000
   1639 
   1640 /*
   1641 ** CAPI3REF: File Locking Levels
   1642 **
   1643 ** SQLite uses one of these integer values as the second
   1644 ** argument to calls it makes to the xLock() and xUnlock() methods
   1645 ** of an [sqlite3_io_methods] object.
   1646 */
   1647 #define SQLITE_LOCK_NONE          0
   1648 #define SQLITE_LOCK_SHARED        1
   1649 #define SQLITE_LOCK_RESERVED      2
   1650 #define SQLITE_LOCK_PENDING       3
   1651 #define SQLITE_LOCK_EXCLUSIVE     4
   1652 
   1653 /*
   1654 ** CAPI3REF: Synchronization Type Flags
   1655 **
   1656 ** When SQLite invokes the xSync() method of an
   1657 ** [sqlite3_io_methods] object it uses a combination of
   1658 ** these integer values as the second argument.
   1659 **
   1660 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
   1661 ** sync operation only needs to flush data to mass storage.  Inode
   1662 ** information need not be flushed. If the lower four bits of the flag
   1663 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
   1664 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
   1665 ** to use Mac OS X style fullsync instead of fsync().
   1666 **
   1667 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
   1668 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
   1669 ** settings.  The [synchronous pragma] determines when calls to the
   1670 ** xSync VFS method occur and applies uniformly across all platforms.
   1671 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
   1672 ** energetic or rigorous or forceful the sync operations are and
   1673 ** only make a difference on Mac OSX for the default SQLite code.
   1674 ** (Third-party VFS implementations might also make the distinction
   1675 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
   1676 ** operating systems natively supported by SQLite, only Mac OSX
   1677 ** cares about the difference.)
   1678 */
   1679 #define SQLITE_SYNC_NORMAL        0x00002
   1680 #define SQLITE_SYNC_FULL          0x00003
   1681 #define SQLITE_SYNC_DATAONLY      0x00010
   1682 
   1683 /*
   1684 ** CAPI3REF: OS Interface Open File Handle
   1685 **
   1686 ** An [sqlite3_file] object represents an open file in the
   1687 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
   1688 ** implementations will
   1689 ** want to subclass this object by appending additional fields
   1690 ** for their own use.  The pMethods entry is a pointer to an
   1691 ** [sqlite3_io_methods] object that defines methods for performing
   1692 ** I/O operations on the open file.
   1693 */
   1694 typedef struct sqlite3_file sqlite3_file;
   1695 struct sqlite3_file {
   1696   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
   1697 };
   1698 
   1699 /*
   1700 ** CAPI3REF: OS Interface File Virtual Methods Object
   1701 **
   1702 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
   1703 ** [sqlite3_file] object (or, more commonly, a subclass of the
   1704 ** [sqlite3_file] object) with a pointer to an instance of this object.
   1705 ** This object defines the methods used to perform various operations
   1706 ** against the open file represented by the [sqlite3_file] object.
   1707 **
   1708 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
   1709 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
   1710 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
   1711 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
   1712 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
   1713 ** to NULL.
   1714 **
   1715 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
   1716 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
   1717 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
   1718 ** flag may be ORed in to indicate that only the data of the file
   1719 ** and not its inode needs to be synced.
   1720 **
   1721 ** The integer values to xLock() and xUnlock() are one of
   1722 ** <ul>
   1723 ** <li> [SQLITE_LOCK_NONE],
   1724 ** <li> [SQLITE_LOCK_SHARED],
   1725 ** <li> [SQLITE_LOCK_RESERVED],
   1726 ** <li> [SQLITE_LOCK_PENDING], or
   1727 ** <li> [SQLITE_LOCK_EXCLUSIVE].
   1728 ** </ul>
   1729 ** xLock() increases the lock. xUnlock() decreases the lock.
   1730 ** The xCheckReservedLock() method checks whether any database connection,
   1731 ** either in this process or in some other process, is holding a RESERVED,
   1732 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
   1733 ** if such a lock exists and false otherwise.
   1734 **
   1735 ** The xFileControl() method is a generic interface that allows custom
   1736 ** VFS implementations to directly control an open file using the
   1737 ** [sqlite3_file_control()] interface.  The second "op" argument is an
   1738 ** integer opcode.  The third argument is a generic pointer intended to
   1739 ** point to a structure that may contain arguments or space in which to
   1740 ** write return values.  Potential uses for xFileControl() might be
   1741 ** functions to enable blocking locks with timeouts, to change the
   1742 ** locking strategy (for example to use dot-file locks), to inquire
   1743 ** about the status of a lock, or to break stale locks.  The SQLite
   1744 ** core reserves all opcodes less than 100 for its own use.
   1745 ** A [file control opcodes | list of opcodes] less than 100 is available.
   1746 ** Applications that define a custom xFileControl method should use opcodes
   1747 ** greater than 100 to avoid conflicts.  VFS implementations should
   1748 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
   1749 ** recognize.
   1750 **
   1751 ** The xSectorSize() method returns the sector size of the
   1752 ** device that underlies the file.  The sector size is the
   1753 ** minimum write that can be performed without disturbing
   1754 ** other bytes in the file.  The xDeviceCharacteristics()
   1755 ** method returns a bit vector describing behaviors of the
   1756 ** underlying device:
   1757 **
   1758 ** <ul>
   1759 ** <li> [SQLITE_IOCAP_ATOMIC]
   1760 ** <li> [SQLITE_IOCAP_ATOMIC512]
   1761 ** <li> [SQLITE_IOCAP_ATOMIC1K]
   1762 ** <li> [SQLITE_IOCAP_ATOMIC2K]
   1763 ** <li> [SQLITE_IOCAP_ATOMIC4K]
   1764 ** <li> [SQLITE_IOCAP_ATOMIC8K]
   1765 ** <li> [SQLITE_IOCAP_ATOMIC16K]
   1766 ** <li> [SQLITE_IOCAP_ATOMIC32K]
   1767 ** <li> [SQLITE_IOCAP_ATOMIC64K]
   1768 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
   1769 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
   1770 ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
   1771 ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
   1772 ** <li> [SQLITE_IOCAP_IMMUTABLE]
   1773 ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
   1774 ** </ul>
   1775 **
   1776 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1777 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1778 ** mean that writes of blocks that are nnn bytes in size and
   1779 ** are aligned to an address which is an integer multiple of
   1780 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1781 ** that when data is appended to a file, the data is appended
   1782 ** first then the size of the file is extended, never the other
   1783 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1784 ** information is written to disk in the same order as calls
   1785 ** to xWrite().
   1786 **
   1787 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
   1788 ** in the unread portions of the buffer with zeros.  A VFS that
   1789 ** fails to zero-fill short reads might seem to work.  However,
   1790 ** failure to zero-fill short reads will eventually lead to
   1791 ** database corruption.
   1792 */
   1793 typedef struct sqlite3_io_methods sqlite3_io_methods;
   1794 struct sqlite3_io_methods {
   1795   int iVersion;
   1796   int (*xClose)(sqlite3_file*);
   1797   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   1798   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
   1799   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
   1800   int (*xSync)(sqlite3_file*, int flags);
   1801   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
   1802   int (*xLock)(sqlite3_file*, int);
   1803   int (*xUnlock)(sqlite3_file*, int);
   1804   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
   1805   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
   1806   int (*xSectorSize)(sqlite3_file*);
   1807   int (*xDeviceCharacteristics)(sqlite3_file*);
   1808   /* Methods above are valid for version 1 */
   1809   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
   1810   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
   1811   void (*xShmBarrier)(sqlite3_file*);
   1812   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
   1813   /* Methods above are valid for version 2 */
   1814   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
   1815   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
   1816   /* Methods above are valid for version 3 */
   1817   /* Additional methods may be added in future releases */
   1818 };
   1819 
   1820 /*
   1821 ** CAPI3REF: Standard File Control Opcodes
   1822 ** KEYWORDS: {file control opcodes} {file control opcode}
   1823 **
   1824 ** These integer constants are opcodes for the xFileControl method
   1825 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   1826 ** interface.
   1827 **
   1828 ** <ul>
   1829 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
   1830 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   1831 ** opcode causes the xFileControl method to write the current state of
   1832 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
   1833 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
   1834 ** into an integer that the pArg argument points to. This capability
   1835 ** is used during testing and is only available when the SQLITE_TEST
   1836 ** compile-time option is used.
   1837 **
   1838 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
   1839 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
   1840 ** layer a hint of how large the database file will grow to be during the
   1841 ** current transaction.  This hint is not guaranteed to be accurate but it
   1842 ** is often close.  The underlying VFS might choose to preallocate database
   1843 ** file space based on this hint in order to help writes to the database
   1844 ** file run faster.
   1845 **
   1846 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
   1847 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
   1848 ** extends and truncates the database file in chunks of a size specified
   1849 ** by the user. The fourth argument to [sqlite3_file_control()] should
   1850 ** point to an integer (type int) containing the new chunk-size to use
   1851 ** for the nominated database. Allocating database file space in large
   1852 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
   1853 ** improve performance on some systems.
   1854 **
   1855 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
   1856 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
   1857 ** to the [sqlite3_file] object associated with a particular database
   1858 ** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
   1859 **
   1860 ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
   1861 ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
   1862 ** to the [sqlite3_file] object associated with the journal file (either
   1863 ** the [rollback journal] or the [write-ahead log]) for a particular database
   1864 ** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
   1865 **
   1866 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
   1867 ** No longer in use.
   1868 **
   1869 ** <li>[[SQLITE_FCNTL_SYNC]]
   1870 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
   1871 ** sent to the VFS immediately before the xSync method is invoked on a
   1872 ** database file descriptor. Or, if the xSync method is not invoked
   1873 ** because the user has configured SQLite with
   1874 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
   1875 ** of the xSync method. In most cases, the pointer argument passed with
   1876 ** this file-control is NULL. However, if the database file is being synced
   1877 ** as part of a multi-database commit, the argument points to a nul-terminated
   1878 ** string containing the transactions master-journal file name. VFSes that
   1879 ** do not need this signal should silently ignore this opcode. Applications
   1880 ** should not call [sqlite3_file_control()] with this opcode as doing so may
   1881 ** disrupt the operation of the specialized VFSes that do require it.
   1882 **
   1883 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
   1884 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
   1885 ** and sent to the VFS after a transaction has been committed immediately
   1886 ** but before the database is unlocked. VFSes that do not need this signal
   1887 ** should silently ignore this opcode. Applications should not call
   1888 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
   1889 ** operation of the specialized VFSes that do require it.
   1890 **
   1891 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
   1892 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
   1893 ** retry counts and intervals for certain disk I/O operations for the
   1894 ** windows [VFS] in order to provide robustness in the presence of
   1895 ** anti-virus programs.  By default, the windows VFS will retry file read,
   1896 ** file write, and file delete operations up to 10 times, with a delay
   1897 ** of 25 milliseconds before the first retry and with the delay increasing
   1898 ** by an additional 25 milliseconds with each subsequent retry.  This
   1899 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
   1900 ** to be adjusted.  The values are changed for all database connections
   1901 ** within the same process.  The argument is a pointer to an array of two
   1902 ** integers where the first integer is the new retry count and the second
   1903 ** integer is the delay.  If either integer is negative, then the setting
   1904 ** is not changed but instead the prior value of that setting is written
   1905 ** into the array entry, allowing the current retry settings to be
   1906 ** interrogated.  The zDbName parameter is ignored.
   1907 **
   1908 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
   1909 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
   1910 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
   1911 ** write ahead log and shared memory files used for transaction control
   1912 ** are automatically deleted when the latest connection to the database
   1913 ** closes.  Setting persistent WAL mode causes those files to persist after
   1914 ** close.  Persisting the files is useful when other processes that do not
   1915 ** have write permission on the directory containing the database file want
   1916 ** to read the database file, as the WAL and shared memory files must exist
   1917 ** in order for the database to be readable.  The fourth parameter to
   1918 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   1919 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
   1920 ** WAL mode.  If the integer is -1, then it is overwritten with the current
   1921 ** WAL persistence setting.
   1922 **
   1923 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
   1924 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
   1925 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
   1926 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
   1927 ** xDeviceCharacteristics methods. The fourth parameter to
   1928 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   1929 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
   1930 ** mode.  If the integer is -1, then it is overwritten with the current
   1931 ** zero-damage mode setting.
   1932 **
   1933 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
   1934 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
   1935 ** a write transaction to indicate that, unless it is rolled back for some
   1936 ** reason, the entire database file will be overwritten by the current
   1937 ** transaction. This is used by VACUUM operations.
   1938 **
   1939 ** <li>[[SQLITE_FCNTL_VFSNAME]]
   1940 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
   1941 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
   1942 ** final bottom-level VFS are written into memory obtained from
   1943 ** [sqlite3_malloc()] and the result is stored in the char* variable
   1944 ** that the fourth parameter of [sqlite3_file_control()] points to.
   1945 ** The caller is responsible for freeing the memory when done.  As with
   1946 ** all file-control actions, there is no guarantee that this will actually
   1947 ** do anything.  Callers should initialize the char* variable to a NULL
   1948 ** pointer in case this file-control is not implemented.  This file-control
   1949 ** is intended for diagnostic use only.
   1950 **
   1951 ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
   1952 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
   1953 ** [VFSes] currently in use.  ^(The argument X in
   1954 ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
   1955 ** of type "[sqlite3_vfs] **".  This opcodes will set *X
   1956 ** to a pointer to the top-level VFS.)^
   1957 ** ^When there are multiple VFS shims in the stack, this opcode finds the
   1958 ** upper-most shim only.
   1959 **
   1960 ** <li>[[SQLITE_FCNTL_PRAGMA]]
   1961 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
   1962 ** file control is sent to the open [sqlite3_file] object corresponding
   1963 ** to the database file to which the pragma statement refers. ^The argument
   1964 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
   1965 ** pointers to strings (char**) in which the second element of the array
   1966 ** is the name of the pragma and the third element is the argument to the
   1967 ** pragma or NULL if the pragma has no argument.  ^The handler for an
   1968 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
   1969 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
   1970 ** or the equivalent and that string will become the result of the pragma or
   1971 ** the error message if the pragma fails. ^If the
   1972 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
   1973 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
   1974 ** file control returns [SQLITE_OK], then the parser assumes that the
   1975 ** VFS has handled the PRAGMA itself and the parser generates a no-op
   1976 ** prepared statement if result string is NULL, or that returns a copy
   1977 ** of the result string if the string is non-NULL.
   1978 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
   1979 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
   1980 ** that the VFS encountered an error while handling the [PRAGMA] and the
   1981 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
   1982 ** file control occurs at the beginning of pragma statement analysis and so
   1983 ** it is able to override built-in [PRAGMA] statements.
   1984 **
   1985 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
   1986 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
   1987 ** file-control may be invoked by SQLite on the database file handle
   1988 ** shortly after it is opened in order to provide a custom VFS with access
   1989 ** to the connections busy-handler callback. The argument is of type (void **)
   1990 ** - an array of two (void *) values. The first (void *) actually points
   1991 ** to a function of type (int (*)(void *)). In order to invoke the connections
   1992 ** busy-handler, this function should be invoked with the second (void *) in
   1993 ** the array as the only argument. If it returns non-zero, then the operation
   1994 ** should be retried. If it returns zero, the custom VFS should abandon the
   1995 ** current operation.
   1996 **
   1997 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
   1998 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
   1999 ** to have SQLite generate a
   2000 ** temporary filename using the same algorithm that is followed to generate
   2001 ** temporary filenames for TEMP tables and other internal uses.  The
   2002 ** argument should be a char** which will be filled with the filename
   2003 ** written into memory obtained from [sqlite3_malloc()].  The caller should
   2004 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
   2005 **
   2006 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
   2007 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
   2008 ** maximum number of bytes that will be used for memory-mapped I/O.
   2009 ** The argument is a pointer to a value of type sqlite3_int64 that
   2010 ** is an advisory maximum number of bytes in the file to memory map.  The
   2011 ** pointer is overwritten with the old value.  The limit is not changed if
   2012 ** the value originally pointed to is negative, and so the current limit
   2013 ** can be queried by passing in a pointer to a negative number.  This
   2014 ** file-control is used internally to implement [PRAGMA mmap_size].
   2015 **
   2016 ** <li>[[SQLITE_FCNTL_TRACE]]
   2017 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
   2018 ** to the VFS about what the higher layers of the SQLite stack are doing.
   2019 ** This file control is used by some VFS activity tracing [shims].
   2020 ** The argument is a zero-terminated string.  Higher layers in the
   2021 ** SQLite stack may generate instances of this file control if
   2022 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
   2023 **
   2024 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
   2025 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
   2026 ** pointer to an integer and it writes a boolean into that integer depending
   2027 ** on whether or not the file has been renamed, moved, or deleted since it
   2028 ** was first opened.
   2029 **
   2030 ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
   2031 ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
   2032 ** underlying native file handle associated with a file handle.  This file
   2033 ** control interprets its argument as a pointer to a native file handle and
   2034 ** writes the resulting value there.
   2035 **
   2036 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
   2037 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
   2038 ** opcode causes the xFileControl method to swap the file handle with the one
   2039 ** pointed to by the pArg argument.  This capability is used during testing
   2040 ** and only needs to be supported when SQLITE_TEST is defined.
   2041 **
   2042 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
   2043 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
   2044 ** be advantageous to block on the next WAL lock if the lock is not immediately
   2045 ** available.  The WAL subsystem issues this signal during rare
   2046 ** circumstances in order to fix a problem with priority inversion.
   2047 ** Applications should <em>not</em> use this file-control.
   2048 **
   2049 ** <li>[[SQLITE_FCNTL_ZIPVFS]]
   2050 ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
   2051 ** VFS should return SQLITE_NOTFOUND for this opcode.
   2052 **
   2053 ** <li>[[SQLITE_FCNTL_RBU]]
   2054 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
   2055 ** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
   2056 ** this opcode.
   2057 **
   2058 ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
   2059 ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
   2060 ** the file descriptor is placed in "batch write mode", which
   2061 ** means all subsequent write operations will be deferred and done
   2062 ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].  Systems
   2063 ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
   2064 ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
   2065 ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
   2066 ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
   2067 ** no VFS interface calls on the same [sqlite3_file] file descriptor
   2068 ** except for calls to the xWrite method and the xFileControl method
   2069 ** with [SQLITE_FCNTL_SIZE_HINT].
   2070 **
   2071 ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
   2072 ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
   2073 ** operations since the previous successful call to
   2074 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
   2075 ** This file control returns [SQLITE_OK] if and only if the writes were
   2076 ** all performed successfully and have been committed to persistent storage.
   2077 ** ^Regardless of whether or not it is successful, this file control takes
   2078 ** the file descriptor out of batch write mode so that all subsequent
   2079 ** write operations are independent.
   2080 ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
   2081 ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
   2082 **
   2083 ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
   2084 ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
   2085 ** operations since the previous successful call to
   2086 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
   2087 ** ^This file control takes the file descriptor out of batch write mode
   2088 ** so that all subsequent write operations are independent.
   2089 ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
   2090 ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
   2091 ** </ul>
   2092 */
   2093 #define SQLITE_FCNTL_LOCKSTATE               1
   2094 #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
   2095 #define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
   2096 #define SQLITE_FCNTL_LAST_ERRNO              4
   2097 #define SQLITE_FCNTL_SIZE_HINT               5
   2098 #define SQLITE_FCNTL_CHUNK_SIZE              6
   2099 #define SQLITE_FCNTL_FILE_POINTER            7
   2100 #define SQLITE_FCNTL_SYNC_OMITTED            8
   2101 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
   2102 #define SQLITE_FCNTL_PERSIST_WAL            10
   2103 #define SQLITE_FCNTL_OVERWRITE              11
   2104 #define SQLITE_FCNTL_VFSNAME                12
   2105 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
   2106 #define SQLITE_FCNTL_PRAGMA                 14
   2107 #define SQLITE_FCNTL_BUSYHANDLER            15
   2108 #define SQLITE_FCNTL_TEMPFILENAME           16
   2109 #define SQLITE_FCNTL_MMAP_SIZE              18
   2110 #define SQLITE_FCNTL_TRACE                  19
   2111 #define SQLITE_FCNTL_HAS_MOVED              20
   2112 #define SQLITE_FCNTL_SYNC                   21
   2113 #define SQLITE_FCNTL_COMMIT_PHASETWO        22
   2114 #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
   2115 #define SQLITE_FCNTL_WAL_BLOCK              24
   2116 #define SQLITE_FCNTL_ZIPVFS                 25
   2117 #define SQLITE_FCNTL_RBU                    26
   2118 #define SQLITE_FCNTL_VFS_POINTER            27
   2119 #define SQLITE_FCNTL_JOURNAL_POINTER        28
   2120 #define SQLITE_FCNTL_WIN32_GET_HANDLE       29
   2121 #define SQLITE_FCNTL_PDB                    30
   2122 #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE     31
   2123 #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE    32
   2124 #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  33
   2125 
   2126 /* deprecated names */
   2127 #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
   2128 #define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
   2129 #define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
   2130 
   2131 
   2132 /*
   2133 ** CAPI3REF: Mutex Handle
   2134 **
   2135 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
   2136 ** abstract type for a mutex object.  The SQLite core never looks
   2137 ** at the internal representation of an [sqlite3_mutex].  It only
   2138 ** deals with pointers to the [sqlite3_mutex] object.
   2139 **
   2140 ** Mutexes are created using [sqlite3_mutex_alloc()].
   2141 */
   2142 typedef struct sqlite3_mutex sqlite3_mutex;
   2143 
   2144 /*
   2145 ** CAPI3REF: Loadable Extension Thunk
   2146 **
   2147 ** A pointer to the opaque sqlite3_api_routines structure is passed as
   2148 ** the third parameter to entry points of [loadable extensions].  This
   2149 ** structure must be typedefed in order to work around compiler warnings
   2150 ** on some platforms.
   2151 */
   2152 typedef struct sqlite3_api_routines sqlite3_api_routines;
   2153 
   2154 /*
   2155 ** CAPI3REF: OS Interface Object
   2156 **
   2157 ** An instance of the sqlite3_vfs object defines the interface between
   2158 ** the SQLite core and the underlying operating system.  The "vfs"
   2159 ** in the name of the object stands for "virtual file system".  See
   2160 ** the [VFS | VFS documentation] for further information.
   2161 **
   2162 ** The VFS interface is sometimes extended by adding new methods onto
   2163 ** the end.  Each time such an extension occurs, the iVersion field
   2164 ** is incremented.  The iVersion value started out as 1 in
   2165 ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
   2166 ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
   2167 ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields
   2168 ** may be appended to the sqlite3_vfs object and the iVersion value
   2169 ** may increase again in future versions of SQLite.
   2170 ** Note that the structure
   2171 ** of the sqlite3_vfs object changes in the transition from
   2172 ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
   2173 ** and yet the iVersion field was not modified.
   2174 **
   2175 ** The szOsFile field is the size of the subclassed [sqlite3_file]
   2176 ** structure used by this VFS.  mxPathname is the maximum length of
   2177 ** a pathname in this VFS.
   2178 **
   2179 ** Registered sqlite3_vfs objects are kept on a linked list formed by
   2180 ** the pNext pointer.  The [sqlite3_vfs_register()]
   2181 ** and [sqlite3_vfs_unregister()] interfaces manage this list
   2182 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
   2183 ** searches the list.  Neither the application code nor the VFS
   2184 ** implementation should use the pNext pointer.
   2185 **
   2186 ** The pNext field is the only field in the sqlite3_vfs
   2187 ** structure that SQLite will ever modify.  SQLite will only access
   2188 ** or modify this field while holding a particular static mutex.
   2189 ** The application should never modify anything within the sqlite3_vfs
   2190 ** object once the object has been registered.
   2191 **
   2192 ** The zName field holds the name of the VFS module.  The name must
   2193 ** be unique across all VFS modules.
   2194 **
   2195 ** [[sqlite3_vfs.xOpen]]
   2196 ** ^SQLite guarantees that the zFilename parameter to xOpen
   2197 ** is either a NULL pointer or string obtained
   2198 ** from xFullPathname() with an optional suffix added.
   2199 ** ^If a suffix is added to the zFilename parameter, it will
   2200 ** consist of a single "-" character followed by no more than
   2201 ** 11 alphanumeric and/or "-" characters.
   2202 ** ^SQLite further guarantees that
   2203 ** the string will be valid and unchanged until xClose() is
   2204 ** called. Because of the previous sentence,
   2205 ** the [sqlite3_file] can safely store a pointer to the
   2206 ** filename if it needs to remember the filename for some reason.
   2207 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
   2208 ** must invent its own temporary name for the file.  ^Whenever the
   2209 ** xFilename parameter is NULL it will also be the case that the
   2210 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
   2211 **
   2212 ** The flags argument to xOpen() includes all bits set in
   2213 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
   2214 ** or [sqlite3_open16()] is used, then flags includes at least
   2215 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
   2216 ** If xOpen() opens a file read-only then it sets *pOutFlags to
   2217 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
   2218 **
   2219 ** ^(SQLite will also add one of the following flags to the xOpen()
   2220 ** call, depending on the object being opened:
   2221 **
   2222 ** <ul>
   2223 ** <li>  [SQLITE_OPEN_MAIN_DB]
   2224 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
   2225 ** <li>  [SQLITE_OPEN_TEMP_DB]
   2226 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
   2227 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
   2228 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
   2229 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
   2230 ** <li>  [SQLITE_OPEN_WAL]
   2231 ** </ul>)^
   2232 **
   2233 ** The file I/O implementation can use the object type flags to
   2234 ** change the way it deals with files.  For example, an application
   2235 ** that does not care about crash recovery or rollback might make
   2236 ** the open of a journal file a no-op.  Writes to this journal would
   2237 ** also be no-ops, and any attempt to read the journal would return
   2238 ** SQLITE_IOERR.  Or the implementation might recognize that a database
   2239 ** file will be doing page-aligned sector reads and writes in a random
   2240 ** order and set up its I/O subsystem accordingly.
   2241 **
   2242 ** SQLite might also add one of the following flags to the xOpen method:
   2243 **
   2244 ** <ul>
   2245 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
   2246 ** <li> [SQLITE_OPEN_EXCLUSIVE]
   2247 ** </ul>
   2248 **
   2249 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
   2250 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
   2251 ** will be set for TEMP databases and their journals, transient
   2252 ** databases, and subjournals.
   2253 **
   2254 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
   2255 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
   2256 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
   2257 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
   2258 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
   2259 ** be created, and that it is an error if it already exists.
   2260 ** It is <i>not</i> used to indicate the file should be opened
   2261 ** for exclusive access.
   2262 **
   2263 ** ^At least szOsFile bytes of memory are allocated by SQLite
   2264 ** to hold the  [sqlite3_file] structure passed as the third
   2265 ** argument to xOpen.  The xOpen method does not have to
   2266 ** allocate the structure; it should just fill it in.  Note that
   2267 ** the xOpen method must set the sqlite3_file.pMethods to either
   2268 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
   2269 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
   2270 ** element will be valid after xOpen returns regardless of the success
   2271 ** or failure of the xOpen call.
   2272 **
   2273 ** [[sqlite3_vfs.xAccess]]
   2274 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
   2275 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
   2276 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
   2277 ** to test whether a file is at least readable.   The file can be a
   2278 ** directory.
   2279 **
   2280 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
   2281 ** output buffer xFullPathname.  The exact size of the output buffer
   2282 ** is also passed as a parameter to both  methods. If the output buffer
   2283 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
   2284 ** handled as a fatal error by SQLite, vfs implementations should endeavor
   2285 ** to prevent this by setting mxPathname to a sufficiently large value.
   2286 **
   2287 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
   2288 ** interfaces are not strictly a part of the filesystem, but they are
   2289 ** included in the VFS structure for completeness.
   2290 ** The xRandomness() function attempts to return nBytes bytes
   2291 ** of good-quality randomness into zOut.  The return value is
   2292 ** the actual number of bytes of randomness obtained.
   2293 ** The xSleep() method causes the calling thread to sleep for at
   2294 ** least the number of microseconds given.  ^The xCurrentTime()
   2295 ** method returns a Julian Day Number for the current date and time as
   2296 ** a floating point value.
   2297 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
   2298 ** Day Number multiplied by 86400000 (the number of milliseconds in
   2299 ** a 24-hour day).
   2300 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
   2301 ** date and time if that method is available (if iVersion is 2 or
   2302 ** greater and the function pointer is not NULL) and will fall back
   2303 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
   2304 **
   2305 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
   2306 ** are not used by the SQLite core.  These optional interfaces are provided
   2307 ** by some VFSes to facilitate testing of the VFS code. By overriding
   2308 ** system calls with functions under its control, a test program can
   2309 ** simulate faults and error conditions that would otherwise be difficult
   2310 ** or impossible to induce.  The set of system calls that can be overridden
   2311 ** varies from one VFS to another, and from one version of the same VFS to the
   2312 ** next.  Applications that use these interfaces must be prepared for any
   2313 ** or all of these interfaces to be NULL or for their behavior to change
   2314 ** from one release to the next.  Applications must not attempt to access
   2315 ** any of these methods if the iVersion of the VFS is less than 3.
   2316 */
   2317 typedef struct sqlite3_vfs sqlite3_vfs;
   2318 typedef void (*sqlite3_syscall_ptr)(void);
   2319 struct sqlite3_vfs {
   2320   int iVersion;            /* Structure version number (currently 3) */
   2321   int szOsFile;            /* Size of subclassed sqlite3_file */
   2322   int mxPathname;          /* Maximum file pathname length */
   2323   sqlite3_vfs *pNext;      /* Next registered VFS */
   2324   const char *zName;       /* Name of this virtual file system */
   2325   void *pAppData;          /* Pointer to application-specific data */
   2326   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
   2327                int flags, int *pOutFlags);
   2328   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
   2329   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
   2330   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
   2331   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
   2332   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
   2333   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
   2334   void (*xDlClose)(sqlite3_vfs*, void*);
   2335   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
   2336   int (*xSleep)(sqlite3_vfs*, int microseconds);
   2337   int (*xCurrentTime)(sqlite3_vfs*, double*);
   2338   int (*xGetLastError)(sqlite3_vfs*, int, char *);
   2339   /*
   2340   ** The methods above are in version 1 of the sqlite_vfs object
   2341   ** definition.  Those that follow are added in version 2 or later
   2342   */
   2343   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
   2344   /*
   2345   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
   2346   ** Those below are for version 3 and greater.
   2347   */
   2348   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
   2349   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
   2350   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
   2351   /*
   2352   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
   2353   ** New fields may be appended in future versions.  The iVersion
   2354   ** value will increment whenever this happens.
   2355   */
   2356 };
   2357 
   2358 /*
   2359 ** CAPI3REF: Flags for the xAccess VFS method
   2360 **
   2361 ** These integer constants can be used as the third parameter to
   2362 ** the xAccess method of an [sqlite3_vfs] object.  They determine
   2363 ** what kind of permissions the xAccess method is looking for.
   2364 ** With SQLITE_ACCESS_EXISTS, the xAccess method
   2365 ** simply checks whether the file exists.
   2366 ** With SQLITE_ACCESS_READWRITE, the xAccess method
   2367 ** checks whether the named directory is both readable and writable
   2368 ** (in other words, if files can be added, removed, and renamed within
   2369 ** the directory).
   2370 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
   2371 ** [temp_store_directory pragma], though this could change in a future
   2372 ** release of SQLite.
   2373 ** With SQLITE_ACCESS_READ, the xAccess method
   2374 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
   2375 ** currently unused, though it might be used in a future release of
   2376 ** SQLite.
   2377 */
   2378 #define SQLITE_ACCESS_EXISTS    0
   2379 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
   2380 #define SQLITE_ACCESS_READ      2   /* Unused */
   2381 
   2382 /*
   2383 ** CAPI3REF: Flags for the xShmLock VFS method
   2384 **
   2385 ** These integer constants define the various locking operations
   2386 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
   2387 ** following are the only legal combinations of flags to the
   2388 ** xShmLock method:
   2389 **
   2390 ** <ul>
   2391 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
   2392 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
   2393 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
   2394 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
   2395 ** </ul>
   2396 **
   2397 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
   2398 ** was given on the corresponding lock.
   2399 **
   2400 ** The xShmLock method can transition between unlocked and SHARED or
   2401 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
   2402 ** and EXCLUSIVE.
   2403 */
   2404 #define SQLITE_SHM_UNLOCK       1
   2405 #define SQLITE_SHM_LOCK         2
   2406 #define SQLITE_SHM_SHARED       4
   2407 #define SQLITE_SHM_EXCLUSIVE    8
   2408 
   2409 /*
   2410 ** CAPI3REF: Maximum xShmLock index
   2411 **
   2412 ** The xShmLock method on [sqlite3_io_methods] may use values
   2413 ** between 0 and this upper bound as its "offset" argument.
   2414 ** The SQLite core will never attempt to acquire or release a
   2415 ** lock outside of this range
   2416 */
   2417 #define SQLITE_SHM_NLOCK        8
   2418 
   2419 
   2420 /*
   2421 ** CAPI3REF: Initialize The SQLite Library
   2422 **
   2423 ** ^The sqlite3_initialize() routine initializes the
   2424 ** SQLite library.  ^The sqlite3_shutdown() routine
   2425 ** deallocates any resources that were allocated by sqlite3_initialize().
   2426 ** These routines are designed to aid in process initialization and
   2427 ** shutdown on embedded systems.  Workstation applications using
   2428 ** SQLite normally do not need to invoke either of these routines.
   2429 **
   2430 ** A call to sqlite3_initialize() is an "effective" call if it is
   2431 ** the first time sqlite3_initialize() is invoked during the lifetime of
   2432 ** the process, or if it is the first time sqlite3_initialize() is invoked
   2433 ** following a call to sqlite3_shutdown().  ^(Only an effective call
   2434 ** of sqlite3_initialize() does any initialization.  All other calls
   2435 ** are harmless no-ops.)^
   2436 **
   2437 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
   2438 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
   2439 ** an effective call to sqlite3_shutdown() does any deinitialization.
   2440 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
   2441 **
   2442 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
   2443 ** is not.  The sqlite3_shutdown() interface must only be called from a
   2444 ** single thread.  All open [database connections] must be closed and all
   2445 ** other SQLite resources must be deallocated prior to invoking
   2446 ** sqlite3_shutdown().
   2447 **
   2448 ** Among other things, ^sqlite3_initialize() will invoke
   2449 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
   2450 ** will invoke sqlite3_os_end().
   2451 **
   2452 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
   2453 ** ^If for some reason, sqlite3_initialize() is unable to initialize
   2454 ** the library (perhaps it is unable to allocate a needed resource such
   2455 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
   2456 **
   2457 ** ^The sqlite3_initialize() routine is called internally by many other
   2458 ** SQLite interfaces so that an application usually does not need to
   2459 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
   2460 ** calls sqlite3_initialize() so the SQLite library will be automatically
   2461 ** initialized when [sqlite3_open()] is called if it has not be initialized
   2462 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
   2463 ** compile-time option, then the automatic calls to sqlite3_initialize()
   2464 ** are omitted and the application must call sqlite3_initialize() directly
   2465 ** prior to using any other SQLite interface.  For maximum portability,
   2466 ** it is recommended that applications always invoke sqlite3_initialize()
   2467 ** directly prior to using any other SQLite interface.  Future releases
   2468 ** of SQLite may require this.  In other words, the behavior exhibited
   2469 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
   2470 ** default behavior in some future release of SQLite.
   2471 **
   2472 ** The sqlite3_os_init() routine does operating-system specific
   2473 ** initialization of the SQLite library.  The sqlite3_os_end()
   2474 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
   2475 ** performed by these routines include allocation or deallocation
   2476 ** of static resources, initialization of global variables,
   2477 ** setting up a default [sqlite3_vfs] module, or setting up
   2478 ** a default configuration using [sqlite3_config()].
   2479 **
   2480 ** The application should never invoke either sqlite3_os_init()
   2481 ** or sqlite3_os_end() directly.  The application should only invoke
   2482 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
   2483 ** interface is called automatically by sqlite3_initialize() and
   2484 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
   2485 ** implementations for sqlite3_os_init() and sqlite3_os_end()
   2486 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
   2487 ** When [custom builds | built for other platforms]
   2488 ** (using the [SQLITE_OS_OTHER=1] compile-time
   2489 ** option) the application must supply a suitable implementation for
   2490 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
   2491 ** implementation of sqlite3_os_init() or sqlite3_os_end()
   2492 ** must return [SQLITE_OK] on success and some other [error code] upon
   2493 ** failure.
   2494 */
   2495 SQLITE_API int sqlite3_initialize(void);
   2496 SQLITE_API int sqlite3_shutdown(void);
   2497 SQLITE_API int sqlite3_os_init(void);
   2498 SQLITE_API int sqlite3_os_end(void);
   2499 
   2500 /*
   2501 ** CAPI3REF: Configuring The SQLite Library
   2502 **
   2503 ** The sqlite3_config() interface is used to make global configuration
   2504 ** changes to SQLite in order to tune SQLite to the specific needs of
   2505 ** the application.  The default configuration is recommended for most
   2506 ** applications and so this routine is usually not necessary.  It is
   2507 ** provided to support rare applications with unusual needs.
   2508 **
   2509 ** <b>The sqlite3_config() interface is not threadsafe. The application
   2510 ** must ensure that no other SQLite interfaces are invoked by other
   2511 ** threads while sqlite3_config() is running.</b>
   2512 **
   2513 ** The sqlite3_config() interface
   2514 ** may only be invoked prior to library initialization using
   2515 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
   2516 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
   2517 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
   2518 ** Note, however, that ^sqlite3_config() can be called as part of the
   2519 ** implementation of an application-defined [sqlite3_os_init()].
   2520 **
   2521 ** The first argument to sqlite3_config() is an integer
   2522 ** [configuration option] that determines
   2523 ** what property of SQLite is to be configured.  Subsequent arguments
   2524 ** vary depending on the [configuration option]
   2525 ** in the first argument.
   2526 **
   2527 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
   2528 ** ^If the option is unknown or SQLite is unable to set the option
   2529 ** then this routine returns a non-zero [error code].
   2530 */
   2531 SQLITE_API int sqlite3_config(int, ...);
   2532 
   2533 /*
   2534 ** CAPI3REF: Configure database connections
   2535 ** METHOD: sqlite3
   2536 **
   2537 ** The sqlite3_db_config() interface is used to make configuration
   2538 ** changes to a [database connection].  The interface is similar to
   2539 ** [sqlite3_config()] except that the changes apply to a single
   2540 ** [database connection] (specified in the first argument).
   2541 **
   2542 ** The second argument to sqlite3_db_config(D,V,...)  is the
   2543 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
   2544 ** that indicates what aspect of the [database connection] is being configured.
   2545 ** Subsequent arguments vary depending on the configuration verb.
   2546 **
   2547 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
   2548 ** the call is considered successful.
   2549 */
   2550 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
   2551 
   2552 /*
   2553 ** CAPI3REF: Memory Allocation Routines
   2554 **
   2555 ** An instance of this object defines the interface between SQLite
   2556 ** and low-level memory allocation routines.
   2557 **
   2558 ** This object is used in only one place in the SQLite interface.
   2559 ** A pointer to an instance of this object is the argument to
   2560 ** [sqlite3_config()] when the configuration option is
   2561 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
   2562 ** By creating an instance of this object
   2563 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
   2564 ** during configuration, an application can specify an alternative
   2565 ** memory allocation subsystem for SQLite to use for all of its
   2566 ** dynamic memory needs.
   2567 **
   2568 ** Note that SQLite comes with several [built-in memory allocators]
   2569 ** that are perfectly adequate for the overwhelming majority of applications
   2570 ** and that this object is only useful to a tiny minority of applications
   2571 ** with specialized memory allocation requirements.  This object is
   2572 ** also used during testing of SQLite in order to specify an alternative
   2573 ** memory allocator that simulates memory out-of-memory conditions in
   2574 ** order to verify that SQLite recovers gracefully from such
   2575 ** conditions.
   2576 **
   2577 ** The xMalloc, xRealloc, and xFree methods must work like the
   2578 ** malloc(), realloc() and free() functions from the standard C library.
   2579 ** ^SQLite guarantees that the second argument to
   2580 ** xRealloc is always a value returned by a prior call to xRoundup.
   2581 **
   2582 ** xSize should return the allocated size of a memory allocation
   2583 ** previously obtained from xMalloc or xRealloc.  The allocated size
   2584 ** is always at least as big as the requested size but may be larger.
   2585 **
   2586 ** The xRoundup method returns what would be the allocated size of
   2587 ** a memory allocation given a particular requested size.  Most memory
   2588 ** allocators round up memory allocations at least to the next multiple
   2589 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
   2590 ** Every memory allocation request coming in through [sqlite3_malloc()]
   2591 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
   2592 ** that causes the corresponding memory allocation to fail.
   2593 **
   2594 ** The xInit method initializes the memory allocator.  For example,
   2595 ** it might allocate any require mutexes or initialize internal data
   2596 ** structures.  The xShutdown method is invoked (indirectly) by
   2597 ** [sqlite3_shutdown()] and should deallocate any resources acquired
   2598 ** by xInit.  The pAppData pointer is used as the only parameter to
   2599 ** xInit and xShutdown.
   2600 **
   2601 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
   2602 ** the xInit method, so the xInit method need not be threadsafe.  The
   2603 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   2604 ** not need to be threadsafe either.  For all other methods, SQLite
   2605 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
   2606 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
   2607 ** it is by default) and so the methods are automatically serialized.
   2608 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
   2609 ** methods must be threadsafe or else make their own arrangements for
   2610 ** serialization.
   2611 **
   2612 ** SQLite will never invoke xInit() more than once without an intervening
   2613 ** call to xShutdown().
   2614 */
   2615 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
   2616 struct sqlite3_mem_methods {
   2617   void *(*xMalloc)(int);         /* Memory allocation function */
   2618   void (*xFree)(void*);          /* Free a prior allocation */
   2619   void *(*xRealloc)(void*,int);  /* Resize an allocation */
   2620   int (*xSize)(void*);           /* Return the size of an allocation */
   2621   int (*xRoundup)(int);          /* Round up request size to allocation size */
   2622   int (*xInit)(void*);           /* Initialize the memory allocator */
   2623   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
   2624   void *pAppData;                /* Argument to xInit() and xShutdown() */
   2625 };
   2626 
   2627 /*
   2628 ** CAPI3REF: Configuration Options
   2629 ** KEYWORDS: {configuration option}
   2630 **
   2631 ** These constants are the available integer configuration options that
   2632 ** can be passed as the first argument to the [sqlite3_config()] interface.
   2633 **
   2634 ** New configuration options may be added in future releases of SQLite.
   2635 ** Existing configuration options might be discontinued.  Applications
   2636 ** should check the return code from [sqlite3_config()] to make sure that
   2637 ** the call worked.  The [sqlite3_config()] interface will return a
   2638 ** non-zero [error code] if a discontinued or unsupported configuration option
   2639 ** is invoked.
   2640 **
   2641 ** <dl>
   2642 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
   2643 ** <dd>There are no arguments to this option.  ^This option sets the
   2644 ** [threading mode] to Single-thread.  In other words, it disables
   2645 ** all mutexing and puts SQLite into a mode where it can only be used
   2646 ** by a single thread.   ^If SQLite is compiled with
   2647 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   2648 ** it is not possible to change the [threading mode] from its default
   2649 ** value of Single-thread and so [sqlite3_config()] will return
   2650 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
   2651 ** configuration option.</dd>
   2652 **
   2653 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
   2654 ** <dd>There are no arguments to this option.  ^This option sets the
   2655 ** [threading mode] to Multi-thread.  In other words, it disables
   2656 ** mutexing on [database connection] and [prepared statement] objects.
   2657 ** The application is responsible for serializing access to
   2658 ** [database connections] and [prepared statements].  But other mutexes
   2659 ** are enabled so that SQLite will be safe to use in a multi-threaded
   2660 ** environment as long as no two threads attempt to use the same
   2661 ** [database connection] at the same time.  ^If SQLite is compiled with
   2662 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   2663 ** it is not possible to set the Multi-thread [threading mode] and
   2664 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   2665 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
   2666 **
   2667 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
   2668 ** <dd>There are no arguments to this option.  ^This option sets the
   2669 ** [threading mode] to Serialized. In other words, this option enables
   2670 ** all mutexes including the recursive
   2671 ** mutexes on [database connection] and [prepared statement] objects.
   2672 ** In this mode (which is the default when SQLite is compiled with
   2673 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
   2674 ** to [database connections] and [prepared statements] so that the
   2675 ** application is free to use the same [database connection] or the
   2676 ** same [prepared statement] in different threads at the same time.
   2677 ** ^If SQLite is compiled with
   2678 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   2679 ** it is not possible to set the Serialized [threading mode] and
   2680 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   2681 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
   2682 **
   2683 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
   2684 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
   2685 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
   2686 ** The argument specifies
   2687 ** alternative low-level memory allocation routines to be used in place of
   2688 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
   2689 ** its own private copy of the content of the [sqlite3_mem_methods] structure
   2690 ** before the [sqlite3_config()] call returns.</dd>
   2691 **
   2692 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
   2693 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
   2694 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
   2695 ** The [sqlite3_mem_methods]
   2696 ** structure is filled with the currently defined memory allocation routines.)^
   2697 ** This option can be used to overload the default memory allocation
   2698 ** routines with a wrapper that simulations memory allocation failure or
   2699 ** tracks memory usage, for example. </dd>
   2700 **
   2701 ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
   2702 ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
   2703 ** type int, interpreted as a boolean, which if true provides a hint to
   2704 ** SQLite that it should avoid large memory allocations if possible.
   2705 ** SQLite will run faster if it is free to make large memory allocations,
   2706 ** but some application might prefer to run slower in exchange for
   2707 ** guarantees about memory fragmentation that are possible if large
   2708 ** allocations are avoided.  This hint is normally off.
   2709 ** </dd>
   2710 **
   2711 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
   2712 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
   2713 ** interpreted as a boolean, which enables or disables the collection of
   2714 ** memory allocation statistics. ^(When memory allocation statistics are
   2715 ** disabled, the following SQLite interfaces become non-operational:
   2716 **   <ul>
   2717 **   <li> [sqlite3_memory_used()]
   2718 **   <li> [sqlite3_memory_highwater()]
   2719 **   <li> [sqlite3_soft_heap_limit64()]
   2720 **   <li> [sqlite3_status64()]
   2721 **   </ul>)^
   2722 ** ^Memory allocation statistics are enabled by default unless SQLite is
   2723 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
   2724 ** allocation statistics are disabled by default.
   2725 ** </dd>
   2726 **
   2727 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
   2728 ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
   2729 ** </dd>
   2730 **
   2731 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
   2732 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
   2733 ** that SQLite can use for the database page cache with the default page
   2734 ** cache implementation.
   2735 ** This configuration option is a no-op if an application-define page
   2736 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
   2737 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
   2738 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
   2739 ** and the number of cache lines (N).
   2740 ** The sz argument should be the size of the largest database page
   2741 ** (a power of two between 512 and 65536) plus some extra bytes for each
   2742 ** page header.  ^The number of extra bytes needed by the page header
   2743 ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
   2744 ** ^It is harmless, apart from the wasted memory,
   2745 ** for the sz parameter to be larger than necessary.  The pMem
   2746 ** argument must be either a NULL pointer or a pointer to an 8-byte
   2747 ** aligned block of memory of at least sz*N bytes, otherwise
   2748 ** subsequent behavior is undefined.
   2749 ** ^When pMem is not NULL, SQLite will strive to use the memory provided
   2750 ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
   2751 ** a page cache line is larger than sz bytes or if all of the pMem buffer
   2752 ** is exhausted.
   2753 ** ^If pMem is NULL and N is non-zero, then each database connection
   2754 ** does an initial bulk allocation for page cache memory
   2755 ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
   2756 ** of -1024*N bytes if N is negative, . ^If additional
   2757 ** page cache memory is needed beyond what is provided by the initial
   2758 ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
   2759 ** additional cache line. </dd>
   2760 **
   2761 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
   2762 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
   2763 ** that SQLite will use for all of its dynamic memory allocation needs
   2764 ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
   2765 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
   2766 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
   2767 ** [SQLITE_ERROR] if invoked otherwise.
   2768 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
   2769 ** An 8-byte aligned pointer to the memory,
   2770 ** the number of bytes in the memory buffer, and the minimum allocation size.
   2771 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
   2772 ** to using its default memory allocator (the system malloc() implementation),
   2773 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
   2774 ** memory pointer is not NULL then the alternative memory
   2775 ** allocator is engaged to handle all of SQLites memory allocation needs.
   2776 ** The first pointer (the memory pointer) must be aligned to an 8-byte
   2777 ** boundary or subsequent behavior of SQLite will be undefined.
   2778 ** The minimum allocation size is capped at 2**12. Reasonable values
   2779 ** for the minimum allocation size are 2**5 through 2**8.</dd>
   2780 **
   2781 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
   2782 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
   2783 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
   2784 ** The argument specifies alternative low-level mutex routines to be used
   2785 ** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
   2786 ** the content of the [sqlite3_mutex_methods] structure before the call to
   2787 ** [sqlite3_config()] returns. ^If SQLite is compiled with
   2788 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   2789 ** the entire mutexing subsystem is omitted from the build and hence calls to
   2790 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
   2791 ** return [SQLITE_ERROR].</dd>
   2792 **
   2793 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
   2794 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
   2795 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
   2796 ** [sqlite3_mutex_methods]
   2797 ** structure is filled with the currently defined mutex routines.)^
   2798 ** This option can be used to overload the default mutex allocation
   2799 ** routines with a wrapper used to track mutex usage for performance
   2800 ** profiling or testing, for example.   ^If SQLite is compiled with
   2801 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   2802 ** the entire mutexing subsystem is omitted from the build and hence calls to
   2803 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
   2804 ** return [SQLITE_ERROR].</dd>
   2805 **
   2806 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
   2807 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
   2808 ** the default size of lookaside memory on each [database connection].
   2809 ** The first argument is the
   2810 ** size of each lookaside buffer slot and the second is the number of
   2811 ** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
   2812 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
   2813 ** option to [sqlite3_db_config()] can be used to change the lookaside
   2814 ** configuration on individual connections.)^ </dd>
   2815 **
   2816 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
   2817 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
   2818 ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
   2819 ** the interface to a custom page cache implementation.)^
   2820 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
   2821 **
   2822 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
   2823 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
   2824 ** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
   2825 ** the current page cache implementation into that object.)^ </dd>
   2826 **
   2827 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
   2828 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
   2829 ** global [error log].
   2830 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
   2831 ** function with a call signature of void(*)(void*,int,const char*),
   2832 ** and a pointer to void. ^If the function pointer is not NULL, it is
   2833 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
   2834 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
   2835 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
   2836 ** passed through as the first parameter to the application-defined logger
   2837 ** function whenever that function is invoked.  ^The second parameter to
   2838 ** the logger function is a copy of the first parameter to the corresponding
   2839 ** [sqlite3_log()] call and is intended to be a [result code] or an
   2840 ** [extended result code].  ^The third parameter passed to the logger is
   2841 ** log message after formatting via [sqlite3_snprintf()].
   2842 ** The SQLite logging interface is not reentrant; the logger function
   2843 ** supplied by the application must not invoke any SQLite interface.
   2844 ** In a multi-threaded application, the application-defined logger
   2845 ** function must be threadsafe. </dd>
   2846 **
   2847 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
   2848 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
   2849 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
   2850 ** then URI handling is globally disabled.)^ ^If URI handling is globally
   2851 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
   2852 ** [sqlite3_open16()] or
   2853 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
   2854 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
   2855 ** connection is opened. ^If it is globally disabled, filenames are
   2856 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
   2857 ** database connection is opened. ^(By default, URI handling is globally
   2858 ** disabled. The default value may be changed by compiling with the
   2859 ** [SQLITE_USE_URI] symbol defined.)^
   2860 **
   2861 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
   2862 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
   2863 ** argument which is interpreted as a boolean in order to enable or disable
   2864 ** the use of covering indices for full table scans in the query optimizer.
   2865 ** ^The default setting is determined
   2866 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
   2867 ** if that compile-time option is omitted.
   2868 ** The ability to disable the use of covering indices for full table scans
   2869 ** is because some incorrectly coded legacy applications might malfunction
   2870 ** when the optimization is enabled.  Providing the ability to
   2871 ** disable the optimization allows the older, buggy application code to work
   2872 ** without change even with newer versions of SQLite.
   2873 **
   2874 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
   2875 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
   2876 ** <dd> These options are obsolete and should not be used by new code.
   2877 ** They are retained for backwards compatibility but are now no-ops.
   2878 ** </dd>
   2879 **
   2880 ** [[SQLITE_CONFIG_SQLLOG]]
   2881 ** <dt>SQLITE_CONFIG_SQLLOG
   2882 ** <dd>This option is only available if sqlite is compiled with the
   2883 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
   2884 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
   2885 ** The second should be of type (void*). The callback is invoked by the library
   2886 ** in three separate circumstances, identified by the value passed as the
   2887 ** fourth parameter. If the fourth parameter is 0, then the database connection
   2888 ** passed as the second argument has just been opened. The third argument
   2889 ** points to a buffer containing the name of the main database file. If the
   2890 ** fourth parameter is 1, then the SQL statement that the third parameter
   2891 ** points to has just been executed. Or, if the fourth parameter is 2, then
   2892 ** the connection being passed as the second parameter is being closed. The
   2893 ** third parameter is passed NULL In this case.  An example of using this
   2894 ** configuration option can be seen in the "test_sqllog.c" source file in
   2895 ** the canonical SQLite source tree.</dd>
   2896 **
   2897 ** [[SQLITE_CONFIG_MMAP_SIZE]]
   2898 ** <dt>SQLITE_CONFIG_MMAP_SIZE
   2899 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
   2900 ** that are the default mmap size limit (the default setting for
   2901 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
   2902 ** ^The default setting can be overridden by each database connection using
   2903 ** either the [PRAGMA mmap_size] command, or by using the
   2904 ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
   2905 ** will be silently truncated if necessary so that it does not exceed the
   2906 ** compile-time maximum mmap size set by the
   2907 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
   2908 ** ^If either argument to this option is negative, then that argument is
   2909 ** changed to its compile-time default.
   2910 **
   2911 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
   2912 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
   2913 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
   2914 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
   2915 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
   2916 ** that specifies the maximum size of the created heap.
   2917 **
   2918 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
   2919 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
   2920 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
   2921 ** is a pointer to an integer and writes into that integer the number of extra
   2922 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
   2923 ** The amount of extra space required can change depending on the compiler,
   2924 ** target platform, and SQLite version.
   2925 **
   2926 ** [[SQLITE_CONFIG_PMASZ]]
   2927 ** <dt>SQLITE_CONFIG_PMASZ
   2928 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
   2929 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
   2930 ** sorter to that integer.  The default minimum PMA Size is set by the
   2931 ** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
   2932 ** to help with sort operations when multithreaded sorting
   2933 ** is enabled (using the [PRAGMA threads] command) and the amount of content
   2934 ** to be sorted exceeds the page size times the minimum of the
   2935 ** [PRAGMA cache_size] setting and this value.
   2936 **
   2937 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
   2938 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
   2939 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
   2940 ** becomes the [statement journal] spill-to-disk threshold.
   2941 ** [Statement journals] are held in memory until their size (in bytes)
   2942 ** exceeds this threshold, at which point they are written to disk.
   2943 ** Or if the threshold is -1, statement journals are always held
   2944 ** exclusively in memory.
   2945 ** Since many statement journals never become large, setting the spill
   2946 ** threshold to a value such as 64KiB can greatly reduce the amount of
   2947 ** I/O required to support statement rollback.
   2948 ** The default value for this setting is controlled by the
   2949 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
   2950 ** </dl>
   2951 */
   2952 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
   2953 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
   2954 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
   2955 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
   2956 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
   2957 #define SQLITE_CONFIG_SCRATCH       6  /* No longer used */
   2958 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
   2959 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
   2960 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
   2961 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
   2962 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
   2963 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
   2964 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
   2965 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
   2966 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
   2967 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
   2968 #define SQLITE_CONFIG_URI          17  /* int */
   2969 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
   2970 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
   2971 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
   2972 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
   2973 #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
   2974 #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
   2975 #define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
   2976 #define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
   2977 #define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
   2978 #define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
   2979 
   2980 /*
   2981 ** CAPI3REF: Database Connection Configuration Options
   2982 **
   2983 ** These constants are the available integer configuration options that
   2984 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
   2985 **
   2986 ** New configuration options may be added in future releases of SQLite.
   2987 ** Existing configuration options might be discontinued.  Applications
   2988 ** should check the return code from [sqlite3_db_config()] to make sure that
   2989 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
   2990 ** non-zero [error code] if a discontinued or unsupported configuration option
   2991 ** is invoked.
   2992 **
   2993 ** <dl>
   2994 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
   2995 ** <dd> ^This option takes three additional arguments that determine the
   2996 ** [lookaside memory allocator] configuration for the [database connection].
   2997 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
   2998 ** pointer to a memory buffer to use for lookaside memory.
   2999 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
   3000 ** may be NULL in which case SQLite will allocate the
   3001 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
   3002 ** size of each lookaside buffer slot.  ^The third argument is the number of
   3003 ** slots.  The size of the buffer in the first argument must be greater than
   3004 ** or equal to the product of the second and third arguments.  The buffer
   3005 ** must be aligned to an 8-byte boundary.  ^If the second argument to
   3006 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
   3007 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
   3008 ** configuration for a database connection can only be changed when that
   3009 ** connection is not currently using lookaside memory, or in other words
   3010 ** when the "current value" returned by
   3011 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
   3012 ** Any attempt to change the lookaside memory configuration when lookaside
   3013 ** memory is in use leaves the configuration unchanged and returns
   3014 ** [SQLITE_BUSY].)^</dd>
   3015 **
   3016 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
   3017 ** <dd> ^This option is used to enable or disable the enforcement of
   3018 ** [foreign key constraints].  There should be two additional arguments.
   3019 ** The first argument is an integer which is 0 to disable FK enforcement,
   3020 ** positive to enable FK enforcement or negative to leave FK enforcement
   3021 ** unchanged.  The second parameter is a pointer to an integer into which
   3022 ** is written 0 or 1 to indicate whether FK enforcement is off or on
   3023 ** following this call.  The second parameter may be a NULL pointer, in
   3024 ** which case the FK enforcement setting is not reported back. </dd>
   3025 **
   3026 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
   3027 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
   3028 ** There should be two additional arguments.
   3029 ** The first argument is an integer which is 0 to disable triggers,
   3030 ** positive to enable triggers or negative to leave the setting unchanged.
   3031 ** The second parameter is a pointer to an integer into which
   3032 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
   3033 ** following this call.  The second parameter may be a NULL pointer, in
   3034 ** which case the trigger setting is not reported back. </dd>
   3035 **
   3036 ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
   3037 ** <dd> ^This option is used to enable or disable the two-argument
   3038 ** version of the [fts3_tokenizer()] function which is part of the
   3039 ** [FTS3] full-text search engine extension.
   3040 ** There should be two additional arguments.
   3041 ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
   3042 ** positive to enable fts3_tokenizer() or negative to leave the setting
   3043 ** unchanged.
   3044 ** The second parameter is a pointer to an integer into which
   3045 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
   3046 ** following this call.  The second parameter may be a NULL pointer, in
   3047 ** which case the new setting is not reported back. </dd>
   3048 **
   3049 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
   3050 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
   3051 ** interface independently of the [load_extension()] SQL function.
   3052 ** The [sqlite3_enable_load_extension()] API enables or disables both the
   3053 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
   3054 ** There should be two additional arguments.
   3055 ** When the first argument to this interface is 1, then only the C-API is
   3056 ** enabled and the SQL function remains disabled.  If the first argument to
   3057 ** this interface is 0, then both the C-API and the SQL function are disabled.
   3058 ** If the first argument is -1, then no changes are made to state of either the
   3059 ** C-API or the SQL function.
   3060 ** The second parameter is a pointer to an integer into which
   3061 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
   3062 ** is disabled or enabled following this call.  The second parameter may
   3063 ** be a NULL pointer, in which case the new setting is not reported back.
   3064 ** </dd>
   3065 **
   3066 ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
   3067 ** <dd> ^This option is used to change the name of the "main" database
   3068 ** schema.  ^The sole argument is a pointer to a constant UTF8 string
   3069 ** which will become the new schema name in place of "main".  ^SQLite
   3070 ** does not make a copy of the new main schema name string, so the application
   3071 ** must ensure that the argument passed into this DBCONFIG option is unchanged
   3072 ** until after the database connection closes.
   3073 ** </dd>
   3074 **
   3075 ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
   3076 ** <dd> Usually, when a database in wal mode is closed or detached from a
   3077 ** database handle, SQLite checks if this will mean that there are now no
   3078 ** connections at all to the database. If so, it performs a checkpoint
   3079 ** operation before closing the connection. This option may be used to
   3080 ** override this behaviour. The first parameter passed to this operation
   3081 ** is an integer - non-zero to disable checkpoints-on-close, or zero (the
   3082 ** default) to enable them. The second parameter is a pointer to an integer
   3083 ** into which is written 0 or 1 to indicate whether checkpoints-on-close
   3084 ** have been disabled - 0 if they are not disabled, 1 if they are.
   3085 ** </dd>
   3086 ** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
   3087 ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
   3088 ** the [query planner stability guarantee] (QPSG).  When the QPSG is active,
   3089 ** a single SQL query statement will always use the same algorithm regardless
   3090 ** of values of [bound parameters].)^ The QPSG disables some query optimizations
   3091 ** that look at the values of bound parameters, which can make some queries
   3092 ** slower.  But the QPSG has the advantage of more predictable behavior.  With
   3093 ** the QPSG active, SQLite will always use the same query plan in the field as
   3094 ** was used during testing in the lab.
   3095 ** </dd>
   3096 ** <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
   3097 ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
   3098 ** include output for any operations performed by trigger programs. This
   3099 ** option is used to set or clear (the default) a flag that governs this
   3100 ** behavior. The first parameter passed to this operation is an integer -
   3101 ** non-zero to enable output for trigger programs, or zero to disable it.
   3102 ** The second parameter is a pointer to an integer into which is written
   3103 ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
   3104 ** it is not disabled, 1 if it is.
   3105 ** </dd>
   3106 ** </dl>
   3107 */
   3108 #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
   3109 #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
   3110 #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
   3111 #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
   3112 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
   3113 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
   3114 #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
   3115 #define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
   3116 #define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
   3117 #define SQLITE_DBCONFIG_MAX                   1008 /* Largest DBCONFIG */
   3118 
   3119 /*
   3120 ** CAPI3REF: Enable Or Disable Extended Result Codes
   3121 ** METHOD: sqlite3
   3122 **
   3123 ** ^The sqlite3_extended_result_codes() routine enables or disables the
   3124 ** [extended result codes] feature of SQLite. ^The extended result
   3125 ** codes are disabled by default for historical compatibility.
   3126 */
   3127 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
   3128 
   3129 /*
   3130 ** CAPI3REF: Last Insert Rowid
   3131 ** METHOD: sqlite3
   3132 **
   3133 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
   3134 ** has a unique 64-bit signed
   3135 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
   3136 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
   3137 ** names are not also used by explicitly declared columns. ^If
   3138 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
   3139 ** is another alias for the rowid.
   3140 **
   3141 ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
   3142 ** the most recent successful [INSERT] into a rowid table or [virtual table]
   3143 ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
   3144 ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
   3145 ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
   3146 ** zero.
   3147 **
   3148 ** As well as being set automatically as rows are inserted into database
   3149 ** tables, the value returned by this function may be set explicitly by
   3150 ** [sqlite3_set_last_insert_rowid()]
   3151 **
   3152 ** Some virtual table implementations may INSERT rows into rowid tables as
   3153 ** part of committing a transaction (e.g. to flush data accumulated in memory
   3154 ** to disk). In this case subsequent calls to this function return the rowid
   3155 ** associated with these internal INSERT operations, which leads to
   3156 ** unintuitive results. Virtual table implementations that do write to rowid
   3157 ** tables in this way can avoid this problem by restoring the original
   3158 ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
   3159 ** control to the user.
   3160 **
   3161 ** ^(If an [INSERT] occurs within a trigger then this routine will
   3162 ** return the [rowid] of the inserted row as long as the trigger is
   3163 ** running. Once the trigger program ends, the value returned
   3164 ** by this routine reverts to what it was before the trigger was fired.)^
   3165 **
   3166 ** ^An [INSERT] that fails due to a constraint violation is not a
   3167 ** successful [INSERT] and does not change the value returned by this
   3168 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
   3169 ** and INSERT OR ABORT make no changes to the return value of this
   3170 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
   3171 ** encounters a constraint violation, it does not fail.  The
   3172 ** INSERT continues to completion after deleting rows that caused
   3173 ** the constraint problem so INSERT OR REPLACE will always change
   3174 ** the return value of this interface.)^
   3175 **
   3176 ** ^For the purposes of this routine, an [INSERT] is considered to
   3177 ** be successful even if it is subsequently rolled back.
   3178 **
   3179 ** This function is accessible to SQL statements via the
   3180 ** [last_insert_rowid() SQL function].
   3181 **
   3182 ** If a separate thread performs a new [INSERT] on the same
   3183 ** database connection while the [sqlite3_last_insert_rowid()]
   3184 ** function is running and thus changes the last insert [rowid],
   3185 ** then the value returned by [sqlite3_last_insert_rowid()] is
   3186 ** unpredictable and might not equal either the old or the new
   3187 ** last insert [rowid].
   3188 */
   3189 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
   3190 
   3191 /*
   3192 ** CAPI3REF: Set the Last Insert Rowid value.
   3193 ** METHOD: sqlite3
   3194 **
   3195 ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
   3196 ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
   3197 ** without inserting a row into the database.
   3198 */
   3199 SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
   3200 
   3201 /*
   3202 ** CAPI3REF: Count The Number Of Rows Modified
   3203 ** METHOD: sqlite3
   3204 **
   3205 ** ^This function returns the number of rows modified, inserted or
   3206 ** deleted by the most recently completed INSERT, UPDATE or DELETE
   3207 ** statement on the database connection specified by the only parameter.
   3208 ** ^Executing any other type of SQL statement does not modify the value
   3209 ** returned by this function.
   3210 **
   3211 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
   3212 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
   3213 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
   3214 **
   3215 ** Changes to a view that are intercepted by
   3216 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
   3217 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
   3218 ** DELETE statement run on a view is always zero. Only changes made to real
   3219 ** tables are counted.
   3220 **
   3221 ** Things are more complicated if the sqlite3_changes() function is
   3222 ** executed while a trigger program is running. This may happen if the
   3223 ** program uses the [changes() SQL function], or if some other callback
   3224 ** function invokes sqlite3_changes() directly. Essentially:
   3225 **
   3226 ** <ul>
   3227 **   <li> ^(Before entering a trigger program the value returned by
   3228 **        sqlite3_changes() function is saved. After the trigger program
   3229 **        has finished, the original value is restored.)^
   3230 **
   3231 **   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
   3232 **        statement sets the value returned by sqlite3_changes()
   3233 **        upon completion as normal. Of course, this value will not include
   3234 **        any changes performed by sub-triggers, as the sqlite3_changes()
   3235 **        value will be saved and restored after each sub-trigger has run.)^
   3236 ** </ul>
   3237 **
   3238 ** ^This means that if the changes() SQL function (or similar) is used
   3239 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
   3240 ** returns the value as set when the calling statement began executing.
   3241 ** ^If it is used by the second or subsequent such statement within a trigger
   3242 ** program, the value returned reflects the number of rows modified by the
   3243 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
   3244 **
   3245 ** See also the [sqlite3_total_changes()] interface, the
   3246 ** [count_changes pragma], and the [changes() SQL function].
   3247 **
   3248 ** If a separate thread makes changes on the same database connection
   3249 ** while [sqlite3_changes()] is running then the value returned
   3250 ** is unpredictable and not meaningful.
   3251 */
   3252 SQLITE_API int sqlite3_changes(sqlite3*);
   3253 
   3254 /*
   3255 ** CAPI3REF: Total Number Of Rows Modified
   3256 ** METHOD: sqlite3
   3257 **
   3258 ** ^This function returns the total number of rows inserted, modified or
   3259 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
   3260 ** since the database connection was opened, including those executed as
   3261 ** part of trigger programs. ^Executing any other type of SQL statement
   3262 ** does not affect the value returned by sqlite3_total_changes().
   3263 **
   3264 ** ^Changes made as part of [foreign key actions] are included in the
   3265 ** count, but those made as part of REPLACE constraint resolution are
   3266 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
   3267 ** are not counted.
   3268 **
   3269 ** See also the [sqlite3_changes()] interface, the
   3270 ** [count_changes pragma], and the [total_changes() SQL function].
   3271 **
   3272 ** If a separate thread makes changes on the same database connection
   3273 ** while [sqlite3_total_changes()] is running then the value
   3274 ** returned is unpredictable and not meaningful.
   3275 */
   3276 SQLITE_API int sqlite3_total_changes(sqlite3*);
   3277 
   3278 /*
   3279 ** CAPI3REF: Interrupt A Long-Running Query
   3280 ** METHOD: sqlite3
   3281 **
   3282 ** ^This function causes any pending database operation to abort and
   3283 ** return at its earliest opportunity. This routine is typically
   3284 ** called in response to a user action such as pressing "Cancel"
   3285 ** or Ctrl-C where the user wants a long query operation to halt
   3286 ** immediately.
   3287 **
   3288 ** ^It is safe to call this routine from a thread different from the
   3289 ** thread that is currently running the database operation.  But it
   3290 ** is not safe to call this routine with a [database connection] that
   3291 ** is closed or might close before sqlite3_interrupt() returns.
   3292 **
   3293 ** ^If an SQL operation is very nearly finished at the time when
   3294 ** sqlite3_interrupt() is called, then it might not have an opportunity
   3295 ** to be interrupted and might continue to completion.
   3296 **
   3297 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
   3298 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
   3299 ** that is inside an explicit transaction, then the entire transaction
   3300 ** will be rolled back automatically.
   3301 **
   3302 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
   3303 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
   3304 ** that are started after the sqlite3_interrupt() call and before the
   3305 ** running statements reaches zero are interrupted as if they had been
   3306 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
   3307 ** that are started after the running statement count reaches zero are
   3308 ** not effected by the sqlite3_interrupt().
   3309 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
   3310 ** SQL statements is a no-op and has no effect on SQL statements
   3311 ** that are started after the sqlite3_interrupt() call returns.
   3312 */
   3313 SQLITE_API void sqlite3_interrupt(sqlite3*);
   3314 
   3315 /*
   3316 ** CAPI3REF: Determine If An SQL Statement Is Complete
   3317 **
   3318 ** These routines are useful during command-line input to determine if the
   3319 ** currently entered text seems to form a complete SQL statement or
   3320 ** if additional input is needed before sending the text into
   3321 ** SQLite for parsing.  ^These routines return 1 if the input string
   3322 ** appears to be a complete SQL statement.  ^A statement is judged to be
   3323 ** complete if it ends with a semicolon token and is not a prefix of a
   3324 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
   3325 ** string literals or quoted identifier names or comments are not
   3326 ** independent tokens (they are part of the token in which they are
   3327 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
   3328 ** and comments that follow the final semicolon are ignored.
   3329 **
   3330 ** ^These routines return 0 if the statement is incomplete.  ^If a
   3331 ** memory allocation fails, then SQLITE_NOMEM is returned.
   3332 **
   3333 ** ^These routines do not parse the SQL statements thus
   3334 ** will not detect syntactically incorrect SQL.
   3335 **
   3336 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
   3337 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
   3338 ** automatically by sqlite3_complete16().  If that initialization fails,
   3339 ** then the return value from sqlite3_complete16() will be non-zero
   3340 ** regardless of whether or not the input SQL is complete.)^
   3341 **
   3342 ** The input to [sqlite3_complete()] must be a zero-terminated
   3343 ** UTF-8 string.
   3344 **
   3345 ** The input to [sqlite3_complete16()] must be a zero-terminated
   3346 ** UTF-16 string in native byte order.
   3347 */
   3348 SQLITE_API int sqlite3_complete(const char *sql);
   3349 SQLITE_API int sqlite3_complete16(const void *sql);
   3350 
   3351 /*
   3352 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
   3353 ** KEYWORDS: {busy-handler callback} {busy handler}
   3354 ** METHOD: sqlite3
   3355 **
   3356 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
   3357 ** that might be invoked with argument P whenever
   3358 ** an attempt is made to access a database table associated with
   3359 ** [database connection] D when another thread
   3360 ** or process has the table locked.
   3361 ** The sqlite3_busy_handler() interface is used to implement
   3362 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
   3363 **
   3364 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
   3365 ** is returned immediately upon encountering the lock.  ^If the busy callback
   3366 ** is not NULL, then the callback might be invoked with two arguments.
   3367 **
   3368 ** ^The first argument to the busy handler is a copy of the void* pointer which
   3369 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
   3370 ** the busy handler callback is the number of times that the busy handler has
   3371 ** been invoked previously for the same locking event.  ^If the
   3372 ** busy callback returns 0, then no additional attempts are made to
   3373 ** access the database and [SQLITE_BUSY] is returned
   3374 ** to the application.
   3375 ** ^If the callback returns non-zero, then another attempt
   3376 ** is made to access the database and the cycle repeats.
   3377 **
   3378 ** The presence of a busy handler does not guarantee that it will be invoked
   3379 ** when there is lock contention. ^If SQLite determines that invoking the busy
   3380 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
   3381 ** to the application instead of invoking the
   3382 ** busy handler.
   3383 ** Consider a scenario where one process is holding a read lock that
   3384 ** it is trying to promote to a reserved lock and
   3385 ** a second process is holding a reserved lock that it is trying
   3386 ** to promote to an exclusive lock.  The first process cannot proceed
   3387 ** because it is blocked by the second and the second process cannot
   3388 ** proceed because it is blocked by the first.  If both processes
   3389 ** invoke the busy handlers, neither will make any progress.  Therefore,
   3390 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
   3391 ** will induce the first process to release its read lock and allow
   3392 ** the second process to proceed.
   3393 **
   3394 ** ^The default busy callback is NULL.
   3395 **
   3396 ** ^(There can only be a single busy handler defined for each
   3397 ** [database connection].  Setting a new busy handler clears any
   3398 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
   3399 ** or evaluating [PRAGMA busy_timeout=N] will change the
   3400 ** busy handler and thus clear any previously set busy handler.
   3401 **
   3402 ** The busy callback should not take any actions which modify the
   3403 ** database connection that invoked the busy handler.  In other words,
   3404 ** the busy handler is not reentrant.  Any such actions
   3405 ** result in undefined behavior.
   3406 **
   3407 ** A busy handler must not close the database connection
   3408 ** or [prepared statement] that invoked the busy handler.
   3409 */
   3410 SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
   3411 
   3412 /*
   3413 ** CAPI3REF: Set A Busy Timeout
   3414 ** METHOD: sqlite3
   3415 **
   3416 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
   3417 ** for a specified amount of time when a table is locked.  ^The handler
   3418 ** will sleep multiple times until at least "ms" milliseconds of sleeping
   3419 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
   3420 ** the handler returns 0 which causes [sqlite3_step()] to return
   3421 ** [SQLITE_BUSY].
   3422 **
   3423 ** ^Calling this routine with an argument less than or equal to zero
   3424 ** turns off all busy handlers.
   3425 **
   3426 ** ^(There can only be a single busy handler for a particular
   3427 ** [database connection] at any given moment.  If another busy handler
   3428 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
   3429 ** this routine, that other busy handler is cleared.)^
   3430 **
   3431 ** See also:  [PRAGMA busy_timeout]
   3432 */
   3433 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
   3434 
   3435 /*
   3436 ** CAPI3REF: Convenience Routines For Running Queries
   3437 ** METHOD: sqlite3
   3438 **
   3439 ** This is a legacy interface that is preserved for backwards compatibility.
   3440 ** Use of this interface is not recommended.
   3441 **
   3442 ** Definition: A <b>result table</b> is memory data structure created by the
   3443 ** [sqlite3_get_table()] interface.  A result table records the
   3444 ** complete query results from one or more queries.
   3445 **
   3446 ** The table conceptually has a number of rows and columns.  But
   3447 ** these numbers are not part of the result table itself.  These
   3448 ** numbers are obtained separately.  Let N be the number of rows
   3449 ** and M be the number of columns.
   3450 **
   3451 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
   3452 ** There are (N+1)*M elements in the array.  The first M pointers point
   3453 ** to zero-terminated strings that  contain the names of the columns.
   3454 ** The remaining entries all point to query results.  NULL values result
   3455 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
   3456 ** string representation as returned by [sqlite3_column_text()].
   3457 **
   3458 ** A result table might consist of one or more memory allocations.
   3459 ** It is not safe to pass a result table directly to [sqlite3_free()].
   3460 ** A result table should be deallocated using [sqlite3_free_table()].
   3461 **
   3462 ** ^(As an example of the result table format, suppose a query result
   3463 ** is as follows:
   3464 **
   3465 ** <blockquote><pre>
   3466 **        Name        | Age
   3467 **        -----------------------
   3468 **        Alice       | 43
   3469 **        Bob         | 28
   3470 **        Cindy       | 21
   3471 ** </pre></blockquote>
   3472 **
   3473 ** There are two column (M==2) and three rows (N==3).  Thus the
   3474 ** result table has 8 entries.  Suppose the result table is stored
   3475 ** in an array names azResult.  Then azResult holds this content:
   3476 **
   3477 ** <blockquote><pre>
   3478 **        azResult&#91;0] = "Name";
   3479 **        azResult&#91;1] = "Age";
   3480 **        azResult&#91;2] = "Alice";
   3481 **        azResult&#91;3] = "43";
   3482 **        azResult&#91;4] = "Bob";
   3483 **        azResult&#91;5] = "28";
   3484 **        azResult&#91;6] = "Cindy";
   3485 **        azResult&#91;7] = "21";
   3486 ** </pre></blockquote>)^
   3487 **
   3488 ** ^The sqlite3_get_table() function evaluates one or more
   3489 ** semicolon-separated SQL statements in the zero-terminated UTF-8
   3490 ** string of its 2nd parameter and returns a result table to the
   3491 ** pointer given in its 3rd parameter.
   3492 **
   3493 ** After the application has finished with the result from sqlite3_get_table(),
   3494 ** it must pass the result table pointer to sqlite3_free_table() in order to
   3495 ** release the memory that was malloced.  Because of the way the
   3496 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
   3497 ** function must not try to call [sqlite3_free()] directly.  Only
   3498 ** [sqlite3_free_table()] is able to release the memory properly and safely.
   3499 **
   3500 ** The sqlite3_get_table() interface is implemented as a wrapper around
   3501 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
   3502 ** to any internal data structures of SQLite.  It uses only the public
   3503 ** interface defined here.  As a consequence, errors that occur in the
   3504 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
   3505 ** reflected in subsequent calls to [sqlite3_errcode()] or
   3506 ** [sqlite3_errmsg()].
   3507 */
   3508 SQLITE_API int sqlite3_get_table(
   3509   sqlite3 *db,          /* An open database */
   3510   const char *zSql,     /* SQL to be evaluated */
   3511   char ***pazResult,    /* Results of the query */
   3512   int *pnRow,           /* Number of result rows written here */
   3513   int *pnColumn,        /* Number of result columns written here */
   3514   char **pzErrmsg       /* Error msg written here */
   3515 );
   3516 SQLITE_API void sqlite3_free_table(char **result);
   3517 
   3518 /*
   3519 ** CAPI3REF: Formatted String Printing Functions
   3520 **
   3521 ** These routines are work-alikes of the "printf()" family of functions
   3522 ** from the standard C library.
   3523 ** These routines understand most of the common K&R formatting options,
   3524 ** plus some additional non-standard formats, detailed below.
   3525 ** Note that some of the more obscure formatting options from recent
   3526 ** C-library standards are omitted from this implementation.
   3527 **
   3528 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
   3529 ** results into memory obtained from [sqlite3_malloc()].
   3530 ** The strings returned by these two routines should be
   3531 ** released by [sqlite3_free()].  ^Both routines return a
   3532 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
   3533 ** memory to hold the resulting string.
   3534 **
   3535 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
   3536 ** the standard C library.  The result is written into the
   3537 ** buffer supplied as the second parameter whose size is given by
   3538 ** the first parameter. Note that the order of the
   3539 ** first two parameters is reversed from snprintf().)^  This is an
   3540 ** historical accident that cannot be fixed without breaking
   3541 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
   3542 ** returns a pointer to its buffer instead of the number of
   3543 ** characters actually written into the buffer.)^  We admit that
   3544 ** the number of characters written would be a more useful return
   3545 ** value but we cannot change the implementation of sqlite3_snprintf()
   3546 ** now without breaking compatibility.
   3547 **
   3548 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
   3549 ** guarantees that the buffer is always zero-terminated.  ^The first
   3550 ** parameter "n" is the total size of the buffer, including space for
   3551 ** the zero terminator.  So the longest string that can be completely
   3552 ** written will be n-1 characters.
   3553 **
   3554 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
   3555 **
   3556 ** These routines all implement some additional formatting
   3557 ** options that are useful for constructing SQL statements.
   3558 ** All of the usual printf() formatting options apply.  In addition, there
   3559 ** is are "%q", "%Q", "%w" and "%z" options.
   3560 **
   3561 ** ^(The %q option works like %s in that it substitutes a nul-terminated
   3562 ** string from the argument list.  But %q also doubles every '\'' character.
   3563 ** %q is designed for use inside a string literal.)^  By doubling each '\''
   3564 ** character it escapes that character and allows it to be inserted into
   3565 ** the string.
   3566 **
   3567 ** For example, assume the string variable zText contains text as follows:
   3568 **
   3569 ** <blockquote><pre>
   3570 **  char *zText = "It's a happy day!";
   3571 ** </pre></blockquote>
   3572 **
   3573 ** One can use this text in an SQL statement as follows:
   3574 **
   3575 ** <blockquote><pre>
   3576 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
   3577 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   3578 **  sqlite3_free(zSQL);
   3579 ** </pre></blockquote>
   3580 **
   3581 ** Because the %q format string is used, the '\'' character in zText
   3582 ** is escaped and the SQL generated is as follows:
   3583 **
   3584 ** <blockquote><pre>
   3585 **  INSERT INTO table1 VALUES('It''s a happy day!')
   3586 ** </pre></blockquote>
   3587 **
   3588 ** This is correct.  Had we used %s instead of %q, the generated SQL
   3589 ** would have looked like this:
   3590 **
   3591 ** <blockquote><pre>
   3592 **  INSERT INTO table1 VALUES('It's a happy day!');
   3593 ** </pre></blockquote>
   3594 **
   3595 ** This second example is an SQL syntax error.  As a general rule you should
   3596 ** always use %q instead of %s when inserting text into a string literal.
   3597 **
   3598 ** ^(The %Q option works like %q except it also adds single quotes around
   3599 ** the outside of the total string.  Additionally, if the parameter in the
   3600 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
   3601 ** single quotes).)^  So, for example, one could say:
   3602 **
   3603 ** <blockquote><pre>
   3604 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
   3605 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   3606 **  sqlite3_free(zSQL);
   3607 ** </pre></blockquote>
   3608 **
   3609 ** The code above will render a correct SQL statement in the zSQL
   3610 ** variable even if the zText variable is a NULL pointer.
   3611 **
   3612 ** ^(The "%w" formatting option is like "%q" except that it expects to
   3613 ** be contained within double-quotes instead of single quotes, and it
   3614 ** escapes the double-quote character instead of the single-quote
   3615 ** character.)^  The "%w" formatting option is intended for safely inserting
   3616 ** table and column names into a constructed SQL statement.
   3617 **
   3618 ** ^(The "%z" formatting option works like "%s" but with the
   3619 ** addition that after the string has been read and copied into
   3620 ** the result, [sqlite3_free()] is called on the input string.)^
   3621 */
   3622 SQLITE_API char *sqlite3_mprintf(const char*,...);
   3623 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
   3624 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
   3625 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
   3626 
   3627 /*
   3628 ** CAPI3REF: Memory Allocation Subsystem
   3629 **
   3630 ** The SQLite core uses these three routines for all of its own
   3631 ** internal memory allocation needs. "Core" in the previous sentence
   3632 ** does not include operating-system specific VFS implementation.  The
   3633 ** Windows VFS uses native malloc() and free() for some operations.
   3634 **
   3635 ** ^The sqlite3_malloc() routine returns a pointer to a block
   3636 ** of memory at least N bytes in length, where N is the parameter.
   3637 ** ^If sqlite3_malloc() is unable to obtain sufficient free
   3638 ** memory, it returns a NULL pointer.  ^If the parameter N to
   3639 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
   3640 ** a NULL pointer.
   3641 **
   3642 ** ^The sqlite3_malloc64(N) routine works just like
   3643 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
   3644 ** of a signed 32-bit integer.
   3645 **
   3646 ** ^Calling sqlite3_free() with a pointer previously returned
   3647 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
   3648 ** that it might be reused.  ^The sqlite3_free() routine is
   3649 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
   3650 ** to sqlite3_free() is harmless.  After being freed, memory
   3651 ** should neither be read nor written.  Even reading previously freed
   3652 ** memory might result in a segmentation fault or other severe error.
   3653 ** Memory corruption, a segmentation fault, or other severe error
   3654 ** might result if sqlite3_free() is called with a non-NULL pointer that
   3655 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
   3656 **
   3657 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
   3658 ** prior memory allocation X to be at least N bytes.
   3659 ** ^If the X parameter to sqlite3_realloc(X,N)
   3660 ** is a NULL pointer then its behavior is identical to calling
   3661 ** sqlite3_malloc(N).
   3662 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
   3663 ** negative then the behavior is exactly the same as calling
   3664 ** sqlite3_free(X).
   3665 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
   3666 ** of at least N bytes in size or NULL if insufficient memory is available.
   3667 ** ^If M is the size of the prior allocation, then min(N,M) bytes
   3668 ** of the prior allocation are copied into the beginning of buffer returned
   3669 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
   3670 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
   3671 ** prior allocation is not freed.
   3672 **
   3673 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
   3674 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
   3675 ** of a 32-bit signed integer.
   3676 **
   3677 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
   3678 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
   3679 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
   3680 ** ^The value returned by sqlite3_msize(X) might be larger than the number
   3681 ** of bytes requested when X was allocated.  ^If X is a NULL pointer then
   3682 ** sqlite3_msize(X) returns zero.  If X points to something that is not
   3683 ** the beginning of memory allocation, or if it points to a formerly
   3684 ** valid memory allocation that has now been freed, then the behavior
   3685 ** of sqlite3_msize(X) is undefined and possibly harmful.
   3686 **
   3687 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
   3688 ** sqlite3_malloc64(), and sqlite3_realloc64()
   3689 ** is always aligned to at least an 8 byte boundary, or to a
   3690 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
   3691 ** option is used.
   3692 **
   3693 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
   3694 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
   3695 ** implementation of these routines to be omitted.  That capability
   3696 ** is no longer provided.  Only built-in memory allocators can be used.
   3697 **
   3698 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
   3699 ** the system malloc() and free() directly when converting
   3700 ** filenames between the UTF-8 encoding used by SQLite
   3701 ** and whatever filename encoding is used by the particular Windows
   3702 ** installation.  Memory allocation errors were detected, but
   3703 ** they were reported back as [SQLITE_CANTOPEN] or
   3704 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
   3705 **
   3706 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
   3707 ** must be either NULL or else pointers obtained from a prior
   3708 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
   3709 ** not yet been released.
   3710 **
   3711 ** The application must not read or write any part of
   3712 ** a block of memory after it has been released using
   3713 ** [sqlite3_free()] or [sqlite3_realloc()].
   3714 */
   3715 SQLITE_API void *sqlite3_malloc(int);
   3716 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
   3717 SQLITE_API void *sqlite3_realloc(void*, int);
   3718 SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
   3719 SQLITE_API void sqlite3_free(void*);
   3720 SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
   3721 
   3722 /*
   3723 ** CAPI3REF: Memory Allocator Statistics
   3724 **
   3725 ** SQLite provides these two interfaces for reporting on the status
   3726 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
   3727 ** routines, which form the built-in memory allocation subsystem.
   3728 **
   3729 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
   3730 ** of memory currently outstanding (malloced but not freed).
   3731 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
   3732 ** value of [sqlite3_memory_used()] since the high-water mark
   3733 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
   3734 ** [sqlite3_memory_highwater()] include any overhead
   3735 ** added by SQLite in its implementation of [sqlite3_malloc()],
   3736 ** but not overhead added by the any underlying system library
   3737 ** routines that [sqlite3_malloc()] may call.
   3738 **
   3739 ** ^The memory high-water mark is reset to the current value of
   3740 ** [sqlite3_memory_used()] if and only if the parameter to
   3741 ** [sqlite3_memory_highwater()] is true.  ^The value returned
   3742 ** by [sqlite3_memory_highwater(1)] is the high-water mark
   3743 ** prior to the reset.
   3744 */
   3745 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
   3746 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
   3747 
   3748 /*
   3749 ** CAPI3REF: Pseudo-Random Number Generator
   3750 **
   3751 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
   3752 ** select random [ROWID | ROWIDs] when inserting new records into a table that
   3753 ** already uses the largest possible [ROWID].  The PRNG is also used for
   3754 ** the build-in random() and randomblob() SQL functions.  This interface allows
   3755 ** applications to access the same PRNG for other purposes.
   3756 **
   3757 ** ^A call to this routine stores N bytes of randomness into buffer P.
   3758 ** ^The P parameter can be a NULL pointer.
   3759 **
   3760 ** ^If this routine has not been previously called or if the previous
   3761 ** call had N less than one or a NULL pointer for P, then the PRNG is
   3762 ** seeded using randomness obtained from the xRandomness method of
   3763 ** the default [sqlite3_vfs] object.
   3764 ** ^If the previous call to this routine had an N of 1 or more and a
   3765 ** non-NULL P then the pseudo-randomness is generated
   3766 ** internally and without recourse to the [sqlite3_vfs] xRandomness
   3767 ** method.
   3768 */
   3769 SQLITE_API void sqlite3_randomness(int N, void *P);
   3770 
   3771 /*
   3772 ** CAPI3REF: Compile-Time Authorization Callbacks
   3773 ** METHOD: sqlite3
   3774 ** KEYWORDS: {authorizer callback}
   3775 **
   3776 ** ^This routine registers an authorizer callback with a particular
   3777 ** [database connection], supplied in the first argument.
   3778 ** ^The authorizer callback is invoked as SQL statements are being compiled
   3779 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
   3780 ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
   3781 ** and [sqlite3_prepare16_v3()].  ^At various
   3782 ** points during the compilation process, as logic is being created
   3783 ** to perform various actions, the authorizer callback is invoked to
   3784 ** see if those actions are allowed.  ^The authorizer callback should
   3785 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
   3786 ** specific action but allow the SQL statement to continue to be
   3787 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
   3788 ** rejected with an error.  ^If the authorizer callback returns
   3789 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
   3790 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
   3791 ** the authorizer will fail with an error message.
   3792 **
   3793 ** When the callback returns [SQLITE_OK], that means the operation
   3794 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
   3795 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
   3796 ** authorizer will fail with an error message explaining that
   3797 ** access is denied.
   3798 **
   3799 ** ^The first parameter to the authorizer callback is a copy of the third
   3800 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
   3801 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
   3802 ** the particular action to be authorized. ^The third through sixth parameters
   3803 ** to the callback are either NULL pointers or zero-terminated strings
   3804 ** that contain additional details about the action to be authorized.
   3805 ** Applications must always be prepared to encounter a NULL pointer in any
   3806 ** of the third through the sixth parameters of the authorization callback.
   3807 **
   3808 ** ^If the action code is [SQLITE_READ]
   3809 ** and the callback returns [SQLITE_IGNORE] then the
   3810 ** [prepared statement] statement is constructed to substitute
   3811 ** a NULL value in place of the table column that would have
   3812 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
   3813 ** return can be used to deny an untrusted user access to individual
   3814 ** columns of a table.
   3815 ** ^When a table is referenced by a [SELECT] but no column values are
   3816 ** extracted from that table (for example in a query like
   3817 ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
   3818 ** is invoked once for that table with a column name that is an empty string.
   3819 ** ^If the action code is [SQLITE_DELETE] and the callback returns
   3820 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
   3821 ** [truncate optimization] is disabled and all rows are deleted individually.
   3822 **
   3823 ** An authorizer is used when [sqlite3_prepare | preparing]
   3824 ** SQL statements from an untrusted source, to ensure that the SQL statements
   3825 ** do not try to access data they are not allowed to see, or that they do not
   3826 ** try to execute malicious statements that damage the database.  For
   3827 ** example, an application may allow a user to enter arbitrary
   3828 ** SQL queries for evaluation by a database.  But the application does
   3829 ** not want the user to be able to make arbitrary changes to the
   3830 ** database.  An authorizer could then be put in place while the
   3831 ** user-entered SQL is being [sqlite3_prepare | prepared] that
   3832 ** disallows everything except [SELECT] statements.
   3833 **
   3834 ** Applications that need to process SQL from untrusted sources
   3835 ** might also consider lowering resource limits using [sqlite3_limit()]
   3836 ** and limiting database size using the [max_page_count] [PRAGMA]
   3837 ** in addition to using an authorizer.
   3838 **
   3839 ** ^(Only a single authorizer can be in place on a database connection
   3840 ** at a time.  Each call to sqlite3_set_authorizer overrides the
   3841 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
   3842 ** The authorizer is disabled by default.
   3843 **
   3844 ** The authorizer callback must not do anything that will modify
   3845 ** the database connection that invoked the authorizer callback.
   3846 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   3847 ** database connections for the meaning of "modify" in this paragraph.
   3848 **
   3849 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
   3850 ** statement might be re-prepared during [sqlite3_step()] due to a
   3851 ** schema change.  Hence, the application should ensure that the
   3852 ** correct authorizer callback remains in place during the [sqlite3_step()].
   3853 **
   3854 ** ^Note that the authorizer callback is invoked only during
   3855 ** [sqlite3_prepare()] or its variants.  Authorization is not
   3856 ** performed during statement evaluation in [sqlite3_step()], unless
   3857 ** as stated in the previous paragraph, sqlite3_step() invokes
   3858 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
   3859 */
   3860 SQLITE_API int sqlite3_set_authorizer(
   3861   sqlite3*,
   3862   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   3863   void *pUserData
   3864 );
   3865 
   3866 /*
   3867 ** CAPI3REF: Authorizer Return Codes
   3868 **
   3869 ** The [sqlite3_set_authorizer | authorizer callback function] must
   3870 ** return either [SQLITE_OK] or one of these two constants in order
   3871 ** to signal SQLite whether or not the action is permitted.  See the
   3872 ** [sqlite3_set_authorizer | authorizer documentation] for additional
   3873 ** information.
   3874 **
   3875 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
   3876 ** returned from the [sqlite3_vtab_on_conflict()] interface.
   3877 */
   3878 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
   3879 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
   3880 
   3881 /*
   3882 ** CAPI3REF: Authorizer Action Codes
   3883 **
   3884 ** The [sqlite3_set_authorizer()] interface registers a callback function
   3885 ** that is invoked to authorize certain SQL statement actions.  The
   3886 ** second parameter to the callback is an integer code that specifies
   3887 ** what action is being authorized.  These are the integer action codes that
   3888 ** the authorizer callback may be passed.
   3889 **
   3890 ** These action code values signify what kind of operation is to be
   3891 ** authorized.  The 3rd and 4th parameters to the authorization
   3892 ** callback function will be parameters or NULL depending on which of these
   3893 ** codes is used as the second parameter.  ^(The 5th parameter to the
   3894 ** authorizer callback is the name of the database ("main", "temp",
   3895 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
   3896 ** is the name of the inner-most trigger or view that is responsible for
   3897 ** the access attempt or NULL if this access attempt is directly from
   3898 ** top-level SQL code.
   3899 */
   3900 /******************************************* 3rd ************ 4th ***********/
   3901 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
   3902 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
   3903 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
   3904 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
   3905 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
   3906 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
   3907 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
   3908 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
   3909 #define SQLITE_DELETE                9   /* Table Name      NULL            */
   3910 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
   3911 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
   3912 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
   3913 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
   3914 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
   3915 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
   3916 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
   3917 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
   3918 #define SQLITE_INSERT               18   /* Table Name      NULL            */
   3919 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
   3920 #define SQLITE_READ                 20   /* Table Name      Column Name     */
   3921 #define SQLITE_SELECT               21   /* NULL            NULL            */
   3922 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
   3923 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
   3924 #define SQLITE_ATTACH               24   /* Filename        NULL            */
   3925 #define SQLITE_DETACH               25   /* Database Name   NULL            */
   3926 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
   3927 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
   3928 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
   3929 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
   3930 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
   3931 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
   3932 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
   3933 #define SQLITE_COPY                  0   /* No longer used */
   3934 #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
   3935 
   3936 /*
   3937 ** CAPI3REF: Tracing And Profiling Functions
   3938 ** METHOD: sqlite3
   3939 **
   3940 ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
   3941 ** instead of the routines described here.
   3942 **
   3943 ** These routines register callback functions that can be used for
   3944 ** tracing and profiling the execution of SQL statements.
   3945 **
   3946 ** ^The callback function registered by sqlite3_trace() is invoked at
   3947 ** various times when an SQL statement is being run by [sqlite3_step()].
   3948 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
   3949 ** SQL statement text as the statement first begins executing.
   3950 ** ^(Additional sqlite3_trace() callbacks might occur
   3951 ** as each triggered subprogram is entered.  The callbacks for triggers
   3952 ** contain a UTF-8 SQL comment that identifies the trigger.)^
   3953 **
   3954 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
   3955 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
   3956 **
   3957 ** ^The callback function registered by sqlite3_profile() is invoked
   3958 ** as each SQL statement finishes.  ^The profile callback contains
   3959 ** the original statement text and an estimate of wall-clock time
   3960 ** of how long that statement took to run.  ^The profile callback
   3961 ** time is in units of nanoseconds, however the current implementation
   3962 ** is only capable of millisecond resolution so the six least significant
   3963 ** digits in the time are meaningless.  Future versions of SQLite
   3964 ** might provide greater resolution on the profiler callback.  The
   3965 ** sqlite3_profile() function is considered experimental and is
   3966 ** subject to change in future versions of SQLite.
   3967 */
   3968 SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
   3969    void(*xTrace)(void*,const char*), void*);
   3970 SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
   3971    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
   3972 
   3973 /*
   3974 ** CAPI3REF: SQL Trace Event Codes
   3975 ** KEYWORDS: SQLITE_TRACE
   3976 **
   3977 ** These constants identify classes of events that can be monitored
   3978 ** using the [sqlite3_trace_v2()] tracing logic.  The M argument
   3979 ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
   3980 ** the following constants.  ^The first argument to the trace callback
   3981 ** is one of the following constants.
   3982 **
   3983 ** New tracing constants may be added in future releases.
   3984 **
   3985 ** ^A trace callback has four arguments: xCallback(T,C,P,X).
   3986 ** ^The T argument is one of the integer type codes above.
   3987 ** ^The C argument is a copy of the context pointer passed in as the
   3988 ** fourth argument to [sqlite3_trace_v2()].
   3989 ** The P and X arguments are pointers whose meanings depend on T.
   3990 **
   3991 ** <dl>
   3992 ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
   3993 ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
   3994 ** first begins running and possibly at other times during the
   3995 ** execution of the prepared statement, such as at the start of each
   3996 ** trigger subprogram. ^The P argument is a pointer to the
   3997 ** [prepared statement]. ^The X argument is a pointer to a string which
   3998 ** is the unexpanded SQL text of the prepared statement or an SQL comment
   3999 ** that indicates the invocation of a trigger.  ^The callback can compute
   4000 ** the same text that would have been returned by the legacy [sqlite3_trace()]
   4001 ** interface by using the X argument when X begins with "--" and invoking
   4002 ** [sqlite3_expanded_sql(P)] otherwise.
   4003 **
   4004 ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
   4005 ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
   4006 ** information as is provided by the [sqlite3_profile()] callback.
   4007 ** ^The P argument is a pointer to the [prepared statement] and the
   4008 ** X argument points to a 64-bit integer which is the estimated of
   4009 ** the number of nanosecond that the prepared statement took to run.
   4010 ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
   4011 **
   4012 ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
   4013 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
   4014 ** statement generates a single row of result.
   4015 ** ^The P argument is a pointer to the [prepared statement] and the
   4016 ** X argument is unused.
   4017 **
   4018 ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
   4019 ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
   4020 ** connection closes.
   4021 ** ^The P argument is a pointer to the [database connection] object
   4022 ** and the X argument is unused.
   4023 ** </dl>
   4024 */
   4025 #define SQLITE_TRACE_STMT       0x01
   4026 #define SQLITE_TRACE_PROFILE    0x02
   4027 #define SQLITE_TRACE_ROW        0x04
   4028 #define SQLITE_TRACE_CLOSE      0x08
   4029 
   4030 /*
   4031 ** CAPI3REF: SQL Trace Hook
   4032 ** METHOD: sqlite3
   4033 **
   4034 ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
   4035 ** function X against [database connection] D, using property mask M
   4036 ** and context pointer P.  ^If the X callback is
   4037 ** NULL or if the M mask is zero, then tracing is disabled.  The
   4038 ** M argument should be the bitwise OR-ed combination of
   4039 ** zero or more [SQLITE_TRACE] constants.
   4040 **
   4041 ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
   4042 ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
   4043 **
   4044 ** ^The X callback is invoked whenever any of the events identified by
   4045 ** mask M occur.  ^The integer return value from the callback is currently
   4046 ** ignored, though this may change in future releases.  Callback
   4047 ** implementations should return zero to ensure future compatibility.
   4048 **
   4049 ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
   4050 ** ^The T argument is one of the [SQLITE_TRACE]
   4051 ** constants to indicate why the callback was invoked.
   4052 ** ^The C argument is a copy of the context pointer.
   4053 ** The P and X arguments are pointers whose meanings depend on T.
   4054 **
   4055 ** The sqlite3_trace_v2() interface is intended to replace the legacy
   4056 ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
   4057 ** are deprecated.
   4058 */
   4059 SQLITE_API int sqlite3_trace_v2(
   4060   sqlite3*,
   4061   unsigned uMask,
   4062   int(*xCallback)(unsigned,void*,void*,void*),
   4063   void *pCtx
   4064 );
   4065 
   4066 /*
   4067 ** CAPI3REF: Query Progress Callbacks
   4068 ** METHOD: sqlite3
   4069 **
   4070 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
   4071 ** function X to be invoked periodically during long running calls to
   4072 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
   4073 ** database connection D.  An example use for this
   4074 ** interface is to keep a GUI updated during a large query.
   4075 **
   4076 ** ^The parameter P is passed through as the only parameter to the
   4077 ** callback function X.  ^The parameter N is the approximate number of
   4078 ** [virtual machine instructions] that are evaluated between successive
   4079 ** invocations of the callback X.  ^If N is less than one then the progress
   4080 ** handler is disabled.
   4081 **
   4082 ** ^Only a single progress handler may be defined at one time per
   4083 ** [database connection]; setting a new progress handler cancels the
   4084 ** old one.  ^Setting parameter X to NULL disables the progress handler.
   4085 ** ^The progress handler is also disabled by setting N to a value less
   4086 ** than 1.
   4087 **
   4088 ** ^If the progress callback returns non-zero, the operation is
   4089 ** interrupted.  This feature can be used to implement a
   4090 ** "Cancel" button on a GUI progress dialog box.
   4091 **
   4092 ** The progress handler callback must not do anything that will modify
   4093 ** the database connection that invoked the progress handler.
   4094 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   4095 ** database connections for the meaning of "modify" in this paragraph.
   4096 **
   4097 */
   4098 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
   4099 
   4100 /*
   4101 ** CAPI3REF: Opening A New Database Connection
   4102 ** CONSTRUCTOR: sqlite3
   4103 **
   4104 ** ^These routines open an SQLite database file as specified by the
   4105 ** filename argument. ^The filename argument is interpreted as UTF-8 for
   4106 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
   4107 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
   4108 ** returned in *ppDb, even if an error occurs.  The only exception is that
   4109 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
   4110 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
   4111 ** object.)^ ^(If the database is opened (and/or created) successfully, then
   4112 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
   4113 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
   4114 ** an English language description of the error following a failure of any
   4115 ** of the sqlite3_open() routines.
   4116 **
   4117 ** ^The default encoding will be UTF-8 for databases created using
   4118 ** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
   4119 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
   4120 **
   4121 ** Whether or not an error occurs when it is opened, resources
   4122 ** associated with the [database connection] handle should be released by
   4123 ** passing it to [sqlite3_close()] when it is no longer required.
   4124 **
   4125 ** The sqlite3_open_v2() interface works like sqlite3_open()
   4126 ** except that it accepts two additional parameters for additional control
   4127 ** over the new database connection.  ^(The flags parameter to
   4128 ** sqlite3_open_v2() can take one of
   4129 ** the following three values, optionally combined with the
   4130 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
   4131 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
   4132 **
   4133 ** <dl>
   4134 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
   4135 ** <dd>The database is opened in read-only mode.  If the database does not
   4136 ** already exist, an error is returned.</dd>)^
   4137 **
   4138 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
   4139 ** <dd>The database is opened for reading and writing if possible, or reading
   4140 ** only if the file is write protected by the operating system.  In either
   4141 ** case the database must already exist, otherwise an error is returned.</dd>)^
   4142 **
   4143 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
   4144 ** <dd>The database is opened for reading and writing, and is created if
   4145 ** it does not already exist. This is the behavior that is always used for
   4146 ** sqlite3_open() and sqlite3_open16().</dd>)^
   4147 ** </dl>
   4148 **
   4149 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
   4150 ** combinations shown above optionally combined with other
   4151 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
   4152 ** then the behavior is undefined.
   4153 **
   4154 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
   4155 ** opens in the multi-thread [threading mode] as long as the single-thread
   4156 ** mode has not been set at compile-time or start-time.  ^If the
   4157 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
   4158 ** in the serialized [threading mode] unless single-thread was
   4159 ** previously selected at compile-time or start-time.
   4160 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
   4161 ** eligible to use [shared cache mode], regardless of whether or not shared
   4162 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
   4163 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
   4164 ** participate in [shared cache mode] even if it is enabled.
   4165 **
   4166 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
   4167 ** [sqlite3_vfs] object that defines the operating system interface that
   4168 ** the new database connection should use.  ^If the fourth parameter is
   4169 ** a NULL pointer then the default [sqlite3_vfs] object is used.
   4170 **
   4171 ** ^If the filename is ":memory:", then a private, temporary in-memory database
   4172 ** is created for the connection.  ^This in-memory database will vanish when
   4173 ** the database connection is closed.  Future versions of SQLite might
   4174 ** make use of additional special filenames that begin with the ":" character.
   4175 ** It is recommended that when a database filename actually does begin with
   4176 ** a ":" character you should prefix the filename with a pathname such as
   4177 ** "./" to avoid ambiguity.
   4178 **
   4179 ** ^If the filename is an empty string, then a private, temporary
   4180 ** on-disk database will be created.  ^This private database will be
   4181 ** automatically deleted as soon as the database connection is closed.
   4182 **
   4183 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
   4184 **
   4185 ** ^If [URI filename] interpretation is enabled, and the filename argument
   4186 ** begins with "file:", then the filename is interpreted as a URI. ^URI
   4187 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
   4188 ** set in the third argument to sqlite3_open_v2(), or if it has
   4189 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
   4190 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
   4191 ** URI filename interpretation is turned off
   4192 ** by default, but future releases of SQLite might enable URI filename
   4193 ** interpretation by default.  See "[URI filenames]" for additional
   4194 ** information.
   4195 **
   4196 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
   4197 ** authority, then it must be either an empty string or the string
   4198 ** "localhost". ^If the authority is not an empty string or "localhost", an
   4199 ** error is returned to the caller. ^The fragment component of a URI, if
   4200 ** present, is ignored.
   4201 **
   4202 ** ^SQLite uses the path component of the URI as the name of the disk file
   4203 ** which contains the database. ^If the path begins with a '/' character,
   4204 ** then it is interpreted as an absolute path. ^If the path does not begin
   4205 ** with a '/' (meaning that the authority section is omitted from the URI)
   4206 ** then the path is interpreted as a relative path.
   4207 ** ^(On windows, the first component of an absolute path
   4208 ** is a drive specification (e.g. "C:").)^
   4209 **
   4210 ** [[core URI query parameters]]
   4211 ** The query component of a URI may contain parameters that are interpreted
   4212 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
   4213 ** SQLite and its built-in [VFSes] interpret the
   4214 ** following query parameters:
   4215 **
   4216 ** <ul>
   4217 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
   4218 **     a VFS object that provides the operating system interface that should
   4219 **     be used to access the database file on disk. ^If this option is set to
   4220 **     an empty string the default VFS object is used. ^Specifying an unknown
   4221 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
   4222 **     present, then the VFS specified by the option takes precedence over
   4223 **     the value passed as the fourth parameter to sqlite3_open_v2().
   4224 **
   4225 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
   4226 **     "rwc", or "memory". Attempting to set it to any other value is
   4227 **     an error)^.
   4228 **     ^If "ro" is specified, then the database is opened for read-only
   4229 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
   4230 **     third argument to sqlite3_open_v2(). ^If the mode option is set to
   4231 **     "rw", then the database is opened for read-write (but not create)
   4232 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
   4233 **     been set. ^Value "rwc" is equivalent to setting both
   4234 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
   4235 **     set to "memory" then a pure [in-memory database] that never reads
   4236 **     or writes from disk is used. ^It is an error to specify a value for
   4237 **     the mode parameter that is less restrictive than that specified by
   4238 **     the flags passed in the third parameter to sqlite3_open_v2().
   4239 **
   4240 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
   4241 **     "private". ^Setting it to "shared" is equivalent to setting the
   4242 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
   4243 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
   4244 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
   4245 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
   4246 **     a URI filename, its value overrides any behavior requested by setting
   4247 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
   4248 **
   4249 **  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
   4250 **     [powersafe overwrite] property does or does not apply to the
   4251 **     storage media on which the database file resides.
   4252 **
   4253 **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
   4254 **     which if set disables file locking in rollback journal modes.  This
   4255 **     is useful for accessing a database on a filesystem that does not
   4256 **     support locking.  Caution:  Database corruption might result if two
   4257 **     or more processes write to the same database and any one of those
   4258 **     processes uses nolock=1.
   4259 **
   4260 **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
   4261 **     parameter that indicates that the database file is stored on
   4262 **     read-only media.  ^When immutable is set, SQLite assumes that the
   4263 **     database file cannot be changed, even by a process with higher
   4264 **     privilege, and so the database is opened read-only and all locking
   4265 **     and change detection is disabled.  Caution: Setting the immutable
   4266 **     property on a database file that does in fact change can result
   4267 **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
   4268 **     See also: [SQLITE_IOCAP_IMMUTABLE].
   4269 **
   4270 ** </ul>
   4271 **
   4272 ** ^Specifying an unknown parameter in the query component of a URI is not an
   4273 ** error.  Future versions of SQLite might understand additional query
   4274 ** parameters.  See "[query parameters with special meaning to SQLite]" for
   4275 ** additional information.
   4276 **
   4277 ** [[URI filename examples]] <h3>URI filename examples</h3>
   4278 **
   4279 ** <table border="1" align=center cellpadding=5>
   4280 ** <tr><th> URI filenames <th> Results
   4281 ** <tr><td> file:data.db <td>
   4282 **          Open the file "data.db" in the current directory.
   4283 ** <tr><td> file:/home/fred/data.db<br>
   4284 **          file:///home/fred/data.db <br>
   4285 **          file://localhost/home/fred/data.db <br> <td>
   4286 **          Open the database file "/home/fred/data.db".
   4287 ** <tr><td> file://darkstar/home/fred/data.db <td>
   4288 **          An error. "darkstar" is not a recognized authority.
   4289 ** <tr><td style="white-space:nowrap">
   4290 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
   4291 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
   4292 **          C:. Note that the %20 escaping in this example is not strictly
   4293 **          necessary - space characters can be used literally
   4294 **          in URI filenames.
   4295 ** <tr><td> file:data.db?mode=ro&cache=private <td>
   4296 **          Open file "data.db" in the current directory for read-only access.
   4297 **          Regardless of whether or not shared-cache mode is enabled by
   4298 **          default, use a private cache.
   4299 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
   4300 **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
   4301 **          that uses dot-files in place of posix advisory locking.
   4302 ** <tr><td> file:data.db?mode=readonly <td>
   4303 **          An error. "readonly" is not a valid option for the "mode" parameter.
   4304 ** </table>
   4305 **
   4306 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
   4307 ** query components of a URI. A hexadecimal escape sequence consists of a
   4308 ** percent sign - "%" - followed by exactly two hexadecimal digits
   4309 ** specifying an octet value. ^Before the path or query components of a
   4310 ** URI filename are interpreted, they are encoded using UTF-8 and all
   4311 ** hexadecimal escape sequences replaced by a single byte containing the
   4312 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
   4313 ** the results are undefined.
   4314 **
   4315 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
   4316 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
   4317 ** codepage is currently defined.  Filenames containing international
   4318 ** characters must be converted to UTF-8 prior to passing them into
   4319 ** sqlite3_open() or sqlite3_open_v2().
   4320 **
   4321 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
   4322 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
   4323 ** features that require the use of temporary files may fail.
   4324 **
   4325 ** See also: [sqlite3_temp_directory]
   4326 */
   4327 SQLITE_API int sqlite3_open(
   4328   const char *filename,   /* Database filename (UTF-8) */
   4329   sqlite3 **ppDb          /* OUT: SQLite db handle */
   4330 );
   4331 SQLITE_API int sqlite3_open16(
   4332   const void *filename,   /* Database filename (UTF-16) */
   4333   sqlite3 **ppDb          /* OUT: SQLite db handle */
   4334 );
   4335 SQLITE_API int sqlite3_open_v2(
   4336   const char *filename,   /* Database filename (UTF-8) */
   4337   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   4338   int flags,              /* Flags */
   4339   const char *zVfs        /* Name of VFS module to use */
   4340 );
   4341 
   4342 /*
   4343 ** CAPI3REF: Obtain Values For URI Parameters
   4344 **
   4345 ** These are utility routines, useful to VFS implementations, that check
   4346 ** to see if a database file was a URI that contained a specific query
   4347 ** parameter, and if so obtains the value of that query parameter.
   4348 **
   4349 ** If F is the database filename pointer passed into the xOpen() method of
   4350 ** a VFS implementation when the flags parameter to xOpen() has one or
   4351 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
   4352 ** P is the name of the query parameter, then
   4353 ** sqlite3_uri_parameter(F,P) returns the value of the P
   4354 ** parameter if it exists or a NULL pointer if P does not appear as a
   4355 ** query parameter on F.  If P is a query parameter of F
   4356 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
   4357 ** a pointer to an empty string.
   4358 **
   4359 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
   4360 ** parameter and returns true (1) or false (0) according to the value
   4361 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
   4362 ** value of query parameter P is one of "yes", "true", or "on" in any
   4363 ** case or if the value begins with a non-zero number.  The
   4364 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
   4365 ** query parameter P is one of "no", "false", or "off" in any case or
   4366 ** if the value begins with a numeric zero.  If P is not a query
   4367 ** parameter on F or if the value of P is does not match any of the
   4368 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
   4369 **
   4370 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
   4371 ** 64-bit signed integer and returns that integer, or D if P does not
   4372 ** exist.  If the value of P is something other than an integer, then
   4373 ** zero is returned.
   4374 **
   4375 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
   4376 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
   4377 ** is not a database file pathname pointer that SQLite passed into the xOpen
   4378 ** VFS method, then the behavior of this routine is undefined and probably
   4379 ** undesirable.
   4380 */
   4381 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
   4382 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
   4383 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
   4384 
   4385 
   4386 /*
   4387 ** CAPI3REF: Error Codes And Messages
   4388 ** METHOD: sqlite3
   4389 **
   4390 ** ^If the most recent sqlite3_* API call associated with
   4391 ** [database connection] D failed, then the sqlite3_errcode(D) interface
   4392 ** returns the numeric [result code] or [extended result code] for that
   4393 ** API call.
   4394 ** If the most recent API call was successful,
   4395 ** then the return value from sqlite3_errcode() is undefined.
   4396 ** ^The sqlite3_extended_errcode()
   4397 ** interface is the same except that it always returns the
   4398 ** [extended result code] even when extended result codes are
   4399 ** disabled.
   4400 **
   4401 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
   4402 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
   4403 ** ^(Memory to hold the error message string is managed internally.
   4404 ** The application does not need to worry about freeing the result.
   4405 ** However, the error string might be overwritten or deallocated by
   4406 ** subsequent calls to other SQLite interface functions.)^
   4407 **
   4408 ** ^The sqlite3_errstr() interface returns the English-language text
   4409 ** that describes the [result code], as UTF-8.
   4410 ** ^(Memory to hold the error message string is managed internally
   4411 ** and must not be freed by the application)^.
   4412 **
   4413 ** When the serialized [threading mode] is in use, it might be the
   4414 ** case that a second error occurs on a separate thread in between
   4415 ** the time of the first error and the call to these interfaces.
   4416 ** When that happens, the second error will be reported since these
   4417 ** interfaces always report the most recent result.  To avoid
   4418 ** this, each thread can obtain exclusive use of the [database connection] D
   4419 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
   4420 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
   4421 ** all calls to the interfaces listed here are completed.
   4422 **
   4423 ** If an interface fails with SQLITE_MISUSE, that means the interface
   4424 ** was invoked incorrectly by the application.  In that case, the
   4425 ** error code and message may or may not be set.
   4426 */
   4427 SQLITE_API int sqlite3_errcode(sqlite3 *db);
   4428 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
   4429 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
   4430 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
   4431 SQLITE_API const char *sqlite3_errstr(int);
   4432 
   4433 /*
   4434 ** CAPI3REF: Prepared Statement Object
   4435 ** KEYWORDS: {prepared statement} {prepared statements}
   4436 **
   4437 ** An instance of this object represents a single SQL statement that
   4438 ** has been compiled into binary form and is ready to be evaluated.
   4439 **
   4440 ** Think of each SQL statement as a separate computer program.  The
   4441 ** original SQL text is source code.  A prepared statement object
   4442 ** is the compiled object code.  All SQL must be converted into a
   4443 ** prepared statement before it can be run.
   4444 **
   4445 ** The life-cycle of a prepared statement object usually goes like this:
   4446 **
   4447 ** <ol>
   4448 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
   4449 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
   4450 **      interfaces.
   4451 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
   4452 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
   4453 **      to step 2.  Do this zero or more times.
   4454 ** <li> Destroy the object using [sqlite3_finalize()].
   4455 ** </ol>
   4456 */
   4457 typedef struct sqlite3_stmt sqlite3_stmt;
   4458 
   4459 /*
   4460 ** CAPI3REF: Run-time Limits
   4461 ** METHOD: sqlite3
   4462 **
   4463 ** ^(This interface allows the size of various constructs to be limited
   4464 ** on a connection by connection basis.  The first parameter is the
   4465 ** [database connection] whose limit is to be set or queried.  The
   4466 ** second parameter is one of the [limit categories] that define a
   4467 ** class of constructs to be size limited.  The third parameter is the
   4468 ** new limit for that construct.)^
   4469 **
   4470 ** ^If the new limit is a negative number, the limit is unchanged.
   4471 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
   4472 ** [limits | hard upper bound]
   4473 ** set at compile-time by a C preprocessor macro called
   4474 ** [limits | SQLITE_MAX_<i>NAME</i>].
   4475 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
   4476 ** ^Attempts to increase a limit above its hard upper bound are
   4477 ** silently truncated to the hard upper bound.
   4478 **
   4479 ** ^Regardless of whether or not the limit was changed, the
   4480 ** [sqlite3_limit()] interface returns the prior value of the limit.
   4481 ** ^Hence, to find the current value of a limit without changing it,
   4482 ** simply invoke this interface with the third parameter set to -1.
   4483 **
   4484 ** Run-time limits are intended for use in applications that manage
   4485 ** both their own internal database and also databases that are controlled
   4486 ** by untrusted external sources.  An example application might be a
   4487 ** web browser that has its own databases for storing history and
   4488 ** separate databases controlled by JavaScript applications downloaded
   4489 ** off the Internet.  The internal databases can be given the
   4490 ** large, default limits.  Databases managed by external sources can
   4491 ** be given much smaller limits designed to prevent a denial of service
   4492 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
   4493 ** interface to further control untrusted SQL.  The size of the database
   4494 ** created by an untrusted script can be contained using the
   4495 ** [max_page_count] [PRAGMA].
   4496 **
   4497 ** New run-time limit categories may be added in future releases.
   4498 */
   4499 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
   4500 
   4501 /*
   4502 ** CAPI3REF: Run-Time Limit Categories
   4503 ** KEYWORDS: {limit category} {*limit categories}
   4504 **
   4505 ** These constants define various performance limits
   4506 ** that can be lowered at run-time using [sqlite3_limit()].
   4507 ** The synopsis of the meanings of the various limits is shown below.
   4508 ** Additional information is available at [limits | Limits in SQLite].
   4509 **
   4510 ** <dl>
   4511 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
   4512 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
   4513 **
   4514 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
   4515 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
   4516 **
   4517 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
   4518 ** <dd>The maximum number of columns in a table definition or in the
   4519 ** result set of a [SELECT] or the maximum number of columns in an index
   4520 ** or in an ORDER BY or GROUP BY clause.</dd>)^
   4521 **
   4522 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
   4523 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
   4524 **
   4525 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
   4526 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
   4527 **
   4528 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
   4529 ** <dd>The maximum number of instructions in a virtual machine program
   4530 ** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or
   4531 ** the equivalent tries to allocate space for more than this many opcodes
   4532 ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
   4533 **
   4534 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
   4535 ** <dd>The maximum number of arguments on a function.</dd>)^
   4536 **
   4537 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
   4538 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
   4539 **
   4540 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
   4541 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
   4542 ** <dd>The maximum length of the pattern argument to the [LIKE] or
   4543 ** [GLOB] operators.</dd>)^
   4544 **
   4545 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
   4546 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
   4547 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
   4548 **
   4549 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
   4550 ** <dd>The maximum depth of recursion for triggers.</dd>)^
   4551 **
   4552 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
   4553 ** <dd>The maximum number of auxiliary worker threads that a single
   4554 ** [prepared statement] may start.</dd>)^
   4555 ** </dl>
   4556 */
   4557 #define SQLITE_LIMIT_LENGTH                    0
   4558 #define SQLITE_LIMIT_SQL_LENGTH                1
   4559 #define SQLITE_LIMIT_COLUMN                    2
   4560 #define SQLITE_LIMIT_EXPR_DEPTH                3
   4561 #define SQLITE_LIMIT_COMPOUND_SELECT           4
   4562 #define SQLITE_LIMIT_VDBE_OP                   5
   4563 #define SQLITE_LIMIT_FUNCTION_ARG              6
   4564 #define SQLITE_LIMIT_ATTACHED                  7
   4565 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
   4566 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
   4567 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
   4568 #define SQLITE_LIMIT_WORKER_THREADS           11
   4569 
   4570 /*
   4571 ** CAPI3REF: Prepare Flags
   4572 **
   4573 ** These constants define various flags that can be passed into
   4574 ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
   4575 ** [sqlite3_prepare16_v3()] interfaces.
   4576 **
   4577 ** New flags may be added in future releases of SQLite.
   4578 **
   4579 ** <dl>
   4580 ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
   4581 ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
   4582 ** that the prepared statement will be retained for a long time and
   4583 ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
   4584 ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
   4585 ** be used just once or at most a few times and then destroyed using
   4586 ** [sqlite3_finalize()] relatively soon. The current implementation acts
   4587 ** on this hint by avoiding the use of [lookaside memory] so as not to
   4588 ** deplete the limited store of lookaside memory. Future versions of
   4589 ** SQLite may act on this hint differently.
   4590 ** </dl>
   4591 */
   4592 #define SQLITE_PREPARE_PERSISTENT              0x01
   4593 
   4594 /*
   4595 ** CAPI3REF: Compiling An SQL Statement
   4596 ** KEYWORDS: {SQL statement compiler}
   4597 ** METHOD: sqlite3
   4598 ** CONSTRUCTOR: sqlite3_stmt
   4599 **
   4600 ** To execute an SQL statement, it must first be compiled into a byte-code
   4601 ** program using one of these routines.  Or, in other words, these routines
   4602 ** are constructors for the [prepared statement] object.
   4603 **
   4604 ** The preferred routine to use is [sqlite3_prepare_v2()].  The
   4605 ** [sqlite3_prepare()] interface is legacy and should be avoided.
   4606 ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
   4607 ** for special purposes.
   4608 **
   4609 ** The use of the UTF-8 interfaces is preferred, as SQLite currently
   4610 ** does all parsing using UTF-8.  The UTF-16 interfaces are provided
   4611 ** as a convenience.  The UTF-16 interfaces work by converting the
   4612 ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
   4613 **
   4614 ** The first argument, "db", is a [database connection] obtained from a
   4615 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
   4616 ** [sqlite3_open16()].  The database connection must not have been closed.
   4617 **
   4618 ** The second argument, "zSql", is the statement to be compiled, encoded
   4619 ** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),
   4620 ** and sqlite3_prepare_v3()
   4621 ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
   4622 ** and sqlite3_prepare16_v3() use UTF-16.
   4623 **
   4624 ** ^If the nByte argument is negative, then zSql is read up to the
   4625 ** first zero terminator. ^If nByte is positive, then it is the
   4626 ** number of bytes read from zSql.  ^If nByte is zero, then no prepared
   4627 ** statement is generated.
   4628 ** If the caller knows that the supplied string is nul-terminated, then
   4629 ** there is a small performance advantage to passing an nByte parameter that
   4630 ** is the number of bytes in the input string <i>including</i>
   4631 ** the nul-terminator.
   4632 **
   4633 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
   4634 ** past the end of the first SQL statement in zSql.  These routines only
   4635 ** compile the first statement in zSql, so *pzTail is left pointing to
   4636 ** what remains uncompiled.
   4637 **
   4638 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
   4639 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
   4640 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
   4641 ** string or a comment) then *ppStmt is set to NULL.
   4642 ** The calling procedure is responsible for deleting the compiled
   4643 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
   4644 ** ppStmt may not be NULL.
   4645 **
   4646 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
   4647 ** otherwise an [error code] is returned.
   4648 **
   4649 ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
   4650 ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
   4651 ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
   4652 ** are retained for backwards compatibility, but their use is discouraged.
   4653 ** ^In the "vX" interfaces, the prepared statement
   4654 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
   4655 ** original SQL text. This causes the [sqlite3_step()] interface to
   4656 ** behave differently in three ways:
   4657 **
   4658 ** <ol>
   4659 ** <li>
   4660 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
   4661 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
   4662 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
   4663 ** retries will occur before sqlite3_step() gives up and returns an error.
   4664 ** </li>
   4665 **
   4666 ** <li>
   4667 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
   4668 ** [error codes] or [extended error codes].  ^The legacy behavior was that
   4669 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
   4670 ** and the application would have to make a second call to [sqlite3_reset()]
   4671 ** in order to find the underlying cause of the problem. With the "v2" prepare
   4672 ** interfaces, the underlying reason for the error is returned immediately.
   4673 ** </li>
   4674 **
   4675 ** <li>
   4676 ** ^If the specific value bound to [parameter | host parameter] in the
   4677 ** WHERE clause might influence the choice of query plan for a statement,
   4678 ** then the statement will be automatically recompiled, as if there had been
   4679 ** a schema change, on the first  [sqlite3_step()] call following any change
   4680 ** to the [sqlite3_bind_text | bindings] of that [parameter].
   4681 ** ^The specific value of WHERE-clause [parameter] might influence the
   4682 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
   4683 ** or [GLOB] operator or if the parameter is compared to an indexed column
   4684 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
   4685 ** </li>
   4686 **
   4687 ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
   4688 ** the extra prepFlags parameter, which is a bit array consisting of zero or
   4689 ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The
   4690 ** sqlite3_prepare_v2() interface works exactly the same as
   4691 ** sqlite3_prepare_v3() with a zero prepFlags parameter.
   4692 ** </ol>
   4693 */
   4694 SQLITE_API int sqlite3_prepare(
   4695   sqlite3 *db,            /* Database handle */
   4696   const char *zSql,       /* SQL statement, UTF-8 encoded */
   4697   int nByte,              /* Maximum length of zSql in bytes. */
   4698   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   4699   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   4700 );
   4701 SQLITE_API int sqlite3_prepare_v2(
   4702   sqlite3 *db,            /* Database handle */
   4703   const char *zSql,       /* SQL statement, UTF-8 encoded */
   4704   int nByte,              /* Maximum length of zSql in bytes. */
   4705   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   4706   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   4707 );
   4708 SQLITE_API int sqlite3_prepare_v3(
   4709   sqlite3 *db,            /* Database handle */
   4710   const char *zSql,       /* SQL statement, UTF-8 encoded */
   4711   int nByte,              /* Maximum length of zSql in bytes. */
   4712   unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
   4713   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   4714   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   4715 );
   4716 SQLITE_API int sqlite3_prepare16(
   4717   sqlite3 *db,            /* Database handle */
   4718   const void *zSql,       /* SQL statement, UTF-16 encoded */
   4719   int nByte,              /* Maximum length of zSql in bytes. */
   4720   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   4721   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   4722 );
   4723 SQLITE_API int sqlite3_prepare16_v2(
   4724   sqlite3 *db,            /* Database handle */
   4725   const void *zSql,       /* SQL statement, UTF-16 encoded */
   4726   int nByte,              /* Maximum length of zSql in bytes. */
   4727   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   4728   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   4729 );
   4730 SQLITE_API int sqlite3_prepare16_v3(
   4731   sqlite3 *db,            /* Database handle */
   4732   const void *zSql,       /* SQL statement, UTF-16 encoded */
   4733   int nByte,              /* Maximum length of zSql in bytes. */
   4734   unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
   4735   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   4736   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   4737 );
   4738 
   4739 /*
   4740 ** CAPI3REF: Retrieving Statement SQL
   4741 ** METHOD: sqlite3_stmt
   4742 **
   4743 ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
   4744 ** SQL text used to create [prepared statement] P if P was
   4745 ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
   4746 ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
   4747 ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
   4748 ** string containing the SQL text of prepared statement P with
   4749 ** [bound parameters] expanded.
   4750 **
   4751 ** ^(For example, if a prepared statement is created using the SQL
   4752 ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
   4753 ** and parameter :xyz is unbound, then sqlite3_sql() will return
   4754 ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
   4755 ** will return "SELECT 2345,NULL".)^
   4756 **
   4757 ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
   4758 ** is available to hold the result, or if the result would exceed the
   4759 ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
   4760 **
   4761 ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
   4762 ** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
   4763 ** option causes sqlite3_expanded_sql() to always return NULL.
   4764 **
   4765 ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
   4766 ** automatically freed when the prepared statement is finalized.
   4767 ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
   4768 ** is obtained from [sqlite3_malloc()] and must be free by the application
   4769 ** by passing it to [sqlite3_free()].
   4770 */
   4771 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
   4772 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
   4773 
   4774 /*
   4775 ** CAPI3REF: Determine If An SQL Statement Writes The Database
   4776 ** METHOD: sqlite3_stmt
   4777 **
   4778 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
   4779 ** and only if the [prepared statement] X makes no direct changes to
   4780 ** the content of the database file.
   4781 **
   4782 ** Note that [application-defined SQL functions] or
   4783 ** [virtual tables] might change the database indirectly as a side effect.
   4784 ** ^(For example, if an application defines a function "eval()" that
   4785 ** calls [sqlite3_exec()], then the following SQL statement would
   4786 ** change the database file through side-effects:
   4787 **
   4788 ** <blockquote><pre>
   4789 **    SELECT eval('DELETE FROM t1') FROM t2;
   4790 ** </pre></blockquote>
   4791 **
   4792 ** But because the [SELECT] statement does not change the database file
   4793 ** directly, sqlite3_stmt_readonly() would still return true.)^
   4794 **
   4795 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
   4796 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
   4797 ** since the statements themselves do not actually modify the database but
   4798 ** rather they control the timing of when other statements modify the
   4799 ** database.  ^The [ATTACH] and [DETACH] statements also cause
   4800 ** sqlite3_stmt_readonly() to return true since, while those statements
   4801 ** change the configuration of a database connection, they do not make
   4802 ** changes to the content of the database files on disk.
   4803 ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
   4804 ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
   4805 ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
   4806 ** sqlite3_stmt_readonly() returns false for those commands.
   4807 */
   4808 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
   4809 
   4810 /*
   4811 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
   4812 ** METHOD: sqlite3_stmt
   4813 **
   4814 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
   4815 ** [prepared statement] S has been stepped at least once using
   4816 ** [sqlite3_step(S)] but has neither run to completion (returned
   4817 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
   4818 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
   4819 ** interface returns false if S is a NULL pointer.  If S is not a
   4820 ** NULL pointer and is not a pointer to a valid [prepared statement]
   4821 ** object, then the behavior is undefined and probably undesirable.
   4822 **
   4823 ** This interface can be used in combination [sqlite3_next_stmt()]
   4824 ** to locate all prepared statements associated with a database
   4825 ** connection that are in need of being reset.  This can be used,
   4826 ** for example, in diagnostic routines to search for prepared
   4827 ** statements that are holding a transaction open.
   4828 */
   4829 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
   4830 
   4831 /*
   4832 ** CAPI3REF: Dynamically Typed Value Object
   4833 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
   4834 **
   4835 ** SQLite uses the sqlite3_value object to represent all values
   4836 ** that can be stored in a database table. SQLite uses dynamic typing
   4837 ** for the values it stores.  ^Values stored in sqlite3_value objects
   4838 ** can be integers, floating point values, strings, BLOBs, or NULL.
   4839 **
   4840 ** An sqlite3_value object may be either "protected" or "unprotected".
   4841 ** Some interfaces require a protected sqlite3_value.  Other interfaces
   4842 ** will accept either a protected or an unprotected sqlite3_value.
   4843 ** Every interface that accepts sqlite3_value arguments specifies
   4844 ** whether or not it requires a protected sqlite3_value.  The
   4845 ** [sqlite3_value_dup()] interface can be used to construct a new
   4846 ** protected sqlite3_value from an unprotected sqlite3_value.
   4847 **
   4848 ** The terms "protected" and "unprotected" refer to whether or not
   4849 ** a mutex is held.  An internal mutex is held for a protected
   4850 ** sqlite3_value object but no mutex is held for an unprotected
   4851 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
   4852 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
   4853 ** or if SQLite is run in one of reduced mutex modes
   4854 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
   4855 ** then there is no distinction between protected and unprotected
   4856 ** sqlite3_value objects and they can be used interchangeably.  However,
   4857 ** for maximum code portability it is recommended that applications
   4858 ** still make the distinction between protected and unprotected
   4859 ** sqlite3_value objects even when not strictly required.
   4860 **
   4861 ** ^The sqlite3_value objects that are passed as parameters into the
   4862 ** implementation of [application-defined SQL functions] are protected.
   4863 ** ^The sqlite3_value object returned by
   4864 ** [sqlite3_column_value()] is unprotected.
   4865 ** Unprotected sqlite3_value objects may only be used as arguments
   4866 ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
   4867 ** [sqlite3_value_dup()].
   4868 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
   4869 ** interfaces require protected sqlite3_value objects.
   4870 */
   4871 typedef struct sqlite3_value sqlite3_value;
   4872 
   4873 /*
   4874 ** CAPI3REF: SQL Function Context Object
   4875 **
   4876 ** The context in which an SQL function executes is stored in an
   4877 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
   4878 ** is always first parameter to [application-defined SQL functions].
   4879 ** The application-defined SQL function implementation will pass this
   4880 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
   4881 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
   4882 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
   4883 ** and/or [sqlite3_set_auxdata()].
   4884 */
   4885 typedef struct sqlite3_context sqlite3_context;
   4886 
   4887 /*
   4888 ** CAPI3REF: Binding Values To Prepared Statements
   4889 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
   4890 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
   4891 ** METHOD: sqlite3_stmt
   4892 **
   4893 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
   4894 ** literals may be replaced by a [parameter] that matches one of following
   4895 ** templates:
   4896 **
   4897 ** <ul>
   4898 ** <li>  ?
   4899 ** <li>  ?NNN
   4900 ** <li>  :VVV
   4901 ** <li>  @VVV
   4902 ** <li>  $VVV
   4903 ** </ul>
   4904 **
   4905 ** In the templates above, NNN represents an integer literal,
   4906 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
   4907 ** parameters (also called "host parameter names" or "SQL parameters")
   4908 ** can be set using the sqlite3_bind_*() routines defined here.
   4909 **
   4910 ** ^The first argument to the sqlite3_bind_*() routines is always
   4911 ** a pointer to the [sqlite3_stmt] object returned from
   4912 ** [sqlite3_prepare_v2()] or its variants.
   4913 **
   4914 ** ^The second argument is the index of the SQL parameter to be set.
   4915 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
   4916 ** SQL parameter is used more than once, second and subsequent
   4917 ** occurrences have the same index as the first occurrence.
   4918 ** ^The index for named parameters can be looked up using the
   4919 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
   4920 ** for "?NNN" parameters is the value of NNN.
   4921 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
   4922 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
   4923 **
   4924 ** ^The third argument is the value to bind to the parameter.
   4925 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
   4926 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
   4927 ** is ignored and the end result is the same as sqlite3_bind_null().
   4928 **
   4929 ** ^(In those routines that have a fourth argument, its value is the
   4930 ** number of bytes in the parameter.  To be clear: the value is the
   4931 ** number of <u>bytes</u> in the value, not the number of characters.)^
   4932 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
   4933 ** is negative, then the length of the string is
   4934 ** the number of bytes up to the first zero terminator.
   4935 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
   4936 ** the behavior is undefined.
   4937 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
   4938 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
   4939 ** that parameter must be the byte offset
   4940 ** where the NUL terminator would occur assuming the string were NUL
   4941 ** terminated.  If any NUL characters occur at byte offsets less than
   4942 ** the value of the fourth parameter then the resulting string value will
   4943 ** contain embedded NULs.  The result of expressions involving strings
   4944 ** with embedded NULs is undefined.
   4945 **
   4946 ** ^The fifth argument to the BLOB and string binding interfaces
   4947 ** is a destructor used to dispose of the BLOB or
   4948 ** string after SQLite has finished with it.  ^The destructor is called
   4949 ** to dispose of the BLOB or string even if the call to bind API fails.
   4950 ** ^If the fifth argument is
   4951 ** the special value [SQLITE_STATIC], then SQLite assumes that the
   4952 ** information is in static, unmanaged space and does not need to be freed.
   4953 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
   4954 ** SQLite makes its own private copy of the data immediately, before
   4955 ** the sqlite3_bind_*() routine returns.
   4956 **
   4957 ** ^The sixth argument to sqlite3_bind_text64() must be one of
   4958 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
   4959 ** to specify the encoding of the text in the third parameter.  If
   4960 ** the sixth argument to sqlite3_bind_text64() is not one of the
   4961 ** allowed values shown above, or if the text encoding is different
   4962 ** from the encoding specified by the sixth parameter, then the behavior
   4963 ** is undefined.
   4964 **
   4965 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
   4966 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
   4967 ** (just an integer to hold its size) while it is being processed.
   4968 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
   4969 ** content is later written using
   4970 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
   4971 ** ^A negative value for the zeroblob results in a zero-length BLOB.
   4972 **
   4973 ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
   4974 ** [prepared statement] S to have an SQL value of NULL, but to also be
   4975 ** associated with the pointer P of type T.  ^D is either a NULL pointer or
   4976 ** a pointer to a destructor function for P. ^SQLite will invoke the
   4977 ** destructor D with a single argument of P when it is finished using
   4978 ** P.  The T parameter should be a static string, preferably a string
   4979 ** literal. The sqlite3_bind_pointer() routine is part of the
   4980 ** [pointer passing interface] added for SQLite 3.20.0.
   4981 **
   4982 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
   4983 ** for the [prepared statement] or with a prepared statement for which
   4984 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
   4985 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
   4986 ** routine is passed a [prepared statement] that has been finalized, the
   4987 ** result is undefined and probably harmful.
   4988 **
   4989 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
   4990 ** ^Unbound parameters are interpreted as NULL.
   4991 **
   4992 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
   4993 ** [error code] if anything goes wrong.
   4994 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
   4995 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
   4996 ** [SQLITE_MAX_LENGTH].
   4997 ** ^[SQLITE_RANGE] is returned if the parameter
   4998 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
   4999 **
   5000 ** See also: [sqlite3_bind_parameter_count()],
   5001 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
   5002 */
   5003 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
   5004 SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
   5005                         void(*)(void*));
   5006 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
   5007 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
   5008 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
   5009 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
   5010 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
   5011 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
   5012 SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
   5013                          void(*)(void*), unsigned char encoding);
   5014 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
   5015 SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
   5016 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
   5017 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
   5018 
   5019 /*
   5020 ** CAPI3REF: Number Of SQL Parameters
   5021 ** METHOD: sqlite3_stmt
   5022 **
   5023 ** ^This routine can be used to find the number of [SQL parameters]
   5024 ** in a [prepared statement].  SQL parameters are tokens of the
   5025 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
   5026 ** placeholders for values that are [sqlite3_bind_blob | bound]
   5027 ** to the parameters at a later time.
   5028 **
   5029 ** ^(This routine actually returns the index of the largest (rightmost)
   5030 ** parameter. For all forms except ?NNN, this will correspond to the
   5031 ** number of unique parameters.  If parameters of the ?NNN form are used,
   5032 ** there may be gaps in the list.)^
   5033 **
   5034 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   5035 ** [sqlite3_bind_parameter_name()], and
   5036 ** [sqlite3_bind_parameter_index()].
   5037 */
   5038 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
   5039 
   5040 /*
   5041 ** CAPI3REF: Name Of A Host Parameter
   5042 ** METHOD: sqlite3_stmt
   5043 **
   5044 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
   5045 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
   5046 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
   5047 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
   5048 ** respectively.
   5049 ** In other words, the initial ":" or "$" or "@" or "?"
   5050 ** is included as part of the name.)^
   5051 ** ^Parameters of the form "?" without a following integer have no name
   5052 ** and are referred to as "nameless" or "anonymous parameters".
   5053 **
   5054 ** ^The first host parameter has an index of 1, not 0.
   5055 **
   5056 ** ^If the value N is out of range or if the N-th parameter is
   5057 ** nameless, then NULL is returned.  ^The returned string is
   5058 ** always in UTF-8 encoding even if the named parameter was
   5059 ** originally specified as UTF-16 in [sqlite3_prepare16()],
   5060 ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
   5061 **
   5062 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   5063 ** [sqlite3_bind_parameter_count()], and
   5064 ** [sqlite3_bind_parameter_index()].
   5065 */
   5066 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
   5067 
   5068 /*
   5069 ** CAPI3REF: Index Of A Parameter With A Given Name
   5070 ** METHOD: sqlite3_stmt
   5071 **
   5072 ** ^Return the index of an SQL parameter given its name.  ^The
   5073 ** index value returned is suitable for use as the second
   5074 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
   5075 ** is returned if no matching parameter is found.  ^The parameter
   5076 ** name must be given in UTF-8 even if the original statement
   5077 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
   5078 ** [sqlite3_prepare16_v3()].
   5079 **
   5080 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   5081 ** [sqlite3_bind_parameter_count()], and
   5082 ** [sqlite3_bind_parameter_name()].
   5083 */
   5084 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
   5085 
   5086 /*
   5087 ** CAPI3REF: Reset All Bindings On A Prepared Statement
   5088 ** METHOD: sqlite3_stmt
   5089 **
   5090 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
   5091 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
   5092 ** ^Use this routine to reset all host parameters to NULL.
   5093 */
   5094 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
   5095 
   5096 /*
   5097 ** CAPI3REF: Number Of Columns In A Result Set
   5098 ** METHOD: sqlite3_stmt
   5099 **
   5100 ** ^Return the number of columns in the result set returned by the
   5101 ** [prepared statement]. ^If this routine returns 0, that means the
   5102 ** [prepared statement] returns no data (for example an [UPDATE]).
   5103 ** ^However, just because this routine returns a positive number does not
   5104 ** mean that one or more rows of data will be returned.  ^A SELECT statement
   5105 ** will always have a positive sqlite3_column_count() but depending on the
   5106 ** WHERE clause constraints and the table content, it might return no rows.
   5107 **
   5108 ** See also: [sqlite3_data_count()]
   5109 */
   5110 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
   5111 
   5112 /*
   5113 ** CAPI3REF: Column Names In A Result Set
   5114 ** METHOD: sqlite3_stmt
   5115 **
   5116 ** ^These routines return the name assigned to a particular column
   5117 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
   5118 ** interface returns a pointer to a zero-terminated UTF-8 string
   5119 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
   5120 ** UTF-16 string.  ^The first parameter is the [prepared statement]
   5121 ** that implements the [SELECT] statement. ^The second parameter is the
   5122 ** column number.  ^The leftmost column is number 0.
   5123 **
   5124 ** ^The returned string pointer is valid until either the [prepared statement]
   5125 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
   5126 ** reprepared by the first call to [sqlite3_step()] for a particular run
   5127 ** or until the next call to
   5128 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
   5129 **
   5130 ** ^If sqlite3_malloc() fails during the processing of either routine
   5131 ** (for example during a conversion from UTF-8 to UTF-16) then a
   5132 ** NULL pointer is returned.
   5133 **
   5134 ** ^The name of a result column is the value of the "AS" clause for
   5135 ** that column, if there is an AS clause.  If there is no AS clause
   5136 ** then the name of the column is unspecified and may change from
   5137 ** one release of SQLite to the next.
   5138 */
   5139 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
   5140 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
   5141 
   5142 /*
   5143 ** CAPI3REF: Source Of Data In A Query Result
   5144 ** METHOD: sqlite3_stmt
   5145 **
   5146 ** ^These routines provide a means to determine the database, table, and
   5147 ** table column that is the origin of a particular result column in
   5148 ** [SELECT] statement.
   5149 ** ^The name of the database or table or column can be returned as
   5150 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
   5151 ** the database name, the _table_ routines return the table name, and
   5152 ** the origin_ routines return the column name.
   5153 ** ^The returned string is valid until the [prepared statement] is destroyed
   5154 ** using [sqlite3_finalize()] or until the statement is automatically
   5155 ** reprepared by the first call to [sqlite3_step()] for a particular run
   5156 ** or until the same information is requested
   5157 ** again in a different encoding.
   5158 **
   5159 ** ^The names returned are the original un-aliased names of the
   5160 ** database, table, and column.
   5161 **
   5162 ** ^The first argument to these interfaces is a [prepared statement].
   5163 ** ^These functions return information about the Nth result column returned by
   5164 ** the statement, where N is the second function argument.
   5165 ** ^The left-most column is column 0 for these routines.
   5166 **
   5167 ** ^If the Nth column returned by the statement is an expression or
   5168 ** subquery and is not a column value, then all of these functions return
   5169 ** NULL.  ^These routine might also return NULL if a memory allocation error
   5170 ** occurs.  ^Otherwise, they return the name of the attached database, table,
   5171 ** or column that query result column was extracted from.
   5172 **
   5173 ** ^As with all other SQLite APIs, those whose names end with "16" return
   5174 ** UTF-16 encoded strings and the other functions return UTF-8.
   5175 **
   5176 ** ^These APIs are only available if the library was compiled with the
   5177 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
   5178 **
   5179 ** If two or more threads call one or more of these routines against the same
   5180 ** prepared statement and column at the same time then the results are
   5181 ** undefined.
   5182 **
   5183 ** If two or more threads call one or more
   5184 ** [sqlite3_column_database_name | column metadata interfaces]
   5185 ** for the same [prepared statement] and result column
   5186 ** at the same time then the results are undefined.
   5187 */
   5188 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
   5189 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
   5190 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
   5191 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
   5192 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
   5193 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
   5194 
   5195 /*
   5196 ** CAPI3REF: Declared Datatype Of A Query Result
   5197 ** METHOD: sqlite3_stmt
   5198 **
   5199 ** ^(The first parameter is a [prepared statement].
   5200 ** If this statement is a [SELECT] statement and the Nth column of the
   5201 ** returned result set of that [SELECT] is a table column (not an
   5202 ** expression or subquery) then the declared type of the table
   5203 ** column is returned.)^  ^If the Nth column of the result set is an
   5204 ** expression or subquery, then a NULL pointer is returned.
   5205 ** ^The returned string is always UTF-8 encoded.
   5206 **
   5207 ** ^(For example, given the database schema:
   5208 **
   5209 ** CREATE TABLE t1(c1 VARIANT);
   5210 **
   5211 ** and the following statement to be compiled:
   5212 **
   5213 ** SELECT c1 + 1, c1 FROM t1;
   5214 **
   5215 ** this routine would return the string "VARIANT" for the second result
   5216 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
   5217 **
   5218 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
   5219 ** is declared to contain a particular type does not mean that the
   5220 ** data stored in that column is of the declared type.  SQLite is
   5221 ** strongly typed, but the typing is dynamic not static.  ^Type
   5222 ** is associated with individual values, not with the containers
   5223 ** used to hold those values.
   5224 */
   5225 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
   5226 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
   5227 
   5228 /*
   5229 ** CAPI3REF: Evaluate An SQL Statement
   5230 ** METHOD: sqlite3_stmt
   5231 **
   5232 ** After a [prepared statement] has been prepared using any of
   5233 ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
   5234 ** or [sqlite3_prepare16_v3()] or one of the legacy
   5235 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
   5236 ** must be called one or more times to evaluate the statement.
   5237 **
   5238 ** The details of the behavior of the sqlite3_step() interface depend
   5239 ** on whether the statement was prepared using the newer "vX" interfaces
   5240 ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
   5241 ** [sqlite3_prepare16_v2()] or the older legacy
   5242 ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
   5243 ** new "vX" interface is recommended for new applications but the legacy
   5244 ** interface will continue to be supported.
   5245 **
   5246 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
   5247 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
   5248 ** ^With the "v2" interface, any of the other [result codes] or
   5249 ** [extended result codes] might be returned as well.
   5250 **
   5251 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
   5252 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
   5253 ** or occurs outside of an explicit transaction, then you can retry the
   5254 ** statement.  If the statement is not a [COMMIT] and occurs within an
   5255 ** explicit transaction then you should rollback the transaction before
   5256 ** continuing.
   5257 **
   5258 ** ^[SQLITE_DONE] means that the statement has finished executing
   5259 ** successfully.  sqlite3_step() should not be called again on this virtual
   5260 ** machine without first calling [sqlite3_reset()] to reset the virtual
   5261 ** machine back to its initial state.
   5262 **
   5263 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
   5264 ** is returned each time a new row of data is ready for processing by the
   5265 ** caller. The values may be accessed using the [column access functions].
   5266 ** sqlite3_step() is called again to retrieve the next row of data.
   5267 **
   5268 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
   5269 ** violation) has occurred.  sqlite3_step() should not be called again on
   5270 ** the VM. More information may be found by calling [sqlite3_errmsg()].
   5271 ** ^With the legacy interface, a more specific error code (for example,
   5272 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
   5273 ** can be obtained by calling [sqlite3_reset()] on the
   5274 ** [prepared statement].  ^In the "v2" interface,
   5275 ** the more specific error code is returned directly by sqlite3_step().
   5276 **
   5277 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
   5278 ** Perhaps it was called on a [prepared statement] that has
   5279 ** already been [sqlite3_finalize | finalized] or on one that had
   5280 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
   5281 ** be the case that the same database connection is being used by two or
   5282 ** more threads at the same moment in time.
   5283 **
   5284 ** For all versions of SQLite up to and including 3.6.23.1, a call to
   5285 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
   5286 ** other than [SQLITE_ROW] before any subsequent invocation of
   5287 ** sqlite3_step().  Failure to reset the prepared statement using
   5288 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
   5289 ** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],
   5290 ** sqlite3_step() began
   5291 ** calling [sqlite3_reset()] automatically in this circumstance rather
   5292 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
   5293 ** break because any application that ever receives an SQLITE_MISUSE error
   5294 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
   5295 ** can be used to restore the legacy behavior.
   5296 **
   5297 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
   5298 ** API always returns a generic error code, [SQLITE_ERROR], following any
   5299 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
   5300 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
   5301 ** specific [error codes] that better describes the error.
   5302 ** We admit that this is a goofy design.  The problem has been fixed
   5303 ** with the "v2" interface.  If you prepare all of your SQL statements
   5304 ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
   5305 ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
   5306 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
   5307 ** then the more specific [error codes] are returned directly
   5308 ** by sqlite3_step().  The use of the "vX" interfaces is recommended.
   5309 */
   5310 SQLITE_API int sqlite3_step(sqlite3_stmt*);
   5311 
   5312 /*
   5313 ** CAPI3REF: Number of columns in a result set
   5314 ** METHOD: sqlite3_stmt
   5315 **
   5316 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
   5317 ** current row of the result set of [prepared statement] P.
   5318 ** ^If prepared statement P does not have results ready to return
   5319 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
   5320 ** interfaces) then sqlite3_data_count(P) returns 0.
   5321 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
   5322 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
   5323 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
   5324 ** will return non-zero if previous call to [sqlite3_step](P) returned
   5325 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
   5326 ** where it always returns zero since each step of that multi-step
   5327 ** pragma returns 0 columns of data.
   5328 **
   5329 ** See also: [sqlite3_column_count()]
   5330 */
   5331 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
   5332 
   5333 /*
   5334 ** CAPI3REF: Fundamental Datatypes
   5335 ** KEYWORDS: SQLITE_TEXT
   5336 **
   5337 ** ^(Every value in SQLite has one of five fundamental datatypes:
   5338 **
   5339 ** <ul>
   5340 ** <li> 64-bit signed integer
   5341 ** <li> 64-bit IEEE floating point number
   5342 ** <li> string
   5343 ** <li> BLOB
   5344 ** <li> NULL
   5345 ** </ul>)^
   5346 **
   5347 ** These constants are codes for each of those types.
   5348 **
   5349 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
   5350 ** for a completely different meaning.  Software that links against both
   5351 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
   5352 ** SQLITE_TEXT.
   5353 */
   5354 #define SQLITE_INTEGER  1
   5355 #define SQLITE_FLOAT    2
   5356 #define SQLITE_BLOB     4
   5357 #define SQLITE_NULL     5
   5358 #ifdef SQLITE_TEXT
   5359 # undef SQLITE_TEXT
   5360 #else
   5361 # define SQLITE_TEXT     3
   5362 #endif
   5363 #define SQLITE3_TEXT     3
   5364 
   5365 /*
   5366 ** CAPI3REF: Result Values From A Query
   5367 ** KEYWORDS: {column access functions}
   5368 ** METHOD: sqlite3_stmt
   5369 **
   5370 ** <b>Summary:</b>
   5371 ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
   5372 ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
   5373 ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
   5374 ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
   5375 ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
   5376 ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
   5377 ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
   5378 ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
   5379 ** [sqlite3_value|unprotected sqlite3_value] object.
   5380 ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
   5381 ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
   5382 ** or a UTF-8 TEXT result in bytes
   5383 ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
   5384 ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
   5385 ** TEXT in bytes
   5386 ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
   5387 ** datatype of the result
   5388 ** </table></blockquote>
   5389 **
   5390 ** <b>Details:</b>
   5391 **
   5392 ** ^These routines return information about a single column of the current
   5393 ** result row of a query.  ^In every case the first argument is a pointer
   5394 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
   5395 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
   5396 ** and the second argument is the index of the column for which information
   5397 ** should be returned. ^The leftmost column of the result set has the index 0.
   5398 ** ^The number of columns in the result can be determined using
   5399 ** [sqlite3_column_count()].
   5400 **
   5401 ** If the SQL statement does not currently point to a valid row, or if the
   5402 ** column index is out of range, the result is undefined.
   5403 ** These routines may only be called when the most recent call to
   5404 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
   5405 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
   5406 ** If any of these routines are called after [sqlite3_reset()] or
   5407 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
   5408 ** something other than [SQLITE_ROW], the results are undefined.
   5409 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
   5410 ** are called from a different thread while any of these routines
   5411 ** are pending, then the results are undefined.
   5412 **
   5413 ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
   5414 ** each return the value of a result column in a specific data format.  If
   5415 ** the result column is not initially in the requested format (for example,
   5416 ** if the query returns an integer but the sqlite3_column_text() interface
   5417 ** is used to extract the value) then an automatic type conversion is performed.
   5418 **
   5419 ** ^The sqlite3_column_type() routine returns the
   5420 ** [SQLITE_INTEGER | datatype code] for the initial data type
   5421 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
   5422 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
   5423 ** The return value of sqlite3_column_type() can be used to decide which
   5424 ** of the first six interface should be used to extract the column value.
   5425 ** The value returned by sqlite3_column_type() is only meaningful if no
   5426 ** automatic type conversions have occurred for the value in question.
   5427 ** After a type conversion, the result of calling sqlite3_column_type()
   5428 ** is undefined, though harmless.  Future
   5429 ** versions of SQLite may change the behavior of sqlite3_column_type()
   5430 ** following a type conversion.
   5431 **
   5432 ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
   5433 ** or sqlite3_column_bytes16() interfaces can be used to determine the size
   5434 ** of that BLOB or string.
   5435 **
   5436 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
   5437 ** routine returns the number of bytes in that BLOB or string.
   5438 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
   5439 ** the string to UTF-8 and then returns the number of bytes.
   5440 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
   5441 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
   5442 ** the number of bytes in that string.
   5443 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
   5444 **
   5445 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
   5446 ** routine returns the number of bytes in that BLOB or string.
   5447 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
   5448 ** the string to UTF-16 and then returns the number of bytes.
   5449 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
   5450 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
   5451 ** the number of bytes in that string.
   5452 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
   5453 **
   5454 ** ^The values returned by [sqlite3_column_bytes()] and
   5455 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
   5456 ** of the string.  ^For clarity: the values returned by
   5457 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
   5458 ** bytes in the string, not the number of characters.
   5459 **
   5460 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
   5461 ** even empty strings, are always zero-terminated.  ^The return
   5462 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
   5463 **
   5464 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
   5465 ** [unprotected sqlite3_value] object.  In a multithreaded environment,
   5466 ** an unprotected sqlite3_value object may only be used safely with
   5467 ** [sqlite3_bind_value()] and [sqlite3_result_value()].
   5468 ** If the [unprotected sqlite3_value] object returned by
   5469 ** [sqlite3_column_value()] is used in any other way, including calls
   5470 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
   5471 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
   5472 ** Hence, the sqlite3_column_value() interface
   5473 ** is normally only useful within the implementation of
   5474 ** [application-defined SQL functions] or [virtual tables], not within
   5475 ** top-level application code.
   5476 **
   5477 ** The these routines may attempt to convert the datatype of the result.
   5478 ** ^For example, if the internal representation is FLOAT and a text result
   5479 ** is requested, [sqlite3_snprintf()] is used internally to perform the
   5480 ** conversion automatically.  ^(The following table details the conversions
   5481 ** that are applied:
   5482 **
   5483 ** <blockquote>
   5484 ** <table border="1">
   5485 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
   5486 **
   5487 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
   5488 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
   5489 ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
   5490 ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
   5491 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
   5492 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
   5493 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
   5494 ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
   5495 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
   5496 ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
   5497 ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
   5498 ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
   5499 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
   5500 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
   5501 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
   5502 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
   5503 ** </table>
   5504 ** </blockquote>)^
   5505 **
   5506 ** Note that when type conversions occur, pointers returned by prior
   5507 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
   5508 ** sqlite3_column_text16() may be invalidated.
   5509 ** Type conversions and pointer invalidations might occur
   5510 ** in the following cases:
   5511 **
   5512 ** <ul>
   5513 ** <li> The initial content is a BLOB and sqlite3_column_text() or
   5514 **      sqlite3_column_text16() is called.  A zero-terminator might
   5515 **      need to be added to the string.</li>
   5516 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
   5517 **      sqlite3_column_text16() is called.  The content must be converted
   5518 **      to UTF-16.</li>
   5519 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
   5520 **      sqlite3_column_text() is called.  The content must be converted
   5521 **      to UTF-8.</li>
   5522 ** </ul>
   5523 **
   5524 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
   5525 ** not invalidate a prior pointer, though of course the content of the buffer
   5526 ** that the prior pointer references will have been modified.  Other kinds
   5527 ** of conversion are done in place when it is possible, but sometimes they
   5528 ** are not possible and in those cases prior pointers are invalidated.
   5529 **
   5530 ** The safest policy is to invoke these routines
   5531 ** in one of the following ways:
   5532 **
   5533 ** <ul>
   5534 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
   5535 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
   5536 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
   5537 ** </ul>
   5538 **
   5539 ** In other words, you should call sqlite3_column_text(),
   5540 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
   5541 ** into the desired format, then invoke sqlite3_column_bytes() or
   5542 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
   5543 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
   5544 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
   5545 ** with calls to sqlite3_column_bytes().
   5546 **
   5547 ** ^The pointers returned are valid until a type conversion occurs as
   5548 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
   5549 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
   5550 ** and BLOBs is freed automatically.  Do not pass the pointers returned
   5551 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
   5552 ** [sqlite3_free()].
   5553 **
   5554 ** ^(If a memory allocation error occurs during the evaluation of any
   5555 ** of these routines, a default value is returned.  The default value
   5556 ** is either the integer 0, the floating point number 0.0, or a NULL
   5557 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
   5558 ** [SQLITE_NOMEM].)^
   5559 */
   5560 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
   5561 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
   5562 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
   5563 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
   5564 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
   5565 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
   5566 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
   5567 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
   5568 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
   5569 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
   5570 
   5571 /*
   5572 ** CAPI3REF: Destroy A Prepared Statement Object
   5573 ** DESTRUCTOR: sqlite3_stmt
   5574 **
   5575 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
   5576 ** ^If the most recent evaluation of the statement encountered no errors
   5577 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
   5578 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
   5579 ** sqlite3_finalize(S) returns the appropriate [error code] or
   5580 ** [extended error code].
   5581 **
   5582 ** ^The sqlite3_finalize(S) routine can be called at any point during
   5583 ** the life cycle of [prepared statement] S:
   5584 ** before statement S is ever evaluated, after
   5585 ** one or more calls to [sqlite3_reset()], or after any call
   5586 ** to [sqlite3_step()] regardless of whether or not the statement has
   5587 ** completed execution.
   5588 **
   5589 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
   5590 **
   5591 ** The application must finalize every [prepared statement] in order to avoid
   5592 ** resource leaks.  It is a grievous error for the application to try to use
   5593 ** a prepared statement after it has been finalized.  Any use of a prepared
   5594 ** statement after it has been finalized can result in undefined and
   5595 ** undesirable behavior such as segfaults and heap corruption.
   5596 */
   5597 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
   5598 
   5599 /*
   5600 ** CAPI3REF: Reset A Prepared Statement Object
   5601 ** METHOD: sqlite3_stmt
   5602 **
   5603 ** The sqlite3_reset() function is called to reset a [prepared statement]
   5604 ** object back to its initial state, ready to be re-executed.
   5605 ** ^Any SQL statement variables that had values bound to them using
   5606 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
   5607 ** Use [sqlite3_clear_bindings()] to reset the bindings.
   5608 **
   5609 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
   5610 ** back to the beginning of its program.
   5611 **
   5612 ** ^If the most recent call to [sqlite3_step(S)] for the
   5613 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
   5614 ** or if [sqlite3_step(S)] has never before been called on S,
   5615 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
   5616 **
   5617 ** ^If the most recent call to [sqlite3_step(S)] for the
   5618 ** [prepared statement] S indicated an error, then
   5619 ** [sqlite3_reset(S)] returns an appropriate [error code].
   5620 **
   5621 ** ^The [sqlite3_reset(S)] interface does not change the values
   5622 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
   5623 */
   5624 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
   5625 
   5626 /*
   5627 ** CAPI3REF: Create Or Redefine SQL Functions
   5628 ** KEYWORDS: {function creation routines}
   5629 ** KEYWORDS: {application-defined SQL function}
   5630 ** KEYWORDS: {application-defined SQL functions}
   5631 ** METHOD: sqlite3
   5632 **
   5633 ** ^These functions (collectively known as "function creation routines")
   5634 ** are used to add SQL functions or aggregates or to redefine the behavior
   5635 ** of existing SQL functions or aggregates.  The only differences between
   5636 ** these routines are the text encoding expected for
   5637 ** the second parameter (the name of the function being created)
   5638 ** and the presence or absence of a destructor callback for
   5639 ** the application data pointer.
   5640 **
   5641 ** ^The first parameter is the [database connection] to which the SQL
   5642 ** function is to be added.  ^If an application uses more than one database
   5643 ** connection then application-defined SQL functions must be added
   5644 ** to each database connection separately.
   5645 **
   5646 ** ^The second parameter is the name of the SQL function to be created or
   5647 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
   5648 ** representation, exclusive of the zero-terminator.  ^Note that the name
   5649 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
   5650 ** ^Any attempt to create a function with a longer name
   5651 ** will result in [SQLITE_MISUSE] being returned.
   5652 **
   5653 ** ^The third parameter (nArg)
   5654 ** is the number of arguments that the SQL function or
   5655 ** aggregate takes. ^If this parameter is -1, then the SQL function or
   5656 ** aggregate may take any number of arguments between 0 and the limit
   5657 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
   5658 ** parameter is less than -1 or greater than 127 then the behavior is
   5659 ** undefined.
   5660 **
   5661 ** ^The fourth parameter, eTextRep, specifies what
   5662 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
   5663 ** its parameters.  The application should set this parameter to
   5664 ** [SQLITE_UTF16LE] if the function implementation invokes
   5665 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
   5666 ** implementation invokes [sqlite3_value_text16be()] on an input, or
   5667 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
   5668 ** otherwise.  ^The same SQL function may be registered multiple times using
   5669 ** different preferred text encodings, with different implementations for
   5670 ** each encoding.
   5671 ** ^When multiple implementations of the same function are available, SQLite
   5672 ** will pick the one that involves the least amount of data conversion.
   5673 **
   5674 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
   5675 ** to signal that the function will always return the same result given
   5676 ** the same inputs within a single SQL statement.  Most SQL functions are
   5677 ** deterministic.  The built-in [random()] SQL function is an example of a
   5678 ** function that is not deterministic.  The SQLite query planner is able to
   5679 ** perform additional optimizations on deterministic functions, so use
   5680 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
   5681 **
   5682 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
   5683 ** function can gain access to this pointer using [sqlite3_user_data()].)^
   5684 **
   5685 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
   5686 ** pointers to C-language functions that implement the SQL function or
   5687 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
   5688 ** callback only; NULL pointers must be passed as the xStep and xFinal
   5689 ** parameters. ^An aggregate SQL function requires an implementation of xStep
   5690 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
   5691 ** SQL function or aggregate, pass NULL pointers for all three function
   5692 ** callbacks.
   5693 **
   5694 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
   5695 ** then it is destructor for the application data pointer.
   5696 ** The destructor is invoked when the function is deleted, either by being
   5697 ** overloaded or when the database connection closes.)^
   5698 ** ^The destructor is also invoked if the call to
   5699 ** sqlite3_create_function_v2() fails.
   5700 ** ^When the destructor callback of the tenth parameter is invoked, it
   5701 ** is passed a single argument which is a copy of the application data
   5702 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
   5703 **
   5704 ** ^It is permitted to register multiple implementations of the same
   5705 ** functions with the same name but with either differing numbers of
   5706 ** arguments or differing preferred text encodings.  ^SQLite will use
   5707 ** the implementation that most closely matches the way in which the
   5708 ** SQL function is used.  ^A function implementation with a non-negative
   5709 ** nArg parameter is a better match than a function implementation with
   5710 ** a negative nArg.  ^A function where the preferred text encoding
   5711 ** matches the database encoding is a better
   5712 ** match than a function where the encoding is different.
   5713 ** ^A function where the encoding difference is between UTF16le and UTF16be
   5714 ** is a closer match than a function where the encoding difference is
   5715 ** between UTF8 and UTF16.
   5716 **
   5717 ** ^Built-in functions may be overloaded by new application-defined functions.
   5718 **
   5719 ** ^An application-defined function is permitted to call other
   5720 ** SQLite interfaces.  However, such calls must not
   5721 ** close the database connection nor finalize or reset the prepared
   5722 ** statement in which the function is running.
   5723 */
   5724 SQLITE_API int sqlite3_create_function(
   5725   sqlite3 *db,
   5726   const char *zFunctionName,
   5727   int nArg,
   5728   int eTextRep,
   5729   void *pApp,
   5730   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   5731   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   5732   void (*xFinal)(sqlite3_context*)
   5733 );
   5734 SQLITE_API int sqlite3_create_function16(
   5735   sqlite3 *db,
   5736   const void *zFunctionName,
   5737   int nArg,
   5738   int eTextRep,
   5739   void *pApp,
   5740   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   5741   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   5742   void (*xFinal)(sqlite3_context*)
   5743 );
   5744 SQLITE_API int sqlite3_create_function_v2(
   5745   sqlite3 *db,
   5746   const char *zFunctionName,
   5747   int nArg,
   5748   int eTextRep,
   5749   void *pApp,
   5750   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   5751   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   5752   void (*xFinal)(sqlite3_context*),
   5753   void(*xDestroy)(void*)
   5754 );
   5755 
   5756 /*
   5757 ** CAPI3REF: Text Encodings
   5758 **
   5759 ** These constant define integer codes that represent the various
   5760 ** text encodings supported by SQLite.
   5761 */
   5762 #define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
   5763 #define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
   5764 #define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
   5765 #define SQLITE_UTF16          4    /* Use native byte order */
   5766 #define SQLITE_ANY            5    /* Deprecated */
   5767 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
   5768 
   5769 /*
   5770 ** CAPI3REF: Function Flags
   5771 **
   5772 ** These constants may be ORed together with the
   5773 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
   5774 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
   5775 ** [sqlite3_create_function_v2()].
   5776 */
   5777 #define SQLITE_DETERMINISTIC    0x800
   5778 
   5779 /*
   5780 ** CAPI3REF: Deprecated Functions
   5781 ** DEPRECATED
   5782 **
   5783 ** These functions are [deprecated].  In order to maintain
   5784 ** backwards compatibility with older code, these functions continue
   5785 ** to be supported.  However, new applications should avoid
   5786 ** the use of these functions.  To encourage programmers to avoid
   5787 ** these functions, we will not explain what they do.
   5788 */
   5789 #ifndef SQLITE_OMIT_DEPRECATED
   5790 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
   5791 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
   5792 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
   5793 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
   5794 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
   5795 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
   5796                       void*,sqlite3_int64);
   5797 #endif
   5798 
   5799 /*
   5800 ** CAPI3REF: Obtaining SQL Values
   5801 ** METHOD: sqlite3_value
   5802 **
   5803 ** <b>Summary:</b>
   5804 ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
   5805 ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
   5806 ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
   5807 ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
   5808 ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
   5809 ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
   5810 ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
   5811 ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
   5812 ** the native byteorder
   5813 ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
   5814 ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
   5815 ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
   5816 ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
   5817 ** or a UTF-8 TEXT in bytes
   5818 ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
   5819 ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
   5820 ** TEXT in bytes
   5821 ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
   5822 ** datatype of the value
   5823 ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
   5824 ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
   5825 ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
   5826 ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
   5827 ** against a virtual table.
   5828 ** </table></blockquote>
   5829 **
   5830 ** <b>Details:</b>
   5831 **
   5832 ** These routines extract type, size, and content information from
   5833 ** [protected sqlite3_value] objects.  Protected sqlite3_value objects
   5834 ** are used to pass parameter information into implementation of
   5835 ** [application-defined SQL functions] and [virtual tables].
   5836 **
   5837 ** These routines work only with [protected sqlite3_value] objects.
   5838 ** Any attempt to use these routines on an [unprotected sqlite3_value]
   5839 ** is not threadsafe.
   5840 **
   5841 ** ^These routines work just like the corresponding [column access functions]
   5842 ** except that these routines take a single [protected sqlite3_value] object
   5843 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
   5844 **
   5845 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
   5846 ** in the native byte-order of the host machine.  ^The
   5847 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
   5848 ** extract UTF-16 strings as big-endian and little-endian respectively.
   5849 **
   5850 ** ^If [sqlite3_value] object V was initialized
   5851 ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
   5852 ** and if X and Y are strings that compare equal according to strcmp(X,Y),
   5853 ** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,
   5854 ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
   5855 ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
   5856 **
   5857 ** ^(The sqlite3_value_type(V) interface returns the
   5858 ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
   5859 ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
   5860 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
   5861 ** Other interfaces might change the datatype for an sqlite3_value object.
   5862 ** For example, if the datatype is initially SQLITE_INTEGER and
   5863 ** sqlite3_value_text(V) is called to extract a text value for that
   5864 ** integer, then subsequent calls to sqlite3_value_type(V) might return
   5865 ** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion
   5866 ** occurs is undefined and may change from one release of SQLite to the next.
   5867 **
   5868 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
   5869 ** numeric affinity to the value.  This means that an attempt is
   5870 ** made to convert the value to an integer or floating point.  If
   5871 ** such a conversion is possible without loss of information (in other
   5872 ** words, if the value is a string that looks like a number)
   5873 ** then the conversion is performed.  Otherwise no conversion occurs.
   5874 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
   5875 **
   5876 ** ^Within the [xUpdate] method of a [virtual table], the
   5877 ** sqlite3_value_nochange(X) interface returns true if and only if
   5878 ** the column corresponding to X is unchanged by the UPDATE operation
   5879 ** that the xUpdate method call was invoked to implement and if
   5880 ** and the prior [xColumn] method call that was invoked to extracted
   5881 ** the value for that column returned without setting a result (probably
   5882 ** because it queried [sqlite3_vtab_nochange()] and found that the column
   5883 ** was unchanging).  ^Within an [xUpdate] method, any value for which
   5884 ** sqlite3_value_nochange(X) is true will in all other respects appear
   5885 ** to be a NULL value.  If sqlite3_value_nochange(X) is invoked anywhere other
   5886 ** than within an [xUpdate] method call for an UPDATE statement, then
   5887 ** the return value is arbitrary and meaningless.
   5888 **
   5889 ** Please pay particular attention to the fact that the pointer returned
   5890 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
   5891 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
   5892 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
   5893 ** or [sqlite3_value_text16()].
   5894 **
   5895 ** These routines must be called from the same thread as
   5896 ** the SQL function that supplied the [sqlite3_value*] parameters.
   5897 */
   5898 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
   5899 SQLITE_API double sqlite3_value_double(sqlite3_value*);
   5900 SQLITE_API int sqlite3_value_int(sqlite3_value*);
   5901 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
   5902 SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
   5903 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
   5904 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
   5905 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
   5906 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
   5907 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
   5908 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
   5909 SQLITE_API int sqlite3_value_type(sqlite3_value*);
   5910 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
   5911 SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
   5912 
   5913 /*
   5914 ** CAPI3REF: Finding The Subtype Of SQL Values
   5915 ** METHOD: sqlite3_value
   5916 **
   5917 ** The sqlite3_value_subtype(V) function returns the subtype for
   5918 ** an [application-defined SQL function] argument V.  The subtype
   5919 ** information can be used to pass a limited amount of context from
   5920 ** one SQL function to another.  Use the [sqlite3_result_subtype()]
   5921 ** routine to set the subtype for the return value of an SQL function.
   5922 */
   5923 SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
   5924 
   5925 /*
   5926 ** CAPI3REF: Copy And Free SQL Values
   5927 ** METHOD: sqlite3_value
   5928 **
   5929 ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
   5930 ** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
   5931 ** is a [protected sqlite3_value] object even if the input is not.
   5932 ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
   5933 ** memory allocation fails.
   5934 **
   5935 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
   5936 ** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
   5937 ** then sqlite3_value_free(V) is a harmless no-op.
   5938 */
   5939 SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
   5940 SQLITE_API void sqlite3_value_free(sqlite3_value*);
   5941 
   5942 /*
   5943 ** CAPI3REF: Obtain Aggregate Function Context
   5944 ** METHOD: sqlite3_context
   5945 **
   5946 ** Implementations of aggregate SQL functions use this
   5947 ** routine to allocate memory for storing their state.
   5948 **
   5949 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
   5950 ** for a particular aggregate function, SQLite
   5951 ** allocates N of memory, zeroes out that memory, and returns a pointer
   5952 ** to the new memory. ^On second and subsequent calls to
   5953 ** sqlite3_aggregate_context() for the same aggregate function instance,
   5954 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
   5955 ** called once for each invocation of the xStep callback and then one
   5956 ** last time when the xFinal callback is invoked.  ^(When no rows match
   5957 ** an aggregate query, the xStep() callback of the aggregate function
   5958 ** implementation is never called and xFinal() is called exactly once.
   5959 ** In those cases, sqlite3_aggregate_context() might be called for the
   5960 ** first time from within xFinal().)^
   5961 **
   5962 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
   5963 ** when first called if N is less than or equal to zero or if a memory
   5964 ** allocate error occurs.
   5965 **
   5966 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
   5967 ** determined by the N parameter on first successful call.  Changing the
   5968 ** value of N in subsequent call to sqlite3_aggregate_context() within
   5969 ** the same aggregate function instance will not resize the memory
   5970 ** allocation.)^  Within the xFinal callback, it is customary to set
   5971 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
   5972 ** pointless memory allocations occur.
   5973 **
   5974 ** ^SQLite automatically frees the memory allocated by
   5975 ** sqlite3_aggregate_context() when the aggregate query concludes.
   5976 **
   5977 ** The first parameter must be a copy of the
   5978 ** [sqlite3_context | SQL function context] that is the first parameter
   5979 ** to the xStep or xFinal callback routine that implements the aggregate
   5980 ** function.
   5981 **
   5982 ** This routine must be called from the same thread in which
   5983 ** the aggregate SQL function is running.
   5984 */
   5985 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
   5986 
   5987 /*
   5988 ** CAPI3REF: User Data For Functions
   5989 ** METHOD: sqlite3_context
   5990 **
   5991 ** ^The sqlite3_user_data() interface returns a copy of
   5992 ** the pointer that was the pUserData parameter (the 5th parameter)
   5993 ** of the [sqlite3_create_function()]
   5994 ** and [sqlite3_create_function16()] routines that originally
   5995 ** registered the application defined function.
   5996 **
   5997 ** This routine must be called from the same thread in which
   5998 ** the application-defined function is running.
   5999 */
   6000 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
   6001 
   6002 /*
   6003 ** CAPI3REF: Database Connection For Functions
   6004 ** METHOD: sqlite3_context
   6005 **
   6006 ** ^The sqlite3_context_db_handle() interface returns a copy of
   6007 ** the pointer to the [database connection] (the 1st parameter)
   6008 ** of the [sqlite3_create_function()]
   6009 ** and [sqlite3_create_function16()] routines that originally
   6010 ** registered the application defined function.
   6011 */
   6012 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
   6013 
   6014 /*
   6015 ** CAPI3REF: Function Auxiliary Data
   6016 ** METHOD: sqlite3_context
   6017 **
   6018 ** These functions may be used by (non-aggregate) SQL functions to
   6019 ** associate metadata with argument values. If the same value is passed to
   6020 ** multiple invocations of the same SQL function during query execution, under
   6021 ** some circumstances the associated metadata may be preserved.  An example
   6022 ** of where this might be useful is in a regular-expression matching
   6023 ** function. The compiled version of the regular expression can be stored as
   6024 ** metadata associated with the pattern string.
   6025 ** Then as long as the pattern string remains the same,
   6026 ** the compiled regular expression can be reused on multiple
   6027 ** invocations of the same function.
   6028 **
   6029 ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
   6030 ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
   6031 ** value to the application-defined function.  ^N is zero for the left-most
   6032 ** function argument.  ^If there is no metadata
   6033 ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
   6034 ** returns a NULL pointer.
   6035 **
   6036 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
   6037 ** argument of the application-defined function.  ^Subsequent
   6038 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
   6039 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
   6040 ** NULL if the metadata has been discarded.
   6041 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
   6042 ** SQLite will invoke the destructor function X with parameter P exactly
   6043 ** once, when the metadata is discarded.
   6044 ** SQLite is free to discard the metadata at any time, including: <ul>
   6045 ** <li> ^(when the corresponding function parameter changes)^, or
   6046 ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
   6047 **      SQL statement)^, or
   6048 ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
   6049 **       parameter)^, or
   6050 ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
   6051 **      allocation error occurs.)^ </ul>
   6052 **
   6053 ** Note the last bullet in particular.  The destructor X in
   6054 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
   6055 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
   6056 ** should be called near the end of the function implementation and the
   6057 ** function implementation should not make any use of P after
   6058 ** sqlite3_set_auxdata() has been called.
   6059 **
   6060 ** ^(In practice, metadata is preserved between function calls for
   6061 ** function parameters that are compile-time constants, including literal
   6062 ** values and [parameters] and expressions composed from the same.)^
   6063 **
   6064 ** The value of the N parameter to these interfaces should be non-negative.
   6065 ** Future enhancements may make use of negative N values to define new
   6066 ** kinds of function caching behavior.
   6067 **
   6068 ** These routines must be called from the same thread in which
   6069 ** the SQL function is running.
   6070 */
   6071 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
   6072 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
   6073 
   6074 
   6075 /*
   6076 ** CAPI3REF: Constants Defining Special Destructor Behavior
   6077 **
   6078 ** These are special values for the destructor that is passed in as the
   6079 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
   6080 ** argument is SQLITE_STATIC, it means that the content pointer is constant
   6081 ** and will never change.  It does not need to be destroyed.  ^The
   6082 ** SQLITE_TRANSIENT value means that the content will likely change in
   6083 ** the near future and that SQLite should make its own private copy of
   6084 ** the content before returning.
   6085 **
   6086 ** The typedef is necessary to work around problems in certain
   6087 ** C++ compilers.
   6088 */
   6089 typedef void (*sqlite3_destructor_type)(void*);
   6090 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
   6091 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
   6092 
   6093 /*
   6094 ** CAPI3REF: Setting The Result Of An SQL Function
   6095 ** METHOD: sqlite3_context
   6096 **
   6097 ** These routines are used by the xFunc or xFinal callbacks that
   6098 ** implement SQL functions and aggregates.  See
   6099 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
   6100 ** for additional information.
   6101 **
   6102 ** These functions work very much like the [parameter binding] family of
   6103 ** functions used to bind values to host parameters in prepared statements.
   6104 ** Refer to the [SQL parameter] documentation for additional information.
   6105 **
   6106 ** ^The sqlite3_result_blob() interface sets the result from
   6107 ** an application-defined function to be the BLOB whose content is pointed
   6108 ** to by the second parameter and which is N bytes long where N is the
   6109 ** third parameter.
   6110 **
   6111 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
   6112 ** interfaces set the result of the application-defined function to be
   6113 ** a BLOB containing all zero bytes and N bytes in size.
   6114 **
   6115 ** ^The sqlite3_result_double() interface sets the result from
   6116 ** an application-defined function to be a floating point value specified
   6117 ** by its 2nd argument.
   6118 **
   6119 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
   6120 ** cause the implemented SQL function to throw an exception.
   6121 ** ^SQLite uses the string pointed to by the
   6122 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
   6123 ** as the text of an error message.  ^SQLite interprets the error
   6124 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
   6125 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
   6126 ** byte order.  ^If the third parameter to sqlite3_result_error()
   6127 ** or sqlite3_result_error16() is negative then SQLite takes as the error
   6128 ** message all text up through the first zero character.
   6129 ** ^If the third parameter to sqlite3_result_error() or
   6130 ** sqlite3_result_error16() is non-negative then SQLite takes that many
   6131 ** bytes (not characters) from the 2nd parameter as the error message.
   6132 ** ^The sqlite3_result_error() and sqlite3_result_error16()
   6133 ** routines make a private copy of the error message text before
   6134 ** they return.  Hence, the calling function can deallocate or
   6135 ** modify the text after they return without harm.
   6136 ** ^The sqlite3_result_error_code() function changes the error code
   6137 ** returned by SQLite as a result of an error in a function.  ^By default,
   6138 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
   6139 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
   6140 **
   6141 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
   6142 ** error indicating that a string or BLOB is too long to represent.
   6143 **
   6144 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
   6145 ** error indicating that a memory allocation failed.
   6146 **
   6147 ** ^The sqlite3_result_int() interface sets the return value
   6148 ** of the application-defined function to be the 32-bit signed integer
   6149 ** value given in the 2nd argument.
   6150 ** ^The sqlite3_result_int64() interface sets the return value
   6151 ** of the application-defined function to be the 64-bit signed integer
   6152 ** value given in the 2nd argument.
   6153 **
   6154 ** ^The sqlite3_result_null() interface sets the return value
   6155 ** of the application-defined function to be NULL.
   6156 **
   6157 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
   6158 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
   6159 ** set the return value of the application-defined function to be
   6160 ** a text string which is represented as UTF-8, UTF-16 native byte order,
   6161 ** UTF-16 little endian, or UTF-16 big endian, respectively.
   6162 ** ^The sqlite3_result_text64() interface sets the return value of an
   6163 ** application-defined function to be a text string in an encoding
   6164 ** specified by the fifth (and last) parameter, which must be one
   6165 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
   6166 ** ^SQLite takes the text result from the application from
   6167 ** the 2nd parameter of the sqlite3_result_text* interfaces.
   6168 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   6169 ** is negative, then SQLite takes result text from the 2nd parameter
   6170 ** through the first zero character.
   6171 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   6172 ** is non-negative, then as many bytes (not characters) of the text
   6173 ** pointed to by the 2nd parameter are taken as the application-defined
   6174 ** function result.  If the 3rd parameter is non-negative, then it
   6175 ** must be the byte offset into the string where the NUL terminator would
   6176 ** appear if the string where NUL terminated.  If any NUL characters occur
   6177 ** in the string at a byte offset that is less than the value of the 3rd
   6178 ** parameter, then the resulting string will contain embedded NULs and the
   6179 ** result of expressions operating on strings with embedded NULs is undefined.
   6180 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   6181 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
   6182 ** function as the destructor on the text or BLOB result when it has
   6183 ** finished using that result.
   6184 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
   6185 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
   6186 ** assumes that the text or BLOB result is in constant space and does not
   6187 ** copy the content of the parameter nor call a destructor on the content
   6188 ** when it has finished using that result.
   6189 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   6190 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
   6191 ** then SQLite makes a copy of the result into space obtained
   6192 ** from [sqlite3_malloc()] before it returns.
   6193 **
   6194 ** ^The sqlite3_result_value() interface sets the result of
   6195 ** the application-defined function to be a copy of the
   6196 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
   6197 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
   6198 ** so that the [sqlite3_value] specified in the parameter may change or
   6199 ** be deallocated after sqlite3_result_value() returns without harm.
   6200 ** ^A [protected sqlite3_value] object may always be used where an
   6201 ** [unprotected sqlite3_value] object is required, so either
   6202 ** kind of [sqlite3_value] object can be used with this interface.
   6203 **
   6204 ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
   6205 ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
   6206 ** also associates the host-language pointer P or type T with that
   6207 ** NULL value such that the pointer can be retrieved within an
   6208 ** [application-defined SQL function] using [sqlite3_value_pointer()].
   6209 ** ^If the D parameter is not NULL, then it is a pointer to a destructor
   6210 ** for the P parameter.  ^SQLite invokes D with P as its only argument
   6211 ** when SQLite is finished with P.  The T parameter should be a static
   6212 ** string and preferably a string literal. The sqlite3_result_pointer()
   6213 ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
   6214 **
   6215 ** If these routines are called from within the different thread
   6216 ** than the one containing the application-defined function that received
   6217 ** the [sqlite3_context] pointer, the results are undefined.
   6218 */
   6219 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
   6220 SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
   6221                            sqlite3_uint64,void(*)(void*));
   6222 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
   6223 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
   6224 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
   6225 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
   6226 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
   6227 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
   6228 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
   6229 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
   6230 SQLITE_API void sqlite3_result_null(sqlite3_context*);
   6231 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
   6232 SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
   6233                            void(*)(void*), unsigned char encoding);
   6234 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
   6235 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
   6236 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
   6237 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
   6238 SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
   6239 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
   6240 SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
   6241 
   6242 
   6243 /*
   6244 ** CAPI3REF: Setting The Subtype Of An SQL Function
   6245 ** METHOD: sqlite3_context
   6246 **
   6247 ** The sqlite3_result_subtype(C,T) function causes the subtype of
   6248 ** the result from the [application-defined SQL function] with
   6249 ** [sqlite3_context] C to be the value T.  Only the lower 8 bits
   6250 ** of the subtype T are preserved in current versions of SQLite;
   6251 ** higher order bits are discarded.
   6252 ** The number of subtype bytes preserved by SQLite might increase
   6253 ** in future releases of SQLite.
   6254 */
   6255 SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
   6256 
   6257 /*
   6258 ** CAPI3REF: Define New Collating Sequences
   6259 ** METHOD: sqlite3
   6260 **
   6261 ** ^These functions add, remove, or modify a [collation] associated
   6262 ** with the [database connection] specified as the first argument.
   6263 **
   6264 ** ^The name of the collation is a UTF-8 string
   6265 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
   6266 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
   6267 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
   6268 ** considered to be the same name.
   6269 **
   6270 ** ^(The third argument (eTextRep) must be one of the constants:
   6271 ** <ul>
   6272 ** <li> [SQLITE_UTF8],
   6273 ** <li> [SQLITE_UTF16LE],
   6274 ** <li> [SQLITE_UTF16BE],
   6275 ** <li> [SQLITE_UTF16], or
   6276 ** <li> [SQLITE_UTF16_ALIGNED].
   6277 ** </ul>)^
   6278 ** ^The eTextRep argument determines the encoding of strings passed
   6279 ** to the collating function callback, xCallback.
   6280 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
   6281 ** force strings to be UTF16 with native byte order.
   6282 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
   6283 ** on an even byte address.
   6284 **
   6285 ** ^The fourth argument, pArg, is an application data pointer that is passed
   6286 ** through as the first argument to the collating function callback.
   6287 **
   6288 ** ^The fifth argument, xCallback, is a pointer to the collating function.
   6289 ** ^Multiple collating functions can be registered using the same name but
   6290 ** with different eTextRep parameters and SQLite will use whichever
   6291 ** function requires the least amount of data transformation.
   6292 ** ^If the xCallback argument is NULL then the collating function is
   6293 ** deleted.  ^When all collating functions having the same name are deleted,
   6294 ** that collation is no longer usable.
   6295 **
   6296 ** ^The collating function callback is invoked with a copy of the pArg
   6297 ** application data pointer and with two strings in the encoding specified
   6298 ** by the eTextRep argument.  The collating function must return an
   6299 ** integer that is negative, zero, or positive
   6300 ** if the first string is less than, equal to, or greater than the second,
   6301 ** respectively.  A collating function must always return the same answer
   6302 ** given the same inputs.  If two or more collating functions are registered
   6303 ** to the same collation name (using different eTextRep values) then all
   6304 ** must give an equivalent answer when invoked with equivalent strings.
   6305 ** The collating function must obey the following properties for all
   6306 ** strings A, B, and C:
   6307 **
   6308 ** <ol>
   6309 ** <li> If A==B then B==A.
   6310 ** <li> If A==B and B==C then A==C.
   6311 ** <li> If A&lt;B THEN B&gt;A.
   6312 ** <li> If A&lt;B and B&lt;C then A&lt;C.
   6313 ** </ol>
   6314 **
   6315 ** If a collating function fails any of the above constraints and that
   6316 ** collating function is  registered and used, then the behavior of SQLite
   6317 ** is undefined.
   6318 **
   6319 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
   6320 ** with the addition that the xDestroy callback is invoked on pArg when
   6321 ** the collating function is deleted.
   6322 ** ^Collating functions are deleted when they are overridden by later
   6323 ** calls to the collation creation functions or when the
   6324 ** [database connection] is closed using [sqlite3_close()].
   6325 **
   6326 ** ^The xDestroy callback is <u>not</u> called if the
   6327 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
   6328 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
   6329 ** check the return code and dispose of the application data pointer
   6330 ** themselves rather than expecting SQLite to deal with it for them.
   6331 ** This is different from every other SQLite interface.  The inconsistency
   6332 ** is unfortunate but cannot be changed without breaking backwards
   6333 ** compatibility.
   6334 **
   6335 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
   6336 */
   6337 SQLITE_API int sqlite3_create_collation(
   6338   sqlite3*,
   6339   const char *zName,
   6340   int eTextRep,
   6341   void *pArg,
   6342   int(*xCompare)(void*,int,const void*,int,const void*)
   6343 );
   6344 SQLITE_API int sqlite3_create_collation_v2(
   6345   sqlite3*,
   6346   const char *zName,
   6347   int eTextRep,
   6348   void *pArg,
   6349   int(*xCompare)(void*,int,const void*,int,const void*),
   6350   void(*xDestroy)(void*)
   6351 );
   6352 SQLITE_API int sqlite3_create_collation16(
   6353   sqlite3*,
   6354   const void *zName,
   6355   int eTextRep,
   6356   void *pArg,
   6357   int(*xCompare)(void*,int,const void*,int,const void*)
   6358 );
   6359 
   6360 /*
   6361 ** CAPI3REF: Collation Needed Callbacks
   6362 ** METHOD: sqlite3
   6363 **
   6364 ** ^To avoid having to register all collation sequences before a database
   6365 ** can be used, a single callback function may be registered with the
   6366 ** [database connection] to be invoked whenever an undefined collation
   6367 ** sequence is required.
   6368 **
   6369 ** ^If the function is registered using the sqlite3_collation_needed() API,
   6370 ** then it is passed the names of undefined collation sequences as strings
   6371 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
   6372 ** the names are passed as UTF-16 in machine native byte order.
   6373 ** ^A call to either function replaces the existing collation-needed callback.
   6374 **
   6375 ** ^(When the callback is invoked, the first argument passed is a copy
   6376 ** of the second argument to sqlite3_collation_needed() or
   6377 ** sqlite3_collation_needed16().  The second argument is the database
   6378 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
   6379 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
   6380 ** sequence function required.  The fourth parameter is the name of the
   6381 ** required collation sequence.)^
   6382 **
   6383 ** The callback function should register the desired collation using
   6384 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
   6385 ** [sqlite3_create_collation_v2()].
   6386 */
   6387 SQLITE_API int sqlite3_collation_needed(
   6388   sqlite3*,
   6389   void*,
   6390   void(*)(void*,sqlite3*,int eTextRep,const char*)
   6391 );
   6392 SQLITE_API int sqlite3_collation_needed16(
   6393   sqlite3*,
   6394   void*,
   6395   void(*)(void*,sqlite3*,int eTextRep,const void*)
   6396 );
   6397 
   6398 #ifdef SQLITE_HAS_CODEC
   6399 /*
   6400 ** Specify the key for an encrypted database.  This routine should be
   6401 ** called right after sqlite3_open().
   6402 **
   6403 ** The code to implement this API is not available in the public release
   6404 ** of SQLite.
   6405 */
   6406 SQLITE_API int sqlite3_key(
   6407   sqlite3 *db,                   /* Database to be rekeyed */
   6408   const void *pKey, int nKey     /* The key */
   6409 );
   6410 SQLITE_API int sqlite3_key_v2(
   6411   sqlite3 *db,                   /* Database to be rekeyed */
   6412   const char *zDbName,           /* Name of the database */
   6413   const void *pKey, int nKey     /* The key */
   6414 );
   6415 
   6416 /*
   6417 ** Change the key on an open database.  If the current database is not
   6418 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
   6419 ** database is decrypted.
   6420 **
   6421 ** The code to implement this API is not available in the public release
   6422 ** of SQLite.
   6423 */
   6424 SQLITE_API int sqlite3_rekey(
   6425   sqlite3 *db,                   /* Database to be rekeyed */
   6426   const void *pKey, int nKey     /* The new key */
   6427 );
   6428 SQLITE_API int sqlite3_rekey_v2(
   6429   sqlite3 *db,                   /* Database to be rekeyed */
   6430   const char *zDbName,           /* Name of the database */
   6431   const void *pKey, int nKey     /* The new key */
   6432 );
   6433 
   6434 /*
   6435 ** Specify the activation key for a SEE database.  Unless
   6436 ** activated, none of the SEE routines will work.
   6437 */
   6438 SQLITE_API void sqlite3_activate_see(
   6439   const char *zPassPhrase        /* Activation phrase */
   6440 );
   6441 #endif
   6442 
   6443 #ifdef SQLITE_ENABLE_CEROD
   6444 /*
   6445 ** Specify the activation key for a CEROD database.  Unless
   6446 ** activated, none of the CEROD routines will work.
   6447 */
   6448 SQLITE_API void sqlite3_activate_cerod(
   6449   const char *zPassPhrase        /* Activation phrase */
   6450 );
   6451 #endif
   6452 
   6453 /*
   6454 ** CAPI3REF: Suspend Execution For A Short Time
   6455 **
   6456 ** The sqlite3_sleep() function causes the current thread to suspend execution
   6457 ** for at least a number of milliseconds specified in its parameter.
   6458 **
   6459 ** If the operating system does not support sleep requests with
   6460 ** millisecond time resolution, then the time will be rounded up to
   6461 ** the nearest second. The number of milliseconds of sleep actually
   6462 ** requested from the operating system is returned.
   6463 **
   6464 ** ^SQLite implements this interface by calling the xSleep()
   6465 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
   6466 ** of the default VFS is not implemented correctly, or not implemented at
   6467 ** all, then the behavior of sqlite3_sleep() may deviate from the description
   6468 ** in the previous paragraphs.
   6469 */
   6470 SQLITE_API int sqlite3_sleep(int);
   6471 
   6472 /*
   6473 ** CAPI3REF: Name Of The Folder Holding Temporary Files
   6474 **
   6475 ** ^(If this global variable is made to point to a string which is
   6476 ** the name of a folder (a.k.a. directory), then all temporary files
   6477 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
   6478 ** will be placed in that directory.)^  ^If this variable
   6479 ** is a NULL pointer, then SQLite performs a search for an appropriate
   6480 ** temporary file directory.
   6481 **
   6482 ** Applications are strongly discouraged from using this global variable.
   6483 ** It is required to set a temporary folder on Windows Runtime (WinRT).
   6484 ** But for all other platforms, it is highly recommended that applications
   6485 ** neither read nor write this variable.  This global variable is a relic
   6486 ** that exists for backwards compatibility of legacy applications and should
   6487 ** be avoided in new projects.
   6488 **
   6489 ** It is not safe to read or modify this variable in more than one
   6490 ** thread at a time.  It is not safe to read or modify this variable
   6491 ** if a [database connection] is being used at the same time in a separate
   6492 ** thread.
   6493 ** It is intended that this variable be set once
   6494 ** as part of process initialization and before any SQLite interface
   6495 ** routines have been called and that this variable remain unchanged
   6496 ** thereafter.
   6497 **
   6498 ** ^The [temp_store_directory pragma] may modify this variable and cause
   6499 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   6500 ** the [temp_store_directory pragma] always assumes that any string
   6501 ** that this variable points to is held in memory obtained from
   6502 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   6503 ** using [sqlite3_free].
   6504 ** Hence, if this variable is modified directly, either it should be
   6505 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   6506 ** or else the use of the [temp_store_directory pragma] should be avoided.
   6507 ** Except when requested by the [temp_store_directory pragma], SQLite
   6508 ** does not free the memory that sqlite3_temp_directory points to.  If
   6509 ** the application wants that memory to be freed, it must do
   6510 ** so itself, taking care to only do so after all [database connection]
   6511 ** objects have been destroyed.
   6512 **
   6513 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
   6514 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
   6515 ** features that require the use of temporary files may fail.  Here is an
   6516 ** example of how to do this using C++ with the Windows Runtime:
   6517 **
   6518 ** <blockquote><pre>
   6519 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
   6520 ** &nbsp;     TemporaryFolder->Path->Data();
   6521 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
   6522 ** memset(zPathBuf, 0, sizeof(zPathBuf));
   6523 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
   6524 ** &nbsp;     NULL, NULL);
   6525 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
   6526 ** </pre></blockquote>
   6527 */
   6528 SQLITE_API char *sqlite3_temp_directory;
   6529 
   6530 /*
   6531 ** CAPI3REF: Name Of The Folder Holding Database Files
   6532 **
   6533 ** ^(If this global variable is made to point to a string which is
   6534 ** the name of a folder (a.k.a. directory), then all database files
   6535 ** specified with a relative pathname and created or accessed by
   6536 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
   6537 ** to be relative to that directory.)^ ^If this variable is a NULL
   6538 ** pointer, then SQLite assumes that all database files specified
   6539 ** with a relative pathname are relative to the current directory
   6540 ** for the process.  Only the windows VFS makes use of this global
   6541 ** variable; it is ignored by the unix VFS.
   6542 **
   6543 ** Changing the value of this variable while a database connection is
   6544 ** open can result in a corrupt database.
   6545 **
   6546 ** It is not safe to read or modify this variable in more than one
   6547 ** thread at a time.  It is not safe to read or modify this variable
   6548 ** if a [database connection] is being used at the same time in a separate
   6549 ** thread.
   6550 ** It is intended that this variable be set once
   6551 ** as part of process initialization and before any SQLite interface
   6552 ** routines have been called and that this variable remain unchanged
   6553 ** thereafter.
   6554 **
   6555 ** ^The [data_store_directory pragma] may modify this variable and cause
   6556 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   6557 ** the [data_store_directory pragma] always assumes that any string
   6558 ** that this variable points to is held in memory obtained from
   6559 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   6560 ** using [sqlite3_free].
   6561 ** Hence, if this variable is modified directly, either it should be
   6562 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   6563 ** or else the use of the [data_store_directory pragma] should be avoided.
   6564 */
   6565 SQLITE_API char *sqlite3_data_directory;
   6566 
   6567 /*
   6568 ** CAPI3REF: Test For Auto-Commit Mode
   6569 ** KEYWORDS: {autocommit mode}
   6570 ** METHOD: sqlite3
   6571 **
   6572 ** ^The sqlite3_get_autocommit() interface returns non-zero or
   6573 ** zero if the given database connection is or is not in autocommit mode,
   6574 ** respectively.  ^Autocommit mode is on by default.
   6575 ** ^Autocommit mode is disabled by a [BEGIN] statement.
   6576 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
   6577 **
   6578 ** If certain kinds of errors occur on a statement within a multi-statement
   6579 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
   6580 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
   6581 ** transaction might be rolled back automatically.  The only way to
   6582 ** find out whether SQLite automatically rolled back the transaction after
   6583 ** an error is to use this function.
   6584 **
   6585 ** If another thread changes the autocommit status of the database
   6586 ** connection while this routine is running, then the return value
   6587 ** is undefined.
   6588 */
   6589 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
   6590 
   6591 /*
   6592 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
   6593 ** METHOD: sqlite3_stmt
   6594 **
   6595 ** ^The sqlite3_db_handle interface returns the [database connection] handle
   6596 ** to which a [prepared statement] belongs.  ^The [database connection]
   6597 ** returned by sqlite3_db_handle is the same [database connection]
   6598 ** that was the first argument
   6599 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
   6600 ** create the statement in the first place.
   6601 */
   6602 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
   6603 
   6604 /*
   6605 ** CAPI3REF: Return The Filename For A Database Connection
   6606 ** METHOD: sqlite3
   6607 **
   6608 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
   6609 ** associated with database N of connection D.  ^The main database file
   6610 ** has the name "main".  If there is no attached database N on the database
   6611 ** connection D, or if database N is a temporary or in-memory database, then
   6612 ** a NULL pointer is returned.
   6613 **
   6614 ** ^The filename returned by this function is the output of the
   6615 ** xFullPathname method of the [VFS].  ^In other words, the filename
   6616 ** will be an absolute pathname, even if the filename used
   6617 ** to open the database originally was a URI or relative pathname.
   6618 */
   6619 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
   6620 
   6621 /*
   6622 ** CAPI3REF: Determine if a database is read-only
   6623 ** METHOD: sqlite3
   6624 **
   6625 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
   6626 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
   6627 ** the name of a database on connection D.
   6628 */
   6629 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
   6630 
   6631 /*
   6632 ** CAPI3REF: Find the next prepared statement
   6633 ** METHOD: sqlite3
   6634 **
   6635 ** ^This interface returns a pointer to the next [prepared statement] after
   6636 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
   6637 ** then this interface returns a pointer to the first prepared statement
   6638 ** associated with the database connection pDb.  ^If no prepared statement
   6639 ** satisfies the conditions of this routine, it returns NULL.
   6640 **
   6641 ** The [database connection] pointer D in a call to
   6642 ** [sqlite3_next_stmt(D,S)] must refer to an open database
   6643 ** connection and in particular must not be a NULL pointer.
   6644 */
   6645 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
   6646 
   6647 /*
   6648 ** CAPI3REF: Commit And Rollback Notification Callbacks
   6649 ** METHOD: sqlite3
   6650 **
   6651 ** ^The sqlite3_commit_hook() interface registers a callback
   6652 ** function to be invoked whenever a transaction is [COMMIT | committed].
   6653 ** ^Any callback set by a previous call to sqlite3_commit_hook()
   6654 ** for the same database connection is overridden.
   6655 ** ^The sqlite3_rollback_hook() interface registers a callback
   6656 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
   6657 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
   6658 ** for the same database connection is overridden.
   6659 ** ^The pArg argument is passed through to the callback.
   6660 ** ^If the callback on a commit hook function returns non-zero,
   6661 ** then the commit is converted into a rollback.
   6662 **
   6663 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
   6664 ** return the P argument from the previous call of the same function
   6665 ** on the same [database connection] D, or NULL for
   6666 ** the first call for each function on D.
   6667 **
   6668 ** The commit and rollback hook callbacks are not reentrant.
   6669 ** The callback implementation must not do anything that will modify
   6670 ** the database connection that invoked the callback.  Any actions
   6671 ** to modify the database connection must be deferred until after the
   6672 ** completion of the [sqlite3_step()] call that triggered the commit
   6673 ** or rollback hook in the first place.
   6674 ** Note that running any other SQL statements, including SELECT statements,
   6675 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
   6676 ** the database connections for the meaning of "modify" in this paragraph.
   6677 **
   6678 ** ^Registering a NULL function disables the callback.
   6679 **
   6680 ** ^When the commit hook callback routine returns zero, the [COMMIT]
   6681 ** operation is allowed to continue normally.  ^If the commit hook
   6682 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
   6683 ** ^The rollback hook is invoked on a rollback that results from a commit
   6684 ** hook returning non-zero, just as it would be with any other rollback.
   6685 **
   6686 ** ^For the purposes of this API, a transaction is said to have been
   6687 ** rolled back if an explicit "ROLLBACK" statement is executed, or
   6688 ** an error or constraint causes an implicit rollback to occur.
   6689 ** ^The rollback callback is not invoked if a transaction is
   6690 ** automatically rolled back because the database connection is closed.
   6691 **
   6692 ** See also the [sqlite3_update_hook()] interface.
   6693 */
   6694 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
   6695 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
   6696 
   6697 /*
   6698 ** CAPI3REF: Data Change Notification Callbacks
   6699 ** METHOD: sqlite3
   6700 **
   6701 ** ^The sqlite3_update_hook() interface registers a callback function
   6702 ** with the [database connection] identified by the first argument
   6703 ** to be invoked whenever a row is updated, inserted or deleted in
   6704 ** a [rowid table].
   6705 ** ^Any callback set by a previous call to this function
   6706 ** for the same database connection is overridden.
   6707 **
   6708 ** ^The second argument is a pointer to the function to invoke when a
   6709 ** row is updated, inserted or deleted in a rowid table.
   6710 ** ^The first argument to the callback is a copy of the third argument
   6711 ** to sqlite3_update_hook().
   6712 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
   6713 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
   6714 ** to be invoked.
   6715 ** ^The third and fourth arguments to the callback contain pointers to the
   6716 ** database and table name containing the affected row.
   6717 ** ^The final callback parameter is the [rowid] of the row.
   6718 ** ^In the case of an update, this is the [rowid] after the update takes place.
   6719 **
   6720 ** ^(The update hook is not invoked when internal system tables are
   6721 ** modified (i.e. sqlite_master and sqlite_sequence).)^
   6722 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
   6723 **
   6724 ** ^In the current implementation, the update hook
   6725 ** is not invoked when conflicting rows are deleted because of an
   6726 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
   6727 ** invoked when rows are deleted using the [truncate optimization].
   6728 ** The exceptions defined in this paragraph might change in a future
   6729 ** release of SQLite.
   6730 **
   6731 ** The update hook implementation must not do anything that will modify
   6732 ** the database connection that invoked the update hook.  Any actions
   6733 ** to modify the database connection must be deferred until after the
   6734 ** completion of the [sqlite3_step()] call that triggered the update hook.
   6735 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   6736 ** database connections for the meaning of "modify" in this paragraph.
   6737 **
   6738 ** ^The sqlite3_update_hook(D,C,P) function
   6739 ** returns the P argument from the previous call
   6740 ** on the same [database connection] D, or NULL for
   6741 ** the first call on D.
   6742 **
   6743 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
   6744 ** and [sqlite3_preupdate_hook()] interfaces.
   6745 */
   6746 SQLITE_API void *sqlite3_update_hook(
   6747   sqlite3*,
   6748   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   6749   void*
   6750 );
   6751 
   6752 /*
   6753 ** CAPI3REF: Enable Or Disable Shared Pager Cache
   6754 **
   6755 ** ^(This routine enables or disables the sharing of the database cache
   6756 ** and schema data structures between [database connection | connections]
   6757 ** to the same database. Sharing is enabled if the argument is true
   6758 ** and disabled if the argument is false.)^
   6759 **
   6760 ** ^Cache sharing is enabled and disabled for an entire process.
   6761 ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
   6762 ** In prior versions of SQLite,
   6763 ** sharing was enabled or disabled for each thread separately.
   6764 **
   6765 ** ^(The cache sharing mode set by this interface effects all subsequent
   6766 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
   6767 ** Existing database connections continue use the sharing mode
   6768 ** that was in effect at the time they were opened.)^
   6769 **
   6770 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
   6771 ** successfully.  An [error code] is returned otherwise.)^
   6772 **
   6773 ** ^Shared cache is disabled by default. But this might change in
   6774 ** future releases of SQLite.  Applications that care about shared
   6775 ** cache setting should set it explicitly.
   6776 **
   6777 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
   6778 ** and will always return SQLITE_MISUSE. On those systems,
   6779 ** shared cache mode should be enabled per-database connection via
   6780 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
   6781 **
   6782 ** This interface is threadsafe on processors where writing a
   6783 ** 32-bit integer is atomic.
   6784 **
   6785 ** See Also:  [SQLite Shared-Cache Mode]
   6786 */
   6787 SQLITE_API int sqlite3_enable_shared_cache(int);
   6788 
   6789 /*
   6790 ** CAPI3REF: Attempt To Free Heap Memory
   6791 **
   6792 ** ^The sqlite3_release_memory() interface attempts to free N bytes
   6793 ** of heap memory by deallocating non-essential memory allocations
   6794 ** held by the database library.   Memory used to cache database
   6795 ** pages to improve performance is an example of non-essential memory.
   6796 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
   6797 ** which might be more or less than the amount requested.
   6798 ** ^The sqlite3_release_memory() routine is a no-op returning zero
   6799 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   6800 **
   6801 ** See also: [sqlite3_db_release_memory()]
   6802 */
   6803 SQLITE_API int sqlite3_release_memory(int);
   6804 
   6805 /*
   6806 ** CAPI3REF: Free Memory Used By A Database Connection
   6807 ** METHOD: sqlite3
   6808 **
   6809 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
   6810 ** memory as possible from database connection D. Unlike the
   6811 ** [sqlite3_release_memory()] interface, this interface is in effect even
   6812 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
   6813 ** omitted.
   6814 **
   6815 ** See also: [sqlite3_release_memory()]
   6816 */
   6817 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
   6818 
   6819 /*
   6820 ** CAPI3REF: Impose A Limit On Heap Size
   6821 **
   6822 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
   6823 ** soft limit on the amount of heap memory that may be allocated by SQLite.
   6824 ** ^SQLite strives to keep heap memory utilization below the soft heap
   6825 ** limit by reducing the number of pages held in the page cache
   6826 ** as heap memory usages approaches the limit.
   6827 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
   6828 ** below the limit, it will exceed the limit rather than generate
   6829 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
   6830 ** is advisory only.
   6831 **
   6832 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
   6833 ** the soft heap limit prior to the call, or negative in the case of an
   6834 ** error.  ^If the argument N is negative
   6835 ** then no change is made to the soft heap limit.  Hence, the current
   6836 ** size of the soft heap limit can be determined by invoking
   6837 ** sqlite3_soft_heap_limit64() with a negative argument.
   6838 **
   6839 ** ^If the argument N is zero then the soft heap limit is disabled.
   6840 **
   6841 ** ^(The soft heap limit is not enforced in the current implementation
   6842 ** if one or more of following conditions are true:
   6843 **
   6844 ** <ul>
   6845 ** <li> The soft heap limit is set to zero.
   6846 ** <li> Memory accounting is disabled using a combination of the
   6847 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
   6848 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
   6849 ** <li> An alternative page cache implementation is specified using
   6850 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
   6851 ** <li> The page cache allocates from its own memory pool supplied
   6852 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
   6853 **      from the heap.
   6854 ** </ul>)^
   6855 **
   6856 ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
   6857 ** the soft heap limit is enforced
   6858 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
   6859 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
   6860 ** the soft heap limit is enforced on every memory allocation.  Without
   6861 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
   6862 ** when memory is allocated by the page cache.  Testing suggests that because
   6863 ** the page cache is the predominate memory user in SQLite, most
   6864 ** applications will achieve adequate soft heap limit enforcement without
   6865 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   6866 **
   6867 ** The circumstances under which SQLite will enforce the soft heap limit may
   6868 ** changes in future releases of SQLite.
   6869 */
   6870 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
   6871 
   6872 /*
   6873 ** CAPI3REF: Deprecated Soft Heap Limit Interface
   6874 ** DEPRECATED
   6875 **
   6876 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
   6877 ** interface.  This routine is provided for historical compatibility
   6878 ** only.  All new applications should use the
   6879 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
   6880 */
   6881 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
   6882 
   6883 
   6884 /*
   6885 ** CAPI3REF: Extract Metadata About A Column Of A Table
   6886 ** METHOD: sqlite3
   6887 **
   6888 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
   6889 ** information about column C of table T in database D
   6890 ** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
   6891 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
   6892 ** the final five arguments with appropriate values if the specified
   6893 ** column exists.  ^The sqlite3_table_column_metadata() interface returns
   6894 ** SQLITE_ERROR and if the specified column does not exist.
   6895 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
   6896 ** NULL pointer, then this routine simply checks for the existence of the
   6897 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
   6898 ** does not.  If the table name parameter T in a call to
   6899 ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
   6900 ** undefined behavior.
   6901 **
   6902 ** ^The column is identified by the second, third and fourth parameters to
   6903 ** this function. ^(The second parameter is either the name of the database
   6904 ** (i.e. "main", "temp", or an attached database) containing the specified
   6905 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
   6906 ** for the table using the same algorithm used by the database engine to
   6907 ** resolve unqualified table references.
   6908 **
   6909 ** ^The third and fourth parameters to this function are the table and column
   6910 ** name of the desired column, respectively.
   6911 **
   6912 ** ^Metadata is returned by writing to the memory locations passed as the 5th
   6913 ** and subsequent parameters to this function. ^Any of these arguments may be
   6914 ** NULL, in which case the corresponding element of metadata is omitted.
   6915 **
   6916 ** ^(<blockquote>
   6917 ** <table border="1">
   6918 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
   6919 **
   6920 ** <tr><td> 5th <td> const char* <td> Data type
   6921 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
   6922 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
   6923 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
   6924 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
   6925 ** </table>
   6926 ** </blockquote>)^
   6927 **
   6928 ** ^The memory pointed to by the character pointers returned for the
   6929 ** declaration type and collation sequence is valid until the next
   6930 ** call to any SQLite API function.
   6931 **
   6932 ** ^If the specified table is actually a view, an [error code] is returned.
   6933 **
   6934 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
   6935 ** is not a [WITHOUT ROWID] table and an
   6936 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
   6937 ** parameters are set for the explicitly declared column. ^(If there is no
   6938 ** [INTEGER PRIMARY KEY] column, then the outputs
   6939 ** for the [rowid] are set as follows:
   6940 **
   6941 ** <pre>
   6942 **     data type: "INTEGER"
   6943 **     collation sequence: "BINARY"
   6944 **     not null: 0
   6945 **     primary key: 1
   6946 **     auto increment: 0
   6947 ** </pre>)^
   6948 **
   6949 ** ^This function causes all database schemas to be read from disk and
   6950 ** parsed, if that has not already been done, and returns an error if
   6951 ** any errors are encountered while loading the schema.
   6952 */
   6953 SQLITE_API int sqlite3_table_column_metadata(
   6954   sqlite3 *db,                /* Connection handle */
   6955   const char *zDbName,        /* Database name or NULL */
   6956   const char *zTableName,     /* Table name */
   6957   const char *zColumnName,    /* Column name */
   6958   char const **pzDataType,    /* OUTPUT: Declared data type */
   6959   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   6960   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   6961   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   6962   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   6963 );
   6964 
   6965 /*
   6966 ** CAPI3REF: Load An Extension
   6967 ** METHOD: sqlite3
   6968 **
   6969 ** ^This interface loads an SQLite extension library from the named file.
   6970 **
   6971 ** ^The sqlite3_load_extension() interface attempts to load an
   6972 ** [SQLite extension] library contained in the file zFile.  If
   6973 ** the file cannot be loaded directly, attempts are made to load
   6974 ** with various operating-system specific extensions added.
   6975 ** So for example, if "samplelib" cannot be loaded, then names like
   6976 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
   6977 ** be tried also.
   6978 **
   6979 ** ^The entry point is zProc.
   6980 ** ^(zProc may be 0, in which case SQLite will try to come up with an
   6981 ** entry point name on its own.  It first tries "sqlite3_extension_init".
   6982 ** If that does not work, it constructs a name "sqlite3_X_init" where the
   6983 ** X is consists of the lower-case equivalent of all ASCII alphabetic
   6984 ** characters in the filename from the last "/" to the first following
   6985 ** "." and omitting any initial "lib".)^
   6986 ** ^The sqlite3_load_extension() interface returns
   6987 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
   6988 ** ^If an error occurs and pzErrMsg is not 0, then the
   6989 ** [sqlite3_load_extension()] interface shall attempt to
   6990 ** fill *pzErrMsg with error message text stored in memory
   6991 ** obtained from [sqlite3_malloc()]. The calling function
   6992 ** should free this memory by calling [sqlite3_free()].
   6993 **
   6994 ** ^Extension loading must be enabled using
   6995 ** [sqlite3_enable_load_extension()] or
   6996 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
   6997 ** prior to calling this API,
   6998 ** otherwise an error will be returned.
   6999 **
   7000 ** <b>Security warning:</b> It is recommended that the
   7001 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
   7002 ** interface.  The use of the [sqlite3_enable_load_extension()] interface
   7003 ** should be avoided.  This will keep the SQL function [load_extension()]
   7004 ** disabled and prevent SQL injections from giving attackers
   7005 ** access to extension loading capabilities.
   7006 **
   7007 ** See also the [load_extension() SQL function].
   7008 */
   7009 SQLITE_API int sqlite3_load_extension(
   7010   sqlite3 *db,          /* Load the extension into this database connection */
   7011   const char *zFile,    /* Name of the shared library containing extension */
   7012   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
   7013   char **pzErrMsg       /* Put error message here if not 0 */
   7014 );
   7015 
   7016 /*
   7017 ** CAPI3REF: Enable Or Disable Extension Loading
   7018 ** METHOD: sqlite3
   7019 **
   7020 ** ^So as not to open security holes in older applications that are
   7021 ** unprepared to deal with [extension loading], and as a means of disabling
   7022 ** [extension loading] while evaluating user-entered SQL, the following API
   7023 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
   7024 **
   7025 ** ^Extension loading is off by default.
   7026 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
   7027 ** to turn extension loading on and call it with onoff==0 to turn
   7028 ** it back off again.
   7029 **
   7030 ** ^This interface enables or disables both the C-API
   7031 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
   7032 ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
   7033 ** to enable or disable only the C-API.)^
   7034 **
   7035 ** <b>Security warning:</b> It is recommended that extension loading
   7036 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
   7037 ** rather than this interface, so the [load_extension()] SQL function
   7038 ** remains disabled. This will prevent SQL injections from giving attackers
   7039 ** access to extension loading capabilities.
   7040 */
   7041 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
   7042 
   7043 /*
   7044 ** CAPI3REF: Automatically Load Statically Linked Extensions
   7045 **
   7046 ** ^This interface causes the xEntryPoint() function to be invoked for
   7047 ** each new [database connection] that is created.  The idea here is that
   7048 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
   7049 ** that is to be automatically loaded into all new database connections.
   7050 **
   7051 ** ^(Even though the function prototype shows that xEntryPoint() takes
   7052 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
   7053 ** arguments and expects an integer result as if the signature of the
   7054 ** entry point where as follows:
   7055 **
   7056 ** <blockquote><pre>
   7057 ** &nbsp;  int xEntryPoint(
   7058 ** &nbsp;    sqlite3 *db,
   7059 ** &nbsp;    const char **pzErrMsg,
   7060 ** &nbsp;    const struct sqlite3_api_routines *pThunk
   7061 ** &nbsp;  );
   7062 ** </pre></blockquote>)^
   7063 **
   7064 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
   7065 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
   7066 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
   7067 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
   7068 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
   7069 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
   7070 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
   7071 **
   7072 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
   7073 ** on the list of automatic extensions is a harmless no-op. ^No entry point
   7074 ** will be called more than once for each database connection that is opened.
   7075 **
   7076 ** See also: [sqlite3_reset_auto_extension()]
   7077 ** and [sqlite3_cancel_auto_extension()]
   7078 */
   7079 SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
   7080 
   7081 /*
   7082 ** CAPI3REF: Cancel Automatic Extension Loading
   7083 **
   7084 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
   7085 ** initialization routine X that was registered using a prior call to
   7086 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
   7087 ** routine returns 1 if initialization routine X was successfully
   7088 ** unregistered and it returns 0 if X was not on the list of initialization
   7089 ** routines.
   7090 */
   7091 SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
   7092 
   7093 /*
   7094 ** CAPI3REF: Reset Automatic Extension Loading
   7095 **
   7096 ** ^This interface disables all automatic extensions previously
   7097 ** registered using [sqlite3_auto_extension()].
   7098 */
   7099 SQLITE_API void sqlite3_reset_auto_extension(void);
   7100 
   7101 /*
   7102 ** The interface to the virtual-table mechanism is currently considered
   7103 ** to be experimental.  The interface might change in incompatible ways.
   7104 ** If this is a problem for you, do not use the interface at this time.
   7105 **
   7106 ** When the virtual-table mechanism stabilizes, we will declare the
   7107 ** interface fixed, support it indefinitely, and remove this comment.
   7108 */
   7109 
   7110 /*
   7111 ** Structures used by the virtual table interface
   7112 */
   7113 typedef struct sqlite3_vtab sqlite3_vtab;
   7114 typedef struct sqlite3_index_info sqlite3_index_info;
   7115 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
   7116 typedef struct sqlite3_module sqlite3_module;
   7117 
   7118 /*
   7119 ** CAPI3REF: Virtual Table Object
   7120 ** KEYWORDS: sqlite3_module {virtual table module}
   7121 **
   7122 ** This structure, sometimes called a "virtual table module",
   7123 ** defines the implementation of a [virtual tables].
   7124 ** This structure consists mostly of methods for the module.
   7125 **
   7126 ** ^A virtual table module is created by filling in a persistent
   7127 ** instance of this structure and passing a pointer to that instance
   7128 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
   7129 ** ^The registration remains valid until it is replaced by a different
   7130 ** module or until the [database connection] closes.  The content
   7131 ** of this structure must not change while it is registered with
   7132 ** any database connection.
   7133 */
   7134 struct sqlite3_module {
   7135   int iVersion;
   7136   int (*xCreate)(sqlite3*, void *pAux,
   7137                int argc, const char *const*argv,
   7138                sqlite3_vtab **ppVTab, char**);
   7139   int (*xConnect)(sqlite3*, void *pAux,
   7140                int argc, const char *const*argv,
   7141                sqlite3_vtab **ppVTab, char**);
   7142   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
   7143   int (*xDisconnect)(sqlite3_vtab *pVTab);
   7144   int (*xDestroy)(sqlite3_vtab *pVTab);
   7145   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
   7146   int (*xClose)(sqlite3_vtab_cursor*);
   7147   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
   7148                 int argc, sqlite3_value **argv);
   7149   int (*xNext)(sqlite3_vtab_cursor*);
   7150   int (*xEof)(sqlite3_vtab_cursor*);
   7151   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
   7152   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
   7153   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
   7154   int (*xBegin)(sqlite3_vtab *pVTab);
   7155   int (*xSync)(sqlite3_vtab *pVTab);
   7156   int (*xCommit)(sqlite3_vtab *pVTab);
   7157   int (*xRollback)(sqlite3_vtab *pVTab);
   7158   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
   7159                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
   7160                        void **ppArg);
   7161   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
   7162   /* The methods above are in version 1 of the sqlite_module object. Those
   7163   ** below are for version 2 and greater. */
   7164   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
   7165   int (*xRelease)(sqlite3_vtab *pVTab, int);
   7166   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
   7167 };
   7168 
   7169 /*
   7170 ** CAPI3REF: Virtual Table Indexing Information
   7171 ** KEYWORDS: sqlite3_index_info
   7172 **
   7173 ** The sqlite3_index_info structure and its substructures is used as part
   7174 ** of the [virtual table] interface to
   7175 ** pass information into and receive the reply from the [xBestIndex]
   7176 ** method of a [virtual table module].  The fields under **Inputs** are the
   7177 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
   7178 ** results into the **Outputs** fields.
   7179 **
   7180 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
   7181 **
   7182 ** <blockquote>column OP expr</blockquote>
   7183 **
   7184 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
   7185 ** stored in aConstraint[].op using one of the
   7186 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
   7187 ** ^(The index of the column is stored in
   7188 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
   7189 ** expr on the right-hand side can be evaluated (and thus the constraint
   7190 ** is usable) and false if it cannot.)^
   7191 **
   7192 ** ^The optimizer automatically inverts terms of the form "expr OP column"
   7193 ** and makes other simplifications to the WHERE clause in an attempt to
   7194 ** get as many WHERE clause terms into the form shown above as possible.
   7195 ** ^The aConstraint[] array only reports WHERE clause terms that are
   7196 ** relevant to the particular virtual table being queried.
   7197 **
   7198 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
   7199 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
   7200 **
   7201 ** The colUsed field indicates which columns of the virtual table may be
   7202 ** required by the current scan. Virtual table columns are numbered from
   7203 ** zero in the order in which they appear within the CREATE TABLE statement
   7204 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
   7205 ** the corresponding bit is set within the colUsed mask if the column may be
   7206 ** required by SQLite. If the table has at least 64 columns and any column
   7207 ** to the right of the first 63 is required, then bit 63 of colUsed is also
   7208 ** set. In other words, column iCol may be required if the expression
   7209 ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
   7210 ** non-zero.
   7211 **
   7212 ** The [xBestIndex] method must fill aConstraintUsage[] with information
   7213 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
   7214 ** the right-hand side of the corresponding aConstraint[] is evaluated
   7215 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
   7216 ** is true, then the constraint is assumed to be fully handled by the
   7217 ** virtual table and is not checked again by SQLite.)^
   7218 **
   7219 ** ^The idxNum and idxPtr values are recorded and passed into the
   7220 ** [xFilter] method.
   7221 ** ^[sqlite3_free()] is used to free idxPtr if and only if
   7222 ** needToFreeIdxPtr is true.
   7223 **
   7224 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
   7225 ** the correct order to satisfy the ORDER BY clause so that no separate
   7226 ** sorting step is required.
   7227 **
   7228 ** ^The estimatedCost value is an estimate of the cost of a particular
   7229 ** strategy. A cost of N indicates that the cost of the strategy is similar
   7230 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
   7231 ** indicates that the expense of the operation is similar to that of a
   7232 ** binary search on a unique indexed field of an SQLite table with N rows.
   7233 **
   7234 ** ^The estimatedRows value is an estimate of the number of rows that
   7235 ** will be returned by the strategy.
   7236 **
   7237 ** The xBestIndex method may optionally populate the idxFlags field with a
   7238 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
   7239 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
   7240 ** assumes that the strategy may visit at most one row.
   7241 **
   7242 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
   7243 ** SQLite also assumes that if a call to the xUpdate() method is made as
   7244 ** part of the same statement to delete or update a virtual table row and the
   7245 ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
   7246 ** any database changes. In other words, if the xUpdate() returns
   7247 ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
   7248 ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
   7249 ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
   7250 ** the xUpdate method are automatically rolled back by SQLite.
   7251 **
   7252 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
   7253 ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
   7254 ** If a virtual table extension is
   7255 ** used with an SQLite version earlier than 3.8.2, the results of attempting
   7256 ** to read or write the estimatedRows field are undefined (but are likely
   7257 ** to included crashing the application). The estimatedRows field should
   7258 ** therefore only be used if [sqlite3_libversion_number()] returns a
   7259 ** value greater than or equal to 3008002. Similarly, the idxFlags field
   7260 ** was added for [version 3.9.0] ([dateof:3.9.0]).
   7261 ** It may therefore only be used if
   7262 ** sqlite3_libversion_number() returns a value greater than or equal to
   7263 ** 3009000.
   7264 */
   7265 struct sqlite3_index_info {
   7266   /* Inputs */
   7267   int nConstraint;           /* Number of entries in aConstraint */
   7268   struct sqlite3_index_constraint {
   7269      int iColumn;              /* Column constrained.  -1 for ROWID */
   7270      unsigned char op;         /* Constraint operator */
   7271      unsigned char usable;     /* True if this constraint is usable */
   7272      int iTermOffset;          /* Used internally - xBestIndex should ignore */
   7273   } *aConstraint;            /* Table of WHERE clause constraints */
   7274   int nOrderBy;              /* Number of terms in the ORDER BY clause */
   7275   struct sqlite3_index_orderby {
   7276      int iColumn;              /* Column number */
   7277      unsigned char desc;       /* True for DESC.  False for ASC. */
   7278   } *aOrderBy;               /* The ORDER BY clause */
   7279   /* Outputs */
   7280   struct sqlite3_index_constraint_usage {
   7281     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
   7282     unsigned char omit;      /* Do not code a test for this constraint */
   7283   } *aConstraintUsage;
   7284   int idxNum;                /* Number used to identify the index */
   7285   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
   7286   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
   7287   int orderByConsumed;       /* True if output is already ordered */
   7288   double estimatedCost;           /* Estimated cost of using this index */
   7289   /* Fields below are only available in SQLite 3.8.2 and later */
   7290   sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
   7291   /* Fields below are only available in SQLite 3.9.0 and later */
   7292   int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
   7293   /* Fields below are only available in SQLite 3.10.0 and later */
   7294   sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
   7295 };
   7296 
   7297 /*
   7298 ** CAPI3REF: Virtual Table Scan Flags
   7299 */
   7300 #define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
   7301 
   7302 /*
   7303 ** CAPI3REF: Virtual Table Constraint Operator Codes
   7304 **
   7305 ** These macros defined the allowed values for the
   7306 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
   7307 ** an operator that is part of a constraint term in the wHERE clause of
   7308 ** a query that uses a [virtual table].
   7309 */
   7310 #define SQLITE_INDEX_CONSTRAINT_EQ         2
   7311 #define SQLITE_INDEX_CONSTRAINT_GT         4
   7312 #define SQLITE_INDEX_CONSTRAINT_LE         8
   7313 #define SQLITE_INDEX_CONSTRAINT_LT        16
   7314 #define SQLITE_INDEX_CONSTRAINT_GE        32
   7315 #define SQLITE_INDEX_CONSTRAINT_MATCH     64
   7316 #define SQLITE_INDEX_CONSTRAINT_LIKE      65
   7317 #define SQLITE_INDEX_CONSTRAINT_GLOB      66
   7318 #define SQLITE_INDEX_CONSTRAINT_REGEXP    67
   7319 #define SQLITE_INDEX_CONSTRAINT_NE        68
   7320 #define SQLITE_INDEX_CONSTRAINT_ISNOT     69
   7321 #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
   7322 #define SQLITE_INDEX_CONSTRAINT_ISNULL    71
   7323 #define SQLITE_INDEX_CONSTRAINT_IS        72
   7324 
   7325 /*
   7326 ** CAPI3REF: Register A Virtual Table Implementation
   7327 ** METHOD: sqlite3
   7328 **
   7329 ** ^These routines are used to register a new [virtual table module] name.
   7330 ** ^Module names must be registered before
   7331 ** creating a new [virtual table] using the module and before using a
   7332 ** preexisting [virtual table] for the module.
   7333 **
   7334 ** ^The module name is registered on the [database connection] specified
   7335 ** by the first parameter.  ^The name of the module is given by the
   7336 ** second parameter.  ^The third parameter is a pointer to
   7337 ** the implementation of the [virtual table module].   ^The fourth
   7338 ** parameter is an arbitrary client data pointer that is passed through
   7339 ** into the [xCreate] and [xConnect] methods of the virtual table module
   7340 ** when a new virtual table is be being created or reinitialized.
   7341 **
   7342 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
   7343 ** is a pointer to a destructor for the pClientData.  ^SQLite will
   7344 ** invoke the destructor function (if it is not NULL) when SQLite
   7345 ** no longer needs the pClientData pointer.  ^The destructor will also
   7346 ** be invoked if the call to sqlite3_create_module_v2() fails.
   7347 ** ^The sqlite3_create_module()
   7348 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
   7349 ** destructor.
   7350 */
   7351 SQLITE_API int sqlite3_create_module(
   7352   sqlite3 *db,               /* SQLite connection to register module with */
   7353   const char *zName,         /* Name of the module */
   7354   const sqlite3_module *p,   /* Methods for the module */
   7355   void *pClientData          /* Client data for xCreate/xConnect */
   7356 );
   7357 SQLITE_API int sqlite3_create_module_v2(
   7358   sqlite3 *db,               /* SQLite connection to register module with */
   7359   const char *zName,         /* Name of the module */
   7360   const sqlite3_module *p,   /* Methods for the module */
   7361   void *pClientData,         /* Client data for xCreate/xConnect */
   7362   void(*xDestroy)(void*)     /* Module destructor function */
   7363 );
   7364 
   7365 /*
   7366 ** CAPI3REF: Virtual Table Instance Object
   7367 ** KEYWORDS: sqlite3_vtab
   7368 **
   7369 ** Every [virtual table module] implementation uses a subclass
   7370 ** of this object to describe a particular instance
   7371 ** of the [virtual table].  Each subclass will
   7372 ** be tailored to the specific needs of the module implementation.
   7373 ** The purpose of this superclass is to define certain fields that are
   7374 ** common to all module implementations.
   7375 **
   7376 ** ^Virtual tables methods can set an error message by assigning a
   7377 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
   7378 ** take care that any prior string is freed by a call to [sqlite3_free()]
   7379 ** prior to assigning a new string to zErrMsg.  ^After the error message
   7380 ** is delivered up to the client application, the string will be automatically
   7381 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
   7382 */
   7383 struct sqlite3_vtab {
   7384   const sqlite3_module *pModule;  /* The module for this virtual table */
   7385   int nRef;                       /* Number of open cursors */
   7386   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
   7387   /* Virtual table implementations will typically add additional fields */
   7388 };
   7389 
   7390 /*
   7391 ** CAPI3REF: Virtual Table Cursor Object
   7392 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
   7393 **
   7394 ** Every [virtual table module] implementation uses a subclass of the
   7395 ** following structure to describe cursors that point into the
   7396 ** [virtual table] and are used
   7397 ** to loop through the virtual table.  Cursors are created using the
   7398 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
   7399 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
   7400 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
   7401 ** of the module.  Each module implementation will define
   7402 ** the content of a cursor structure to suit its own needs.
   7403 **
   7404 ** This superclass exists in order to define fields of the cursor that
   7405 ** are common to all implementations.
   7406 */
   7407 struct sqlite3_vtab_cursor {
   7408   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
   7409   /* Virtual table implementations will typically add additional fields */
   7410 };
   7411 
   7412 /*
   7413 ** CAPI3REF: Declare The Schema Of A Virtual Table
   7414 **
   7415 ** ^The [xCreate] and [xConnect] methods of a
   7416 ** [virtual table module] call this interface
   7417 ** to declare the format (the names and datatypes of the columns) of
   7418 ** the virtual tables they implement.
   7419 */
   7420 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
   7421 
   7422 /*
   7423 ** CAPI3REF: Overload A Function For A Virtual Table
   7424 ** METHOD: sqlite3
   7425 **
   7426 ** ^(Virtual tables can provide alternative implementations of functions
   7427 ** using the [xFindFunction] method of the [virtual table module].
   7428 ** But global versions of those functions
   7429 ** must exist in order to be overloaded.)^
   7430 **
   7431 ** ^(This API makes sure a global version of a function with a particular
   7432 ** name and number of parameters exists.  If no such function exists
   7433 ** before this API is called, a new function is created.)^  ^The implementation
   7434 ** of the new function always causes an exception to be thrown.  So
   7435 ** the new function is not good for anything by itself.  Its only
   7436 ** purpose is to be a placeholder function that can be overloaded
   7437 ** by a [virtual table].
   7438 */
   7439 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
   7440 
   7441 /*
   7442 ** The interface to the virtual-table mechanism defined above (back up
   7443 ** to a comment remarkably similar to this one) is currently considered
   7444 ** to be experimental.  The interface might change in incompatible ways.
   7445 ** If this is a problem for you, do not use the interface at this time.
   7446 **
   7447 ** When the virtual-table mechanism stabilizes, we will declare the
   7448 ** interface fixed, support it indefinitely, and remove this comment.
   7449 */
   7450 
   7451 /*
   7452 ** CAPI3REF: A Handle To An Open BLOB
   7453 ** KEYWORDS: {BLOB handle} {BLOB handles}
   7454 **
   7455 ** An instance of this object represents an open BLOB on which
   7456 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
   7457 ** ^Objects of this type are created by [sqlite3_blob_open()]
   7458 ** and destroyed by [sqlite3_blob_close()].
   7459 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
   7460 ** can be used to read or write small subsections of the BLOB.
   7461 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
   7462 */
   7463 typedef struct sqlite3_blob sqlite3_blob;
   7464 
   7465 /*
   7466 ** CAPI3REF: Open A BLOB For Incremental I/O
   7467 ** METHOD: sqlite3
   7468 ** CONSTRUCTOR: sqlite3_blob
   7469 **
   7470 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
   7471 ** in row iRow, column zColumn, table zTable in database zDb;
   7472 ** in other words, the same BLOB that would be selected by:
   7473 **
   7474 ** <pre>
   7475 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
   7476 ** </pre>)^
   7477 **
   7478 ** ^(Parameter zDb is not the filename that contains the database, but
   7479 ** rather the symbolic name of the database. For attached databases, this is
   7480 ** the name that appears after the AS keyword in the [ATTACH] statement.
   7481 ** For the main database file, the database name is "main". For TEMP
   7482 ** tables, the database name is "temp".)^
   7483 **
   7484 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
   7485 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
   7486 ** read-only access.
   7487 **
   7488 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
   7489 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
   7490 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
   7491 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
   7492 ** on *ppBlob after this function it returns.
   7493 **
   7494 ** This function fails with SQLITE_ERROR if any of the following are true:
   7495 ** <ul>
   7496 **   <li> ^(Database zDb does not exist)^,
   7497 **   <li> ^(Table zTable does not exist within database zDb)^,
   7498 **   <li> ^(Table zTable is a WITHOUT ROWID table)^,
   7499 **   <li> ^(Column zColumn does not exist)^,
   7500 **   <li> ^(Row iRow is not present in the table)^,
   7501 **   <li> ^(The specified column of row iRow contains a value that is not
   7502 **         a TEXT or BLOB value)^,
   7503 **   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
   7504 **         constraint and the blob is being opened for read/write access)^,
   7505 **   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
   7506 **         column zColumn is part of a [child key] definition and the blob is
   7507 **         being opened for read/write access)^.
   7508 ** </ul>
   7509 **
   7510 ** ^Unless it returns SQLITE_MISUSE, this function sets the
   7511 ** [database connection] error code and message accessible via
   7512 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
   7513 **
   7514 ** A BLOB referenced by sqlite3_blob_open() may be read using the
   7515 ** [sqlite3_blob_read()] interface and modified by using
   7516 ** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a
   7517 ** different row of the same table using the [sqlite3_blob_reopen()]
   7518 ** interface.  However, the column, table, or database of a [BLOB handle]
   7519 ** cannot be changed after the [BLOB handle] is opened.
   7520 **
   7521 ** ^(If the row that a BLOB handle points to is modified by an
   7522 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
   7523 ** then the BLOB handle is marked as "expired".
   7524 ** This is true if any column of the row is changed, even a column
   7525 ** other than the one the BLOB handle is open on.)^
   7526 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
   7527 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
   7528 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
   7529 ** rolled back by the expiration of the BLOB.  Such changes will eventually
   7530 ** commit if the transaction continues to completion.)^
   7531 **
   7532 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
   7533 ** the opened blob.  ^The size of a blob may not be changed by this
   7534 ** interface.  Use the [UPDATE] SQL command to change the size of a
   7535 ** blob.
   7536 **
   7537 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
   7538 ** and the built-in [zeroblob] SQL function may be used to create a
   7539 ** zero-filled blob to read or write using the incremental-blob interface.
   7540 **
   7541 ** To avoid a resource leak, every open [BLOB handle] should eventually
   7542 ** be released by a call to [sqlite3_blob_close()].
   7543 **
   7544 ** See also: [sqlite3_blob_close()],
   7545 ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
   7546 ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
   7547 */
   7548 SQLITE_API int sqlite3_blob_open(
   7549   sqlite3*,
   7550   const char *zDb,
   7551   const char *zTable,
   7552   const char *zColumn,
   7553   sqlite3_int64 iRow,
   7554   int flags,
   7555   sqlite3_blob **ppBlob
   7556 );
   7557 
   7558 /*
   7559 ** CAPI3REF: Move a BLOB Handle to a New Row
   7560 ** METHOD: sqlite3_blob
   7561 **
   7562 ** ^This function is used to move an existing [BLOB handle] so that it points
   7563 ** to a different row of the same database table. ^The new row is identified
   7564 ** by the rowid value passed as the second argument. Only the row can be
   7565 ** changed. ^The database, table and column on which the blob handle is open
   7566 ** remain the same. Moving an existing [BLOB handle] to a new row is
   7567 ** faster than closing the existing handle and opening a new one.
   7568 **
   7569 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
   7570 ** it must exist and there must be either a blob or text value stored in
   7571 ** the nominated column.)^ ^If the new row is not present in the table, or if
   7572 ** it does not contain a blob or text value, or if another error occurs, an
   7573 ** SQLite error code is returned and the blob handle is considered aborted.
   7574 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
   7575 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
   7576 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
   7577 ** always returns zero.
   7578 **
   7579 ** ^This function sets the database handle error code and message.
   7580 */
   7581 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
   7582 
   7583 /*
   7584 ** CAPI3REF: Close A BLOB Handle
   7585 ** DESTRUCTOR: sqlite3_blob
   7586 **
   7587 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
   7588 ** unconditionally.  Even if this routine returns an error code, the
   7589 ** handle is still closed.)^
   7590 **
   7591 ** ^If the blob handle being closed was opened for read-write access, and if
   7592 ** the database is in auto-commit mode and there are no other open read-write
   7593 ** blob handles or active write statements, the current transaction is
   7594 ** committed. ^If an error occurs while committing the transaction, an error
   7595 ** code is returned and the transaction rolled back.
   7596 **
   7597 ** Calling this function with an argument that is not a NULL pointer or an
   7598 ** open blob handle results in undefined behaviour. ^Calling this routine
   7599 ** with a null pointer (such as would be returned by a failed call to
   7600 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
   7601 ** is passed a valid open blob handle, the values returned by the
   7602 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
   7603 */
   7604 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
   7605 
   7606 /*
   7607 ** CAPI3REF: Return The Size Of An Open BLOB
   7608 ** METHOD: sqlite3_blob
   7609 **
   7610 ** ^Returns the size in bytes of the BLOB accessible via the
   7611 ** successfully opened [BLOB handle] in its only argument.  ^The
   7612 ** incremental blob I/O routines can only read or overwriting existing
   7613 ** blob content; they cannot change the size of a blob.
   7614 **
   7615 ** This routine only works on a [BLOB handle] which has been created
   7616 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   7617 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   7618 ** to this routine results in undefined and probably undesirable behavior.
   7619 */
   7620 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
   7621 
   7622 /*
   7623 ** CAPI3REF: Read Data From A BLOB Incrementally
   7624 ** METHOD: sqlite3_blob
   7625 **
   7626 ** ^(This function is used to read data from an open [BLOB handle] into a
   7627 ** caller-supplied buffer. N bytes of data are copied into buffer Z
   7628 ** from the open BLOB, starting at offset iOffset.)^
   7629 **
   7630 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   7631 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
   7632 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
   7633 ** ^The size of the blob (and hence the maximum value of N+iOffset)
   7634 ** can be determined using the [sqlite3_blob_bytes()] interface.
   7635 **
   7636 ** ^An attempt to read from an expired [BLOB handle] fails with an
   7637 ** error code of [SQLITE_ABORT].
   7638 **
   7639 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
   7640 ** Otherwise, an [error code] or an [extended error code] is returned.)^
   7641 **
   7642 ** This routine only works on a [BLOB handle] which has been created
   7643 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   7644 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   7645 ** to this routine results in undefined and probably undesirable behavior.
   7646 **
   7647 ** See also: [sqlite3_blob_write()].
   7648 */
   7649 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
   7650 
   7651 /*
   7652 ** CAPI3REF: Write Data Into A BLOB Incrementally
   7653 ** METHOD: sqlite3_blob
   7654 **
   7655 ** ^(This function is used to write data into an open [BLOB handle] from a
   7656 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
   7657 ** into the open BLOB, starting at offset iOffset.)^
   7658 **
   7659 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
   7660 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
   7661 ** ^Unless SQLITE_MISUSE is returned, this function sets the
   7662 ** [database connection] error code and message accessible via
   7663 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
   7664 **
   7665 ** ^If the [BLOB handle] passed as the first argument was not opened for
   7666 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
   7667 ** this function returns [SQLITE_READONLY].
   7668 **
   7669 ** This function may only modify the contents of the BLOB; it is
   7670 ** not possible to increase the size of a BLOB using this API.
   7671 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   7672 ** [SQLITE_ERROR] is returned and no data is written. The size of the
   7673 ** BLOB (and hence the maximum value of N+iOffset) can be determined
   7674 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
   7675 ** than zero [SQLITE_ERROR] is returned and no data is written.
   7676 **
   7677 ** ^An attempt to write to an expired [BLOB handle] fails with an
   7678 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
   7679 ** before the [BLOB handle] expired are not rolled back by the
   7680 ** expiration of the handle, though of course those changes might
   7681 ** have been overwritten by the statement that expired the BLOB handle
   7682 ** or by other independent statements.
   7683 **
   7684 ** This routine only works on a [BLOB handle] which has been created
   7685 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   7686 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   7687 ** to this routine results in undefined and probably undesirable behavior.
   7688 **
   7689 ** See also: [sqlite3_blob_read()].
   7690 */
   7691 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
   7692 
   7693 /*
   7694 ** CAPI3REF: Virtual File System Objects
   7695 **
   7696 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
   7697 ** that SQLite uses to interact
   7698 ** with the underlying operating system.  Most SQLite builds come with a
   7699 ** single default VFS that is appropriate for the host computer.
   7700 ** New VFSes can be registered and existing VFSes can be unregistered.
   7701 ** The following interfaces are provided.
   7702 **
   7703 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
   7704 ** ^Names are case sensitive.
   7705 ** ^Names are zero-terminated UTF-8 strings.
   7706 ** ^If there is no match, a NULL pointer is returned.
   7707 ** ^If zVfsName is NULL then the default VFS is returned.
   7708 **
   7709 ** ^New VFSes are registered with sqlite3_vfs_register().
   7710 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
   7711 ** ^The same VFS can be registered multiple times without injury.
   7712 ** ^To make an existing VFS into the default VFS, register it again
   7713 ** with the makeDflt flag set.  If two different VFSes with the
   7714 ** same name are registered, the behavior is undefined.  If a
   7715 ** VFS is registered with a name that is NULL or an empty string,
   7716 ** then the behavior is undefined.
   7717 **
   7718 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
   7719 ** ^(If the default VFS is unregistered, another VFS is chosen as
   7720 ** the default.  The choice for the new VFS is arbitrary.)^
   7721 */
   7722 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
   7723 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
   7724 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
   7725 
   7726 /*
   7727 ** CAPI3REF: Mutexes
   7728 **
   7729 ** The SQLite core uses these routines for thread
   7730 ** synchronization. Though they are intended for internal
   7731 ** use by SQLite, code that links against SQLite is
   7732 ** permitted to use any of these routines.
   7733 **
   7734 ** The SQLite source code contains multiple implementations
   7735 ** of these mutex routines.  An appropriate implementation
   7736 ** is selected automatically at compile-time.  The following
   7737 ** implementations are available in the SQLite core:
   7738 **
   7739 ** <ul>
   7740 ** <li>   SQLITE_MUTEX_PTHREADS
   7741 ** <li>   SQLITE_MUTEX_W32
   7742 ** <li>   SQLITE_MUTEX_NOOP
   7743 ** </ul>
   7744 **
   7745 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
   7746 ** that does no real locking and is appropriate for use in
   7747 ** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
   7748 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
   7749 ** and Windows.
   7750 **
   7751 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
   7752 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
   7753 ** implementation is included with the library. In this case the
   7754 ** application must supply a custom mutex implementation using the
   7755 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
   7756 ** before calling sqlite3_initialize() or any other public sqlite3_
   7757 ** function that calls sqlite3_initialize().
   7758 **
   7759 ** ^The sqlite3_mutex_alloc() routine allocates a new
   7760 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
   7761 ** routine returns NULL if it is unable to allocate the requested
   7762 ** mutex.  The argument to sqlite3_mutex_alloc() must one of these
   7763 ** integer constants:
   7764 **
   7765 ** <ul>
   7766 ** <li>  SQLITE_MUTEX_FAST
   7767 ** <li>  SQLITE_MUTEX_RECURSIVE
   7768 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   7769 ** <li>  SQLITE_MUTEX_STATIC_MEM
   7770 ** <li>  SQLITE_MUTEX_STATIC_OPEN
   7771 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   7772 ** <li>  SQLITE_MUTEX_STATIC_LRU
   7773 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   7774 ** <li>  SQLITE_MUTEX_STATIC_APP1
   7775 ** <li>  SQLITE_MUTEX_STATIC_APP2
   7776 ** <li>  SQLITE_MUTEX_STATIC_APP3
   7777 ** <li>  SQLITE_MUTEX_STATIC_VFS1
   7778 ** <li>  SQLITE_MUTEX_STATIC_VFS2
   7779 ** <li>  SQLITE_MUTEX_STATIC_VFS3
   7780 ** </ul>
   7781 **
   7782 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
   7783 ** cause sqlite3_mutex_alloc() to create
   7784 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   7785 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   7786 ** The mutex implementation does not need to make a distinction
   7787 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   7788 ** not want to.  SQLite will only request a recursive mutex in
   7789 ** cases where it really needs one.  If a faster non-recursive mutex
   7790 ** implementation is available on the host platform, the mutex subsystem
   7791 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   7792 **
   7793 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
   7794 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
   7795 ** a pointer to a static preexisting mutex.  ^Nine static mutexes are
   7796 ** used by the current version of SQLite.  Future versions of SQLite
   7797 ** may add additional static mutexes.  Static mutexes are for internal
   7798 ** use by SQLite only.  Applications that use SQLite mutexes should
   7799 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   7800 ** SQLITE_MUTEX_RECURSIVE.
   7801 **
   7802 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   7803 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   7804 ** returns a different mutex on every call.  ^For the static
   7805 ** mutex types, the same mutex is returned on every call that has
   7806 ** the same type number.
   7807 **
   7808 ** ^The sqlite3_mutex_free() routine deallocates a previously
   7809 ** allocated dynamic mutex.  Attempting to deallocate a static
   7810 ** mutex results in undefined behavior.
   7811 **
   7812 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   7813 ** to enter a mutex.  ^If another thread is already within the mutex,
   7814 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   7815 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
   7816 ** upon successful entry.  ^(Mutexes created using
   7817 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
   7818 ** In such cases, the
   7819 ** mutex must be exited an equal number of times before another thread
   7820 ** can enter.)^  If the same thread tries to enter any mutex other
   7821 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
   7822 **
   7823 ** ^(Some systems (for example, Windows 95) do not support the operation
   7824 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
   7825 ** will always return SQLITE_BUSY. The SQLite core only ever uses
   7826 ** sqlite3_mutex_try() as an optimization so this is acceptable
   7827 ** behavior.)^
   7828 **
   7829 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
   7830 ** previously entered by the same thread.   The behavior
   7831 ** is undefined if the mutex is not currently entered by the
   7832 ** calling thread or is not currently allocated.
   7833 **
   7834 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
   7835 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
   7836 ** behave as no-ops.
   7837 **
   7838 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
   7839 */
   7840 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
   7841 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
   7842 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
   7843 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
   7844 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
   7845 
   7846 /*
   7847 ** CAPI3REF: Mutex Methods Object
   7848 **
   7849 ** An instance of this structure defines the low-level routines
   7850 ** used to allocate and use mutexes.
   7851 **
   7852 ** Usually, the default mutex implementations provided by SQLite are
   7853 ** sufficient, however the application has the option of substituting a custom
   7854 ** implementation for specialized deployments or systems for which SQLite
   7855 ** does not provide a suitable implementation. In this case, the application
   7856 ** creates and populates an instance of this structure to pass
   7857 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
   7858 ** Additionally, an instance of this structure can be used as an
   7859 ** output variable when querying the system for the current mutex
   7860 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
   7861 **
   7862 ** ^The xMutexInit method defined by this structure is invoked as
   7863 ** part of system initialization by the sqlite3_initialize() function.
   7864 ** ^The xMutexInit routine is called by SQLite exactly once for each
   7865 ** effective call to [sqlite3_initialize()].
   7866 **
   7867 ** ^The xMutexEnd method defined by this structure is invoked as
   7868 ** part of system shutdown by the sqlite3_shutdown() function. The
   7869 ** implementation of this method is expected to release all outstanding
   7870 ** resources obtained by the mutex methods implementation, especially
   7871 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
   7872 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
   7873 **
   7874 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
   7875 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
   7876 ** xMutexNotheld) implement the following interfaces (respectively):
   7877 **
   7878 ** <ul>
   7879 **   <li>  [sqlite3_mutex_alloc()] </li>
   7880 **   <li>  [sqlite3_mutex_free()] </li>
   7881 **   <li>  [sqlite3_mutex_enter()] </li>
   7882 **   <li>  [sqlite3_mutex_try()] </li>
   7883 **   <li>  [sqlite3_mutex_leave()] </li>
   7884 **   <li>  [sqlite3_mutex_held()] </li>
   7885 **   <li>  [sqlite3_mutex_notheld()] </li>
   7886 ** </ul>)^
   7887 **
   7888 ** The only difference is that the public sqlite3_XXX functions enumerated
   7889 ** above silently ignore any invocations that pass a NULL pointer instead
   7890 ** of a valid mutex handle. The implementations of the methods defined
   7891 ** by this structure are not required to handle this case, the results
   7892 ** of passing a NULL pointer instead of a valid mutex handle are undefined
   7893 ** (i.e. it is acceptable to provide an implementation that segfaults if
   7894 ** it is passed a NULL pointer).
   7895 **
   7896 ** The xMutexInit() method must be threadsafe.  It must be harmless to
   7897 ** invoke xMutexInit() multiple times within the same process and without
   7898 ** intervening calls to xMutexEnd().  Second and subsequent calls to
   7899 ** xMutexInit() must be no-ops.
   7900 **
   7901 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
   7902 ** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
   7903 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
   7904 ** memory allocation for a fast or recursive mutex.
   7905 **
   7906 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
   7907 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
   7908 ** If xMutexInit fails in any way, it is expected to clean up after itself
   7909 ** prior to returning.
   7910 */
   7911 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
   7912 struct sqlite3_mutex_methods {
   7913   int (*xMutexInit)(void);
   7914   int (*xMutexEnd)(void);
   7915   sqlite3_mutex *(*xMutexAlloc)(int);
   7916   void (*xMutexFree)(sqlite3_mutex *);
   7917   void (*xMutexEnter)(sqlite3_mutex *);
   7918   int (*xMutexTry)(sqlite3_mutex *);
   7919   void (*xMutexLeave)(sqlite3_mutex *);
   7920   int (*xMutexHeld)(sqlite3_mutex *);
   7921   int (*xMutexNotheld)(sqlite3_mutex *);
   7922 };
   7923 
   7924 /*
   7925 ** CAPI3REF: Mutex Verification Routines
   7926 **
   7927 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
   7928 ** are intended for use inside assert() statements.  The SQLite core
   7929 ** never uses these routines except inside an assert() and applications
   7930 ** are advised to follow the lead of the core.  The SQLite core only
   7931 ** provides implementations for these routines when it is compiled
   7932 ** with the SQLITE_DEBUG flag.  External mutex implementations
   7933 ** are only required to provide these routines if SQLITE_DEBUG is
   7934 ** defined and if NDEBUG is not defined.
   7935 **
   7936 ** These routines should return true if the mutex in their argument
   7937 ** is held or not held, respectively, by the calling thread.
   7938 **
   7939 ** The implementation is not required to provide versions of these
   7940 ** routines that actually work. If the implementation does not provide working
   7941 ** versions of these routines, it should at least provide stubs that always
   7942 ** return true so that one does not get spurious assertion failures.
   7943 **
   7944 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
   7945 ** the routine should return 1.   This seems counter-intuitive since
   7946 ** clearly the mutex cannot be held if it does not exist.  But
   7947 ** the reason the mutex does not exist is because the build is not
   7948 ** using mutexes.  And we do not want the assert() containing the
   7949 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
   7950 ** the appropriate thing to do.  The sqlite3_mutex_notheld()
   7951 ** interface should also return 1 when given a NULL pointer.
   7952 */
   7953 #ifndef NDEBUG
   7954 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
   7955 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
   7956 #endif
   7957 
   7958 /*
   7959 ** CAPI3REF: Mutex Types
   7960 **
   7961 ** The [sqlite3_mutex_alloc()] interface takes a single argument
   7962 ** which is one of these integer constants.
   7963 **
   7964 ** The set of static mutexes may change from one SQLite release to the
   7965 ** next.  Applications that override the built-in mutex logic must be
   7966 ** prepared to accommodate additional static mutexes.
   7967 */
   7968 #define SQLITE_MUTEX_FAST             0
   7969 #define SQLITE_MUTEX_RECURSIVE        1
   7970 #define SQLITE_MUTEX_STATIC_MASTER    2
   7971 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
   7972 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
   7973 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
   7974 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */
   7975 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
   7976 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
   7977 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
   7978 #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
   7979 #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
   7980 #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
   7981 #define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
   7982 #define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
   7983 #define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
   7984 
   7985 /*
   7986 ** CAPI3REF: Retrieve the mutex for a database connection
   7987 ** METHOD: sqlite3
   7988 **
   7989 ** ^This interface returns a pointer the [sqlite3_mutex] object that
   7990 ** serializes access to the [database connection] given in the argument
   7991 ** when the [threading mode] is Serialized.
   7992 ** ^If the [threading mode] is Single-thread or Multi-thread then this
   7993 ** routine returns a NULL pointer.
   7994 */
   7995 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
   7996 
   7997 /*
   7998 ** CAPI3REF: Low-Level Control Of Database Files
   7999 ** METHOD: sqlite3
   8000 **
   8001 ** ^The [sqlite3_file_control()] interface makes a direct call to the
   8002 ** xFileControl method for the [sqlite3_io_methods] object associated
   8003 ** with a particular database identified by the second argument. ^The
   8004 ** name of the database is "main" for the main database or "temp" for the
   8005 ** TEMP database, or the name that appears after the AS keyword for
   8006 ** databases that are added using the [ATTACH] SQL command.
   8007 ** ^A NULL pointer can be used in place of "main" to refer to the
   8008 ** main database file.
   8009 ** ^The third and fourth parameters to this routine
   8010 ** are passed directly through to the second and third parameters of
   8011 ** the xFileControl method.  ^The return value of the xFileControl
   8012 ** method becomes the return value of this routine.
   8013 **
   8014 ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
   8015 ** a pointer to the underlying [sqlite3_file] object to be written into
   8016 ** the space pointed to by the 4th parameter.  ^The [SQLITE_FCNTL_FILE_POINTER]
   8017 ** case is a short-circuit path which does not actually invoke the
   8018 ** underlying sqlite3_io_methods.xFileControl method.
   8019 **
   8020 ** ^If the second parameter (zDbName) does not match the name of any
   8021 ** open database file, then SQLITE_ERROR is returned.  ^This error
   8022 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
   8023 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
   8024 ** also return SQLITE_ERROR.  There is no way to distinguish between
   8025 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
   8026 ** xFileControl method.
   8027 **
   8028 ** See also: [file control opcodes]
   8029 */
   8030 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
   8031 
   8032 /*
   8033 ** CAPI3REF: Testing Interface
   8034 **
   8035 ** ^The sqlite3_test_control() interface is used to read out internal
   8036 ** state of SQLite and to inject faults into SQLite for testing
   8037 ** purposes.  ^The first parameter is an operation code that determines
   8038 ** the number, meaning, and operation of all subsequent parameters.
   8039 **
   8040 ** This interface is not for use by applications.  It exists solely
   8041 ** for verifying the correct operation of the SQLite library.  Depending
   8042 ** on how the SQLite library is compiled, this interface might not exist.
   8043 **
   8044 ** The details of the operation codes, their meanings, the parameters
   8045 ** they take, and what they do are all subject to change without notice.
   8046 ** Unlike most of the SQLite API, this function is not guaranteed to
   8047 ** operate consistently from one release to the next.
   8048 */
   8049 SQLITE_API int sqlite3_test_control(int op, ...);
   8050 
   8051 /*
   8052 ** CAPI3REF: Testing Interface Operation Codes
   8053 **
   8054 ** These constants are the valid operation code parameters used
   8055 ** as the first argument to [sqlite3_test_control()].
   8056 **
   8057 ** These parameters and their meanings are subject to change
   8058 ** without notice.  These values are for testing purposes only.
   8059 ** Applications should not use any of these parameters or the
   8060 ** [sqlite3_test_control()] interface.
   8061 */
   8062 #define SQLITE_TESTCTRL_FIRST                    5
   8063 #define SQLITE_TESTCTRL_PRNG_SAVE                5
   8064 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
   8065 #define SQLITE_TESTCTRL_PRNG_RESET               7
   8066 #define SQLITE_TESTCTRL_BITVEC_TEST              8
   8067 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
   8068 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
   8069 #define SQLITE_TESTCTRL_PENDING_BYTE            11
   8070 #define SQLITE_TESTCTRL_ASSERT                  12
   8071 #define SQLITE_TESTCTRL_ALWAYS                  13
   8072 #define SQLITE_TESTCTRL_RESERVE                 14
   8073 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
   8074 #define SQLITE_TESTCTRL_ISKEYWORD               16
   8075 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */
   8076 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
   8077 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
   8078 #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19
   8079 #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
   8080 #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
   8081 #define SQLITE_TESTCTRL_BYTEORDER               22
   8082 #define SQLITE_TESTCTRL_ISINIT                  23
   8083 #define SQLITE_TESTCTRL_SORTER_MMAP             24
   8084 #define SQLITE_TESTCTRL_IMPOSTER                25
   8085 #define SQLITE_TESTCTRL_PARSER_COVERAGE         26
   8086 #define SQLITE_TESTCTRL_LAST                    26  /* Largest TESTCTRL */
   8087 
   8088 /*
   8089 ** CAPI3REF: SQLite Runtime Status
   8090 **
   8091 ** ^These interfaces are used to retrieve runtime status information
   8092 ** about the performance of SQLite, and optionally to reset various
   8093 ** highwater marks.  ^The first argument is an integer code for
   8094 ** the specific parameter to measure.  ^(Recognized integer codes
   8095 ** are of the form [status parameters | SQLITE_STATUS_...].)^
   8096 ** ^The current value of the parameter is returned into *pCurrent.
   8097 ** ^The highest recorded value is returned in *pHighwater.  ^If the
   8098 ** resetFlag is true, then the highest record value is reset after
   8099 ** *pHighwater is written.  ^(Some parameters do not record the highest
   8100 ** value.  For those parameters
   8101 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
   8102 ** ^(Other parameters record only the highwater mark and not the current
   8103 ** value.  For these latter parameters nothing is written into *pCurrent.)^
   8104 **
   8105 ** ^The sqlite3_status() and sqlite3_status64() routines return
   8106 ** SQLITE_OK on success and a non-zero [error code] on failure.
   8107 **
   8108 ** If either the current value or the highwater mark is too large to
   8109 ** be represented by a 32-bit integer, then the values returned by
   8110 ** sqlite3_status() are undefined.
   8111 **
   8112 ** See also: [sqlite3_db_status()]
   8113 */
   8114 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
   8115 SQLITE_API int sqlite3_status64(
   8116   int op,
   8117   sqlite3_int64 *pCurrent,
   8118   sqlite3_int64 *pHighwater,
   8119   int resetFlag
   8120 );
   8121 
   8122 
   8123 /*
   8124 ** CAPI3REF: Status Parameters
   8125 ** KEYWORDS: {status parameters}
   8126 **
   8127 ** These integer constants designate various run-time status parameters
   8128 ** that can be returned by [sqlite3_status()].
   8129 **
   8130 ** <dl>
   8131 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
   8132 ** <dd>This parameter is the current amount of memory checked out
   8133 ** using [sqlite3_malloc()], either directly or indirectly.  The
   8134 ** figure includes calls made to [sqlite3_malloc()] by the application
   8135 ** and internal memory usage by the SQLite library.  Auxiliary page-cache
   8136 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
   8137 ** this parameter.  The amount returned is the sum of the allocation
   8138 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
   8139 **
   8140 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
   8141 ** <dd>This parameter records the largest memory allocation request
   8142 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
   8143 ** internal equivalents).  Only the value returned in the
   8144 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   8145 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   8146 **
   8147 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
   8148 ** <dd>This parameter records the number of separate memory allocations
   8149 ** currently checked out.</dd>)^
   8150 **
   8151 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
   8152 ** <dd>This parameter returns the number of pages used out of the
   8153 ** [pagecache memory allocator] that was configured using
   8154 ** [SQLITE_CONFIG_PAGECACHE].  The
   8155 ** value returned is in pages, not in bytes.</dd>)^
   8156 **
   8157 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
   8158 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
   8159 ** <dd>This parameter returns the number of bytes of page cache
   8160 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
   8161 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
   8162 ** returned value includes allocations that overflowed because they
   8163 ** where too large (they were larger than the "sz" parameter to
   8164 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
   8165 ** no space was left in the page cache.</dd>)^
   8166 **
   8167 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
   8168 ** <dd>This parameter records the largest memory allocation request
   8169 ** handed to [pagecache memory allocator].  Only the value returned in the
   8170 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   8171 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   8172 **
   8173 ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
   8174 ** <dd>No longer used.</dd>
   8175 **
   8176 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
   8177 ** <dd>No longer used.</dd>
   8178 **
   8179 ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
   8180 ** <dd>No longer used.</dd>
   8181 **
   8182 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
   8183 ** <dd>The *pHighwater parameter records the deepest parser stack.
   8184 ** The *pCurrent value is undefined.  The *pHighwater value is only
   8185 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
   8186 ** </dl>
   8187 **
   8188 ** New status parameters may be added from time to time.
   8189 */
   8190 #define SQLITE_STATUS_MEMORY_USED          0
   8191 #define SQLITE_STATUS_PAGECACHE_USED       1
   8192 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
   8193 #define SQLITE_STATUS_SCRATCH_USED         3  /* NOT USED */
   8194 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4  /* NOT USED */
   8195 #define SQLITE_STATUS_MALLOC_SIZE          5
   8196 #define SQLITE_STATUS_PARSER_STACK         6
   8197 #define SQLITE_STATUS_PAGECACHE_SIZE       7
   8198 #define SQLITE_STATUS_SCRATCH_SIZE         8  /* NOT USED */
   8199 #define SQLITE_STATUS_MALLOC_COUNT         9
   8200 
   8201 /*
   8202 ** CAPI3REF: Database Connection Status
   8203 ** METHOD: sqlite3
   8204 **
   8205 ** ^This interface is used to retrieve runtime status information
   8206 ** about a single [database connection].  ^The first argument is the
   8207 ** database connection object to be interrogated.  ^The second argument
   8208 ** is an integer constant, taken from the set of
   8209 ** [SQLITE_DBSTATUS options], that
   8210 ** determines the parameter to interrogate.  The set of
   8211 ** [SQLITE_DBSTATUS options] is likely
   8212 ** to grow in future releases of SQLite.
   8213 **
   8214 ** ^The current value of the requested parameter is written into *pCur
   8215 ** and the highest instantaneous value is written into *pHiwtr.  ^If
   8216 ** the resetFlg is true, then the highest instantaneous value is
   8217 ** reset back down to the current value.
   8218 **
   8219 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
   8220 ** non-zero [error code] on failure.
   8221 **
   8222 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
   8223 */
   8224 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
   8225 
   8226 /*
   8227 ** CAPI3REF: Status Parameters for database connections
   8228 ** KEYWORDS: {SQLITE_DBSTATUS options}
   8229 **
   8230 ** These constants are the available integer "verbs" that can be passed as
   8231 ** the second argument to the [sqlite3_db_status()] interface.
   8232 **
   8233 ** New verbs may be added in future releases of SQLite. Existing verbs
   8234 ** might be discontinued. Applications should check the return code from
   8235 ** [sqlite3_db_status()] to make sure that the call worked.
   8236 ** The [sqlite3_db_status()] interface will return a non-zero error code
   8237 ** if a discontinued or unsupported verb is invoked.
   8238 **
   8239 ** <dl>
   8240 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
   8241 ** <dd>This parameter returns the number of lookaside memory slots currently
   8242 ** checked out.</dd>)^
   8243 **
   8244 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
   8245 ** <dd>This parameter returns the number malloc attempts that were
   8246 ** satisfied using lookaside memory. Only the high-water value is meaningful;
   8247 ** the current value is always zero.)^
   8248 **
   8249 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
   8250 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
   8251 ** <dd>This parameter returns the number malloc attempts that might have
   8252 ** been satisfied using lookaside memory but failed due to the amount of
   8253 ** memory requested being larger than the lookaside slot size.
   8254 ** Only the high-water value is meaningful;
   8255 ** the current value is always zero.)^
   8256 **
   8257 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
   8258 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
   8259 ** <dd>This parameter returns the number malloc attempts that might have
   8260 ** been satisfied using lookaside memory but failed due to all lookaside
   8261 ** memory already being in use.
   8262 ** Only the high-water value is meaningful;
   8263 ** the current value is always zero.)^
   8264 **
   8265 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
   8266 ** <dd>This parameter returns the approximate number of bytes of heap
   8267 ** memory used by all pager caches associated with the database connection.)^
   8268 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
   8269 **
   8270 ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
   8271 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
   8272 ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
   8273 ** pager cache is shared between two or more connections the bytes of heap
   8274 ** memory used by that pager cache is divided evenly between the attached
   8275 ** connections.)^  In other words, if none of the pager caches associated
   8276 ** with the database connection are shared, this request returns the same
   8277 ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
   8278 ** shared, the value returned by this call will be smaller than that returned
   8279 ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
   8280 ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
   8281 **
   8282 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
   8283 ** <dd>This parameter returns the approximate number of bytes of heap
   8284 ** memory used to store the schema for all databases associated
   8285 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
   8286 ** ^The full amount of memory used by the schemas is reported, even if the
   8287 ** schema memory is shared with other database connections due to
   8288 ** [shared cache mode] being enabled.
   8289 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
   8290 **
   8291 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
   8292 ** <dd>This parameter returns the approximate number of bytes of heap
   8293 ** and lookaside memory used by all prepared statements associated with
   8294 ** the database connection.)^
   8295 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
   8296 ** </dd>
   8297 **
   8298 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
   8299 ** <dd>This parameter returns the number of pager cache hits that have
   8300 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
   8301 ** is always 0.
   8302 ** </dd>
   8303 **
   8304 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
   8305 ** <dd>This parameter returns the number of pager cache misses that have
   8306 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
   8307 ** is always 0.
   8308 ** </dd>
   8309 **
   8310 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
   8311 ** <dd>This parameter returns the number of dirty cache entries that have
   8312 ** been written to disk. Specifically, the number of pages written to the
   8313 ** wal file in wal mode databases, or the number of pages written to the
   8314 ** database file in rollback mode databases. Any pages written as part of
   8315 ** transaction rollback or database recovery operations are not included.
   8316 ** If an IO or other error occurs while writing a page to disk, the effect
   8317 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
   8318 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
   8319 ** </dd>
   8320 **
   8321 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
   8322 ** <dd>This parameter returns zero for the current value if and only if
   8323 ** all foreign key constraints (deferred or immediate) have been
   8324 ** resolved.)^  ^The highwater mark is always 0.
   8325 ** </dd>
   8326 ** </dl>
   8327 */
   8328 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
   8329 #define SQLITE_DBSTATUS_CACHE_USED           1
   8330 #define SQLITE_DBSTATUS_SCHEMA_USED          2
   8331 #define SQLITE_DBSTATUS_STMT_USED            3
   8332 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
   8333 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
   8334 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
   8335 #define SQLITE_DBSTATUS_CACHE_HIT            7
   8336 #define SQLITE_DBSTATUS_CACHE_MISS           8
   8337 #define SQLITE_DBSTATUS_CACHE_WRITE          9
   8338 #define SQLITE_DBSTATUS_DEFERRED_FKS        10
   8339 #define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
   8340 #define SQLITE_DBSTATUS_MAX                 11   /* Largest defined DBSTATUS */
   8341 
   8342 
   8343 /*
   8344 ** CAPI3REF: Prepared Statement Status
   8345 ** METHOD: sqlite3_stmt
   8346 **
   8347 ** ^(Each prepared statement maintains various
   8348 ** [SQLITE_STMTSTATUS counters] that measure the number
   8349 ** of times it has performed specific operations.)^  These counters can
   8350 ** be used to monitor the performance characteristics of the prepared
   8351 ** statements.  For example, if the number of table steps greatly exceeds
   8352 ** the number of table searches or result rows, that would tend to indicate
   8353 ** that the prepared statement is using a full table scan rather than
   8354 ** an index.
   8355 **
   8356 ** ^(This interface is used to retrieve and reset counter values from
   8357 ** a [prepared statement].  The first argument is the prepared statement
   8358 ** object to be interrogated.  The second argument
   8359 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
   8360 ** to be interrogated.)^
   8361 ** ^The current value of the requested counter is returned.
   8362 ** ^If the resetFlg is true, then the counter is reset to zero after this
   8363 ** interface call returns.
   8364 **
   8365 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
   8366 */
   8367 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
   8368 
   8369 /*
   8370 ** CAPI3REF: Status Parameters for prepared statements
   8371 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
   8372 **
   8373 ** These preprocessor macros define integer codes that name counter
   8374 ** values associated with the [sqlite3_stmt_status()] interface.
   8375 ** The meanings of the various counters are as follows:
   8376 **
   8377 ** <dl>
   8378 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
   8379 ** <dd>^This is the number of times that SQLite has stepped forward in
   8380 ** a table as part of a full table scan.  Large numbers for this counter
   8381 ** may indicate opportunities for performance improvement through
   8382 ** careful use of indices.</dd>
   8383 **
   8384 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
   8385 ** <dd>^This is the number of sort operations that have occurred.
   8386 ** A non-zero value in this counter may indicate an opportunity to
   8387 ** improvement performance through careful use of indices.</dd>
   8388 **
   8389 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
   8390 ** <dd>^This is the number of rows inserted into transient indices that
   8391 ** were created automatically in order to help joins run faster.
   8392 ** A non-zero value in this counter may indicate an opportunity to
   8393 ** improvement performance by adding permanent indices that do not
   8394 ** need to be reinitialized each time the statement is run.</dd>
   8395 **
   8396 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
   8397 ** <dd>^This is the number of virtual machine operations executed
   8398 ** by the prepared statement if that number is less than or equal
   8399 ** to 2147483647.  The number of virtual machine operations can be
   8400 ** used as a proxy for the total work done by the prepared statement.
   8401 ** If the number of virtual machine operations exceeds 2147483647
   8402 ** then the value returned by this statement status code is undefined.
   8403 **
   8404 ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
   8405 ** <dd>^This is the number of times that the prepare statement has been
   8406 ** automatically regenerated due to schema changes or change to
   8407 ** [bound parameters] that might affect the query plan.
   8408 **
   8409 ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
   8410 ** <dd>^This is the number of times that the prepared statement has
   8411 ** been run.  A single "run" for the purposes of this counter is one
   8412 ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
   8413 ** The counter is incremented on the first [sqlite3_step()] call of each
   8414 ** cycle.
   8415 **
   8416 ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
   8417 ** <dd>^This is the approximate number of bytes of heap memory
   8418 ** used to store the prepared statement.  ^This value is not actually
   8419 ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
   8420 ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
   8421 ** </dd>
   8422 ** </dl>
   8423 */
   8424 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
   8425 #define SQLITE_STMTSTATUS_SORT              2
   8426 #define SQLITE_STMTSTATUS_AUTOINDEX         3
   8427 #define SQLITE_STMTSTATUS_VM_STEP           4
   8428 #define SQLITE_STMTSTATUS_REPREPARE         5
   8429 #define SQLITE_STMTSTATUS_RUN               6
   8430 #define SQLITE_STMTSTATUS_MEMUSED           99
   8431 
   8432 /*
   8433 ** CAPI3REF: Custom Page Cache Object
   8434 **
   8435 ** The sqlite3_pcache type is opaque.  It is implemented by
   8436 ** the pluggable module.  The SQLite core has no knowledge of
   8437 ** its size or internal structure and never deals with the
   8438 ** sqlite3_pcache object except by holding and passing pointers
   8439 ** to the object.
   8440 **
   8441 ** See [sqlite3_pcache_methods2] for additional information.
   8442 */
   8443 typedef struct sqlite3_pcache sqlite3_pcache;
   8444 
   8445 /*
   8446 ** CAPI3REF: Custom Page Cache Object
   8447 **
   8448 ** The sqlite3_pcache_page object represents a single page in the
   8449 ** page cache.  The page cache will allocate instances of this
   8450 ** object.  Various methods of the page cache use pointers to instances
   8451 ** of this object as parameters or as their return value.
   8452 **
   8453 ** See [sqlite3_pcache_methods2] for additional information.
   8454 */
   8455 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
   8456 struct sqlite3_pcache_page {
   8457   void *pBuf;        /* The content of the page */
   8458   void *pExtra;      /* Extra information associated with the page */
   8459 };
   8460 
   8461 /*
   8462 ** CAPI3REF: Application Defined Page Cache.
   8463 ** KEYWORDS: {page cache}
   8464 **
   8465 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
   8466 ** register an alternative page cache implementation by passing in an
   8467 ** instance of the sqlite3_pcache_methods2 structure.)^
   8468 ** In many applications, most of the heap memory allocated by
   8469 ** SQLite is used for the page cache.
   8470 ** By implementing a
   8471 ** custom page cache using this API, an application can better control
   8472 ** the amount of memory consumed by SQLite, the way in which
   8473 ** that memory is allocated and released, and the policies used to
   8474 ** determine exactly which parts of a database file are cached and for
   8475 ** how long.
   8476 **
   8477 ** The alternative page cache mechanism is an
   8478 ** extreme measure that is only needed by the most demanding applications.
   8479 ** The built-in page cache is recommended for most uses.
   8480 **
   8481 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
   8482 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
   8483 ** the application may discard the parameter after the call to
   8484 ** [sqlite3_config()] returns.)^
   8485 **
   8486 ** [[the xInit() page cache method]]
   8487 ** ^(The xInit() method is called once for each effective
   8488 ** call to [sqlite3_initialize()])^
   8489 ** (usually only once during the lifetime of the process). ^(The xInit()
   8490 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
   8491 ** The intent of the xInit() method is to set up global data structures
   8492 ** required by the custom page cache implementation.
   8493 ** ^(If the xInit() method is NULL, then the
   8494 ** built-in default page cache is used instead of the application defined
   8495 ** page cache.)^
   8496 **
   8497 ** [[the xShutdown() page cache method]]
   8498 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
   8499 ** It can be used to clean up
   8500 ** any outstanding resources before process shutdown, if required.
   8501 ** ^The xShutdown() method may be NULL.
   8502 **
   8503 ** ^SQLite automatically serializes calls to the xInit method,
   8504 ** so the xInit method need not be threadsafe.  ^The
   8505 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   8506 ** not need to be threadsafe either.  All other methods must be threadsafe
   8507 ** in multithreaded applications.
   8508 **
   8509 ** ^SQLite will never invoke xInit() more than once without an intervening
   8510 ** call to xShutdown().
   8511 **
   8512 ** [[the xCreate() page cache methods]]
   8513 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
   8514 ** SQLite will typically create one cache instance for each open database file,
   8515 ** though this is not guaranteed. ^The
   8516 ** first parameter, szPage, is the size in bytes of the pages that must
   8517 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
   8518 ** second parameter szExtra is a number of bytes of extra storage
   8519 ** associated with each page cache entry.  ^The szExtra parameter will
   8520 ** a number less than 250.  SQLite will use the
   8521 ** extra szExtra bytes on each page to store metadata about the underlying
   8522 ** database page on disk.  The value passed into szExtra depends
   8523 ** on the SQLite version, the target platform, and how SQLite was compiled.
   8524 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
   8525 ** created will be used to cache database pages of a file stored on disk, or
   8526 ** false if it is used for an in-memory database. The cache implementation
   8527 ** does not have to do anything special based with the value of bPurgeable;
   8528 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
   8529 ** never invoke xUnpin() except to deliberately delete a page.
   8530 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
   8531 ** false will always have the "discard" flag set to true.
   8532 ** ^Hence, a cache created with bPurgeable false will
   8533 ** never contain any unpinned pages.
   8534 **
   8535 ** [[the xCachesize() page cache method]]
   8536 ** ^(The xCachesize() method may be called at any time by SQLite to set the
   8537 ** suggested maximum cache-size (number of pages stored by) the cache
   8538 ** instance passed as the first argument. This is the value configured using
   8539 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
   8540 ** parameter, the implementation is not required to do anything with this
   8541 ** value; it is advisory only.
   8542 **
   8543 ** [[the xPagecount() page cache methods]]
   8544 ** The xPagecount() method must return the number of pages currently
   8545 ** stored in the cache, both pinned and unpinned.
   8546 **
   8547 ** [[the xFetch() page cache methods]]
   8548 ** The xFetch() method locates a page in the cache and returns a pointer to
   8549 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
   8550 ** The pBuf element of the returned sqlite3_pcache_page object will be a
   8551 ** pointer to a buffer of szPage bytes used to store the content of a
   8552 ** single database page.  The pExtra element of sqlite3_pcache_page will be
   8553 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
   8554 ** for each entry in the page cache.
   8555 **
   8556 ** The page to be fetched is determined by the key. ^The minimum key value
   8557 ** is 1.  After it has been retrieved using xFetch, the page is considered
   8558 ** to be "pinned".
   8559 **
   8560 ** If the requested page is already in the page cache, then the page cache
   8561 ** implementation must return a pointer to the page buffer with its content
   8562 ** intact.  If the requested page is not already in the cache, then the
   8563 ** cache implementation should use the value of the createFlag
   8564 ** parameter to help it determined what action to take:
   8565 **
   8566 ** <table border=1 width=85% align=center>
   8567 ** <tr><th> createFlag <th> Behavior when page is not already in cache
   8568 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
   8569 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
   8570 **                 Otherwise return NULL.
   8571 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
   8572 **                 NULL if allocating a new page is effectively impossible.
   8573 ** </table>
   8574 **
   8575 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
   8576 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
   8577 ** failed.)^  In between the to xFetch() calls, SQLite may
   8578 ** attempt to unpin one or more cache pages by spilling the content of
   8579 ** pinned pages to disk and synching the operating system disk cache.
   8580 **
   8581 ** [[the xUnpin() page cache method]]
   8582 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
   8583 ** as its second argument.  If the third parameter, discard, is non-zero,
   8584 ** then the page must be evicted from the cache.
   8585 ** ^If the discard parameter is
   8586 ** zero, then the page may be discarded or retained at the discretion of
   8587 ** page cache implementation. ^The page cache implementation
   8588 ** may choose to evict unpinned pages at any time.
   8589 **
   8590 ** The cache must not perform any reference counting. A single
   8591 ** call to xUnpin() unpins the page regardless of the number of prior calls
   8592 ** to xFetch().
   8593 **
   8594 ** [[the xRekey() page cache methods]]
   8595 ** The xRekey() method is used to change the key value associated with the
   8596 ** page passed as the second argument. If the cache
   8597 ** previously contains an entry associated with newKey, it must be
   8598 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
   8599 ** to be pinned.
   8600 **
   8601 ** When SQLite calls the xTruncate() method, the cache must discard all
   8602 ** existing cache entries with page numbers (keys) greater than or equal
   8603 ** to the value of the iLimit parameter passed to xTruncate(). If any
   8604 ** of these pages are pinned, they are implicitly unpinned, meaning that
   8605 ** they can be safely discarded.
   8606 **
   8607 ** [[the xDestroy() page cache method]]
   8608 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
   8609 ** All resources associated with the specified cache should be freed. ^After
   8610 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
   8611 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
   8612 ** functions.
   8613 **
   8614 ** [[the xShrink() page cache method]]
   8615 ** ^SQLite invokes the xShrink() method when it wants the page cache to
   8616 ** free up as much of heap memory as possible.  The page cache implementation
   8617 ** is not obligated to free any memory, but well-behaved implementations should
   8618 ** do their best.
   8619 */
   8620 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
   8621 struct sqlite3_pcache_methods2 {
   8622   int iVersion;
   8623   void *pArg;
   8624   int (*xInit)(void*);
   8625   void (*xShutdown)(void*);
   8626   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
   8627   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   8628   int (*xPagecount)(sqlite3_pcache*);
   8629   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   8630   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
   8631   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
   8632       unsigned oldKey, unsigned newKey);
   8633   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   8634   void (*xDestroy)(sqlite3_pcache*);
   8635   void (*xShrink)(sqlite3_pcache*);
   8636 };
   8637 
   8638 /*
   8639 ** This is the obsolete pcache_methods object that has now been replaced
   8640 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
   8641 ** retained in the header file for backwards compatibility only.
   8642 */
   8643 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
   8644 struct sqlite3_pcache_methods {
   8645   void *pArg;
   8646   int (*xInit)(void*);
   8647   void (*xShutdown)(void*);
   8648   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
   8649   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   8650   int (*xPagecount)(sqlite3_pcache*);
   8651   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   8652   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
   8653   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
   8654   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   8655   void (*xDestroy)(sqlite3_pcache*);
   8656 };
   8657 
   8658 
   8659 /*
   8660 ** CAPI3REF: Online Backup Object
   8661 **
   8662 ** The sqlite3_backup object records state information about an ongoing
   8663 ** online backup operation.  ^The sqlite3_backup object is created by
   8664 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
   8665 ** [sqlite3_backup_finish()].
   8666 **
   8667 ** See Also: [Using the SQLite Online Backup API]
   8668 */
   8669 typedef struct sqlite3_backup sqlite3_backup;
   8670 
   8671 /*
   8672 ** CAPI3REF: Online Backup API.
   8673 **
   8674 ** The backup API copies the content of one database into another.
   8675 ** It is useful either for creating backups of databases or
   8676 ** for copying in-memory databases to or from persistent files.
   8677 **
   8678 ** See Also: [Using the SQLite Online Backup API]
   8679 **
   8680 ** ^SQLite holds a write transaction open on the destination database file
   8681 ** for the duration of the backup operation.
   8682 ** ^The source database is read-locked only while it is being read;
   8683 ** it is not locked continuously for the entire backup operation.
   8684 ** ^Thus, the backup may be performed on a live source database without
   8685 ** preventing other database connections from
   8686 ** reading or writing to the source database while the backup is underway.
   8687 **
   8688 ** ^(To perform a backup operation:
   8689 **   <ol>
   8690 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
   8691 **         backup,
   8692 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
   8693 **         the data between the two databases, and finally
   8694 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
   8695 **         associated with the backup operation.
   8696 **   </ol>)^
   8697 ** There should be exactly one call to sqlite3_backup_finish() for each
   8698 ** successful call to sqlite3_backup_init().
   8699 **
   8700 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
   8701 **
   8702 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
   8703 ** [database connection] associated with the destination database
   8704 ** and the database name, respectively.
   8705 ** ^The database name is "main" for the main database, "temp" for the
   8706 ** temporary database, or the name specified after the AS keyword in
   8707 ** an [ATTACH] statement for an attached database.
   8708 ** ^The S and M arguments passed to
   8709 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
   8710 ** and database name of the source database, respectively.
   8711 ** ^The source and destination [database connections] (parameters S and D)
   8712 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
   8713 ** an error.
   8714 **
   8715 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
   8716 ** there is already a read or read-write transaction open on the
   8717 ** destination database.
   8718 **
   8719 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
   8720 ** returned and an error code and error message are stored in the
   8721 ** destination [database connection] D.
   8722 ** ^The error code and message for the failed call to sqlite3_backup_init()
   8723 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
   8724 ** [sqlite3_errmsg16()] functions.
   8725 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
   8726 ** [sqlite3_backup] object.
   8727 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
   8728 ** sqlite3_backup_finish() functions to perform the specified backup
   8729 ** operation.
   8730 **
   8731 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
   8732 **
   8733 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
   8734 ** the source and destination databases specified by [sqlite3_backup] object B.
   8735 ** ^If N is negative, all remaining source pages are copied.
   8736 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
   8737 ** are still more pages to be copied, then the function returns [SQLITE_OK].
   8738 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
   8739 ** from source to destination, then it returns [SQLITE_DONE].
   8740 ** ^If an error occurs while running sqlite3_backup_step(B,N),
   8741 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
   8742 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
   8743 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
   8744 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
   8745 **
   8746 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
   8747 ** <ol>
   8748 ** <li> the destination database was opened read-only, or
   8749 ** <li> the destination database is using write-ahead-log journaling
   8750 ** and the destination and source page sizes differ, or
   8751 ** <li> the destination database is an in-memory database and the
   8752 ** destination and source page sizes differ.
   8753 ** </ol>)^
   8754 **
   8755 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
   8756 ** the [sqlite3_busy_handler | busy-handler function]
   8757 ** is invoked (if one is specified). ^If the
   8758 ** busy-handler returns non-zero before the lock is available, then
   8759 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
   8760 ** sqlite3_backup_step() can be retried later. ^If the source
   8761 ** [database connection]
   8762 ** is being used to write to the source database when sqlite3_backup_step()
   8763 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
   8764 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
   8765 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
   8766 ** [SQLITE_READONLY] is returned, then
   8767 ** there is no point in retrying the call to sqlite3_backup_step(). These
   8768 ** errors are considered fatal.)^  The application must accept
   8769 ** that the backup operation has failed and pass the backup operation handle
   8770 ** to the sqlite3_backup_finish() to release associated resources.
   8771 **
   8772 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
   8773 ** on the destination file. ^The exclusive lock is not released until either
   8774 ** sqlite3_backup_finish() is called or the backup operation is complete
   8775 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
   8776 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
   8777 ** lasts for the duration of the sqlite3_backup_step() call.
   8778 ** ^Because the source database is not locked between calls to
   8779 ** sqlite3_backup_step(), the source database may be modified mid-way
   8780 ** through the backup process.  ^If the source database is modified by an
   8781 ** external process or via a database connection other than the one being
   8782 ** used by the backup operation, then the backup will be automatically
   8783 ** restarted by the next call to sqlite3_backup_step(). ^If the source
   8784 ** database is modified by the using the same database connection as is used
   8785 ** by the backup operation, then the backup database is automatically
   8786 ** updated at the same time.
   8787 **
   8788 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
   8789 **
   8790 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
   8791 ** application wishes to abandon the backup operation, the application
   8792 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
   8793 ** ^The sqlite3_backup_finish() interfaces releases all
   8794 ** resources associated with the [sqlite3_backup] object.
   8795 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
   8796 ** active write-transaction on the destination database is rolled back.
   8797 ** The [sqlite3_backup] object is invalid
   8798 ** and may not be used following a call to sqlite3_backup_finish().
   8799 **
   8800 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
   8801 ** sqlite3_backup_step() errors occurred, regardless or whether or not
   8802 ** sqlite3_backup_step() completed.
   8803 ** ^If an out-of-memory condition or IO error occurred during any prior
   8804 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
   8805 ** sqlite3_backup_finish() returns the corresponding [error code].
   8806 **
   8807 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
   8808 ** is not a permanent error and does not affect the return value of
   8809 ** sqlite3_backup_finish().
   8810 **
   8811 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
   8812 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
   8813 **
   8814 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
   8815 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
   8816 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
   8817 ** in the source database at the conclusion of the most recent
   8818 ** sqlite3_backup_step().
   8819 ** ^(The values returned by these functions are only updated by
   8820 ** sqlite3_backup_step(). If the source database is modified in a way that
   8821 ** changes the size of the source database or the number of pages remaining,
   8822 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
   8823 ** and sqlite3_backup_remaining() until after the next
   8824 ** sqlite3_backup_step().)^
   8825 **
   8826 ** <b>Concurrent Usage of Database Handles</b>
   8827 **
   8828 ** ^The source [database connection] may be used by the application for other
   8829 ** purposes while a backup operation is underway or being initialized.
   8830 ** ^If SQLite is compiled and configured to support threadsafe database
   8831 ** connections, then the source database connection may be used concurrently
   8832 ** from within other threads.
   8833 **
   8834 ** However, the application must guarantee that the destination
   8835 ** [database connection] is not passed to any other API (by any thread) after
   8836 ** sqlite3_backup_init() is called and before the corresponding call to
   8837 ** sqlite3_backup_finish().  SQLite does not currently check to see
   8838 ** if the application incorrectly accesses the destination [database connection]
   8839 ** and so no error code is reported, but the operations may malfunction
   8840 ** nevertheless.  Use of the destination database connection while a
   8841 ** backup is in progress might also also cause a mutex deadlock.
   8842 **
   8843 ** If running in [shared cache mode], the application must
   8844 ** guarantee that the shared cache used by the destination database
   8845 ** is not accessed while the backup is running. In practice this means
   8846 ** that the application must guarantee that the disk file being
   8847 ** backed up to is not accessed by any connection within the process,
   8848 ** not just the specific connection that was passed to sqlite3_backup_init().
   8849 **
   8850 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
   8851 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
   8852 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
   8853 ** APIs are not strictly speaking threadsafe. If they are invoked at the
   8854 ** same time as another thread is invoking sqlite3_backup_step() it is
   8855 ** possible that they return invalid values.
   8856 */
   8857 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   8858   sqlite3 *pDest,                        /* Destination database handle */
   8859   const char *zDestName,                 /* Destination database name */
   8860   sqlite3 *pSource,                      /* Source database handle */
   8861   const char *zSourceName                /* Source database name */
   8862 );
   8863 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
   8864 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
   8865 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
   8866 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
   8867 
   8868 /*
   8869 ** CAPI3REF: Unlock Notification
   8870 ** METHOD: sqlite3
   8871 **
   8872 ** ^When running in shared-cache mode, a database operation may fail with
   8873 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
   8874 ** individual tables within the shared-cache cannot be obtained. See
   8875 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
   8876 ** ^This API may be used to register a callback that SQLite will invoke
   8877 ** when the connection currently holding the required lock relinquishes it.
   8878 ** ^This API is only available if the library was compiled with the
   8879 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
   8880 **
   8881 ** See Also: [Using the SQLite Unlock Notification Feature].
   8882 **
   8883 ** ^Shared-cache locks are released when a database connection concludes
   8884 ** its current transaction, either by committing it or rolling it back.
   8885 **
   8886 ** ^When a connection (known as the blocked connection) fails to obtain a
   8887 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
   8888 ** identity of the database connection (the blocking connection) that
   8889 ** has locked the required resource is stored internally. ^After an
   8890 ** application receives an SQLITE_LOCKED error, it may call the
   8891 ** sqlite3_unlock_notify() method with the blocked connection handle as
   8892 ** the first argument to register for a callback that will be invoked
   8893 ** when the blocking connections current transaction is concluded. ^The
   8894 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
   8895 ** call that concludes the blocking connections transaction.
   8896 **
   8897 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
   8898 ** there is a chance that the blocking connection will have already
   8899 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
   8900 ** If this happens, then the specified callback is invoked immediately,
   8901 ** from within the call to sqlite3_unlock_notify().)^
   8902 **
   8903 ** ^If the blocked connection is attempting to obtain a write-lock on a
   8904 ** shared-cache table, and more than one other connection currently holds
   8905 ** a read-lock on the same table, then SQLite arbitrarily selects one of
   8906 ** the other connections to use as the blocking connection.
   8907 **
   8908 ** ^(There may be at most one unlock-notify callback registered by a
   8909 ** blocked connection. If sqlite3_unlock_notify() is called when the
   8910 ** blocked connection already has a registered unlock-notify callback,
   8911 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
   8912 ** called with a NULL pointer as its second argument, then any existing
   8913 ** unlock-notify callback is canceled. ^The blocked connections
   8914 ** unlock-notify callback may also be canceled by closing the blocked
   8915 ** connection using [sqlite3_close()].
   8916 **
   8917 ** The unlock-notify callback is not reentrant. If an application invokes
   8918 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
   8919 ** crash or deadlock may be the result.
   8920 **
   8921 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
   8922 ** returns SQLITE_OK.
   8923 **
   8924 ** <b>Callback Invocation Details</b>
   8925 **
   8926 ** When an unlock-notify callback is registered, the application provides a
   8927 ** single void* pointer that is passed to the callback when it is invoked.
   8928 ** However, the signature of the callback function allows SQLite to pass
   8929 ** it an array of void* context pointers. The first argument passed to
   8930 ** an unlock-notify callback is a pointer to an array of void* pointers,
   8931 ** and the second is the number of entries in the array.
   8932 **
   8933 ** When a blocking connections transaction is concluded, there may be
   8934 ** more than one blocked connection that has registered for an unlock-notify
   8935 ** callback. ^If two or more such blocked connections have specified the
   8936 ** same callback function, then instead of invoking the callback function
   8937 ** multiple times, it is invoked once with the set of void* context pointers
   8938 ** specified by the blocked connections bundled together into an array.
   8939 ** This gives the application an opportunity to prioritize any actions
   8940 ** related to the set of unblocked database connections.
   8941 **
   8942 ** <b>Deadlock Detection</b>
   8943 **
   8944 ** Assuming that after registering for an unlock-notify callback a
   8945 ** database waits for the callback to be issued before taking any further
   8946 ** action (a reasonable assumption), then using this API may cause the
   8947 ** application to deadlock. For example, if connection X is waiting for
   8948 ** connection Y's transaction to be concluded, and similarly connection
   8949 ** Y is waiting on connection X's transaction, then neither connection
   8950 ** will proceed and the system may remain deadlocked indefinitely.
   8951 **
   8952 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
   8953 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
   8954 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
   8955 ** unlock-notify callback is registered. The system is said to be in
   8956 ** a deadlocked state if connection A has registered for an unlock-notify
   8957 ** callback on the conclusion of connection B's transaction, and connection
   8958 ** B has itself registered for an unlock-notify callback when connection
   8959 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
   8960 ** the system is also considered to be deadlocked if connection B has
   8961 ** registered for an unlock-notify callback on the conclusion of connection
   8962 ** C's transaction, where connection C is waiting on connection A. ^Any
   8963 ** number of levels of indirection are allowed.
   8964 **
   8965 ** <b>The "DROP TABLE" Exception</b>
   8966 **
   8967 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
   8968 ** always appropriate to call sqlite3_unlock_notify(). There is however,
   8969 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
   8970 ** SQLite checks if there are any currently executing SELECT statements
   8971 ** that belong to the same connection. If there are, SQLITE_LOCKED is
   8972 ** returned. In this case there is no "blocking connection", so invoking
   8973 ** sqlite3_unlock_notify() results in the unlock-notify callback being
   8974 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
   8975 ** or "DROP INDEX" query, an infinite loop might be the result.
   8976 **
   8977 ** One way around this problem is to check the extended error code returned
   8978 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
   8979 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
   8980 ** the special "DROP TABLE/INDEX" case, the extended error code is just
   8981 ** SQLITE_LOCKED.)^
   8982 */
   8983 SQLITE_API int sqlite3_unlock_notify(
   8984   sqlite3 *pBlocked,                          /* Waiting connection */
   8985   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
   8986   void *pNotifyArg                            /* Argument to pass to xNotify */
   8987 );
   8988 
   8989 
   8990 /*
   8991 ** CAPI3REF: String Comparison
   8992 **
   8993 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
   8994 ** and extensions to compare the contents of two buffers containing UTF-8
   8995 ** strings in a case-independent fashion, using the same definition of "case
   8996 ** independence" that SQLite uses internally when comparing identifiers.
   8997 */
   8998 SQLITE_API int sqlite3_stricmp(const char *, const char *);
   8999 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
   9000 
   9001 /*
   9002 ** CAPI3REF: String Globbing
   9003 *
   9004 ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
   9005 ** string X matches the [GLOB] pattern P.
   9006 ** ^The definition of [GLOB] pattern matching used in
   9007 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
   9008 ** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
   9009 ** is case sensitive.
   9010 **
   9011 ** Note that this routine returns zero on a match and non-zero if the strings
   9012 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
   9013 **
   9014 ** See also: [sqlite3_strlike()].
   9015 */
   9016 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
   9017 
   9018 /*
   9019 ** CAPI3REF: String LIKE Matching
   9020 *
   9021 ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
   9022 ** string X matches the [LIKE] pattern P with escape character E.
   9023 ** ^The definition of [LIKE] pattern matching used in
   9024 ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
   9025 ** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
   9026 ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
   9027 ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
   9028 ** insensitive - equivalent upper and lower case ASCII characters match
   9029 ** one another.
   9030 **
   9031 ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
   9032 ** only ASCII characters are case folded.
   9033 **
   9034 ** Note that this routine returns zero on a match and non-zero if the strings
   9035 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
   9036 **
   9037 ** See also: [sqlite3_strglob()].
   9038 */
   9039 SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
   9040 
   9041 /*
   9042 ** CAPI3REF: Error Logging Interface
   9043 **
   9044 ** ^The [sqlite3_log()] interface writes a message into the [error log]
   9045 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
   9046 ** ^If logging is enabled, the zFormat string and subsequent arguments are
   9047 ** used with [sqlite3_snprintf()] to generate the final output string.
   9048 **
   9049 ** The sqlite3_log() interface is intended for use by extensions such as
   9050 ** virtual tables, collating functions, and SQL functions.  While there is
   9051 ** nothing to prevent an application from calling sqlite3_log(), doing so
   9052 ** is considered bad form.
   9053 **
   9054 ** The zFormat string must not be NULL.
   9055 **
   9056 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
   9057 ** will not use dynamically allocated memory.  The log message is stored in
   9058 ** a fixed-length buffer on the stack.  If the log message is longer than
   9059 ** a few hundred characters, it will be truncated to the length of the
   9060 ** buffer.
   9061 */
   9062 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
   9063 
   9064 /*
   9065 ** CAPI3REF: Write-Ahead Log Commit Hook
   9066 ** METHOD: sqlite3
   9067 **
   9068 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
   9069 ** is invoked each time data is committed to a database in wal mode.
   9070 **
   9071 ** ^(The callback is invoked by SQLite after the commit has taken place and
   9072 ** the associated write-lock on the database released)^, so the implementation
   9073 ** may read, write or [checkpoint] the database as required.
   9074 **
   9075 ** ^The first parameter passed to the callback function when it is invoked
   9076 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
   9077 ** registering the callback. ^The second is a copy of the database handle.
   9078 ** ^The third parameter is the name of the database that was written to -
   9079 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
   9080 ** is the number of pages currently in the write-ahead log file,
   9081 ** including those that were just committed.
   9082 **
   9083 ** The callback function should normally return [SQLITE_OK].  ^If an error
   9084 ** code is returned, that error will propagate back up through the
   9085 ** SQLite code base to cause the statement that provoked the callback
   9086 ** to report an error, though the commit will have still occurred. If the
   9087 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
   9088 ** that does not correspond to any valid SQLite error code, the results
   9089 ** are undefined.
   9090 **
   9091 ** A single database handle may have at most a single write-ahead log callback
   9092 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
   9093 ** previously registered write-ahead log callback. ^Note that the
   9094 ** [sqlite3_wal_autocheckpoint()] interface and the
   9095 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
   9096 ** overwrite any prior [sqlite3_wal_hook()] settings.
   9097 */
   9098 SQLITE_API void *sqlite3_wal_hook(
   9099   sqlite3*,
   9100   int(*)(void *,sqlite3*,const char*,int),
   9101   void*
   9102 );
   9103 
   9104 /*
   9105 ** CAPI3REF: Configure an auto-checkpoint
   9106 ** METHOD: sqlite3
   9107 **
   9108 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
   9109 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
   9110 ** to automatically [checkpoint]
   9111 ** after committing a transaction if there are N or
   9112 ** more frames in the [write-ahead log] file.  ^Passing zero or
   9113 ** a negative value as the nFrame parameter disables automatic
   9114 ** checkpoints entirely.
   9115 **
   9116 ** ^The callback registered by this function replaces any existing callback
   9117 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
   9118 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
   9119 ** configured by this function.
   9120 **
   9121 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
   9122 ** from SQL.
   9123 **
   9124 ** ^Checkpoints initiated by this mechanism are
   9125 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
   9126 **
   9127 ** ^Every new [database connection] defaults to having the auto-checkpoint
   9128 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
   9129 ** pages.  The use of this interface
   9130 ** is only necessary if the default setting is found to be suboptimal
   9131 ** for a particular application.
   9132 */
   9133 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
   9134 
   9135 /*
   9136 ** CAPI3REF: Checkpoint a database
   9137 ** METHOD: sqlite3
   9138 **
   9139 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
   9140 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
   9141 **
   9142 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
   9143 ** [write-ahead log] for database X on [database connection] D to be
   9144 ** transferred into the database file and for the write-ahead log to
   9145 ** be reset.  See the [checkpointing] documentation for addition
   9146 ** information.
   9147 **
   9148 ** This interface used to be the only way to cause a checkpoint to
   9149 ** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
   9150 ** interface was added.  This interface is retained for backwards
   9151 ** compatibility and as a convenience for applications that need to manually
   9152 ** start a callback but which do not need the full power (and corresponding
   9153 ** complication) of [sqlite3_wal_checkpoint_v2()].
   9154 */
   9155 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
   9156 
   9157 /*
   9158 ** CAPI3REF: Checkpoint a database
   9159 ** METHOD: sqlite3
   9160 **
   9161 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
   9162 ** operation on database X of [database connection] D in mode M.  Status
   9163 ** information is written back into integers pointed to by L and C.)^
   9164 ** ^(The M parameter must be a valid [checkpoint mode]:)^
   9165 **
   9166 ** <dl>
   9167 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
   9168 **   ^Checkpoint as many frames as possible without waiting for any database
   9169 **   readers or writers to finish, then sync the database file if all frames
   9170 **   in the log were checkpointed. ^The [busy-handler callback]
   9171 **   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
   9172 **   ^On the other hand, passive mode might leave the checkpoint unfinished
   9173 **   if there are concurrent readers or writers.
   9174 **
   9175 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
   9176 **   ^This mode blocks (it invokes the
   9177 **   [sqlite3_busy_handler|busy-handler callback]) until there is no
   9178 **   database writer and all readers are reading from the most recent database
   9179 **   snapshot. ^It then checkpoints all frames in the log file and syncs the
   9180 **   database file. ^This mode blocks new database writers while it is pending,
   9181 **   but new database readers are allowed to continue unimpeded.
   9182 **
   9183 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
   9184 **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
   9185 **   that after checkpointing the log file it blocks (calls the
   9186 **   [busy-handler callback])
   9187 **   until all readers are reading from the database file only. ^This ensures
   9188 **   that the next writer will restart the log file from the beginning.
   9189 **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
   9190 **   database writer attempts while it is pending, but does not impede readers.
   9191 **
   9192 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
   9193 **   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
   9194 **   addition that it also truncates the log file to zero bytes just prior
   9195 **   to a successful return.
   9196 ** </dl>
   9197 **
   9198 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
   9199 ** the log file or to -1 if the checkpoint could not run because
   9200 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
   9201 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
   9202 ** log file (including any that were already checkpointed before the function
   9203 ** was called) or to -1 if the checkpoint could not run due to an error or
   9204 ** because the database is not in WAL mode. ^Note that upon successful
   9205 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
   9206 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
   9207 **
   9208 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
   9209 ** any other process is running a checkpoint operation at the same time, the
   9210 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
   9211 ** busy-handler configured, it will not be invoked in this case.
   9212 **
   9213 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
   9214 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
   9215 ** obtained immediately, and a busy-handler is configured, it is invoked and
   9216 ** the writer lock retried until either the busy-handler returns 0 or the lock
   9217 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
   9218 ** database readers as described above. ^If the busy-handler returns 0 before
   9219 ** the writer lock is obtained or while waiting for database readers, the
   9220 ** checkpoint operation proceeds from that point in the same way as
   9221 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
   9222 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
   9223 **
   9224 ** ^If parameter zDb is NULL or points to a zero length string, then the
   9225 ** specified operation is attempted on all WAL databases [attached] to
   9226 ** [database connection] db.  In this case the
   9227 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
   9228 ** an SQLITE_BUSY error is encountered when processing one or more of the
   9229 ** attached WAL databases, the operation is still attempted on any remaining
   9230 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
   9231 ** error occurs while processing an attached database, processing is abandoned
   9232 ** and the error code is returned to the caller immediately. ^If no error
   9233 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
   9234 ** databases, SQLITE_OK is returned.
   9235 **
   9236 ** ^If database zDb is the name of an attached database that is not in WAL
   9237 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
   9238 ** zDb is not NULL (or a zero length string) and is not the name of any
   9239 ** attached database, SQLITE_ERROR is returned to the caller.
   9240 **
   9241 ** ^Unless it returns SQLITE_MISUSE,
   9242 ** the sqlite3_wal_checkpoint_v2() interface
   9243 ** sets the error information that is queried by
   9244 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
   9245 **
   9246 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
   9247 ** from SQL.
   9248 */
   9249 SQLITE_API int sqlite3_wal_checkpoint_v2(
   9250   sqlite3 *db,                    /* Database handle */
   9251   const char *zDb,                /* Name of attached database (or NULL) */
   9252   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   9253   int *pnLog,                     /* OUT: Size of WAL log in frames */
   9254   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   9255 );
   9256 
   9257 /*
   9258 ** CAPI3REF: Checkpoint Mode Values
   9259 ** KEYWORDS: {checkpoint mode}
   9260 **
   9261 ** These constants define all valid values for the "checkpoint mode" passed
   9262 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
   9263 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
   9264 ** meaning of each of these checkpoint modes.
   9265 */
   9266 #define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
   9267 #define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
   9268 #define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
   9269 #define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
   9270 
   9271 /*
   9272 ** CAPI3REF: Virtual Table Interface Configuration
   9273 **
   9274 ** This function may be called by either the [xConnect] or [xCreate] method
   9275 ** of a [virtual table] implementation to configure
   9276 ** various facets of the virtual table interface.
   9277 **
   9278 ** If this interface is invoked outside the context of an xConnect or
   9279 ** xCreate virtual table method then the behavior is undefined.
   9280 **
   9281 ** At present, there is only one option that may be configured using
   9282 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
   9283 ** may be added in the future.
   9284 */
   9285 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
   9286 
   9287 /*
   9288 ** CAPI3REF: Virtual Table Configuration Options
   9289 **
   9290 ** These macros define the various options to the
   9291 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
   9292 ** can use to customize and optimize their behavior.
   9293 **
   9294 ** <dl>
   9295 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
   9296 ** <dd>Calls of the form
   9297 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
   9298 ** where X is an integer.  If X is zero, then the [virtual table] whose
   9299 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
   9300 ** support constraints.  In this configuration (which is the default) if
   9301 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
   9302 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
   9303 ** specified as part of the users SQL statement, regardless of the actual
   9304 ** ON CONFLICT mode specified.
   9305 **
   9306 ** If X is non-zero, then the virtual table implementation guarantees
   9307 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
   9308 ** any modifications to internal or persistent data structures have been made.
   9309 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
   9310 ** is able to roll back a statement or database transaction, and abandon
   9311 ** or continue processing the current SQL statement as appropriate.
   9312 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
   9313 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
   9314 ** had been ABORT.
   9315 **
   9316 ** Virtual table implementations that are required to handle OR REPLACE
   9317 ** must do so within the [xUpdate] method. If a call to the
   9318 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
   9319 ** CONFLICT policy is REPLACE, the virtual table implementation should
   9320 ** silently replace the appropriate rows within the xUpdate callback and
   9321 ** return SQLITE_OK. Or, if this is not possible, it may return
   9322 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
   9323 ** constraint handling.
   9324 ** </dl>
   9325 */
   9326 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
   9327 
   9328 /*
   9329 ** CAPI3REF: Determine The Virtual Table Conflict Policy
   9330 **
   9331 ** This function may only be called from within a call to the [xUpdate] method
   9332 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
   9333 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
   9334 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
   9335 ** of the SQL statement that triggered the call to the [xUpdate] method of the
   9336 ** [virtual table].
   9337 */
   9338 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
   9339 
   9340 /*
   9341 ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
   9342 **
   9343 ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
   9344 ** method of a [virtual table], then it returns true if and only if the
   9345 ** column is being fetched as part of an UPDATE operation during which the
   9346 ** column value will not change.  Applications might use this to substitute
   9347 ** a lighter-weight value to return that the corresponding [xUpdate] method
   9348 ** understands as a "no-change" value.
   9349 **
   9350 ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
   9351 ** the column is not changed by the UPDATE statement, they the xColumn
   9352 ** method can optionally return without setting a result, without calling
   9353 ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
   9354 ** In that case, [sqlite3_value_nochange(X)] will return true for the
   9355 ** same column in the [xUpdate] method.
   9356 */
   9357 SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
   9358 
   9359 /*
   9360 ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
   9361 **
   9362 ** This function may only be called from within a call to the [xBestIndex]
   9363 ** method of a [virtual table].
   9364 **
   9365 ** The first argument must be the sqlite3_index_info object that is the
   9366 ** first parameter to the xBestIndex() method. The second argument must be
   9367 ** an index into the aConstraint[] array belonging to the sqlite3_index_info
   9368 ** structure passed to xBestIndex. This function returns a pointer to a buffer
   9369 ** containing the name of the collation sequence for the corresponding
   9370 ** constraint.
   9371 */
   9372 SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
   9373 
   9374 /*
   9375 ** CAPI3REF: Conflict resolution modes
   9376 ** KEYWORDS: {conflict resolution mode}
   9377 **
   9378 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
   9379 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
   9380 ** is for the SQL statement being evaluated.
   9381 **
   9382 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
   9383 ** return value from the [sqlite3_set_authorizer()] callback and that
   9384 ** [SQLITE_ABORT] is also a [result code].
   9385 */
   9386 #define SQLITE_ROLLBACK 1
   9387 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
   9388 #define SQLITE_FAIL     3
   9389 /* #define SQLITE_ABORT 4  // Also an error code */
   9390 #define SQLITE_REPLACE  5
   9391 
   9392 /*
   9393 ** CAPI3REF: Prepared Statement Scan Status Opcodes
   9394 ** KEYWORDS: {scanstatus options}
   9395 **
   9396 ** The following constants can be used for the T parameter to the
   9397 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
   9398 ** different metric for sqlite3_stmt_scanstatus() to return.
   9399 **
   9400 ** When the value returned to V is a string, space to hold that string is
   9401 ** managed by the prepared statement S and will be automatically freed when
   9402 ** S is finalized.
   9403 **
   9404 ** <dl>
   9405 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
   9406 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
   9407 ** set to the total number of times that the X-th loop has run.</dd>
   9408 **
   9409 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
   9410 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
   9411 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
   9412 **
   9413 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
   9414 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
   9415 ** query planner's estimate for the average number of rows output from each
   9416 ** iteration of the X-th loop.  If the query planner's estimates was accurate,
   9417 ** then this value will approximate the quotient NVISIT/NLOOP and the
   9418 ** product of this value for all prior loops with the same SELECTID will
   9419 ** be the NLOOP value for the current loop.
   9420 **
   9421 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
   9422 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
   9423 ** to a zero-terminated UTF-8 string containing the name of the index or table
   9424 ** used for the X-th loop.
   9425 **
   9426 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
   9427 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
   9428 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
   9429 ** description for the X-th loop.
   9430 **
   9431 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
   9432 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
   9433 ** "select-id" for the X-th loop.  The select-id identifies which query or
   9434 ** subquery the loop is part of.  The main query has a select-id of zero.
   9435 ** The select-id is the same value as is output in the first column
   9436 ** of an [EXPLAIN QUERY PLAN] query.
   9437 ** </dl>
   9438 */
   9439 #define SQLITE_SCANSTAT_NLOOP    0
   9440 #define SQLITE_SCANSTAT_NVISIT   1
   9441 #define SQLITE_SCANSTAT_EST      2
   9442 #define SQLITE_SCANSTAT_NAME     3
   9443 #define SQLITE_SCANSTAT_EXPLAIN  4
   9444 #define SQLITE_SCANSTAT_SELECTID 5
   9445 
   9446 /*
   9447 ** CAPI3REF: Prepared Statement Scan Status
   9448 ** METHOD: sqlite3_stmt
   9449 **
   9450 ** This interface returns information about the predicted and measured
   9451 ** performance for pStmt.  Advanced applications can use this
   9452 ** interface to compare the predicted and the measured performance and
   9453 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
   9454 **
   9455 ** Since this interface is expected to be rarely used, it is only
   9456 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
   9457 ** compile-time option.
   9458 **
   9459 ** The "iScanStatusOp" parameter determines which status information to return.
   9460 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
   9461 ** of this interface is undefined.
   9462 ** ^The requested measurement is written into a variable pointed to by
   9463 ** the "pOut" parameter.
   9464 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
   9465 ** Loops are numbered starting from zero. ^If idx is out of range - less than
   9466 ** zero or greater than or equal to the total number of loops used to implement
   9467 ** the statement - a non-zero value is returned and the variable that pOut
   9468 ** points to is unchanged.
   9469 **
   9470 ** ^Statistics might not be available for all loops in all statements. ^In cases
   9471 ** where there exist loops with no available statistics, this function behaves
   9472 ** as if the loop did not exist - it returns non-zero and leave the variable
   9473 ** that pOut points to unchanged.
   9474 **
   9475 ** See also: [sqlite3_stmt_scanstatus_reset()]
   9476 */
   9477 SQLITE_API int sqlite3_stmt_scanstatus(
   9478   sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
   9479   int idx,                  /* Index of loop to report on */
   9480   int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
   9481   void *pOut                /* Result written here */
   9482 );
   9483 
   9484 /*
   9485 ** CAPI3REF: Zero Scan-Status Counters
   9486 ** METHOD: sqlite3_stmt
   9487 **
   9488 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
   9489 **
   9490 ** This API is only available if the library is built with pre-processor
   9491 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
   9492 */
   9493 SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
   9494 
   9495 /*
   9496 ** CAPI3REF: Flush caches to disk mid-transaction
   9497 **
   9498 ** ^If a write-transaction is open on [database connection] D when the
   9499 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
   9500 ** pages in the pager-cache that are not currently in use are written out
   9501 ** to disk. A dirty page may be in use if a database cursor created by an
   9502 ** active SQL statement is reading from it, or if it is page 1 of a database
   9503 ** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
   9504 ** interface flushes caches for all schemas - "main", "temp", and
   9505 ** any [attached] databases.
   9506 **
   9507 ** ^If this function needs to obtain extra database locks before dirty pages
   9508 ** can be flushed to disk, it does so. ^If those locks cannot be obtained
   9509 ** immediately and there is a busy-handler callback configured, it is invoked
   9510 ** in the usual manner. ^If the required lock still cannot be obtained, then
   9511 ** the database is skipped and an attempt made to flush any dirty pages
   9512 ** belonging to the next (if any) database. ^If any databases are skipped
   9513 ** because locks cannot be obtained, but no other error occurs, this
   9514 ** function returns SQLITE_BUSY.
   9515 **
   9516 ** ^If any other error occurs while flushing dirty pages to disk (for
   9517 ** example an IO error or out-of-memory condition), then processing is
   9518 ** abandoned and an SQLite [error code] is returned to the caller immediately.
   9519 **
   9520 ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
   9521 **
   9522 ** ^This function does not set the database handle error code or message
   9523 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
   9524 */
   9525 SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
   9526 
   9527 /*
   9528 ** CAPI3REF: The pre-update hook.
   9529 **
   9530 ** ^These interfaces are only available if SQLite is compiled using the
   9531 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
   9532 **
   9533 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
   9534 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
   9535 ** on a database table.
   9536 ** ^At most one preupdate hook may be registered at a time on a single
   9537 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
   9538 ** the previous setting.
   9539 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
   9540 ** with a NULL pointer as the second parameter.
   9541 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
   9542 ** the first parameter to callbacks.
   9543 **
   9544 ** ^The preupdate hook only fires for changes to real database tables; the
   9545 ** preupdate hook is not invoked for changes to [virtual tables] or to
   9546 ** system tables like sqlite_master or sqlite_stat1.
   9547 **
   9548 ** ^The second parameter to the preupdate callback is a pointer to
   9549 ** the [database connection] that registered the preupdate hook.
   9550 ** ^The third parameter to the preupdate callback is one of the constants
   9551 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
   9552 ** kind of update operation that is about to occur.
   9553 ** ^(The fourth parameter to the preupdate callback is the name of the
   9554 ** database within the database connection that is being modified.  This
   9555 ** will be "main" for the main database or "temp" for TEMP tables or
   9556 ** the name given after the AS keyword in the [ATTACH] statement for attached
   9557 ** databases.)^
   9558 ** ^The fifth parameter to the preupdate callback is the name of the
   9559 ** table that is being modified.
   9560 **
   9561 ** For an UPDATE or DELETE operation on a [rowid table], the sixth
   9562 ** parameter passed to the preupdate callback is the initial [rowid] of the
   9563 ** row being modified or deleted. For an INSERT operation on a rowid table,
   9564 ** or any operation on a WITHOUT ROWID table, the value of the sixth
   9565 ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
   9566 ** seventh parameter is the final rowid value of the row being inserted
   9567 ** or updated. The value of the seventh parameter passed to the callback
   9568 ** function is not defined for operations on WITHOUT ROWID tables, or for
   9569 ** INSERT operations on rowid tables.
   9570 **
   9571 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
   9572 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
   9573 ** provide additional information about a preupdate event. These routines
   9574 ** may only be called from within a preupdate callback.  Invoking any of
   9575 ** these routines from outside of a preupdate callback or with a
   9576 ** [database connection] pointer that is different from the one supplied
   9577 ** to the preupdate callback results in undefined and probably undesirable
   9578 ** behavior.
   9579 **
   9580 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
   9581 ** in the row that is being inserted, updated, or deleted.
   9582 **
   9583 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
   9584 ** a [protected sqlite3_value] that contains the value of the Nth column of
   9585 ** the table row before it is updated.  The N parameter must be between 0
   9586 ** and one less than the number of columns or the behavior will be
   9587 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
   9588 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
   9589 ** behavior is undefined.  The [sqlite3_value] that P points to
   9590 ** will be destroyed when the preupdate callback returns.
   9591 **
   9592 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
   9593 ** a [protected sqlite3_value] that contains the value of the Nth column of
   9594 ** the table row after it is updated.  The N parameter must be between 0
   9595 ** and one less than the number of columns or the behavior will be
   9596 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
   9597 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
   9598 ** behavior is undefined.  The [sqlite3_value] that P points to
   9599 ** will be destroyed when the preupdate callback returns.
   9600 **
   9601 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
   9602 ** callback was invoked as a result of a direct insert, update, or delete
   9603 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
   9604 ** triggers; or 2 for changes resulting from triggers called by top-level
   9605 ** triggers; and so forth.
   9606 **
   9607 ** See also:  [sqlite3_update_hook()]
   9608 */
   9609 #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
   9610 SQLITE_API void *sqlite3_preupdate_hook(
   9611   sqlite3 *db,
   9612   void(*xPreUpdate)(
   9613     void *pCtx,                   /* Copy of third arg to preupdate_hook() */
   9614     sqlite3 *db,                  /* Database handle */
   9615     int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
   9616     char const *zDb,              /* Database name */
   9617     char const *zName,            /* Table name */
   9618     sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
   9619     sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
   9620   ),
   9621   void*
   9622 );
   9623 SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
   9624 SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
   9625 SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
   9626 SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
   9627 #endif
   9628 
   9629 /*
   9630 ** CAPI3REF: Low-level system error code
   9631 **
   9632 ** ^Attempt to return the underlying operating system error code or error
   9633 ** number that caused the most recent I/O error or failure to open a file.
   9634 ** The return value is OS-dependent.  For example, on unix systems, after
   9635 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
   9636 ** called to get back the underlying "errno" that caused the problem, such
   9637 ** as ENOSPC, EAUTH, EISDIR, and so forth.
   9638 */
   9639 SQLITE_API int sqlite3_system_errno(sqlite3*);
   9640 
   9641 /*
   9642 ** CAPI3REF: Database Snapshot
   9643 ** KEYWORDS: {snapshot} {sqlite3_snapshot}
   9644 ** EXPERIMENTAL
   9645 **
   9646 ** An instance of the snapshot object records the state of a [WAL mode]
   9647 ** database for some specific point in history.
   9648 **
   9649 ** In [WAL mode], multiple [database connections] that are open on the
   9650 ** same database file can each be reading a different historical version
   9651 ** of the database file.  When a [database connection] begins a read
   9652 ** transaction, that connection sees an unchanging copy of the database
   9653 ** as it existed for the point in time when the transaction first started.
   9654 ** Subsequent changes to the database from other connections are not seen
   9655 ** by the reader until a new read transaction is started.
   9656 **
   9657 ** The sqlite3_snapshot object records state information about an historical
   9658 ** version of the database file so that it is possible to later open a new read
   9659 ** transaction that sees that historical version of the database rather than
   9660 ** the most recent version.
   9661 **
   9662 ** The constructor for this object is [sqlite3_snapshot_get()].  The
   9663 ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
   9664 ** to an historical snapshot (if possible).  The destructor for
   9665 ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
   9666 */
   9667 typedef struct sqlite3_snapshot {
   9668   unsigned char hidden[48];
   9669 } sqlite3_snapshot;
   9670 
   9671 /*
   9672 ** CAPI3REF: Record A Database Snapshot
   9673 ** EXPERIMENTAL
   9674 **
   9675 ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
   9676 ** new [sqlite3_snapshot] object that records the current state of
   9677 ** schema S in database connection D.  ^On success, the
   9678 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
   9679 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
   9680 ** If there is not already a read-transaction open on schema S when
   9681 ** this function is called, one is opened automatically.
   9682 **
   9683 ** The following must be true for this function to succeed. If any of
   9684 ** the following statements are false when sqlite3_snapshot_get() is
   9685 ** called, SQLITE_ERROR is returned. The final value of *P is undefined
   9686 ** in this case.
   9687 **
   9688 ** <ul>
   9689 **   <li> The database handle must be in [autocommit mode].
   9690 **
   9691 **   <li> Schema S of [database connection] D must be a [WAL mode] database.
   9692 **
   9693 **   <li> There must not be a write transaction open on schema S of database
   9694 **        connection D.
   9695 **
   9696 **   <li> One or more transactions must have been written to the current wal
   9697 **        file since it was created on disk (by any connection). This means
   9698 **        that a snapshot cannot be taken on a wal mode database with no wal
   9699 **        file immediately after it is first opened. At least one transaction
   9700 **        must be written to it first.
   9701 ** </ul>
   9702 **
   9703 ** This function may also return SQLITE_NOMEM.  If it is called with the
   9704 ** database handle in autocommit mode but fails for some other reason,
   9705 ** whether or not a read transaction is opened on schema S is undefined.
   9706 **
   9707 ** The [sqlite3_snapshot] object returned from a successful call to
   9708 ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
   9709 ** to avoid a memory leak.
   9710 **
   9711 ** The [sqlite3_snapshot_get()] interface is only available when the
   9712 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
   9713 */
   9714 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
   9715   sqlite3 *db,
   9716   const char *zSchema,
   9717   sqlite3_snapshot **ppSnapshot
   9718 );
   9719 
   9720 /*
   9721 ** CAPI3REF: Start a read transaction on an historical snapshot
   9722 ** EXPERIMENTAL
   9723 **
   9724 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
   9725 ** read transaction for schema S of
   9726 ** [database connection] D such that the read transaction
   9727 ** refers to historical [snapshot] P, rather than the most
   9728 ** recent change to the database.
   9729 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
   9730 ** or an appropriate [error code] if it fails.
   9731 **
   9732 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
   9733 ** the first operation following the [BEGIN] that takes the schema S
   9734 ** out of [autocommit mode].
   9735 ** ^In other words, schema S must not currently be in
   9736 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
   9737 ** database connection D must be out of [autocommit mode].
   9738 ** ^A [snapshot] will fail to open if it has been overwritten by a
   9739 ** [checkpoint].
   9740 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
   9741 ** database connection D does not know that the database file for
   9742 ** schema S is in [WAL mode].  A database connection might not know
   9743 ** that the database file is in [WAL mode] if there has been no prior
   9744 ** I/O on that database connection, or if the database entered [WAL mode]
   9745 ** after the most recent I/O on the database connection.)^
   9746 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
   9747 ** database connection in order to make it ready to use snapshots.)
   9748 **
   9749 ** The [sqlite3_snapshot_open()] interface is only available when the
   9750 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
   9751 */
   9752 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
   9753   sqlite3 *db,
   9754   const char *zSchema,
   9755   sqlite3_snapshot *pSnapshot
   9756 );
   9757 
   9758 /*
   9759 ** CAPI3REF: Destroy a snapshot
   9760 ** EXPERIMENTAL
   9761 **
   9762 ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
   9763 ** The application must eventually free every [sqlite3_snapshot] object
   9764 ** using this routine to avoid a memory leak.
   9765 **
   9766 ** The [sqlite3_snapshot_free()] interface is only available when the
   9767 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
   9768 */
   9769 SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
   9770 
   9771 /*
   9772 ** CAPI3REF: Compare the ages of two snapshot handles.
   9773 ** EXPERIMENTAL
   9774 **
   9775 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
   9776 ** of two valid snapshot handles.
   9777 **
   9778 ** If the two snapshot handles are not associated with the same database
   9779 ** file, the result of the comparison is undefined.
   9780 **
   9781 ** Additionally, the result of the comparison is only valid if both of the
   9782 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
   9783 ** last time the wal file was deleted. The wal file is deleted when the
   9784 ** database is changed back to rollback mode or when the number of database
   9785 ** clients drops to zero. If either snapshot handle was obtained before the
   9786 ** wal file was last deleted, the value returned by this function
   9787 ** is undefined.
   9788 **
   9789 ** Otherwise, this API returns a negative value if P1 refers to an older
   9790 ** snapshot than P2, zero if the two handles refer to the same database
   9791 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
   9792 */
   9793 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
   9794   sqlite3_snapshot *p1,
   9795   sqlite3_snapshot *p2
   9796 );
   9797 
   9798 /*
   9799 ** CAPI3REF: Recover snapshots from a wal file
   9800 ** EXPERIMENTAL
   9801 **
   9802 ** If all connections disconnect from a database file but do not perform
   9803 ** a checkpoint, the existing wal file is opened along with the database
   9804 ** file the next time the database is opened. At this point it is only
   9805 ** possible to successfully call sqlite3_snapshot_open() to open the most
   9806 ** recent snapshot of the database (the one at the head of the wal file),
   9807 ** even though the wal file may contain other valid snapshots for which
   9808 ** clients have sqlite3_snapshot handles.
   9809 **
   9810 ** This function attempts to scan the wal file associated with database zDb
   9811 ** of database handle db and make all valid snapshots available to
   9812 ** sqlite3_snapshot_open(). It is an error if there is already a read
   9813 ** transaction open on the database, or if the database is not a wal mode
   9814 ** database.
   9815 **
   9816 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
   9817 */
   9818 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
   9819 
   9820 /*
   9821 ** Undo the hack that converts floating point types to integer for
   9822 ** builds on processors without floating point support.
   9823 */
   9824 #ifdef SQLITE_OMIT_FLOATING_POINT
   9825 # undef double
   9826 #endif
   9827 
   9828 #if 0
   9829 }  /* End of the 'extern "C"' block */
   9830 #endif
   9831 #endif /* SQLITE3_H */
   9832 
   9833 /******** Begin file sqlite3rtree.h *********/
   9834 /*
   9835 ** 2010 August 30
   9836 **
   9837 ** The author disclaims copyright to this source code.  In place of
   9838 ** a legal notice, here is a blessing:
   9839 **
   9840 **    May you do good and not evil.
   9841 **    May you find forgiveness for yourself and forgive others.
   9842 **    May you share freely, never taking more than you give.
   9843 **
   9844 *************************************************************************
   9845 */
   9846 
   9847 #ifndef _SQLITE3RTREE_H_
   9848 #define _SQLITE3RTREE_H_
   9849 
   9850 
   9851 #if 0
   9852 extern "C" {
   9853 #endif
   9854 
   9855 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
   9856 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
   9857 
   9858 /* The double-precision datatype used by RTree depends on the
   9859 ** SQLITE_RTREE_INT_ONLY compile-time option.
   9860 */
   9861 #ifdef SQLITE_RTREE_INT_ONLY
   9862   typedef sqlite3_int64 sqlite3_rtree_dbl;
   9863 #else
   9864   typedef double sqlite3_rtree_dbl;
   9865 #endif
   9866 
   9867 /*
   9868 ** Register a geometry callback named zGeom that can be used as part of an
   9869 ** R-Tree geometry query as follows:
   9870 **
   9871 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
   9872 */
   9873 SQLITE_API int sqlite3_rtree_geometry_callback(
   9874   sqlite3 *db,
   9875   const char *zGeom,
   9876   int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
   9877   void *pContext
   9878 );
   9879 
   9880 
   9881 /*
   9882 ** A pointer to a structure of the following type is passed as the first
   9883 ** argument to callbacks registered using rtree_geometry_callback().
   9884 */
   9885 struct sqlite3_rtree_geometry {
   9886   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
   9887   int nParam;                     /* Size of array aParam[] */
   9888   sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
   9889   void *pUser;                    /* Callback implementation user data */
   9890   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
   9891 };
   9892 
   9893 /*
   9894 ** Register a 2nd-generation geometry callback named zScore that can be
   9895 ** used as part of an R-Tree geometry query as follows:
   9896 **
   9897 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
   9898 */
   9899 SQLITE_API int sqlite3_rtree_query_callback(
   9900   sqlite3 *db,
   9901   const char *zQueryFunc,
   9902   int (*xQueryFunc)(sqlite3_rtree_query_info*),
   9903   void *pContext,
   9904   void (*xDestructor)(void*)
   9905 );
   9906 
   9907 
   9908 /*
   9909 ** A pointer to a structure of the following type is passed as the
   9910 ** argument to scored geometry callback registered using
   9911 ** sqlite3_rtree_query_callback().
   9912 **
   9913 ** Note that the first 5 fields of this structure are identical to
   9914 ** sqlite3_rtree_geometry.  This structure is a subclass of
   9915 ** sqlite3_rtree_geometry.
   9916 */
   9917 struct sqlite3_rtree_query_info {
   9918   void *pContext;                   /* pContext from when function registered */
   9919   int nParam;                       /* Number of function parameters */
   9920   sqlite3_rtree_dbl *aParam;        /* value of function parameters */
   9921   void *pUser;                      /* callback can use this, if desired */
   9922   void (*xDelUser)(void*);          /* function to free pUser */
   9923   sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
   9924   unsigned int *anQueue;            /* Number of pending entries in the queue */
   9925   int nCoord;                       /* Number of coordinates */
   9926   int iLevel;                       /* Level of current node or entry */
   9927   int mxLevel;                      /* The largest iLevel value in the tree */
   9928   sqlite3_int64 iRowid;             /* Rowid for current entry */
   9929   sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
   9930   int eParentWithin;                /* Visibility of parent node */
   9931   int eWithin;                      /* OUT: Visiblity */
   9932   sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
   9933   /* The following fields are only available in 3.8.11 and later */
   9934   sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
   9935 };
   9936 
   9937 /*
   9938 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
   9939 */
   9940 #define NOT_WITHIN       0   /* Object completely outside of query region */
   9941 #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
   9942 #define FULLY_WITHIN     2   /* Object fully contained within query region */
   9943 
   9944 
   9945 #if 0
   9946 }  /* end of the 'extern "C"' block */
   9947 #endif
   9948 
   9949 #endif  /* ifndef _SQLITE3RTREE_H_ */
   9950 
   9951 /******** End of sqlite3rtree.h *********/
   9952 /******** Begin file sqlite3session.h *********/
   9953 
   9954 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
   9955 #define __SQLITESESSION_H_ 1
   9956 
   9957 /*
   9958 ** Make sure we can call this stuff from C++.
   9959 */
   9960 #if 0
   9961 extern "C" {
   9962 #endif
   9963 
   9964 
   9965 /*
   9966 ** CAPI3REF: Session Object Handle
   9967 */
   9968 typedef struct sqlite3_session sqlite3_session;
   9969 
   9970 /*
   9971 ** CAPI3REF: Changeset Iterator Handle
   9972 */
   9973 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
   9974 
   9975 /*
   9976 ** CAPI3REF: Create A New Session Object
   9977 **
   9978 ** Create a new session object attached to database handle db. If successful,
   9979 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
   9980 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
   9981 ** error code (e.g. SQLITE_NOMEM) is returned.
   9982 **
   9983 ** It is possible to create multiple session objects attached to a single
   9984 ** database handle.
   9985 **
   9986 ** Session objects created using this function should be deleted using the
   9987 ** [sqlite3session_delete()] function before the database handle that they
   9988 ** are attached to is itself closed. If the database handle is closed before
   9989 ** the session object is deleted, then the results of calling any session
   9990 ** module function, including [sqlite3session_delete()] on the session object
   9991 ** are undefined.
   9992 **
   9993 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
   9994 ** is not possible for an application to register a pre-update hook on a
   9995 ** database handle that has one or more session objects attached. Nor is
   9996 ** it possible to create a session object attached to a database handle for
   9997 ** which a pre-update hook is already defined. The results of attempting
   9998 ** either of these things are undefined.
   9999 **
   10000 ** The session object will be used to create changesets for tables in
   10001 ** database zDb, where zDb is either "main", or "temp", or the name of an
   10002 ** attached database. It is not an error if database zDb is not attached
   10003 ** to the database when the session object is created.
   10004 */
   10005 SQLITE_API int sqlite3session_create(
   10006   sqlite3 *db,                    /* Database handle */
   10007   const char *zDb,                /* Name of db (e.g. "main") */
   10008   sqlite3_session **ppSession     /* OUT: New session object */
   10009 );
   10010 
   10011 /*
   10012 ** CAPI3REF: Delete A Session Object
   10013 **
   10014 ** Delete a session object previously allocated using
   10015 ** [sqlite3session_create()]. Once a session object has been deleted, the
   10016 ** results of attempting to use pSession with any other session module
   10017 ** function are undefined.
   10018 **
   10019 ** Session objects must be deleted before the database handle to which they
   10020 ** are attached is closed. Refer to the documentation for
   10021 ** [sqlite3session_create()] for details.
   10022 */
   10023 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
   10024 
   10025 
   10026 /*
   10027 ** CAPI3REF: Enable Or Disable A Session Object
   10028 **
   10029 ** Enable or disable the recording of changes by a session object. When
   10030 ** enabled, a session object records changes made to the database. When
   10031 ** disabled - it does not. A newly created session object is enabled.
   10032 ** Refer to the documentation for [sqlite3session_changeset()] for further
   10033 ** details regarding how enabling and disabling a session object affects
   10034 ** the eventual changesets.
   10035 **
   10036 ** Passing zero to this function disables the session. Passing a value
   10037 ** greater than zero enables it. Passing a value less than zero is a
   10038 ** no-op, and may be used to query the current state of the session.
   10039 **
   10040 ** The return value indicates the final state of the session object: 0 if
   10041 ** the session is disabled, or 1 if it is enabled.
   10042 */
   10043 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
   10044 
   10045 /*
   10046 ** CAPI3REF: Set Or Clear the Indirect Change Flag
   10047 **
   10048 ** Each change recorded by a session object is marked as either direct or
   10049 ** indirect. A change is marked as indirect if either:
   10050 **
   10051 ** <ul>
   10052 **   <li> The session object "indirect" flag is set when the change is
   10053 **        made, or
   10054 **   <li> The change is made by an SQL trigger or foreign key action
   10055 **        instead of directly as a result of a users SQL statement.
   10056 ** </ul>
   10057 **
   10058 ** If a single row is affected by more than one operation within a session,
   10059 ** then the change is considered indirect if all operations meet the criteria
   10060 ** for an indirect change above, or direct otherwise.
   10061 **
   10062 ** This function is used to set, clear or query the session object indirect
   10063 ** flag.  If the second argument passed to this function is zero, then the
   10064 ** indirect flag is cleared. If it is greater than zero, the indirect flag
   10065 ** is set. Passing a value less than zero does not modify the current value
   10066 ** of the indirect flag, and may be used to query the current state of the
   10067 ** indirect flag for the specified session object.
   10068 **
   10069 ** The return value indicates the final state of the indirect flag: 0 if
   10070 ** it is clear, or 1 if it is set.
   10071 */
   10072 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
   10073 
   10074 /*
   10075 ** CAPI3REF: Attach A Table To A Session Object
   10076 **
   10077 ** If argument zTab is not NULL, then it is the name of a table to attach
   10078 ** to the session object passed as the first argument. All subsequent changes
   10079 ** made to the table while the session object is enabled will be recorded. See
   10080 ** documentation for [sqlite3session_changeset()] for further details.
   10081 **
   10082 ** Or, if argument zTab is NULL, then changes are recorded for all tables
   10083 ** in the database. If additional tables are added to the database (by
   10084 ** executing "CREATE TABLE" statements) after this call is made, changes for
   10085 ** the new tables are also recorded.
   10086 **
   10087 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
   10088 ** defined as part of their CREATE TABLE statement. It does not matter if the
   10089 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
   10090 ** KEY may consist of a single column, or may be a composite key.
   10091 **
   10092 ** It is not an error if the named table does not exist in the database. Nor
   10093 ** is it an error if the named table does not have a PRIMARY KEY. However,
   10094 ** no changes will be recorded in either of these scenarios.
   10095 **
   10096 ** Changes are not recorded for individual rows that have NULL values stored
   10097 ** in one or more of their PRIMARY KEY columns.
   10098 **
   10099 ** SQLITE_OK is returned if the call completes without error. Or, if an error
   10100 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
   10101 **
   10102 ** <h3>Special sqlite_stat1 Handling</h3>
   10103 **
   10104 ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
   10105 ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
   10106 **  <pre>
   10107 **  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)
   10108 **  </pre>
   10109 **
   10110 ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
   10111 ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
   10112 ** are recorded for rows for which (idx IS NULL) is true. However, for such
   10113 ** rows a zero-length blob (SQL value X'') is stored in the changeset or
   10114 ** patchset instead of a NULL value. This allows such changesets to be
   10115 ** manipulated by legacy implementations of sqlite3changeset_invert(),
   10116 ** concat() and similar.
   10117 **
   10118 ** The sqlite3changeset_apply() function automatically converts the
   10119 ** zero-length blob back to a NULL value when updating the sqlite_stat1
   10120 ** table. However, if the application calls sqlite3changeset_new(),
   10121 ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
   10122 ** iterator directly (including on a changeset iterator passed to a
   10123 ** conflict-handler callback) then the X'' value is returned. The application
   10124 ** must translate X'' to NULL itself if required.
   10125 **
   10126 ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
   10127 ** changes made to the sqlite_stat1 table. Legacy versions of the
   10128 ** sqlite3changeset_apply() function silently ignore any modifications to the
   10129 ** sqlite_stat1 table that are part of a changeset or patchset.
   10130 */
   10131 SQLITE_API int sqlite3session_attach(
   10132   sqlite3_session *pSession,      /* Session object */
   10133   const char *zTab                /* Table name */
   10134 );
   10135 
   10136 /*
   10137 ** CAPI3REF: Set a table filter on a Session Object.
   10138 **
   10139 ** The second argument (xFilter) is the "filter callback". For changes to rows
   10140 ** in tables that are not attached to the Session object, the filter is called
   10141 ** to determine whether changes to the table's rows should be tracked or not.
   10142 ** If xFilter returns 0, changes is not tracked. Note that once a table is
   10143 ** attached, xFilter will not be called again.
   10144 */
   10145 SQLITE_API void sqlite3session_table_filter(
   10146   sqlite3_session *pSession,      /* Session object */
   10147   int(*xFilter)(
   10148     void *pCtx,                   /* Copy of third arg to _filter_table() */
   10149     const char *zTab              /* Table name */
   10150   ),
   10151   void *pCtx                      /* First argument passed to xFilter */
   10152 );
   10153 
   10154 /*
   10155 ** CAPI3REF: Generate A Changeset From A Session Object
   10156 **
   10157 ** Obtain a changeset containing changes to the tables attached to the
   10158 ** session object passed as the first argument. If successful,
   10159 ** set *ppChangeset to point to a buffer containing the changeset
   10160 ** and *pnChangeset to the size of the changeset in bytes before returning
   10161 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
   10162 ** zero and return an SQLite error code.
   10163 **
   10164 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
   10165 ** each representing a change to a single row of an attached table. An INSERT
   10166 ** change contains the values of each field of a new database row. A DELETE
   10167 ** contains the original values of each field of a deleted database row. An
   10168 ** UPDATE change contains the original values of each field of an updated
   10169 ** database row along with the updated values for each updated non-primary-key
   10170 ** column. It is not possible for an UPDATE change to represent a change that
   10171 ** modifies the values of primary key columns. If such a change is made, it
   10172 ** is represented in a changeset as a DELETE followed by an INSERT.
   10173 **
   10174 ** Changes are not recorded for rows that have NULL values stored in one or
   10175 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
   10176 ** no corresponding change is present in the changesets returned by this
   10177 ** function. If an existing row with one or more NULL values stored in
   10178 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
   10179 ** only an INSERT is appears in the changeset. Similarly, if an existing row
   10180 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
   10181 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
   10182 ** DELETE change only.
   10183 **
   10184 ** The contents of a changeset may be traversed using an iterator created
   10185 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
   10186 ** a database with a compatible schema using the [sqlite3changeset_apply()]
   10187 ** API.
   10188 **
   10189 ** Within a changeset generated by this function, all changes related to a
   10190 ** single table are grouped together. In other words, when iterating through
   10191 ** a changeset or when applying a changeset to a database, all changes related
   10192 ** to a single table are processed before moving on to the next table. Tables
   10193 ** are sorted in the same order in which they were attached (or auto-attached)
   10194 ** to the sqlite3_session object. The order in which the changes related to
   10195 ** a single table are stored is undefined.
   10196 **
   10197 ** Following a successful call to this function, it is the responsibility of
   10198 ** the caller to eventually free the buffer that *ppChangeset points to using
   10199 ** [sqlite3_free()].
   10200 **
   10201 ** <h3>Changeset Generation</h3>
   10202 **
   10203 ** Once a table has been attached to a session object, the session object
   10204 ** records the primary key values of all new rows inserted into the table.
   10205 ** It also records the original primary key and other column values of any
   10206 ** deleted or updated rows. For each unique primary key value, data is only
   10207 ** recorded once - the first time a row with said primary key is inserted,
   10208 ** updated or deleted in the lifetime of the session.
   10209 **
   10210 ** There is one exception to the previous paragraph: when a row is inserted,
   10211 ** updated or deleted, if one or more of its primary key columns contain a
   10212 ** NULL value, no record of the change is made.
   10213 **
   10214 ** The session object therefore accumulates two types of records - those
   10215 ** that consist of primary key values only (created when the user inserts
   10216 ** a new record) and those that consist of the primary key values and the
   10217 ** original values of other table columns (created when the users deletes
   10218 ** or updates a record).
   10219 **
   10220 ** When this function is called, the requested changeset is created using
   10221 ** both the accumulated records and the current contents of the database
   10222 ** file. Specifically:
   10223 **
   10224 ** <ul>
   10225 **   <li> For each record generated by an insert, the database is queried
   10226 **        for a row with a matching primary key. If one is found, an INSERT
   10227 **        change is added to the changeset. If no such row is found, no change
   10228 **        is added to the changeset.
   10229 **
   10230 **   <li> For each record generated by an update or delete, the database is
   10231 **        queried for a row with a matching primary key. If such a row is
   10232 **        found and one or more of the non-primary key fields have been
   10233 **        modified from their original values, an UPDATE change is added to
   10234 **        the changeset. Or, if no such row is found in the table, a DELETE
   10235 **        change is added to the changeset. If there is a row with a matching
   10236 **        primary key in the database, but all fields contain their original
   10237 **        values, no change is added to the changeset.
   10238 ** </ul>
   10239 **
   10240 ** This means, amongst other things, that if a row is inserted and then later
   10241 ** deleted while a session object is active, neither the insert nor the delete
   10242 ** will be present in the changeset. Or if a row is deleted and then later a
   10243 ** row with the same primary key values inserted while a session object is
   10244 ** active, the resulting changeset will contain an UPDATE change instead of
   10245 ** a DELETE and an INSERT.
   10246 **
   10247 ** When a session object is disabled (see the [sqlite3session_enable()] API),
   10248 ** it does not accumulate records when rows are inserted, updated or deleted.
   10249 ** This may appear to have some counter-intuitive effects if a single row
   10250 ** is written to more than once during a session. For example, if a row
   10251 ** is inserted while a session object is enabled, then later deleted while
   10252 ** the same session object is disabled, no INSERT record will appear in the
   10253 ** changeset, even though the delete took place while the session was disabled.
   10254 ** Or, if one field of a row is updated while a session is disabled, and
   10255 ** another field of the same row is updated while the session is enabled, the
   10256 ** resulting changeset will contain an UPDATE change that updates both fields.
   10257 */
   10258 SQLITE_API int sqlite3session_changeset(
   10259   sqlite3_session *pSession,      /* Session object */
   10260   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
   10261   void **ppChangeset              /* OUT: Buffer containing changeset */
   10262 );
   10263 
   10264 /*
   10265 ** CAPI3REF: Load The Difference Between Tables Into A Session
   10266 **
   10267 ** If it is not already attached to the session object passed as the first
   10268 ** argument, this function attaches table zTbl in the same manner as the
   10269 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
   10270 ** does not have a primary key, this function is a no-op (but does not return
   10271 ** an error).
   10272 **
   10273 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
   10274 ** attached to the same database handle as the session object that contains
   10275 ** a table compatible with the table attached to the session by this function.
   10276 ** A table is considered compatible if it:
   10277 **
   10278 ** <ul>
   10279 **   <li> Has the same name,
   10280 **   <li> Has the same set of columns declared in the same order, and
   10281 **   <li> Has the same PRIMARY KEY definition.
   10282 ** </ul>
   10283 **
   10284 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
   10285 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
   10286 ** but no changes are added to the session object. As with other session
   10287 ** APIs, tables without PRIMARY KEYs are simply ignored.
   10288 **
   10289 ** This function adds a set of changes to the session object that could be
   10290 ** used to update the table in database zFrom (call this the "from-table")
   10291 ** so that its content is the same as the table attached to the session
   10292 ** object (call this the "to-table"). Specifically:
   10293 **
   10294 ** <ul>
   10295 **   <li> For each row (primary key) that exists in the to-table but not in
   10296 **     the from-table, an INSERT record is added to the session object.
   10297 **
   10298 **   <li> For each row (primary key) that exists in the to-table but not in
   10299 **     the from-table, a DELETE record is added to the session object.
   10300 **
   10301 **   <li> For each row (primary key) that exists in both tables, but features
   10302 **     different non-PK values in each, an UPDATE record is added to the
   10303 **     session.
   10304 ** </ul>
   10305 **
   10306 ** To clarify, if this function is called and then a changeset constructed
   10307 ** using [sqlite3session_changeset()], then after applying that changeset to
   10308 ** database zFrom the contents of the two compatible tables would be
   10309 ** identical.
   10310 **
   10311 ** It an error if database zFrom does not exist or does not contain the
   10312 ** required compatible table.
   10313 **
   10314 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
   10315 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
   10316 ** may be set to point to a buffer containing an English language error
   10317 ** message. It is the responsibility of the caller to free this buffer using
   10318 ** sqlite3_free().
   10319 */
   10320 SQLITE_API int sqlite3session_diff(
   10321   sqlite3_session *pSession,
   10322   const char *zFromDb,
   10323   const char *zTbl,
   10324   char **pzErrMsg
   10325 );
   10326 
   10327 
   10328 /*
   10329 ** CAPI3REF: Generate A Patchset From A Session Object
   10330 **
   10331 ** The differences between a patchset and a changeset are that:
   10332 **
   10333 ** <ul>
   10334 **   <li> DELETE records consist of the primary key fields only. The
   10335 **        original values of other fields are omitted.
   10336 **   <li> The original values of any modified fields are omitted from
   10337 **        UPDATE records.
   10338 ** </ul>
   10339 **
   10340 ** A patchset blob may be used with up to date versions of all
   10341 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
   10342 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
   10343 ** attempting to use a patchset blob with old versions of the
   10344 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
   10345 **
   10346 ** Because the non-primary key "old.*" fields are omitted, no
   10347 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
   10348 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
   10349 ** in the same way as for changesets.
   10350 **
   10351 ** Changes within a patchset are ordered in the same way as for changesets
   10352 ** generated by the sqlite3session_changeset() function (i.e. all changes for
   10353 ** a single table are grouped together, tables appear in the order in which
   10354 ** they were attached to the session object).
   10355 */
   10356 SQLITE_API int sqlite3session_patchset(
   10357   sqlite3_session *pSession,      /* Session object */
   10358   int *pnPatchset,                /* OUT: Size of buffer at *ppPatchset */
   10359   void **ppPatchset               /* OUT: Buffer containing patchset */
   10360 );
   10361 
   10362 /*
   10363 ** CAPI3REF: Test if a changeset has recorded any changes.
   10364 **
   10365 ** Return non-zero if no changes to attached tables have been recorded by
   10366 ** the session object passed as the first argument. Otherwise, if one or
   10367 ** more changes have been recorded, return zero.
   10368 **
   10369 ** Even if this function returns zero, it is possible that calling
   10370 ** [sqlite3session_changeset()] on the session handle may still return a
   10371 ** changeset that contains no changes. This can happen when a row in
   10372 ** an attached table is modified and then later on the original values
   10373 ** are restored. However, if this function returns non-zero, then it is
   10374 ** guaranteed that a call to sqlite3session_changeset() will return a
   10375 ** changeset containing zero changes.
   10376 */
   10377 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
   10378 
   10379 /*
   10380 ** CAPI3REF: Create An Iterator To Traverse A Changeset
   10381 **
   10382 ** Create an iterator used to iterate through the contents of a changeset.
   10383 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
   10384 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
   10385 ** SQLite error code is returned.
   10386 **
   10387 ** The following functions can be used to advance and query a changeset
   10388 ** iterator created by this function:
   10389 **
   10390 ** <ul>
   10391 **   <li> [sqlite3changeset_next()]
   10392 **   <li> [sqlite3changeset_op()]
   10393 **   <li> [sqlite3changeset_new()]
   10394 **   <li> [sqlite3changeset_old()]
   10395 ** </ul>
   10396 **
   10397 ** It is the responsibility of the caller to eventually destroy the iterator
   10398 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
   10399 ** changeset (pChangeset) must remain valid until after the iterator is
   10400 ** destroyed.
   10401 **
   10402 ** Assuming the changeset blob was created by one of the
   10403 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
   10404 ** [sqlite3changeset_invert()] functions, all changes within the changeset
   10405 ** that apply to a single table are grouped together. This means that when
   10406 ** an application iterates through a changeset using an iterator created by
   10407 ** this function, all changes that relate to a single table are visited
   10408 ** consecutively. There is no chance that the iterator will visit a change
   10409 ** the applies to table X, then one for table Y, and then later on visit
   10410 ** another change for table X.
   10411 */
   10412 SQLITE_API int sqlite3changeset_start(
   10413   sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
   10414   int nChangeset,                 /* Size of changeset blob in bytes */
   10415   void *pChangeset                /* Pointer to blob containing changeset */
   10416 );
   10417 
   10418 
   10419 /*
   10420 ** CAPI3REF: Advance A Changeset Iterator
   10421 **
   10422 ** This function may only be used with iterators created by function
   10423 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
   10424 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
   10425 ** is returned and the call has no effect.
   10426 **
   10427 ** Immediately after an iterator is created by sqlite3changeset_start(), it
   10428 ** does not point to any change in the changeset. Assuming the changeset
   10429 ** is not empty, the first call to this function advances the iterator to
   10430 ** point to the first change in the changeset. Each subsequent call advances
   10431 ** the iterator to point to the next change in the changeset (if any). If
   10432 ** no error occurs and the iterator points to a valid change after a call
   10433 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
   10434 ** Otherwise, if all changes in the changeset have already been visited,
   10435 ** SQLITE_DONE is returned.
   10436 **
   10437 ** If an error occurs, an SQLite error code is returned. Possible error
   10438 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
   10439 ** SQLITE_NOMEM.
   10440 */
   10441 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
   10442 
   10443 /*
   10444 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
   10445 **
   10446 ** The pIter argument passed to this function may either be an iterator
   10447 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
   10448 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
   10449 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
   10450 ** is not the case, this function returns [SQLITE_MISUSE].
   10451 **
   10452 ** If argument pzTab is not NULL, then *pzTab is set to point to a
   10453 ** nul-terminated utf-8 encoded string containing the name of the table
   10454 ** affected by the current change. The buffer remains valid until either
   10455 ** sqlite3changeset_next() is called on the iterator or until the
   10456 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
   10457 ** set to the number of columns in the table affected by the change. If
   10458 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
   10459 ** is an indirect change, or false (0) otherwise. See the documentation for
   10460 ** [sqlite3session_indirect()] for a description of direct and indirect
   10461 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
   10462 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
   10463 ** type of change that the iterator currently points to.
   10464 **
   10465 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
   10466 ** SQLite error code is returned. The values of the output variables may not
   10467 ** be trusted in this case.
   10468 */
   10469 SQLITE_API int sqlite3changeset_op(
   10470   sqlite3_changeset_iter *pIter,  /* Iterator object */
   10471   const char **pzTab,             /* OUT: Pointer to table name */
   10472   int *pnCol,                     /* OUT: Number of columns in table */
   10473   int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
   10474   int *pbIndirect                 /* OUT: True for an 'indirect' change */
   10475 );
   10476 
   10477 /*
   10478 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
   10479 **
   10480 ** For each modified table, a changeset includes the following:
   10481 **
   10482 ** <ul>
   10483 **   <li> The number of columns in the table, and
   10484 **   <li> Which of those columns make up the tables PRIMARY KEY.
   10485 ** </ul>
   10486 **
   10487 ** This function is used to find which columns comprise the PRIMARY KEY of
   10488 ** the table modified by the change that iterator pIter currently points to.
   10489 ** If successful, *pabPK is set to point to an array of nCol entries, where
   10490 ** nCol is the number of columns in the table. Elements of *pabPK are set to
   10491 ** 0x01 if the corresponding column is part of the tables primary key, or
   10492 ** 0x00 if it is not.
   10493 **
   10494 ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
   10495 ** in the table.
   10496 **
   10497 ** If this function is called when the iterator does not point to a valid
   10498 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
   10499 ** SQLITE_OK is returned and the output variables populated as described
   10500 ** above.
   10501 */
   10502 SQLITE_API int sqlite3changeset_pk(
   10503   sqlite3_changeset_iter *pIter,  /* Iterator object */
   10504   unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
   10505   int *pnCol                      /* OUT: Number of entries in output array */
   10506 );
   10507 
   10508 /*
   10509 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
   10510 **
   10511 ** The pIter argument passed to this function may either be an iterator
   10512 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
   10513 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
   10514 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
   10515 ** Furthermore, it may only be called if the type of change that the iterator
   10516 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
   10517 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
   10518 **
   10519 ** Argument iVal must be greater than or equal to 0, and less than the number
   10520 ** of columns in the table affected by the current change. Otherwise,
   10521 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
   10522 **
   10523 ** If successful, this function sets *ppValue to point to a protected
   10524 ** sqlite3_value object containing the iVal'th value from the vector of
   10525 ** original row values stored as part of the UPDATE or DELETE change and
   10526 ** returns SQLITE_OK. The name of the function comes from the fact that this
   10527 ** is similar to the "old.*" columns available to update or delete triggers.
   10528 **
   10529 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
   10530 ** is returned and *ppValue is set to NULL.
   10531 */
   10532 SQLITE_API int sqlite3changeset_old(
   10533   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   10534   int iVal,                       /* Column number */
   10535   sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
   10536 );
   10537 
   10538 /*
   10539 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
   10540 **
   10541 ** The pIter argument passed to this function may either be an iterator
   10542 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
   10543 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
   10544 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
   10545 ** Furthermore, it may only be called if the type of change that the iterator
   10546 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
   10547 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
   10548 **
   10549 ** Argument iVal must be greater than or equal to 0, and less than the number
   10550 ** of columns in the table affected by the current change. Otherwise,
   10551 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
   10552 **
   10553 ** If successful, this function sets *ppValue to point to a protected
   10554 ** sqlite3_value object containing the iVal'th value from the vector of
   10555 ** new row values stored as part of the UPDATE or INSERT change and
   10556 ** returns SQLITE_OK. If the change is an UPDATE and does not include
   10557 ** a new value for the requested column, *ppValue is set to NULL and
   10558 ** SQLITE_OK returned. The name of the function comes from the fact that
   10559 ** this is similar to the "new.*" columns available to update or delete
   10560 ** triggers.
   10561 **
   10562 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
   10563 ** is returned and *ppValue is set to NULL.
   10564 */
   10565 SQLITE_API int sqlite3changeset_new(
   10566   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   10567   int iVal,                       /* Column number */
   10568   sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
   10569 );
   10570 
   10571 /*
   10572 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
   10573 **
   10574 ** This function should only be used with iterator objects passed to a
   10575 ** conflict-handler callback by [sqlite3changeset_apply()] with either
   10576 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
   10577 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
   10578 ** is set to NULL.
   10579 **
   10580 ** Argument iVal must be greater than or equal to 0, and less than the number
   10581 ** of columns in the table affected by the current change. Otherwise,
   10582 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
   10583 **
   10584 ** If successful, this function sets *ppValue to point to a protected
   10585 ** sqlite3_value object containing the iVal'th value from the
   10586 ** "conflicting row" associated with the current conflict-handler callback
   10587 ** and returns SQLITE_OK.
   10588 **
   10589 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
   10590 ** is returned and *ppValue is set to NULL.
   10591 */
   10592 SQLITE_API int sqlite3changeset_conflict(
   10593   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   10594   int iVal,                       /* Column number */
   10595   sqlite3_value **ppValue         /* OUT: Value from conflicting row */
   10596 );
   10597 
   10598 /*
   10599 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
   10600 **
   10601 ** This function may only be called with an iterator passed to an
   10602 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
   10603 ** it sets the output variable to the total number of known foreign key
   10604 ** violations in the destination database and returns SQLITE_OK.
   10605 **
   10606 ** In all other cases this function returns SQLITE_MISUSE.
   10607 */
   10608 SQLITE_API int sqlite3changeset_fk_conflicts(
   10609   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   10610   int *pnOut                      /* OUT: Number of FK violations */
   10611 );
   10612 
   10613 
   10614 /*
   10615 ** CAPI3REF: Finalize A Changeset Iterator
   10616 **
   10617 ** This function is used to finalize an iterator allocated with
   10618 ** [sqlite3changeset_start()].
   10619 **
   10620 ** This function should only be called on iterators created using the
   10621 ** [sqlite3changeset_start()] function. If an application calls this
   10622 ** function with an iterator passed to a conflict-handler by
   10623 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
   10624 ** call has no effect.
   10625 **
   10626 ** If an error was encountered within a call to an sqlite3changeset_xxx()
   10627 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
   10628 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
   10629 ** to that error is returned by this function. Otherwise, SQLITE_OK is
   10630 ** returned. This is to allow the following pattern (pseudo-code):
   10631 **
   10632 **   sqlite3changeset_start();
   10633 **   while( SQLITE_ROW==sqlite3changeset_next() ){
   10634 **     // Do something with change.
   10635 **   }
   10636 **   rc = sqlite3changeset_finalize();
   10637 **   if( rc!=SQLITE_OK ){
   10638 **     // An error has occurred
   10639 **   }
   10640 */
   10641 SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
   10642 
   10643 /*
   10644 ** CAPI3REF: Invert A Changeset
   10645 **
   10646 ** This function is used to "invert" a changeset object. Applying an inverted
   10647 ** changeset to a database reverses the effects of applying the uninverted
   10648 ** changeset. Specifically:
   10649 **
   10650 ** <ul>
   10651 **   <li> Each DELETE change is changed to an INSERT, and
   10652 **   <li> Each INSERT change is changed to a DELETE, and
   10653 **   <li> For each UPDATE change, the old.* and new.* values are exchanged.
   10654 ** </ul>
   10655 **
   10656 ** This function does not change the order in which changes appear within
   10657 ** the changeset. It merely reverses the sense of each individual change.
   10658 **
   10659 ** If successful, a pointer to a buffer containing the inverted changeset
   10660 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
   10661 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
   10662 ** zeroed and an SQLite error code returned.
   10663 **
   10664 ** It is the responsibility of the caller to eventually call sqlite3_free()
   10665 ** on the *ppOut pointer to free the buffer allocation following a successful
   10666 ** call to this function.
   10667 **
   10668 ** WARNING/TODO: This function currently assumes that the input is a valid
   10669 ** changeset. If it is not, the results are undefined.
   10670 */
   10671 SQLITE_API int sqlite3changeset_invert(
   10672   int nIn, const void *pIn,       /* Input changeset */
   10673   int *pnOut, void **ppOut        /* OUT: Inverse of input */
   10674 );
   10675 
   10676 /*
   10677 ** CAPI3REF: Concatenate Two Changeset Objects
   10678 **
   10679 ** This function is used to concatenate two changesets, A and B, into a
   10680 ** single changeset. The result is a changeset equivalent to applying
   10681 ** changeset A followed by changeset B.
   10682 **
   10683 ** This function combines the two input changesets using an
   10684 ** sqlite3_changegroup object. Calling it produces similar results as the
   10685 ** following code fragment:
   10686 **
   10687 **   sqlite3_changegroup *pGrp;
   10688 **   rc = sqlite3_changegroup_new(&pGrp);
   10689 **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
   10690 **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
   10691 **   if( rc==SQLITE_OK ){
   10692 **     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
   10693 **   }else{
   10694 **     *ppOut = 0;
   10695 **     *pnOut = 0;
   10696 **   }
   10697 **
   10698 ** Refer to the sqlite3_changegroup documentation below for details.
   10699 */
   10700 SQLITE_API int sqlite3changeset_concat(
   10701   int nA,                         /* Number of bytes in buffer pA */
   10702   void *pA,                       /* Pointer to buffer containing changeset A */
   10703   int nB,                         /* Number of bytes in buffer pB */
   10704   void *pB,                       /* Pointer to buffer containing changeset B */
   10705   int *pnOut,                     /* OUT: Number of bytes in output changeset */
   10706   void **ppOut                    /* OUT: Buffer containing output changeset */
   10707 );
   10708 
   10709 
   10710 /*
   10711 ** CAPI3REF: Changegroup Handle
   10712 */
   10713 typedef struct sqlite3_changegroup sqlite3_changegroup;
   10714 
   10715 /*
   10716 ** CAPI3REF: Create A New Changegroup Object
   10717 **
   10718 ** An sqlite3_changegroup object is used to combine two or more changesets
   10719 ** (or patchsets) into a single changeset (or patchset). A single changegroup
   10720 ** object may combine changesets or patchsets, but not both. The output is
   10721 ** always in the same format as the input.
   10722 **
   10723 ** If successful, this function returns SQLITE_OK and populates (*pp) with
   10724 ** a pointer to a new sqlite3_changegroup object before returning. The caller
   10725 ** should eventually free the returned object using a call to
   10726 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
   10727 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
   10728 **
   10729 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
   10730 **
   10731 ** <ul>
   10732 **   <li> It is created using a call to sqlite3changegroup_new().
   10733 **
   10734 **   <li> Zero or more changesets (or patchsets) are added to the object
   10735 **        by calling sqlite3changegroup_add().
   10736 **
   10737 **   <li> The result of combining all input changesets together is obtained
   10738 **        by the application via a call to sqlite3changegroup_output().
   10739 **
   10740 **   <li> The object is deleted using a call to sqlite3changegroup_delete().
   10741 ** </ul>
   10742 **
   10743 ** Any number of calls to add() and output() may be made between the calls to
   10744 ** new() and delete(), and in any order.
   10745 **
   10746 ** As well as the regular sqlite3changegroup_add() and
   10747 ** sqlite3changegroup_output() functions, also available are the streaming
   10748 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
   10749 */
   10750 SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
   10751 
   10752 /*
   10753 ** CAPI3REF: Add A Changeset To A Changegroup
   10754 **
   10755 ** Add all changes within the changeset (or patchset) in buffer pData (size
   10756 ** nData bytes) to the changegroup.
   10757 **
   10758 ** If the buffer contains a patchset, then all prior calls to this function
   10759 ** on the same changegroup object must also have specified patchsets. Or, if
   10760 ** the buffer contains a changeset, so must have the earlier calls to this
   10761 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
   10762 ** to the changegroup.
   10763 **
   10764 ** Rows within the changeset and changegroup are identified by the values in
   10765 ** their PRIMARY KEY columns. A change in the changeset is considered to
   10766 ** apply to the same row as a change already present in the changegroup if
   10767 ** the two rows have the same primary key.
   10768 **
   10769 ** Changes to rows that do not already appear in the changegroup are
   10770 ** simply copied into it. Or, if both the new changeset and the changegroup
   10771 ** contain changes that apply to a single row, the final contents of the
   10772 ** changegroup depends on the type of each change, as follows:
   10773 **
   10774 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
   10775 **   <tr><th style="white-space:pre">Existing Change  </th>
   10776 **       <th style="white-space:pre">New Change       </th>
   10777 **       <th>Output Change
   10778 **   <tr><td>INSERT <td>INSERT <td>
   10779 **       The new change is ignored. This case does not occur if the new
   10780 **       changeset was recorded immediately after the changesets already
   10781 **       added to the changegroup.
   10782 **   <tr><td>INSERT <td>UPDATE <td>
   10783 **       The INSERT change remains in the changegroup. The values in the
   10784 **       INSERT change are modified as if the row was inserted by the
   10785 **       existing change and then updated according to the new change.
   10786 **   <tr><td>INSERT <td>DELETE <td>
   10787 **       The existing INSERT is removed from the changegroup. The DELETE is
   10788 **       not added.
   10789 **   <tr><td>UPDATE <td>INSERT <td>
   10790 **       The new change is ignored. This case does not occur if the new
   10791 **       changeset was recorded immediately after the changesets already
   10792 **       added to the changegroup.
   10793 **   <tr><td>UPDATE <td>UPDATE <td>
   10794 **       The existing UPDATE remains within the changegroup. It is amended
   10795 **       so that the accompanying values are as if the row was updated once
   10796 **       by the existing change and then again by the new change.
   10797 **   <tr><td>UPDATE <td>DELETE <td>
   10798 **       The existing UPDATE is replaced by the new DELETE within the
   10799 **       changegroup.
   10800 **   <tr><td>DELETE <td>INSERT <td>
   10801 **       If one or more of the column values in the row inserted by the
   10802 **       new change differ from those in the row deleted by the existing
   10803 **       change, the existing DELETE is replaced by an UPDATE within the
   10804 **       changegroup. Otherwise, if the inserted row is exactly the same
   10805 **       as the deleted row, the existing DELETE is simply discarded.
   10806 **   <tr><td>DELETE <td>UPDATE <td>
   10807 **       The new change is ignored. This case does not occur if the new
   10808 **       changeset was recorded immediately after the changesets already
   10809 **       added to the changegroup.
   10810 **   <tr><td>DELETE <td>DELETE <td>
   10811 **       The new change is ignored. This case does not occur if the new
   10812 **       changeset was recorded immediately after the changesets already
   10813 **       added to the changegroup.
   10814 ** </table>
   10815 **
   10816 ** If the new changeset contains changes to a table that is already present
   10817 ** in the changegroup, then the number of columns and the position of the
   10818 ** primary key columns for the table must be consistent. If this is not the
   10819 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
   10820 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
   10821 ** returned. Or, if an out-of-memory condition occurs during processing, this
   10822 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
   10823 ** final contents of the changegroup is undefined.
   10824 **
   10825 ** If no error occurs, SQLITE_OK is returned.
   10826 */
   10827 SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
   10828 
   10829 /*
   10830 ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
   10831 **
   10832 ** Obtain a buffer containing a changeset (or patchset) representing the
   10833 ** current contents of the changegroup. If the inputs to the changegroup
   10834 ** were themselves changesets, the output is a changeset. Or, if the
   10835 ** inputs were patchsets, the output is also a patchset.
   10836 **
   10837 ** As with the output of the sqlite3session_changeset() and
   10838 ** sqlite3session_patchset() functions, all changes related to a single
   10839 ** table are grouped together in the output of this function. Tables appear
   10840 ** in the same order as for the very first changeset added to the changegroup.
   10841 ** If the second or subsequent changesets added to the changegroup contain
   10842 ** changes for tables that do not appear in the first changeset, they are
   10843 ** appended onto the end of the output changeset, again in the order in
   10844 ** which they are first encountered.
   10845 **
   10846 ** If an error occurs, an SQLite error code is returned and the output
   10847 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
   10848 ** is returned and the output variables are set to the size of and a
   10849 ** pointer to the output buffer, respectively. In this case it is the
   10850 ** responsibility of the caller to eventually free the buffer using a
   10851 ** call to sqlite3_free().
   10852 */
   10853 SQLITE_API int sqlite3changegroup_output(
   10854   sqlite3_changegroup*,
   10855   int *pnData,                    /* OUT: Size of output buffer in bytes */
   10856   void **ppData                   /* OUT: Pointer to output buffer */
   10857 );
   10858 
   10859 /*
   10860 ** CAPI3REF: Delete A Changegroup Object
   10861 */
   10862 SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
   10863 
   10864 /*
   10865 ** CAPI3REF: Apply A Changeset To A Database
   10866 **
   10867 ** Apply a changeset to a database. This function attempts to update the
   10868 ** "main" database attached to handle db with the changes found in the
   10869 ** changeset passed via the second and third arguments.
   10870 **
   10871 ** The fourth argument (xFilter) passed to this function is the "filter
   10872 ** callback". If it is not NULL, then for each table affected by at least one
   10873 ** change in the changeset, the filter callback is invoked with
   10874 ** the table name as the second argument, and a copy of the context pointer
   10875 ** passed as the sixth argument to this function as the first. If the "filter
   10876 ** callback" returns zero, then no attempt is made to apply any changes to
   10877 ** the table. Otherwise, if the return value is non-zero or the xFilter
   10878 ** argument to this function is NULL, all changes related to the table are
   10879 ** attempted.
   10880 **
   10881 ** For each table that is not excluded by the filter callback, this function
   10882 ** tests that the target database contains a compatible table. A table is
   10883 ** considered compatible if all of the following are true:
   10884 **
   10885 ** <ul>
   10886 **   <li> The table has the same name as the name recorded in the
   10887 **        changeset, and
   10888 **   <li> The table has at least as many columns as recorded in the
   10889 **        changeset, and
   10890 **   <li> The table has primary key columns in the same position as
   10891 **        recorded in the changeset.
   10892 ** </ul>
   10893 **
   10894 ** If there is no compatible table, it is not an error, but none of the
   10895 ** changes associated with the table are applied. A warning message is issued
   10896 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
   10897 ** one such warning is issued for each table in the changeset.
   10898 **
   10899 ** For each change for which there is a compatible table, an attempt is made
   10900 ** to modify the table contents according to the UPDATE, INSERT or DELETE
   10901 ** change. If a change cannot be applied cleanly, the conflict handler
   10902 ** function passed as the fifth argument to sqlite3changeset_apply() may be
   10903 ** invoked. A description of exactly when the conflict handler is invoked for
   10904 ** each type of change is below.
   10905 **
   10906 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
   10907 ** of passing anything other than a valid function pointer as the xConflict
   10908 ** argument are undefined.
   10909 **
   10910 ** Each time the conflict handler function is invoked, it must return one
   10911 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
   10912 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
   10913 ** if the second argument passed to the conflict handler is either
   10914 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
   10915 ** returns an illegal value, any changes already made are rolled back and
   10916 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
   10917 ** actions are taken by sqlite3changeset_apply() depending on the value
   10918 ** returned by each invocation of the conflict-handler function. Refer to
   10919 ** the documentation for the three
   10920 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
   10921 **
   10922 ** <dl>
   10923 ** <dt>DELETE Changes<dd>
   10924 **   For each DELETE change, this function checks if the target database
   10925 **   contains a row with the same primary key value (or values) as the
   10926 **   original row values stored in the changeset. If it does, and the values
   10927 **   stored in all non-primary key columns also match the values stored in
   10928 **   the changeset the row is deleted from the target database.
   10929 **
   10930 **   If a row with matching primary key values is found, but one or more of
   10931 **   the non-primary key fields contains a value different from the original
   10932 **   row value stored in the changeset, the conflict-handler function is
   10933 **   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
   10934 **   database table has more columns than are recorded in the changeset,
   10935 **   only the values of those non-primary key fields are compared against
   10936 **   the current database contents - any trailing database table columns
   10937 **   are ignored.
   10938 **
   10939 **   If no row with matching primary key values is found in the database,
   10940 **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
   10941 **   passed as the second argument.
   10942 **
   10943 **   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
   10944 **   (which can only happen if a foreign key constraint is violated), the
   10945 **   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
   10946 **   passed as the second argument. This includes the case where the DELETE
   10947 **   operation is attempted because an earlier call to the conflict handler
   10948 **   function returned [SQLITE_CHANGESET_REPLACE].
   10949 **
   10950 ** <dt>INSERT Changes<dd>
   10951 **   For each INSERT change, an attempt is made to insert the new row into
   10952 **   the database. If the changeset row contains fewer fields than the
   10953 **   database table, the trailing fields are populated with their default
   10954 **   values.
   10955 **
   10956 **   If the attempt to insert the row fails because the database already
   10957 **   contains a row with the same primary key values, the conflict handler
   10958 **   function is invoked with the second argument set to
   10959 **   [SQLITE_CHANGESET_CONFLICT].
   10960 **
   10961 **   If the attempt to insert the row fails because of some other constraint
   10962 **   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
   10963 **   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
   10964 **   This includes the case where the INSERT operation is re-attempted because
   10965 **   an earlier call to the conflict handler function returned
   10966 **   [SQLITE_CHANGESET_REPLACE].
   10967 **
   10968 ** <dt>UPDATE Changes<dd>
   10969 **   For each UPDATE change, this function checks if the target database
   10970 **   contains a row with the same primary key value (or values) as the
   10971 **   original row values stored in the changeset. If it does, and the values
   10972 **   stored in all modified non-primary key columns also match the values
   10973 **   stored in the changeset the row is updated within the target database.
   10974 **
   10975 **   If a row with matching primary key values is found, but one or more of
   10976 **   the modified non-primary key fields contains a value different from an
   10977 **   original row value stored in the changeset, the conflict-handler function
   10978 **   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
   10979 **   UPDATE changes only contain values for non-primary key fields that are
   10980 **   to be modified, only those fields need to match the original values to
   10981 **   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
   10982 **
   10983 **   If no row with matching primary key values is found in the database,
   10984 **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
   10985 **   passed as the second argument.
   10986 **
   10987 **   If the UPDATE operation is attempted, but SQLite returns
   10988 **   SQLITE_CONSTRAINT, the conflict-handler function is invoked with
   10989 **   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
   10990 **   This includes the case where the UPDATE operation is attempted after
   10991 **   an earlier call to the conflict handler function returned
   10992 **   [SQLITE_CHANGESET_REPLACE].
   10993 ** </dl>
   10994 **
   10995 ** It is safe to execute SQL statements, including those that write to the
   10996 ** table that the callback related to, from within the xConflict callback.
   10997 ** This can be used to further customize the applications conflict
   10998 ** resolution strategy.
   10999 **
   11000 ** All changes made by this function are enclosed in a savepoint transaction.
   11001 ** If any other error (aside from a constraint failure when attempting to
   11002 ** write to the target database) occurs, then the savepoint transaction is
   11003 ** rolled back, restoring the target database to its original state, and an
   11004 ** SQLite error code returned.
   11005 */
   11006 SQLITE_API int sqlite3changeset_apply(
   11007   sqlite3 *db,                    /* Apply change to "main" db of this handle */
   11008   int nChangeset,                 /* Size of changeset in bytes */
   11009   void *pChangeset,               /* Changeset blob */
   11010   int(*xFilter)(
   11011     void *pCtx,                   /* Copy of sixth arg to _apply() */
   11012     const char *zTab              /* Table name */
   11013   ),
   11014   int(*xConflict)(
   11015     void *pCtx,                   /* Copy of sixth arg to _apply() */
   11016     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
   11017     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
   11018   ),
   11019   void *pCtx                      /* First argument passed to xConflict */
   11020 );
   11021 
   11022 /*
   11023 ** CAPI3REF: Constants Passed To The Conflict Handler
   11024 **
   11025 ** Values that may be passed as the second argument to a conflict-handler.
   11026 **
   11027 ** <dl>
   11028 ** <dt>SQLITE_CHANGESET_DATA<dd>
   11029 **   The conflict handler is invoked with CHANGESET_DATA as the second argument
   11030 **   when processing a DELETE or UPDATE change if a row with the required
   11031 **   PRIMARY KEY fields is present in the database, but one or more other
   11032 **   (non primary-key) fields modified by the update do not contain the
   11033 **   expected "before" values.
   11034 **
   11035 **   The conflicting row, in this case, is the database row with the matching
   11036 **   primary key.
   11037 **
   11038 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
   11039 **   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
   11040 **   argument when processing a DELETE or UPDATE change if a row with the
   11041 **   required PRIMARY KEY fields is not present in the database.
   11042 **
   11043 **   There is no conflicting row in this case. The results of invoking the
   11044 **   sqlite3changeset_conflict() API are undefined.
   11045 **
   11046 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
   11047 **   CHANGESET_CONFLICT is passed as the second argument to the conflict
   11048 **   handler while processing an INSERT change if the operation would result
   11049 **   in duplicate primary key values.
   11050 **
   11051 **   The conflicting row in this case is the database row with the matching
   11052 **   primary key.
   11053 **
   11054 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
   11055 **   If foreign key handling is enabled, and applying a changeset leaves the
   11056 **   database in a state containing foreign key violations, the conflict
   11057 **   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
   11058 **   exactly once before the changeset is committed. If the conflict handler
   11059 **   returns CHANGESET_OMIT, the changes, including those that caused the
   11060 **   foreign key constraint violation, are committed. Or, if it returns
   11061 **   CHANGESET_ABORT, the changeset is rolled back.
   11062 **
   11063 **   No current or conflicting row information is provided. The only function
   11064 **   it is possible to call on the supplied sqlite3_changeset_iter handle
   11065 **   is sqlite3changeset_fk_conflicts().
   11066 **
   11067 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
   11068 **   If any other constraint violation occurs while applying a change (i.e.
   11069 **   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
   11070 **   invoked with CHANGESET_CONSTRAINT as the second argument.
   11071 **
   11072 **   There is no conflicting row in this case. The results of invoking the
   11073 **   sqlite3changeset_conflict() API are undefined.
   11074 **
   11075 ** </dl>
   11076 */
   11077 #define SQLITE_CHANGESET_DATA        1
   11078 #define SQLITE_CHANGESET_NOTFOUND    2
   11079 #define SQLITE_CHANGESET_CONFLICT    3
   11080 #define SQLITE_CHANGESET_CONSTRAINT  4
   11081 #define SQLITE_CHANGESET_FOREIGN_KEY 5
   11082 
   11083 /*
   11084 ** CAPI3REF: Constants Returned By The Conflict Handler
   11085 **
   11086 ** A conflict handler callback must return one of the following three values.
   11087 **
   11088 ** <dl>
   11089 ** <dt>SQLITE_CHANGESET_OMIT<dd>
   11090 **   If a conflict handler returns this value no special action is taken. The
   11091 **   change that caused the conflict is not applied. The session module
   11092 **   continues to the next change in the changeset.
   11093 **
   11094 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
   11095 **   This value may only be returned if the second argument to the conflict
   11096 **   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
   11097 **   is not the case, any changes applied so far are rolled back and the
   11098 **   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
   11099 **
   11100 **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
   11101 **   handler, then the conflicting row is either updated or deleted, depending
   11102 **   on the type of change.
   11103 **
   11104 **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
   11105 **   handler, then the conflicting row is removed from the database and a
   11106 **   second attempt to apply the change is made. If this second attempt fails,
   11107 **   the original row is restored to the database before continuing.
   11108 **
   11109 ** <dt>SQLITE_CHANGESET_ABORT<dd>
   11110 **   If this value is returned, any changes applied so far are rolled back
   11111 **   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
   11112 ** </dl>
   11113 */
   11114 #define SQLITE_CHANGESET_OMIT       0
   11115 #define SQLITE_CHANGESET_REPLACE    1
   11116 #define SQLITE_CHANGESET_ABORT      2
   11117 
   11118 /*
   11119 ** CAPI3REF: Streaming Versions of API functions.
   11120 **
   11121 ** The six streaming API xxx_strm() functions serve similar purposes to the
   11122 ** corresponding non-streaming API functions:
   11123 **
   11124 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
   11125 **   <tr><th>Streaming function<th>Non-streaming equivalent</th>
   11126 **   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
   11127 **   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
   11128 **   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
   11129 **   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
   11130 **   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
   11131 **   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
   11132 ** </table>
   11133 **
   11134 ** Non-streaming functions that accept changesets (or patchsets) as input
   11135 ** require that the entire changeset be stored in a single buffer in memory.
   11136 ** Similarly, those that return a changeset or patchset do so by returning
   11137 ** a pointer to a single large buffer allocated using sqlite3_malloc().
   11138 ** Normally this is convenient. However, if an application running in a
   11139 ** low-memory environment is required to handle very large changesets, the
   11140 ** large contiguous memory allocations required can become onerous.
   11141 **
   11142 ** In order to avoid this problem, instead of a single large buffer, input
   11143 ** is passed to a streaming API functions by way of a callback function that
   11144 ** the sessions module invokes to incrementally request input data as it is
   11145 ** required. In all cases, a pair of API function parameters such as
   11146 **
   11147 **  <pre>
   11148 **  &nbsp;     int nChangeset,
   11149 **  &nbsp;     void *pChangeset,
   11150 **  </pre>
   11151 **
   11152 ** Is replaced by:
   11153 **
   11154 **  <pre>
   11155 **  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
   11156 **  &nbsp;     void *pIn,
   11157 **  </pre>
   11158 **
   11159 ** Each time the xInput callback is invoked by the sessions module, the first
   11160 ** argument passed is a copy of the supplied pIn context pointer. The second
   11161 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
   11162 ** error occurs the xInput method should copy up to (*pnData) bytes of data
   11163 ** into the buffer and set (*pnData) to the actual number of bytes copied
   11164 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
   11165 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
   11166 ** error code should be returned. In all cases, if an xInput callback returns
   11167 ** an error, all processing is abandoned and the streaming API function
   11168 ** returns a copy of the error code to the caller.
   11169 **
   11170 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
   11171 ** invoked by the sessions module at any point during the lifetime of the
   11172 ** iterator. If such an xInput callback returns an error, the iterator enters
   11173 ** an error state, whereby all subsequent calls to iterator functions
   11174 ** immediately fail with the same error code as returned by xInput.
   11175 **
   11176 ** Similarly, streaming API functions that return changesets (or patchsets)
   11177 ** return them in chunks by way of a callback function instead of via a
   11178 ** pointer to a single large buffer. In this case, a pair of parameters such
   11179 ** as:
   11180 **
   11181 **  <pre>
   11182 **  &nbsp;     int *pnChangeset,
   11183 **  &nbsp;     void **ppChangeset,
   11184 **  </pre>
   11185 **
   11186 ** Is replaced by:
   11187 **
   11188 **  <pre>
   11189 **  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
   11190 **  &nbsp;     void *pOut
   11191 **  </pre>
   11192 **
   11193 ** The xOutput callback is invoked zero or more times to return data to
   11194 ** the application. The first parameter passed to each call is a copy of the
   11195 ** pOut pointer supplied by the application. The second parameter, pData,
   11196 ** points to a buffer nData bytes in size containing the chunk of output
   11197 ** data being returned. If the xOutput callback successfully processes the
   11198 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
   11199 ** it should return some other SQLite error code. In this case processing
   11200 ** is immediately abandoned and the streaming API function returns a copy
   11201 ** of the xOutput error code to the application.
   11202 **
   11203 ** The sessions module never invokes an xOutput callback with the third
   11204 ** parameter set to a value less than or equal to zero. Other than this,
   11205 ** no guarantees are made as to the size of the chunks of data returned.
   11206 */
   11207 SQLITE_API int sqlite3changeset_apply_strm(
   11208   sqlite3 *db,                    /* Apply change to "main" db of this handle */
   11209   int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
   11210   void *pIn,                                          /* First arg for xInput */
   11211   int(*xFilter)(
   11212     void *pCtx,                   /* Copy of sixth arg to _apply() */
   11213     const char *zTab              /* Table name */
   11214   ),
   11215   int(*xConflict)(
   11216     void *pCtx,                   /* Copy of sixth arg to _apply() */
   11217     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
   11218     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
   11219   ),
   11220   void *pCtx                      /* First argument passed to xConflict */
   11221 );
   11222 SQLITE_API int sqlite3changeset_concat_strm(
   11223   int (*xInputA)(void *pIn, void *pData, int *pnData),
   11224   void *pInA,
   11225   int (*xInputB)(void *pIn, void *pData, int *pnData),
   11226   void *pInB,
   11227   int (*xOutput)(void *pOut, const void *pData, int nData),
   11228   void *pOut
   11229 );
   11230 SQLITE_API int sqlite3changeset_invert_strm(
   11231   int (*xInput)(void *pIn, void *pData, int *pnData),
   11232   void *pIn,
   11233   int (*xOutput)(void *pOut, const void *pData, int nData),
   11234   void *pOut
   11235 );
   11236 SQLITE_API int sqlite3changeset_start_strm(
   11237   sqlite3_changeset_iter **pp,
   11238   int (*xInput)(void *pIn, void *pData, int *pnData),
   11239   void *pIn
   11240 );
   11241 SQLITE_API int sqlite3session_changeset_strm(
   11242   sqlite3_session *pSession,
   11243   int (*xOutput)(void *pOut, const void *pData, int nData),
   11244   void *pOut
   11245 );
   11246 SQLITE_API int sqlite3session_patchset_strm(
   11247   sqlite3_session *pSession,
   11248   int (*xOutput)(void *pOut, const void *pData, int nData),
   11249   void *pOut
   11250 );
   11251 SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
   11252     int (*xInput)(void *pIn, void *pData, int *pnData),
   11253     void *pIn
   11254 );
   11255 SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
   11256     int (*xOutput)(void *pOut, const void *pData, int nData),
   11257     void *pOut
   11258 );
   11259 
   11260 
   11261 /*
   11262 ** Make sure we can call this stuff from C++.
   11263 */
   11264 #if 0
   11265 }
   11266 #endif
   11267 
   11268 #endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
   11269 
   11270 /******** End of sqlite3session.h *********/
   11271 /******** Begin file fts5.h *********/
   11272 /*
   11273 ** 2014 May 31
   11274 **
   11275 ** The author disclaims copyright to this source code.  In place of
   11276 ** a legal notice, here is a blessing:
   11277 **
   11278 **    May you do good and not evil.
   11279 **    May you find forgiveness for yourself and forgive others.
   11280 **    May you share freely, never taking more than you give.
   11281 **
   11282 ******************************************************************************
   11283 **
   11284 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
   11285 ** FTS5 may be extended with:
   11286 **
   11287 **     * custom tokenizers, and
   11288 **     * custom auxiliary functions.
   11289 */
   11290 
   11291 
   11292 #ifndef _FTS5_H
   11293 #define _FTS5_H
   11294 
   11295 
   11296 #if 0
   11297 extern "C" {
   11298 #endif
   11299 
   11300 /*************************************************************************
   11301 ** CUSTOM AUXILIARY FUNCTIONS
   11302 **
   11303 ** Virtual table implementations may overload SQL functions by implementing
   11304 ** the sqlite3_module.xFindFunction() method.
   11305 */
   11306 
   11307 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
   11308 typedef struct Fts5Context Fts5Context;
   11309 typedef struct Fts5PhraseIter Fts5PhraseIter;
   11310 
   11311 typedef void (*fts5_extension_function)(
   11312   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
   11313   Fts5Context *pFts,              /* First arg to pass to pApi functions */
   11314   sqlite3_context *pCtx,          /* Context for returning result/error */
   11315   int nVal,                       /* Number of values in apVal[] array */
   11316   sqlite3_value **apVal           /* Array of trailing arguments */
   11317 );
   11318 
   11319 struct Fts5PhraseIter {
   11320   const unsigned char *a;
   11321   const unsigned char *b;
   11322 };
   11323 
   11324 /*
   11325 ** EXTENSION API FUNCTIONS
   11326 **
   11327 ** xUserData(pFts):
   11328 **   Return a copy of the context pointer the extension function was
   11329 **   registered with.
   11330 **
   11331 ** xColumnTotalSize(pFts, iCol, pnToken):
   11332 **   If parameter iCol is less than zero, set output variable *pnToken
   11333 **   to the total number of tokens in the FTS5 table. Or, if iCol is
   11334 **   non-negative but less than the number of columns in the table, return
   11335 **   the total number of tokens in column iCol, considering all rows in
   11336 **   the FTS5 table.
   11337 **
   11338 **   If parameter iCol is greater than or equal to the number of columns
   11339 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
   11340 **   an OOM condition or IO error), an appropriate SQLite error code is
   11341 **   returned.
   11342 **
   11343 ** xColumnCount(pFts):
   11344 **   Return the number of columns in the table.
   11345 **
   11346 ** xColumnSize(pFts, iCol, pnToken):
   11347 **   If parameter iCol is less than zero, set output variable *pnToken
   11348 **   to the total number of tokens in the current row. Or, if iCol is
   11349 **   non-negative but less than the number of columns in the table, set
   11350 **   *pnToken to the number of tokens in column iCol of the current row.
   11351 **
   11352 **   If parameter iCol is greater than or equal to the number of columns
   11353 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
   11354 **   an OOM condition or IO error), an appropriate SQLite error code is
   11355 **   returned.
   11356 **
   11357 **   This function may be quite inefficient if used with an FTS5 table
   11358 **   created with the "columnsize=0" option.
   11359 **
   11360 ** xColumnText:
   11361 **   This function attempts to retrieve the text of column iCol of the
   11362 **   current document. If successful, (*pz) is set to point to a buffer
   11363 **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
   11364 **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
   11365 **   if an error occurs, an SQLite error code is returned and the final values
   11366 **   of (*pz) and (*pn) are undefined.
   11367 **
   11368 ** xPhraseCount:
   11369 **   Returns the number of phrases in the current query expression.
   11370 **
   11371 ** xPhraseSize:
   11372 **   Returns the number of tokens in phrase iPhrase of the query. Phrases
   11373 **   are numbered starting from zero.
   11374 **
   11375 ** xInstCount:
   11376 **   Set *pnInst to the total number of occurrences of all phrases within
   11377 **   the query within the current row. Return SQLITE_OK if successful, or
   11378 **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
   11379 **
   11380 **   This API can be quite slow if used with an FTS5 table created with the
   11381 **   "detail=none" or "detail=column" option. If the FTS5 table is created
   11382 **   with either "detail=none" or "detail=column" and "content=" option
   11383 **   (i.e. if it is a contentless table), then this API always returns 0.
   11384 **
   11385 ** xInst:
   11386 **   Query for the details of phrase match iIdx within the current row.
   11387 **   Phrase matches are numbered starting from zero, so the iIdx argument
   11388 **   should be greater than or equal to zero and smaller than the value
   11389 **   output by xInstCount().
   11390 **
   11391 **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
   11392 **   to the column in which it occurs and *piOff the token offset of the
   11393 **   first token of the phrase. The exception is if the table was created
   11394 **   with the offsets=0 option specified. In this case *piOff is always
   11395 **   set to -1.
   11396 **
   11397 **   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
   11398 **   if an error occurs.
   11399 **
   11400 **   This API can be quite slow if used with an FTS5 table created with the
   11401 **   "detail=none" or "detail=column" option.
   11402 **
   11403 ** xRowid:
   11404 **   Returns the rowid of the current row.
   11405 **
   11406 ** xTokenize:
   11407 **   Tokenize text using the tokenizer belonging to the FTS5 table.
   11408 **
   11409 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
   11410 **   This API function is used to query the FTS table for phrase iPhrase
   11411 **   of the current query. Specifically, a query equivalent to:
   11412 **
   11413 **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
   11414 **
   11415 **   with $p set to a phrase equivalent to the phrase iPhrase of the
   11416 **   current query is executed. Any column filter that applies to
   11417 **   phrase iPhrase of the current query is included in $p. For each
   11418 **   row visited, the callback function passed as the fourth argument
   11419 **   is invoked. The context and API objects passed to the callback
   11420 **   function may be used to access the properties of each matched row.
   11421 **   Invoking Api.xUserData() returns a copy of the pointer passed as
   11422 **   the third argument to pUserData.
   11423 **
   11424 **   If the callback function returns any value other than SQLITE_OK, the
   11425 **   query is abandoned and the xQueryPhrase function returns immediately.
   11426 **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
   11427 **   Otherwise, the error code is propagated upwards.
   11428 **
   11429 **   If the query runs to completion without incident, SQLITE_OK is returned.
   11430 **   Or, if some error occurs before the query completes or is aborted by
   11431 **   the callback, an SQLite error code is returned.
   11432 **
   11433 **
   11434 ** xSetAuxdata(pFts5, pAux, xDelete)
   11435 **
   11436 **   Save the pointer passed as the second argument as the extension functions
   11437 **   "auxiliary data". The pointer may then be retrieved by the current or any
   11438 **   future invocation of the same fts5 extension function made as part of
   11439 **   of the same MATCH query using the xGetAuxdata() API.
   11440 **
   11441 **   Each extension function is allocated a single auxiliary data slot for
   11442 **   each FTS query (MATCH expression). If the extension function is invoked
   11443 **   more than once for a single FTS query, then all invocations share a
   11444 **   single auxiliary data context.
   11445 **
   11446 **   If there is already an auxiliary data pointer when this function is
   11447 **   invoked, then it is replaced by the new pointer. If an xDelete callback
   11448 **   was specified along with the original pointer, it is invoked at this
   11449 **   point.
   11450 **
   11451 **   The xDelete callback, if one is specified, is also invoked on the
   11452 **   auxiliary data pointer after the FTS5 query has finished.
   11453 **
   11454 **   If an error (e.g. an OOM condition) occurs within this function, an
   11455 **   the auxiliary data is set to NULL and an error code returned. If the
   11456 **   xDelete parameter was not NULL, it is invoked on the auxiliary data
   11457 **   pointer before returning.
   11458 **
   11459 **
   11460 ** xGetAuxdata(pFts5, bClear)
   11461 **
   11462 **   Returns the current auxiliary data pointer for the fts5 extension
   11463 **   function. See the xSetAuxdata() method for details.
   11464 **
   11465 **   If the bClear argument is non-zero, then the auxiliary data is cleared
   11466 **   (set to NULL) before this function returns. In this case the xDelete,
   11467 **   if any, is not invoked.
   11468 **
   11469 **
   11470 ** xRowCount(pFts5, pnRow)
   11471 **
   11472 **   This function is used to retrieve the total number of rows in the table.
   11473 **   In other words, the same value that would be returned by:
   11474 **
   11475 **        SELECT count(*) FROM ftstable;
   11476 **
   11477 ** xPhraseFirst()
   11478 **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
   11479 **   method, to iterate through all instances of a single query phrase within
   11480 **   the current row. This is the same information as is accessible via the
   11481 **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
   11482 **   to use, this API may be faster under some circumstances. To iterate
   11483 **   through instances of phrase iPhrase, use the following code:
   11484 **
   11485 **       Fts5PhraseIter iter;
   11486 **       int iCol, iOff;
   11487 **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
   11488 **           iCol>=0;
   11489 **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
   11490 **       ){
   11491 **         // An instance of phrase iPhrase at offset iOff of column iCol
   11492 **       }
   11493 **
   11494 **   The Fts5PhraseIter structure is defined above. Applications should not
   11495 **   modify this structure directly - it should only be used as shown above
   11496 **   with the xPhraseFirst() and xPhraseNext() API methods (and by
   11497 **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
   11498 **
   11499 **   This API can be quite slow if used with an FTS5 table created with the
   11500 **   "detail=none" or "detail=column" option. If the FTS5 table is created
   11501 **   with either "detail=none" or "detail=column" and "content=" option
   11502 **   (i.e. if it is a contentless table), then this API always iterates
   11503 **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
   11504 **
   11505 ** xPhraseNext()
   11506 **   See xPhraseFirst above.
   11507 **
   11508 ** xPhraseFirstColumn()
   11509 **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
   11510 **   and xPhraseNext() APIs described above. The difference is that instead
   11511 **   of iterating through all instances of a phrase in the current row, these
   11512 **   APIs are used to iterate through the set of columns in the current row
   11513 **   that contain one or more instances of a specified phrase. For example:
   11514 **
   11515 **       Fts5PhraseIter iter;
   11516 **       int iCol;
   11517 **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
   11518 **           iCol>=0;
   11519 **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
   11520 **       ){
   11521 **         // Column iCol contains at least one instance of phrase iPhrase
   11522 **       }
   11523 **
   11524 **   This API can be quite slow if used with an FTS5 table created with the
   11525 **   "detail=none" option. If the FTS5 table is created with either
   11526 **   "detail=none" "content=" option (i.e. if it is a contentless table),
   11527 **   then this API always iterates through an empty set (all calls to
   11528 **   xPhraseFirstColumn() set iCol to -1).
   11529 **
   11530 **   The information accessed using this API and its companion
   11531 **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
   11532 **   (or xInst/xInstCount). The chief advantage of this API is that it is
   11533 **   significantly more efficient than those alternatives when used with
   11534 **   "detail=column" tables.
   11535 **
   11536 ** xPhraseNextColumn()
   11537 **   See xPhraseFirstColumn above.
   11538 */
   11539 struct Fts5ExtensionApi {
   11540   int iVersion;                   /* Currently always set to 3 */
   11541 
   11542   void *(*xUserData)(Fts5Context*);
   11543 
   11544   int (*xColumnCount)(Fts5Context*);
   11545   int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
   11546   int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
   11547 
   11548   int (*xTokenize)(Fts5Context*,
   11549     const char *pText, int nText, /* Text to tokenize */
   11550     void *pCtx,                   /* Context passed to xToken() */
   11551     int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
   11552   );
   11553 
   11554   int (*xPhraseCount)(Fts5Context*);
   11555   int (*xPhraseSize)(Fts5Context*, int iPhrase);
   11556 
   11557   int (*xInstCount)(Fts5Context*, int *pnInst);
   11558   int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
   11559 
   11560   sqlite3_int64 (*xRowid)(Fts5Context*);
   11561   int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
   11562   int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
   11563 
   11564   int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
   11565     int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
   11566   );
   11567   int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
   11568   void *(*xGetAuxdata)(Fts5Context*, int bClear);
   11569 
   11570   int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
   11571   void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
   11572 
   11573   int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
   11574   void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
   11575 };
   11576 
   11577 /*
   11578 ** CUSTOM AUXILIARY FUNCTIONS
   11579 *************************************************************************/
   11580 
   11581 /*************************************************************************
   11582 ** CUSTOM TOKENIZERS
   11583 **
   11584 ** Applications may also register custom tokenizer types. A tokenizer
   11585 ** is registered by providing fts5 with a populated instance of the
   11586 ** following structure. All structure methods must be defined, setting
   11587 ** any member of the fts5_tokenizer struct to NULL leads to undefined
   11588 ** behaviour. The structure methods are expected to function as follows:
   11589 **
   11590 ** xCreate:
   11591 **   This function is used to allocate and initialize a tokenizer instance.
   11592 **   A tokenizer instance is required to actually tokenize text.
   11593 **
   11594 **   The first argument passed to this function is a copy of the (void*)
   11595 **   pointer provided by the application when the fts5_tokenizer object
   11596 **   was registered with FTS5 (the third argument to xCreateTokenizer()).
   11597 **   The second and third arguments are an array of nul-terminated strings
   11598 **   containing the tokenizer arguments, if any, specified following the
   11599 **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
   11600 **   to create the FTS5 table.
   11601 **
   11602 **   The final argument is an output variable. If successful, (*ppOut)
   11603 **   should be set to point to the new tokenizer handle and SQLITE_OK
   11604 **   returned. If an error occurs, some value other than SQLITE_OK should
   11605 **   be returned. In this case, fts5 assumes that the final value of *ppOut
   11606 **   is undefined.
   11607 **
   11608 ** xDelete:
   11609 **   This function is invoked to delete a tokenizer handle previously
   11610 **   allocated using xCreate(). Fts5 guarantees that this function will
   11611 **   be invoked exactly once for each successful call to xCreate().
   11612 **
   11613 ** xTokenize:
   11614 **   This function is expected to tokenize the nText byte string indicated
   11615 **   by argument pText. pText may or may not be nul-terminated. The first
   11616 **   argument passed to this function is a pointer to an Fts5Tokenizer object
   11617 **   returned by an earlier call to xCreate().
   11618 **
   11619 **   The second argument indicates the reason that FTS5 is requesting
   11620 **   tokenization of the supplied text. This is always one of the following
   11621 **   four values:
   11622 **
   11623 **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
   11624 **            or removed from the FTS table. The tokenizer is being invoked to
   11625 **            determine the set of tokens to add to (or delete from) the
   11626 **            FTS index.
   11627 **
   11628 **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
   11629 **            against the FTS index. The tokenizer is being called to tokenize
   11630 **            a bareword or quoted string specified as part of the query.
   11631 **
   11632 **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
   11633 **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
   11634 **            followed by a "*" character, indicating that the last token
   11635 **            returned by the tokenizer will be treated as a token prefix.
   11636 **
   11637 **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
   11638 **            satisfy an fts5_api.xTokenize() request made by an auxiliary
   11639 **            function. Or an fts5_api.xColumnSize() request made by the same
   11640 **            on a columnsize=0 database.
   11641 **   </ul>
   11642 **
   11643 **   For each token in the input string, the supplied callback xToken() must
   11644 **   be invoked. The first argument to it should be a copy of the pointer
   11645 **   passed as the second argument to xTokenize(). The third and fourth
   11646 **   arguments are a pointer to a buffer containing the token text, and the
   11647 **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
   11648 **   of the first byte of and first byte immediately following the text from
   11649 **   which the token is derived within the input.
   11650 **
   11651 **   The second argument passed to the xToken() callback ("tflags") should
   11652 **   normally be set to 0. The exception is if the tokenizer supports
   11653 **   synonyms. In this case see the discussion below for details.
   11654 **
   11655 **   FTS5 assumes the xToken() callback is invoked for each token in the
   11656 **   order that they occur within the input text.
   11657 **
   11658 **   If an xToken() callback returns any value other than SQLITE_OK, then
   11659 **   the tokenization should be abandoned and the xTokenize() method should
   11660 **   immediately return a copy of the xToken() return value. Or, if the
   11661 **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
   11662 **   if an error occurs with the xTokenize() implementation itself, it
   11663 **   may abandon the tokenization and return any error code other than
   11664 **   SQLITE_OK or SQLITE_DONE.
   11665 **
   11666 ** SYNONYM SUPPORT
   11667 **
   11668 **   Custom tokenizers may also support synonyms. Consider a case in which a
   11669 **   user wishes to query for a phrase such as "first place". Using the
   11670 **   built-in tokenizers, the FTS5 query 'first + place' will match instances
   11671 **   of "first place" within the document set, but not alternative forms
   11672 **   such as "1st place". In some applications, it would be better to match
   11673 **   all instances of "first place" or "1st place" regardless of which form
   11674 **   the user specified in the MATCH query text.
   11675 **
   11676 **   There are several ways to approach this in FTS5:
   11677 **
   11678 **   <ol><li> By mapping all synonyms to a single token. In this case, the
   11679 **            In the above example, this means that the tokenizer returns the
   11680 **            same token for inputs "first" and "1st". Say that token is in
   11681 **            fact "first", so that when the user inserts the document "I won
   11682 **            1st place" entries are added to the index for tokens "i", "won",
   11683 **            "first" and "place". If the user then queries for '1st + place',
   11684 **            the tokenizer substitutes "first" for "1st" and the query works
   11685 **            as expected.
   11686 **
   11687 **       <li> By adding multiple synonyms for a single term to the FTS index.
   11688 **            In this case, when tokenizing query text, the tokenizer may
   11689 **            provide multiple synonyms for a single term within the document.
   11690 **            FTS5 then queries the index for each synonym individually. For
   11691 **            example, faced with the query:
   11692 **
   11693 **   <codeblock>
   11694 **     ... MATCH 'first place'</codeblock>
   11695 **
   11696 **            the tokenizer offers both "1st" and "first" as synonyms for the
   11697 **            first token in the MATCH query and FTS5 effectively runs a query
   11698 **            similar to:
   11699 **
   11700 **   <codeblock>
   11701 **     ... MATCH '(first OR 1st) place'</codeblock>
   11702 **
   11703 **            except that, for the purposes of auxiliary functions, the query
   11704 **            still appears to contain just two phrases - "(first OR 1st)"
   11705 **            being treated as a single phrase.
   11706 **
   11707 **       <li> By adding multiple synonyms for a single term to the FTS index.
   11708 **            Using this method, when tokenizing document text, the tokenizer
   11709 **            provides multiple synonyms for each token. So that when a
   11710 **            document such as "I won first place" is tokenized, entries are
   11711 **            added to the FTS index for "i", "won", "first", "1st" and
   11712 **            "place".
   11713 **
   11714 **            This way, even if the tokenizer does not provide synonyms
   11715 **            when tokenizing query text (it should not - to do would be
   11716 **            inefficient), it doesn't matter if the user queries for
   11717 **            'first + place' or '1st + place', as there are entires in the
   11718 **            FTS index corresponding to both forms of the first token.
   11719 **   </ol>
   11720 **
   11721 **   Whether it is parsing document or query text, any call to xToken that
   11722 **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
   11723 **   is considered to supply a synonym for the previous token. For example,
   11724 **   when parsing the document "I won first place", a tokenizer that supports
   11725 **   synonyms would call xToken() 5 times, as follows:
   11726 **
   11727 **   <codeblock>
   11728 **       xToken(pCtx, 0, "i",                      1,  0,  1);
   11729 **       xToken(pCtx, 0, "won",                    3,  2,  5);
   11730 **       xToken(pCtx, 0, "first",                  5,  6, 11);
   11731 **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
   11732 **       xToken(pCtx, 0, "place",                  5, 12, 17);
   11733 **</codeblock>
   11734 **
   11735 **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
   11736 **   xToken() is called. Multiple synonyms may be specified for a single token
   11737 **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
   11738 **   There is no limit to the number of synonyms that may be provided for a
   11739 **   single token.
   11740 **
   11741 **   In many cases, method (1) above is the best approach. It does not add
   11742 **   extra data to the FTS index or require FTS5 to query for multiple terms,
   11743 **   so it is efficient in terms of disk space and query speed. However, it
   11744 **   does not support prefix queries very well. If, as suggested above, the
   11745 **   token "first" is subsituted for "1st" by the tokenizer, then the query:
   11746 **
   11747 **   <codeblock>
   11748 **     ... MATCH '1s*'</codeblock>
   11749 **
   11750 **   will not match documents that contain the token "1st" (as the tokenizer
   11751 **   will probably not map "1s" to any prefix of "first").
   11752 **
   11753 **   For full prefix support, method (3) may be preferred. In this case,
   11754 **   because the index contains entries for both "first" and "1st", prefix
   11755 **   queries such as 'fi*' or '1s*' will match correctly. However, because
   11756 **   extra entries are added to the FTS index, this method uses more space
   11757 **   within the database.
   11758 **
   11759 **   Method (2) offers a midpoint between (1) and (3). Using this method,
   11760 **   a query such as '1s*' will match documents that contain the literal
   11761 **   token "1st", but not "first" (assuming the tokenizer is not able to
   11762 **   provide synonyms for prefixes). However, a non-prefix query like '1st'
   11763 **   will match against "1st" and "first". This method does not require
   11764 **   extra disk space, as no extra entries are added to the FTS index.
   11765 **   On the other hand, it may require more CPU cycles to run MATCH queries,
   11766 **   as separate queries of the FTS index are required for each synonym.
   11767 **
   11768 **   When using methods (2) or (3), it is important that the tokenizer only
   11769 **   provide synonyms when tokenizing document text (method (2)) or query
   11770 **   text (method (3)), not both. Doing so will not cause any errors, but is
   11771 **   inefficient.
   11772 */
   11773 typedef struct Fts5Tokenizer Fts5Tokenizer;
   11774 typedef struct fts5_tokenizer fts5_tokenizer;
   11775 struct fts5_tokenizer {
   11776   int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
   11777   void (*xDelete)(Fts5Tokenizer*);
   11778   int (*xTokenize)(Fts5Tokenizer*,
   11779       void *pCtx,
   11780       int flags,            /* Mask of FTS5_TOKENIZE_* flags */
   11781       const char *pText, int nText,
   11782       int (*xToken)(
   11783         void *pCtx,         /* Copy of 2nd argument to xTokenize() */
   11784         int tflags,         /* Mask of FTS5_TOKEN_* flags */
   11785         const char *pToken, /* Pointer to buffer containing token */
   11786         int nToken,         /* Size of token in bytes */
   11787         int iStart,         /* Byte offset of token within input text */
   11788         int iEnd            /* Byte offset of end of token within input text */
   11789       )
   11790   );
   11791 };
   11792 
   11793 /* Flags that may be passed as the third argument to xTokenize() */
   11794 #define FTS5_TOKENIZE_QUERY     0x0001
   11795 #define FTS5_TOKENIZE_PREFIX    0x0002
   11796 #define FTS5_TOKENIZE_DOCUMENT  0x0004
   11797 #define FTS5_TOKENIZE_AUX       0x0008
   11798 
   11799 /* Flags that may be passed by the tokenizer implementation back to FTS5
   11800 ** as the third argument to the supplied xToken callback. */
   11801 #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
   11802 
   11803 /*
   11804 ** END OF CUSTOM TOKENIZERS
   11805 *************************************************************************/
   11806 
   11807 /*************************************************************************
   11808 ** FTS5 EXTENSION REGISTRATION API
   11809 */
   11810 typedef struct fts5_api fts5_api;
   11811 struct fts5_api {
   11812   int iVersion;                   /* Currently always set to 2 */
   11813 
   11814   /* Create a new tokenizer */
   11815   int (*xCreateTokenizer)(
   11816     fts5_api *pApi,
   11817     const char *zName,
   11818     void *pContext,
   11819     fts5_tokenizer *pTokenizer,
   11820     void (*xDestroy)(void*)
   11821   );
   11822 
   11823   /* Find an existing tokenizer */
   11824   int (*xFindTokenizer)(
   11825     fts5_api *pApi,
   11826     const char *zName,
   11827     void **ppContext,
   11828     fts5_tokenizer *pTokenizer
   11829   );
   11830 
   11831   /* Create a new auxiliary function */
   11832   int (*xCreateFunction)(
   11833     fts5_api *pApi,
   11834     const char *zName,
   11835     void *pContext,
   11836     fts5_extension_function xFunction,
   11837     void (*xDestroy)(void*)
   11838   );
   11839 };
   11840 
   11841 /*
   11842 ** END OF REGISTRATION API
   11843 *************************************************************************/
   11844 
   11845 #if 0
   11846 }  /* end of the 'extern "C"' block */
   11847 #endif
   11848 
   11849 #endif /* _FTS5_H */
   11850 
   11851 /******** End of fts5.h *********/
   11852 
   11853 /************** End of sqlite3.h *********************************************/
   11854 /************** Continuing where we left off in sqliteInt.h ******************/
   11855 
   11856 /*
   11857 ** Include the configuration header output by 'configure' if we're using the
   11858 ** autoconf-based build
   11859 */
   11860 #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
   11861 /* #include "config.h" */
   11862 #define SQLITECONFIG_H 1
   11863 #endif
   11864 
   11865 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
   11866 /************** Begin file sqliteLimit.h *************************************/
   11867 /*
   11868 ** 2007 May 7
   11869 **
   11870 ** The author disclaims copyright to this source code.  In place of
   11871 ** a legal notice, here is a blessing:
   11872 **
   11873 **    May you do good and not evil.
   11874 **    May you find forgiveness for yourself and forgive others.
   11875 **    May you share freely, never taking more than you give.
   11876 **
   11877 *************************************************************************
   11878 **
   11879 ** This file defines various limits of what SQLite can process.
   11880 */
   11881 
   11882 /*
   11883 ** The maximum length of a TEXT or BLOB in bytes.   This also
   11884 ** limits the size of a row in a table or index.
   11885 **
   11886 ** The hard limit is the ability of a 32-bit signed integer
   11887 ** to count the size: 2^31-1 or 2147483647.
   11888 */
   11889 #ifndef SQLITE_MAX_LENGTH
   11890 # define SQLITE_MAX_LENGTH 1000000000
   11891 #endif
   11892 
   11893 /*
   11894 ** This is the maximum number of
   11895 **
   11896 **    * Columns in a table
   11897 **    * Columns in an index
   11898 **    * Columns in a view
   11899 **    * Terms in the SET clause of an UPDATE statement
   11900 **    * Terms in the result set of a SELECT statement
   11901 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
   11902 **    * Terms in the VALUES clause of an INSERT statement
   11903 **
   11904 ** The hard upper limit here is 32676.  Most database people will
   11905 ** tell you that in a well-normalized database, you usually should
   11906 ** not have more than a dozen or so columns in any table.  And if
   11907 ** that is the case, there is no point in having more than a few
   11908 ** dozen values in any of the other situations described above.
   11909 */
   11910 #ifndef SQLITE_MAX_COLUMN
   11911 # define SQLITE_MAX_COLUMN 2000
   11912 #endif
   11913 
   11914 /*
   11915 ** The maximum length of a single SQL statement in bytes.
   11916 **
   11917 ** It used to be the case that setting this value to zero would
   11918 ** turn the limit off.  That is no longer true.  It is not possible
   11919 ** to turn this limit off.
   11920 */
   11921 #ifndef SQLITE_MAX_SQL_LENGTH
   11922 # define SQLITE_MAX_SQL_LENGTH 1000000000
   11923 #endif
   11924 
   11925 /*
   11926 ** The maximum depth of an expression tree. This is limited to
   11927 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
   11928 ** want to place more severe limits on the complexity of an
   11929 ** expression.
   11930 **
   11931 ** A value of 0 used to mean that the limit was not enforced.
   11932 ** But that is no longer true.  The limit is now strictly enforced
   11933 ** at all times.
   11934 */
   11935 #ifndef SQLITE_MAX_EXPR_DEPTH
   11936 # define SQLITE_MAX_EXPR_DEPTH 1000
   11937 #endif
   11938 
   11939 /*
   11940 ** The maximum number of terms in a compound SELECT statement.
   11941 ** The code generator for compound SELECT statements does one
   11942 ** level of recursion for each term.  A stack overflow can result
   11943 ** if the number of terms is too large.  In practice, most SQL
   11944 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
   11945 ** any limit on the number of terms in a compount SELECT.
   11946 */
   11947 #ifndef SQLITE_MAX_COMPOUND_SELECT
   11948 # define SQLITE_MAX_COMPOUND_SELECT 500
   11949 #endif
   11950 
   11951 /*
   11952 ** The maximum number of opcodes in a VDBE program.
   11953 ** Not currently enforced.
   11954 */
   11955 #ifndef SQLITE_MAX_VDBE_OP
   11956 # define SQLITE_MAX_VDBE_OP 250000000
   11957 #endif
   11958 
   11959 /*
   11960 ** The maximum number of arguments to an SQL function.
   11961 */
   11962 #ifndef SQLITE_MAX_FUNCTION_ARG
   11963 # define SQLITE_MAX_FUNCTION_ARG 127
   11964 #endif
   11965 
   11966 /*
   11967 ** The suggested maximum number of in-memory pages to use for
   11968 ** the main database table and for temporary tables.
   11969 **
   11970 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
   11971 ** which means the cache size is limited to 2048000 bytes of memory.
   11972 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
   11973 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
   11974 */
   11975 #ifndef SQLITE_DEFAULT_CACHE_SIZE
   11976 # define SQLITE_DEFAULT_CACHE_SIZE  -2000
   11977 #endif
   11978 
   11979 /*
   11980 ** The default number of frames to accumulate in the log file before
   11981 ** checkpointing the database in WAL mode.
   11982 */
   11983 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
   11984 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
   11985 #endif
   11986 
   11987 /*
   11988 ** The maximum number of attached databases.  This must be between 0
   11989 ** and 125.  The upper bound of 125 is because the attached databases are
   11990 ** counted using a signed 8-bit integer which has a maximum value of 127
   11991 ** and we have to allow 2 extra counts for the "main" and "temp" databases.
   11992 */
   11993 #ifndef SQLITE_MAX_ATTACHED
   11994 # define SQLITE_MAX_ATTACHED 10
   11995 #endif
   11996 
   11997 
   11998 /*
   11999 ** The maximum value of a ?nnn wildcard that the parser will accept.
   12000 */
   12001 #ifndef SQLITE_MAX_VARIABLE_NUMBER
   12002 # define SQLITE_MAX_VARIABLE_NUMBER 999
   12003 #endif
   12004 
   12005 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
   12006 ** imposed by the use of 16-bit offsets within each page.
   12007 **
   12008 ** Earlier versions of SQLite allowed the user to change this value at
   12009 ** compile time. This is no longer permitted, on the grounds that it creates
   12010 ** a library that is technically incompatible with an SQLite library
   12011 ** compiled with a different limit. If a process operating on a database
   12012 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
   12013 ** compiled with the default page-size limit will not be able to rollback
   12014 ** the aborted transaction. This could lead to database corruption.
   12015 */
   12016 #ifdef SQLITE_MAX_PAGE_SIZE
   12017 # undef SQLITE_MAX_PAGE_SIZE
   12018 #endif
   12019 #define SQLITE_MAX_PAGE_SIZE 65536
   12020 
   12021 
   12022 /*
   12023 ** The default size of a database page.
   12024 */
   12025 #ifndef SQLITE_DEFAULT_PAGE_SIZE
   12026 # define SQLITE_DEFAULT_PAGE_SIZE 4096
   12027 #endif
   12028 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
   12029 # undef SQLITE_DEFAULT_PAGE_SIZE
   12030 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
   12031 #endif
   12032 
   12033 /*
   12034 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
   12035 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
   12036 ** device characteristics (sector-size and atomic write() support),
   12037 ** SQLite may choose a larger value. This constant is the maximum value
   12038 ** SQLite will choose on its own.
   12039 */
   12040 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
   12041 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
   12042 #endif
   12043 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
   12044 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
   12045 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
   12046 #endif
   12047 
   12048 
   12049 /*
   12050 ** Maximum number of pages in one database file.
   12051 **
   12052 ** This is really just the default value for the max_page_count pragma.
   12053 ** This value can be lowered (or raised) at run-time using that the
   12054 ** max_page_count macro.
   12055 */
   12056 #ifndef SQLITE_MAX_PAGE_COUNT
   12057 # define SQLITE_MAX_PAGE_COUNT 1073741823
   12058 #endif
   12059 
   12060 /*
   12061 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   12062 ** operator.
   12063 */
   12064 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   12065 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   12066 #endif
   12067 
   12068 /*
   12069 ** Maximum depth of recursion for triggers.
   12070 **
   12071 ** A value of 1 means that a trigger program will not be able to itself
   12072 ** fire any triggers. A value of 0 means that no trigger programs at all
   12073 ** may be executed.
   12074 */
   12075 #ifndef SQLITE_MAX_TRIGGER_DEPTH
   12076 # define SQLITE_MAX_TRIGGER_DEPTH 1000
   12077 #endif
   12078 
   12079 /************** End of sqliteLimit.h *****************************************/
   12080 /************** Continuing where we left off in sqliteInt.h ******************/
   12081 
   12082 /* Disable nuisance warnings on Borland compilers */
   12083 #if defined(__BORLANDC__)
   12084 #pragma warn -rch /* unreachable code */
   12085 #pragma warn -ccc /* Condition is always true or false */
   12086 #pragma warn -aus /* Assigned value is never used */
   12087 #pragma warn -csu /* Comparing signed and unsigned */
   12088 #pragma warn -spa /* Suspicious pointer arithmetic */
   12089 #endif
   12090 
   12091 /*
   12092 ** Include standard header files as necessary
   12093 */
   12094 #ifdef HAVE_STDINT_H
   12095 #include <stdint.h>
   12096 #endif
   12097 #ifdef HAVE_INTTYPES_H
   12098 #include <inttypes.h>
   12099 #endif
   12100 
   12101 /*
   12102 ** The following macros are used to cast pointers to integers and
   12103 ** integers to pointers.  The way you do this varies from one compiler
   12104 ** to the next, so we have developed the following set of #if statements
   12105 ** to generate appropriate macros for a wide range of compilers.
   12106 **
   12107 ** The correct "ANSI" way to do this is to use the intptr_t type.
   12108 ** Unfortunately, that typedef is not available on all compilers, or
   12109 ** if it is available, it requires an #include of specific headers
   12110 ** that vary from one machine to the next.
   12111 **
   12112 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
   12113 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
   12114 ** So we have to define the macros in different ways depending on the
   12115 ** compiler.
   12116 */
   12117 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
   12118 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
   12119 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
   12120 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
   12121 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
   12122 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
   12123 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
   12124 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
   12125 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
   12126 #else                          /* Generates a warning - but it always works */
   12127 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
   12128 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
   12129 #endif
   12130 
   12131 /*
   12132 ** A macro to hint to the compiler that a function should not be
   12133 ** inlined.
   12134 */
   12135 #if defined(__GNUC__)
   12136 #  define SQLITE_NOINLINE  __attribute__((noinline))
   12137 #elif defined(_MSC_VER) && _MSC_VER>=1310
   12138 #  define SQLITE_NOINLINE  __declspec(noinline)
   12139 #else
   12140 #  define SQLITE_NOINLINE
   12141 #endif
   12142 
   12143 /*
   12144 ** Make sure that the compiler intrinsics we desire are enabled when
   12145 ** compiling with an appropriate version of MSVC unless prevented by
   12146 ** the SQLITE_DISABLE_INTRINSIC define.
   12147 */
   12148 #if !defined(SQLITE_DISABLE_INTRINSIC)
   12149 #  if defined(_MSC_VER) && _MSC_VER>=1400
   12150 #    if !defined(_WIN32_WCE)
   12151 #      include <intrin.h>
   12152 #      pragma intrinsic(_byteswap_ushort)
   12153 #      pragma intrinsic(_byteswap_ulong)
   12154 #      pragma intrinsic(_byteswap_uint64)
   12155 #      pragma intrinsic(_ReadWriteBarrier)
   12156 #    else
   12157 #      include <cmnintrin.h>
   12158 #    endif
   12159 #  endif
   12160 #endif
   12161 
   12162 /*
   12163 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
   12164 ** 0 means mutexes are permanently disable and the library is never
   12165 ** threadsafe.  1 means the library is serialized which is the highest
   12166 ** level of threadsafety.  2 means the library is multithreaded - multiple
   12167 ** threads can use SQLite as long as no two threads try to use the same
   12168 ** database connection at the same time.
   12169 **
   12170 ** Older versions of SQLite used an optional THREADSAFE macro.
   12171 ** We support that for legacy.
   12172 **
   12173 ** To ensure that the correct value of "THREADSAFE" is reported when querying
   12174 ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
   12175 ** logic is partially replicated in ctime.c. If it is updated here, it should
   12176 ** also be updated there.
   12177 */
   12178 #if !defined(SQLITE_THREADSAFE)
   12179 # if defined(THREADSAFE)
   12180 #   define SQLITE_THREADSAFE THREADSAFE
   12181 # else
   12182 #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
   12183 # endif
   12184 #endif
   12185 
   12186 /*
   12187 ** Powersafe overwrite is on by default.  But can be turned off using
   12188 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
   12189 */
   12190 #ifndef SQLITE_POWERSAFE_OVERWRITE
   12191 # define SQLITE_POWERSAFE_OVERWRITE 1
   12192 #endif
   12193 
   12194 /*
   12195 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
   12196 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
   12197 ** which case memory allocation statistics are disabled by default.
   12198 */
   12199 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
   12200 # define SQLITE_DEFAULT_MEMSTATUS 1
   12201 #endif
   12202 
   12203 /*
   12204 ** Exactly one of the following macros must be defined in order to
   12205 ** specify which memory allocation subsystem to use.
   12206 **
   12207 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
   12208 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
   12209 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
   12210 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
   12211 **
   12212 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
   12213 ** assert() macro is enabled, each call into the Win32 native heap subsystem
   12214 ** will cause HeapValidate to be called.  If heap validation should fail, an
   12215 ** assertion will be triggered.
   12216 **
   12217 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
   12218 ** the default.
   12219 */
   12220 #if defined(SQLITE_SYSTEM_MALLOC) \
   12221   + defined(SQLITE_WIN32_MALLOC) \
   12222   + defined(SQLITE_ZERO_MALLOC) \
   12223   + defined(SQLITE_MEMDEBUG)>1
   12224 # error "Two or more of the following compile-time configuration options\
   12225  are defined but at most one is allowed:\
   12226  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
   12227  SQLITE_ZERO_MALLOC"
   12228 #endif
   12229 #if defined(SQLITE_SYSTEM_MALLOC) \
   12230   + defined(SQLITE_WIN32_MALLOC) \
   12231   + defined(SQLITE_ZERO_MALLOC) \
   12232   + defined(SQLITE_MEMDEBUG)==0
   12233 # define SQLITE_SYSTEM_MALLOC 1
   12234 #endif
   12235 
   12236 /*
   12237 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
   12238 ** sizes of memory allocations below this value where possible.
   12239 */
   12240 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
   12241 # define SQLITE_MALLOC_SOFT_LIMIT 1024
   12242 #endif
   12243 
   12244 /*
   12245 ** We need to define _XOPEN_SOURCE as follows in order to enable
   12246 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
   12247 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
   12248 ** it.
   12249 */
   12250 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
   12251 #  define _XOPEN_SOURCE 600
   12252 #endif
   12253 
   12254 /*
   12255 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
   12256 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
   12257 ** make it true by defining or undefining NDEBUG.
   12258 **
   12259 ** Setting NDEBUG makes the code smaller and faster by disabling the
   12260 ** assert() statements in the code.  So we want the default action
   12261 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
   12262 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
   12263 ** feature.
   12264 */
   12265 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   12266 # define NDEBUG 1
   12267 #endif
   12268 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
   12269 # undef NDEBUG
   12270 #endif
   12271 
   12272 /*
   12273 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
   12274 */
   12275 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
   12276 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
   12277 #endif
   12278 
   12279 /*
   12280 ** The testcase() macro is used to aid in coverage testing.  When
   12281 ** doing coverage testing, the condition inside the argument to
   12282 ** testcase() must be evaluated both true and false in order to
   12283 ** get full branch coverage.  The testcase() macro is inserted
   12284 ** to help ensure adequate test coverage in places where simple
   12285 ** condition/decision coverage is inadequate.  For example, testcase()
   12286 ** can be used to make sure boundary values are tested.  For
   12287 ** bitmask tests, testcase() can be used to make sure each bit
   12288 ** is significant and used at least once.  On switch statements
   12289 ** where multiple cases go to the same block of code, testcase()
   12290 ** can insure that all cases are evaluated.
   12291 **
   12292 */
   12293 #ifdef SQLITE_COVERAGE_TEST
   12294 SQLITE_PRIVATE   void sqlite3Coverage(int);
   12295 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
   12296 #else
   12297 # define testcase(X)
   12298 #endif
   12299 
   12300 /*
   12301 ** The TESTONLY macro is used to enclose variable declarations or
   12302 ** other bits of code that are needed to support the arguments
   12303 ** within testcase() and assert() macros.
   12304 */
   12305 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
   12306 # define TESTONLY(X)  X
   12307 #else
   12308 # define TESTONLY(X)
   12309 #endif
   12310 
   12311 /*
   12312 ** Sometimes we need a small amount of code such as a variable initialization
   12313 ** to setup for a later assert() statement.  We do not want this code to
   12314 ** appear when assert() is disabled.  The following macro is therefore
   12315 ** used to contain that setup code.  The "VVA" acronym stands for
   12316 ** "Verification, Validation, and Accreditation".  In other words, the
   12317 ** code within VVA_ONLY() will only run during verification processes.
   12318 */
   12319 #ifndef NDEBUG
   12320 # define VVA_ONLY(X)  X
   12321 #else
   12322 # define VVA_ONLY(X)
   12323 #endif
   12324 
   12325 /*
   12326 ** The ALWAYS and NEVER macros surround boolean expressions which
   12327 ** are intended to always be true or false, respectively.  Such
   12328 ** expressions could be omitted from the code completely.  But they
   12329 ** are included in a few cases in order to enhance the resilience
   12330 ** of SQLite to unexpected behavior - to make the code "self-healing"
   12331 ** or "ductile" rather than being "brittle" and crashing at the first
   12332 ** hint of unplanned behavior.
   12333 **
   12334 ** In other words, ALWAYS and NEVER are added for defensive code.
   12335 **
   12336 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
   12337 ** be true and false so that the unreachable code they specify will
   12338 ** not be counted as untested code.
   12339 */
   12340 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
   12341 # define ALWAYS(X)      (1)
   12342 # define NEVER(X)       (0)
   12343 #elif !defined(NDEBUG)
   12344 # define ALWAYS(X)      ((X)?1:(assert(0),0))
   12345 # define NEVER(X)       ((X)?(assert(0),1):0)
   12346 #else
   12347 # define ALWAYS(X)      (X)
   12348 # define NEVER(X)       (X)
   12349 #endif
   12350 
   12351 /*
   12352 ** Some conditionals are optimizations only.  In other words, if the
   12353 ** conditionals are replaced with a constant 1 (true) or 0 (false) then
   12354 ** the correct answer is still obtained, though perhaps not as quickly.
   12355 **
   12356 ** The following macros mark these optimizations conditionals.
   12357 */
   12358 #if defined(SQLITE_MUTATION_TEST)
   12359 # define OK_IF_ALWAYS_TRUE(X)  (1)
   12360 # define OK_IF_ALWAYS_FALSE(X) (0)
   12361 #else
   12362 # define OK_IF_ALWAYS_TRUE(X)  (X)
   12363 # define OK_IF_ALWAYS_FALSE(X) (X)
   12364 #endif
   12365 
   12366 /*
   12367 ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
   12368 ** defined.  We need to defend against those failures when testing with
   12369 ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
   12370 ** during a normal build.  The following macro can be used to disable tests
   12371 ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
   12372 */
   12373 #if defined(SQLITE_TEST_REALLOC_STRESS)
   12374 # define ONLY_IF_REALLOC_STRESS(X)  (X)
   12375 #elif !defined(NDEBUG)
   12376 # define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
   12377 #else
   12378 # define ONLY_IF_REALLOC_STRESS(X)  (0)
   12379 #endif
   12380 
   12381 /*
   12382 ** Declarations used for tracing the operating system interfaces.
   12383 */
   12384 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
   12385     (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
   12386   extern int sqlite3OSTrace;
   12387 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   12388 # define SQLITE_HAVE_OS_TRACE
   12389 #else
   12390 # define OSTRACE(X)
   12391 # undef  SQLITE_HAVE_OS_TRACE
   12392 #endif
   12393 
   12394 /*
   12395 ** Is the sqlite3ErrName() function needed in the build?  Currently,
   12396 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
   12397 ** OSTRACE is enabled), and by several "test*.c" files (which are
   12398 ** compiled using SQLITE_TEST).
   12399 */
   12400 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
   12401     (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
   12402 # define SQLITE_NEED_ERR_NAME
   12403 #else
   12404 # undef  SQLITE_NEED_ERR_NAME
   12405 #endif
   12406 
   12407 /*
   12408 ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
   12409 */
   12410 #ifdef SQLITE_OMIT_EXPLAIN
   12411 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
   12412 #endif
   12413 
   12414 /*
   12415 ** Return true (non-zero) if the input is an integer that is too large
   12416 ** to fit in 32-bits.  This macro is used inside of various testcase()
   12417 ** macros to verify that we have tested SQLite for large-file support.
   12418 */
   12419 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
   12420 
   12421 /*
   12422 ** The macro unlikely() is a hint that surrounds a boolean
   12423 ** expression that is usually false.  Macro likely() surrounds
   12424 ** a boolean expression that is usually true.  These hints could,
   12425 ** in theory, be used by the compiler to generate better code, but
   12426 ** currently they are just comments for human readers.
   12427 */
   12428 #define likely(X)    (X)
   12429 #define unlikely(X)  (X)
   12430 
   12431 /************** Include hash.h in the middle of sqliteInt.h ******************/
   12432 /************** Begin file hash.h ********************************************/
   12433 /*
   12434 ** 2001 September 22
   12435 **
   12436 ** The author disclaims copyright to this source code.  In place of
   12437 ** a legal notice, here is a blessing:
   12438 **
   12439 **    May you do good and not evil.
   12440 **    May you find forgiveness for yourself and forgive others.
   12441 **    May you share freely, never taking more than you give.
   12442 **
   12443 *************************************************************************
   12444 ** This is the header file for the generic hash-table implementation
   12445 ** used in SQLite.
   12446 */
   12447 #ifndef SQLITE_HASH_H
   12448 #define SQLITE_HASH_H
   12449 
   12450 /* Forward declarations of structures. */
   12451 typedef struct Hash Hash;
   12452 typedef struct HashElem HashElem;
   12453 
   12454 /* A complete hash table is an instance of the following structure.
   12455 ** The internals of this structure are intended to be opaque -- client
   12456 ** code should not attempt to access or modify the fields of this structure
   12457 ** directly.  Change this structure only by using the routines below.
   12458 ** However, some of the "procedures" and "functions" for modifying and
   12459 ** accessing this structure are really macros, so we can't really make
   12460 ** this structure opaque.
   12461 **
   12462 ** All elements of the hash table are on a single doubly-linked list.
   12463 ** Hash.first points to the head of this list.
   12464 **
   12465 ** There are Hash.htsize buckets.  Each bucket points to a spot in
   12466 ** the global doubly-linked list.  The contents of the bucket are the
   12467 ** element pointed to plus the next _ht.count-1 elements in the list.
   12468 **
   12469 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
   12470 ** by a linear search of the global list.  For small tables, the
   12471 ** Hash.ht table is never allocated because if there are few elements
   12472 ** in the table, it is faster to do a linear search than to manage
   12473 ** the hash table.
   12474 */
   12475 struct Hash {
   12476   unsigned int htsize;      /* Number of buckets in the hash table */
   12477   unsigned int count;       /* Number of entries in this table */
   12478   HashElem *first;          /* The first element of the array */
   12479   struct _ht {              /* the hash table */
   12480     int count;                 /* Number of entries with this hash */
   12481     HashElem *chain;           /* Pointer to first entry with this hash */
   12482   } *ht;
   12483 };
   12484 
   12485 /* Each element in the hash table is an instance of the following
   12486 ** structure.  All elements are stored on a single doubly-linked list.
   12487 **
   12488 ** Again, this structure is intended to be opaque, but it can't really
   12489 ** be opaque because it is used by macros.
   12490 */
   12491 struct HashElem {
   12492   HashElem *next, *prev;       /* Next and previous elements in the table */
   12493   void *data;                  /* Data associated with this element */
   12494   const char *pKey;            /* Key associated with this element */
   12495 };
   12496 
   12497 /*
   12498 ** Access routines.  To delete, insert a NULL pointer.
   12499 */
   12500 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
   12501 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
   12502 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
   12503 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
   12504 
   12505 /*
   12506 ** Macros for looping over all elements of a hash table.  The idiom is
   12507 ** like this:
   12508 **
   12509 **   Hash h;
   12510 **   HashElem *p;
   12511 **   ...
   12512 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
   12513 **     SomeStructure *pData = sqliteHashData(p);
   12514 **     // do something with pData
   12515 **   }
   12516 */
   12517 #define sqliteHashFirst(H)  ((H)->first)
   12518 #define sqliteHashNext(E)   ((E)->next)
   12519 #define sqliteHashData(E)   ((E)->data)
   12520 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
   12521 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
   12522 
   12523 /*
   12524 ** Number of entries in a hash table
   12525 */
   12526 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
   12527 
   12528 #endif /* SQLITE_HASH_H */
   12529 
   12530 /************** End of hash.h ************************************************/
   12531 /************** Continuing where we left off in sqliteInt.h ******************/
   12532 /************** Include parse.h in the middle of sqliteInt.h *****************/
   12533 /************** Begin file parse.h *******************************************/
   12534 #define TK_SEMI                             1
   12535 #define TK_EXPLAIN                          2
   12536 #define TK_QUERY                            3
   12537 #define TK_PLAN                             4
   12538 #define TK_BEGIN                            5
   12539 #define TK_TRANSACTION                      6
   12540 #define TK_DEFERRED                         7
   12541 #define TK_IMMEDIATE                        8
   12542 #define TK_EXCLUSIVE                        9
   12543 #define TK_COMMIT                          10
   12544 #define TK_END                             11
   12545 #define TK_ROLLBACK                        12
   12546 #define TK_SAVEPOINT                       13
   12547 #define TK_RELEASE                         14
   12548 #define TK_TO                              15
   12549 #define TK_TABLE                           16
   12550 #define TK_CREATE                          17
   12551 #define TK_IF                              18
   12552 #define TK_NOT                             19
   12553 #define TK_EXISTS                          20
   12554 #define TK_TEMP                            21
   12555 #define TK_LP                              22
   12556 #define TK_RP                              23
   12557 #define TK_AS                              24
   12558 #define TK_WITHOUT                         25
   12559 #define TK_COMMA                           26
   12560 #define TK_ABORT                           27
   12561 #define TK_ACTION                          28
   12562 #define TK_AFTER                           29
   12563 #define TK_ANALYZE                         30
   12564 #define TK_ASC                             31
   12565 #define TK_ATTACH                          32
   12566 #define TK_BEFORE                          33
   12567 #define TK_BY                              34
   12568 #define TK_CASCADE                         35
   12569 #define TK_CAST                            36
   12570 #define TK_CONFLICT                        37
   12571 #define TK_DATABASE                        38
   12572 #define TK_DESC                            39
   12573 #define TK_DETACH                          40
   12574 #define TK_EACH                            41
   12575 #define TK_FAIL                            42
   12576 #define TK_OR                              43
   12577 #define TK_AND                             44
   12578 #define TK_IS                              45
   12579 #define TK_MATCH                           46
   12580 #define TK_LIKE_KW                         47
   12581 #define TK_BETWEEN                         48
   12582 #define TK_IN                              49
   12583 #define TK_ISNULL                          50
   12584 #define TK_NOTNULL                         51
   12585 #define TK_NE                              52
   12586 #define TK_EQ                              53
   12587 #define TK_GT                              54
   12588 #define TK_LE                              55
   12589 #define TK_LT                              56
   12590 #define TK_GE                              57
   12591 #define TK_ESCAPE                          58
   12592 #define TK_ID                              59
   12593 #define TK_COLUMNKW                        60
   12594 #define TK_FOR                             61
   12595 #define TK_IGNORE                          62
   12596 #define TK_INITIALLY                       63
   12597 #define TK_INSTEAD                         64
   12598 #define TK_NO                              65
   12599 #define TK_KEY                             66
   12600 #define TK_OF                              67
   12601 #define TK_OFFSET                          68
   12602 #define TK_PRAGMA                          69
   12603 #define TK_RAISE                           70
   12604 #define TK_RECURSIVE                       71
   12605 #define TK_REPLACE                         72
   12606 #define TK_RESTRICT                        73
   12607 #define TK_ROW                             74
   12608 #define TK_TRIGGER                         75
   12609 #define TK_VACUUM                          76
   12610 #define TK_VIEW                            77
   12611 #define TK_VIRTUAL                         78
   12612 #define TK_WITH                            79
   12613 #define TK_REINDEX                         80
   12614 #define TK_RENAME                          81
   12615 #define TK_CTIME_KW                        82
   12616 #define TK_ANY                             83
   12617 #define TK_BITAND                          84
   12618 #define TK_BITOR                           85
   12619 #define TK_LSHIFT                          86
   12620 #define TK_RSHIFT                          87
   12621 #define TK_PLUS                            88
   12622 #define TK_MINUS                           89
   12623 #define TK_STAR                            90
   12624 #define TK_SLASH                           91
   12625 #define TK_REM                             92
   12626 #define TK_CONCAT                          93
   12627 #define TK_COLLATE                         94
   12628 #define TK_BITNOT                          95
   12629 #define TK_INDEXED                         96
   12630 #define TK_STRING                          97
   12631 #define TK_JOIN_KW                         98
   12632 #define TK_CONSTRAINT                      99
   12633 #define TK_DEFAULT                        100
   12634 #define TK_NULL                           101
   12635 #define TK_PRIMARY                        102
   12636 #define TK_UNIQUE                         103
   12637 #define TK_CHECK                          104
   12638 #define TK_REFERENCES                     105
   12639 #define TK_AUTOINCR                       106
   12640 #define TK_ON                             107
   12641 #define TK_INSERT                         108
   12642 #define TK_DELETE                         109
   12643 #define TK_UPDATE                         110
   12644 #define TK_SET                            111
   12645 #define TK_DEFERRABLE                     112
   12646 #define TK_FOREIGN                        113
   12647 #define TK_DROP                           114
   12648 #define TK_UNION                          115
   12649 #define TK_ALL                            116
   12650 #define TK_EXCEPT                         117
   12651 #define TK_INTERSECT                      118
   12652 #define TK_SELECT                         119
   12653 #define TK_VALUES                         120
   12654 #define TK_DISTINCT                       121
   12655 #define TK_DOT                            122
   12656 #define TK_FROM                           123
   12657 #define TK_JOIN                           124
   12658 #define TK_USING                          125
   12659 #define TK_ORDER                          126
   12660 #define TK_GROUP                          127
   12661 #define TK_HAVING                         128
   12662 #define TK_LIMIT                          129
   12663 #define TK_WHERE                          130
   12664 #define TK_INTO                           131
   12665 #define TK_FLOAT                          132
   12666 #define TK_BLOB                           133
   12667 #define TK_INTEGER                        134
   12668 #define TK_VARIABLE                       135
   12669 #define TK_CASE                           136
   12670 #define TK_WHEN                           137
   12671 #define TK_THEN                           138
   12672 #define TK_ELSE                           139
   12673 #define TK_INDEX                          140
   12674 #define TK_ALTER                          141
   12675 #define TK_ADD                            142
   12676 #define TK_ISNOT                          143
   12677 #define TK_FUNCTION                       144
   12678 #define TK_COLUMN                         145
   12679 #define TK_AGG_FUNCTION                   146
   12680 #define TK_AGG_COLUMN                     147
   12681 #define TK_UMINUS                         148
   12682 #define TK_UPLUS                          149
   12683 #define TK_REGISTER                       150
   12684 #define TK_VECTOR                         151
   12685 #define TK_SELECT_COLUMN                  152
   12686 #define TK_IF_NULL_ROW                    153
   12687 #define TK_ASTERISK                       154
   12688 #define TK_SPAN                           155
   12689 #define TK_END_OF_FILE                    156
   12690 #define TK_UNCLOSED_STRING                157
   12691 #define TK_SPACE                          158
   12692 #define TK_ILLEGAL                        159
   12693 
   12694 /* The token codes above must all fit in 8 bits */
   12695 #define TKFLG_MASK           0xff
   12696 
   12697 /* Flags that can be added to a token code when it is not
   12698 ** being stored in a u8: */
   12699 #define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
   12700 
   12701 /************** End of parse.h ***********************************************/
   12702 /************** Continuing where we left off in sqliteInt.h ******************/
   12703 #include <stdio.h>
   12704 #include <stdlib.h>
   12705 #include <string.h>
   12706 #include <assert.h>
   12707 #include <stddef.h>
   12708 
   12709 /*
   12710 ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
   12711 ** This allows better measurements of where memcpy() is used when running
   12712 ** cachegrind.  But this macro version of memcpy() is very slow so it
   12713 ** should not be used in production.  This is a performance measurement
   12714 ** hack only.
   12715 */
   12716 #ifdef SQLITE_INLINE_MEMCPY
   12717 # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
   12718                         int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
   12719 #endif
   12720 
   12721 /*
   12722 ** If compiling for a processor that lacks floating point support,
   12723 ** substitute integer for floating-point
   12724 */
   12725 #ifdef SQLITE_OMIT_FLOATING_POINT
   12726 # define double sqlite_int64
   12727 # define float sqlite_int64
   12728 # define LONGDOUBLE_TYPE sqlite_int64
   12729 # ifndef SQLITE_BIG_DBL
   12730 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
   12731 # endif
   12732 # define SQLITE_OMIT_DATETIME_FUNCS 1
   12733 # define SQLITE_OMIT_TRACE 1
   12734 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   12735 # undef SQLITE_HAVE_ISNAN
   12736 #endif
   12737 #ifndef SQLITE_BIG_DBL
   12738 # define SQLITE_BIG_DBL (1e99)
   12739 #endif
   12740 
   12741 /*
   12742 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
   12743 ** afterward. Having this macro allows us to cause the C compiler
   12744 ** to omit code used by TEMP tables without messy #ifndef statements.
   12745 */
   12746 #ifdef SQLITE_OMIT_TEMPDB
   12747 #define OMIT_TEMPDB 1
   12748 #else
   12749 #define OMIT_TEMPDB 0
   12750 #endif
   12751 
   12752 /*
   12753 ** The "file format" number is an integer that is incremented whenever
   12754 ** the VDBE-level file format changes.  The following macros define the
   12755 ** the default file format for new databases and the maximum file format
   12756 ** that the library can read.
   12757 */
   12758 #define SQLITE_MAX_FILE_FORMAT 4
   12759 #ifndef SQLITE_DEFAULT_FILE_FORMAT
   12760 # define SQLITE_DEFAULT_FILE_FORMAT 4
   12761 #endif
   12762 
   12763 /*
   12764 ** Determine whether triggers are recursive by default.  This can be
   12765 ** changed at run-time using a pragma.
   12766 */
   12767 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   12768 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
   12769 #endif
   12770 
   12771 /*
   12772 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
   12773 ** on the command-line
   12774 */
   12775 #ifndef SQLITE_TEMP_STORE
   12776 # define SQLITE_TEMP_STORE 1
   12777 #endif
   12778 
   12779 /*
   12780 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
   12781 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
   12782 ** to zero.
   12783 */
   12784 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
   12785 # undef SQLITE_MAX_WORKER_THREADS
   12786 # define SQLITE_MAX_WORKER_THREADS 0
   12787 #endif
   12788 #ifndef SQLITE_MAX_WORKER_THREADS
   12789 # define SQLITE_MAX_WORKER_THREADS 8
   12790 #endif
   12791 #ifndef SQLITE_DEFAULT_WORKER_THREADS
   12792 # define SQLITE_DEFAULT_WORKER_THREADS 0
   12793 #endif
   12794 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
   12795 # undef SQLITE_MAX_WORKER_THREADS
   12796 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
   12797 #endif
   12798 
   12799 /*
   12800 ** The default initial allocation for the pagecache when using separate
   12801 ** pagecaches for each database connection.  A positive number is the
   12802 ** number of pages.  A negative number N translations means that a buffer
   12803 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
   12804 **
   12805 ** The default value of "20" was choosen to minimize the run-time of the
   12806 ** speedtest1 test program with options: --shrink-memory --reprepare
   12807 */
   12808 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
   12809 # define SQLITE_DEFAULT_PCACHE_INITSZ 20
   12810 #endif
   12811 
   12812 /*
   12813 ** The compile-time options SQLITE_MMAP_READWRITE and
   12814 ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
   12815 ** You must choose one or the other (or neither) but not both.
   12816 */
   12817 #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   12818 #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   12819 #endif
   12820 
   12821 /*
   12822 ** GCC does not define the offsetof() macro so we'll have to do it
   12823 ** ourselves.
   12824 */
   12825 #ifndef offsetof
   12826 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
   12827 #endif
   12828 
   12829 /*
   12830 ** Macros to compute minimum and maximum of two numbers.
   12831 */
   12832 #ifndef MIN
   12833 # define MIN(A,B) ((A)<(B)?(A):(B))
   12834 #endif
   12835 #ifndef MAX
   12836 # define MAX(A,B) ((A)>(B)?(A):(B))
   12837 #endif
   12838 
   12839 /*
   12840 ** Swap two objects of type TYPE.
   12841 */
   12842 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   12843 
   12844 /*
   12845 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
   12846 ** not, there are still machines out there that use EBCDIC.)
   12847 */
   12848 #if 'A' == '\301'
   12849 # define SQLITE_EBCDIC 1
   12850 #else
   12851 # define SQLITE_ASCII 1
   12852 #endif
   12853 
   12854 /*
   12855 ** Integers of known sizes.  These typedefs might change for architectures
   12856 ** where the sizes very.  Preprocessor macros are available so that the
   12857 ** types can be conveniently redefined at compile-type.  Like this:
   12858 **
   12859 **         cc '-DUINTPTR_TYPE=long long int' ...
   12860 */
   12861 #ifndef UINT32_TYPE
   12862 # ifdef HAVE_UINT32_T
   12863 #  define UINT32_TYPE uint32_t
   12864 # else
   12865 #  define UINT32_TYPE unsigned int
   12866 # endif
   12867 #endif
   12868 #ifndef UINT16_TYPE
   12869 # ifdef HAVE_UINT16_T
   12870 #  define UINT16_TYPE uint16_t
   12871 # else
   12872 #  define UINT16_TYPE unsigned short int
   12873 # endif
   12874 #endif
   12875 #ifndef INT16_TYPE
   12876 # ifdef HAVE_INT16_T
   12877 #  define INT16_TYPE int16_t
   12878 # else
   12879 #  define INT16_TYPE short int
   12880 # endif
   12881 #endif
   12882 #ifndef UINT8_TYPE
   12883 # ifdef HAVE_UINT8_T
   12884 #  define UINT8_TYPE uint8_t
   12885 # else
   12886 #  define UINT8_TYPE unsigned char
   12887 # endif
   12888 #endif
   12889 #ifndef INT8_TYPE
   12890 # ifdef HAVE_INT8_T
   12891 #  define INT8_TYPE int8_t
   12892 # else
   12893 #  define INT8_TYPE signed char
   12894 # endif
   12895 #endif
   12896 #ifndef LONGDOUBLE_TYPE
   12897 # define LONGDOUBLE_TYPE long double
   12898 #endif
   12899 typedef sqlite_int64 i64;          /* 8-byte signed integer */
   12900 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
   12901 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
   12902 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
   12903 typedef INT16_TYPE i16;            /* 2-byte signed integer */
   12904 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
   12905 typedef INT8_TYPE i8;              /* 1-byte signed integer */
   12906 
   12907 /*
   12908 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
   12909 ** that can be stored in a u32 without loss of data.  The value
   12910 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
   12911 ** have to specify the value in the less intuitive manner shown:
   12912 */
   12913 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
   12914 
   12915 /*
   12916 ** The datatype used to store estimates of the number of rows in a
   12917 ** table or index.  This is an unsigned integer type.  For 99.9% of
   12918 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
   12919 ** can be used at compile-time if desired.
   12920 */
   12921 #ifdef SQLITE_64BIT_STATS
   12922  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
   12923 #else
   12924  typedef u32 tRowcnt;    /* 32-bit is the default */
   12925 #endif
   12926 
   12927 /*
   12928 ** Estimated quantities used for query planning are stored as 16-bit
   12929 ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
   12930 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
   12931 ** But the allowed values are "grainy".  Not every value is representable.
   12932 ** For example, quantities 16 and 17 are both represented by a LogEst
   12933 ** of 40.  However, since LogEst quantities are suppose to be estimates,
   12934 ** not exact values, this imprecision is not a problem.
   12935 **
   12936 ** "LogEst" is short for "Logarithmic Estimate".
   12937 **
   12938 ** Examples:
   12939 **      1 -> 0              20 -> 43          10000 -> 132
   12940 **      2 -> 10             25 -> 46          25000 -> 146
   12941 **      3 -> 16            100 -> 66        1000000 -> 199
   12942 **      4 -> 20           1000 -> 99        1048576 -> 200
   12943 **     10 -> 33           1024 -> 100    4294967296 -> 320
   12944 **
   12945 ** The LogEst can be negative to indicate fractional values.
   12946 ** Examples:
   12947 **
   12948 **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
   12949 */
   12950 typedef INT16_TYPE LogEst;
   12951 
   12952 /*
   12953 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
   12954 */
   12955 #ifndef SQLITE_PTRSIZE
   12956 # if defined(__SIZEOF_POINTER__)
   12957 #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
   12958 # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
   12959        defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
   12960 #   define SQLITE_PTRSIZE 4
   12961 # else
   12962 #   define SQLITE_PTRSIZE 8
   12963 # endif
   12964 #endif
   12965 
   12966 /* The uptr type is an unsigned integer large enough to hold a pointer
   12967 */
   12968 #if defined(HAVE_STDINT_H)
   12969   typedef uintptr_t uptr;
   12970 #elif SQLITE_PTRSIZE==4
   12971   typedef u32 uptr;
   12972 #else
   12973   typedef u64 uptr;
   12974 #endif
   12975 
   12976 /*
   12977 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
   12978 ** something between S (inclusive) and E (exclusive).
   12979 **
   12980 ** In other words, S is a buffer and E is a pointer to the first byte after
   12981 ** the end of buffer S.  This macro returns true if P points to something
   12982 ** contained within the buffer S.
   12983 */
   12984 #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
   12985 
   12986 
   12987 /*
   12988 ** Macros to determine whether the machine is big or little endian,
   12989 ** and whether or not that determination is run-time or compile-time.
   12990 **
   12991 ** For best performance, an attempt is made to guess at the byte-order
   12992 ** using C-preprocessor macros.  If that is unsuccessful, or if
   12993 ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
   12994 ** at run-time.
   12995 */
   12996 #ifndef SQLITE_BYTEORDER
   12997 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
   12998      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
   12999      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
   13000      defined(__arm__)
   13001 #   define SQLITE_BYTEORDER    1234
   13002 # elif defined(sparc)    || defined(__ppc__)
   13003 #   define SQLITE_BYTEORDER    4321
   13004 # else
   13005 #   define SQLITE_BYTEORDER 0
   13006 # endif
   13007 #endif
   13008 #if SQLITE_BYTEORDER==4321
   13009 # define SQLITE_BIGENDIAN    1
   13010 # define SQLITE_LITTLEENDIAN 0
   13011 # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
   13012 #elif SQLITE_BYTEORDER==1234
   13013 # define SQLITE_BIGENDIAN    0
   13014 # define SQLITE_LITTLEENDIAN 1
   13015 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
   13016 #else
   13017 # ifdef SQLITE_AMALGAMATION
   13018   const int sqlite3one = 1;
   13019 # else
   13020   extern const int sqlite3one;
   13021 # endif
   13022 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
   13023 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
   13024 # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
   13025 #endif
   13026 
   13027 /*
   13028 ** Constants for the largest and smallest possible 64-bit signed integers.
   13029 ** These macros are designed to work correctly on both 32-bit and 64-bit
   13030 ** compilers.
   13031 */
   13032 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   13033 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
   13034 
   13035 /*
   13036 ** Round up a number to the next larger multiple of 8.  This is used
   13037 ** to force 8-byte alignment on 64-bit architectures.
   13038 */
   13039 #define ROUND8(x)     (((x)+7)&~7)
   13040 
   13041 /*
   13042 ** Round down to the nearest multiple of 8
   13043 */
   13044 #define ROUNDDOWN8(x) ((x)&~7)
   13045 
   13046 /*
   13047 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
   13048 ** macro is used only within assert() to verify that the code gets
   13049 ** all alignment restrictions correct.
   13050 **
   13051 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
   13052 ** underlying malloc() implementation might return us 4-byte aligned
   13053 ** pointers.  In that case, only verify 4-byte alignment.
   13054 */
   13055 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   13056 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
   13057 #else
   13058 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
   13059 #endif
   13060 
   13061 /*
   13062 ** Disable MMAP on platforms where it is known to not work
   13063 */
   13064 #if defined(__OpenBSD__) || defined(__QNXNTO__)
   13065 # undef SQLITE_MAX_MMAP_SIZE
   13066 # define SQLITE_MAX_MMAP_SIZE 0
   13067 #endif
   13068 
   13069 /*
   13070 ** Default maximum size of memory used by memory-mapped I/O in the VFS
   13071 */
   13072 #ifdef __APPLE__
   13073 # include <TargetConditionals.h>
   13074 #endif
   13075 #ifndef SQLITE_MAX_MMAP_SIZE
   13076 # if defined(__linux__) \
   13077   || defined(_WIN32) \
   13078   || (defined(__APPLE__) && defined(__MACH__)) \
   13079   || defined(__sun) \
   13080   || defined(__FreeBSD__) \
   13081   || defined(__DragonFly__)
   13082 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
   13083 # else
   13084 #   define SQLITE_MAX_MMAP_SIZE 0
   13085 # endif
   13086 #endif
   13087 
   13088 /*
   13089 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
   13090 ** default MMAP_SIZE is specified at compile-time, make sure that it does
   13091 ** not exceed the maximum mmap size.
   13092 */
   13093 #ifndef SQLITE_DEFAULT_MMAP_SIZE
   13094 # define SQLITE_DEFAULT_MMAP_SIZE 0
   13095 #endif
   13096 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
   13097 # undef SQLITE_DEFAULT_MMAP_SIZE
   13098 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
   13099 #endif
   13100 
   13101 /*
   13102 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
   13103 ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
   13104 ** define SQLITE_ENABLE_STAT3_OR_STAT4
   13105 */
   13106 #ifdef SQLITE_ENABLE_STAT4
   13107 # undef SQLITE_ENABLE_STAT3
   13108 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
   13109 #elif SQLITE_ENABLE_STAT3
   13110 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
   13111 #elif SQLITE_ENABLE_STAT3_OR_STAT4
   13112 # undef SQLITE_ENABLE_STAT3_OR_STAT4
   13113 #endif
   13114 
   13115 /*
   13116 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
   13117 ** the Select query generator tracing logic is turned on.
   13118 */
   13119 #if defined(SQLITE_ENABLE_SELECTTRACE)
   13120 # define SELECTTRACE_ENABLED 1
   13121 #else
   13122 # define SELECTTRACE_ENABLED 0
   13123 #endif
   13124 
   13125 /*
   13126 ** An instance of the following structure is used to store the busy-handler
   13127 ** callback for a given sqlite handle.
   13128 **
   13129 ** The sqlite.busyHandler member of the sqlite struct contains the busy
   13130 ** callback for the database handle. Each pager opened via the sqlite
   13131 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
   13132 ** callback is currently invoked only from within pager.c.
   13133 */
   13134 typedef struct BusyHandler BusyHandler;
   13135 struct BusyHandler {
   13136   int (*xFunc)(void *,int);  /* The busy callback */
   13137   void *pArg;                /* First arg to busy callback */
   13138   int nBusy;                 /* Incremented with each busy call */
   13139 };
   13140 
   13141 /*
   13142 ** Name of the master database table.  The master database table
   13143 ** is a special table that holds the names and attributes of all
   13144 ** user tables and indices.
   13145 */
   13146 #define MASTER_NAME       "sqlite_master"
   13147 #define TEMP_MASTER_NAME  "sqlite_temp_master"
   13148 
   13149 /*
   13150 ** The root-page of the master database table.
   13151 */
   13152 #define MASTER_ROOT       1
   13153 
   13154 /*
   13155 ** The name of the schema table.
   13156 */
   13157 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
   13158 
   13159 /*
   13160 ** A convenience macro that returns the number of elements in
   13161 ** an array.
   13162 */
   13163 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
   13164 
   13165 /*
   13166 ** Determine if the argument is a power of two
   13167 */
   13168 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
   13169 
   13170 /*
   13171 ** The following value as a destructor means to use sqlite3DbFree().
   13172 ** The sqlite3DbFree() routine requires two parameters instead of the
   13173 ** one parameter that destructors normally want.  So we have to introduce
   13174 ** this magic value that the code knows to handle differently.  Any
   13175 ** pointer will work here as long as it is distinct from SQLITE_STATIC
   13176 ** and SQLITE_TRANSIENT.
   13177 */
   13178 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
   13179 
   13180 /*
   13181 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
   13182 ** not support Writable Static Data (WSD) such as global and static variables.
   13183 ** All variables must either be on the stack or dynamically allocated from
   13184 ** the heap.  When WSD is unsupported, the variable declarations scattered
   13185 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
   13186 ** macro is used for this purpose.  And instead of referencing the variable
   13187 ** directly, we use its constant as a key to lookup the run-time allocated
   13188 ** buffer that holds real variable.  The constant is also the initializer
   13189 ** for the run-time allocated buffer.
   13190 **
   13191 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
   13192 ** macros become no-ops and have zero performance impact.
   13193 */
   13194 #ifdef SQLITE_OMIT_WSD
   13195   #define SQLITE_WSD const
   13196   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
   13197   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
   13198 SQLITE_API int sqlite3_wsd_init(int N, int J);
   13199 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
   13200 #else
   13201   #define SQLITE_WSD
   13202   #define GLOBAL(t,v) v
   13203   #define sqlite3GlobalConfig sqlite3Config
   13204 #endif
   13205 
   13206 /*
   13207 ** The following macros are used to suppress compiler warnings and to
   13208 ** make it clear to human readers when a function parameter is deliberately
   13209 ** left unused within the body of a function. This usually happens when
   13210 ** a function is called via a function pointer. For example the
   13211 ** implementation of an SQL aggregate step callback may not use the
   13212 ** parameter indicating the number of arguments passed to the aggregate,
   13213 ** if it knows that this is enforced elsewhere.
   13214 **
   13215 ** When a function parameter is not used at all within the body of a function,
   13216 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
   13217 ** However, these macros may also be used to suppress warnings related to
   13218 ** parameters that may or may not be used depending on compilation options.
   13219 ** For example those parameters only used in assert() statements. In these
   13220 ** cases the parameters are named as per the usual conventions.
   13221 */
   13222 #define UNUSED_PARAMETER(x) (void)(x)
   13223 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
   13224 
   13225 /*
   13226 ** Forward references to structures
   13227 */
   13228 typedef struct AggInfo AggInfo;
   13229 typedef struct AuthContext AuthContext;
   13230 typedef struct AutoincInfo AutoincInfo;
   13231 typedef struct Bitvec Bitvec;
   13232 typedef struct CollSeq CollSeq;
   13233 typedef struct Column Column;
   13234 typedef struct Db Db;
   13235 typedef struct Schema Schema;
   13236 typedef struct Expr Expr;
   13237 typedef struct ExprList ExprList;
   13238 typedef struct FKey FKey;
   13239 typedef struct FuncDestructor FuncDestructor;
   13240 typedef struct FuncDef FuncDef;
   13241 typedef struct FuncDefHash FuncDefHash;
   13242 typedef struct IdList IdList;
   13243 typedef struct Index Index;
   13244 typedef struct IndexSample IndexSample;
   13245 typedef struct KeyClass KeyClass;
   13246 typedef struct KeyInfo KeyInfo;
   13247 typedef struct Lookaside Lookaside;
   13248 typedef struct LookasideSlot LookasideSlot;
   13249 typedef struct Module Module;
   13250 typedef struct NameContext NameContext;
   13251 typedef struct Parse Parse;
   13252 typedef struct PreUpdate PreUpdate;
   13253 typedef struct PrintfArguments PrintfArguments;
   13254 typedef struct RowSet RowSet;
   13255 typedef struct Savepoint Savepoint;
   13256 typedef struct Select Select;
   13257 typedef struct SQLiteThread SQLiteThread;
   13258 typedef struct SelectDest SelectDest;
   13259 typedef struct SrcList SrcList;
   13260 typedef struct StrAccum StrAccum;
   13261 typedef struct Table Table;
   13262 typedef struct TableLock TableLock;
   13263 typedef struct Token Token;
   13264 typedef struct TreeView TreeView;
   13265 typedef struct Trigger Trigger;
   13266 typedef struct TriggerPrg TriggerPrg;
   13267 typedef struct TriggerStep TriggerStep;
   13268 typedef struct UnpackedRecord UnpackedRecord;
   13269 typedef struct VTable VTable;
   13270 typedef struct VtabCtx VtabCtx;
   13271 typedef struct Walker Walker;
   13272 typedef struct WhereInfo WhereInfo;
   13273 typedef struct With With;
   13274 
   13275 /* A VList object records a mapping between parameters/variables/wildcards
   13276 ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
   13277 ** variable number associated with that parameter.  See the format description
   13278 ** on the sqlite3VListAdd() routine for more information.  A VList is really
   13279 ** just an array of integers.
   13280 */
   13281 typedef int VList;
   13282 
   13283 /*
   13284 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
   13285 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
   13286 ** pointer types (i.e. FuncDef) defined above.
   13287 */
   13288 /************** Include btree.h in the middle of sqliteInt.h *****************/
   13289 /************** Begin file btree.h *******************************************/
   13290 /*
   13291 ** 2001 September 15
   13292 **
   13293 ** The author disclaims copyright to this source code.  In place of
   13294 ** a legal notice, here is a blessing:
   13295 **
   13296 **    May you do good and not evil.
   13297 **    May you find forgiveness for yourself and forgive others.
   13298 **    May you share freely, never taking more than you give.
   13299 **
   13300 *************************************************************************
   13301 ** This header file defines the interface that the sqlite B-Tree file
   13302 ** subsystem.  See comments in the source code for a detailed description
   13303 ** of what each interface routine does.
   13304 */
   13305 #ifndef SQLITE_BTREE_H
   13306 #define SQLITE_BTREE_H
   13307 
   13308 /* TODO: This definition is just included so other modules compile. It
   13309 ** needs to be revisited.
   13310 */
   13311 #define SQLITE_N_BTREE_META 16
   13312 
   13313 /*
   13314 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
   13315 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
   13316 */
   13317 #ifndef SQLITE_DEFAULT_AUTOVACUUM
   13318   #define SQLITE_DEFAULT_AUTOVACUUM 0
   13319 #endif
   13320 
   13321 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
   13322 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
   13323 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
   13324 
   13325 /*
   13326 ** Forward declarations of structure
   13327 */
   13328 typedef struct Btree Btree;
   13329 typedef struct BtCursor BtCursor;
   13330 typedef struct BtShared BtShared;
   13331 typedef struct BtreePayload BtreePayload;
   13332 
   13333 
   13334 SQLITE_PRIVATE int sqlite3BtreeOpen(
   13335   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
   13336   const char *zFilename,   /* Name of database file to open */
   13337   sqlite3 *db,             /* Associated database connection */
   13338   Btree **ppBtree,         /* Return open Btree* here */
   13339   int flags,               /* Flags */
   13340   int vfsFlags             /* Flags passed through to VFS open */
   13341 );
   13342 
   13343 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
   13344 ** following values.
   13345 **
   13346 ** NOTE:  These values must match the corresponding PAGER_ values in
   13347 ** pager.h.
   13348 */
   13349 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
   13350 #define BTREE_MEMORY        2  /* This is an in-memory DB */
   13351 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
   13352 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
   13353 
   13354 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
   13355 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
   13356 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
   13357 #if SQLITE_MAX_MMAP_SIZE>0
   13358 SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
   13359 #endif
   13360 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
   13361 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
   13362 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
   13363 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
   13364 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
   13365 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
   13366 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
   13367 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
   13368 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
   13369 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
   13370 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
   13371 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
   13372 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
   13373 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
   13374 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
   13375 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
   13376 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
   13377 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
   13378 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
   13379 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
   13380 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
   13381 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
   13382 #ifndef SQLITE_OMIT_SHARED_CACHE
   13383 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
   13384 #endif
   13385 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
   13386 
   13387 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
   13388 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
   13389 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
   13390 
   13391 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
   13392 
   13393 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
   13394 ** of the flags shown below.
   13395 **
   13396 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
   13397 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
   13398 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
   13399 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
   13400 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
   13401 ** indices.)
   13402 */
   13403 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
   13404 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
   13405 
   13406 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
   13407 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
   13408 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
   13409 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
   13410 
   13411 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
   13412 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
   13413 
   13414 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
   13415 
   13416 /*
   13417 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
   13418 ** should be one of the following values. The integer values are assigned
   13419 ** to constants so that the offset of the corresponding field in an
   13420 ** SQLite database header may be found using the following formula:
   13421 **
   13422 **   offset = 36 + (idx * 4)
   13423 **
   13424 ** For example, the free-page-count field is located at byte offset 36 of
   13425 ** the database file header. The incr-vacuum-flag field is located at
   13426 ** byte offset 64 (== 36+4*7).
   13427 **
   13428 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
   13429 ** It is a read-only number computed by the pager.  But we merge it with
   13430 ** the header value access routines since its access pattern is the same.
   13431 ** Call it a "virtual meta value".
   13432 */
   13433 #define BTREE_FREE_PAGE_COUNT     0
   13434 #define BTREE_SCHEMA_VERSION      1
   13435 #define BTREE_FILE_FORMAT         2
   13436 #define BTREE_DEFAULT_CACHE_SIZE  3
   13437 #define BTREE_LARGEST_ROOT_PAGE   4
   13438 #define BTREE_TEXT_ENCODING       5
   13439 #define BTREE_USER_VERSION        6
   13440 #define BTREE_INCR_VACUUM         7
   13441 #define BTREE_APPLICATION_ID      8
   13442 #define BTREE_DATA_VERSION        15  /* A virtual meta-value */
   13443 
   13444 /*
   13445 ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
   13446 ** interface.
   13447 **
   13448 ** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
   13449 **
   13450 **     The first argument is an Expr* (which is guaranteed to be constant for
   13451 **     the lifetime of the cursor) that defines constraints on which rows
   13452 **     might be fetched with this cursor.  The Expr* tree may contain
   13453 **     TK_REGISTER nodes that refer to values stored in the array of registers
   13454 **     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
   13455 **     then the value of the node is the value in Mem[pExpr.iTable].  Any
   13456 **     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
   13457 **     column of the b-tree of the cursor.  The Expr tree will not contain
   13458 **     any function calls nor subqueries nor references to b-trees other than
   13459 **     the cursor being hinted.
   13460 **
   13461 **     The design of the _RANGE hint is aid b-tree implementations that try
   13462 **     to prefetch content from remote machines - to provide those
   13463 **     implementations with limits on what needs to be prefetched and thereby
   13464 **     reduce network bandwidth.
   13465 **
   13466 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
   13467 ** standard SQLite.  The other hints are provided for extentions that use
   13468 ** the SQLite parser and code generator but substitute their own storage
   13469 ** engine.
   13470 */
   13471 #define BTREE_HINT_RANGE 0       /* Range constraints on queries */
   13472 
   13473 /*
   13474 ** Values that may be OR'd together to form the argument to the
   13475 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
   13476 **
   13477 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
   13478 ** to be filled with content that is already in sorted order.
   13479 **
   13480 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
   13481 ** OP_SeekLE opcodes for a range search, but where the range of entries
   13482 ** selected will all have the same key.  In other words, the cursor will
   13483 ** be used only for equality key searches.
   13484 **
   13485 */
   13486 #define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
   13487 #define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
   13488 
   13489 /*
   13490 ** Flags passed as the third argument to sqlite3BtreeCursor().
   13491 **
   13492 ** For read-only cursors the wrFlag argument is always zero. For read-write
   13493 ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
   13494 ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
   13495 ** only be used by SQLite for the following:
   13496 **
   13497 **   * to seek to and then delete specific entries, and/or
   13498 **
   13499 **   * to read values that will be used to create keys that other
   13500 **     BTREE_FORDELETE cursors will seek to and delete.
   13501 **
   13502 ** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
   13503 ** by this, the native b-tree engine of SQLite, but it is available to
   13504 ** alternative storage engines that might be substituted in place of this
   13505 ** b-tree system.  For alternative storage engines in which a delete of
   13506 ** the main table row automatically deletes corresponding index rows,
   13507 ** the FORDELETE flag hint allows those alternative storage engines to
   13508 ** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
   13509 ** and DELETE operations as no-ops, and any READ operation against a
   13510 ** FORDELETE cursor may return a null row: 0x01 0x00.
   13511 */
   13512 #define BTREE_WRCSR     0x00000004     /* read-write cursor */
   13513 #define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
   13514 
   13515 SQLITE_PRIVATE int sqlite3BtreeCursor(
   13516   Btree*,                              /* BTree containing table to open */
   13517   int iTable,                          /* Index of root page */
   13518   int wrFlag,                          /* 1 for writing.  0 for read-only */
   13519   struct KeyInfo*,                     /* First argument to compare function */
   13520   BtCursor *pCursor                    /* Space to write cursor structure */
   13521 );
   13522 SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
   13523 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
   13524 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
   13525 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
   13526 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   13527 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
   13528 #endif
   13529 
   13530 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
   13531 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   13532   BtCursor*,
   13533   UnpackedRecord *pUnKey,
   13534   i64 intKey,
   13535   int bias,
   13536   int *pRes
   13537 );
   13538 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
   13539 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
   13540 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
   13541 
   13542 /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
   13543 #define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
   13544 #define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
   13545 #define BTREE_APPEND       0x08  /* Insert is likely an append */
   13546 
   13547 /* An instance of the BtreePayload object describes the content of a single
   13548 ** entry in either an index or table btree.
   13549 **
   13550 ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
   13551 ** an arbitrary key and no data.  These btrees have pKey,nKey set to their
   13552 ** key and pData,nData,nZero set to zero.
   13553 **
   13554 ** Table btrees (used for rowid tables) contain an integer rowid used as
   13555 ** the key and passed in the nKey field.  The pKey field is zero.
   13556 ** pData,nData hold the content of the new entry.  nZero extra zero bytes
   13557 ** are appended to the end of the content when constructing the entry.
   13558 **
   13559 ** This object is used to pass information into sqlite3BtreeInsert().  The
   13560 ** same information used to be passed as five separate parameters.  But placing
   13561 ** the information into this object helps to keep the interface more
   13562 ** organized and understandable, and it also helps the resulting code to
   13563 ** run a little faster by using fewer registers for parameter passing.
   13564 */
   13565 struct BtreePayload {
   13566   const void *pKey;       /* Key content for indexes.  NULL for tables */
   13567   sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
   13568   const void *pData;      /* Data for tables.  NULL for indexes */
   13569   sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */
   13570   u16 nMem;               /* Number of aMem[] value.  Might be zero */
   13571   int nData;              /* Size of pData.  0 if none. */
   13572   int nZero;              /* Extra zero data appended after pData,nData */
   13573 };
   13574 
   13575 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
   13576                        int flags, int seekResult);
   13577 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
   13578 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
   13579 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
   13580 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
   13581 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
   13582 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
   13583 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
   13584 SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
   13585 #endif
   13586 SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
   13587 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
   13588 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
   13589 
   13590 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
   13591 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
   13592 SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
   13593 
   13594 #ifndef SQLITE_OMIT_INCRBLOB
   13595 SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
   13596 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
   13597 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
   13598 #endif
   13599 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
   13600 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
   13601 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
   13602 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
   13603 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
   13604 
   13605 #ifndef NDEBUG
   13606 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
   13607 #endif
   13608 SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
   13609 
   13610 #ifndef SQLITE_OMIT_BTREECOUNT
   13611 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
   13612 #endif
   13613 
   13614 #ifdef SQLITE_TEST
   13615 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
   13616 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
   13617 #endif
   13618 
   13619 #ifndef SQLITE_OMIT_WAL
   13620 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
   13621 #endif
   13622 
   13623 /*
   13624 ** If we are not using shared cache, then there is no need to
   13625 ** use mutexes to access the BtShared structures.  So make the
   13626 ** Enter and Leave procedures no-ops.
   13627 */
   13628 #ifndef SQLITE_OMIT_SHARED_CACHE
   13629 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
   13630 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
   13631 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
   13632 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
   13633 SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
   13634 #else
   13635 # define sqlite3BtreeEnter(X)
   13636 # define sqlite3BtreeEnterAll(X)
   13637 # define sqlite3BtreeSharable(X) 0
   13638 # define sqlite3BtreeEnterCursor(X)
   13639 # define sqlite3BtreeConnectionCount(X) 1
   13640 #endif
   13641 
   13642 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
   13643 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
   13644 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
   13645 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
   13646 #ifndef NDEBUG
   13647   /* These routines are used inside assert() statements only. */
   13648 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
   13649 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
   13650 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
   13651 #endif
   13652 #else
   13653 
   13654 # define sqlite3BtreeLeave(X)
   13655 # define sqlite3BtreeLeaveCursor(X)
   13656 # define sqlite3BtreeLeaveAll(X)
   13657 
   13658 # define sqlite3BtreeHoldsMutex(X) 1
   13659 # define sqlite3BtreeHoldsAllMutexes(X) 1
   13660 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
   13661 #endif
   13662 
   13663 
   13664 #endif /* SQLITE_BTREE_H */
   13665 
   13666 /************** End of btree.h ***********************************************/
   13667 /************** Continuing where we left off in sqliteInt.h ******************/
   13668 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
   13669 /************** Begin file vdbe.h ********************************************/
   13670 /*
   13671 ** 2001 September 15
   13672 **
   13673 ** The author disclaims copyright to this source code.  In place of
   13674 ** a legal notice, here is a blessing:
   13675 **
   13676 **    May you do good and not evil.
   13677 **    May you find forgiveness for yourself and forgive others.
   13678 **    May you share freely, never taking more than you give.
   13679 **
   13680 *************************************************************************
   13681 ** Header file for the Virtual DataBase Engine (VDBE)
   13682 **
   13683 ** This header defines the interface to the virtual database engine
   13684 ** or VDBE.  The VDBE implements an abstract machine that runs a
   13685 ** simple program to access and modify the underlying database.
   13686 */
   13687 #ifndef SQLITE_VDBE_H
   13688 #define SQLITE_VDBE_H
   13689 /* #include <stdio.h> */
   13690 
   13691 /*
   13692 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
   13693 ** in the source file sqliteVdbe.c are allowed to see the insides
   13694 ** of this structure.
   13695 */
   13696 typedef struct Vdbe Vdbe;
   13697 
   13698 /*
   13699 ** The names of the following types declared in vdbeInt.h are required
   13700 ** for the VdbeOp definition.
   13701 */
   13702 typedef struct sqlite3_value Mem;
   13703 typedef struct SubProgram SubProgram;
   13704 
   13705 /*
   13706 ** A single instruction of the virtual machine has an opcode
   13707 ** and as many as three operands.  The instruction is recorded
   13708 ** as an instance of the following structure:
   13709 */
   13710 struct VdbeOp {
   13711   u8 opcode;          /* What operation to perform */
   13712   signed char p4type; /* One of the P4_xxx constants for p4 */
   13713   u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */
   13714   int p1;             /* First operand */
   13715   int p2;             /* Second parameter (often the jump destination) */
   13716   int p3;             /* The third parameter */
   13717   union p4union {     /* fourth parameter */
   13718     int i;                 /* Integer value if p4type==P4_INT32 */
   13719     void *p;               /* Generic pointer */
   13720     char *z;               /* Pointer to data for string (char array) types */
   13721     i64 *pI64;             /* Used when p4type is P4_INT64 */
   13722     double *pReal;         /* Used when p4type is P4_REAL */
   13723     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
   13724     sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
   13725     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
   13726     Mem *pMem;             /* Used when p4type is P4_MEM */
   13727     VTable *pVtab;         /* Used when p4type is P4_VTAB */
   13728     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
   13729     int *ai;               /* Used when p4type is P4_INTARRAY */
   13730     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
   13731     Table *pTab;           /* Used when p4type is P4_TABLE */
   13732 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   13733     Expr *pExpr;           /* Used when p4type is P4_EXPR */
   13734 #endif
   13735     int (*xAdvance)(BtCursor *, int);
   13736   } p4;
   13737 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   13738   char *zComment;          /* Comment to improve readability */
   13739 #endif
   13740 #ifdef VDBE_PROFILE
   13741   u32 cnt;                 /* Number of times this instruction was executed */
   13742   u64 cycles;              /* Total time spent executing this instruction */
   13743 #endif
   13744 #ifdef SQLITE_VDBE_COVERAGE
   13745   int iSrcLine;            /* Source-code line that generated this opcode */
   13746 #endif
   13747 };
   13748 typedef struct VdbeOp VdbeOp;
   13749 
   13750 
   13751 /*
   13752 ** A sub-routine used to implement a trigger program.
   13753 */
   13754 struct SubProgram {
   13755   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
   13756   int nOp;                      /* Elements in aOp[] */
   13757   int nMem;                     /* Number of memory cells required */
   13758   int nCsr;                     /* Number of cursors required */
   13759   u8 *aOnce;                    /* Array of OP_Once flags */
   13760   void *token;                  /* id that may be used to recursive triggers */
   13761   SubProgram *pNext;            /* Next sub-program already visited */
   13762 };
   13763 
   13764 /*
   13765 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
   13766 ** it takes up less space.
   13767 */
   13768 struct VdbeOpList {
   13769   u8 opcode;          /* What operation to perform */
   13770   signed char p1;     /* First operand */
   13771   signed char p2;     /* Second parameter (often the jump destination) */
   13772   signed char p3;     /* Third parameter */
   13773 };
   13774 typedef struct VdbeOpList VdbeOpList;
   13775 
   13776 /*
   13777 ** Allowed values of VdbeOp.p4type
   13778 */
   13779 #define P4_NOTUSED      0   /* The P4 parameter is not used */
   13780 #define P4_TRANSIENT    0   /* P4 is a pointer to a transient string */
   13781 #define P4_STATIC     (-1)  /* Pointer to a static string */
   13782 #define P4_COLLSEQ    (-2)  /* P4 is a pointer to a CollSeq structure */
   13783 #define P4_INT32      (-3)  /* P4 is a 32-bit signed integer */
   13784 #define P4_SUBPROGRAM (-4)  /* P4 is a pointer to a SubProgram structure */
   13785 #define P4_ADVANCE    (-5)  /* P4 is a pointer to BtreeNext() or BtreePrev() */
   13786 #define P4_TABLE      (-6)  /* P4 is a pointer to a Table structure */
   13787 /* Above do not own any resources.  Must free those below */
   13788 #define P4_FREE_IF_LE (-7)
   13789 #define P4_DYNAMIC    (-7)  /* Pointer to memory from sqliteMalloc() */
   13790 #define P4_FUNCDEF    (-8)  /* P4 is a pointer to a FuncDef structure */
   13791 #define P4_KEYINFO    (-9)  /* P4 is a pointer to a KeyInfo structure */
   13792 #define P4_EXPR       (-10) /* P4 is a pointer to an Expr tree */
   13793 #define P4_MEM        (-11) /* P4 is a pointer to a Mem*    structure */
   13794 #define P4_VTAB       (-12) /* P4 is a pointer to an sqlite3_vtab structure */
   13795 #define P4_REAL       (-13) /* P4 is a 64-bit floating point value */
   13796 #define P4_INT64      (-14) /* P4 is a 64-bit signed integer */
   13797 #define P4_INTARRAY   (-15) /* P4 is a vector of 32-bit integers */
   13798 #define P4_FUNCCTX    (-16) /* P4 is a pointer to an sqlite3_context object */
   13799 #define P4_DYNBLOB    (-17) /* Pointer to memory from sqliteMalloc() */
   13800 
   13801 /* Error message codes for OP_Halt */
   13802 #define P5_ConstraintNotNull 1
   13803 #define P5_ConstraintUnique  2
   13804 #define P5_ConstraintCheck   3
   13805 #define P5_ConstraintFK      4
   13806 
   13807 /*
   13808 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
   13809 ** number of columns of data returned by the statement.
   13810 */
   13811 #define COLNAME_NAME     0
   13812 #define COLNAME_DECLTYPE 1
   13813 #define COLNAME_DATABASE 2
   13814 #define COLNAME_TABLE    3
   13815 #define COLNAME_COLUMN   4
   13816 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   13817 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
   13818 #else
   13819 # ifdef SQLITE_OMIT_DECLTYPE
   13820 #   define COLNAME_N      1      /* Store only the name */
   13821 # else
   13822 #   define COLNAME_N      2      /* Store the name and decltype */
   13823 # endif
   13824 #endif
   13825 
   13826 /*
   13827 ** The following macro converts a relative address in the p2 field
   13828 ** of a VdbeOp structure into a negative number so that
   13829 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
   13830 ** the macro again restores the address.
   13831 */
   13832 #define ADDR(X)  (-1-(X))
   13833 
   13834 /*
   13835 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
   13836 ** header file that defines a number for each opcode used by the VDBE.
   13837 */
   13838 /************** Include opcodes.h in the middle of vdbe.h ********************/
   13839 /************** Begin file opcodes.h *****************************************/
   13840 /* Automatically generated.  Do not edit */
   13841 /* See the tool/mkopcodeh.tcl script for details */
   13842 #define OP_Savepoint       0
   13843 #define OP_AutoCommit      1
   13844 #define OP_Transaction     2
   13845 #define OP_SorterNext      3 /* jump                                       */
   13846 #define OP_PrevIfOpen      4 /* jump                                       */
   13847 #define OP_NextIfOpen      5 /* jump                                       */
   13848 #define OP_Prev            6 /* jump                                       */
   13849 #define OP_Next            7 /* jump                                       */
   13850 #define OP_Checkpoint      8
   13851 #define OP_JournalMode     9
   13852 #define OP_Vacuum         10
   13853 #define OP_VFilter        11 /* jump, synopsis: iplan=r[P3] zplan='P4'     */
   13854 #define OP_VUpdate        12 /* synopsis: data=r[P3@P2]                    */
   13855 #define OP_Goto           13 /* jump                                       */
   13856 #define OP_Gosub          14 /* jump                                       */
   13857 #define OP_InitCoroutine  15 /* jump                                       */
   13858 #define OP_Yield          16 /* jump                                       */
   13859 #define OP_MustBeInt      17 /* jump                                       */
   13860 #define OP_Jump           18 /* jump                                       */
   13861 #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
   13862 #define OP_Once           20 /* jump                                       */
   13863 #define OP_If             21 /* jump                                       */
   13864 #define OP_IfNot          22 /* jump                                       */
   13865 #define OP_IfNullRow      23 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
   13866 #define OP_SeekLT         24 /* jump, synopsis: key=r[P3@P4]               */
   13867 #define OP_SeekLE         25 /* jump, synopsis: key=r[P3@P4]               */
   13868 #define OP_SeekGE         26 /* jump, synopsis: key=r[P3@P4]               */
   13869 #define OP_SeekGT         27 /* jump, synopsis: key=r[P3@P4]               */
   13870 #define OP_NoConflict     28 /* jump, synopsis: key=r[P3@P4]               */
   13871 #define OP_NotFound       29 /* jump, synopsis: key=r[P3@P4]               */
   13872 #define OP_Found          30 /* jump, synopsis: key=r[P3@P4]               */
   13873 #define OP_SeekRowid      31 /* jump, synopsis: intkey=r[P3]               */
   13874 #define OP_NotExists      32 /* jump, synopsis: intkey=r[P3]               */
   13875 #define OP_Last           33 /* jump                                       */
   13876 #define OP_IfSmaller      34 /* jump                                       */
   13877 #define OP_SorterSort     35 /* jump                                       */
   13878 #define OP_Sort           36 /* jump                                       */
   13879 #define OP_Rewind         37 /* jump                                       */
   13880 #define OP_IdxLE          38 /* jump, synopsis: key=r[P3@P4]               */
   13881 #define OP_IdxGT          39 /* jump, synopsis: key=r[P3@P4]               */
   13882 #define OP_IdxLT          40 /* jump, synopsis: key=r[P3@P4]               */
   13883 #define OP_IdxGE          41 /* jump, synopsis: key=r[P3@P4]               */
   13884 #define OP_RowSetRead     42 /* jump, synopsis: r[P3]=rowset(P1)           */
   13885 #define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
   13886 #define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
   13887 #define OP_RowSetTest     45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
   13888 #define OP_Program        46 /* jump                                       */
   13889 #define OP_FkIfZero       47 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
   13890 #define OP_IfPos          48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
   13891 #define OP_IfNotZero      49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
   13892 #define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
   13893 #define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
   13894 #define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
   13895 #define OP_Eq             53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
   13896 #define OP_Gt             54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
   13897 #define OP_Le             55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
   13898 #define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
   13899 #define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
   13900 #define OP_ElseNotEq      58 /* jump, same as TK_ESCAPE                    */
   13901 #define OP_DecrJumpZero   59 /* jump, synopsis: if (--r[P1])==0 goto P2    */
   13902 #define OP_IncrVacuum     60 /* jump                                       */
   13903 #define OP_VNext          61 /* jump                                       */
   13904 #define OP_Init           62 /* jump, synopsis: Start at P2                */
   13905 #define OP_Return         63
   13906 #define OP_EndCoroutine   64
   13907 #define OP_HaltIfNull     65 /* synopsis: if r[P3]=null halt               */
   13908 #define OP_Halt           66
   13909 #define OP_Integer        67 /* synopsis: r[P2]=P1                         */
   13910 #define OP_Int64          68 /* synopsis: r[P2]=P4                         */
   13911 #define OP_String         69 /* synopsis: r[P2]='P4' (len=P1)              */
   13912 #define OP_Null           70 /* synopsis: r[P2..P3]=NULL                   */
   13913 #define OP_SoftNull       71 /* synopsis: r[P1]=NULL                       */
   13914 #define OP_Blob           72 /* synopsis: r[P2]=P4 (len=P1)                */
   13915 #define OP_Variable       73 /* synopsis: r[P2]=parameter(P1,P4)           */
   13916 #define OP_Move           74 /* synopsis: r[P2@P3]=r[P1@P3]                */
   13917 #define OP_Copy           75 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
   13918 #define OP_SCopy          76 /* synopsis: r[P2]=r[P1]                      */
   13919 #define OP_IntCopy        77 /* synopsis: r[P2]=r[P1]                      */
   13920 #define OP_ResultRow      78 /* synopsis: output=r[P1@P2]                  */
   13921 #define OP_CollSeq        79
   13922 #define OP_AddImm         80 /* synopsis: r[P1]=r[P1]+P2                   */
   13923 #define OP_RealAffinity   81
   13924 #define OP_Cast           82 /* synopsis: affinity(r[P1])                  */
   13925 #define OP_Permutation    83
   13926 #define OP_BitAnd         84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
   13927 #define OP_BitOr          85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
   13928 #define OP_ShiftLeft      86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
   13929 #define OP_ShiftRight     87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
   13930 #define OP_Add            88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
   13931 #define OP_Subtract       89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
   13932 #define OP_Multiply       90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
   13933 #define OP_Divide         91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
   13934 #define OP_Remainder      92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
   13935 #define OP_Concat         93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
   13936 #define OP_Compare        94 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
   13937 #define OP_BitNot         95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
   13938 #define OP_Offset         96 /* synopsis: r[P3] = sqlite_offset(P1)        */
   13939 #define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
   13940 #define OP_Column         98 /* synopsis: r[P3]=PX                         */
   13941 #define OP_Affinity       99 /* synopsis: affinity(r[P1@P2])               */
   13942 #define OP_MakeRecord    100 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
   13943 #define OP_Count         101 /* synopsis: r[P2]=count()                    */
   13944 #define OP_ReadCookie    102
   13945 #define OP_SetCookie     103
   13946 #define OP_ReopenIdx     104 /* synopsis: root=P2 iDb=P3                   */
   13947 #define OP_OpenRead      105 /* synopsis: root=P2 iDb=P3                   */
   13948 #define OP_OpenWrite     106 /* synopsis: root=P2 iDb=P3                   */
   13949 #define OP_OpenDup       107
   13950 #define OP_OpenAutoindex 108 /* synopsis: nColumn=P2                       */
   13951 #define OP_OpenEphemeral 109 /* synopsis: nColumn=P2                       */
   13952 #define OP_SorterOpen    110
   13953 #define OP_SequenceTest  111 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
   13954 #define OP_OpenPseudo    112 /* synopsis: P3 columns in r[P2]              */
   13955 #define OP_Close         113
   13956 #define OP_ColumnsUsed   114
   13957 #define OP_Sequence      115 /* synopsis: r[P2]=cursor[P1].ctr++           */
   13958 #define OP_NewRowid      116 /* synopsis: r[P2]=rowid                      */
   13959 #define OP_Insert        117 /* synopsis: intkey=r[P3] data=r[P2]          */
   13960 #define OP_InsertInt     118 /* synopsis: intkey=P3 data=r[P2]             */
   13961 #define OP_Delete        119
   13962 #define OP_ResetCount    120
   13963 #define OP_SorterCompare 121 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
   13964 #define OP_SorterData    122 /* synopsis: r[P2]=data                       */
   13965 #define OP_RowData       123 /* synopsis: r[P2]=data                       */
   13966 #define OP_Rowid         124 /* synopsis: r[P2]=rowid                      */
   13967 #define OP_NullRow       125
   13968 #define OP_SeekEnd       126
   13969 #define OP_SorterInsert  127 /* synopsis: key=r[P2]                        */
   13970 #define OP_IdxInsert     128 /* synopsis: key=r[P2]                        */
   13971 #define OP_IdxDelete     129 /* synopsis: key=r[P2@P3]                     */
   13972 #define OP_DeferredSeek  130 /* synopsis: Move P3 to P1.rowid if needed    */
   13973 #define OP_IdxRowid      131 /* synopsis: r[P2]=rowid                      */
   13974 #define OP_Real          132 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
   13975 #define OP_Destroy       133
   13976 #define OP_Clear         134
   13977 #define OP_ResetSorter   135
   13978 #define OP_CreateBtree   136 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
   13979 #define OP_SqlExec       137
   13980 #define OP_ParseSchema   138
   13981 #define OP_LoadAnalysis  139
   13982 #define OP_DropTable     140
   13983 #define OP_DropIndex     141
   13984 #define OP_DropTrigger   142
   13985 #define OP_IntegrityCk   143
   13986 #define OP_RowSetAdd     144 /* synopsis: rowset(P1)=r[P2]                 */
   13987 #define OP_Param         145
   13988 #define OP_FkCounter     146 /* synopsis: fkctr[P1]+=P2                    */
   13989 #define OP_MemMax        147 /* synopsis: r[P1]=max(r[P1],r[P2])           */
   13990 #define OP_OffsetLimit   148 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
   13991 #define OP_AggStep0      149 /* synopsis: accum=r[P3] step(r[P2@P5])       */
   13992 #define OP_AggStep       150 /* synopsis: accum=r[P3] step(r[P2@P5])       */
   13993 #define OP_AggFinal      151 /* synopsis: accum=r[P1] N=P2                 */
   13994 #define OP_Expire        152
   13995 #define OP_TableLock     153 /* synopsis: iDb=P1 root=P2 write=P3          */
   13996 #define OP_VBegin        154
   13997 #define OP_VCreate       155
   13998 #define OP_VDestroy      156
   13999 #define OP_VOpen         157
   14000 #define OP_VColumn       158 /* synopsis: r[P3]=vcolumn(P2)                */
   14001 #define OP_VRename       159
   14002 #define OP_Pagecount     160
   14003 #define OP_MaxPgcnt      161
   14004 #define OP_PureFunc0     162
   14005 #define OP_Function0     163 /* synopsis: r[P3]=func(r[P2@P5])             */
   14006 #define OP_PureFunc      164
   14007 #define OP_Function      165 /* synopsis: r[P3]=func(r[P2@P5])             */
   14008 #define OP_Trace         166
   14009 #define OP_CursorHint    167
   14010 #define OP_Noop          168
   14011 #define OP_Explain       169
   14012 
   14013 /* Properties such as "out2" or "jump" that are specified in
   14014 ** comments following the "case" for each opcode in the vdbe.c
   14015 ** are encoded into bitvectors as follows:
   14016 */
   14017 #define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
   14018 #define OPFLG_IN1         0x02  /* in1:   P1 is an input */
   14019 #define OPFLG_IN2         0x04  /* in2:   P2 is an input */
   14020 #define OPFLG_IN3         0x08  /* in3:   P3 is an input */
   14021 #define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
   14022 #define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
   14023 #define OPFLG_INITIALIZER {\
   14024 /*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
   14025 /*   8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
   14026 /*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
   14027 /*  24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
   14028 /*  32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
   14029 /*  40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
   14030 /*  48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
   14031 /*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x02,\
   14032 /*  64 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
   14033 /*  72 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
   14034 /*  80 */ 0x02, 0x02, 0x02, 0x00, 0x26, 0x26, 0x26, 0x26,\
   14035 /*  88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
   14036 /*  96 */ 0x20, 0x10, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
   14037 /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   14038 /* 112 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
   14039 /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x04,\
   14040 /* 128 */ 0x04, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00,\
   14041 /* 136 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   14042 /* 144 */ 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00,\
   14043 /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   14044 /* 160 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   14045 /* 168 */ 0x00, 0x00,}
   14046 
   14047 /* The sqlite3P2Values() routine is able to run faster if it knows
   14048 ** the value of the largest JUMP opcode.  The smaller the maximum
   14049 ** JUMP opcode the better, so the mkopcodeh.tcl script that
   14050 ** generated this include file strives to group all JUMP opcodes
   14051 ** together near the beginning of the list.
   14052 */
   14053 #define SQLITE_MX_JUMP_OPCODE  62  /* Maximum JUMP opcode */
   14054 
   14055 /************** End of opcodes.h *********************************************/
   14056 /************** Continuing where we left off in vdbe.h ***********************/
   14057 
   14058 /*
   14059 ** Additional non-public SQLITE_PREPARE_* flags
   14060 */
   14061 #define SQLITE_PREPARE_SAVESQL  0x80  /* Preserve SQL text */
   14062 #define SQLITE_PREPARE_MASK     0x0f  /* Mask of public flags */
   14063 
   14064 /*
   14065 ** Prototypes for the VDBE interface.  See comments on the implementation
   14066 ** for a description of what each of these routines does.
   14067 */
   14068 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
   14069 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
   14070 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
   14071 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
   14072 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
   14073 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
   14074 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
   14075 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
   14076 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
   14077 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
   14078 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
   14079 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
   14080 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
   14081 SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
   14082 SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
   14083 #else
   14084 # define sqlite3VdbeVerifyNoMallocRequired(A,B)
   14085 # define sqlite3VdbeVerifyNoResultRow(A)
   14086 #endif
   14087 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
   14088 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
   14089 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
   14090 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
   14091 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
   14092 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
   14093 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
   14094 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
   14095 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
   14096 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
   14097 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
   14098 SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
   14099 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
   14100 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
   14101 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   14102 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
   14103 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
   14104 SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
   14105 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
   14106 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
   14107 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
   14108 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
   14109 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
   14110 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
   14111 #ifdef SQLITE_DEBUG
   14112 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
   14113 #endif
   14114 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
   14115 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
   14116 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
   14117 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
   14118 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   14119 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
   14120 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
   14121 SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
   14122 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
   14123 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
   14124 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
   14125 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
   14126 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
   14127 #ifndef SQLITE_OMIT_TRACE
   14128 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   14129 #endif
   14130 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
   14131 
   14132 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
   14133 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
   14134 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
   14135 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
   14136 
   14137 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
   14138 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
   14139 
   14140 #ifndef SQLITE_OMIT_TRIGGER
   14141 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
   14142 #endif
   14143 
   14144 SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
   14145 
   14146 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
   14147 ** each VDBE opcode.
   14148 **
   14149 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
   14150 ** comments in VDBE programs that show key decision points in the code
   14151 ** generator.
   14152 */
   14153 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   14154 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
   14155 # define VdbeComment(X)  sqlite3VdbeComment X
   14156 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
   14157 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
   14158 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
   14159 #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
   14160 # else
   14161 #   define VdbeModuleComment(X)
   14162 # endif
   14163 #else
   14164 # define VdbeComment(X)
   14165 # define VdbeNoopComment(X)
   14166 # define VdbeModuleComment(X)
   14167 #endif
   14168 
   14169 /*
   14170 ** The VdbeCoverage macros are used to set a coverage testing point
   14171 ** for VDBE branch instructions.  The coverage testing points are line
   14172 ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
   14173 ** only works with an amalagmation build.  That's ok since a VDBE branch
   14174 ** coverage build designed for testing the test suite only.  No application
   14175 ** should ever ship with VDBE branch coverage measuring turned on.
   14176 **
   14177 **    VdbeCoverage(v)                  // Mark the previously coded instruction
   14178 **                                     // as a branch
   14179 **
   14180 **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
   14181 **
   14182 **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
   14183 **
   14184 **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
   14185 **
   14186 ** Every VDBE branch operation must be tagged with one of the macros above.
   14187 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
   14188 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
   14189 ** routine in vdbe.c, alerting the developer to the missed tag.
   14190 */
   14191 #ifdef SQLITE_VDBE_COVERAGE
   14192 SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
   14193 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
   14194 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
   14195 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
   14196 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
   14197 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
   14198 #else
   14199 # define VdbeCoverage(v)
   14200 # define VdbeCoverageIf(v,x)
   14201 # define VdbeCoverageAlwaysTaken(v)
   14202 # define VdbeCoverageNeverTaken(v)
   14203 # define VDBE_OFFSET_LINENO(x) 0
   14204 #endif
   14205 
   14206 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   14207 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
   14208 #else
   14209 # define sqlite3VdbeScanStatus(a,b,c,d,e)
   14210 #endif
   14211 
   14212 #endif /* SQLITE_VDBE_H */
   14213 
   14214 /************** End of vdbe.h ************************************************/
   14215 /************** Continuing where we left off in sqliteInt.h ******************/
   14216 /************** Include pager.h in the middle of sqliteInt.h *****************/
   14217 /************** Begin file pager.h *******************************************/
   14218 /*
   14219 ** 2001 September 15
   14220 **
   14221 ** The author disclaims copyright to this source code.  In place of
   14222 ** a legal notice, here is a blessing:
   14223 **
   14224 **    May you do good and not evil.
   14225 **    May you find forgiveness for yourself and forgive others.
   14226 **    May you share freely, never taking more than you give.
   14227 **
   14228 *************************************************************************
   14229 ** This header file defines the interface that the sqlite page cache
   14230 ** subsystem.  The page cache subsystem reads and writes a file a page
   14231 ** at a time and provides a journal for rollback.
   14232 */
   14233 
   14234 #ifndef SQLITE_PAGER_H
   14235 #define SQLITE_PAGER_H
   14236 
   14237 /*
   14238 ** Default maximum size for persistent journal files. A negative
   14239 ** value means no limit. This value may be overridden using the
   14240 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
   14241 */
   14242 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   14243   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
   14244 #endif
   14245 
   14246 /*
   14247 ** The type used to represent a page number.  The first page in a file
   14248 ** is called page 1.  0 is used to represent "not a page".
   14249 */
   14250 typedef u32 Pgno;
   14251 
   14252 /*
   14253 ** Each open file is managed by a separate instance of the "Pager" structure.
   14254 */
   14255 typedef struct Pager Pager;
   14256 
   14257 /*
   14258 ** Handle type for pages.
   14259 */
   14260 typedef struct PgHdr DbPage;
   14261 
   14262 /*
   14263 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
   14264 ** reserved for working around a windows/posix incompatibility). It is
   14265 ** used in the journal to signify that the remainder of the journal file
   14266 ** is devoted to storing a master journal name - there are no more pages to
   14267 ** roll back. See comments for function writeMasterJournal() in pager.c
   14268 ** for details.
   14269 */
   14270 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
   14271 
   14272 /*
   14273 ** Allowed values for the flags parameter to sqlite3PagerOpen().
   14274 **
   14275 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
   14276 */
   14277 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
   14278 #define PAGER_MEMORY        0x0002    /* In-memory database */
   14279 
   14280 /*
   14281 ** Valid values for the second argument to sqlite3PagerLockingMode().
   14282 */
   14283 #define PAGER_LOCKINGMODE_QUERY      -1
   14284 #define PAGER_LOCKINGMODE_NORMAL      0
   14285 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
   14286 
   14287 /*
   14288 ** Numeric constants that encode the journalmode.
   14289 **
   14290 ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
   14291 ** are exposed in the API via the "PRAGMA journal_mode" command and
   14292 ** therefore cannot be changed without a compatibility break.
   14293 */
   14294 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
   14295 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
   14296 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
   14297 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
   14298 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
   14299 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
   14300 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
   14301 
   14302 /*
   14303 ** Flags that make up the mask passed to sqlite3PagerGet().
   14304 */
   14305 #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
   14306 #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
   14307 
   14308 /*
   14309 ** Flags for sqlite3PagerSetFlags()
   14310 **
   14311 ** Value constraints (enforced via assert()):
   14312 **    PAGER_FULLFSYNC      == SQLITE_FullFSync
   14313 **    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
   14314 **    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
   14315 */
   14316 #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
   14317 #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
   14318 #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
   14319 #define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
   14320 #define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
   14321 #define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
   14322 #define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
   14323 #define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
   14324 #define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
   14325 
   14326 /*
   14327 ** The remainder of this file contains the declarations of the functions
   14328 ** that make up the Pager sub-system API. See source code comments for
   14329 ** a detailed description of each routine.
   14330 */
   14331 
   14332 /* Open and close a Pager connection. */
   14333 SQLITE_PRIVATE int sqlite3PagerOpen(
   14334   sqlite3_vfs*,
   14335   Pager **ppPager,
   14336   const char*,
   14337   int,
   14338   int,
   14339   int,
   14340   void(*)(DbPage*)
   14341 );
   14342 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
   14343 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
   14344 
   14345 /* Functions used to configure a Pager object. */
   14346 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
   14347 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
   14348 #ifdef SQLITE_HAS_CODEC
   14349 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
   14350 #endif
   14351 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
   14352 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
   14353 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
   14354 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
   14355 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
   14356 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
   14357 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
   14358 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
   14359 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
   14360 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
   14361 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
   14362 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
   14363 SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
   14364 
   14365 /* Functions used to obtain and release page references. */
   14366 SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
   14367 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
   14368 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
   14369 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
   14370 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
   14371 SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
   14372 
   14373 /* Operations on page references. */
   14374 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
   14375 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
   14376 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
   14377 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
   14378 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
   14379 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
   14380 
   14381 /* Functions used to manage pager transactions and savepoints. */
   14382 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
   14383 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
   14384 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
   14385 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
   14386 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
   14387 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
   14388 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
   14389 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
   14390 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
   14391 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
   14392 
   14393 #ifndef SQLITE_OMIT_WAL
   14394 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
   14395 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
   14396 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
   14397 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
   14398 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
   14399 # ifdef SQLITE_DIRECT_OVERFLOW_READ
   14400 SQLITE_PRIVATE   int sqlite3PagerUseWal(Pager *pPager, Pgno);
   14401 # endif
   14402 # ifdef SQLITE_ENABLE_SNAPSHOT
   14403 SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
   14404 SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
   14405 SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
   14406 # endif
   14407 #else
   14408 # define sqlite3PagerUseWal(x,y) 0
   14409 #endif
   14410 
   14411 #ifdef SQLITE_ENABLE_ZIPVFS
   14412 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
   14413 #endif
   14414 
   14415 /* Functions used to query pager state and configuration. */
   14416 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
   14417 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
   14418 #ifdef SQLITE_DEBUG
   14419 SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
   14420 #endif
   14421 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
   14422 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
   14423 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
   14424 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
   14425 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
   14426 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
   14427 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
   14428 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
   14429 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
   14430 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
   14431 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
   14432 
   14433 /* Functions used to truncate the database file. */
   14434 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
   14435 
   14436 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
   14437 
   14438 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
   14439 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
   14440 #endif
   14441 
   14442 /* Functions to support testing and debugging. */
   14443 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   14444 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
   14445 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
   14446 #endif
   14447 #ifdef SQLITE_TEST
   14448 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
   14449 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
   14450   void disable_simulated_io_errors(void);
   14451   void enable_simulated_io_errors(void);
   14452 #else
   14453 # define disable_simulated_io_errors()
   14454 # define enable_simulated_io_errors()
   14455 #endif
   14456 
   14457 #endif /* SQLITE_PAGER_H */
   14458 
   14459 /************** End of pager.h ***********************************************/
   14460 /************** Continuing where we left off in sqliteInt.h ******************/
   14461 /************** Include pcache.h in the middle of sqliteInt.h ****************/
   14462 /************** Begin file pcache.h ******************************************/
   14463 /*
   14464 ** 2008 August 05
   14465 **
   14466 ** The author disclaims copyright to this source code.  In place of
   14467 ** a legal notice, here is a blessing:
   14468 **
   14469 **    May you do good and not evil.
   14470 **    May you find forgiveness for yourself and forgive others.
   14471 **    May you share freely, never taking more than you give.
   14472 **
   14473 *************************************************************************
   14474 ** This header file defines the interface that the sqlite page cache
   14475 ** subsystem.
   14476 */
   14477 
   14478 #ifndef _PCACHE_H_
   14479 
   14480 typedef struct PgHdr PgHdr;
   14481 typedef struct PCache PCache;
   14482 
   14483 /*
   14484 ** Every page in the cache is controlled by an instance of the following
   14485 ** structure.
   14486 */
   14487 struct PgHdr {
   14488   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
   14489   void *pData;                   /* Page data */
   14490   void *pExtra;                  /* Extra content */
   14491   PCache *pCache;                /* PRIVATE: Cache that owns this page */
   14492   PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
   14493   Pager *pPager;                 /* The pager this page is part of */
   14494   Pgno pgno;                     /* Page number for this page */
   14495 #ifdef SQLITE_CHECK_PAGES
   14496   u32 pageHash;                  /* Hash of page content */
   14497 #endif
   14498   u16 flags;                     /* PGHDR flags defined below */
   14499 
   14500   /**********************************************************************
   14501   ** Elements above, except pCache, are public.  All that follow are
   14502   ** private to pcache.c and should not be accessed by other modules.
   14503   ** pCache is grouped with the public elements for efficiency.
   14504   */
   14505   i16 nRef;                      /* Number of users of this page */
   14506   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
   14507   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
   14508                           /* NB: pDirtyNext and pDirtyPrev are undefined if the
   14509                           ** PgHdr object is not dirty */
   14510 };
   14511 
   14512 /* Bit values for PgHdr.flags */
   14513 #define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
   14514 #define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
   14515 #define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
   14516 #define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
   14517                                      ** writing this page to the database */
   14518 #define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
   14519 #define PGHDR_MMAP            0x020  /* This is an mmap page object */
   14520 
   14521 #define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
   14522 
   14523 /* Initialize and shutdown the page cache subsystem */
   14524 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
   14525 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
   14526 
   14527 /* Page cache buffer management:
   14528 ** These routines implement SQLITE_CONFIG_PAGECACHE.
   14529 */
   14530 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
   14531 
   14532 /* Create a new pager cache.
   14533 ** Under memory stress, invoke xStress to try to make pages clean.
   14534 ** Only clean and unpinned pages can be reclaimed.
   14535 */
   14536 SQLITE_PRIVATE int sqlite3PcacheOpen(
   14537   int szPage,                    /* Size of every page */
   14538   int szExtra,                   /* Extra space associated with each page */
   14539   int bPurgeable,                /* True if pages are on backing store */
   14540   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
   14541   void *pStress,                 /* Argument to xStress */
   14542   PCache *pToInit                /* Preallocated space for the PCache */
   14543 );
   14544 
   14545 /* Modify the page-size after the cache has been created. */
   14546 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
   14547 
   14548 /* Return the size in bytes of a PCache object.  Used to preallocate
   14549 ** storage space.
   14550 */
   14551 SQLITE_PRIVATE int sqlite3PcacheSize(void);
   14552 
   14553 /* One release per successful fetch.  Page is pinned until released.
   14554 ** Reference counted.
   14555 */
   14556 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
   14557 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
   14558 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
   14559 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
   14560 
   14561 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
   14562 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
   14563 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
   14564 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
   14565 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
   14566 
   14567 /* Change a page number.  Used by incr-vacuum. */
   14568 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
   14569 
   14570 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
   14571 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
   14572 
   14573 /* Get a list of all dirty pages in the cache, sorted by page number */
   14574 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
   14575 
   14576 /* Reset and close the cache object */
   14577 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
   14578 
   14579 /* Clear flags from pages of the page cache */
   14580 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
   14581 
   14582 /* Discard the contents of the cache */
   14583 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
   14584 
   14585 /* Return the total number of outstanding page references */
   14586 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
   14587 
   14588 /* Increment the reference count of an existing page */
   14589 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
   14590 
   14591 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
   14592 
   14593 /* Return the total number of pages stored in the cache */
   14594 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
   14595 
   14596 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   14597 /* Iterate through all dirty pages currently stored in the cache. This
   14598 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
   14599 ** library is built.
   14600 */
   14601 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
   14602 #endif
   14603 
   14604 #if defined(SQLITE_DEBUG)
   14605 /* Check invariants on a PgHdr object */
   14606 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
   14607 #endif
   14608 
   14609 /* Set and get the suggested cache-size for the specified pager-cache.
   14610 **
   14611 ** If no global maximum is configured, then the system attempts to limit
   14612 ** the total number of pages cached by purgeable pager-caches to the sum
   14613 ** of the suggested cache-sizes.
   14614 */
   14615 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
   14616 #ifdef SQLITE_TEST
   14617 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
   14618 #endif
   14619 
   14620 /* Set or get the suggested spill-size for the specified pager-cache.
   14621 **
   14622 ** The spill-size is the minimum number of pages in cache before the cache
   14623 ** will attempt to spill dirty pages by calling xStress.
   14624 */
   14625 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
   14626 
   14627 /* Free up as much memory as possible from the page cache */
   14628 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
   14629 
   14630 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   14631 /* Try to return memory used by the pcache module to the main memory heap */
   14632 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
   14633 #endif
   14634 
   14635 #ifdef SQLITE_TEST
   14636 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
   14637 #endif
   14638 
   14639 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
   14640 
   14641 /* Return the header size */
   14642 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
   14643 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
   14644 
   14645 /* Number of dirty pages as a percentage of the configured cache size */
   14646 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
   14647 
   14648 #endif /* _PCACHE_H_ */
   14649 
   14650 /************** End of pcache.h **********************************************/
   14651 /************** Continuing where we left off in sqliteInt.h ******************/
   14652 /************** Include os.h in the middle of sqliteInt.h ********************/
   14653 /************** Begin file os.h **********************************************/
   14654 /*
   14655 ** 2001 September 16
   14656 **
   14657 ** The author disclaims copyright to this source code.  In place of
   14658 ** a legal notice, here is a blessing:
   14659 **
   14660 **    May you do good and not evil.
   14661 **    May you find forgiveness for yourself and forgive others.
   14662 **    May you share freely, never taking more than you give.
   14663 **
   14664 ******************************************************************************
   14665 **
   14666 ** This header file (together with is companion C source-code file
   14667 ** "os.c") attempt to abstract the underlying operating system so that
   14668 ** the SQLite library will work on both POSIX and windows systems.
   14669 **
   14670 ** This header file is #include-ed by sqliteInt.h and thus ends up
   14671 ** being included by every source file.
   14672 */
   14673 #ifndef _SQLITE_OS_H_
   14674 #define _SQLITE_OS_H_
   14675 
   14676 /*
   14677 ** Attempt to automatically detect the operating system and setup the
   14678 ** necessary pre-processor macros for it.
   14679 */
   14680 /************** Include os_setup.h in the middle of os.h *********************/
   14681 /************** Begin file os_setup.h ****************************************/
   14682 /*
   14683 ** 2013 November 25
   14684 **
   14685 ** The author disclaims copyright to this source code.  In place of
   14686 ** a legal notice, here is a blessing:
   14687 **
   14688 **    May you do good and not evil.
   14689 **    May you find forgiveness for yourself and forgive others.
   14690 **    May you share freely, never taking more than you give.
   14691 **
   14692 ******************************************************************************
   14693 **
   14694 ** This file contains pre-processor directives related to operating system
   14695 ** detection and/or setup.
   14696 */
   14697 #ifndef SQLITE_OS_SETUP_H
   14698 #define SQLITE_OS_SETUP_H
   14699 
   14700 /*
   14701 ** Figure out if we are dealing with Unix, Windows, or some other operating
   14702 ** system.
   14703 **
   14704 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
   14705 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
   14706 ** the three will be 1.  The other two will be 0.
   14707 */
   14708 #if defined(SQLITE_OS_OTHER)
   14709 #  if SQLITE_OS_OTHER==1
   14710 #    undef SQLITE_OS_UNIX
   14711 #    define SQLITE_OS_UNIX 0
   14712 #    undef SQLITE_OS_WIN
   14713 #    define SQLITE_OS_WIN 0
   14714 #  else
   14715 #    undef SQLITE_OS_OTHER
   14716 #  endif
   14717 #endif
   14718 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
   14719 #  define SQLITE_OS_OTHER 0
   14720 #  ifndef SQLITE_OS_WIN
   14721 #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
   14722         defined(__MINGW32__) || defined(__BORLANDC__)
   14723 #      define SQLITE_OS_WIN 1
   14724 #      define SQLITE_OS_UNIX 0
   14725 #    else
   14726 #      define SQLITE_OS_WIN 0
   14727 #      define SQLITE_OS_UNIX 1
   14728 #    endif
   14729 #  else
   14730 #    define SQLITE_OS_UNIX 0
   14731 #  endif
   14732 #else
   14733 #  ifndef SQLITE_OS_WIN
   14734 #    define SQLITE_OS_WIN 0
   14735 #  endif
   14736 #endif
   14737 
   14738 #endif /* SQLITE_OS_SETUP_H */
   14739 
   14740 /************** End of os_setup.h ********************************************/
   14741 /************** Continuing where we left off in os.h *************************/
   14742 
   14743 /* If the SET_FULLSYNC macro is not defined above, then make it
   14744 ** a no-op
   14745 */
   14746 #ifndef SET_FULLSYNC
   14747 # define SET_FULLSYNC(x,y)
   14748 #endif
   14749 
   14750 /*
   14751 ** The default size of a disk sector
   14752 */
   14753 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
   14754 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
   14755 #endif
   14756 
   14757 /*
   14758 ** Temporary files are named starting with this prefix followed by 16 random
   14759 ** alphanumeric characters, and no file extension. They are stored in the
   14760 ** OS's standard temporary file directory, and are deleted prior to exit.
   14761 ** If sqlite is being embedded in another program, you may wish to change the
   14762 ** prefix to reflect your program's name, so that if your program exits
   14763 ** prematurely, old temporary files can be easily identified. This can be done
   14764 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
   14765 **
   14766 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
   14767 ** Mcafee started using SQLite in their anti-virus product and it
   14768 ** started putting files with the "sqlite" name in the c:/temp folder.
   14769 ** This annoyed many windows users.  Those users would then do a
   14770 ** Google search for "sqlite", find the telephone numbers of the
   14771 ** developers and call to wake them up at night and complain.
   14772 ** For this reason, the default name prefix is changed to be "sqlite"
   14773 ** spelled backwards.  So the temp files are still identified, but
   14774 ** anybody smart enough to figure out the code is also likely smart
   14775 ** enough to know that calling the developer will not help get rid
   14776 ** of the file.
   14777 */
   14778 #ifndef SQLITE_TEMP_FILE_PREFIX
   14779 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
   14780 #endif
   14781 
   14782 /*
   14783 ** The following values may be passed as the second argument to
   14784 ** sqlite3OsLock(). The various locks exhibit the following semantics:
   14785 **
   14786 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
   14787 ** RESERVED:  A single process may hold a RESERVED lock on a file at
   14788 **            any time. Other processes may hold and obtain new SHARED locks.
   14789 ** PENDING:   A single process may hold a PENDING lock on a file at
   14790 **            any one time. Existing SHARED locks may persist, but no new
   14791 **            SHARED locks may be obtained by other processes.
   14792 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
   14793 **
   14794 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
   14795 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
   14796 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
   14797 ** sqlite3OsLock().
   14798 */
   14799 #define NO_LOCK         0
   14800 #define SHARED_LOCK     1
   14801 #define RESERVED_LOCK   2
   14802 #define PENDING_LOCK    3
   14803 #define EXCLUSIVE_LOCK  4
   14804 
   14805 /*
   14806 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
   14807 **
   14808 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
   14809 ** those functions are not available.  So we use only LockFile() and
   14810 ** UnlockFile().
   14811 **
   14812 ** LockFile() prevents not just writing but also reading by other processes.
   14813 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
   14814 ** byte out of a specific range of bytes. The lock byte is obtained at
   14815 ** random so two separate readers can probably access the file at the
   14816 ** same time, unless they are unlucky and choose the same lock byte.
   14817 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
   14818 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
   14819 ** a single byte of the file that is designated as the reserved lock byte.
   14820 ** A PENDING_LOCK is obtained by locking a designated byte different from
   14821 ** the RESERVED_LOCK byte.
   14822 **
   14823 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
   14824 ** which means we can use reader/writer locks.  When reader/writer locks
   14825 ** are used, the lock is placed on the same range of bytes that is used
   14826 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
   14827 ** will support two or more Win95 readers or two or more WinNT readers.
   14828 ** But a single Win95 reader will lock out all WinNT readers and a single
   14829 ** WinNT reader will lock out all other Win95 readers.
   14830 **
   14831 ** The following #defines specify the range of bytes used for locking.
   14832 ** SHARED_SIZE is the number of bytes available in the pool from which
   14833 ** a random byte is selected for a shared lock.  The pool of bytes for
   14834 ** shared locks begins at SHARED_FIRST.
   14835 **
   14836 ** The same locking strategy and
   14837 ** byte ranges are used for Unix.  This leaves open the possibility of having
   14838 ** clients on win95, winNT, and unix all talking to the same shared file
   14839 ** and all locking correctly.  To do so would require that samba (or whatever
   14840 ** tool is being used for file sharing) implements locks correctly between
   14841 ** windows and unix.  I'm guessing that isn't likely to happen, but by
   14842 ** using the same locking range we are at least open to the possibility.
   14843 **
   14844 ** Locking in windows is manditory.  For this reason, we cannot store
   14845 ** actual data in the bytes used for locking.  The pager never allocates
   14846 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
   14847 ** that all locks will fit on a single page even at the minimum page size.
   14848 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
   14849 ** is set high so that we don't have to allocate an unused page except
   14850 ** for very large databases.  But one should test the page skipping logic
   14851 ** by setting PENDING_BYTE low and running the entire regression suite.
   14852 **
   14853 ** Changing the value of PENDING_BYTE results in a subtly incompatible
   14854 ** file format.  Depending on how it is changed, you might not notice
   14855 ** the incompatibility right away, even running a full regression test.
   14856 ** The default location of PENDING_BYTE is the first byte past the
   14857 ** 1GB boundary.
   14858 **
   14859 */
   14860 #ifdef SQLITE_OMIT_WSD
   14861 # define PENDING_BYTE     (0x40000000)
   14862 #else
   14863 # define PENDING_BYTE      sqlite3PendingByte
   14864 #endif
   14865 #define RESERVED_BYTE     (PENDING_BYTE+1)
   14866 #define SHARED_FIRST      (PENDING_BYTE+2)
   14867 #define SHARED_SIZE       510
   14868 
   14869 /*
   14870 ** Wrapper around OS specific sqlite3_os_init() function.
   14871 */
   14872 SQLITE_PRIVATE int sqlite3OsInit(void);
   14873 
   14874 /*
   14875 ** Functions for accessing sqlite3_file methods
   14876 */
   14877 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
   14878 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
   14879 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
   14880 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
   14881 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
   14882 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
   14883 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
   14884 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
   14885 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
   14886 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
   14887 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
   14888 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
   14889 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
   14890 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
   14891 #ifndef SQLITE_OMIT_WAL
   14892 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
   14893 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
   14894 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
   14895 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
   14896 #endif /* SQLITE_OMIT_WAL */
   14897 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
   14898 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
   14899 
   14900 
   14901 /*
   14902 ** Functions for accessing sqlite3_vfs methods
   14903 */
   14904 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
   14905 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
   14906 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
   14907 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
   14908 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   14909 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
   14910 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
   14911 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
   14912 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
   14913 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   14914 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
   14915 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
   14916 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
   14917 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
   14918 
   14919 /*
   14920 ** Convenience functions for opening and closing files using
   14921 ** sqlite3_malloc() to obtain space for the file-handle structure.
   14922 */
   14923 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
   14924 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
   14925 
   14926 #endif /* _SQLITE_OS_H_ */
   14927 
   14928 /************** End of os.h **************************************************/
   14929 /************** Continuing where we left off in sqliteInt.h ******************/
   14930 /************** Include mutex.h in the middle of sqliteInt.h *****************/
   14931 /************** Begin file mutex.h *******************************************/
   14932 /*
   14933 ** 2007 August 28
   14934 **
   14935 ** The author disclaims copyright to this source code.  In place of
   14936 ** a legal notice, here is a blessing:
   14937 **
   14938 **    May you do good and not evil.
   14939 **    May you find forgiveness for yourself and forgive others.
   14940 **    May you share freely, never taking more than you give.
   14941 **
   14942 *************************************************************************
   14943 **
   14944 ** This file contains the common header for all mutex implementations.
   14945 ** The sqliteInt.h header #includes this file so that it is available
   14946 ** to all source files.  We break it out in an effort to keep the code
   14947 ** better organized.
   14948 **
   14949 ** NOTE:  source files should *not* #include this header file directly.
   14950 ** Source files should #include the sqliteInt.h file and let that file
   14951 ** include this one indirectly.
   14952 */
   14953 
   14954 
   14955 /*
   14956 ** Figure out what version of the code to use.  The choices are
   14957 **
   14958 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
   14959 **                             mutexes implementation cannot be overridden
   14960 **                             at start-time.
   14961 **
   14962 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
   14963 **                             mutual exclusion is provided.  But this
   14964 **                             implementation can be overridden at
   14965 **                             start-time.
   14966 **
   14967 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
   14968 **
   14969 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
   14970 */
   14971 #if !SQLITE_THREADSAFE
   14972 # define SQLITE_MUTEX_OMIT
   14973 #endif
   14974 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
   14975 #  if SQLITE_OS_UNIX
   14976 #    define SQLITE_MUTEX_PTHREADS
   14977 #  elif SQLITE_OS_WIN
   14978 #    define SQLITE_MUTEX_W32
   14979 #  else
   14980 #    define SQLITE_MUTEX_NOOP
   14981 #  endif
   14982 #endif
   14983 
   14984 #ifdef SQLITE_MUTEX_OMIT
   14985 /*
   14986 ** If this is a no-op implementation, implement everything as macros.
   14987 */
   14988 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
   14989 #define sqlite3_mutex_free(X)
   14990 #define sqlite3_mutex_enter(X)
   14991 #define sqlite3_mutex_try(X)      SQLITE_OK
   14992 #define sqlite3_mutex_leave(X)
   14993 #define sqlite3_mutex_held(X)     ((void)(X),1)
   14994 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
   14995 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
   14996 #define sqlite3MutexInit()        SQLITE_OK
   14997 #define sqlite3MutexEnd()
   14998 #define MUTEX_LOGIC(X)
   14999 #else
   15000 #define MUTEX_LOGIC(X)            X
   15001 #endif /* defined(SQLITE_MUTEX_OMIT) */
   15002 
   15003 /************** End of mutex.h ***********************************************/
   15004 /************** Continuing where we left off in sqliteInt.h ******************/
   15005 
   15006 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
   15007 ** synchronous setting to EXTRA.  It is no longer supported.
   15008 */
   15009 #ifdef SQLITE_EXTRA_DURABLE
   15010 # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
   15011 # define SQLITE_DEFAULT_SYNCHRONOUS 3
   15012 #endif
   15013 
   15014 /*
   15015 ** Default synchronous levels.
   15016 **
   15017 ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
   15018 ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
   15019 **
   15020 **           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
   15021 **   OFF           1                         0
   15022 **   NORMAL        2                         1
   15023 **   FULL          3                         2
   15024 **   EXTRA         4                         3
   15025 **
   15026 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
   15027 ** In other words, the zero-based numbers are used for all external interfaces
   15028 ** and the one-based values are used internally.
   15029 */
   15030 #ifndef SQLITE_DEFAULT_SYNCHRONOUS
   15031 # define SQLITE_DEFAULT_SYNCHRONOUS 2
   15032 #endif
   15033 #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
   15034 # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
   15035 #endif
   15036 
   15037 /*
   15038 ** Each database file to be accessed by the system is an instance
   15039 ** of the following structure.  There are normally two of these structures
   15040 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
   15041 ** aDb[1] is the database file used to hold temporary tables.  Additional
   15042 ** databases may be attached.
   15043 */
   15044 struct Db {
   15045   char *zDbSName;      /* Name of this database. (schema name, not filename) */
   15046   Btree *pBt;          /* The B*Tree structure for this database file */
   15047   u8 safety_level;     /* How aggressive at syncing data to disk */
   15048   u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
   15049   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
   15050 };
   15051 
   15052 /*
   15053 ** An instance of the following structure stores a database schema.
   15054 **
   15055 ** Most Schema objects are associated with a Btree.  The exception is
   15056 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
   15057 ** In shared cache mode, a single Schema object can be shared by multiple
   15058 ** Btrees that refer to the same underlying BtShared object.
   15059 **
   15060 ** Schema objects are automatically deallocated when the last Btree that
   15061 ** references them is destroyed.   The TEMP Schema is manually freed by
   15062 ** sqlite3_close().
   15063 *
   15064 ** A thread must be holding a mutex on the corresponding Btree in order
   15065 ** to access Schema content.  This implies that the thread must also be
   15066 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
   15067 ** For a TEMP Schema, only the connection mutex is required.
   15068 */
   15069 struct Schema {
   15070   int schema_cookie;   /* Database schema version number for this file */
   15071   int iGeneration;     /* Generation counter.  Incremented with each change */
   15072   Hash tblHash;        /* All tables indexed by name */
   15073   Hash idxHash;        /* All (named) indices indexed by name */
   15074   Hash trigHash;       /* All triggers indexed by name */
   15075   Hash fkeyHash;       /* All foreign keys by referenced table name */
   15076   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
   15077   u8 file_format;      /* Schema format version for this file */
   15078   u8 enc;              /* Text encoding used by this database */
   15079   u16 schemaFlags;     /* Flags associated with this schema */
   15080   int cache_size;      /* Number of pages to use in the cache */
   15081 };
   15082 
   15083 /*
   15084 ** These macros can be used to test, set, or clear bits in the
   15085 ** Db.pSchema->flags field.
   15086 */
   15087 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
   15088 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
   15089 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
   15090 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
   15091 
   15092 /*
   15093 ** Allowed values for the DB.pSchema->flags field.
   15094 **
   15095 ** The DB_SchemaLoaded flag is set after the database schema has been
   15096 ** read into internal hash tables.
   15097 **
   15098 ** DB_UnresetViews means that one or more views have column names that
   15099 ** have been filled out.  If the schema changes, these column names might
   15100 ** changes and so the view will need to be reset.
   15101 */
   15102 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
   15103 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
   15104 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
   15105 #define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */
   15106 
   15107 /*
   15108 ** The number of different kinds of things that can be limited
   15109 ** using the sqlite3_limit() interface.
   15110 */
   15111 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
   15112 
   15113 /*
   15114 ** Lookaside malloc is a set of fixed-size buffers that can be used
   15115 ** to satisfy small transient memory allocation requests for objects
   15116 ** associated with a particular database connection.  The use of
   15117 ** lookaside malloc provides a significant performance enhancement
   15118 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
   15119 ** SQL statements.
   15120 **
   15121 ** The Lookaside structure holds configuration information about the
   15122 ** lookaside malloc subsystem.  Each available memory allocation in
   15123 ** the lookaside subsystem is stored on a linked list of LookasideSlot
   15124 ** objects.
   15125 **
   15126 ** Lookaside allocations are only allowed for objects that are associated
   15127 ** with a particular database connection.  Hence, schema information cannot
   15128 ** be stored in lookaside because in shared cache mode the schema information
   15129 ** is shared by multiple database connections.  Therefore, while parsing
   15130 ** schema information, the Lookaside.bEnabled flag is cleared so that
   15131 ** lookaside allocations are not used to construct the schema objects.
   15132 */
   15133 struct Lookaside {
   15134   u32 bDisable;           /* Only operate the lookaside when zero */
   15135   u16 sz;                 /* Size of each buffer in bytes */
   15136   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
   15137   u32 nSlot;              /* Number of lookaside slots allocated */
   15138   u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
   15139   LookasideSlot *pInit;   /* List of buffers not previously used */
   15140   LookasideSlot *pFree;   /* List of available buffers */
   15141   void *pStart;           /* First byte of available memory space */
   15142   void *pEnd;             /* First byte past end of available space */
   15143 };
   15144 struct LookasideSlot {
   15145   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
   15146 };
   15147 
   15148 /*
   15149 ** A hash table for built-in function definitions.  (Application-defined
   15150 ** functions use a regular table table from hash.h.)
   15151 **
   15152 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
   15153 ** Collisions are on the FuncDef.u.pHash chain.
   15154 */
   15155 #define SQLITE_FUNC_HASH_SZ 23
   15156 struct FuncDefHash {
   15157   FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
   15158 };
   15159 
   15160 #ifdef SQLITE_USER_AUTHENTICATION
   15161 /*
   15162 ** Information held in the "sqlite3" database connection object and used
   15163 ** to manage user authentication.
   15164 */
   15165 typedef struct sqlite3_userauth sqlite3_userauth;
   15166 struct sqlite3_userauth {
   15167   u8 authLevel;                 /* Current authentication level */
   15168   int nAuthPW;                  /* Size of the zAuthPW in bytes */
   15169   char *zAuthPW;                /* Password used to authenticate */
   15170   char *zAuthUser;              /* User name used to authenticate */
   15171 };
   15172 
   15173 /* Allowed values for sqlite3_userauth.authLevel */
   15174 #define UAUTH_Unknown     0     /* Authentication not yet checked */
   15175 #define UAUTH_Fail        1     /* User authentication failed */
   15176 #define UAUTH_User        2     /* Authenticated as a normal user */
   15177 #define UAUTH_Admin       3     /* Authenticated as an administrator */
   15178 
   15179 /* Functions used only by user authorization logic */
   15180 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
   15181 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
   15182 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
   15183 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
   15184 
   15185 #endif /* SQLITE_USER_AUTHENTICATION */
   15186 
   15187 /*
   15188 ** typedef for the authorization callback function.
   15189 */
   15190 #ifdef SQLITE_USER_AUTHENTICATION
   15191   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
   15192                                const char*, const char*);
   15193 #else
   15194   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
   15195                                const char*);
   15196 #endif
   15197 
   15198 #ifndef SQLITE_OMIT_DEPRECATED
   15199 /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
   15200 ** in the style of sqlite3_trace()
   15201 */
   15202 #define SQLITE_TRACE_LEGACY  0x80
   15203 #else
   15204 #define SQLITE_TRACE_LEGACY  0
   15205 #endif /* SQLITE_OMIT_DEPRECATED */
   15206 
   15207 
   15208 /*
   15209 ** Each database connection is an instance of the following structure.
   15210 */
   15211 struct sqlite3 {
   15212   sqlite3_vfs *pVfs;            /* OS Interface */
   15213   struct Vdbe *pVdbe;           /* List of active virtual machines */
   15214   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
   15215   sqlite3_mutex *mutex;         /* Connection mutex */
   15216   Db *aDb;                      /* All backends */
   15217   int nDb;                      /* Number of backends currently in use */
   15218   u32 mDbFlags;                 /* flags recording internal state */
   15219   u32 flags;                    /* flags settable by pragmas. See below */
   15220   i64 lastRowid;                /* ROWID of most recent insert (see above) */
   15221   i64 szMmap;                   /* Default mmap_size setting */
   15222   u32 nSchemaLock;              /* Do not reset the schema when non-zero */
   15223   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
   15224   int errCode;                  /* Most recent error code (SQLITE_*) */
   15225   int errMask;                  /* & result codes with this before returning */
   15226   int iSysErrno;                /* Errno value from last system error */
   15227   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
   15228   u8 enc;                       /* Text encoding */
   15229   u8 autoCommit;                /* The auto-commit flag. */
   15230   u8 temp_store;                /* 1: file 2: memory 0: default */
   15231   u8 mallocFailed;              /* True if we have seen a malloc failure */
   15232   u8 bBenignMalloc;             /* Do not require OOMs if true */
   15233   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
   15234   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
   15235   u8 suppressErr;               /* Do not issue error messages if true */
   15236   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
   15237   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
   15238   u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
   15239   u8 skipBtreeMutex;            /* True if no shared-cache backends */
   15240   u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
   15241   int nextPagesize;             /* Pagesize after VACUUM if >0 */
   15242   u32 magic;                    /* Magic number for detect library misuse */
   15243   int nChange;                  /* Value returned by sqlite3_changes() */
   15244   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
   15245   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   15246   int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
   15247   struct sqlite3InitInfo {      /* Information used during initialization */
   15248     int newTnum;                /* Rootpage of table being initialized */
   15249     u8 iDb;                     /* Which db file is being initialized */
   15250     u8 busy;                    /* TRUE if currently initializing */
   15251     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
   15252     u8 imposterTable;           /* Building an imposter table */
   15253   } init;
   15254   int nVdbeActive;              /* Number of VDBEs currently running */
   15255   int nVdbeRead;                /* Number of active VDBEs that read or write */
   15256   int nVdbeWrite;               /* Number of active VDBEs that read and write */
   15257   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
   15258   int nVDestroy;                /* Number of active OP_VDestroy operations */
   15259   int nExtension;               /* Number of loaded extensions */
   15260   void **aExtension;            /* Array of shared library handles */
   15261   int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
   15262   void *pTraceArg;                          /* Argument to the trace function */
   15263   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
   15264   void *pProfileArg;                        /* Argument to profile function */
   15265   void *pCommitArg;                 /* Argument to xCommitCallback() */
   15266   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
   15267   void *pRollbackArg;               /* Argument to xRollbackCallback() */
   15268   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
   15269   void *pUpdateArg;
   15270   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
   15271 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   15272   void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
   15273   void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
   15274     void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
   15275   );
   15276   PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
   15277 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   15278 #ifndef SQLITE_OMIT_WAL
   15279   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
   15280   void *pWalArg;
   15281 #endif
   15282   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
   15283   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
   15284   void *pCollNeededArg;
   15285   sqlite3_value *pErr;          /* Most recent error message */
   15286   union {
   15287     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
   15288     double notUsed1;            /* Spacer */
   15289   } u1;
   15290   Lookaside lookaside;          /* Lookaside malloc configuration */
   15291 #ifndef SQLITE_OMIT_AUTHORIZATION
   15292   sqlite3_xauth xAuth;          /* Access authorization function */
   15293   void *pAuthArg;               /* 1st argument to the access auth function */
   15294 #endif
   15295 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   15296   int (*xProgress)(void *);     /* The progress callback */
   15297   void *pProgressArg;           /* Argument to the progress callback */
   15298   unsigned nProgressOps;        /* Number of opcodes for progress callback */
   15299 #endif
   15300 #ifndef SQLITE_OMIT_VIRTUALTABLE
   15301   int nVTrans;                  /* Allocated size of aVTrans */
   15302   Hash aModule;                 /* populated by sqlite3_create_module() */
   15303   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
   15304   VTable **aVTrans;             /* Virtual tables with open transactions */
   15305   VTable *pDisconnect;          /* Disconnect these in next sqlite3_prepare() */
   15306 #endif
   15307   Hash aFunc;                   /* Hash table of connection functions */
   15308   Hash aCollSeq;                /* All collating sequences */
   15309   BusyHandler busyHandler;      /* Busy callback */
   15310   Db aDbStatic[2];              /* Static space for the 2 default backends */
   15311   Savepoint *pSavepoint;        /* List of active savepoints */
   15312   int busyTimeout;              /* Busy handler timeout, in msec */
   15313   int nSavepoint;               /* Number of non-transaction savepoints */
   15314   int nStatement;               /* Number of nested statement-transactions  */
   15315   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
   15316   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
   15317   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
   15318 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   15319   /* The following variables are all protected by the STATIC_MASTER
   15320   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
   15321   **
   15322   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
   15323   ** unlock so that it can proceed.
   15324   **
   15325   ** When X.pBlockingConnection==Y, that means that something that X tried
   15326   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
   15327   ** held by Y.
   15328   */
   15329   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
   15330   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
   15331   void *pUnlockArg;                     /* Argument to xUnlockNotify */
   15332   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
   15333   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
   15334 #endif
   15335 #ifdef SQLITE_USER_AUTHENTICATION
   15336   sqlite3_userauth auth;        /* User authentication information */
   15337 #endif
   15338 };
   15339 
   15340 /*
   15341 ** A macro to discover the encoding of a database.
   15342 */
   15343 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
   15344 #define ENC(db)        ((db)->enc)
   15345 
   15346 /*
   15347 ** Possible values for the sqlite3.flags.
   15348 **
   15349 ** Value constraints (enforced via assert()):
   15350 **      SQLITE_FullFSync     == PAGER_FULLFSYNC
   15351 **      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
   15352 **      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
   15353 */
   15354 #define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_MASTER */
   15355 #define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
   15356 #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
   15357 #define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
   15358 #define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
   15359 #define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
   15360 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
   15361 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
   15362                                           /*   DELETE, or UPDATE and return */
   15363                                           /*   the count using a callback. */
   15364 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
   15365                                           /*   result set is empty */
   15366 #define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
   15367 #define SQLITE_ReadUncommit   0x00000400  /* READ UNCOMMITTED in shared-cache */
   15368 #define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
   15369 #define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
   15370 #define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
   15371 #define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
   15372 #define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
   15373 #define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
   15374 #define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */
   15375 #define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */
   15376 #define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
   15377 #define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
   15378 #define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
   15379 #define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
   15380 #define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/
   15381 #define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */
   15382 
   15383 /* Flags used only if debugging */
   15384 #ifdef SQLITE_DEBUG
   15385 #define SQLITE_SqlTrace       0x08000000  /* Debug print SQL as it executes */
   15386 #define SQLITE_VdbeListing    0x10000000  /* Debug listings of VDBE programs */
   15387 #define SQLITE_VdbeTrace      0x20000000  /* True to trace VDBE execution */
   15388 #define SQLITE_VdbeAddopTrace 0x40000000  /* Trace sqlite3VdbeAddOp() calls */
   15389 #define SQLITE_VdbeEQP        0x80000000  /* Debug EXPLAIN QUERY PLAN */
   15390 #endif
   15391 
   15392 /*
   15393 ** Allowed values for sqlite3.mDbFlags
   15394 */
   15395 #define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */
   15396 #define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */
   15397 #define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */
   15398 
   15399 /*
   15400 ** Bits of the sqlite3.dbOptFlags field that are used by the
   15401 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
   15402 ** selectively disable various optimizations.
   15403 */
   15404 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
   15405 #define SQLITE_ColumnCache    0x0002   /* Column cache */
   15406 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
   15407 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
   15408 #define SQLITE_DistinctOpt    0x0010   /* DISTINCT using indexes */
   15409 #define SQLITE_CoverIdxScan   0x0020   /* Covering index scans */
   15410 #define SQLITE_OrderByIdxJoin 0x0040   /* ORDER BY of joins via index */
   15411 #define SQLITE_Transitive     0x0080   /* Transitive constraints */
   15412 #define SQLITE_OmitNoopJoin   0x0100   /* Omit unused tables in joins */
   15413 #define SQLITE_CountOfView    0x0200   /* The count-of-view optimization */
   15414 #define SQLITE_CursorHints    0x0400   /* Add OP_CursorHint opcodes */
   15415 #define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
   15416    /* TH3 expects the Stat34  ^^^^^^ value to be 0x0800.  Don't change it */
   15417 #define SQLITE_AllOpts        0xffff   /* All optimizations */
   15418 
   15419 /*
   15420 ** Macros for testing whether or not optimizations are enabled or disabled.
   15421 */
   15422 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
   15423 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
   15424 
   15425 /*
   15426 ** Return true if it OK to factor constant expressions into the initialization
   15427 ** code. The argument is a Parse object for the code generator.
   15428 */
   15429 #define ConstFactorOk(P) ((P)->okConstFactor)
   15430 
   15431 /*
   15432 ** Possible values for the sqlite.magic field.
   15433 ** The numbers are obtained at random and have no special meaning, other
   15434 ** than being distinct from one another.
   15435 */
   15436 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
   15437 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
   15438 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
   15439 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
   15440 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
   15441 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
   15442 
   15443 /*
   15444 ** Each SQL function is defined by an instance of the following
   15445 ** structure.  For global built-in functions (ex: substr(), max(), count())
   15446 ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
   15447 ** For per-connection application-defined functions, a pointer to this
   15448 ** structure is held in the db->aHash hash table.
   15449 **
   15450 ** The u.pHash field is used by the global built-ins.  The u.pDestructor
   15451 ** field is used by per-connection app-def functions.
   15452 */
   15453 struct FuncDef {
   15454   i8 nArg;             /* Number of arguments.  -1 means unlimited */
   15455   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
   15456   void *pUserData;     /* User data parameter */
   15457   FuncDef *pNext;      /* Next function with same name */
   15458   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
   15459   void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
   15460   const char *zName;   /* SQL name of the function. */
   15461   union {
   15462     FuncDef *pHash;      /* Next with a different name but the same hash */
   15463     FuncDestructor *pDestructor;   /* Reference counted destructor function */
   15464   } u;
   15465 };
   15466 
   15467 /*
   15468 ** This structure encapsulates a user-function destructor callback (as
   15469 ** configured using create_function_v2()) and a reference counter. When
   15470 ** create_function_v2() is called to create a function with a destructor,
   15471 ** a single object of this type is allocated. FuncDestructor.nRef is set to
   15472 ** the number of FuncDef objects created (either 1 or 3, depending on whether
   15473 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
   15474 ** member of each of the new FuncDef objects is set to point to the allocated
   15475 ** FuncDestructor.
   15476 **
   15477 ** Thereafter, when one of the FuncDef objects is deleted, the reference
   15478 ** count on this object is decremented. When it reaches 0, the destructor
   15479 ** is invoked and the FuncDestructor structure freed.
   15480 */
   15481 struct FuncDestructor {
   15482   int nRef;
   15483   void (*xDestroy)(void *);
   15484   void *pUserData;
   15485 };
   15486 
   15487 /*
   15488 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
   15489 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
   15490 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
   15491 ** are assert() statements in the code to verify this.
   15492 **
   15493 ** Value constraints (enforced via assert()):
   15494 **     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
   15495 **     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
   15496 **     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
   15497 **     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
   15498 **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
   15499 */
   15500 #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
   15501 #define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
   15502 #define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
   15503 #define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
   15504 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
   15505 #define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
   15506 #define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
   15507 #define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
   15508 #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
   15509 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
   15510 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
   15511 #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
   15512 #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
   15513                                     ** single query - might change over time */
   15514 #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
   15515 #define SQLITE_FUNC_OFFSET   0x8000 /* Built-in sqlite_offset() function */
   15516 
   15517 /*
   15518 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
   15519 ** used to create the initializers for the FuncDef structures.
   15520 **
   15521 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
   15522 **     Used to create a scalar function definition of a function zName
   15523 **     implemented by C function xFunc that accepts nArg arguments. The
   15524 **     value passed as iArg is cast to a (void*) and made available
   15525 **     as the user-data (sqlite3_user_data()) for the function. If
   15526 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
   15527 **
   15528 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
   15529 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
   15530 **
   15531 **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
   15532 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
   15533 **     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
   15534 **     and functions like sqlite_version() that can change, but not during
   15535 **     a single query.  The iArg is ignored.  The user-data is always set
   15536 **     to a NULL pointer.  The bNC parameter is not used.
   15537 **
   15538 **   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
   15539 **     Used for "pure" date/time functions, this macro is like DFUNCTION
   15540 **     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
   15541 **     ignored and the user-data for these functions is set to an
   15542 **     arbitrary non-NULL pointer.  The bNC parameter is not used.
   15543 **
   15544 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
   15545 **     Used to create an aggregate function definition implemented by
   15546 **     the C functions xStep and xFinal. The first four parameters
   15547 **     are interpreted in the same way as the first 4 parameters to
   15548 **     FUNCTION().
   15549 **
   15550 **   LIKEFUNC(zName, nArg, pArg, flags)
   15551 **     Used to create a scalar function definition of a function zName
   15552 **     that accepts nArg arguments and is implemented by a call to C
   15553 **     function likeFunc. Argument pArg is cast to a (void *) and made
   15554 **     available as the function user-data (sqlite3_user_data()). The
   15555 **     FuncDef.flags variable is set to the value passed as the flags
   15556 **     parameter.
   15557 */
   15558 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
   15559   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
   15560    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
   15561 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
   15562   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
   15563    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
   15564 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
   15565   {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
   15566    0, 0, xFunc, 0, #zName, {0} }
   15567 #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
   15568   {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
   15569    (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
   15570 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
   15571   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
   15572    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
   15573 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
   15574   {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
   15575    pArg, 0, xFunc, 0, #zName, }
   15576 #define LIKEFUNC(zName, nArg, arg, flags) \
   15577   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
   15578    (void *)arg, 0, likeFunc, 0, #zName, {0} }
   15579 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
   15580   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
   15581    SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
   15582 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
   15583   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
   15584    SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
   15585 
   15586 /*
   15587 ** All current savepoints are stored in a linked list starting at
   15588 ** sqlite3.pSavepoint. The first element in the list is the most recently
   15589 ** opened savepoint. Savepoints are added to the list by the vdbe
   15590 ** OP_Savepoint instruction.
   15591 */
   15592 struct Savepoint {
   15593   char *zName;                        /* Savepoint name (nul-terminated) */
   15594   i64 nDeferredCons;                  /* Number of deferred fk violations */
   15595   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
   15596   Savepoint *pNext;                   /* Parent savepoint (if any) */
   15597 };
   15598 
   15599 /*
   15600 ** The following are used as the second parameter to sqlite3Savepoint(),
   15601 ** and as the P1 argument to the OP_Savepoint instruction.
   15602 */
   15603 #define SAVEPOINT_BEGIN      0
   15604 #define SAVEPOINT_RELEASE    1
   15605 #define SAVEPOINT_ROLLBACK   2
   15606 
   15607 
   15608 /*
   15609 ** Each SQLite module (virtual table definition) is defined by an
   15610 ** instance of the following structure, stored in the sqlite3.aModule
   15611 ** hash table.
   15612 */
   15613 struct Module {
   15614   const sqlite3_module *pModule;       /* Callback pointers */
   15615   const char *zName;                   /* Name passed to create_module() */
   15616   void *pAux;                          /* pAux passed to create_module() */
   15617   void (*xDestroy)(void *);            /* Module destructor function */
   15618   Table *pEpoTab;                      /* Eponymous table for this module */
   15619 };
   15620 
   15621 /*
   15622 ** information about each column of an SQL table is held in an instance
   15623 ** of this structure.
   15624 */
   15625 struct Column {
   15626   char *zName;     /* Name of this column, \000, then the type */
   15627   Expr *pDflt;     /* Default value of this column */
   15628   char *zColl;     /* Collating sequence.  If NULL, use the default */
   15629   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
   15630   char affinity;   /* One of the SQLITE_AFF_... values */
   15631   u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
   15632   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
   15633 };
   15634 
   15635 /* Allowed values for Column.colFlags:
   15636 */
   15637 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
   15638 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
   15639 #define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
   15640 
   15641 /*
   15642 ** A "Collating Sequence" is defined by an instance of the following
   15643 ** structure. Conceptually, a collating sequence consists of a name and
   15644 ** a comparison routine that defines the order of that sequence.
   15645 **
   15646 ** If CollSeq.xCmp is NULL, it means that the
   15647 ** collating sequence is undefined.  Indices built on an undefined
   15648 ** collating sequence may not be read or written.
   15649 */
   15650 struct CollSeq {
   15651   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
   15652   u8 enc;               /* Text encoding handled by xCmp() */
   15653   void *pUser;          /* First argument to xCmp() */
   15654   int (*xCmp)(void*,int, const void*, int, const void*);
   15655   void (*xDel)(void*);  /* Destructor for pUser */
   15656 };
   15657 
   15658 /*
   15659 ** A sort order can be either ASC or DESC.
   15660 */
   15661 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
   15662 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
   15663 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
   15664 
   15665 /*
   15666 ** Column affinity types.
   15667 **
   15668 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
   15669 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
   15670 ** the speed a little by numbering the values consecutively.
   15671 **
   15672 ** But rather than start with 0 or 1, we begin with 'A'.  That way,
   15673 ** when multiple affinity types are concatenated into a string and
   15674 ** used as the P4 operand, they will be more readable.
   15675 **
   15676 ** Note also that the numeric types are grouped together so that testing
   15677 ** for a numeric type is a single comparison.  And the BLOB type is first.
   15678 */
   15679 #define SQLITE_AFF_BLOB     'A'
   15680 #define SQLITE_AFF_TEXT     'B'
   15681 #define SQLITE_AFF_NUMERIC  'C'
   15682 #define SQLITE_AFF_INTEGER  'D'
   15683 #define SQLITE_AFF_REAL     'E'
   15684 
   15685 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
   15686 
   15687 /*
   15688 ** The SQLITE_AFF_MASK values masks off the significant bits of an
   15689 ** affinity value.
   15690 */
   15691 #define SQLITE_AFF_MASK     0x47
   15692 
   15693 /*
   15694 ** Additional bit values that can be ORed with an affinity without
   15695 ** changing the affinity.
   15696 **
   15697 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
   15698 ** It causes an assert() to fire if either operand to a comparison
   15699 ** operator is NULL.  It is added to certain comparison operators to
   15700 ** prove that the operands are always NOT NULL.
   15701 */
   15702 #define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */
   15703 #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
   15704 #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
   15705 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
   15706 #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
   15707 
   15708 /*
   15709 ** An object of this type is created for each virtual table present in
   15710 ** the database schema.
   15711 **
   15712 ** If the database schema is shared, then there is one instance of this
   15713 ** structure for each database connection (sqlite3*) that uses the shared
   15714 ** schema. This is because each database connection requires its own unique
   15715 ** instance of the sqlite3_vtab* handle used to access the virtual table
   15716 ** implementation. sqlite3_vtab* handles can not be shared between
   15717 ** database connections, even when the rest of the in-memory database
   15718 ** schema is shared, as the implementation often stores the database
   15719 ** connection handle passed to it via the xConnect() or xCreate() method
   15720 ** during initialization internally. This database connection handle may
   15721 ** then be used by the virtual table implementation to access real tables
   15722 ** within the database. So that they appear as part of the callers
   15723 ** transaction, these accesses need to be made via the same database
   15724 ** connection as that used to execute SQL operations on the virtual table.
   15725 **
   15726 ** All VTable objects that correspond to a single table in a shared
   15727 ** database schema are initially stored in a linked-list pointed to by
   15728 ** the Table.pVTable member variable of the corresponding Table object.
   15729 ** When an sqlite3_prepare() operation is required to access the virtual
   15730 ** table, it searches the list for the VTable that corresponds to the
   15731 ** database connection doing the preparing so as to use the correct
   15732 ** sqlite3_vtab* handle in the compiled query.
   15733 **
   15734 ** When an in-memory Table object is deleted (for example when the
   15735 ** schema is being reloaded for some reason), the VTable objects are not
   15736 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
   15737 ** immediately. Instead, they are moved from the Table.pVTable list to
   15738 ** another linked list headed by the sqlite3.pDisconnect member of the
   15739 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
   15740 ** next time a statement is prepared using said sqlite3*. This is done
   15741 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
   15742 ** Refer to comments above function sqlite3VtabUnlockList() for an
   15743 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
   15744 ** list without holding the corresponding sqlite3.mutex mutex.
   15745 **
   15746 ** The memory for objects of this type is always allocated by
   15747 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
   15748 ** the first argument.
   15749 */
   15750 struct VTable {
   15751   sqlite3 *db;              /* Database connection associated with this table */
   15752   Module *pMod;             /* Pointer to module implementation */
   15753   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
   15754   int nRef;                 /* Number of pointers to this structure */
   15755   u8 bConstraint;           /* True if constraints are supported */
   15756   int iSavepoint;           /* Depth of the SAVEPOINT stack */
   15757   VTable *pNext;            /* Next in linked list (see above) */
   15758 };
   15759 
   15760 /*
   15761 ** The schema for each SQL table and view is represented in memory
   15762 ** by an instance of the following structure.
   15763 */
   15764 struct Table {
   15765   char *zName;         /* Name of the table or view */
   15766   Column *aCol;        /* Information about each column */
   15767   Index *pIndex;       /* List of SQL indexes on this table. */
   15768   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
   15769   FKey *pFKey;         /* Linked list of all foreign keys in this table */
   15770   char *zColAff;       /* String defining the affinity of each column */
   15771   ExprList *pCheck;    /* All CHECK constraints */
   15772                        /*   ... also used as column name list in a VIEW */
   15773   int tnum;            /* Root BTree page for this table */
   15774   u32 nTabRef;         /* Number of pointers to this Table */
   15775   u32 tabFlags;        /* Mask of TF_* values */
   15776   i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
   15777   i16 nCol;            /* Number of columns in this table */
   15778   LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
   15779   LogEst szTabRow;     /* Estimated size of each table row in bytes */
   15780 #ifdef SQLITE_ENABLE_COSTMULT
   15781   LogEst costMult;     /* Cost multiplier for using this table */
   15782 #endif
   15783   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
   15784 #ifndef SQLITE_OMIT_ALTERTABLE
   15785   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
   15786 #endif
   15787 #ifndef SQLITE_OMIT_VIRTUALTABLE
   15788   int nModuleArg;      /* Number of arguments to the module */
   15789   char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
   15790   VTable *pVTable;     /* List of VTable objects. */
   15791 #endif
   15792   Trigger *pTrigger;   /* List of triggers stored in pSchema */
   15793   Schema *pSchema;     /* Schema that contains this table */
   15794   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
   15795 };
   15796 
   15797 /*
   15798 ** Allowed values for Table.tabFlags.
   15799 **
   15800 ** TF_OOOHidden applies to tables or view that have hidden columns that are
   15801 ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
   15802 ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
   15803 ** the TF_OOOHidden attribute would apply in this case.  Such tables require
   15804 ** special handling during INSERT processing.
   15805 */
   15806 #define TF_Readonly        0x0001    /* Read-only system table */
   15807 #define TF_Ephemeral       0x0002    /* An ephemeral table */
   15808 #define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
   15809 #define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
   15810 #define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
   15811 #define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
   15812 #define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
   15813 #define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
   15814 #define TF_StatsUsed       0x0100    /* Query planner decisions affected by
   15815                                      ** Index.aiRowLogEst[] values */
   15816 #define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
   15817 
   15818 /*
   15819 ** Test to see whether or not a table is a virtual table.  This is
   15820 ** done as a macro so that it will be optimized out when virtual
   15821 ** table support is omitted from the build.
   15822 */
   15823 #ifndef SQLITE_OMIT_VIRTUALTABLE
   15824 #  define IsVirtual(X)      ((X)->nModuleArg)
   15825 #else
   15826 #  define IsVirtual(X)      0
   15827 #endif
   15828 
   15829 /*
   15830 ** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
   15831 ** only works for non-virtual tables (ordinary tables and views) and is
   15832 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
   15833 ** IsHiddenColumn() macro is general purpose.
   15834 */
   15835 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
   15836 #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
   15837 #  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
   15838 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
   15839 #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
   15840 #  define IsOrdinaryHiddenColumn(X) 0
   15841 #else
   15842 #  define IsHiddenColumn(X)         0
   15843 #  define IsOrdinaryHiddenColumn(X) 0
   15844 #endif
   15845 
   15846 
   15847 /* Does the table have a rowid */
   15848 #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
   15849 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
   15850 
   15851 /*
   15852 ** Each foreign key constraint is an instance of the following structure.
   15853 **
   15854 ** A foreign key is associated with two tables.  The "from" table is
   15855 ** the table that contains the REFERENCES clause that creates the foreign
   15856 ** key.  The "to" table is the table that is named in the REFERENCES clause.
   15857 ** Consider this example:
   15858 **
   15859 **     CREATE TABLE ex1(
   15860 **       a INTEGER PRIMARY KEY,
   15861 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
   15862 **     );
   15863 **
   15864 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
   15865 ** Equivalent names:
   15866 **
   15867 **     from-table == child-table
   15868 **       to-table == parent-table
   15869 **
   15870 ** Each REFERENCES clause generates an instance of the following structure
   15871 ** which is attached to the from-table.  The to-table need not exist when
   15872 ** the from-table is created.  The existence of the to-table is not checked.
   15873 **
   15874 ** The list of all parents for child Table X is held at X.pFKey.
   15875 **
   15876 ** A list of all children for a table named Z (which might not even exist)
   15877 ** is held in Schema.fkeyHash with a hash key of Z.
   15878 */
   15879 struct FKey {
   15880   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
   15881   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
   15882   char *zTo;        /* Name of table that the key points to (aka: Parent) */
   15883   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
   15884   FKey *pPrevTo;    /* Previous with the same zTo */
   15885   int nCol;         /* Number of columns in this key */
   15886   /* EV: R-30323-21917 */
   15887   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
   15888   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
   15889   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
   15890   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
   15891     int iFrom;            /* Index of column in pFrom */
   15892     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
   15893   } aCol[1];            /* One entry for each of nCol columns */
   15894 };
   15895 
   15896 /*
   15897 ** SQLite supports many different ways to resolve a constraint
   15898 ** error.  ROLLBACK processing means that a constraint violation
   15899 ** causes the operation in process to fail and for the current transaction
   15900 ** to be rolled back.  ABORT processing means the operation in process
   15901 ** fails and any prior changes from that one operation are backed out,
   15902 ** but the transaction is not rolled back.  FAIL processing means that
   15903 ** the operation in progress stops and returns an error code.  But prior
   15904 ** changes due to the same operation are not backed out and no rollback
   15905 ** occurs.  IGNORE means that the particular row that caused the constraint
   15906 ** error is not inserted or updated.  Processing continues and no error
   15907 ** is returned.  REPLACE means that preexisting database rows that caused
   15908 ** a UNIQUE constraint violation are removed so that the new insert or
   15909 ** update can proceed.  Processing continues and no error is reported.
   15910 **
   15911 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
   15912 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
   15913 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
   15914 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
   15915 ** referenced table row is propagated into the row that holds the
   15916 ** foreign key.
   15917 **
   15918 ** The following symbolic values are used to record which type
   15919 ** of action to take.
   15920 */
   15921 #define OE_None     0   /* There is no constraint to check */
   15922 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
   15923 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
   15924 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
   15925 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
   15926 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
   15927 
   15928 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
   15929 #define OE_SetNull  7   /* Set the foreign key value to NULL */
   15930 #define OE_SetDflt  8   /* Set the foreign key value to its default */
   15931 #define OE_Cascade  9   /* Cascade the changes */
   15932 
   15933 #define OE_Default  10  /* Do whatever the default action is */
   15934 
   15935 
   15936 /*
   15937 ** An instance of the following structure is passed as the first
   15938 ** argument to sqlite3VdbeKeyCompare and is used to control the
   15939 ** comparison of the two index keys.
   15940 **
   15941 ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
   15942 ** are nField slots for the columns of an index then one extra slot
   15943 ** for the rowid at the end.
   15944 */
   15945 struct KeyInfo {
   15946   u32 nRef;           /* Number of references to this KeyInfo object */
   15947   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
   15948   u16 nKeyField;      /* Number of key columns in the index */
   15949   u16 nAllField;      /* Total columns, including key plus others */
   15950   sqlite3 *db;        /* The database connection */
   15951   u8 *aSortOrder;     /* Sort order for each column. */
   15952   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
   15953 };
   15954 
   15955 /*
   15956 ** This object holds a record which has been parsed out into individual
   15957 ** fields, for the purposes of doing a comparison.
   15958 **
   15959 ** A record is an object that contains one or more fields of data.
   15960 ** Records are used to store the content of a table row and to store
   15961 ** the key of an index.  A blob encoding of a record is created by
   15962 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
   15963 ** OP_Column opcode.
   15964 **
   15965 ** An instance of this object serves as a "key" for doing a search on
   15966 ** an index b+tree. The goal of the search is to find the entry that
   15967 ** is closed to the key described by this object.  This object might hold
   15968 ** just a prefix of the key.  The number of fields is given by
   15969 ** pKeyInfo->nField.
   15970 **
   15971 ** The r1 and r2 fields are the values to return if this key is less than
   15972 ** or greater than a key in the btree, respectively.  These are normally
   15973 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
   15974 ** is in DESC order.
   15975 **
   15976 ** The key comparison functions actually return default_rc when they find
   15977 ** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
   15978 ** multiple entries in the b-tree with the same key (when only looking
   15979 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
   15980 ** cause the search to find the last match, or +1 to cause the search to
   15981 ** find the first match.
   15982 **
   15983 ** The key comparison functions will set eqSeen to true if they ever
   15984 ** get and equal results when comparing this structure to a b-tree record.
   15985 ** When default_rc!=0, the search might end up on the record immediately
   15986 ** before the first match or immediately after the last match.  The
   15987 ** eqSeen field will indicate whether or not an exact match exists in the
   15988 ** b-tree.
   15989 */
   15990 struct UnpackedRecord {
   15991   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
   15992   Mem *aMem;          /* Values */
   15993   u16 nField;         /* Number of entries in apMem[] */
   15994   i8 default_rc;      /* Comparison result if keys are equal */
   15995   u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
   15996   i8 r1;              /* Value to return if (lhs < rhs) */
   15997   i8 r2;              /* Value to return if (lhs > rhs) */
   15998   u8 eqSeen;          /* True if an equality comparison has been seen */
   15999 };
   16000 
   16001 
   16002 /*
   16003 ** Each SQL index is represented in memory by an
   16004 ** instance of the following structure.
   16005 **
   16006 ** The columns of the table that are to be indexed are described
   16007 ** by the aiColumn[] field of this structure.  For example, suppose
   16008 ** we have the following table and index:
   16009 **
   16010 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
   16011 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
   16012 **
   16013 ** In the Table structure describing Ex1, nCol==3 because there are
   16014 ** three columns in the table.  In the Index structure describing
   16015 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
   16016 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
   16017 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
   16018 ** The second column to be indexed (c1) has an index of 0 in
   16019 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
   16020 **
   16021 ** The Index.onError field determines whether or not the indexed columns
   16022 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
   16023 ** it means this is not a unique index.  Otherwise it is a unique index
   16024 ** and the value of Index.onError indicate the which conflict resolution
   16025 ** algorithm to employ whenever an attempt is made to insert a non-unique
   16026 ** element.
   16027 **
   16028 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
   16029 ** generate VDBE code (as opposed to parsing one read from an sqlite_master
   16030 ** table as part of parsing an existing database schema), transient instances
   16031 ** of this structure may be created. In this case the Index.tnum variable is
   16032 ** used to store the address of a VDBE instruction, not a database page
   16033 ** number (it cannot - the database page is not allocated until the VDBE
   16034 ** program is executed). See convertToWithoutRowidTable() for details.
   16035 */
   16036 struct Index {
   16037   char *zName;             /* Name of this index */
   16038   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
   16039   LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
   16040   Table *pTable;           /* The SQL table being indexed */
   16041   char *zColAff;           /* String defining the affinity of each column */
   16042   Index *pNext;            /* The next index associated with the same table */
   16043   Schema *pSchema;         /* Schema containing this index */
   16044   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
   16045   const char **azColl;     /* Array of collation sequence names for index */
   16046   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
   16047   ExprList *aColExpr;      /* Column expressions */
   16048   int tnum;                /* DB Page containing root of this index */
   16049   LogEst szIdxRow;         /* Estimated average row size in bytes */
   16050   u16 nKeyCol;             /* Number of columns forming the key */
   16051   u16 nColumn;             /* Number of columns stored in the index */
   16052   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   16053   unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
   16054   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
   16055   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
   16056   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
   16057   unsigned isCovering:1;   /* True if this is a covering index */
   16058   unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
   16059   unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
   16060   unsigned bNoQuery:1;     /* Do not use this index to optimize queries */
   16061 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   16062   int nSample;             /* Number of elements in aSample[] */
   16063   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
   16064   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
   16065   IndexSample *aSample;    /* Samples of the left-most key */
   16066   tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
   16067   tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
   16068 #endif
   16069 };
   16070 
   16071 /*
   16072 ** Allowed values for Index.idxType
   16073 */
   16074 #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
   16075 #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
   16076 #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
   16077 
   16078 /* Return true if index X is a PRIMARY KEY index */
   16079 #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
   16080 
   16081 /* Return true if index X is a UNIQUE index */
   16082 #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
   16083 
   16084 /* The Index.aiColumn[] values are normally positive integer.  But
   16085 ** there are some negative values that have special meaning:
   16086 */
   16087 #define XN_ROWID     (-1)     /* Indexed column is the rowid */
   16088 #define XN_EXPR      (-2)     /* Indexed column is an expression */
   16089 
   16090 /*
   16091 ** Each sample stored in the sqlite_stat3 table is represented in memory
   16092 ** using a structure of this type.  See documentation at the top of the
   16093 ** analyze.c source file for additional information.
   16094 */
   16095 struct IndexSample {
   16096   void *p;          /* Pointer to sampled record */
   16097   int n;            /* Size of record in bytes */
   16098   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
   16099   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
   16100   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
   16101 };
   16102 
   16103 /*
   16104 ** Each token coming out of the lexer is an instance of
   16105 ** this structure.  Tokens are also used as part of an expression.
   16106 **
   16107 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
   16108 ** may contain random values.  Do not make any assumptions about Token.dyn
   16109 ** and Token.n when Token.z==0.
   16110 */
   16111 struct Token {
   16112   const char *z;     /* Text of the token.  Not NULL-terminated! */
   16113   unsigned int n;    /* Number of characters in this token */
   16114 };
   16115 
   16116 /*
   16117 ** An instance of this structure contains information needed to generate
   16118 ** code for a SELECT that contains aggregate functions.
   16119 **
   16120 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
   16121 ** pointer to this structure.  The Expr.iColumn field is the index in
   16122 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
   16123 ** code for that node.
   16124 **
   16125 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
   16126 ** original Select structure that describes the SELECT statement.  These
   16127 ** fields do not need to be freed when deallocating the AggInfo structure.
   16128 */
   16129 struct AggInfo {
   16130   u8 directMode;          /* Direct rendering mode means take data directly
   16131                           ** from source tables rather than from accumulators */
   16132   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
   16133                           ** than the source table */
   16134   int sortingIdx;         /* Cursor number of the sorting index */
   16135   int sortingIdxPTab;     /* Cursor number of pseudo-table */
   16136   int nSortingColumn;     /* Number of columns in the sorting index */
   16137   int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
   16138   ExprList *pGroupBy;     /* The group by clause */
   16139   struct AggInfo_col {    /* For each column used in source tables */
   16140     Table *pTab;             /* Source table */
   16141     int iTable;              /* Cursor number of the source table */
   16142     int iColumn;             /* Column number within the source table */
   16143     int iSorterColumn;       /* Column number in the sorting index */
   16144     int iMem;                /* Memory location that acts as accumulator */
   16145     Expr *pExpr;             /* The original expression */
   16146   } *aCol;
   16147   int nColumn;            /* Number of used entries in aCol[] */
   16148   int nAccumulator;       /* Number of columns that show through to the output.
   16149                           ** Additional columns are used only as parameters to
   16150                           ** aggregate functions */
   16151   struct AggInfo_func {   /* For each aggregate function */
   16152     Expr *pExpr;             /* Expression encoding the function */
   16153     FuncDef *pFunc;          /* The aggregate function implementation */
   16154     int iMem;                /* Memory location that acts as accumulator */
   16155     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
   16156   } *aFunc;
   16157   int nFunc;              /* Number of entries in aFunc[] */
   16158 };
   16159 
   16160 /*
   16161 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
   16162 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
   16163 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
   16164 ** it uses less memory in the Expr object, which is a big memory user
   16165 ** in systems with lots of prepared statements.  And few applications
   16166 ** need more than about 10 or 20 variables.  But some extreme users want
   16167 ** to have prepared statements with over 32767 variables, and for them
   16168 ** the option is available (at compile-time).
   16169 */
   16170 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
   16171 typedef i16 ynVar;
   16172 #else
   16173 typedef int ynVar;
   16174 #endif
   16175 
   16176 /*
   16177 ** Each node of an expression in the parse tree is an instance
   16178 ** of this structure.
   16179 **
   16180 ** Expr.op is the opcode. The integer parser token codes are reused
   16181 ** as opcodes here. For example, the parser defines TK_GE to be an integer
   16182 ** code representing the ">=" operator. This same integer code is reused
   16183 ** to represent the greater-than-or-equal-to operator in the expression
   16184 ** tree.
   16185 **
   16186 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
   16187 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
   16188 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
   16189 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
   16190 ** then Expr.token contains the name of the function.
   16191 **
   16192 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
   16193 ** binary operator. Either or both may be NULL.
   16194 **
   16195 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
   16196 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
   16197 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
   16198 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
   16199 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
   16200 ** valid.
   16201 **
   16202 ** An expression of the form ID or ID.ID refers to a column in a table.
   16203 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
   16204 ** the integer cursor number of a VDBE cursor pointing to that table and
   16205 ** Expr.iColumn is the column number for the specific column.  If the
   16206 ** expression is used as a result in an aggregate SELECT, then the
   16207 ** value is also stored in the Expr.iAgg column in the aggregate so that
   16208 ** it can be accessed after all aggregates are computed.
   16209 **
   16210 ** If the expression is an unbound variable marker (a question mark
   16211 ** character '?' in the original SQL) then the Expr.iTable holds the index
   16212 ** number for that variable.
   16213 **
   16214 ** If the expression is a subquery then Expr.iColumn holds an integer
   16215 ** register number containing the result of the subquery.  If the
   16216 ** subquery gives a constant result, then iTable is -1.  If the subquery
   16217 ** gives a different answer at different times during statement processing
   16218 ** then iTable is the address of a subroutine that computes the subquery.
   16219 **
   16220 ** If the Expr is of type OP_Column, and the table it is selecting from
   16221 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
   16222 ** corresponding table definition.
   16223 **
   16224 ** ALLOCATION NOTES:
   16225 **
   16226 ** Expr objects can use a lot of memory space in database schema.  To
   16227 ** help reduce memory requirements, sometimes an Expr object will be
   16228 ** truncated.  And to reduce the number of memory allocations, sometimes
   16229 ** two or more Expr objects will be stored in a single memory allocation,
   16230 ** together with Expr.zToken strings.
   16231 **
   16232 ** If the EP_Reduced and EP_TokenOnly flags are set when
   16233 ** an Expr object is truncated.  When EP_Reduced is set, then all
   16234 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
   16235 ** are contained within the same memory allocation.  Note, however, that
   16236 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
   16237 ** allocated, regardless of whether or not EP_Reduced is set.
   16238 */
   16239 struct Expr {
   16240   u8 op;                 /* Operation performed by this node */
   16241   char affinity;         /* The affinity of the column or 0 if not a column */
   16242   u32 flags;             /* Various flags.  EP_* See below */
   16243   union {
   16244     char *zToken;          /* Token value. Zero terminated and dequoted */
   16245     int iValue;            /* Non-negative integer value if EP_IntValue */
   16246   } u;
   16247 
   16248   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
   16249   ** space is allocated for the fields below this point. An attempt to
   16250   ** access them will result in a segfault or malfunction.
   16251   *********************************************************************/
   16252 
   16253   Expr *pLeft;           /* Left subnode */
   16254   Expr *pRight;          /* Right subnode */
   16255   union {
   16256     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
   16257     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
   16258   } x;
   16259 
   16260   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
   16261   ** space is allocated for the fields below this point. An attempt to
   16262   ** access them will result in a segfault or malfunction.
   16263   *********************************************************************/
   16264 
   16265 #if SQLITE_MAX_EXPR_DEPTH>0
   16266   int nHeight;           /* Height of the tree headed by this node */
   16267 #endif
   16268   int iTable;            /* TK_COLUMN: cursor number of table holding column
   16269                          ** TK_REGISTER: register number
   16270                          ** TK_TRIGGER: 1 -> new, 0 -> old
   16271                          ** EP_Unlikely:  134217728 times likelihood
   16272                          ** TK_SELECT: 1st register of result vector */
   16273   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
   16274                          ** TK_VARIABLE: variable number (always >= 1).
   16275                          ** TK_SELECT_COLUMN: column of the result vector */
   16276   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
   16277   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
   16278   u8 op2;                /* TK_REGISTER: original value of Expr.op
   16279                          ** TK_COLUMN: the value of p5 for OP_Column
   16280                          ** TK_AGG_FUNCTION: nesting depth */
   16281   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   16282   Table *pTab;           /* Table for TK_COLUMN expressions.  Can be NULL
   16283                          ** for a column of an index on an expression */
   16284 };
   16285 
   16286 /*
   16287 ** The following are the meanings of bits in the Expr.flags field.
   16288 */
   16289 #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
   16290 #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
   16291 #define EP_HasFunc   0x000004 /* Contains one or more functions of any kind */
   16292                   /* 0x000008 // available for use */
   16293 #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
   16294 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
   16295 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
   16296 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
   16297 #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
   16298 #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
   16299 #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
   16300 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
   16301 #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
   16302 #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
   16303 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
   16304 #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
   16305 #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
   16306 #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
   16307 #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
   16308 #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
   16309 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
   16310 #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
   16311 #define EP_Alias     0x400000 /* Is an alias for a result set column */
   16312 #define EP_Leaf      0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
   16313 
   16314 /*
   16315 ** The EP_Propagate mask is a set of properties that automatically propagate
   16316 ** upwards into parent nodes.
   16317 */
   16318 #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
   16319 
   16320 /*
   16321 ** These macros can be used to test, set, or clear bits in the
   16322 ** Expr.flags field.
   16323 */
   16324 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
   16325 #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
   16326 #define ExprSetProperty(E,P)     (E)->flags|=(P)
   16327 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
   16328 
   16329 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
   16330 ** and Accreditation only.  It works like ExprSetProperty() during VVA
   16331 ** processes but is a no-op for delivery.
   16332 */
   16333 #ifdef SQLITE_DEBUG
   16334 # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
   16335 #else
   16336 # define ExprSetVVAProperty(E,P)
   16337 #endif
   16338 
   16339 /*
   16340 ** Macros to determine the number of bytes required by a normal Expr
   16341 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
   16342 ** and an Expr struct with the EP_TokenOnly flag set.
   16343 */
   16344 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
   16345 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
   16346 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
   16347 
   16348 /*
   16349 ** Flags passed to the sqlite3ExprDup() function. See the header comment
   16350 ** above sqlite3ExprDup() for details.
   16351 */
   16352 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
   16353 
   16354 /*
   16355 ** A list of expressions.  Each expression may optionally have a
   16356 ** name.  An expr/name combination can be used in several ways, such
   16357 ** as the list of "expr AS ID" fields following a "SELECT" or in the
   16358 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
   16359 ** also be used as the argument to a function, in which case the a.zName
   16360 ** field is not used.
   16361 **
   16362 ** By default the Expr.zSpan field holds a human-readable description of
   16363 ** the expression that is used in the generation of error messages and
   16364 ** column labels.  In this case, Expr.zSpan is typically the text of a
   16365 ** column expression as it exists in a SELECT statement.  However, if
   16366 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
   16367 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
   16368 ** form is used for name resolution with nested FROM clauses.
   16369 */
   16370 struct ExprList {
   16371   int nExpr;             /* Number of expressions on the list */
   16372   struct ExprList_item { /* For each expression in the list */
   16373     Expr *pExpr;            /* The parse tree for this expression */
   16374     char *zName;            /* Token associated with this expression */
   16375     char *zSpan;            /* Original text of the expression */
   16376     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
   16377     unsigned done :1;       /* A flag to indicate when processing is finished */
   16378     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
   16379     unsigned reusable :1;   /* Constant expression is reusable */
   16380     union {
   16381       struct {
   16382         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
   16383         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
   16384       } x;
   16385       int iConstExprReg;      /* Register in which Expr value is cached */
   16386     } u;
   16387   } a[1];                  /* One slot for each expression in the list */
   16388 };
   16389 
   16390 /*
   16391 ** An instance of this structure can hold a simple list of identifiers,
   16392 ** such as the list "a,b,c" in the following statements:
   16393 **
   16394 **      INSERT INTO t(a,b,c) VALUES ...;
   16395 **      CREATE INDEX idx ON t(a,b,c);
   16396 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
   16397 **
   16398 ** The IdList.a.idx field is used when the IdList represents the list of
   16399 ** column names after a table name in an INSERT statement.  In the statement
   16400 **
   16401 **     INSERT INTO t(a,b,c) ...
   16402 **
   16403 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
   16404 */
   16405 struct IdList {
   16406   struct IdList_item {
   16407     char *zName;      /* Name of the identifier */
   16408     int idx;          /* Index in some Table.aCol[] of a column named zName */
   16409   } *a;
   16410   int nId;         /* Number of identifiers on the list */
   16411 };
   16412 
   16413 /*
   16414 ** The bitmask datatype defined below is used for various optimizations.
   16415 **
   16416 ** Changing this from a 64-bit to a 32-bit type limits the number of
   16417 ** tables in a join to 32 instead of 64.  But it also reduces the size
   16418 ** of the library by 738 bytes on ix86.
   16419 */
   16420 #ifdef SQLITE_BITMASK_TYPE
   16421   typedef SQLITE_BITMASK_TYPE Bitmask;
   16422 #else
   16423   typedef u64 Bitmask;
   16424 #endif
   16425 
   16426 /*
   16427 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
   16428 */
   16429 #define BMS  ((int)(sizeof(Bitmask)*8))
   16430 
   16431 /*
   16432 ** A bit in a Bitmask
   16433 */
   16434 #define MASKBIT(n)   (((Bitmask)1)<<(n))
   16435 #define MASKBIT32(n) (((unsigned int)1)<<(n))
   16436 #define ALLBITS      ((Bitmask)-1)
   16437 
   16438 /*
   16439 ** The following structure describes the FROM clause of a SELECT statement.
   16440 ** Each table or subquery in the FROM clause is a separate element of
   16441 ** the SrcList.a[] array.
   16442 **
   16443 ** With the addition of multiple database support, the following structure
   16444 ** can also be used to describe a particular table such as the table that
   16445 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
   16446 ** such a table must be a simple name: ID.  But in SQLite, the table can
   16447 ** now be identified by a database name, a dot, then the table name: ID.ID.
   16448 **
   16449 ** The jointype starts out showing the join type between the current table
   16450 ** and the next table on the list.  The parser builds the list this way.
   16451 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
   16452 ** jointype expresses the join between the table and the previous table.
   16453 **
   16454 ** In the colUsed field, the high-order bit (bit 63) is set if the table
   16455 ** contains more than 63 columns and the 64-th or later column is used.
   16456 */
   16457 struct SrcList {
   16458   int nSrc;        /* Number of tables or subqueries in the FROM clause */
   16459   u32 nAlloc;      /* Number of entries allocated in a[] below */
   16460   struct SrcList_item {
   16461     Schema *pSchema;  /* Schema to which this item is fixed */
   16462     char *zDatabase;  /* Name of database holding this table */
   16463     char *zName;      /* Name of the table */
   16464     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
   16465     Table *pTab;      /* An SQL table corresponding to zName */
   16466     Select *pSelect;  /* A SELECT statement used in place of a table name */
   16467     int addrFillSub;  /* Address of subroutine to manifest a subquery */
   16468     int regReturn;    /* Register holding return address of addrFillSub */
   16469     int regResult;    /* Registers holding results of a co-routine */
   16470     struct {
   16471       u8 jointype;      /* Type of join between this table and the previous */
   16472       unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
   16473       unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
   16474       unsigned isTabFunc :1;     /* True if table-valued-function syntax */
   16475       unsigned isCorrelated :1;  /* True if sub-query is correlated */
   16476       unsigned viaCoroutine :1;  /* Implemented as a co-routine */
   16477       unsigned isRecursive :1;   /* True for recursive reference in WITH */
   16478     } fg;
   16479 #ifndef SQLITE_OMIT_EXPLAIN
   16480     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
   16481 #endif
   16482     int iCursor;      /* The VDBE cursor number used to access this table */
   16483     Expr *pOn;        /* The ON clause of a join */
   16484     IdList *pUsing;   /* The USING clause of a join */
   16485     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
   16486     union {
   16487       char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
   16488       ExprList *pFuncArg;  /* Arguments to table-valued-function */
   16489     } u1;
   16490     Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
   16491   } a[1];             /* One entry for each identifier on the list */
   16492 };
   16493 
   16494 /*
   16495 ** Permitted values of the SrcList.a.jointype field
   16496 */
   16497 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
   16498 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
   16499 #define JT_NATURAL   0x0004    /* True for a "natural" join */
   16500 #define JT_LEFT      0x0008    /* Left outer join */
   16501 #define JT_RIGHT     0x0010    /* Right outer join */
   16502 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
   16503 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
   16504 
   16505 
   16506 /*
   16507 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
   16508 ** and the WhereInfo.wctrlFlags member.
   16509 **
   16510 ** Value constraints (enforced via assert()):
   16511 **     WHERE_USE_LIMIT  == SF_FixedLimit
   16512 */
   16513 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
   16514 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
   16515 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
   16516 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
   16517 #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
   16518 #define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
   16519 #define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
   16520                                       ** the OR optimization  */
   16521 #define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
   16522 #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
   16523 #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
   16524 #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
   16525 #define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
   16526 #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
   16527 #define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */
   16528                         /*     0x2000    not currently used */
   16529 #define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
   16530                         /*     0x8000    not currently used */
   16531 
   16532 /* Allowed return values from sqlite3WhereIsDistinct()
   16533 */
   16534 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
   16535 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
   16536 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
   16537 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
   16538 
   16539 /*
   16540 ** A NameContext defines a context in which to resolve table and column
   16541 ** names.  The context consists of a list of tables (the pSrcList) field and
   16542 ** a list of named expression (pEList).  The named expression list may
   16543 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
   16544 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
   16545 ** pEList corresponds to the result set of a SELECT and is NULL for
   16546 ** other statements.
   16547 **
   16548 ** NameContexts can be nested.  When resolving names, the inner-most
   16549 ** context is searched first.  If no match is found, the next outer
   16550 ** context is checked.  If there is still no match, the next context
   16551 ** is checked.  This process continues until either a match is found
   16552 ** or all contexts are check.  When a match is found, the nRef member of
   16553 ** the context containing the match is incremented.
   16554 **
   16555 ** Each subquery gets a new NameContext.  The pNext field points to the
   16556 ** NameContext in the parent query.  Thus the process of scanning the
   16557 ** NameContext list corresponds to searching through successively outer
   16558 ** subqueries looking for a match.
   16559 */
   16560 struct NameContext {
   16561   Parse *pParse;       /* The parser */
   16562   SrcList *pSrcList;   /* One or more tables used to resolve names */
   16563   ExprList *pEList;    /* Optional list of result-set columns */
   16564   AggInfo *pAggInfo;   /* Information about aggregates at this level */
   16565   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   16566   int nRef;            /* Number of names resolved by this context */
   16567   int nErr;            /* Number of errors encountered while resolving names */
   16568   u16 ncFlags;         /* Zero or more NC_* flags defined below */
   16569 };
   16570 
   16571 /*
   16572 ** Allowed values for the NameContext, ncFlags field.
   16573 **
   16574 ** Value constraints (all checked via assert()):
   16575 **    NC_HasAgg    == SF_HasAgg
   16576 **    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
   16577 **
   16578 */
   16579 #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
   16580 #define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
   16581 #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
   16582 #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
   16583 #define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
   16584 #define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
   16585 #define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
   16586 #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
   16587 #define NC_Complex   0x2000  /* True if a function or subquery seen */
   16588 
   16589 /*
   16590 ** An instance of the following structure contains all information
   16591 ** needed to generate code for a single SELECT statement.
   16592 **
   16593 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
   16594 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
   16595 ** limit and nOffset to the value of the offset (or 0 if there is not
   16596 ** offset).  But later on, nLimit and nOffset become the memory locations
   16597 ** in the VDBE that record the limit and offset counters.
   16598 **
   16599 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
   16600 ** These addresses must be stored so that we can go back and fill in
   16601 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
   16602 ** the number of columns in P2 can be computed at the same time
   16603 ** as the OP_OpenEphm instruction is coded because not
   16604 ** enough information about the compound query is known at that point.
   16605 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
   16606 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
   16607 ** sequences for the ORDER BY clause.
   16608 */
   16609 struct Select {
   16610   ExprList *pEList;      /* The fields of the result */
   16611   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
   16612   LogEst nSelectRow;     /* Estimated number of result rows */
   16613   u32 selFlags;          /* Various SF_* values */
   16614   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
   16615 #if SELECTTRACE_ENABLED
   16616   char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
   16617 #endif
   16618   int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
   16619   SrcList *pSrc;         /* The FROM clause */
   16620   Expr *pWhere;          /* The WHERE clause */
   16621   ExprList *pGroupBy;    /* The GROUP BY clause */
   16622   Expr *pHaving;         /* The HAVING clause */
   16623   ExprList *pOrderBy;    /* The ORDER BY clause */
   16624   Select *pPrior;        /* Prior select in a compound select statement */
   16625   Select *pNext;         /* Next select to the left in a compound */
   16626   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
   16627   With *pWith;           /* WITH clause attached to this select. Or NULL. */
   16628 };
   16629 
   16630 /*
   16631 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
   16632 ** "Select Flag".
   16633 **
   16634 ** Value constraints (all checked via assert())
   16635 **     SF_HasAgg     == NC_HasAgg
   16636 **     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
   16637 **     SF_FixedLimit == WHERE_USE_LIMIT
   16638 */
   16639 #define SF_Distinct       0x00001  /* Output should be DISTINCT */
   16640 #define SF_All            0x00002  /* Includes the ALL keyword */
   16641 #define SF_Resolved       0x00004  /* Identifiers have been resolved */
   16642 #define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
   16643 #define SF_HasAgg         0x00010  /* Contains aggregate functions */
   16644 #define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
   16645 #define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
   16646 #define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
   16647 #define SF_Compound       0x00100  /* Part of a compound query */
   16648 #define SF_Values         0x00200  /* Synthesized from VALUES clause */
   16649 #define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
   16650 #define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
   16651 #define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
   16652 #define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
   16653 #define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
   16654 #define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
   16655 #define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
   16656 #define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
   16657 #define SF_ComplexResult  0x40000  /* Result set contains subquery or function */
   16658 
   16659 
   16660 /*
   16661 ** The results of a SELECT can be distributed in several ways, as defined
   16662 ** by one of the following macros.  The "SRT" prefix means "SELECT Result
   16663 ** Type".
   16664 **
   16665 **     SRT_Union       Store results as a key in a temporary index
   16666 **                     identified by pDest->iSDParm.
   16667 **
   16668 **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
   16669 **
   16670 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
   16671 **                     set is not empty.
   16672 **
   16673 **     SRT_Discard     Throw the results away.  This is used by SELECT
   16674 **                     statements within triggers whose only purpose is
   16675 **                     the side-effects of functions.
   16676 **
   16677 ** All of the above are free to ignore their ORDER BY clause. Those that
   16678 ** follow must honor the ORDER BY clause.
   16679 **
   16680 **     SRT_Output      Generate a row of output (using the OP_ResultRow
   16681 **                     opcode) for each row in the result set.
   16682 **
   16683 **     SRT_Mem         Only valid if the result is a single column.
   16684 **                     Store the first column of the first result row
   16685 **                     in register pDest->iSDParm then abandon the rest
   16686 **                     of the query.  This destination implies "LIMIT 1".
   16687 **
   16688 **     SRT_Set         The result must be a single column.  Store each
   16689 **                     row of result as the key in table pDest->iSDParm.
   16690 **                     Apply the affinity pDest->affSdst before storing
   16691 **                     results.  Used to implement "IN (SELECT ...)".
   16692 **
   16693 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
   16694 **                     the result there. The cursor is left open after
   16695 **                     returning.  This is like SRT_Table except that
   16696 **                     this destination uses OP_OpenEphemeral to create
   16697 **                     the table first.
   16698 **
   16699 **     SRT_Coroutine   Generate a co-routine that returns a new row of
   16700 **                     results each time it is invoked.  The entry point
   16701 **                     of the co-routine is stored in register pDest->iSDParm
   16702 **                     and the result row is stored in pDest->nDest registers
   16703 **                     starting with pDest->iSdst.
   16704 **
   16705 **     SRT_Table       Store results in temporary table pDest->iSDParm.
   16706 **     SRT_Fifo        This is like SRT_EphemTab except that the table
   16707 **                     is assumed to already be open.  SRT_Fifo has
   16708 **                     the additional property of being able to ignore
   16709 **                     the ORDER BY clause.
   16710 **
   16711 **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
   16712 **                     But also use temporary table pDest->iSDParm+1 as
   16713 **                     a record of all prior results and ignore any duplicate
   16714 **                     rows.  Name means:  "Distinct Fifo".
   16715 **
   16716 **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
   16717 **                     an index).  Append a sequence number so that all entries
   16718 **                     are distinct.
   16719 **
   16720 **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
   16721 **                     the same record has never been stored before.  The
   16722 **                     index at pDest->iSDParm+1 hold all prior stores.
   16723 */
   16724 #define SRT_Union        1  /* Store result as keys in an index */
   16725 #define SRT_Except       2  /* Remove result from a UNION index */
   16726 #define SRT_Exists       3  /* Store 1 if the result is not empty */
   16727 #define SRT_Discard      4  /* Do not save the results anywhere */
   16728 #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
   16729 #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
   16730 #define SRT_Queue        7  /* Store result in an queue */
   16731 #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
   16732 
   16733 /* The ORDER BY clause is ignored for all of the above */
   16734 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
   16735 
   16736 #define SRT_Output       9  /* Output each row of result */
   16737 #define SRT_Mem         10  /* Store result in a memory cell */
   16738 #define SRT_Set         11  /* Store results as keys in an index */
   16739 #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
   16740 #define SRT_Coroutine   13  /* Generate a single row of result */
   16741 #define SRT_Table       14  /* Store result as data with an automatic rowid */
   16742 
   16743 /*
   16744 ** An instance of this object describes where to put of the results of
   16745 ** a SELECT statement.
   16746 */
   16747 struct SelectDest {
   16748   u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
   16749   int iSDParm;         /* A parameter used by the eDest disposal method */
   16750   int iSdst;           /* Base register where results are written */
   16751   int nSdst;           /* Number of registers allocated */
   16752   char *zAffSdst;      /* Affinity used when eDest==SRT_Set */
   16753   ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
   16754 };
   16755 
   16756 /*
   16757 ** During code generation of statements that do inserts into AUTOINCREMENT
   16758 ** tables, the following information is attached to the Table.u.autoInc.p
   16759 ** pointer of each autoincrement table to record some side information that
   16760 ** the code generator needs.  We have to keep per-table autoincrement
   16761 ** information in case inserts are done within triggers.  Triggers do not
   16762 ** normally coordinate their activities, but we do need to coordinate the
   16763 ** loading and saving of autoincrement information.
   16764 */
   16765 struct AutoincInfo {
   16766   AutoincInfo *pNext;   /* Next info block in a list of them all */
   16767   Table *pTab;          /* Table this info block refers to */
   16768   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
   16769   int regCtr;           /* Memory register holding the rowid counter */
   16770 };
   16771 
   16772 /*
   16773 ** Size of the column cache
   16774 */
   16775 #ifndef SQLITE_N_COLCACHE
   16776 # define SQLITE_N_COLCACHE 10
   16777 #endif
   16778 
   16779 /*
   16780 ** At least one instance of the following structure is created for each
   16781 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
   16782 ** statement. All such objects are stored in the linked list headed at
   16783 ** Parse.pTriggerPrg and deleted once statement compilation has been
   16784 ** completed.
   16785 **
   16786 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
   16787 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
   16788 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
   16789 ** The Parse.pTriggerPrg list never contains two entries with the same
   16790 ** values for both pTrigger and orconf.
   16791 **
   16792 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
   16793 ** accessed (or set to 0 for triggers fired as a result of INSERT
   16794 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
   16795 ** a mask of new.* columns used by the program.
   16796 */
   16797 struct TriggerPrg {
   16798   Trigger *pTrigger;      /* Trigger this program was coded from */
   16799   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
   16800   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
   16801   int orconf;             /* Default ON CONFLICT policy */
   16802   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
   16803 };
   16804 
   16805 /*
   16806 ** The yDbMask datatype for the bitmask of all attached databases.
   16807 */
   16808 #if SQLITE_MAX_ATTACHED>30
   16809   typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
   16810 # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
   16811 # define DbMaskZero(M)      memset((M),0,sizeof(M))
   16812 # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
   16813 # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
   16814 # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
   16815 #else
   16816   typedef unsigned int yDbMask;
   16817 # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
   16818 # define DbMaskZero(M)      (M)=0
   16819 # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
   16820 # define DbMaskAllZero(M)   (M)==0
   16821 # define DbMaskNonZero(M)   (M)!=0
   16822 #endif
   16823 
   16824 /*
   16825 ** An SQL parser context.  A copy of this structure is passed through
   16826 ** the parser and down into all the parser action routine in order to
   16827 ** carry around information that is global to the entire parse.
   16828 **
   16829 ** The structure is divided into two parts.  When the parser and code
   16830 ** generate call themselves recursively, the first part of the structure
   16831 ** is constant but the second part is reset at the beginning and end of
   16832 ** each recursion.
   16833 **
   16834 ** The nTableLock and aTableLock variables are only used if the shared-cache
   16835 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
   16836 ** used to store the set of table-locks required by the statement being
   16837 ** compiled. Function sqlite3TableLock() is used to add entries to the
   16838 ** list.
   16839 */
   16840 struct Parse {
   16841   sqlite3 *db;         /* The main database structure */
   16842   char *zErrMsg;       /* An error message */
   16843   Vdbe *pVdbe;         /* An engine for executing database bytecode */
   16844   int rc;              /* Return code from execution */
   16845   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
   16846   u8 checkSchema;      /* Causes schema cookie check after an error */
   16847   u8 nested;           /* Number of nested calls to the parser/code generator */
   16848   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
   16849   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
   16850   u8 mayAbort;         /* True if statement may throw an ABORT exception */
   16851   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
   16852   u8 okConstFactor;    /* OK to factor out constants */
   16853   u8 disableLookaside; /* Number of times lookaside has been disabled */
   16854   u8 nColCache;        /* Number of entries in aColCache[] */
   16855   int nRangeReg;       /* Size of the temporary register block */
   16856   int iRangeReg;       /* First register in temporary register block */
   16857   int nErr;            /* Number of errors seen */
   16858   int nTab;            /* Number of previously allocated VDBE cursors */
   16859   int nMem;            /* Number of memory cells used so far */
   16860   int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
   16861   int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
   16862   int iSelfTab;        /* Table associated with an index on expr, or negative
   16863                        ** of the base register during check-constraint eval */
   16864   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
   16865   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
   16866   int nLabel;          /* Number of labels used */
   16867   int *aLabel;         /* Space to hold the labels */
   16868   ExprList *pConstExpr;/* Constant expressions */
   16869   Token constraintName;/* Name of the constraint currently being parsed */
   16870   yDbMask writeMask;   /* Start a write transaction on these databases */
   16871   yDbMask cookieMask;  /* Bitmask of schema verified databases */
   16872   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
   16873   int regRoot;         /* Register holding root page number for new objects */
   16874   int nMaxArg;         /* Max args passed to user function by sub-program */
   16875 #if SELECTTRACE_ENABLED
   16876   int nSelect;         /* Number of SELECT statements seen */
   16877   int nSelectIndent;   /* How far to indent SELECTTRACE() output */
   16878 #endif
   16879 #ifndef SQLITE_OMIT_SHARED_CACHE
   16880   int nTableLock;        /* Number of locks in aTableLock */
   16881   TableLock *aTableLock; /* Required table locks for shared-cache mode */
   16882 #endif
   16883   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
   16884   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   16885   Table *pTriggerTab;  /* Table triggers are being coded for */
   16886   int addrCrTab;       /* Address of OP_CreateBtree opcode on CREATE TABLE */
   16887   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
   16888   u32 oldmask;         /* Mask of old.* columns referenced */
   16889   u32 newmask;         /* Mask of new.* columns referenced */
   16890   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
   16891   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
   16892   u8 disableTriggers;  /* True to disable triggers */
   16893 
   16894   /**************************************************************************
   16895   ** Fields above must be initialized to zero.  The fields that follow,
   16896   ** down to the beginning of the recursive section, do not need to be
   16897   ** initialized as they will be set before being used.  The boundary is
   16898   ** determined by offsetof(Parse,aColCache).
   16899   **************************************************************************/
   16900 
   16901   struct yColCache {
   16902     int iTable;           /* Table cursor number */
   16903     i16 iColumn;          /* Table column number */
   16904     u8 tempReg;           /* iReg is a temp register that needs to be freed */
   16905     int iLevel;           /* Nesting level */
   16906     int iReg;             /* Reg with value of this column. 0 means none. */
   16907     int lru;              /* Least recently used entry has the smallest value */
   16908   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
   16909   int aTempReg[8];        /* Holding area for temporary registers */
   16910   Token sNameToken;       /* Token with unqualified schema object name */
   16911 
   16912   /************************************************************************
   16913   ** Above is constant between recursions.  Below is reset before and after
   16914   ** each recursion.  The boundary between these two regions is determined
   16915   ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
   16916   ** first field in the recursive region.
   16917   ************************************************************************/
   16918 
   16919   Token sLastToken;       /* The last token parsed */
   16920   ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
   16921   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
   16922   u8 explain;               /* True if the EXPLAIN flag is found on the query */
   16923 #ifndef SQLITE_OMIT_VIRTUALTABLE
   16924   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
   16925   int nVtabLock;            /* Number of virtual tables to lock */
   16926 #endif
   16927   int nHeight;              /* Expression tree height of current sub-select */
   16928 #ifndef SQLITE_OMIT_EXPLAIN
   16929   int iSelectId;            /* ID of current select for EXPLAIN output */
   16930   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
   16931 #endif
   16932   VList *pVList;            /* Mapping between variable names and numbers */
   16933   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
   16934   const char *zTail;        /* All SQL text past the last semicolon parsed */
   16935   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
   16936   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
   16937   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
   16938 #ifndef SQLITE_OMIT_VIRTUALTABLE
   16939   Token sArg;               /* Complete text of a module argument */
   16940   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
   16941 #endif
   16942   Table *pZombieTab;        /* List of Table objects to delete after code gen */
   16943   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
   16944   With *pWith;              /* Current WITH clause, or NULL */
   16945   With *pWithToFree;        /* Free this WITH object at the end of the parse */
   16946 };
   16947 
   16948 /*
   16949 ** Sizes and pointers of various parts of the Parse object.
   16950 */
   16951 #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
   16952 #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
   16953 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
   16954 #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
   16955 
   16956 /*
   16957 ** Return true if currently inside an sqlite3_declare_vtab() call.
   16958 */
   16959 #ifdef SQLITE_OMIT_VIRTUALTABLE
   16960   #define IN_DECLARE_VTAB 0
   16961 #else
   16962   #define IN_DECLARE_VTAB (pParse->declareVtab)
   16963 #endif
   16964 
   16965 /*
   16966 ** An instance of the following structure can be declared on a stack and used
   16967 ** to save the Parse.zAuthContext value so that it can be restored later.
   16968 */
   16969 struct AuthContext {
   16970   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
   16971   Parse *pParse;              /* The Parse structure */
   16972 };
   16973 
   16974 /*
   16975 ** Bitfield flags for P5 value in various opcodes.
   16976 **
   16977 ** Value constraints (enforced via assert()):
   16978 **    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
   16979 **    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
   16980 **    OPFLAG_BULKCSR      == BTREE_BULKLOAD
   16981 **    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
   16982 **    OPFLAG_FORDELETE    == BTREE_FORDELETE
   16983 **    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
   16984 **    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
   16985 */
   16986 #define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
   16987                                      /* Also used in P2 (not P5) of OP_Delete */
   16988 #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
   16989 #define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
   16990 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
   16991 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
   16992 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
   16993 #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
   16994 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
   16995 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
   16996 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
   16997 #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
   16998 #define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
   16999 #define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
   17000 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
   17001 #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
   17002 #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
   17003 #define OPFLAG_NOCHNG_MAGIC  0x6d    /* OP_MakeRecord: serialtype 10 is ok */
   17004 
   17005 /*
   17006  * Each trigger present in the database schema is stored as an instance of
   17007  * struct Trigger.
   17008  *
   17009  * Pointers to instances of struct Trigger are stored in two ways.
   17010  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
   17011  *    database). This allows Trigger structures to be retrieved by name.
   17012  * 2. All triggers associated with a single table form a linked list, using the
   17013  *    pNext member of struct Trigger. A pointer to the first element of the
   17014  *    linked list is stored as the "pTrigger" member of the associated
   17015  *    struct Table.
   17016  *
   17017  * The "step_list" member points to the first element of a linked list
   17018  * containing the SQL statements specified as the trigger program.
   17019  */
   17020 struct Trigger {
   17021   char *zName;            /* The name of the trigger                        */
   17022   char *table;            /* The table or view to which the trigger applies */
   17023   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
   17024   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   17025   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
   17026   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
   17027                              the <column-list> is stored here */
   17028   Schema *pSchema;        /* Schema containing the trigger */
   17029   Schema *pTabSchema;     /* Schema containing the table */
   17030   TriggerStep *step_list; /* Link list of trigger program steps             */
   17031   Trigger *pNext;         /* Next trigger associated with the table */
   17032 };
   17033 
   17034 /*
   17035 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
   17036 ** determine which.
   17037 **
   17038 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
   17039 ** In that cases, the constants below can be ORed together.
   17040 */
   17041 #define TRIGGER_BEFORE  1
   17042 #define TRIGGER_AFTER   2
   17043 
   17044 /*
   17045  * An instance of struct TriggerStep is used to store a single SQL statement
   17046  * that is a part of a trigger-program.
   17047  *
   17048  * Instances of struct TriggerStep are stored in a singly linked list (linked
   17049  * using the "pNext" member) referenced by the "step_list" member of the
   17050  * associated struct Trigger instance. The first element of the linked list is
   17051  * the first step of the trigger-program.
   17052  *
   17053  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
   17054  * "SELECT" statement. The meanings of the other members is determined by the
   17055  * value of "op" as follows:
   17056  *
   17057  * (op == TK_INSERT)
   17058  * orconf    -> stores the ON CONFLICT algorithm
   17059  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
   17060  *              this stores a pointer to the SELECT statement. Otherwise NULL.
   17061  * zTarget   -> Dequoted name of the table to insert into.
   17062  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
   17063  *              this stores values to be inserted. Otherwise NULL.
   17064  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
   17065  *              statement, then this stores the column-names to be
   17066  *              inserted into.
   17067  *
   17068  * (op == TK_DELETE)
   17069  * zTarget   -> Dequoted name of the table to delete from.
   17070  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
   17071  *              Otherwise NULL.
   17072  *
   17073  * (op == TK_UPDATE)
   17074  * zTarget   -> Dequoted name of the table to update.
   17075  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
   17076  *              Otherwise NULL.
   17077  * pExprList -> A list of the columns to update and the expressions to update
   17078  *              them to. See sqlite3Update() documentation of "pChanges"
   17079  *              argument.
   17080  *
   17081  */
   17082 struct TriggerStep {
   17083   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
   17084   u8 orconf;           /* OE_Rollback etc. */
   17085   Trigger *pTrig;      /* The trigger that this step is a part of */
   17086   Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
   17087   char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
   17088   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
   17089   ExprList *pExprList; /* SET clause for UPDATE. */
   17090   IdList *pIdList;     /* Column names for INSERT */
   17091   char *zSpan;         /* Original SQL text of this command */
   17092   TriggerStep *pNext;  /* Next in the link-list */
   17093   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
   17094 };
   17095 
   17096 /*
   17097 ** The following structure contains information used by the sqliteFix...
   17098 ** routines as they walk the parse tree to make database references
   17099 ** explicit.
   17100 */
   17101 typedef struct DbFixer DbFixer;
   17102 struct DbFixer {
   17103   Parse *pParse;      /* The parsing context.  Error messages written here */
   17104   Schema *pSchema;    /* Fix items to this schema */
   17105   int bVarOnly;       /* Check for variable references only */
   17106   const char *zDb;    /* Make sure all objects are contained in this database */
   17107   const char *zType;  /* Type of the container - used for error messages */
   17108   const Token *pName; /* Name of the container - used for error messages */
   17109 };
   17110 
   17111 /*
   17112 ** An objected used to accumulate the text of a string where we
   17113 ** do not necessarily know how big the string will be in the end.
   17114 */
   17115 struct StrAccum {
   17116   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
   17117   char *zText;         /* The string collected so far */
   17118   u32  nAlloc;         /* Amount of space allocated in zText */
   17119   u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
   17120   u32  nChar;          /* Length of the string so far */
   17121   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
   17122   u8   printfFlags;    /* SQLITE_PRINTF flags below */
   17123 };
   17124 #define STRACCUM_NOMEM   1
   17125 #define STRACCUM_TOOBIG  2
   17126 #define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
   17127 #define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
   17128 #define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
   17129 
   17130 #define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
   17131 
   17132 
   17133 /*
   17134 ** A pointer to this structure is used to communicate information
   17135 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
   17136 */
   17137 typedef struct {
   17138   sqlite3 *db;        /* The database being initialized */
   17139   char **pzErrMsg;    /* Error message stored here */
   17140   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
   17141   int rc;             /* Result code stored here */
   17142 } InitData;
   17143 
   17144 /*
   17145 ** Structure containing global configuration data for the SQLite library.
   17146 **
   17147 ** This structure also contains some state information.
   17148 */
   17149 struct Sqlite3Config {
   17150   int bMemstat;                     /* True to enable memory status */
   17151   int bCoreMutex;                   /* True to enable core mutexing */
   17152   int bFullMutex;                   /* True to enable full mutexing */
   17153   int bOpenUri;                     /* True to interpret filenames as URIs */
   17154   int bUseCis;                      /* Use covering indices for full-scans */
   17155   int bSmallMalloc;                 /* Avoid large memory allocations if true */
   17156   int mxStrlen;                     /* Maximum string length */
   17157   int neverCorrupt;                 /* Database is always well-formed */
   17158   int szLookaside;                  /* Default lookaside buffer size */
   17159   int nLookaside;                   /* Default lookaside buffer count */
   17160   int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
   17161   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
   17162   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
   17163   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
   17164   void *pHeap;                      /* Heap storage space */
   17165   int nHeap;                        /* Size of pHeap[] */
   17166   int mnReq, mxReq;                 /* Min and max heap requests sizes */
   17167   sqlite3_int64 szMmap;             /* mmap() space per open file */
   17168   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
   17169   void *pPage;                      /* Page cache memory */
   17170   int szPage;                       /* Size of each page in pPage[] */
   17171   int nPage;                        /* Number of pages in pPage[] */
   17172   int mxParserStack;                /* maximum depth of the parser stack */
   17173   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
   17174   u32 szPma;                        /* Maximum Sorter PMA size */
   17175   /* The above might be initialized to non-zero.  The following need to always
   17176   ** initially be zero, however. */
   17177   int isInit;                       /* True after initialization has finished */
   17178   int inProgress;                   /* True while initialization in progress */
   17179   int isMutexInit;                  /* True after mutexes are initialized */
   17180   int isMallocInit;                 /* True after malloc is initialized */
   17181   int isPCacheInit;                 /* True after malloc is initialized */
   17182   int nRefInitMutex;                /* Number of users of pInitMutex */
   17183   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
   17184   void (*xLog)(void*,int,const char*); /* Function for logging */
   17185   void *pLogArg;                       /* First argument to xLog() */
   17186 #ifdef SQLITE_ENABLE_SQLLOG
   17187   void(*xSqllog)(void*,sqlite3*,const char*, int);
   17188   void *pSqllogArg;
   17189 #endif
   17190 #ifdef SQLITE_VDBE_COVERAGE
   17191   /* The following callback (if not NULL) is invoked on every VDBE branch
   17192   ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
   17193   */
   17194   void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
   17195   void *pVdbeBranchArg;                                     /* 1st argument */
   17196 #endif
   17197 #ifndef SQLITE_UNTESTABLE
   17198   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
   17199 #endif
   17200   int bLocaltimeFault;              /* True to fail localtime() calls */
   17201   int iOnceResetThreshold;          /* When to reset OP_Once counters */
   17202 };
   17203 
   17204 /*
   17205 ** This macro is used inside of assert() statements to indicate that
   17206 ** the assert is only valid on a well-formed database.  Instead of:
   17207 **
   17208 **     assert( X );
   17209 **
   17210 ** One writes:
   17211 **
   17212 **     assert( X || CORRUPT_DB );
   17213 **
   17214 ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
   17215 ** that the database is definitely corrupt, only that it might be corrupt.
   17216 ** For most test cases, CORRUPT_DB is set to false using a special
   17217 ** sqlite3_test_control().  This enables assert() statements to prove
   17218 ** things that are always true for well-formed databases.
   17219 */
   17220 #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
   17221 
   17222 /*
   17223 ** Context pointer passed down through the tree-walk.
   17224 */
   17225 struct Walker {
   17226   Parse *pParse;                            /* Parser context.  */
   17227   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
   17228   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
   17229   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
   17230   int walkerDepth;                          /* Number of subqueries */
   17231   u8 eCode;                                 /* A small processing code */
   17232   union {                                   /* Extra data for callback */
   17233     NameContext *pNC;                         /* Naming context */
   17234     int n;                                    /* A counter */
   17235     int iCur;                                 /* A cursor number */
   17236     SrcList *pSrcList;                        /* FROM clause */
   17237     struct SrcCount *pSrcCount;               /* Counting column references */
   17238     struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
   17239     int *aiCol;                               /* array of column indexes */
   17240     struct IdxCover *pIdxCover;               /* Check for index coverage */
   17241     struct IdxExprTrans *pIdxTrans;           /* Convert indexed expr to column */
   17242     ExprList *pGroupBy;                       /* GROUP BY clause */
   17243     struct HavingToWhereCtx *pHavingCtx;      /* HAVING to WHERE clause ctx */
   17244   } u;
   17245 };
   17246 
   17247 /* Forward declarations */
   17248 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
   17249 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
   17250 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
   17251 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
   17252 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
   17253 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
   17254 SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
   17255 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
   17256 #ifdef SQLITE_DEBUG
   17257 SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
   17258 #endif
   17259 
   17260 /*
   17261 ** Return code from the parse-tree walking primitives and their
   17262 ** callbacks.
   17263 */
   17264 #define WRC_Continue    0   /* Continue down into children */
   17265 #define WRC_Prune       1   /* Omit children but continue walking siblings */
   17266 #define WRC_Abort       2   /* Abandon the tree walk */
   17267 
   17268 /*
   17269 ** An instance of this structure represents a set of one or more CTEs
   17270 ** (common table expressions) created by a single WITH clause.
   17271 */
   17272 struct With {
   17273   int nCte;                       /* Number of CTEs in the WITH clause */
   17274   With *pOuter;                   /* Containing WITH clause, or NULL */
   17275   struct Cte {                    /* For each CTE in the WITH clause.... */
   17276     char *zName;                    /* Name of this CTE */
   17277     ExprList *pCols;                /* List of explicit column names, or NULL */
   17278     Select *pSelect;                /* The definition of this CTE */
   17279     const char *zCteErr;            /* Error message for circular references */
   17280   } a[1];
   17281 };
   17282 
   17283 #ifdef SQLITE_DEBUG
   17284 /*
   17285 ** An instance of the TreeView object is used for printing the content of
   17286 ** data structures on sqlite3DebugPrintf() using a tree-like view.
   17287 */
   17288 struct TreeView {
   17289   int iLevel;             /* Which level of the tree we are on */
   17290   u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
   17291 };
   17292 #endif /* SQLITE_DEBUG */
   17293 
   17294 /*
   17295 ** Assuming zIn points to the first byte of a UTF-8 character,
   17296 ** advance zIn to point to the first byte of the next UTF-8 character.
   17297 */
   17298 #define SQLITE_SKIP_UTF8(zIn) {                        \
   17299   if( (*(zIn++))>=0xc0 ){                              \
   17300     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
   17301   }                                                    \
   17302 }
   17303 
   17304 /*
   17305 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
   17306 ** the same name but without the _BKPT suffix.  These macros invoke
   17307 ** routines that report the line-number on which the error originated
   17308 ** using sqlite3_log().  The routines also provide a convenient place
   17309 ** to set a debugger breakpoint.
   17310 */
   17311 SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
   17312 SQLITE_PRIVATE int sqlite3CorruptError(int);
   17313 SQLITE_PRIVATE int sqlite3MisuseError(int);
   17314 SQLITE_PRIVATE int sqlite3CantopenError(int);
   17315 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
   17316 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
   17317 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
   17318 #ifdef SQLITE_DEBUG
   17319 SQLITE_PRIVATE   int sqlite3NomemError(int);
   17320 SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
   17321 SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);
   17322 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
   17323 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
   17324 # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
   17325 #else
   17326 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
   17327 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
   17328 # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
   17329 #endif
   17330 
   17331 /*
   17332 ** FTS3 and FTS4 both require virtual table support
   17333 */
   17334 #if defined(SQLITE_OMIT_VIRTUALTABLE)
   17335 # undef SQLITE_ENABLE_FTS3
   17336 # undef SQLITE_ENABLE_FTS4
   17337 #endif
   17338 
   17339 /*
   17340 ** FTS4 is really an extension for FTS3.  It is enabled using the
   17341 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
   17342 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
   17343 */
   17344 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   17345 # define SQLITE_ENABLE_FTS3 1
   17346 #endif
   17347 
   17348 /*
   17349 ** The ctype.h header is needed for non-ASCII systems.  It is also
   17350 ** needed by FTS3 when FTS3 is included in the amalgamation.
   17351 */
   17352 #if !defined(SQLITE_ASCII) || \
   17353     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
   17354 # include <ctype.h>
   17355 #endif
   17356 
   17357 /*
   17358 ** The following macros mimic the standard library functions toupper(),
   17359 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
   17360 ** sqlite versions only work for ASCII characters, regardless of locale.
   17361 */
   17362 #ifdef SQLITE_ASCII
   17363 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
   17364 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
   17365 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
   17366 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
   17367 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
   17368 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
   17369 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
   17370 # define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
   17371 #else
   17372 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
   17373 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
   17374 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
   17375 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
   17376 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
   17377 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
   17378 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
   17379 # define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
   17380 #endif
   17381 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   17382 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
   17383 #endif
   17384 
   17385 /*
   17386 ** Internal function prototypes
   17387 */
   17388 SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
   17389 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
   17390 SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
   17391 #define sqlite3StrNICmp sqlite3_strnicmp
   17392 
   17393 SQLITE_PRIVATE int sqlite3MallocInit(void);
   17394 SQLITE_PRIVATE void sqlite3MallocEnd(void);
   17395 SQLITE_PRIVATE void *sqlite3Malloc(u64);
   17396 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
   17397 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
   17398 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
   17399 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
   17400 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
   17401 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
   17402 SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
   17403 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
   17404 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
   17405 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
   17406 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
   17407 SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
   17408 SQLITE_PRIVATE int sqlite3MallocSize(void*);
   17409 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
   17410 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
   17411 SQLITE_PRIVATE void sqlite3PageFree(void*);
   17412 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
   17413 #ifndef SQLITE_UNTESTABLE
   17414 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
   17415 #endif
   17416 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
   17417 
   17418 /*
   17419 ** On systems with ample stack space and that support alloca(), make
   17420 ** use of alloca() to obtain space for large automatic objects.  By default,
   17421 ** obtain space from malloc().
   17422 **
   17423 ** The alloca() routine never returns NULL.  This will cause code paths
   17424 ** that deal with sqlite3StackAlloc() failures to be unreachable.
   17425 */
   17426 #ifdef SQLITE_USE_ALLOCA
   17427 # define sqlite3StackAllocRaw(D,N)   alloca(N)
   17428 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
   17429 # define sqlite3StackFree(D,P)
   17430 #else
   17431 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
   17432 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
   17433 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
   17434 #endif
   17435 
   17436 /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
   17437 ** are, disable MEMSYS3
   17438 */
   17439 #ifdef SQLITE_ENABLE_MEMSYS5
   17440 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
   17441 #undef SQLITE_ENABLE_MEMSYS3
   17442 #endif
   17443 #ifdef SQLITE_ENABLE_MEMSYS3
   17444 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
   17445 #endif
   17446 
   17447 
   17448 #ifndef SQLITE_MUTEX_OMIT
   17449 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
   17450 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
   17451 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
   17452 SQLITE_PRIVATE   int sqlite3MutexInit(void);
   17453 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
   17454 #endif
   17455 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
   17456 SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
   17457 #else
   17458 # define sqlite3MemoryBarrier()
   17459 #endif
   17460 
   17461 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
   17462 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
   17463 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
   17464 SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
   17465 SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
   17466 
   17467 /* Access to mutexes used by sqlite3_status() */
   17468 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
   17469 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
   17470 
   17471 #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
   17472 SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
   17473 #else
   17474 # define sqlite3MutexWarnOnContention(x)
   17475 #endif
   17476 
   17477 #ifndef SQLITE_OMIT_FLOATING_POINT
   17478 SQLITE_PRIVATE   int sqlite3IsNaN(double);
   17479 #else
   17480 # define sqlite3IsNaN(X)  0
   17481 #endif
   17482 
   17483 /*
   17484 ** An instance of the following structure holds information about SQL
   17485 ** functions arguments that are the parameters to the printf() function.
   17486 */
   17487 struct PrintfArguments {
   17488   int nArg;                /* Total number of arguments */
   17489   int nUsed;               /* Number of arguments used so far */
   17490   sqlite3_value **apArg;   /* The argument values */
   17491 };
   17492 
   17493 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
   17494 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
   17495 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
   17496 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
   17497 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
   17498 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
   17499 #endif
   17500 #if defined(SQLITE_TEST)
   17501 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
   17502 #endif
   17503 
   17504 #if defined(SQLITE_DEBUG)
   17505 SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
   17506 SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
   17507 SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
   17508 SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
   17509 SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
   17510 #endif
   17511 
   17512 
   17513 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
   17514 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
   17515 SQLITE_PRIVATE void sqlite3Dequote(char*);
   17516 SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
   17517 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
   17518 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
   17519 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
   17520 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
   17521 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
   17522 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
   17523 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
   17524 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
   17525 #ifdef SQLITE_DEBUG
   17526 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
   17527 #endif
   17528 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
   17529 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
   17530 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
   17531 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
   17532 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
   17533 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
   17534 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
   17535 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
   17536 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
   17537 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
   17538 SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
   17539 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
   17540 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
   17541 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
   17542 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
   17543 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
   17544 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
   17545 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
   17546 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
   17547 #ifndef SQLITE_OMIT_VIRTUALTABLE
   17548 SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
   17549 #endif
   17550 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
   17551 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
   17552 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
   17553 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
   17554 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
   17555 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
   17556 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
   17557 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
   17558 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
   17559 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
   17560 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
   17561 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
   17562 #if SQLITE_ENABLE_HIDDEN_COLUMNS
   17563 SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
   17564 #else
   17565 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
   17566 #endif
   17567 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
   17568 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
   17569 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
   17570 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
   17571 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
   17572 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
   17573 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
   17574 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
   17575                     sqlite3_vfs**,char**,char **);
   17576 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
   17577 
   17578 #ifdef SQLITE_UNTESTABLE
   17579 # define sqlite3FaultSim(X) SQLITE_OK
   17580 #else
   17581 SQLITE_PRIVATE   int sqlite3FaultSim(int);
   17582 #endif
   17583 
   17584 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
   17585 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
   17586 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
   17587 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
   17588 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
   17589 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
   17590 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
   17591 #ifndef SQLITE_UNTESTABLE
   17592 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
   17593 #endif
   17594 
   17595 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
   17596 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
   17597 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
   17598 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
   17599 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
   17600 
   17601 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
   17602 
   17603 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   17604 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
   17605 #else
   17606 # define sqlite3ViewGetColumnNames(A,B) 0
   17607 #endif
   17608 
   17609 #if SQLITE_MAX_ATTACHED>30
   17610 SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
   17611 #endif
   17612 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
   17613 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
   17614 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
   17615 #ifndef SQLITE_OMIT_AUTOINCREMENT
   17616 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
   17617 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
   17618 #else
   17619 # define sqlite3AutoincrementBegin(X)
   17620 # define sqlite3AutoincrementEnd(X)
   17621 #endif
   17622 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
   17623 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
   17624 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
   17625 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
   17626 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
   17627 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
   17628 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
   17629                                       Token*, Select*, Expr*, IdList*);
   17630 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
   17631 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
   17632 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
   17633 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
   17634 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
   17635 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
   17636 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
   17637 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
   17638 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
   17639                           Expr*, int, int, u8);
   17640 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
   17641 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
   17642 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
   17643                          Expr*,ExprList*,u32,Expr*);
   17644 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
   17645 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
   17646 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
   17647 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
   17648 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   17649 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
   17650 #endif
   17651 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
   17652 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*);
   17653 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
   17654 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
   17655 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
   17656 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
   17657 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
   17658 SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
   17659 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
   17660 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
   17661 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
   17662 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
   17663 #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
   17664 #define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
   17665 #define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
   17666 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
   17667 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
   17668 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
   17669 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
   17670 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
   17671 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
   17672 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
   17673 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
   17674 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
   17675 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
   17676 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
   17677 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
   17678 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
   17679 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
   17680 SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
   17681 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
   17682 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
   17683 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
   17684 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
   17685 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
   17686 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
   17687 #define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
   17688 #define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
   17689 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
   17690 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
   17691 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
   17692 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
   17693 #define LOCATE_VIEW    0x01
   17694 #define LOCATE_NOERR   0x02
   17695 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
   17696 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
   17697 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
   17698 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
   17699 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
   17700 SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
   17701 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
   17702 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
   17703 SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
   17704 SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
   17705 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
   17706 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
   17707 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
   17708 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
   17709 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
   17710 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
   17711 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
   17712 #ifndef SQLITE_UNTESTABLE
   17713 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
   17714 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
   17715 #endif
   17716 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
   17717 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
   17718 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
   17719 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
   17720 SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
   17721 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
   17722 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
   17723 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
   17724 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
   17725 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
   17726 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
   17727 SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
   17728 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
   17729 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   17730 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
   17731 #endif
   17732 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
   17733 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
   17734 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
   17735 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
   17736 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   17737     Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
   17738 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
   17739 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
   17740 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
   17741 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
   17742                                      u8,u8,int,int*,int*);
   17743 #ifdef SQLITE_ENABLE_NULL_TRIM
   17744 SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);
   17745 #else
   17746 # define sqlite3SetMakeRecordP5(A,B)
   17747 #endif
   17748 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
   17749 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
   17750 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
   17751 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
   17752 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
   17753 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
   17754 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
   17755 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
   17756 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
   17757 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
   17758 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
   17759 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
   17760 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
   17761 #if SELECTTRACE_ENABLED
   17762 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
   17763 #else
   17764 # define sqlite3SelectSetName(A,B)
   17765 #endif
   17766 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
   17767 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
   17768 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
   17769 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
   17770 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
   17771 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
   17772 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
   17773 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
   17774 
   17775 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   17776 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
   17777 #endif
   17778 
   17779 #ifndef SQLITE_OMIT_TRIGGER
   17780 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
   17781                            Expr*,int, int);
   17782 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
   17783 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
   17784 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
   17785 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
   17786 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
   17787 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
   17788                             int, int, int);
   17789 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
   17790   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
   17791 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
   17792 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
   17793                                         const char*,const char*);
   17794 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
   17795                                         Select*,u8,const char*,const char*);
   17796 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8,
   17797                                         const char*,const char*);
   17798 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*,
   17799                                         const char*,const char*);
   17800 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
   17801 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
   17802 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
   17803 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
   17804 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
   17805 #else
   17806 # define sqlite3TriggersExist(B,C,D,E,F) 0
   17807 # define sqlite3DeleteTrigger(A,B)
   17808 # define sqlite3DropTriggerPtr(A,B)
   17809 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
   17810 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
   17811 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
   17812 # define sqlite3TriggerList(X, Y) 0
   17813 # define sqlite3ParseToplevel(p) p
   17814 # define sqlite3IsToplevel(p) 1
   17815 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
   17816 #endif
   17817 
   17818 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
   17819 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
   17820 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
   17821 #ifndef SQLITE_OMIT_AUTHORIZATION
   17822 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
   17823 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
   17824 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
   17825 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
   17826 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
   17827 #else
   17828 # define sqlite3AuthRead(a,b,c,d)
   17829 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
   17830 # define sqlite3AuthContextPush(a,b,c)
   17831 # define sqlite3AuthContextPop(a)  ((void)(a))
   17832 #endif
   17833 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
   17834 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
   17835 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
   17836 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
   17837 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
   17838 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
   17839 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
   17840 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
   17841 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
   17842 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
   17843 SQLITE_PRIVATE int sqlite3Atoi(const char*);
   17844 #ifndef SQLITE_OMIT_UTF16
   17845 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
   17846 #endif
   17847 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
   17848 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
   17849 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
   17850 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
   17851 #ifndef SQLITE_OMIT_VIRTUALTABLE
   17852 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
   17853 #endif
   17854 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
   17855     defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
   17856     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
   17857 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
   17858 #endif
   17859 SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
   17860 SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
   17861 SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
   17862 
   17863 /*
   17864 ** Routines to read and write variable-length integers.  These used to
   17865 ** be defined locally, but now we use the varint routines in the util.c
   17866 ** file.
   17867 */
   17868 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
   17869 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
   17870 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
   17871 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
   17872 
   17873 /*
   17874 ** The common case is for a varint to be a single byte.  They following
   17875 ** macros handle the common case without a procedure call, but then call
   17876 ** the procedure for larger varints.
   17877 */
   17878 #define getVarint32(A,B)  \
   17879   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
   17880 #define putVarint32(A,B)  \
   17881   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
   17882   sqlite3PutVarint((A),(B)))
   17883 #define getVarint    sqlite3GetVarint
   17884 #define putVarint    sqlite3PutVarint
   17885 
   17886 
   17887 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
   17888 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
   17889 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
   17890 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
   17891 SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
   17892 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
   17893 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
   17894 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
   17895 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
   17896 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
   17897 SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
   17898 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
   17899 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
   17900 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
   17901 
   17902 #if defined(SQLITE_NEED_ERR_NAME)
   17903 SQLITE_PRIVATE const char *sqlite3ErrName(int);
   17904 #endif
   17905 
   17906 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
   17907 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
   17908 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
   17909 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
   17910 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
   17911 SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
   17912 SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
   17913 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
   17914 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
   17915 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
   17916 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
   17917 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
   17918 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
   17919 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
   17920 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
   17921 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
   17922 SQLITE_PRIVATE int sqlite3AbsInt32(int);
   17923 #ifdef SQLITE_ENABLE_8_3_NAMES
   17924 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
   17925 #else
   17926 # define sqlite3FileSuffix3(X,Y)
   17927 #endif
   17928 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
   17929 
   17930 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
   17931 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
   17932 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
   17933                         void(*)(void*));
   17934 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
   17935 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
   17936 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
   17937 #ifndef SQLITE_OMIT_UTF16
   17938 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
   17939 #endif
   17940 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
   17941 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
   17942 #ifndef SQLITE_AMALGAMATION
   17943 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
   17944 SQLITE_PRIVATE const char sqlite3StrBINARY[];
   17945 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
   17946 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
   17947 SQLITE_PRIVATE const Token sqlite3IntTokens[];
   17948 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
   17949 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
   17950 #ifndef SQLITE_OMIT_WSD
   17951 SQLITE_PRIVATE int sqlite3PendingByte;
   17952 #endif
   17953 #endif
   17954 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
   17955 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
   17956 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
   17957 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
   17958 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
   17959 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
   17960 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
   17961 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
   17962 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
   17963 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
   17964 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
   17965 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
   17966 SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
   17967 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
   17968 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
   17969 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
   17970 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
   17971 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
   17972 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
   17973 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
   17974 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
   17975 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
   17976 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
   17977 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
   17978 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
   17979 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
   17980 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
   17981 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
   17982 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
   17983 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
   17984 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
   17985 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
   17986 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
   17987 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
   17988 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
   17989 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
   17990 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
   17991 #ifdef SQLITE_DEBUG
   17992 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
   17993 #endif
   17994 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   17995   void (*)(sqlite3_context*,int,sqlite3_value **),
   17996   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
   17997   FuncDestructor *pDestructor
   17998 );
   17999 SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
   18000 SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
   18001 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
   18002 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
   18003 
   18004 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
   18005 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
   18006 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
   18007 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
   18008 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
   18009 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
   18010 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
   18011 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
   18012 
   18013 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
   18014 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
   18015 
   18016 #ifndef SQLITE_OMIT_SUBQUERY
   18017 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
   18018 #else
   18019 # define sqlite3ExprCheckIN(x,y) SQLITE_OK
   18020 #endif
   18021 
   18022 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   18023 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
   18024 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
   18025     Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
   18026 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
   18027 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
   18028 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
   18029 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
   18030 #endif
   18031 
   18032 /*
   18033 ** The interface to the LEMON-generated parser
   18034 */
   18035 #ifndef SQLITE_AMALGAMATION
   18036 SQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64));
   18037 SQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));
   18038 #endif
   18039 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
   18040 #ifdef YYTRACKMAXSTACKDEPTH
   18041 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
   18042 #endif
   18043 
   18044 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
   18045 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   18046 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
   18047 #else
   18048 # define sqlite3CloseExtensions(X)
   18049 #endif
   18050 
   18051 #ifndef SQLITE_OMIT_SHARED_CACHE
   18052 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
   18053 #else
   18054   #define sqlite3TableLock(v,w,x,y,z)
   18055 #endif
   18056 
   18057 #ifdef SQLITE_TEST
   18058 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
   18059 #endif
   18060 
   18061 #ifdef SQLITE_OMIT_VIRTUALTABLE
   18062 #  define sqlite3VtabClear(Y)
   18063 #  define sqlite3VtabSync(X,Y) SQLITE_OK
   18064 #  define sqlite3VtabRollback(X)
   18065 #  define sqlite3VtabCommit(X)
   18066 #  define sqlite3VtabInSync(db) 0
   18067 #  define sqlite3VtabLock(X)
   18068 #  define sqlite3VtabUnlock(X)
   18069 #  define sqlite3VtabUnlockList(X)
   18070 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
   18071 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
   18072 #else
   18073 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
   18074 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
   18075 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
   18076 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
   18077 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
   18078 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
   18079 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
   18080 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
   18081 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
   18082 SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
   18083 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
   18084 SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(
   18085      sqlite3*,
   18086      const char*,
   18087      const sqlite3_module*,
   18088      void*,
   18089      void(*)(void*)
   18090    );
   18091 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
   18092 #endif
   18093 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
   18094 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
   18095 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
   18096 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
   18097 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
   18098 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
   18099 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
   18100 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
   18101 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
   18102 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
   18103 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
   18104 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
   18105 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
   18106 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
   18107 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
   18108 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
   18109 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
   18110 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
   18111 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
   18112 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
   18113 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
   18114 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
   18115 #ifndef SQLITE_OMIT_WAL
   18116 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
   18117 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
   18118 #endif
   18119 #ifndef SQLITE_OMIT_CTE
   18120 SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
   18121 SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
   18122 SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
   18123 #else
   18124 #define sqlite3WithPush(x,y,z)
   18125 #define sqlite3WithDelete(x,y)
   18126 #endif
   18127 
   18128 /* Declarations for functions in fkey.c. All of these are replaced by
   18129 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
   18130 ** key functionality is available. If OMIT_TRIGGER is defined but
   18131 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
   18132 ** this case foreign keys are parsed, but no other functionality is
   18133 ** provided (enforcement of FK constraints requires the triggers sub-system).
   18134 */
   18135 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   18136 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
   18137 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
   18138 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
   18139 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
   18140 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
   18141 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
   18142 #else
   18143   #define sqlite3FkActions(a,b,c,d,e,f)
   18144   #define sqlite3FkCheck(a,b,c,d,e,f)
   18145   #define sqlite3FkDropTable(a,b,c)
   18146   #define sqlite3FkOldmask(a,b)         0
   18147   #define sqlite3FkRequired(a,b,c,d)    0
   18148   #define sqlite3FkReferences(a)        0
   18149 #endif
   18150 #ifndef SQLITE_OMIT_FOREIGN_KEY
   18151 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
   18152 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
   18153 #else
   18154   #define sqlite3FkDelete(a,b)
   18155   #define sqlite3FkLocateIndex(a,b,c,d,e)
   18156 #endif
   18157 
   18158 
   18159 /*
   18160 ** Available fault injectors.  Should be numbered beginning with 0.
   18161 */
   18162 #define SQLITE_FAULTINJECTOR_MALLOC     0
   18163 #define SQLITE_FAULTINJECTOR_COUNT      1
   18164 
   18165 /*
   18166 ** The interface to the code in fault.c used for identifying "benign"
   18167 ** malloc failures. This is only present if SQLITE_UNTESTABLE
   18168 ** is not defined.
   18169 */
   18170 #ifndef SQLITE_UNTESTABLE
   18171 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
   18172 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
   18173 #else
   18174   #define sqlite3BeginBenignMalloc()
   18175   #define sqlite3EndBenignMalloc()
   18176 #endif
   18177 
   18178 /*
   18179 ** Allowed return values from sqlite3FindInIndex()
   18180 */
   18181 #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
   18182 #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
   18183 #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
   18184 #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
   18185 #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
   18186 /*
   18187 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
   18188 */
   18189 #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
   18190 #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
   18191 #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
   18192 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
   18193 
   18194 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
   18195 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
   18196 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
   18197  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   18198 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
   18199 #endif
   18200 
   18201 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
   18202 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
   18203 
   18204 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
   18205 #if SQLITE_MAX_EXPR_DEPTH>0
   18206 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
   18207 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
   18208 #else
   18209   #define sqlite3SelectExprHeight(x) 0
   18210   #define sqlite3ExprCheckHeight(x,y)
   18211 #endif
   18212 
   18213 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
   18214 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
   18215 
   18216 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   18217 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
   18218 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
   18219 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
   18220 #else
   18221   #define sqlite3ConnectionBlocked(x,y)
   18222   #define sqlite3ConnectionUnlocked(x)
   18223   #define sqlite3ConnectionClosed(x)
   18224 #endif
   18225 
   18226 #ifdef SQLITE_DEBUG
   18227 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
   18228 #endif
   18229 #if defined(YYCOVERAGE)
   18230 SQLITE_PRIVATE   int sqlite3ParserCoverage(FILE*);
   18231 #endif
   18232 
   18233 /*
   18234 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
   18235 ** sqlite3IoTrace is a pointer to a printf-like routine used to
   18236 ** print I/O tracing messages.
   18237 */
   18238 #ifdef SQLITE_ENABLE_IOTRACE
   18239 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
   18240 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
   18241 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
   18242 #else
   18243 # define IOTRACE(A)
   18244 # define sqlite3VdbeIOTraceSql(X)
   18245 #endif
   18246 
   18247 /*
   18248 ** These routines are available for the mem2.c debugging memory allocator
   18249 ** only.  They are used to verify that different "types" of memory
   18250 ** allocations are properly tracked by the system.
   18251 **
   18252 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
   18253 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
   18254 ** a single bit set.
   18255 **
   18256 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
   18257 ** argument match the type set by the previous sqlite3MemdebugSetType().
   18258 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
   18259 **
   18260 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
   18261 ** argument match the type set by the previous sqlite3MemdebugSetType().
   18262 **
   18263 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
   18264 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
   18265 ** it might have been allocated by lookaside, except the allocation was
   18266 ** too large or lookaside was already full.  It is important to verify
   18267 ** that allocations that might have been satisfied by lookaside are not
   18268 ** passed back to non-lookaside free() routines.  Asserts such as the
   18269 ** example above are placed on the non-lookaside free() routines to verify
   18270 ** this constraint.
   18271 **
   18272 ** All of this is no-op for a production build.  It only comes into
   18273 ** play when the SQLITE_MEMDEBUG compile-time option is used.
   18274 */
   18275 #ifdef SQLITE_MEMDEBUG
   18276 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
   18277 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
   18278 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
   18279 #else
   18280 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
   18281 # define sqlite3MemdebugHasType(X,Y)  1
   18282 # define sqlite3MemdebugNoType(X,Y)   1
   18283 #endif
   18284 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
   18285 #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
   18286 #define MEMTYPE_PCACHE     0x04  /* Page cache allocations */
   18287 
   18288 /*
   18289 ** Threading interface
   18290 */
   18291 #if SQLITE_MAX_WORKER_THREADS>0
   18292 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
   18293 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
   18294 #endif
   18295 
   18296 #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
   18297 SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
   18298 #endif
   18299 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
   18300 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
   18301 #endif
   18302 
   18303 SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
   18304 SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
   18305 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
   18306 SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
   18307 SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
   18308 
   18309 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   18310 SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
   18311 #endif
   18312 
   18313 #endif /* SQLITEINT_H */
   18314 
   18315 /************** End of sqliteInt.h *******************************************/
   18316 /************** Begin file global.c ******************************************/
   18317 /*
   18318 ** 2008 June 13
   18319 **
   18320 ** The author disclaims copyright to this source code.  In place of
   18321 ** a legal notice, here is a blessing:
   18322 **
   18323 **    May you do good and not evil.
   18324 **    May you find forgiveness for yourself and forgive others.
   18325 **    May you share freely, never taking more than you give.
   18326 **
   18327 *************************************************************************
   18328 **
   18329 ** This file contains definitions of global variables and constants.
   18330 */
   18331 /* #include "sqliteInt.h" */
   18332 
   18333 /* An array to map all upper-case characters into their corresponding
   18334 ** lower-case character.
   18335 **
   18336 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
   18337 ** handle case conversions for the UTF character set since the tables
   18338 ** involved are nearly as big or bigger than SQLite itself.
   18339 */
   18340 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
   18341 #ifdef SQLITE_ASCII
   18342       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
   18343      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
   18344      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
   18345      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
   18346     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
   18347     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
   18348     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
   18349     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   18350     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
   18351     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
   18352     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
   18353     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
   18354     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
   18355     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
   18356     252,253,254,255
   18357 #endif
   18358 #ifdef SQLITE_EBCDIC
   18359       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
   18360      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
   18361      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
   18362      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
   18363      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
   18364      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
   18365      96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
   18366     112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
   18367     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
   18368     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
   18369     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
   18370     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
   18371     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
   18372     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
   18373     224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
   18374     240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
   18375 #endif
   18376 };
   18377 
   18378 /*
   18379 ** The following 256 byte lookup table is used to support SQLites built-in
   18380 ** equivalents to the following standard library functions:
   18381 **
   18382 **   isspace()                        0x01
   18383 **   isalpha()                        0x02
   18384 **   isdigit()                        0x04
   18385 **   isalnum()                        0x06
   18386 **   isxdigit()                       0x08
   18387 **   toupper()                        0x20
   18388 **   SQLite identifier character      0x40
   18389 **   Quote character                  0x80
   18390 **
   18391 ** Bit 0x20 is set if the mapped character requires translation to upper
   18392 ** case. i.e. if the character is a lower-case ASCII character.
   18393 ** If x is a lower-case ASCII character, then its upper-case equivalent
   18394 ** is (x - 0x20). Therefore toupper() can be implemented as:
   18395 **
   18396 **   (x & ~(map[x]&0x20))
   18397 **
   18398 ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
   18399 ** array. tolower() is used more often than toupper() by SQLite.
   18400 **
   18401 ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
   18402 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
   18403 ** non-ASCII UTF character. Hence the test for whether or not a character is
   18404 ** part of an identifier is 0x46.
   18405 */
   18406 #ifdef SQLITE_ASCII
   18407 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   18408   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
   18409   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
   18410   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
   18411   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
   18412   0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
   18413   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
   18414   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
   18415   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
   18416 
   18417   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
   18418   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
   18419   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
   18420   0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
   18421   0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
   18422   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
   18423   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
   18424   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
   18425 
   18426   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
   18427   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
   18428   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
   18429   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
   18430   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
   18431   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
   18432   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
   18433   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
   18434 
   18435   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
   18436   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
   18437   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
   18438   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
   18439   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
   18440   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
   18441   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
   18442   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
   18443 };
   18444 #endif
   18445 
   18446 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
   18447 ** compatibility for legacy applications, the URI filename capability is
   18448 ** disabled by default.
   18449 **
   18450 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
   18451 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
   18452 **
   18453 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
   18454 ** disabled. The default value may be changed by compiling with the
   18455 ** SQLITE_USE_URI symbol defined.
   18456 **
   18457 ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
   18458 ** enabled.
   18459 */
   18460 #ifndef SQLITE_USE_URI
   18461 # ifdef SQLITE_HAS_CODEC
   18462 #  define SQLITE_USE_URI 1
   18463 # else
   18464 #  define SQLITE_USE_URI 0
   18465 # endif
   18466 #endif
   18467 
   18468 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
   18469 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
   18470 ** that compile-time option is omitted.
   18471 */
   18472 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
   18473 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
   18474 #endif
   18475 
   18476 /* The minimum PMA size is set to this value multiplied by the database
   18477 ** page size in bytes.
   18478 */
   18479 #ifndef SQLITE_SORTER_PMASZ
   18480 # define SQLITE_SORTER_PMASZ 250
   18481 #endif
   18482 
   18483 /* Statement journals spill to disk when their size exceeds the following
   18484 ** threshold (in bytes). 0 means that statement journals are created and
   18485 ** written to disk immediately (the default behavior for SQLite versions
   18486 ** before 3.12.0).  -1 means always keep the entire statement journal in
   18487 ** memory.  (The statement journal is also always held entirely in memory
   18488 ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
   18489 ** setting.)
   18490 */
   18491 #ifndef SQLITE_STMTJRNL_SPILL
   18492 # define SQLITE_STMTJRNL_SPILL (64*1024)
   18493 #endif
   18494 
   18495 /*
   18496 ** The default lookaside-configuration, the format "SZ,N".  SZ is the
   18497 ** number of bytes in each lookaside slot (should be a multiple of 8)
   18498 ** and N is the number of slots.  The lookaside-configuration can be
   18499 ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
   18500 ** or at run-time for an individual database connection using
   18501 ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
   18502 */
   18503 #ifndef SQLITE_DEFAULT_LOOKASIDE
   18504 # define SQLITE_DEFAULT_LOOKASIDE 1200,100
   18505 #endif
   18506 
   18507 
   18508 /*
   18509 ** The following singleton contains the global configuration for
   18510 ** the SQLite library.
   18511 */
   18512 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   18513    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   18514    1,                         /* bCoreMutex */
   18515    SQLITE_THREADSAFE==1,      /* bFullMutex */
   18516    SQLITE_USE_URI,            /* bOpenUri */
   18517    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
   18518    0,                         /* bSmallMalloc */
   18519    0x7ffffffe,                /* mxStrlen */
   18520    0,                         /* neverCorrupt */
   18521    SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
   18522    SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
   18523    {0,0,0,0,0,0,0,0},         /* m */
   18524    {0,0,0,0,0,0,0,0,0},       /* mutex */
   18525    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
   18526    (void*)0,                  /* pHeap */
   18527    0,                         /* nHeap */
   18528    0, 0,                      /* mnHeap, mxHeap */
   18529    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
   18530    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
   18531    (void*)0,                  /* pPage */
   18532    0,                         /* szPage */
   18533    SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
   18534    0,                         /* mxParserStack */
   18535    0,                         /* sharedCacheEnabled */
   18536    SQLITE_SORTER_PMASZ,       /* szPma */
   18537    /* All the rest should always be initialized to zero */
   18538    0,                         /* isInit */
   18539    0,                         /* inProgress */
   18540    0,                         /* isMutexInit */
   18541    0,                         /* isMallocInit */
   18542    0,                         /* isPCacheInit */
   18543    0,                         /* nRefInitMutex */
   18544    0,                         /* pInitMutex */
   18545    0,                         /* xLog */
   18546    0,                         /* pLogArg */
   18547 #ifdef SQLITE_ENABLE_SQLLOG
   18548    0,                         /* xSqllog */
   18549    0,                         /* pSqllogArg */
   18550 #endif
   18551 #ifdef SQLITE_VDBE_COVERAGE
   18552    0,                         /* xVdbeBranch */
   18553    0,                         /* pVbeBranchArg */
   18554 #endif
   18555 #ifndef SQLITE_UNTESTABLE
   18556    0,                         /* xTestCallback */
   18557 #endif
   18558    0,                         /* bLocaltimeFault */
   18559    0x7ffffffe                 /* iOnceResetThreshold */
   18560 };
   18561 
   18562 /*
   18563 ** Hash table for global functions - functions common to all
   18564 ** database connections.  After initialization, this table is
   18565 ** read-only.
   18566 */
   18567 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
   18568 
   18569 /*
   18570 ** Constant tokens for values 0 and 1.
   18571 */
   18572 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
   18573    { "0", 1 },
   18574    { "1", 1 }
   18575 };
   18576 
   18577 
   18578 /*
   18579 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
   18580 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
   18581 ** the database page that contains the pending byte.  It never attempts
   18582 ** to read or write that page.  The pending byte page is set aside
   18583 ** for use by the VFS layers as space for managing file locks.
   18584 **
   18585 ** During testing, it is often desirable to move the pending byte to
   18586 ** a different position in the file.  This allows code that has to
   18587 ** deal with the pending byte to run on files that are much smaller
   18588 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
   18589 ** move the pending byte.
   18590 **
   18591 ** IMPORTANT:  Changing the pending byte to any value other than
   18592 ** 0x40000000 results in an incompatible database file format!
   18593 ** Changing the pending byte during operation will result in undefined
   18594 ** and incorrect behavior.
   18595 */
   18596 #ifndef SQLITE_OMIT_WSD
   18597 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
   18598 #endif
   18599 
   18600 /* #include "opcodes.h" */
   18601 /*
   18602 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
   18603 ** created by mkopcodeh.awk during compilation.  Data is obtained
   18604 ** from the comments following the "case OP_xxxx:" statements in
   18605 ** the vdbe.c file.
   18606 */
   18607 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
   18608 
   18609 /*
   18610 ** Name of the default collating sequence
   18611 */
   18612 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
   18613 
   18614 /************** End of global.c **********************************************/
   18615 /************** Begin file status.c ******************************************/
   18616 /*
   18617 ** 2008 June 18
   18618 **
   18619 ** The author disclaims copyright to this source code.  In place of
   18620 ** a legal notice, here is a blessing:
   18621 **
   18622 **    May you do good and not evil.
   18623 **    May you find forgiveness for yourself and forgive others.
   18624 **    May you share freely, never taking more than you give.
   18625 **
   18626 *************************************************************************
   18627 **
   18628 ** This module implements the sqlite3_status() interface and related
   18629 ** functionality.
   18630 */
   18631 /* #include "sqliteInt.h" */
   18632 /************** Include vdbeInt.h in the middle of status.c ******************/
   18633 /************** Begin file vdbeInt.h *****************************************/
   18634 /*
   18635 ** 2003 September 6
   18636 **
   18637 ** The author disclaims copyright to this source code.  In place of
   18638 ** a legal notice, here is a blessing:
   18639 **
   18640 **    May you do good and not evil.
   18641 **    May you find forgiveness for yourself and forgive others.
   18642 **    May you share freely, never taking more than you give.
   18643 **
   18644 *************************************************************************
   18645 ** This is the header file for information that is private to the
   18646 ** VDBE.  This information used to all be at the top of the single
   18647 ** source code file "vdbe.c".  When that file became too big (over
   18648 ** 6000 lines long) it was split up into several smaller files and
   18649 ** this header information was factored out.
   18650 */
   18651 #ifndef SQLITE_VDBEINT_H
   18652 #define SQLITE_VDBEINT_H
   18653 
   18654 /*
   18655 ** The maximum number of times that a statement will try to reparse
   18656 ** itself before giving up and returning SQLITE_SCHEMA.
   18657 */
   18658 #ifndef SQLITE_MAX_SCHEMA_RETRY
   18659 # define SQLITE_MAX_SCHEMA_RETRY 50
   18660 #endif
   18661 
   18662 /*
   18663 ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
   18664 ** "explain" P4 display logic is enabled.
   18665 */
   18666 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   18667      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   18668 # define VDBE_DISPLAY_P4 1
   18669 #else
   18670 # define VDBE_DISPLAY_P4 0
   18671 #endif
   18672 
   18673 /*
   18674 ** SQL is translated into a sequence of instructions to be
   18675 ** executed by a virtual machine.  Each instruction is an instance
   18676 ** of the following structure.
   18677 */
   18678 typedef struct VdbeOp Op;
   18679 
   18680 /*
   18681 ** Boolean values
   18682 */
   18683 typedef unsigned Bool;
   18684 
   18685 /* Opaque type used by code in vdbesort.c */
   18686 typedef struct VdbeSorter VdbeSorter;
   18687 
   18688 /* Elements of the linked list at Vdbe.pAuxData */
   18689 typedef struct AuxData AuxData;
   18690 
   18691 /* Types of VDBE cursors */
   18692 #define CURTYPE_BTREE       0
   18693 #define CURTYPE_SORTER      1
   18694 #define CURTYPE_VTAB        2
   18695 #define CURTYPE_PSEUDO      3
   18696 
   18697 /*
   18698 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
   18699 **
   18700 **      * A b-tree cursor
   18701 **          -  In the main database or in an ephemeral database
   18702 **          -  On either an index or a table
   18703 **      * A sorter
   18704 **      * A virtual table
   18705 **      * A one-row "pseudotable" stored in a single register
   18706 */
   18707 typedef struct VdbeCursor VdbeCursor;
   18708 struct VdbeCursor {
   18709   u8 eCurType;            /* One of the CURTYPE_* values above */
   18710   i8 iDb;                 /* Index of cursor database in db->aDb[] (or -1) */
   18711   u8 nullRow;             /* True if pointing to a row with no data */
   18712   u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */
   18713   u8 isTable;             /* True for rowid tables.  False for indexes */
   18714 #ifdef SQLITE_DEBUG
   18715   u8 seekOp;              /* Most recent seek operation on this cursor */
   18716   u8 wrFlag;              /* The wrFlag argument to sqlite3BtreeCursor() */
   18717 #endif
   18718   Bool isEphemeral:1;     /* True for an ephemeral table */
   18719   Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
   18720   Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
   18721   Btree *pBtx;            /* Separate file holding temporary table */
   18722   i64 seqCount;           /* Sequence counter */
   18723   int *aAltMap;           /* Mapping from table to index column numbers */
   18724 
   18725   /* Cached OP_Column parse information is only valid if cacheStatus matches
   18726   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
   18727   ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
   18728   ** the cache is out of date. */
   18729   u32 cacheStatus;        /* Cache is valid if this matches Vdbe.cacheCtr */
   18730   int seekResult;         /* Result of previous sqlite3BtreeMoveto() or 0
   18731                           ** if there have been no prior seeks on the cursor. */
   18732   /* seekResult does not distinguish between "no seeks have ever occurred
   18733   ** on this cursor" and "the most recent seek was an exact match".
   18734   ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
   18735 
   18736   /* When a new VdbeCursor is allocated, only the fields above are zeroed.
   18737   ** The fields that follow are uninitialized, and must be individually
   18738   ** initialized prior to first use. */
   18739   VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
   18740   union {
   18741     BtCursor *pCursor;          /* CURTYPE_BTREE or _PSEUDO.  Btree cursor */
   18742     sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.              Vtab cursor */
   18743     VdbeSorter *pSorter;        /* CURTYPE_SORTER.            Sorter object */
   18744   } uc;
   18745   KeyInfo *pKeyInfo;      /* Info about index keys needed by index cursors */
   18746   u32 iHdrOffset;         /* Offset to next unparsed byte of the header */
   18747   Pgno pgnoRoot;          /* Root page of the open btree cursor */
   18748   i16 nField;             /* Number of fields in the header */
   18749   u16 nHdrParsed;         /* Number of header fields parsed so far */
   18750   i64 movetoTarget;       /* Argument to the deferred sqlite3BtreeMoveto() */
   18751   u32 *aOffset;           /* Pointer to aType[nField] */
   18752   const u8 *aRow;         /* Data for the current row, if all on one page */
   18753   u32 payloadSize;        /* Total number of bytes in the record */
   18754   u32 szRow;              /* Byte available in aRow */
   18755 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
   18756   u64 maskUsed;           /* Mask of columns used by this cursor */
   18757 #endif
   18758 
   18759   /* 2*nField extra array elements allocated for aType[], beyond the one
   18760   ** static element declared in the structure.  nField total array slots for
   18761   ** aType[] and nField+1 array slots for aOffset[] */
   18762   u32 aType[1];           /* Type values record decode.  MUST BE LAST */
   18763 };
   18764 
   18765 
   18766 /*
   18767 ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
   18768 */
   18769 #define CACHE_STALE 0
   18770 
   18771 /*
   18772 ** When a sub-program is executed (OP_Program), a structure of this type
   18773 ** is allocated to store the current value of the program counter, as
   18774 ** well as the current memory cell array and various other frame specific
   18775 ** values stored in the Vdbe struct. When the sub-program is finished,
   18776 ** these values are copied back to the Vdbe from the VdbeFrame structure,
   18777 ** restoring the state of the VM to as it was before the sub-program
   18778 ** began executing.
   18779 **
   18780 ** The memory for a VdbeFrame object is allocated and managed by a memory
   18781 ** cell in the parent (calling) frame. When the memory cell is deleted or
   18782 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
   18783 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
   18784 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
   18785 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
   18786 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
   18787 ** child frame are released.
   18788 **
   18789 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
   18790 ** set to NULL if the currently executing frame is the main program.
   18791 */
   18792 typedef struct VdbeFrame VdbeFrame;
   18793 struct VdbeFrame {
   18794   Vdbe *v;                /* VM this frame belongs to */
   18795   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
   18796   Op *aOp;                /* Program instructions for parent frame */
   18797   i64 *anExec;            /* Event counters from parent frame */
   18798   Mem *aMem;              /* Array of memory cells for parent frame */
   18799   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
   18800   u8 *aOnce;              /* Bitmask used by OP_Once */
   18801   void *token;            /* Copy of SubProgram.token */
   18802   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
   18803   AuxData *pAuxData;      /* Linked list of auxdata allocations */
   18804   int nCursor;            /* Number of entries in apCsr */
   18805   int pc;                 /* Program Counter in parent (calling) frame */
   18806   int nOp;                /* Size of aOp array */
   18807   int nMem;               /* Number of entries in aMem */
   18808   int nChildMem;          /* Number of memory cells for child frame */
   18809   int nChildCsr;          /* Number of cursors for child frame */
   18810   int nChange;            /* Statement changes (Vdbe.nChange)     */
   18811   int nDbChange;          /* Value of db->nChange */
   18812 };
   18813 
   18814 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
   18815 
   18816 /*
   18817 ** Internally, the vdbe manipulates nearly all SQL values as Mem
   18818 ** structures. Each Mem struct may cache multiple representations (string,
   18819 ** integer etc.) of the same value.
   18820 */
   18821 struct sqlite3_value {
   18822   union MemValue {
   18823     double r;           /* Real value used when MEM_Real is set in flags */
   18824     i64 i;              /* Integer value used when MEM_Int is set in flags */
   18825     int nZero;          /* Extra zero bytes when MEM_Zero and MEM_Blob set */
   18826     const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
   18827     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
   18828     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
   18829     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
   18830   } u;
   18831   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
   18832   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
   18833   u8  eSubtype;       /* Subtype for this value */
   18834   int n;              /* Number of characters in string value, excluding '\0' */
   18835   char *z;            /* String or BLOB value */
   18836   /* ShallowCopy only needs to copy the information above */
   18837   char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
   18838   int szMalloc;       /* Size of the zMalloc allocation */
   18839   u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
   18840   sqlite3 *db;        /* The associated database connection */
   18841   void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
   18842 #ifdef SQLITE_DEBUG
   18843   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
   18844   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
   18845 #endif
   18846 };
   18847 
   18848 /*
   18849 ** Size of struct Mem not including the Mem.zMalloc member or anything that
   18850 ** follows.
   18851 */
   18852 #define MEMCELLSIZE offsetof(Mem,zMalloc)
   18853 
   18854 /* One or more of the following flags are set to indicate the validOK
   18855 ** representations of the value stored in the Mem struct.
   18856 **
   18857 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
   18858 ** For a pointer type created using sqlite3_bind_pointer() or
   18859 ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
   18860 ** If both MEM_Null and MEM_Zero are set, that means that the value is
   18861 ** an unchanging column value from VColumn.
   18862 **
   18863 ** If the MEM_Str flag is set then Mem.z points at a string representation.
   18864 ** Usually this is encoded in the same unicode encoding as the main
   18865 ** database (see below for exceptions). If the MEM_Term flag is also
   18866 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
   18867 ** flags may coexist with the MEM_Str flag.
   18868 */
   18869 #define MEM_Null      0x0001   /* Value is NULL (or a pointer) */
   18870 #define MEM_Str       0x0002   /* Value is a string */
   18871 #define MEM_Int       0x0004   /* Value is an integer */
   18872 #define MEM_Real      0x0008   /* Value is a real number */
   18873 #define MEM_Blob      0x0010   /* Value is a BLOB */
   18874 #define MEM_AffMask   0x001f   /* Mask of affinity bits */
   18875 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
   18876 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
   18877 #define MEM_Undefined 0x0080   /* Value is undefined */
   18878 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
   18879 #define MEM_TypeMask  0xc1ff   /* Mask of type bits */
   18880 
   18881 
   18882 /* Whenever Mem contains a valid string or blob representation, one of
   18883 ** the following flags must be set to determine the memory management
   18884 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   18885 ** string is \000 or \u0000 terminated
   18886 */
   18887 #define MEM_Term      0x0200   /* String in Mem.z is zero terminated */
   18888 #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
   18889 #define MEM_Static    0x0800   /* Mem.z points to a static string */
   18890 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
   18891 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
   18892 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
   18893 #define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */
   18894 #ifdef SQLITE_OMIT_INCRBLOB
   18895   #undef MEM_Zero
   18896   #define MEM_Zero 0x0000
   18897 #endif
   18898 
   18899 /* Return TRUE if Mem X contains dynamically allocated content - anything
   18900 ** that needs to be deallocated to avoid a leak.
   18901 */
   18902 #define VdbeMemDynamic(X)  \
   18903   (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
   18904 
   18905 /*
   18906 ** Clear any existing type flags from a Mem and replace them with f
   18907 */
   18908 #define MemSetTypeFlag(p, f) \
   18909    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
   18910 
   18911 /*
   18912 ** Return true if a memory cell is not marked as invalid.  This macro
   18913 ** is for use inside assert() statements only.
   18914 */
   18915 #ifdef SQLITE_DEBUG
   18916 #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
   18917 #endif
   18918 
   18919 /*
   18920 ** Each auxiliary data pointer stored by a user defined function
   18921 ** implementation calling sqlite3_set_auxdata() is stored in an instance
   18922 ** of this structure. All such structures associated with a single VM
   18923 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
   18924 ** when the VM is halted (if not before).
   18925 */
   18926 struct AuxData {
   18927   int iAuxOp;                     /* Instruction number of OP_Function opcode */
   18928   int iAuxArg;                    /* Index of function argument. */
   18929   void *pAux;                     /* Aux data pointer */
   18930   void (*xDeleteAux)(void*);      /* Destructor for the aux data */
   18931   AuxData *pNextAux;              /* Next element in list */
   18932 };
   18933 
   18934 /*
   18935 ** The "context" argument for an installable function.  A pointer to an
   18936 ** instance of this structure is the first argument to the routines used
   18937 ** implement the SQL functions.
   18938 **
   18939 ** There is a typedef for this structure in sqlite.h.  So all routines,
   18940 ** even the public interface to SQLite, can use a pointer to this structure.
   18941 ** But this file is the only place where the internal details of this
   18942 ** structure are known.
   18943 **
   18944 ** This structure is defined inside of vdbeInt.h because it uses substructures
   18945 ** (Mem) which are only defined there.
   18946 */
   18947 struct sqlite3_context {
   18948   Mem *pOut;              /* The return value is stored here */
   18949   FuncDef *pFunc;         /* Pointer to function information */
   18950   Mem *pMem;              /* Memory cell used to store aggregate context */
   18951   Vdbe *pVdbe;            /* The VM that owns this context */
   18952   int iOp;                /* Instruction number of OP_Function */
   18953   int isError;            /* Error code returned by the function. */
   18954   u8 skipFlag;            /* Skip accumulator loading if true */
   18955   u8 fErrorOrAux;         /* isError!=0 or pVdbe->pAuxData modified */
   18956   u8 argc;                /* Number of arguments */
   18957   sqlite3_value *argv[1]; /* Argument set */
   18958 };
   18959 
   18960 /* A bitfield type for use inside of structures.  Always follow with :N where
   18961 ** N is the number of bits.
   18962 */
   18963 typedef unsigned bft;  /* Bit Field Type */
   18964 
   18965 typedef struct ScanStatus ScanStatus;
   18966 struct ScanStatus {
   18967   int addrExplain;                /* OP_Explain for loop */
   18968   int addrLoop;                   /* Address of "loops" counter */
   18969   int addrVisit;                  /* Address of "rows visited" counter */
   18970   int iSelectID;                  /* The "Select-ID" for this loop */
   18971   LogEst nEst;                    /* Estimated output rows per loop */
   18972   char *zName;                    /* Name of table or index */
   18973 };
   18974 
   18975 /*
   18976 ** An instance of the virtual machine.  This structure contains the complete
   18977 ** state of the virtual machine.
   18978 **
   18979 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
   18980 ** is really a pointer to an instance of this structure.
   18981 */
   18982 struct Vdbe {
   18983   sqlite3 *db;            /* The database connection that owns this statement */
   18984   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
   18985   Parse *pParse;          /* Parsing context used to create this Vdbe */
   18986   ynVar nVar;             /* Number of entries in aVar[] */
   18987   u32 magic;              /* Magic number for sanity checking */
   18988   int nMem;               /* Number of memory locations currently allocated */
   18989   int nCursor;            /* Number of slots in apCsr[] */
   18990   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
   18991   int pc;                 /* The program counter */
   18992   int rc;                 /* Value to return */
   18993   int nChange;            /* Number of db changes made since last reset */
   18994   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
   18995   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
   18996   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
   18997   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
   18998   i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
   18999 
   19000   /* When allocating a new Vdbe object, all of the fields below should be
   19001   ** initialized to zero or NULL */
   19002 
   19003   Op *aOp;                /* Space to hold the virtual machine's program */
   19004   Mem *aMem;              /* The memory locations */
   19005   Mem **apArg;            /* Arguments to currently executing user function */
   19006   Mem *aColName;          /* Column names to return */
   19007   Mem *pResultSet;        /* Pointer to an array of results */
   19008   char *zErrMsg;          /* Error message written here */
   19009   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
   19010   Mem *aVar;              /* Values for the OP_Variable opcode. */
   19011   VList *pVList;          /* Name of variables */
   19012 #ifndef SQLITE_OMIT_TRACE
   19013   i64 startTime;          /* Time when query started - used for profiling */
   19014 #endif
   19015   int nOp;                /* Number of instructions in the program */
   19016 #ifdef SQLITE_DEBUG
   19017   int rcApp;              /* errcode set by sqlite3_result_error_code() */
   19018 #endif
   19019   u16 nResColumn;         /* Number of columns in one row of the result set */
   19020   u8 errorAction;         /* Recovery action to do in case of an error */
   19021   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
   19022   u8 prepFlags;           /* SQLITE_PREPARE_* flags */
   19023   bft expired:1;          /* True if the VM needs to be recompiled */
   19024   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
   19025   bft explain:2;          /* True if EXPLAIN present on SQL command */
   19026   bft changeCntOn:1;      /* True to update the change-counter */
   19027   bft runOnlyOnce:1;      /* Automatically expire on reset */
   19028   bft usesStmtJournal:1;  /* True if uses a statement journal */
   19029   bft readOnly:1;         /* True for statements that do not write */
   19030   bft bIsReader:1;        /* True for statements that read */
   19031   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
   19032   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
   19033   u32 aCounter[7];        /* Counters used by sqlite3_stmt_status() */
   19034   char *zSql;             /* Text of the SQL statement that generated this */
   19035   void *pFree;            /* Free this when deleting the vdbe */
   19036   VdbeFrame *pFrame;      /* Parent frame */
   19037   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
   19038   int nFrame;             /* Number of frames in pFrame list */
   19039   u32 expmask;            /* Binding to these vars invalidates VM */
   19040   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
   19041   AuxData *pAuxData;      /* Linked list of auxdata allocations */
   19042 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   19043   i64 *anExec;            /* Number of times each op has been executed */
   19044   int nScan;              /* Entries in aScan[] */
   19045   ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
   19046 #endif
   19047 };
   19048 
   19049 /*
   19050 ** The following are allowed values for Vdbe.magic
   19051 */
   19052 #define VDBE_MAGIC_INIT     0x16bceaa5    /* Building a VDBE program */
   19053 #define VDBE_MAGIC_RUN      0x2df20da3    /* VDBE is ready to execute */
   19054 #define VDBE_MAGIC_HALT     0x319c2973    /* VDBE has completed execution */
   19055 #define VDBE_MAGIC_RESET    0x48fa9f76    /* Reset and ready to run again */
   19056 #define VDBE_MAGIC_DEAD     0x5606c3c8    /* The VDBE has been deallocated */
   19057 
   19058 /*
   19059 ** Structure used to store the context required by the
   19060 ** sqlite3_preupdate_*() API functions.
   19061 */
   19062 struct PreUpdate {
   19063   Vdbe *v;
   19064   VdbeCursor *pCsr;               /* Cursor to read old values from */
   19065   int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
   19066   u8 *aRecord;                    /* old.* database record */
   19067   KeyInfo keyinfo;
   19068   UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
   19069   UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
   19070   int iNewReg;                    /* Register for new.* values */
   19071   i64 iKey1;                      /* First key value passed to hook */
   19072   i64 iKey2;                      /* Second key value passed to hook */
   19073   Mem *aNew;                      /* Array of new.* values */
   19074   Table *pTab;                    /* Schema object being upated */
   19075   Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
   19076 };
   19077 
   19078 /*
   19079 ** Function prototypes
   19080 */
   19081 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
   19082 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
   19083 void sqliteVdbePopStack(Vdbe*,int);
   19084 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
   19085 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
   19086 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   19087 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
   19088 #endif
   19089 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
   19090 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
   19091 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
   19092 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
   19093 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
   19094 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
   19095 
   19096 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
   19097 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
   19098 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
   19099 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
   19100 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
   19101 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
   19102 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
   19103 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
   19104 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
   19105 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
   19106 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
   19107 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
   19108 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
   19109 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
   19110 #ifdef SQLITE_OMIT_FLOATING_POINT
   19111 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
   19112 #else
   19113 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
   19114 #endif
   19115 SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
   19116 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
   19117 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
   19118 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
   19119 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
   19120 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
   19121 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
   19122 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
   19123 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
   19124 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
   19125 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
   19126 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
   19127 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
   19128 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
   19129 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
   19130 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
   19131 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
   19132 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
   19133 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
   19134 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
   19135 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
   19136 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
   19137 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
   19138 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   19139 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
   19140 #endif
   19141 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
   19142 
   19143 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
   19144 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
   19145 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
   19146 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
   19147 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
   19148 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
   19149 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
   19150 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
   19151 
   19152 #if !defined(SQLITE_OMIT_SHARED_CACHE)
   19153 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
   19154 #else
   19155 # define sqlite3VdbeEnter(X)
   19156 #endif
   19157 
   19158 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   19159 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
   19160 #else
   19161 # define sqlite3VdbeLeave(X)
   19162 #endif
   19163 
   19164 #ifdef SQLITE_DEBUG
   19165 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
   19166 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
   19167 #endif
   19168 
   19169 #ifndef SQLITE_OMIT_FOREIGN_KEY
   19170 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
   19171 #else
   19172 # define sqlite3VdbeCheckFk(p,i) 0
   19173 #endif
   19174 
   19175 #ifdef SQLITE_DEBUG
   19176 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
   19177 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
   19178 #endif
   19179 #ifndef SQLITE_OMIT_UTF16
   19180 SQLITE_PRIVATE   int sqlite3VdbeMemTranslate(Mem*, u8);
   19181 SQLITE_PRIVATE   int sqlite3VdbeMemHandleBom(Mem *pMem);
   19182 #endif
   19183 
   19184 #ifndef SQLITE_OMIT_INCRBLOB
   19185 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
   19186   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
   19187 #else
   19188   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
   19189   #define ExpandBlob(P) SQLITE_OK
   19190 #endif
   19191 
   19192 #endif /* !defined(SQLITE_VDBEINT_H) */
   19193 
   19194 /************** End of vdbeInt.h *********************************************/
   19195 /************** Continuing where we left off in status.c *********************/
   19196 
   19197 /*
   19198 ** Variables in which to record status information.
   19199 */
   19200 #if SQLITE_PTRSIZE>4
   19201 typedef sqlite3_int64 sqlite3StatValueType;
   19202 #else
   19203 typedef u32 sqlite3StatValueType;
   19204 #endif
   19205 typedef struct sqlite3StatType sqlite3StatType;
   19206 static SQLITE_WSD struct sqlite3StatType {
   19207   sqlite3StatValueType nowValue[10];  /* Current value */
   19208   sqlite3StatValueType mxValue[10];   /* Maximum value */
   19209 } sqlite3Stat = { {0,}, {0,} };
   19210 
   19211 /*
   19212 ** Elements of sqlite3Stat[] are protected by either the memory allocator
   19213 ** mutex, or by the pcache1 mutex.  The following array determines which.
   19214 */
   19215 static const char statMutex[] = {
   19216   0,  /* SQLITE_STATUS_MEMORY_USED */
   19217   1,  /* SQLITE_STATUS_PAGECACHE_USED */
   19218   1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
   19219   0,  /* SQLITE_STATUS_SCRATCH_USED */
   19220   0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
   19221   0,  /* SQLITE_STATUS_MALLOC_SIZE */
   19222   0,  /* SQLITE_STATUS_PARSER_STACK */
   19223   1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
   19224   0,  /* SQLITE_STATUS_SCRATCH_SIZE */
   19225   0,  /* SQLITE_STATUS_MALLOC_COUNT */
   19226 };
   19227 
   19228 
   19229 /* The "wsdStat" macro will resolve to the status information
   19230 ** state vector.  If writable static data is unsupported on the target,
   19231 ** we have to locate the state vector at run-time.  In the more common
   19232 ** case where writable static data is supported, wsdStat can refer directly
   19233 ** to the "sqlite3Stat" state vector declared above.
   19234 */
   19235 #ifdef SQLITE_OMIT_WSD
   19236 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
   19237 # define wsdStat x[0]
   19238 #else
   19239 # define wsdStatInit
   19240 # define wsdStat sqlite3Stat
   19241 #endif
   19242 
   19243 /*
   19244 ** Return the current value of a status parameter.  The caller must
   19245 ** be holding the appropriate mutex.
   19246 */
   19247 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
   19248   wsdStatInit;
   19249   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   19250   assert( op>=0 && op<ArraySize(statMutex) );
   19251   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
   19252                                            : sqlite3MallocMutex()) );
   19253   return wsdStat.nowValue[op];
   19254 }
   19255 
   19256 /*
   19257 ** Add N to the value of a status record.  The caller must hold the
   19258 ** appropriate mutex.  (Locking is checked by assert()).
   19259 **
   19260 ** The StatusUp() routine can accept positive or negative values for N.
   19261 ** The value of N is added to the current status value and the high-water
   19262 ** mark is adjusted if necessary.
   19263 **
   19264 ** The StatusDown() routine lowers the current value by N.  The highwater
   19265 ** mark is unchanged.  N must be non-negative for StatusDown().
   19266 */
   19267 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
   19268   wsdStatInit;
   19269   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   19270   assert( op>=0 && op<ArraySize(statMutex) );
   19271   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
   19272                                            : sqlite3MallocMutex()) );
   19273   wsdStat.nowValue[op] += N;
   19274   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   19275     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   19276   }
   19277 }
   19278 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
   19279   wsdStatInit;
   19280   assert( N>=0 );
   19281   assert( op>=0 && op<ArraySize(statMutex) );
   19282   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
   19283                                            : sqlite3MallocMutex()) );
   19284   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   19285   wsdStat.nowValue[op] -= N;
   19286 }
   19287 
   19288 /*
   19289 ** Adjust the highwater mark if necessary.
   19290 ** The caller must hold the appropriate mutex.
   19291 */
   19292 SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
   19293   sqlite3StatValueType newValue;
   19294   wsdStatInit;
   19295   assert( X>=0 );
   19296   newValue = (sqlite3StatValueType)X;
   19297   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   19298   assert( op>=0 && op<ArraySize(statMutex) );
   19299   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
   19300                                            : sqlite3MallocMutex()) );
   19301   assert( op==SQLITE_STATUS_MALLOC_SIZE
   19302           || op==SQLITE_STATUS_PAGECACHE_SIZE
   19303           || op==SQLITE_STATUS_PARSER_STACK );
   19304   if( newValue>wsdStat.mxValue[op] ){
   19305     wsdStat.mxValue[op] = newValue;
   19306   }
   19307 }
   19308 
   19309 /*
   19310 ** Query status information.
   19311 */
   19312 SQLITE_API int sqlite3_status64(
   19313   int op,
   19314   sqlite3_int64 *pCurrent,
   19315   sqlite3_int64 *pHighwater,
   19316   int resetFlag
   19317 ){
   19318   sqlite3_mutex *pMutex;
   19319   wsdStatInit;
   19320   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
   19321     return SQLITE_MISUSE_BKPT;
   19322   }
   19323 #ifdef SQLITE_ENABLE_API_ARMOR
   19324   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
   19325 #endif
   19326   pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
   19327   sqlite3_mutex_enter(pMutex);
   19328   *pCurrent = wsdStat.nowValue[op];
   19329   *pHighwater = wsdStat.mxValue[op];
   19330   if( resetFlag ){
   19331     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   19332   }
   19333   sqlite3_mutex_leave(pMutex);
   19334   (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
   19335   return SQLITE_OK;
   19336 }
   19337 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
   19338   sqlite3_int64 iCur = 0, iHwtr = 0;
   19339   int rc;
   19340 #ifdef SQLITE_ENABLE_API_ARMOR
   19341   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
   19342 #endif
   19343   rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
   19344   if( rc==0 ){
   19345     *pCurrent = (int)iCur;
   19346     *pHighwater = (int)iHwtr;
   19347   }
   19348   return rc;
   19349 }
   19350 
   19351 /*
   19352 ** Return the number of LookasideSlot elements on the linked list
   19353 */
   19354 static u32 countLookasideSlots(LookasideSlot *p){
   19355   u32 cnt = 0;
   19356   while( p ){
   19357     p = p->pNext;
   19358     cnt++;
   19359   }
   19360   return cnt;
   19361 }
   19362 
   19363 /*
   19364 ** Count the number of slots of lookaside memory that are outstanding
   19365 */
   19366 SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
   19367   u32 nInit = countLookasideSlots(db->lookaside.pInit);
   19368   u32 nFree = countLookasideSlots(db->lookaside.pFree);
   19369   if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
   19370   return db->lookaside.nSlot - (nInit+nFree);
   19371 }
   19372 
   19373 /*
   19374 ** Query status information for a single database connection
   19375 */
   19376 SQLITE_API int sqlite3_db_status(
   19377   sqlite3 *db,          /* The database connection whose status is desired */
   19378   int op,               /* Status verb */
   19379   int *pCurrent,        /* Write current value here */
   19380   int *pHighwater,      /* Write high-water mark here */
   19381   int resetFlag         /* Reset high-water mark if true */
   19382 ){
   19383   int rc = SQLITE_OK;   /* Return code */
   19384 #ifdef SQLITE_ENABLE_API_ARMOR
   19385   if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
   19386     return SQLITE_MISUSE_BKPT;
   19387   }
   19388 #endif
   19389   sqlite3_mutex_enter(db->mutex);
   19390   switch( op ){
   19391     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
   19392       *pCurrent = sqlite3LookasideUsed(db, pHighwater);
   19393       if( resetFlag ){
   19394         LookasideSlot *p = db->lookaside.pFree;
   19395         if( p ){
   19396           while( p->pNext ) p = p->pNext;
   19397           p->pNext = db->lookaside.pInit;
   19398           db->lookaside.pInit = db->lookaside.pFree;
   19399           db->lookaside.pFree = 0;
   19400         }
   19401       }
   19402       break;
   19403     }
   19404 
   19405     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
   19406     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
   19407     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
   19408       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
   19409       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
   19410       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
   19411       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
   19412       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
   19413       *pCurrent = 0;
   19414       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
   19415       if( resetFlag ){
   19416         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
   19417       }
   19418       break;
   19419     }
   19420 
   19421     /*
   19422     ** Return an approximation for the amount of memory currently used
   19423     ** by all pagers associated with the given database connection.  The
   19424     ** highwater mark is meaningless and is returned as zero.
   19425     */
   19426     case SQLITE_DBSTATUS_CACHE_USED_SHARED:
   19427     case SQLITE_DBSTATUS_CACHE_USED: {
   19428       int totalUsed = 0;
   19429       int i;
   19430       sqlite3BtreeEnterAll(db);
   19431       for(i=0; i<db->nDb; i++){
   19432         Btree *pBt = db->aDb[i].pBt;
   19433         if( pBt ){
   19434           Pager *pPager = sqlite3BtreePager(pBt);
   19435           int nByte = sqlite3PagerMemUsed(pPager);
   19436           if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
   19437             nByte = nByte / sqlite3BtreeConnectionCount(pBt);
   19438           }
   19439           totalUsed += nByte;
   19440         }
   19441       }
   19442       sqlite3BtreeLeaveAll(db);
   19443       *pCurrent = totalUsed;
   19444       *pHighwater = 0;
   19445       break;
   19446     }
   19447 
   19448     /*
   19449     ** *pCurrent gets an accurate estimate of the amount of memory used
   19450     ** to store the schema for all databases (main, temp, and any ATTACHed
   19451     ** databases.  *pHighwater is set to zero.
   19452     */
   19453     case SQLITE_DBSTATUS_SCHEMA_USED: {
   19454       int i;                      /* Used to iterate through schemas */
   19455       int nByte = 0;              /* Used to accumulate return value */
   19456 
   19457       sqlite3BtreeEnterAll(db);
   19458       db->pnBytesFreed = &nByte;
   19459       for(i=0; i<db->nDb; i++){
   19460         Schema *pSchema = db->aDb[i].pSchema;
   19461         if( ALWAYS(pSchema!=0) ){
   19462           HashElem *p;
   19463 
   19464           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
   19465               pSchema->tblHash.count
   19466             + pSchema->trigHash.count
   19467             + pSchema->idxHash.count
   19468             + pSchema->fkeyHash.count
   19469           );
   19470           nByte += sqlite3_msize(pSchema->tblHash.ht);
   19471           nByte += sqlite3_msize(pSchema->trigHash.ht);
   19472           nByte += sqlite3_msize(pSchema->idxHash.ht);
   19473           nByte += sqlite3_msize(pSchema->fkeyHash.ht);
   19474 
   19475           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
   19476             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
   19477           }
   19478           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
   19479             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
   19480           }
   19481         }
   19482       }
   19483       db->pnBytesFreed = 0;
   19484       sqlite3BtreeLeaveAll(db);
   19485 
   19486       *pHighwater = 0;
   19487       *pCurrent = nByte;
   19488       break;
   19489     }
   19490 
   19491     /*
   19492     ** *pCurrent gets an accurate estimate of the amount of memory used
   19493     ** to store all prepared statements.
   19494     ** *pHighwater is set to zero.
   19495     */
   19496     case SQLITE_DBSTATUS_STMT_USED: {
   19497       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
   19498       int nByte = 0;              /* Used to accumulate return value */
   19499 
   19500       db->pnBytesFreed = &nByte;
   19501       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
   19502         sqlite3VdbeClearObject(db, pVdbe);
   19503         sqlite3DbFree(db, pVdbe);
   19504       }
   19505       db->pnBytesFreed = 0;
   19506 
   19507       *pHighwater = 0;  /* IMP: R-64479-57858 */
   19508       *pCurrent = nByte;
   19509 
   19510       break;
   19511     }
   19512 
   19513     /*
   19514     ** Set *pCurrent to the total cache hits or misses encountered by all
   19515     ** pagers the database handle is connected to. *pHighwater is always set
   19516     ** to zero.
   19517     */
   19518     case SQLITE_DBSTATUS_CACHE_HIT:
   19519     case SQLITE_DBSTATUS_CACHE_MISS:
   19520     case SQLITE_DBSTATUS_CACHE_WRITE:{
   19521       int i;
   19522       int nRet = 0;
   19523       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
   19524       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
   19525 
   19526       for(i=0; i<db->nDb; i++){
   19527         if( db->aDb[i].pBt ){
   19528           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
   19529           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
   19530         }
   19531       }
   19532       *pHighwater = 0; /* IMP: R-42420-56072 */
   19533                        /* IMP: R-54100-20147 */
   19534                        /* IMP: R-29431-39229 */
   19535       *pCurrent = nRet;
   19536       break;
   19537     }
   19538 
   19539     /* Set *pCurrent to non-zero if there are unresolved deferred foreign
   19540     ** key constraints.  Set *pCurrent to zero if all foreign key constraints
   19541     ** have been satisfied.  The *pHighwater is always set to zero.
   19542     */
   19543     case SQLITE_DBSTATUS_DEFERRED_FKS: {
   19544       *pHighwater = 0;  /* IMP: R-11967-56545 */
   19545       *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
   19546       break;
   19547     }
   19548 
   19549     default: {
   19550       rc = SQLITE_ERROR;
   19551     }
   19552   }
   19553   sqlite3_mutex_leave(db->mutex);
   19554   return rc;
   19555 }
   19556 
   19557 /************** End of status.c **********************************************/
   19558 /************** Begin file date.c ********************************************/
   19559 /*
   19560 ** 2003 October 31
   19561 **
   19562 ** The author disclaims copyright to this source code.  In place of
   19563 ** a legal notice, here is a blessing:
   19564 **
   19565 **    May you do good and not evil.
   19566 **    May you find forgiveness for yourself and forgive others.
   19567 **    May you share freely, never taking more than you give.
   19568 **
   19569 *************************************************************************
   19570 ** This file contains the C functions that implement date and time
   19571 ** functions for SQLite.
   19572 **
   19573 ** There is only one exported symbol in this file - the function
   19574 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
   19575 ** All other code has file scope.
   19576 **
   19577 ** SQLite processes all times and dates as julian day numbers.  The
   19578 ** dates and times are stored as the number of days since noon
   19579 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
   19580 ** calendar system.
   19581 **
   19582 ** 1970-01-01 00:00:00 is JD 2440587.5
   19583 ** 2000-01-01 00:00:00 is JD 2451544.5
   19584 **
   19585 ** This implementation requires years to be expressed as a 4-digit number
   19586 ** which means that only dates between 0000-01-01 and 9999-12-31 can
   19587 ** be represented, even though julian day numbers allow a much wider
   19588 ** range of dates.
   19589 **
   19590 ** The Gregorian calendar system is used for all dates and times,
   19591 ** even those that predate the Gregorian calendar.  Historians usually
   19592 ** use the julian calendar for dates prior to 1582-10-15 and for some
   19593 ** dates afterwards, depending on locale.  Beware of this difference.
   19594 **
   19595 ** The conversion algorithms are implemented based on descriptions
   19596 ** in the following text:
   19597 **
   19598 **      Jean Meeus
   19599 **      Astronomical Algorithms, 2nd Edition, 1998
   19600 **      ISBN 0-943396-61-1
   19601 **      Willmann-Bell, Inc
   19602 **      Richmond, Virginia (USA)
   19603 */
   19604 /* #include "sqliteInt.h" */
   19605 /* #include <stdlib.h> */
   19606 /* #include <assert.h> */
   19607 #include <time.h>
   19608 
   19609 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   19610 
   19611 /*
   19612 ** The MSVC CRT on Windows CE may not have a localtime() function.
   19613 ** So declare a substitute.  The substitute function itself is
   19614 ** defined in "os_win.c".
   19615 */
   19616 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
   19617     (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
   19618 struct tm *__cdecl localtime(const time_t *);
   19619 #endif
   19620 
   19621 /*
   19622 ** A structure for holding a single date and time.
   19623 */
   19624 typedef struct DateTime DateTime;
   19625 struct DateTime {
   19626   sqlite3_int64 iJD;  /* The julian day number times 86400000 */
   19627   int Y, M, D;        /* Year, month, and day */
   19628   int h, m;           /* Hour and minutes */
   19629   int tz;             /* Timezone offset in minutes */
   19630   double s;           /* Seconds */
   19631   char validJD;       /* True (1) if iJD is valid */
   19632   char rawS;          /* Raw numeric value stored in s */
   19633   char validYMD;      /* True (1) if Y,M,D are valid */
   19634   char validHMS;      /* True (1) if h,m,s are valid */
   19635   char validTZ;       /* True (1) if tz is valid */
   19636   char tzSet;         /* Timezone was set explicitly */
   19637   char isError;       /* An overflow has occurred */
   19638 };
   19639 
   19640 
   19641 /*
   19642 ** Convert zDate into one or more integers according to the conversion
   19643 ** specifier zFormat.
   19644 **
   19645 ** zFormat[] contains 4 characters for each integer converted, except for
   19646 ** the last integer which is specified by three characters.  The meaning
   19647 ** of a four-character format specifiers ABCD is:
   19648 **
   19649 **    A:   number of digits to convert.  Always "2" or "4".
   19650 **    B:   minimum value.  Always "0" or "1".
   19651 **    C:   maximum value, decoded as:
   19652 **           a:  12
   19653 **           b:  14
   19654 **           c:  24
   19655 **           d:  31
   19656 **           e:  59
   19657 **           f:  9999
   19658 **    D:   the separator character, or \000 to indicate this is the
   19659 **         last number to convert.
   19660 **
   19661 ** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
   19662 ** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
   19663 ** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
   19664 ** the 2-digit day which is the last integer in the set.
   19665 **
   19666 ** The function returns the number of successful conversions.
   19667 */
   19668 static int getDigits(const char *zDate, const char *zFormat, ...){
   19669   /* The aMx[] array translates the 3rd character of each format
   19670   ** spec into a max size:    a   b   c   d   e     f */
   19671   static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
   19672   va_list ap;
   19673   int cnt = 0;
   19674   char nextC;
   19675   va_start(ap, zFormat);
   19676   do{
   19677     char N = zFormat[0] - '0';
   19678     char min = zFormat[1] - '0';
   19679     int val = 0;
   19680     u16 max;
   19681 
   19682     assert( zFormat[2]>='a' && zFormat[2]<='f' );
   19683     max = aMx[zFormat[2] - 'a'];
   19684     nextC = zFormat[3];
   19685     val = 0;
   19686     while( N-- ){
   19687       if( !sqlite3Isdigit(*zDate) ){
   19688         goto end_getDigits;
   19689       }
   19690       val = val*10 + *zDate - '0';
   19691       zDate++;
   19692     }
   19693     if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
   19694       goto end_getDigits;
   19695     }
   19696     *va_arg(ap,int*) = val;
   19697     zDate++;
   19698     cnt++;
   19699     zFormat += 4;
   19700   }while( nextC );
   19701 end_getDigits:
   19702   va_end(ap);
   19703   return cnt;
   19704 }
   19705 
   19706 /*
   19707 ** Parse a timezone extension on the end of a date-time.
   19708 ** The extension is of the form:
   19709 **
   19710 **        (+/-)HH:MM
   19711 **
   19712 ** Or the "zulu" notation:
   19713 **
   19714 **        Z
   19715 **
   19716 ** If the parse is successful, write the number of minutes
   19717 ** of change in p->tz and return 0.  If a parser error occurs,
   19718 ** return non-zero.
   19719 **
   19720 ** A missing specifier is not considered an error.
   19721 */
   19722 static int parseTimezone(const char *zDate, DateTime *p){
   19723   int sgn = 0;
   19724   int nHr, nMn;
   19725   int c;
   19726   while( sqlite3Isspace(*zDate) ){ zDate++; }
   19727   p->tz = 0;
   19728   c = *zDate;
   19729   if( c=='-' ){
   19730     sgn = -1;
   19731   }else if( c=='+' ){
   19732     sgn = +1;
   19733   }else if( c=='Z' || c=='z' ){
   19734     zDate++;
   19735     goto zulu_time;
   19736   }else{
   19737     return c!=0;
   19738   }
   19739   zDate++;
   19740   if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
   19741     return 1;
   19742   }
   19743   zDate += 5;
   19744   p->tz = sgn*(nMn + nHr*60);
   19745 zulu_time:
   19746   while( sqlite3Isspace(*zDate) ){ zDate++; }
   19747   p->tzSet = 1;
   19748   return *zDate!=0;
   19749 }
   19750 
   19751 /*
   19752 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
   19753 ** The HH, MM, and SS must each be exactly 2 digits.  The
   19754 ** fractional seconds FFFF can be one or more digits.
   19755 **
   19756 ** Return 1 if there is a parsing error and 0 on success.
   19757 */
   19758 static int parseHhMmSs(const char *zDate, DateTime *p){
   19759   int h, m, s;
   19760   double ms = 0.0;
   19761   if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
   19762     return 1;
   19763   }
   19764   zDate += 5;
   19765   if( *zDate==':' ){
   19766     zDate++;
   19767     if( getDigits(zDate, "20e", &s)!=1 ){
   19768       return 1;
   19769     }
   19770     zDate += 2;
   19771     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
   19772       double rScale = 1.0;
   19773       zDate++;
   19774       while( sqlite3Isdigit(*zDate) ){
   19775         ms = ms*10.0 + *zDate - '0';
   19776         rScale *= 10.0;
   19777         zDate++;
   19778       }
   19779       ms /= rScale;
   19780     }
   19781   }else{
   19782     s = 0;
   19783   }
   19784   p->validJD = 0;
   19785   p->rawS = 0;
   19786   p->validHMS = 1;
   19787   p->h = h;
   19788   p->m = m;
   19789   p->s = s + ms;
   19790   if( parseTimezone(zDate, p) ) return 1;
   19791   p->validTZ = (p->tz!=0)?1:0;
   19792   return 0;
   19793 }
   19794 
   19795 /*
   19796 ** Put the DateTime object into its error state.
   19797 */
   19798 static void datetimeError(DateTime *p){
   19799   memset(p, 0, sizeof(*p));
   19800   p->isError = 1;
   19801 }
   19802 
   19803 /*
   19804 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
   19805 ** that the YYYY-MM-DD is according to the Gregorian calendar.
   19806 **
   19807 ** Reference:  Meeus page 61
   19808 */
   19809 static void computeJD(DateTime *p){
   19810   int Y, M, D, A, B, X1, X2;
   19811 
   19812   if( p->validJD ) return;
   19813   if( p->validYMD ){
   19814     Y = p->Y;
   19815     M = p->M;
   19816     D = p->D;
   19817   }else{
   19818     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
   19819     M = 1;
   19820     D = 1;
   19821   }
   19822   if( Y<-4713 || Y>9999 || p->rawS ){
   19823     datetimeError(p);
   19824     return;
   19825   }
   19826   if( M<=2 ){
   19827     Y--;
   19828     M += 12;
   19829   }
   19830   A = Y/100;
   19831   B = 2 - A + (A/4);
   19832   X1 = 36525*(Y+4716)/100;
   19833   X2 = 306001*(M+1)/10000;
   19834   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
   19835   p->validJD = 1;
   19836   if( p->validHMS ){
   19837     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
   19838     if( p->validTZ ){
   19839       p->iJD -= p->tz*60000;
   19840       p->validYMD = 0;
   19841       p->validHMS = 0;
   19842       p->validTZ = 0;
   19843     }
   19844   }
   19845 }
   19846 
   19847 /*
   19848 ** Parse dates of the form
   19849 **
   19850 **     YYYY-MM-DD HH:MM:SS.FFF
   19851 **     YYYY-MM-DD HH:MM:SS
   19852 **     YYYY-MM-DD HH:MM
   19853 **     YYYY-MM-DD
   19854 **
   19855 ** Write the result into the DateTime structure and return 0
   19856 ** on success and 1 if the input string is not a well-formed
   19857 ** date.
   19858 */
   19859 static int parseYyyyMmDd(const char *zDate, DateTime *p){
   19860   int Y, M, D, neg;
   19861 
   19862   if( zDate[0]=='-' ){
   19863     zDate++;
   19864     neg = 1;
   19865   }else{
   19866     neg = 0;
   19867   }
   19868   if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
   19869     return 1;
   19870   }
   19871   zDate += 10;
   19872   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
   19873   if( parseHhMmSs(zDate, p)==0 ){
   19874     /* We got the time */
   19875   }else if( *zDate==0 ){
   19876     p->validHMS = 0;
   19877   }else{
   19878     return 1;
   19879   }
   19880   p->validJD = 0;
   19881   p->validYMD = 1;
   19882   p->Y = neg ? -Y : Y;
   19883   p->M = M;
   19884   p->D = D;
   19885   if( p->validTZ ){
   19886     computeJD(p);
   19887   }
   19888   return 0;
   19889 }
   19890 
   19891 /*
   19892 ** Set the time to the current time reported by the VFS.
   19893 **
   19894 ** Return the number of errors.
   19895 */
   19896 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
   19897   p->iJD = sqlite3StmtCurrentTime(context);
   19898   if( p->iJD>0 ){
   19899     p->validJD = 1;
   19900     return 0;
   19901   }else{
   19902     return 1;
   19903   }
   19904 }
   19905 
   19906 /*
   19907 ** Input "r" is a numeric quantity which might be a julian day number,
   19908 ** or the number of seconds since 1970.  If the value if r is within
   19909 ** range of a julian day number, install it as such and set validJD.
   19910 ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
   19911 */
   19912 static void setRawDateNumber(DateTime *p, double r){
   19913   p->s = r;
   19914   p->rawS = 1;
   19915   if( r>=0.0 && r<5373484.5 ){
   19916     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   19917     p->validJD = 1;
   19918   }
   19919 }
   19920 
   19921 /*
   19922 ** Attempt to parse the given string into a julian day number.  Return
   19923 ** the number of errors.
   19924 **
   19925 ** The following are acceptable forms for the input string:
   19926 **
   19927 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
   19928 **      DDDD.DD
   19929 **      now
   19930 **
   19931 ** In the first form, the +/-HH:MM is always optional.  The fractional
   19932 ** seconds extension (the ".FFF") is optional.  The seconds portion
   19933 ** (":SS.FFF") is option.  The year and date can be omitted as long
   19934 ** as there is a time string.  The time string can be omitted as long
   19935 ** as there is a year and date.
   19936 */
   19937 static int parseDateOrTime(
   19938   sqlite3_context *context,
   19939   const char *zDate,
   19940   DateTime *p
   19941 ){
   19942   double r;
   19943   if( parseYyyyMmDd(zDate,p)==0 ){
   19944     return 0;
   19945   }else if( parseHhMmSs(zDate, p)==0 ){
   19946     return 0;
   19947   }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
   19948     return setDateTimeToCurrent(context, p);
   19949   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
   19950     setRawDateNumber(p, r);
   19951     return 0;
   19952   }
   19953   return 1;
   19954 }
   19955 
   19956 /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
   19957 ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
   19958 ** for DateTime.iJD.
   19959 **
   19960 ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
   19961 ** such a large integer literal, so we have to encode it.
   19962 */
   19963 #define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
   19964 
   19965 /*
   19966 ** Return TRUE if the given julian day number is within range.
   19967 **
   19968 ** The input is the JulianDay times 86400000.
   19969 */
   19970 static int validJulianDay(sqlite3_int64 iJD){
   19971   return iJD>=0 && iJD<=INT_464269060799999;
   19972 }
   19973 
   19974 /*
   19975 ** Compute the Year, Month, and Day from the julian day number.
   19976 */
   19977 static void computeYMD(DateTime *p){
   19978   int Z, A, B, C, D, E, X1;
   19979   if( p->validYMD ) return;
   19980   if( !p->validJD ){
   19981     p->Y = 2000;
   19982     p->M = 1;
   19983     p->D = 1;
   19984   }else if( !validJulianDay(p->iJD) ){
   19985     datetimeError(p);
   19986     return;
   19987   }else{
   19988     Z = (int)((p->iJD + 43200000)/86400000);
   19989     A = (int)((Z - 1867216.25)/36524.25);
   19990     A = Z + 1 + A - (A/4);
   19991     B = A + 1524;
   19992     C = (int)((B - 122.1)/365.25);
   19993     D = (36525*(C&32767))/100;
   19994     E = (int)((B-D)/30.6001);
   19995     X1 = (int)(30.6001*E);
   19996     p->D = B - D - X1;
   19997     p->M = E<14 ? E-1 : E-13;
   19998     p->Y = p->M>2 ? C - 4716 : C - 4715;
   19999   }
   20000   p->validYMD = 1;
   20001 }
   20002 
   20003 /*
   20004 ** Compute the Hour, Minute, and Seconds from the julian day number.
   20005 */
   20006 static void computeHMS(DateTime *p){
   20007   int s;
   20008   if( p->validHMS ) return;
   20009   computeJD(p);
   20010   s = (int)((p->iJD + 43200000) % 86400000);
   20011   p->s = s/1000.0;
   20012   s = (int)p->s;
   20013   p->s -= s;
   20014   p->h = s/3600;
   20015   s -= p->h*3600;
   20016   p->m = s/60;
   20017   p->s += s - p->m*60;
   20018   p->rawS = 0;
   20019   p->validHMS = 1;
   20020 }
   20021 
   20022 /*
   20023 ** Compute both YMD and HMS
   20024 */
   20025 static void computeYMD_HMS(DateTime *p){
   20026   computeYMD(p);
   20027   computeHMS(p);
   20028 }
   20029 
   20030 /*
   20031 ** Clear the YMD and HMS and the TZ
   20032 */
   20033 static void clearYMD_HMS_TZ(DateTime *p){
   20034   p->validYMD = 0;
   20035   p->validHMS = 0;
   20036   p->validTZ = 0;
   20037 }
   20038 
   20039 #ifndef SQLITE_OMIT_LOCALTIME
   20040 /*
   20041 ** On recent Windows platforms, the localtime_s() function is available
   20042 ** as part of the "Secure CRT". It is essentially equivalent to
   20043 ** localtime_r() available under most POSIX platforms, except that the
   20044 ** order of the parameters is reversed.
   20045 **
   20046 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
   20047 **
   20048 ** If the user has not indicated to use localtime_r() or localtime_s()
   20049 ** already, check for an MSVC build environment that provides
   20050 ** localtime_s().
   20051 */
   20052 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
   20053     && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
   20054 #undef  HAVE_LOCALTIME_S
   20055 #define HAVE_LOCALTIME_S 1
   20056 #endif
   20057 
   20058 /*
   20059 ** The following routine implements the rough equivalent of localtime_r()
   20060 ** using whatever operating-system specific localtime facility that
   20061 ** is available.  This routine returns 0 on success and
   20062 ** non-zero on any kind of error.
   20063 **
   20064 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
   20065 ** routine will always fail.
   20066 **
   20067 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
   20068 ** library function localtime_r() is used to assist in the calculation of
   20069 ** local time.
   20070 */
   20071 static int osLocaltime(time_t *t, struct tm *pTm){
   20072   int rc;
   20073 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
   20074   struct tm *pX;
   20075 #if SQLITE_THREADSAFE>0
   20076   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   20077 #endif
   20078   sqlite3_mutex_enter(mutex);
   20079   pX = localtime(t);
   20080 #ifndef SQLITE_UNTESTABLE
   20081   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
   20082 #endif
   20083   if( pX ) *pTm = *pX;
   20084   sqlite3_mutex_leave(mutex);
   20085   rc = pX==0;
   20086 #else
   20087 #ifndef SQLITE_UNTESTABLE
   20088   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
   20089 #endif
   20090 #if HAVE_LOCALTIME_R
   20091   rc = localtime_r(t, pTm)==0;
   20092 #else
   20093   rc = localtime_s(pTm, t);
   20094 #endif /* HAVE_LOCALTIME_R */
   20095 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
   20096   return rc;
   20097 }
   20098 #endif /* SQLITE_OMIT_LOCALTIME */
   20099 
   20100 
   20101 #ifndef SQLITE_OMIT_LOCALTIME
   20102 /*
   20103 ** Compute the difference (in milliseconds) between localtime and UTC
   20104 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
   20105 ** return this value and set *pRc to SQLITE_OK.
   20106 **
   20107 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
   20108 ** is undefined in this case.
   20109 */
   20110 static sqlite3_int64 localtimeOffset(
   20111   DateTime *p,                    /* Date at which to calculate offset */
   20112   sqlite3_context *pCtx,          /* Write error here if one occurs */
   20113   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
   20114 ){
   20115   DateTime x, y;
   20116   time_t t;
   20117   struct tm sLocal;
   20118 
   20119   /* Initialize the contents of sLocal to avoid a compiler warning. */
   20120   memset(&sLocal, 0, sizeof(sLocal));
   20121 
   20122   x = *p;
   20123   computeYMD_HMS(&x);
   20124   if( x.Y<1971 || x.Y>=2038 ){
   20125     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
   20126     ** works for years between 1970 and 2037. For dates outside this range,
   20127     ** SQLite attempts to map the year into an equivalent year within this
   20128     ** range, do the calculation, then map the year back.
   20129     */
   20130     x.Y = 2000;
   20131     x.M = 1;
   20132     x.D = 1;
   20133     x.h = 0;
   20134     x.m = 0;
   20135     x.s = 0.0;
   20136   } else {
   20137     int s = (int)(x.s + 0.5);
   20138     x.s = s;
   20139   }
   20140   x.tz = 0;
   20141   x.validJD = 0;
   20142   computeJD(&x);
   20143   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
   20144   if( osLocaltime(&t, &sLocal) ){
   20145     sqlite3_result_error(pCtx, "local time unavailable", -1);
   20146     *pRc = SQLITE_ERROR;
   20147     return 0;
   20148   }
   20149   y.Y = sLocal.tm_year + 1900;
   20150   y.M = sLocal.tm_mon + 1;
   20151   y.D = sLocal.tm_mday;
   20152   y.h = sLocal.tm_hour;
   20153   y.m = sLocal.tm_min;
   20154   y.s = sLocal.tm_sec;
   20155   y.validYMD = 1;
   20156   y.validHMS = 1;
   20157   y.validJD = 0;
   20158   y.rawS = 0;
   20159   y.validTZ = 0;
   20160   y.isError = 0;
   20161   computeJD(&y);
   20162   *pRc = SQLITE_OK;
   20163   return y.iJD - x.iJD;
   20164 }
   20165 #endif /* SQLITE_OMIT_LOCALTIME */
   20166 
   20167 /*
   20168 ** The following table defines various date transformations of the form
   20169 **
   20170 **            'NNN days'
   20171 **
   20172 ** Where NNN is an arbitrary floating-point number and "days" can be one
   20173 ** of several units of time.
   20174 */
   20175 static const struct {
   20176   u8 eType;           /* Transformation type code */
   20177   u8 nName;           /* Length of th name */
   20178   char *zName;        /* Name of the transformation */
   20179   double rLimit;      /* Maximum NNN value for this transform */
   20180   double rXform;      /* Constant used for this transform */
   20181 } aXformType[] = {
   20182   { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
   20183   { 0, 6, "minute", 7737817680.0,   86400000.0/(24.0*60.0)      },
   20184   { 0, 4, "hour",   128963628.0,    86400000.0/24.0             },
   20185   { 0, 3, "day",    5373485.0,      86400000.0                  },
   20186   { 1, 5, "month",  176546.0,       30.0*86400000.0             },
   20187   { 2, 4, "year",   14713.0,        365.0*86400000.0            },
   20188 };
   20189 
   20190 /*
   20191 ** Process a modifier to a date-time stamp.  The modifiers are
   20192 ** as follows:
   20193 **
   20194 **     NNN days
   20195 **     NNN hours
   20196 **     NNN minutes
   20197 **     NNN.NNNN seconds
   20198 **     NNN months
   20199 **     NNN years
   20200 **     start of month
   20201 **     start of year
   20202 **     start of week
   20203 **     start of day
   20204 **     weekday N
   20205 **     unixepoch
   20206 **     localtime
   20207 **     utc
   20208 **
   20209 ** Return 0 on success and 1 if there is any kind of error. If the error
   20210 ** is in a system call (i.e. localtime()), then an error message is written
   20211 ** to context pCtx. If the error is an unrecognized modifier, no error is
   20212 ** written to pCtx.
   20213 */
   20214 static int parseModifier(
   20215   sqlite3_context *pCtx,      /* Function context */
   20216   const char *z,              /* The text of the modifier */
   20217   int n,                      /* Length of zMod in bytes */
   20218   DateTime *p                 /* The date/time value to be modified */
   20219 ){
   20220   int rc = 1;
   20221   double r;
   20222   switch(sqlite3UpperToLower[(u8)z[0]] ){
   20223 #ifndef SQLITE_OMIT_LOCALTIME
   20224     case 'l': {
   20225       /*    localtime
   20226       **
   20227       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
   20228       ** show local time.
   20229       */
   20230       if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
   20231         computeJD(p);
   20232         p->iJD += localtimeOffset(p, pCtx, &rc);
   20233         clearYMD_HMS_TZ(p);
   20234       }
   20235       break;
   20236     }
   20237 #endif
   20238     case 'u': {
   20239       /*
   20240       **    unixepoch
   20241       **
   20242       ** Treat the current value of p->s as the number of
   20243       ** seconds since 1970.  Convert to a real julian day number.
   20244       */
   20245       if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
   20246         r = p->s*1000.0 + 210866760000000.0;
   20247         if( r>=0.0 && r<464269060800000.0 ){
   20248           clearYMD_HMS_TZ(p);
   20249           p->iJD = (sqlite3_int64)r;
   20250           p->validJD = 1;
   20251           p->rawS = 0;
   20252           rc = 0;
   20253         }
   20254       }
   20255 #ifndef SQLITE_OMIT_LOCALTIME
   20256       else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
   20257         if( p->tzSet==0 ){
   20258           sqlite3_int64 c1;
   20259           computeJD(p);
   20260           c1 = localtimeOffset(p, pCtx, &rc);
   20261           if( rc==SQLITE_OK ){
   20262             p->iJD -= c1;
   20263             clearYMD_HMS_TZ(p);
   20264             p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
   20265           }
   20266           p->tzSet = 1;
   20267         }else{
   20268           rc = SQLITE_OK;
   20269         }
   20270       }
   20271 #endif
   20272       break;
   20273     }
   20274     case 'w': {
   20275       /*
   20276       **    weekday N
   20277       **
   20278       ** Move the date to the same time on the next occurrence of
   20279       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
   20280       ** date is already on the appropriate weekday, this is a no-op.
   20281       */
   20282       if( sqlite3_strnicmp(z, "weekday ", 8)==0
   20283                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
   20284                && (n=(int)r)==r && n>=0 && r<7 ){
   20285         sqlite3_int64 Z;
   20286         computeYMD_HMS(p);
   20287         p->validTZ = 0;
   20288         p->validJD = 0;
   20289         computeJD(p);
   20290         Z = ((p->iJD + 129600000)/86400000) % 7;
   20291         if( Z>n ) Z -= 7;
   20292         p->iJD += (n - Z)*86400000;
   20293         clearYMD_HMS_TZ(p);
   20294         rc = 0;
   20295       }
   20296       break;
   20297     }
   20298     case 's': {
   20299       /*
   20300       **    start of TTTTT
   20301       **
   20302       ** Move the date backwards to the beginning of the current day,
   20303       ** or month or year.
   20304       */
   20305       if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
   20306       if( !p->validJD && !p->validYMD && !p->validHMS ) break;
   20307       z += 9;
   20308       computeYMD(p);
   20309       p->validHMS = 1;
   20310       p->h = p->m = 0;
   20311       p->s = 0.0;
   20312       p->rawS = 0;
   20313       p->validTZ = 0;
   20314       p->validJD = 0;
   20315       if( sqlite3_stricmp(z,"month")==0 ){
   20316         p->D = 1;
   20317         rc = 0;
   20318       }else if( sqlite3_stricmp(z,"year")==0 ){
   20319         p->M = 1;
   20320         p->D = 1;
   20321         rc = 0;
   20322       }else if( sqlite3_stricmp(z,"day")==0 ){
   20323         rc = 0;
   20324       }
   20325       break;
   20326     }
   20327     case '+':
   20328     case '-':
   20329     case '0':
   20330     case '1':
   20331     case '2':
   20332     case '3':
   20333     case '4':
   20334     case '5':
   20335     case '6':
   20336     case '7':
   20337     case '8':
   20338     case '9': {
   20339       double rRounder;
   20340       int i;
   20341       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
   20342       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
   20343         rc = 1;
   20344         break;
   20345       }
   20346       if( z[n]==':' ){
   20347         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
   20348         ** specified number of hours, minutes, seconds, and fractional seconds
   20349         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
   20350         ** omitted.
   20351         */
   20352         const char *z2 = z;
   20353         DateTime tx;
   20354         sqlite3_int64 day;
   20355         if( !sqlite3Isdigit(*z2) ) z2++;
   20356         memset(&tx, 0, sizeof(tx));
   20357         if( parseHhMmSs(z2, &tx) ) break;
   20358         computeJD(&tx);
   20359         tx.iJD -= 43200000;
   20360         day = tx.iJD/86400000;
   20361         tx.iJD -= day*86400000;
   20362         if( z[0]=='-' ) tx.iJD = -tx.iJD;
   20363         computeJD(p);
   20364         clearYMD_HMS_TZ(p);
   20365         p->iJD += tx.iJD;
   20366         rc = 0;
   20367         break;
   20368       }
   20369 
   20370       /* If control reaches this point, it means the transformation is
   20371       ** one of the forms like "+NNN days".  */
   20372       z += n;
   20373       while( sqlite3Isspace(*z) ) z++;
   20374       n = sqlite3Strlen30(z);
   20375       if( n>10 || n<3 ) break;
   20376       if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
   20377       computeJD(p);
   20378       rc = 1;
   20379       rRounder = r<0 ? -0.5 : +0.5;
   20380       for(i=0; i<ArraySize(aXformType); i++){
   20381         if( aXformType[i].nName==n
   20382          && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
   20383          && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
   20384         ){
   20385           switch( aXformType[i].eType ){
   20386             case 1: { /* Special processing to add months */
   20387               int x;
   20388               computeYMD_HMS(p);
   20389               p->M += (int)r;
   20390               x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
   20391               p->Y += x;
   20392               p->M -= x*12;
   20393               p->validJD = 0;
   20394               r -= (int)r;
   20395               break;
   20396             }
   20397             case 2: { /* Special processing to add years */
   20398               int y = (int)r;
   20399               computeYMD_HMS(p);
   20400               p->Y += y;
   20401               p->validJD = 0;
   20402               r -= (int)r;
   20403               break;
   20404             }
   20405           }
   20406           computeJD(p);
   20407           p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
   20408           rc = 0;
   20409           break;
   20410         }
   20411       }
   20412       clearYMD_HMS_TZ(p);
   20413       break;
   20414     }
   20415     default: {
   20416       break;
   20417     }
   20418   }
   20419   return rc;
   20420 }
   20421 
   20422 /*
   20423 ** Process time function arguments.  argv[0] is a date-time stamp.
   20424 ** argv[1] and following are modifiers.  Parse them all and write
   20425 ** the resulting time into the DateTime structure p.  Return 0
   20426 ** on success and 1 if there are any errors.
   20427 **
   20428 ** If there are zero parameters (if even argv[0] is undefined)
   20429 ** then assume a default value of "now" for argv[0].
   20430 */
   20431 static int isDate(
   20432   sqlite3_context *context,
   20433   int argc,
   20434   sqlite3_value **argv,
   20435   DateTime *p
   20436 ){
   20437   int i, n;
   20438   const unsigned char *z;
   20439   int eType;
   20440   memset(p, 0, sizeof(*p));
   20441   if( argc==0 ){
   20442     return setDateTimeToCurrent(context, p);
   20443   }
   20444   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
   20445                    || eType==SQLITE_INTEGER ){
   20446     setRawDateNumber(p, sqlite3_value_double(argv[0]));
   20447   }else{
   20448     z = sqlite3_value_text(argv[0]);
   20449     if( !z || parseDateOrTime(context, (char*)z, p) ){
   20450       return 1;
   20451     }
   20452   }
   20453   for(i=1; i<argc; i++){
   20454     z = sqlite3_value_text(argv[i]);
   20455     n = sqlite3_value_bytes(argv[i]);
   20456     if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
   20457   }
   20458   computeJD(p);
   20459   if( p->isError || !validJulianDay(p->iJD) ) return 1;
   20460   return 0;
   20461 }
   20462 
   20463 
   20464 /*
   20465 ** The following routines implement the various date and time functions
   20466 ** of SQLite.
   20467 */
   20468 
   20469 /*
   20470 **    julianday( TIMESTRING, MOD, MOD, ...)
   20471 **
   20472 ** Return the julian day number of the date specified in the arguments
   20473 */
   20474 static void juliandayFunc(
   20475   sqlite3_context *context,
   20476   int argc,
   20477   sqlite3_value **argv
   20478 ){
   20479   DateTime x;
   20480   if( isDate(context, argc, argv, &x)==0 ){
   20481     computeJD(&x);
   20482     sqlite3_result_double(context, x.iJD/86400000.0);
   20483   }
   20484 }
   20485 
   20486 /*
   20487 **    datetime( TIMESTRING, MOD, MOD, ...)
   20488 **
   20489 ** Return YYYY-MM-DD HH:MM:SS
   20490 */
   20491 static void datetimeFunc(
   20492   sqlite3_context *context,
   20493   int argc,
   20494   sqlite3_value **argv
   20495 ){
   20496   DateTime x;
   20497   if( isDate(context, argc, argv, &x)==0 ){
   20498     char zBuf[100];
   20499     computeYMD_HMS(&x);
   20500     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
   20501                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
   20502     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   20503   }
   20504 }
   20505 
   20506 /*
   20507 **    time( TIMESTRING, MOD, MOD, ...)
   20508 **
   20509 ** Return HH:MM:SS
   20510 */
   20511 static void timeFunc(
   20512   sqlite3_context *context,
   20513   int argc,
   20514   sqlite3_value **argv
   20515 ){
   20516   DateTime x;
   20517   if( isDate(context, argc, argv, &x)==0 ){
   20518     char zBuf[100];
   20519     computeHMS(&x);
   20520     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
   20521     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   20522   }
   20523 }
   20524 
   20525 /*
   20526 **    date( TIMESTRING, MOD, MOD, ...)
   20527 **
   20528 ** Return YYYY-MM-DD
   20529 */
   20530 static void dateFunc(
   20531   sqlite3_context *context,
   20532   int argc,
   20533   sqlite3_value **argv
   20534 ){
   20535   DateTime x;
   20536   if( isDate(context, argc, argv, &x)==0 ){
   20537     char zBuf[100];
   20538     computeYMD(&x);
   20539     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
   20540     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   20541   }
   20542 }
   20543 
   20544 /*
   20545 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
   20546 **
   20547 ** Return a string described by FORMAT.  Conversions as follows:
   20548 **
   20549 **   %d  day of month
   20550 **   %f  ** fractional seconds  SS.SSS
   20551 **   %H  hour 00-24
   20552 **   %j  day of year 000-366
   20553 **   %J  ** julian day number
   20554 **   %m  month 01-12
   20555 **   %M  minute 00-59
   20556 **   %s  seconds since 1970-01-01
   20557 **   %S  seconds 00-59
   20558 **   %w  day of week 0-6  sunday==0
   20559 **   %W  week of year 00-53
   20560 **   %Y  year 0000-9999
   20561 **   %%  %
   20562 */
   20563 static void strftimeFunc(
   20564   sqlite3_context *context,
   20565   int argc,
   20566   sqlite3_value **argv
   20567 ){
   20568   DateTime x;
   20569   u64 n;
   20570   size_t i,j;
   20571   char *z;
   20572   sqlite3 *db;
   20573   const char *zFmt;
   20574   char zBuf[100];
   20575   if( argc==0 ) return;
   20576   zFmt = (const char*)sqlite3_value_text(argv[0]);
   20577   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
   20578   db = sqlite3_context_db_handle(context);
   20579   for(i=0, n=1; zFmt[i]; i++, n++){
   20580     if( zFmt[i]=='%' ){
   20581       switch( zFmt[i+1] ){
   20582         case 'd':
   20583         case 'H':
   20584         case 'm':
   20585         case 'M':
   20586         case 'S':
   20587         case 'W':
   20588           n++;
   20589           /* fall thru */
   20590         case 'w':
   20591         case '%':
   20592           break;
   20593         case 'f':
   20594           n += 8;
   20595           break;
   20596         case 'j':
   20597           n += 3;
   20598           break;
   20599         case 'Y':
   20600           n += 8;
   20601           break;
   20602         case 's':
   20603         case 'J':
   20604           n += 50;
   20605           break;
   20606         default:
   20607           return;  /* ERROR.  return a NULL */
   20608       }
   20609       i++;
   20610     }
   20611   }
   20612   testcase( n==sizeof(zBuf)-1 );
   20613   testcase( n==sizeof(zBuf) );
   20614   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   20615   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
   20616   if( n<sizeof(zBuf) ){
   20617     z = zBuf;
   20618   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   20619     sqlite3_result_error_toobig(context);
   20620     return;
   20621   }else{
   20622     z = sqlite3DbMallocRawNN(db, (int)n);
   20623     if( z==0 ){
   20624       sqlite3_result_error_nomem(context);
   20625       return;
   20626     }
   20627   }
   20628   computeJD(&x);
   20629   computeYMD_HMS(&x);
   20630   for(i=j=0; zFmt[i]; i++){
   20631     if( zFmt[i]!='%' ){
   20632       z[j++] = zFmt[i];
   20633     }else{
   20634       i++;
   20635       switch( zFmt[i] ){
   20636         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
   20637         case 'f': {
   20638           double s = x.s;
   20639           if( s>59.999 ) s = 59.999;
   20640           sqlite3_snprintf(7, &z[j],"%06.3f", s);
   20641           j += sqlite3Strlen30(&z[j]);
   20642           break;
   20643         }
   20644         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
   20645         case 'W': /* Fall thru */
   20646         case 'j': {
   20647           int nDay;             /* Number of days since 1st day of year */
   20648           DateTime y = x;
   20649           y.validJD = 0;
   20650           y.M = 1;
   20651           y.D = 1;
   20652           computeJD(&y);
   20653           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
   20654           if( zFmt[i]=='W' ){
   20655             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
   20656             wd = (int)(((x.iJD+43200000)/86400000)%7);
   20657             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
   20658             j += 2;
   20659           }else{
   20660             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
   20661             j += 3;
   20662           }
   20663           break;
   20664         }
   20665         case 'J': {
   20666           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
   20667           j+=sqlite3Strlen30(&z[j]);
   20668           break;
   20669         }
   20670         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
   20671         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
   20672         case 's': {
   20673           sqlite3_snprintf(30,&z[j],"%lld",
   20674                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
   20675           j += sqlite3Strlen30(&z[j]);
   20676           break;
   20677         }
   20678         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
   20679         case 'w': {
   20680           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
   20681           break;
   20682         }
   20683         case 'Y': {
   20684           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
   20685           break;
   20686         }
   20687         default:   z[j++] = '%'; break;
   20688       }
   20689     }
   20690   }
   20691   z[j] = 0;
   20692   sqlite3_result_text(context, z, -1,
   20693                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
   20694 }
   20695 
   20696 /*
   20697 ** current_time()
   20698 **
   20699 ** This function returns the same value as time('now').
   20700 */
   20701 static void ctimeFunc(
   20702   sqlite3_context *context,
   20703   int NotUsed,
   20704   sqlite3_value **NotUsed2
   20705 ){
   20706   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   20707   timeFunc(context, 0, 0);
   20708 }
   20709 
   20710 /*
   20711 ** current_date()
   20712 **
   20713 ** This function returns the same value as date('now').
   20714 */
   20715 static void cdateFunc(
   20716   sqlite3_context *context,
   20717   int NotUsed,
   20718   sqlite3_value **NotUsed2
   20719 ){
   20720   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   20721   dateFunc(context, 0, 0);
   20722 }
   20723 
   20724 /*
   20725 ** current_timestamp()
   20726 **
   20727 ** This function returns the same value as datetime('now').
   20728 */
   20729 static void ctimestampFunc(
   20730   sqlite3_context *context,
   20731   int NotUsed,
   20732   sqlite3_value **NotUsed2
   20733 ){
   20734   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   20735   datetimeFunc(context, 0, 0);
   20736 }
   20737 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
   20738 
   20739 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   20740 /*
   20741 ** If the library is compiled to omit the full-scale date and time
   20742 ** handling (to get a smaller binary), the following minimal version
   20743 ** of the functions current_time(), current_date() and current_timestamp()
   20744 ** are included instead. This is to support column declarations that
   20745 ** include "DEFAULT CURRENT_TIME" etc.
   20746 **
   20747 ** This function uses the C-library functions time(), gmtime()
   20748 ** and strftime(). The format string to pass to strftime() is supplied
   20749 ** as the user-data for the function.
   20750 */
   20751 static void currentTimeFunc(
   20752   sqlite3_context *context,
   20753   int argc,
   20754   sqlite3_value **argv
   20755 ){
   20756   time_t t;
   20757   char *zFormat = (char *)sqlite3_user_data(context);
   20758   sqlite3_int64 iT;
   20759   struct tm *pTm;
   20760   struct tm sNow;
   20761   char zBuf[20];
   20762 
   20763   UNUSED_PARAMETER(argc);
   20764   UNUSED_PARAMETER(argv);
   20765 
   20766   iT = sqlite3StmtCurrentTime(context);
   20767   if( iT<=0 ) return;
   20768   t = iT/1000 - 10000*(sqlite3_int64)21086676;
   20769 #if HAVE_GMTIME_R
   20770   pTm = gmtime_r(&t, &sNow);
   20771 #else
   20772   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   20773   pTm = gmtime(&t);
   20774   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
   20775   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   20776 #endif
   20777   if( pTm ){
   20778     strftime(zBuf, 20, zFormat, &sNow);
   20779     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   20780   }
   20781 }
   20782 #endif
   20783 
   20784 /*
   20785 ** This function registered all of the above C functions as SQL
   20786 ** functions.  This should be the only routine in this file with
   20787 ** external linkage.
   20788 */
   20789 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
   20790   static FuncDef aDateTimeFuncs[] = {
   20791 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   20792     PURE_DATE(julianday,        -1, 0, 0, juliandayFunc ),
   20793     PURE_DATE(date,             -1, 0, 0, dateFunc      ),
   20794     PURE_DATE(time,             -1, 0, 0, timeFunc      ),
   20795     PURE_DATE(datetime,         -1, 0, 0, datetimeFunc  ),
   20796     PURE_DATE(strftime,         -1, 0, 0, strftimeFunc  ),
   20797     DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
   20798     DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
   20799     DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
   20800 #else
   20801     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
   20802     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
   20803     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
   20804 #endif
   20805   };
   20806   sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
   20807 }
   20808 
   20809 /************** End of date.c ************************************************/
   20810 /************** Begin file os.c **********************************************/
   20811 /*
   20812 ** 2005 November 29
   20813 **
   20814 ** The author disclaims copyright to this source code.  In place of
   20815 ** a legal notice, here is a blessing:
   20816 **
   20817 **    May you do good and not evil.
   20818 **    May you find forgiveness for yourself and forgive others.
   20819 **    May you share freely, never taking more than you give.
   20820 **
   20821 ******************************************************************************
   20822 **
   20823 ** This file contains OS interface code that is common to all
   20824 ** architectures.
   20825 */
   20826 /* #include "sqliteInt.h" */
   20827 
   20828 /*
   20829 ** If we compile with the SQLITE_TEST macro set, then the following block
   20830 ** of code will give us the ability to simulate a disk I/O error.  This
   20831 ** is used for testing the I/O recovery logic.
   20832 */
   20833 #if defined(SQLITE_TEST)
   20834 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   20835 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   20836 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   20837 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   20838 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   20839 SQLITE_API int sqlite3_diskfull_pending = 0;
   20840 SQLITE_API int sqlite3_diskfull = 0;
   20841 #endif /* defined(SQLITE_TEST) */
   20842 
   20843 /*
   20844 ** When testing, also keep a count of the number of open files.
   20845 */
   20846 #if defined(SQLITE_TEST)
   20847 SQLITE_API int sqlite3_open_file_count = 0;
   20848 #endif /* defined(SQLITE_TEST) */
   20849 
   20850 /*
   20851 ** The default SQLite sqlite3_vfs implementations do not allocate
   20852 ** memory (actually, os_unix.c allocates a small amount of memory
   20853 ** from within OsOpen()), but some third-party implementations may.
   20854 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
   20855 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
   20856 **
   20857 ** The following functions are instrumented for malloc() failure
   20858 ** testing:
   20859 **
   20860 **     sqlite3OsRead()
   20861 **     sqlite3OsWrite()
   20862 **     sqlite3OsSync()
   20863 **     sqlite3OsFileSize()
   20864 **     sqlite3OsLock()
   20865 **     sqlite3OsCheckReservedLock()
   20866 **     sqlite3OsFileControl()
   20867 **     sqlite3OsShmMap()
   20868 **     sqlite3OsOpen()
   20869 **     sqlite3OsDelete()
   20870 **     sqlite3OsAccess()
   20871 **     sqlite3OsFullPathname()
   20872 **
   20873 */
   20874 #if defined(SQLITE_TEST)
   20875 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
   20876   #define DO_OS_MALLOC_TEST(x)                                       \
   20877   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
   20878     void *pTstAlloc = sqlite3Malloc(10);                             \
   20879     if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
   20880     sqlite3_free(pTstAlloc);                                         \
   20881   }
   20882 #else
   20883   #define DO_OS_MALLOC_TEST(x)
   20884 #endif
   20885 
   20886 /*
   20887 ** The following routines are convenience wrappers around methods
   20888 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
   20889 ** of this would be completely automatic if SQLite were coded using
   20890 ** C++ instead of plain old C.
   20891 */
   20892 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
   20893   if( pId->pMethods ){
   20894     pId->pMethods->xClose(pId);
   20895     pId->pMethods = 0;
   20896   }
   20897 }
   20898 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
   20899   DO_OS_MALLOC_TEST(id);
   20900   return id->pMethods->xRead(id, pBuf, amt, offset);
   20901 }
   20902 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
   20903   DO_OS_MALLOC_TEST(id);
   20904   return id->pMethods->xWrite(id, pBuf, amt, offset);
   20905 }
   20906 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
   20907   return id->pMethods->xTruncate(id, size);
   20908 }
   20909 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
   20910   DO_OS_MALLOC_TEST(id);
   20911   return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
   20912 }
   20913 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
   20914   DO_OS_MALLOC_TEST(id);
   20915   return id->pMethods->xFileSize(id, pSize);
   20916 }
   20917 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
   20918   DO_OS_MALLOC_TEST(id);
   20919   return id->pMethods->xLock(id, lockType);
   20920 }
   20921 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
   20922   return id->pMethods->xUnlock(id, lockType);
   20923 }
   20924 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
   20925   DO_OS_MALLOC_TEST(id);
   20926   return id->pMethods->xCheckReservedLock(id, pResOut);
   20927 }
   20928 
   20929 /*
   20930 ** Use sqlite3OsFileControl() when we are doing something that might fail
   20931 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
   20932 ** when simply tossing information over the wall to the VFS and we do not
   20933 ** really care if the VFS receives and understands the information since it
   20934 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
   20935 ** routine has no return value since the return value would be meaningless.
   20936 */
   20937 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
   20938 #ifdef SQLITE_TEST
   20939   if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
   20940     /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
   20941     ** is using a regular VFS, it is called after the corresponding
   20942     ** transaction has been committed. Injecting a fault at this point
   20943     ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
   20944     ** but the transaction is committed anyway.
   20945     **
   20946     ** The core must call OsFileControl() though, not OsFileControlHint(),
   20947     ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
   20948     ** means the commit really has failed and an error should be returned
   20949     ** to the user.  */
   20950     DO_OS_MALLOC_TEST(id);
   20951   }
   20952 #endif
   20953   return id->pMethods->xFileControl(id, op, pArg);
   20954 }
   20955 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
   20956   (void)id->pMethods->xFileControl(id, op, pArg);
   20957 }
   20958 
   20959 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
   20960   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
   20961   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
   20962 }
   20963 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
   20964   return id->pMethods->xDeviceCharacteristics(id);
   20965 }
   20966 #ifndef SQLITE_OMIT_WAL
   20967 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
   20968   return id->pMethods->xShmLock(id, offset, n, flags);
   20969 }
   20970 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
   20971   id->pMethods->xShmBarrier(id);
   20972 }
   20973 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
   20974   return id->pMethods->xShmUnmap(id, deleteFlag);
   20975 }
   20976 SQLITE_PRIVATE int sqlite3OsShmMap(
   20977   sqlite3_file *id,               /* Database file handle */
   20978   int iPage,
   20979   int pgsz,
   20980   int bExtend,                    /* True to extend file if necessary */
   20981   void volatile **pp              /* OUT: Pointer to mapping */
   20982 ){
   20983   DO_OS_MALLOC_TEST(id);
   20984   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
   20985 }
   20986 #endif /* SQLITE_OMIT_WAL */
   20987 
   20988 #if SQLITE_MAX_MMAP_SIZE>0
   20989 /* The real implementation of xFetch and xUnfetch */
   20990 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
   20991   DO_OS_MALLOC_TEST(id);
   20992   return id->pMethods->xFetch(id, iOff, iAmt, pp);
   20993 }
   20994 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
   20995   return id->pMethods->xUnfetch(id, iOff, p);
   20996 }
   20997 #else
   20998 /* No-op stubs to use when memory-mapped I/O is disabled */
   20999 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
   21000   *pp = 0;
   21001   return SQLITE_OK;
   21002 }
   21003 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
   21004   return SQLITE_OK;
   21005 }
   21006 #endif
   21007 
   21008 /*
   21009 ** The next group of routines are convenience wrappers around the
   21010 ** VFS methods.
   21011 */
   21012 SQLITE_PRIVATE int sqlite3OsOpen(
   21013   sqlite3_vfs *pVfs,
   21014   const char *zPath,
   21015   sqlite3_file *pFile,
   21016   int flags,
   21017   int *pFlagsOut
   21018 ){
   21019   int rc;
   21020   DO_OS_MALLOC_TEST(0);
   21021   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
   21022   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   21023   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   21024   ** reaching the VFS. */
   21025   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
   21026   assert( rc==SQLITE_OK || pFile->pMethods==0 );
   21027   return rc;
   21028 }
   21029 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   21030   DO_OS_MALLOC_TEST(0);
   21031   assert( dirSync==0 || dirSync==1 );
   21032   return pVfs->xDelete(pVfs, zPath, dirSync);
   21033 }
   21034 SQLITE_PRIVATE int sqlite3OsAccess(
   21035   sqlite3_vfs *pVfs,
   21036   const char *zPath,
   21037   int flags,
   21038   int *pResOut
   21039 ){
   21040   DO_OS_MALLOC_TEST(0);
   21041   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
   21042 }
   21043 SQLITE_PRIVATE int sqlite3OsFullPathname(
   21044   sqlite3_vfs *pVfs,
   21045   const char *zPath,
   21046   int nPathOut,
   21047   char *zPathOut
   21048 ){
   21049   DO_OS_MALLOC_TEST(0);
   21050   zPathOut[0] = 0;
   21051   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
   21052 }
   21053 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   21054 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   21055   return pVfs->xDlOpen(pVfs, zPath);
   21056 }
   21057 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   21058   pVfs->xDlError(pVfs, nByte, zBufOut);
   21059 }
   21060 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
   21061   return pVfs->xDlSym(pVfs, pHdle, zSym);
   21062 }
   21063 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
   21064   pVfs->xDlClose(pVfs, pHandle);
   21065 }
   21066 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   21067 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   21068   return pVfs->xRandomness(pVfs, nByte, zBufOut);
   21069 }
   21070 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
   21071   return pVfs->xSleep(pVfs, nMicro);
   21072 }
   21073 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
   21074   return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
   21075 }
   21076 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
   21077   int rc;
   21078   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
   21079   ** method to get the current date and time if that method is available
   21080   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
   21081   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
   21082   ** unavailable.
   21083   */
   21084   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
   21085     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
   21086   }else{
   21087     double r;
   21088     rc = pVfs->xCurrentTime(pVfs, &r);
   21089     *pTimeOut = (sqlite3_int64)(r*86400000.0);
   21090   }
   21091   return rc;
   21092 }
   21093 
   21094 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
   21095   sqlite3_vfs *pVfs,
   21096   const char *zFile,
   21097   sqlite3_file **ppFile,
   21098   int flags,
   21099   int *pOutFlags
   21100 ){
   21101   int rc;
   21102   sqlite3_file *pFile;
   21103   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
   21104   if( pFile ){
   21105     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
   21106     if( rc!=SQLITE_OK ){
   21107       sqlite3_free(pFile);
   21108     }else{
   21109       *ppFile = pFile;
   21110     }
   21111   }else{
   21112     rc = SQLITE_NOMEM_BKPT;
   21113   }
   21114   return rc;
   21115 }
   21116 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
   21117   assert( pFile );
   21118   sqlite3OsClose(pFile);
   21119   sqlite3_free(pFile);
   21120 }
   21121 
   21122 /*
   21123 ** This function is a wrapper around the OS specific implementation of
   21124 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
   21125 ** ability to simulate a malloc failure, so that the handling of an
   21126 ** error in sqlite3_os_init() by the upper layers can be tested.
   21127 */
   21128 SQLITE_PRIVATE int sqlite3OsInit(void){
   21129   void *p = sqlite3_malloc(10);
   21130   if( p==0 ) return SQLITE_NOMEM_BKPT;
   21131   sqlite3_free(p);
   21132   return sqlite3_os_init();
   21133 }
   21134 
   21135 /*
   21136 ** The list of all registered VFS implementations.
   21137 */
   21138 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
   21139 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
   21140 
   21141 /*
   21142 ** Locate a VFS by name.  If no name is given, simply return the
   21143 ** first VFS on the list.
   21144 */
   21145 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
   21146   sqlite3_vfs *pVfs = 0;
   21147 #if SQLITE_THREADSAFE
   21148   sqlite3_mutex *mutex;
   21149 #endif
   21150 #ifndef SQLITE_OMIT_AUTOINIT
   21151   int rc = sqlite3_initialize();
   21152   if( rc ) return 0;
   21153 #endif
   21154 #if SQLITE_THREADSAFE
   21155   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   21156 #endif
   21157   sqlite3_mutex_enter(mutex);
   21158   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
   21159     if( zVfs==0 ) break;
   21160     if( strcmp(zVfs, pVfs->zName)==0 ) break;
   21161   }
   21162   sqlite3_mutex_leave(mutex);
   21163   return pVfs;
   21164 }
   21165 
   21166 /*
   21167 ** Unlink a VFS from the linked list
   21168 */
   21169 static void vfsUnlink(sqlite3_vfs *pVfs){
   21170   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
   21171   if( pVfs==0 ){
   21172     /* No-op */
   21173   }else if( vfsList==pVfs ){
   21174     vfsList = pVfs->pNext;
   21175   }else if( vfsList ){
   21176     sqlite3_vfs *p = vfsList;
   21177     while( p->pNext && p->pNext!=pVfs ){
   21178       p = p->pNext;
   21179     }
   21180     if( p->pNext==pVfs ){
   21181       p->pNext = pVfs->pNext;
   21182     }
   21183   }
   21184 }
   21185 
   21186 /*
   21187 ** Register a VFS with the system.  It is harmless to register the same
   21188 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
   21189 ** true.
   21190 */
   21191 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
   21192   MUTEX_LOGIC(sqlite3_mutex *mutex;)
   21193 #ifndef SQLITE_OMIT_AUTOINIT
   21194   int rc = sqlite3_initialize();
   21195   if( rc ) return rc;
   21196 #endif
   21197 #ifdef SQLITE_ENABLE_API_ARMOR
   21198   if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
   21199 #endif
   21200 
   21201   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   21202   sqlite3_mutex_enter(mutex);
   21203   vfsUnlink(pVfs);
   21204   if( makeDflt || vfsList==0 ){
   21205     pVfs->pNext = vfsList;
   21206     vfsList = pVfs;
   21207   }else{
   21208     pVfs->pNext = vfsList->pNext;
   21209     vfsList->pNext = pVfs;
   21210   }
   21211   assert(vfsList);
   21212   sqlite3_mutex_leave(mutex);
   21213   return SQLITE_OK;
   21214 }
   21215 
   21216 /*
   21217 ** Unregister a VFS so that it is no longer accessible.
   21218 */
   21219 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
   21220 #if SQLITE_THREADSAFE
   21221   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   21222 #endif
   21223   sqlite3_mutex_enter(mutex);
   21224   vfsUnlink(pVfs);
   21225   sqlite3_mutex_leave(mutex);
   21226   return SQLITE_OK;
   21227 }
   21228 
   21229 /************** End of os.c **************************************************/
   21230 /************** Begin file fault.c *******************************************/
   21231 /*
   21232 ** 2008 Jan 22
   21233 **
   21234 ** The author disclaims copyright to this source code.  In place of
   21235 ** a legal notice, here is a blessing:
   21236 **
   21237 **    May you do good and not evil.
   21238 **    May you find forgiveness for yourself and forgive others.
   21239 **    May you share freely, never taking more than you give.
   21240 **
   21241 *************************************************************************
   21242 **
   21243 ** This file contains code to support the concept of "benign"
   21244 ** malloc failures (when the xMalloc() or xRealloc() method of the
   21245 ** sqlite3_mem_methods structure fails to allocate a block of memory
   21246 ** and returns 0).
   21247 **
   21248 ** Most malloc failures are non-benign. After they occur, SQLite
   21249 ** abandons the current operation and returns an error code (usually
   21250 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
   21251 ** fatal. For example, if a malloc fails while resizing a hash table, this
   21252 ** is completely recoverable simply by not carrying out the resize. The
   21253 ** hash table will continue to function normally.  So a malloc failure
   21254 ** during a hash table resize is a benign fault.
   21255 */
   21256 
   21257 /* #include "sqliteInt.h" */
   21258 
   21259 #ifndef SQLITE_UNTESTABLE
   21260 
   21261 /*
   21262 ** Global variables.
   21263 */
   21264 typedef struct BenignMallocHooks BenignMallocHooks;
   21265 static SQLITE_WSD struct BenignMallocHooks {
   21266   void (*xBenignBegin)(void);
   21267   void (*xBenignEnd)(void);
   21268 } sqlite3Hooks = { 0, 0 };
   21269 
   21270 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
   21271 ** structure.  If writable static data is unsupported on the target,
   21272 ** we have to locate the state vector at run-time.  In the more common
   21273 ** case where writable static data is supported, wsdHooks can refer directly
   21274 ** to the "sqlite3Hooks" state vector declared above.
   21275 */
   21276 #ifdef SQLITE_OMIT_WSD
   21277 # define wsdHooksInit \
   21278   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
   21279 # define wsdHooks x[0]
   21280 #else
   21281 # define wsdHooksInit
   21282 # define wsdHooks sqlite3Hooks
   21283 #endif
   21284 
   21285 
   21286 /*
   21287 ** Register hooks to call when sqlite3BeginBenignMalloc() and
   21288 ** sqlite3EndBenignMalloc() are called, respectively.
   21289 */
   21290 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
   21291   void (*xBenignBegin)(void),
   21292   void (*xBenignEnd)(void)
   21293 ){
   21294   wsdHooksInit;
   21295   wsdHooks.xBenignBegin = xBenignBegin;
   21296   wsdHooks.xBenignEnd = xBenignEnd;
   21297 }
   21298 
   21299 /*
   21300 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
   21301 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
   21302 ** indicates that subsequent malloc failures are non-benign.
   21303 */
   21304 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
   21305   wsdHooksInit;
   21306   if( wsdHooks.xBenignBegin ){
   21307     wsdHooks.xBenignBegin();
   21308   }
   21309 }
   21310 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
   21311   wsdHooksInit;
   21312   if( wsdHooks.xBenignEnd ){
   21313     wsdHooks.xBenignEnd();
   21314   }
   21315 }
   21316 
   21317 #endif   /* #ifndef SQLITE_UNTESTABLE */
   21318 
   21319 /************** End of fault.c ***********************************************/
   21320 /************** Begin file mem0.c ********************************************/
   21321 /*
   21322 ** 2008 October 28
   21323 **
   21324 ** The author disclaims copyright to this source code.  In place of
   21325 ** a legal notice, here is a blessing:
   21326 **
   21327 **    May you do good and not evil.
   21328 **    May you find forgiveness for yourself and forgive others.
   21329 **    May you share freely, never taking more than you give.
   21330 **
   21331 *************************************************************************
   21332 **
   21333 ** This file contains a no-op memory allocation drivers for use when
   21334 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
   21335 ** here always fail.  SQLite will not operate with these drivers.  These
   21336 ** are merely placeholders.  Real drivers must be substituted using
   21337 ** sqlite3_config() before SQLite will operate.
   21338 */
   21339 /* #include "sqliteInt.h" */
   21340 
   21341 /*
   21342 ** This version of the memory allocator is the default.  It is
   21343 ** used when no other memory allocator is specified using compile-time
   21344 ** macros.
   21345 */
   21346 #ifdef SQLITE_ZERO_MALLOC
   21347 
   21348 /*
   21349 ** No-op versions of all memory allocation routines
   21350 */
   21351 static void *sqlite3MemMalloc(int nByte){ return 0; }
   21352 static void sqlite3MemFree(void *pPrior){ return; }
   21353 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
   21354 static int sqlite3MemSize(void *pPrior){ return 0; }
   21355 static int sqlite3MemRoundup(int n){ return n; }
   21356 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
   21357 static void sqlite3MemShutdown(void *NotUsed){ return; }
   21358 
   21359 /*
   21360 ** This routine is the only routine in this file with external linkage.
   21361 **
   21362 ** Populate the low-level memory allocation function pointers in
   21363 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   21364 */
   21365 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   21366   static const sqlite3_mem_methods defaultMethods = {
   21367      sqlite3MemMalloc,
   21368      sqlite3MemFree,
   21369      sqlite3MemRealloc,
   21370      sqlite3MemSize,
   21371      sqlite3MemRoundup,
   21372      sqlite3MemInit,
   21373      sqlite3MemShutdown,
   21374      0
   21375   };
   21376   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   21377 }
   21378 
   21379 #endif /* SQLITE_ZERO_MALLOC */
   21380 
   21381 /************** End of mem0.c ************************************************/
   21382 /************** Begin file mem1.c ********************************************/
   21383 /*
   21384 ** 2007 August 14
   21385 **
   21386 ** The author disclaims copyright to this source code.  In place of
   21387 ** a legal notice, here is a blessing:
   21388 **
   21389 **    May you do good and not evil.
   21390 **    May you find forgiveness for yourself and forgive others.
   21391 **    May you share freely, never taking more than you give.
   21392 **
   21393 *************************************************************************
   21394 **
   21395 ** This file contains low-level memory allocation drivers for when
   21396 ** SQLite will use the standard C-library malloc/realloc/free interface
   21397 ** to obtain the memory it needs.
   21398 **
   21399 ** This file contains implementations of the low-level memory allocation
   21400 ** routines specified in the sqlite3_mem_methods object.  The content of
   21401 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
   21402 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
   21403 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
   21404 ** default configuration is to use memory allocation routines in this
   21405 ** file.
   21406 **
   21407 ** C-preprocessor macro summary:
   21408 **
   21409 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
   21410 **                                the malloc_usable_size() interface exists
   21411 **                                on the target platform.  Or, this symbol
   21412 **                                can be set manually, if desired.
   21413 **                                If an equivalent interface exists by
   21414 **                                a different name, using a separate -D
   21415 **                                option to rename it.
   21416 **
   21417 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
   21418 **                                memory allocator.  Set this symbol to enable
   21419 **                                building on older macs.
   21420 **
   21421 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
   21422 **                                _msize() on windows systems.  This might
   21423 **                                be necessary when compiling for Delphi,
   21424 **                                for example.
   21425 */
   21426 /* #include "sqliteInt.h" */
   21427 
   21428 /*
   21429 ** This version of the memory allocator is the default.  It is
   21430 ** used when no other memory allocator is specified using compile-time
   21431 ** macros.
   21432 */
   21433 #ifdef SQLITE_SYSTEM_MALLOC
   21434 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
   21435 
   21436 /*
   21437 ** Use the zone allocator available on apple products unless the
   21438 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
   21439 */
   21440 #include <sys/sysctl.h>
   21441 #include <malloc/malloc.h>
   21442 #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
   21443 #include <libkern/OSAtomic.h>
   21444 #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
   21445 static malloc_zone_t* _sqliteZone_;
   21446 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
   21447 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
   21448 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
   21449 #define SQLITE_MALLOCSIZE(x) \
   21450         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
   21451 
   21452 #else /* if not __APPLE__ */
   21453 
   21454 /*
   21455 ** Use standard C library malloc and free on non-Apple systems.
   21456 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
   21457 */
   21458 #define SQLITE_MALLOC(x)             malloc(x)
   21459 #define SQLITE_FREE(x)               free(x)
   21460 #define SQLITE_REALLOC(x,y)          realloc((x),(y))
   21461 
   21462 /*
   21463 ** The malloc.h header file is needed for malloc_usable_size() function
   21464 ** on some systems (e.g. Linux).
   21465 */
   21466 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
   21467 #  define SQLITE_USE_MALLOC_H 1
   21468 #  define SQLITE_USE_MALLOC_USABLE_SIZE 1
   21469 /*
   21470 ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
   21471 ** use of _msize() is automatic, but can be disabled by compiling with
   21472 ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
   21473 ** the malloc.h header file.
   21474 */
   21475 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
   21476 #  define SQLITE_USE_MALLOC_H
   21477 #  define SQLITE_USE_MSIZE
   21478 #endif
   21479 
   21480 /*
   21481 ** Include the malloc.h header file, if necessary.  Also set define macro
   21482 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
   21483 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
   21484 ** The memory size function can always be overridden manually by defining
   21485 ** the macro SQLITE_MALLOCSIZE to the desired function name.
   21486 */
   21487 #if defined(SQLITE_USE_MALLOC_H)
   21488 #  include <malloc.h>
   21489 #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
   21490 #    if !defined(SQLITE_MALLOCSIZE)
   21491 #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
   21492 #    endif
   21493 #  elif defined(SQLITE_USE_MSIZE)
   21494 #    if !defined(SQLITE_MALLOCSIZE)
   21495 #      define SQLITE_MALLOCSIZE      _msize
   21496 #    endif
   21497 #  endif
   21498 #endif /* defined(SQLITE_USE_MALLOC_H) */
   21499 
   21500 #endif /* __APPLE__ or not __APPLE__ */
   21501 
   21502 /*
   21503 ** Like malloc(), but remember the size of the allocation
   21504 ** so that we can find it later using sqlite3MemSize().
   21505 **
   21506 ** For this low-level routine, we are guaranteed that nByte>0 because
   21507 ** cases of nByte<=0 will be intercepted and dealt with by higher level
   21508 ** routines.
   21509 */
   21510 static void *sqlite3MemMalloc(int nByte){
   21511 #ifdef SQLITE_MALLOCSIZE
   21512   void *p;
   21513   testcase( ROUND8(nByte)==nByte );
   21514   p = SQLITE_MALLOC( nByte );
   21515   if( p==0 ){
   21516     testcase( sqlite3GlobalConfig.xLog!=0 );
   21517     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   21518   }
   21519   return p;
   21520 #else
   21521   sqlite3_int64 *p;
   21522   assert( nByte>0 );
   21523   testcase( ROUND8(nByte)!=nByte );
   21524   p = SQLITE_MALLOC( nByte+8 );
   21525   if( p ){
   21526     p[0] = nByte;
   21527     p++;
   21528   }else{
   21529     testcase( sqlite3GlobalConfig.xLog!=0 );
   21530     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   21531   }
   21532   return (void *)p;
   21533 #endif
   21534 }
   21535 
   21536 /*
   21537 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
   21538 ** or sqlite3MemRealloc().
   21539 **
   21540 ** For this low-level routine, we already know that pPrior!=0 since
   21541 ** cases where pPrior==0 will have been intecepted and dealt with
   21542 ** by higher-level routines.
   21543 */
   21544 static void sqlite3MemFree(void *pPrior){
   21545 #ifdef SQLITE_MALLOCSIZE
   21546   SQLITE_FREE(pPrior);
   21547 #else
   21548   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   21549   assert( pPrior!=0 );
   21550   p--;
   21551   SQLITE_FREE(p);
   21552 #endif
   21553 }
   21554 
   21555 /*
   21556 ** Report the allocated size of a prior return from xMalloc()
   21557 ** or xRealloc().
   21558 */
   21559 static int sqlite3MemSize(void *pPrior){
   21560 #ifdef SQLITE_MALLOCSIZE
   21561   assert( pPrior!=0 );
   21562   return (int)SQLITE_MALLOCSIZE(pPrior);
   21563 #else
   21564   sqlite3_int64 *p;
   21565   assert( pPrior!=0 );
   21566   p = (sqlite3_int64*)pPrior;
   21567   p--;
   21568   return (int)p[0];
   21569 #endif
   21570 }
   21571 
   21572 /*
   21573 ** Like realloc().  Resize an allocation previously obtained from
   21574 ** sqlite3MemMalloc().
   21575 **
   21576 ** For this low-level interface, we know that pPrior!=0.  Cases where
   21577 ** pPrior==0 while have been intercepted by higher-level routine and
   21578 ** redirected to xMalloc.  Similarly, we know that nByte>0 because
   21579 ** cases where nByte<=0 will have been intercepted by higher-level
   21580 ** routines and redirected to xFree.
   21581 */
   21582 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   21583 #ifdef SQLITE_MALLOCSIZE
   21584   void *p = SQLITE_REALLOC(pPrior, nByte);
   21585   if( p==0 ){
   21586     testcase( sqlite3GlobalConfig.xLog!=0 );
   21587     sqlite3_log(SQLITE_NOMEM,
   21588       "failed memory resize %u to %u bytes",
   21589       SQLITE_MALLOCSIZE(pPrior), nByte);
   21590   }
   21591   return p;
   21592 #else
   21593   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   21594   assert( pPrior!=0 && nByte>0 );
   21595   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
   21596   p--;
   21597   p = SQLITE_REALLOC(p, nByte+8 );
   21598   if( p ){
   21599     p[0] = nByte;
   21600     p++;
   21601   }else{
   21602     testcase( sqlite3GlobalConfig.xLog!=0 );
   21603     sqlite3_log(SQLITE_NOMEM,
   21604       "failed memory resize %u to %u bytes",
   21605       sqlite3MemSize(pPrior), nByte);
   21606   }
   21607   return (void*)p;
   21608 #endif
   21609 }
   21610 
   21611 /*
   21612 ** Round up a request size to the next valid allocation size.
   21613 */
   21614 static int sqlite3MemRoundup(int n){
   21615   return ROUND8(n);
   21616 }
   21617 
   21618 /*
   21619 ** Initialize this module.
   21620 */
   21621 static int sqlite3MemInit(void *NotUsed){
   21622 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
   21623   int cpuCount;
   21624   size_t len;
   21625   if( _sqliteZone_ ){
   21626     return SQLITE_OK;
   21627   }
   21628   len = sizeof(cpuCount);
   21629   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
   21630   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
   21631   if( cpuCount>1 ){
   21632     /* defer MT decisions to system malloc */
   21633     _sqliteZone_ = malloc_default_zone();
   21634   }else{
   21635     /* only 1 core, use our own zone to contention over global locks,
   21636     ** e.g. we have our own dedicated locks */
   21637     _sqliteZone_ = malloc_create_zone(4096, 0);
   21638     malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
   21639   }
   21640 #endif /*  defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
   21641   UNUSED_PARAMETER(NotUsed);
   21642   return SQLITE_OK;
   21643 }
   21644 
   21645 /*
   21646 ** Deinitialize this module.
   21647 */
   21648 static void sqlite3MemShutdown(void *NotUsed){
   21649   UNUSED_PARAMETER(NotUsed);
   21650   return;
   21651 }
   21652 
   21653 /*
   21654 ** This routine is the only routine in this file with external linkage.
   21655 **
   21656 ** Populate the low-level memory allocation function pointers in
   21657 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   21658 */
   21659 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   21660   static const sqlite3_mem_methods defaultMethods = {
   21661      sqlite3MemMalloc,
   21662      sqlite3MemFree,
   21663      sqlite3MemRealloc,
   21664      sqlite3MemSize,
   21665      sqlite3MemRoundup,
   21666      sqlite3MemInit,
   21667      sqlite3MemShutdown,
   21668      0
   21669   };
   21670   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   21671 }
   21672 
   21673 #endif /* SQLITE_SYSTEM_MALLOC */
   21674 
   21675 /************** End of mem1.c ************************************************/
   21676 /************** Begin file mem2.c ********************************************/
   21677 /*
   21678 ** 2007 August 15
   21679 **
   21680 ** The author disclaims copyright to this source code.  In place of
   21681 ** a legal notice, here is a blessing:
   21682 **
   21683 **    May you do good and not evil.
   21684 **    May you find forgiveness for yourself and forgive others.
   21685 **    May you share freely, never taking more than you give.
   21686 **
   21687 *************************************************************************
   21688 **
   21689 ** This file contains low-level memory allocation drivers for when
   21690 ** SQLite will use the standard C-library malloc/realloc/free interface
   21691 ** to obtain the memory it needs while adding lots of additional debugging
   21692 ** information to each allocation in order to help detect and fix memory
   21693 ** leaks and memory usage errors.
   21694 **
   21695 ** This file contains implementations of the low-level memory allocation
   21696 ** routines specified in the sqlite3_mem_methods object.
   21697 */
   21698 /* #include "sqliteInt.h" */
   21699 
   21700 /*
   21701 ** This version of the memory allocator is used only if the
   21702 ** SQLITE_MEMDEBUG macro is defined
   21703 */
   21704 #ifdef SQLITE_MEMDEBUG
   21705 
   21706 /*
   21707 ** The backtrace functionality is only available with GLIBC
   21708 */
   21709 #ifdef __GLIBC__
   21710   extern int backtrace(void**,int);
   21711   extern void backtrace_symbols_fd(void*const*,int,int);
   21712 #else
   21713 # define backtrace(A,B) 1
   21714 # define backtrace_symbols_fd(A,B,C)
   21715 #endif
   21716 /* #include <stdio.h> */
   21717 
   21718 /*
   21719 ** Each memory allocation looks like this:
   21720 **
   21721 **  ------------------------------------------------------------------------
   21722 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
   21723 **  ------------------------------------------------------------------------
   21724 **
   21725 ** The application code sees only a pointer to the allocation.  We have
   21726 ** to back up from the allocation pointer to find the MemBlockHdr.  The
   21727 ** MemBlockHdr tells us the size of the allocation and the number of
   21728 ** backtrace pointers.  There is also a guard word at the end of the
   21729 ** MemBlockHdr.
   21730 */
   21731 struct MemBlockHdr {
   21732   i64 iSize;                          /* Size of this allocation */
   21733   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
   21734   char nBacktrace;                    /* Number of backtraces on this alloc */
   21735   char nBacktraceSlots;               /* Available backtrace slots */
   21736   u8 nTitle;                          /* Bytes of title; includes '\0' */
   21737   u8 eType;                           /* Allocation type code */
   21738   int iForeGuard;                     /* Guard word for sanity */
   21739 };
   21740 
   21741 /*
   21742 ** Guard words
   21743 */
   21744 #define FOREGUARD 0x80F5E153
   21745 #define REARGUARD 0xE4676B53
   21746 
   21747 /*
   21748 ** Number of malloc size increments to track.
   21749 */
   21750 #define NCSIZE  1000
   21751 
   21752 /*
   21753 ** All of the static variables used by this module are collected
   21754 ** into a single structure named "mem".  This is to keep the
   21755 ** static variables organized and to reduce namespace pollution
   21756 ** when this module is combined with other in the amalgamation.
   21757 */
   21758 static struct {
   21759 
   21760   /*
   21761   ** Mutex to control access to the memory allocation subsystem.
   21762   */
   21763   sqlite3_mutex *mutex;
   21764 
   21765   /*
   21766   ** Head and tail of a linked list of all outstanding allocations
   21767   */
   21768   struct MemBlockHdr *pFirst;
   21769   struct MemBlockHdr *pLast;
   21770 
   21771   /*
   21772   ** The number of levels of backtrace to save in new allocations.
   21773   */
   21774   int nBacktrace;
   21775   void (*xBacktrace)(int, int, void **);
   21776 
   21777   /*
   21778   ** Title text to insert in front of each block
   21779   */
   21780   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
   21781   char zTitle[100];  /* The title text */
   21782 
   21783   /*
   21784   ** sqlite3MallocDisallow() increments the following counter.
   21785   ** sqlite3MallocAllow() decrements it.
   21786   */
   21787   int disallow; /* Do not allow memory allocation */
   21788 
   21789   /*
   21790   ** Gather statistics on the sizes of memory allocations.
   21791   ** nAlloc[i] is the number of allocation attempts of i*8
   21792   ** bytes.  i==NCSIZE is the number of allocation attempts for
   21793   ** sizes more than NCSIZE*8 bytes.
   21794   */
   21795   int nAlloc[NCSIZE];      /* Total number of allocations */
   21796   int nCurrent[NCSIZE];    /* Current number of allocations */
   21797   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
   21798 
   21799 } mem;
   21800 
   21801 
   21802 /*
   21803 ** Adjust memory usage statistics
   21804 */
   21805 static void adjustStats(int iSize, int increment){
   21806   int i = ROUND8(iSize)/8;
   21807   if( i>NCSIZE-1 ){
   21808     i = NCSIZE - 1;
   21809   }
   21810   if( increment>0 ){
   21811     mem.nAlloc[i]++;
   21812     mem.nCurrent[i]++;
   21813     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
   21814       mem.mxCurrent[i] = mem.nCurrent[i];
   21815     }
   21816   }else{
   21817     mem.nCurrent[i]--;
   21818     assert( mem.nCurrent[i]>=0 );
   21819   }
   21820 }
   21821 
   21822 /*
   21823 ** Given an allocation, find the MemBlockHdr for that allocation.
   21824 **
   21825 ** This routine checks the guards at either end of the allocation and
   21826 ** if they are incorrect it asserts.
   21827 */
   21828 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
   21829   struct MemBlockHdr *p;
   21830   int *pInt;
   21831   u8 *pU8;
   21832   int nReserve;
   21833 
   21834   p = (struct MemBlockHdr*)pAllocation;
   21835   p--;
   21836   assert( p->iForeGuard==(int)FOREGUARD );
   21837   nReserve = ROUND8(p->iSize);
   21838   pInt = (int*)pAllocation;
   21839   pU8 = (u8*)pAllocation;
   21840   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
   21841   /* This checks any of the "extra" bytes allocated due
   21842   ** to rounding up to an 8 byte boundary to ensure
   21843   ** they haven't been overwritten.
   21844   */
   21845   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
   21846   return p;
   21847 }
   21848 
   21849 /*
   21850 ** Return the number of bytes currently allocated at address p.
   21851 */
   21852 static int sqlite3MemSize(void *p){
   21853   struct MemBlockHdr *pHdr;
   21854   if( !p ){
   21855     return 0;
   21856   }
   21857   pHdr = sqlite3MemsysGetHeader(p);
   21858   return (int)pHdr->iSize;
   21859 }
   21860 
   21861 /*
   21862 ** Initialize the memory allocation subsystem.
   21863 */
   21864 static int sqlite3MemInit(void *NotUsed){
   21865   UNUSED_PARAMETER(NotUsed);
   21866   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
   21867   if( !sqlite3GlobalConfig.bMemstat ){
   21868     /* If memory status is enabled, then the malloc.c wrapper will already
   21869     ** hold the STATIC_MEM mutex when the routines here are invoked. */
   21870     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   21871   }
   21872   return SQLITE_OK;
   21873 }
   21874 
   21875 /*
   21876 ** Deinitialize the memory allocation subsystem.
   21877 */
   21878 static void sqlite3MemShutdown(void *NotUsed){
   21879   UNUSED_PARAMETER(NotUsed);
   21880   mem.mutex = 0;
   21881 }
   21882 
   21883 /*
   21884 ** Round up a request size to the next valid allocation size.
   21885 */
   21886 static int sqlite3MemRoundup(int n){
   21887   return ROUND8(n);
   21888 }
   21889 
   21890 /*
   21891 ** Fill a buffer with pseudo-random bytes.  This is used to preset
   21892 ** the content of a new memory allocation to unpredictable values and
   21893 ** to clear the content of a freed allocation to unpredictable values.
   21894 */
   21895 static void randomFill(char *pBuf, int nByte){
   21896   unsigned int x, y, r;
   21897   x = SQLITE_PTR_TO_INT(pBuf);
   21898   y = nByte | 1;
   21899   while( nByte >= 4 ){
   21900     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
   21901     y = y*1103515245 + 12345;
   21902     r = x ^ y;
   21903     *(int*)pBuf = r;
   21904     pBuf += 4;
   21905     nByte -= 4;
   21906   }
   21907   while( nByte-- > 0 ){
   21908     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
   21909     y = y*1103515245 + 12345;
   21910     r = x ^ y;
   21911     *(pBuf++) = r & 0xff;
   21912   }
   21913 }
   21914 
   21915 /*
   21916 ** Allocate nByte bytes of memory.
   21917 */
   21918 static void *sqlite3MemMalloc(int nByte){
   21919   struct MemBlockHdr *pHdr;
   21920   void **pBt;
   21921   char *z;
   21922   int *pInt;
   21923   void *p = 0;
   21924   int totalSize;
   21925   int nReserve;
   21926   sqlite3_mutex_enter(mem.mutex);
   21927   assert( mem.disallow==0 );
   21928   nReserve = ROUND8(nByte);
   21929   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
   21930                mem.nBacktrace*sizeof(void*) + mem.nTitle;
   21931   p = malloc(totalSize);
   21932   if( p ){
   21933     z = p;
   21934     pBt = (void**)&z[mem.nTitle];
   21935     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
   21936     pHdr->pNext = 0;
   21937     pHdr->pPrev = mem.pLast;
   21938     if( mem.pLast ){
   21939       mem.pLast->pNext = pHdr;
   21940     }else{
   21941       mem.pFirst = pHdr;
   21942     }
   21943     mem.pLast = pHdr;
   21944     pHdr->iForeGuard = FOREGUARD;
   21945     pHdr->eType = MEMTYPE_HEAP;
   21946     pHdr->nBacktraceSlots = mem.nBacktrace;
   21947     pHdr->nTitle = mem.nTitle;
   21948     if( mem.nBacktrace ){
   21949       void *aAddr[40];
   21950       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
   21951       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
   21952       assert(pBt[0]);
   21953       if( mem.xBacktrace ){
   21954         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
   21955       }
   21956     }else{
   21957       pHdr->nBacktrace = 0;
   21958     }
   21959     if( mem.nTitle ){
   21960       memcpy(z, mem.zTitle, mem.nTitle);
   21961     }
   21962     pHdr->iSize = nByte;
   21963     adjustStats(nByte, +1);
   21964     pInt = (int*)&pHdr[1];
   21965     pInt[nReserve/sizeof(int)] = REARGUARD;
   21966     randomFill((char*)pInt, nByte);
   21967     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
   21968     p = (void*)pInt;
   21969   }
   21970   sqlite3_mutex_leave(mem.mutex);
   21971   return p;
   21972 }
   21973 
   21974 /*
   21975 ** Free memory.
   21976 */
   21977 static void sqlite3MemFree(void *pPrior){
   21978   struct MemBlockHdr *pHdr;
   21979   void **pBt;
   21980   char *z;
   21981   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
   21982        || mem.mutex!=0 );
   21983   pHdr = sqlite3MemsysGetHeader(pPrior);
   21984   pBt = (void**)pHdr;
   21985   pBt -= pHdr->nBacktraceSlots;
   21986   sqlite3_mutex_enter(mem.mutex);
   21987   if( pHdr->pPrev ){
   21988     assert( pHdr->pPrev->pNext==pHdr );
   21989     pHdr->pPrev->pNext = pHdr->pNext;
   21990   }else{
   21991     assert( mem.pFirst==pHdr );
   21992     mem.pFirst = pHdr->pNext;
   21993   }
   21994   if( pHdr->pNext ){
   21995     assert( pHdr->pNext->pPrev==pHdr );
   21996     pHdr->pNext->pPrev = pHdr->pPrev;
   21997   }else{
   21998     assert( mem.pLast==pHdr );
   21999     mem.pLast = pHdr->pPrev;
   22000   }
   22001   z = (char*)pBt;
   22002   z -= pHdr->nTitle;
   22003   adjustStats((int)pHdr->iSize, -1);
   22004   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
   22005                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
   22006   free(z);
   22007   sqlite3_mutex_leave(mem.mutex);
   22008 }
   22009 
   22010 /*
   22011 ** Change the size of an existing memory allocation.
   22012 **
   22013 ** For this debugging implementation, we *always* make a copy of the
   22014 ** allocation into a new place in memory.  In this way, if the
   22015 ** higher level code is using pointer to the old allocation, it is
   22016 ** much more likely to break and we are much more liking to find
   22017 ** the error.
   22018 */
   22019 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   22020   struct MemBlockHdr *pOldHdr;
   22021   void *pNew;
   22022   assert( mem.disallow==0 );
   22023   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
   22024   pOldHdr = sqlite3MemsysGetHeader(pPrior);
   22025   pNew = sqlite3MemMalloc(nByte);
   22026   if( pNew ){
   22027     memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
   22028     if( nByte>pOldHdr->iSize ){
   22029       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
   22030     }
   22031     sqlite3MemFree(pPrior);
   22032   }
   22033   return pNew;
   22034 }
   22035 
   22036 /*
   22037 ** Populate the low-level memory allocation function pointers in
   22038 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   22039 */
   22040 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   22041   static const sqlite3_mem_methods defaultMethods = {
   22042      sqlite3MemMalloc,
   22043      sqlite3MemFree,
   22044      sqlite3MemRealloc,
   22045      sqlite3MemSize,
   22046      sqlite3MemRoundup,
   22047      sqlite3MemInit,
   22048      sqlite3MemShutdown,
   22049      0
   22050   };
   22051   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   22052 }
   22053 
   22054 /*
   22055 ** Set the "type" of an allocation.
   22056 */
   22057 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
   22058   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   22059     struct MemBlockHdr *pHdr;
   22060     pHdr = sqlite3MemsysGetHeader(p);
   22061     assert( pHdr->iForeGuard==FOREGUARD );
   22062     pHdr->eType = eType;
   22063   }
   22064 }
   22065 
   22066 /*
   22067 ** Return TRUE if the mask of type in eType matches the type of the
   22068 ** allocation p.  Also return true if p==NULL.
   22069 **
   22070 ** This routine is designed for use within an assert() statement, to
   22071 ** verify the type of an allocation.  For example:
   22072 **
   22073 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   22074 */
   22075 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
   22076   int rc = 1;
   22077   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   22078     struct MemBlockHdr *pHdr;
   22079     pHdr = sqlite3MemsysGetHeader(p);
   22080     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   22081     if( (pHdr->eType&eType)==0 ){
   22082       rc = 0;
   22083     }
   22084   }
   22085   return rc;
   22086 }
   22087 
   22088 /*
   22089 ** Return TRUE if the mask of type in eType matches no bits of the type of the
   22090 ** allocation p.  Also return true if p==NULL.
   22091 **
   22092 ** This routine is designed for use within an assert() statement, to
   22093 ** verify the type of an allocation.  For example:
   22094 **
   22095 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   22096 */
   22097 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
   22098   int rc = 1;
   22099   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   22100     struct MemBlockHdr *pHdr;
   22101     pHdr = sqlite3MemsysGetHeader(p);
   22102     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   22103     if( (pHdr->eType&eType)!=0 ){
   22104       rc = 0;
   22105     }
   22106   }
   22107   return rc;
   22108 }
   22109 
   22110 /*
   22111 ** Set the number of backtrace levels kept for each allocation.
   22112 ** A value of zero turns off backtracing.  The number is always rounded
   22113 ** up to a multiple of 2.
   22114 */
   22115 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
   22116   if( depth<0 ){ depth = 0; }
   22117   if( depth>20 ){ depth = 20; }
   22118   depth = (depth+1)&0xfe;
   22119   mem.nBacktrace = depth;
   22120 }
   22121 
   22122 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
   22123   mem.xBacktrace = xBacktrace;
   22124 }
   22125 
   22126 /*
   22127 ** Set the title string for subsequent allocations.
   22128 */
   22129 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
   22130   unsigned int n = sqlite3Strlen30(zTitle) + 1;
   22131   sqlite3_mutex_enter(mem.mutex);
   22132   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
   22133   memcpy(mem.zTitle, zTitle, n);
   22134   mem.zTitle[n] = 0;
   22135   mem.nTitle = ROUND8(n);
   22136   sqlite3_mutex_leave(mem.mutex);
   22137 }
   22138 
   22139 SQLITE_PRIVATE void sqlite3MemdebugSync(){
   22140   struct MemBlockHdr *pHdr;
   22141   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   22142     void **pBt = (void**)pHdr;
   22143     pBt -= pHdr->nBacktraceSlots;
   22144     mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
   22145   }
   22146 }
   22147 
   22148 /*
   22149 ** Open the file indicated and write a log of all unfreed memory
   22150 ** allocations into that log.
   22151 */
   22152 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   22153   FILE *out;
   22154   struct MemBlockHdr *pHdr;
   22155   void **pBt;
   22156   int i;
   22157   out = fopen(zFilename, "w");
   22158   if( out==0 ){
   22159     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   22160                     zFilename);
   22161     return;
   22162   }
   22163   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   22164     char *z = (char*)pHdr;
   22165     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
   22166     fprintf(out, "**** %lld bytes at %p from %s ****\n",
   22167             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
   22168     if( pHdr->nBacktrace ){
   22169       fflush(out);
   22170       pBt = (void**)pHdr;
   22171       pBt -= pHdr->nBacktraceSlots;
   22172       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
   22173       fprintf(out, "\n");
   22174     }
   22175   }
   22176   fprintf(out, "COUNTS:\n");
   22177   for(i=0; i<NCSIZE-1; i++){
   22178     if( mem.nAlloc[i] ){
   22179       fprintf(out, "   %5d: %10d %10d %10d\n",
   22180             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
   22181     }
   22182   }
   22183   if( mem.nAlloc[NCSIZE-1] ){
   22184     fprintf(out, "   %5d: %10d %10d %10d\n",
   22185              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
   22186              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
   22187   }
   22188   fclose(out);
   22189 }
   22190 
   22191 /*
   22192 ** Return the number of times sqlite3MemMalloc() has been called.
   22193 */
   22194 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
   22195   int i;
   22196   int nTotal = 0;
   22197   for(i=0; i<NCSIZE; i++){
   22198     nTotal += mem.nAlloc[i];
   22199   }
   22200   return nTotal;
   22201 }
   22202 
   22203 
   22204 #endif /* SQLITE_MEMDEBUG */
   22205 
   22206 /************** End of mem2.c ************************************************/
   22207 /************** Begin file mem3.c ********************************************/
   22208 /*
   22209 ** 2007 October 14
   22210 **
   22211 ** The author disclaims copyright to this source code.  In place of
   22212 ** a legal notice, here is a blessing:
   22213 **
   22214 **    May you do good and not evil.
   22215 **    May you find forgiveness for yourself and forgive others.
   22216 **    May you share freely, never taking more than you give.
   22217 **
   22218 *************************************************************************
   22219 ** This file contains the C functions that implement a memory
   22220 ** allocation subsystem for use by SQLite.
   22221 **
   22222 ** This version of the memory allocation subsystem omits all
   22223 ** use of malloc(). The SQLite user supplies a block of memory
   22224 ** before calling sqlite3_initialize() from which allocations
   22225 ** are made and returned by the xMalloc() and xRealloc()
   22226 ** implementations. Once sqlite3_initialize() has been called,
   22227 ** the amount of memory available to SQLite is fixed and cannot
   22228 ** be changed.
   22229 **
   22230 ** This version of the memory allocation subsystem is included
   22231 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
   22232 */
   22233 /* #include "sqliteInt.h" */
   22234 
   22235 /*
   22236 ** This version of the memory allocator is only built into the library
   22237 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
   22238 ** mean that the library will use a memory-pool by default, just that
   22239 ** it is available. The mempool allocator is activated by calling
   22240 ** sqlite3_config().
   22241 */
   22242 #ifdef SQLITE_ENABLE_MEMSYS3
   22243 
   22244 /*
   22245 ** Maximum size (in Mem3Blocks) of a "small" chunk.
   22246 */
   22247 #define MX_SMALL 10
   22248 
   22249 
   22250 /*
   22251 ** Number of freelist hash slots
   22252 */
   22253 #define N_HASH  61
   22254 
   22255 /*
   22256 ** A memory allocation (also called a "chunk") consists of two or
   22257 ** more blocks where each block is 8 bytes.  The first 8 bytes are
   22258 ** a header that is not returned to the user.
   22259 **
   22260 ** A chunk is two or more blocks that is either checked out or
   22261 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
   22262 ** size of the allocation in blocks if the allocation is free.
   22263 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
   22264 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
   22265 ** is true if the previous chunk is checked out and false if the
   22266 ** previous chunk is free.  The u.hdr.prevSize field is the size of
   22267 ** the previous chunk in blocks if the previous chunk is on the
   22268 ** freelist. If the previous chunk is checked out, then
   22269 ** u.hdr.prevSize can be part of the data for that chunk and should
   22270 ** not be read or written.
   22271 **
   22272 ** We often identify a chunk by its index in mem3.aPool[].  When
   22273 ** this is done, the chunk index refers to the second block of
   22274 ** the chunk.  In this way, the first chunk has an index of 1.
   22275 ** A chunk index of 0 means "no such chunk" and is the equivalent
   22276 ** of a NULL pointer.
   22277 **
   22278 ** The second block of free chunks is of the form u.list.  The
   22279 ** two fields form a double-linked list of chunks of related sizes.
   22280 ** Pointers to the head of the list are stored in mem3.aiSmall[]
   22281 ** for smaller chunks and mem3.aiHash[] for larger chunks.
   22282 **
   22283 ** The second block of a chunk is user data if the chunk is checked
   22284 ** out.  If a chunk is checked out, the user data may extend into
   22285 ** the u.hdr.prevSize value of the following chunk.
   22286 */
   22287 typedef struct Mem3Block Mem3Block;
   22288 struct Mem3Block {
   22289   union {
   22290     struct {
   22291       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
   22292       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
   22293     } hdr;
   22294     struct {
   22295       u32 next;       /* Index in mem3.aPool[] of next free chunk */
   22296       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
   22297     } list;
   22298   } u;
   22299 };
   22300 
   22301 /*
   22302 ** All of the static variables used by this module are collected
   22303 ** into a single structure named "mem3".  This is to keep the
   22304 ** static variables organized and to reduce namespace pollution
   22305 ** when this module is combined with other in the amalgamation.
   22306 */
   22307 static SQLITE_WSD struct Mem3Global {
   22308   /*
   22309   ** Memory available for allocation. nPool is the size of the array
   22310   ** (in Mem3Blocks) pointed to by aPool less 2.
   22311   */
   22312   u32 nPool;
   22313   Mem3Block *aPool;
   22314 
   22315   /*
   22316   ** True if we are evaluating an out-of-memory callback.
   22317   */
   22318   int alarmBusy;
   22319 
   22320   /*
   22321   ** Mutex to control access to the memory allocation subsystem.
   22322   */
   22323   sqlite3_mutex *mutex;
   22324 
   22325   /*
   22326   ** The minimum amount of free space that we have seen.
   22327   */
   22328   u32 mnMaster;
   22329 
   22330   /*
   22331   ** iMaster is the index of the master chunk.  Most new allocations
   22332   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
   22333   ** of the current master.  iMaster is 0 if there is not master chunk.
   22334   ** The master chunk is not in either the aiHash[] or aiSmall[].
   22335   */
   22336   u32 iMaster;
   22337   u32 szMaster;
   22338 
   22339   /*
   22340   ** Array of lists of free blocks according to the block size
   22341   ** for smaller chunks, or a hash on the block size for larger
   22342   ** chunks.
   22343   */
   22344   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
   22345   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
   22346 } mem3 = { 97535575 };
   22347 
   22348 #define mem3 GLOBAL(struct Mem3Global, mem3)
   22349 
   22350 /*
   22351 ** Unlink the chunk at mem3.aPool[i] from list it is currently
   22352 ** on.  *pRoot is the list that i is a member of.
   22353 */
   22354 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
   22355   u32 next = mem3.aPool[i].u.list.next;
   22356   u32 prev = mem3.aPool[i].u.list.prev;
   22357   assert( sqlite3_mutex_held(mem3.mutex) );
   22358   if( prev==0 ){
   22359     *pRoot = next;
   22360   }else{
   22361     mem3.aPool[prev].u.list.next = next;
   22362   }
   22363   if( next ){
   22364     mem3.aPool[next].u.list.prev = prev;
   22365   }
   22366   mem3.aPool[i].u.list.next = 0;
   22367   mem3.aPool[i].u.list.prev = 0;
   22368 }
   22369 
   22370 /*
   22371 ** Unlink the chunk at index i from
   22372 ** whatever list is currently a member of.
   22373 */
   22374 static void memsys3Unlink(u32 i){
   22375   u32 size, hash;
   22376   assert( sqlite3_mutex_held(mem3.mutex) );
   22377   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   22378   assert( i>=1 );
   22379   size = mem3.aPool[i-1].u.hdr.size4x/4;
   22380   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   22381   assert( size>=2 );
   22382   if( size <= MX_SMALL ){
   22383     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
   22384   }else{
   22385     hash = size % N_HASH;
   22386     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   22387   }
   22388 }
   22389 
   22390 /*
   22391 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
   22392 ** at *pRoot.
   22393 */
   22394 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
   22395   assert( sqlite3_mutex_held(mem3.mutex) );
   22396   mem3.aPool[i].u.list.next = *pRoot;
   22397   mem3.aPool[i].u.list.prev = 0;
   22398   if( *pRoot ){
   22399     mem3.aPool[*pRoot].u.list.prev = i;
   22400   }
   22401   *pRoot = i;
   22402 }
   22403 
   22404 /*
   22405 ** Link the chunk at index i into either the appropriate
   22406 ** small chunk list, or into the large chunk hash table.
   22407 */
   22408 static void memsys3Link(u32 i){
   22409   u32 size, hash;
   22410   assert( sqlite3_mutex_held(mem3.mutex) );
   22411   assert( i>=1 );
   22412   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   22413   size = mem3.aPool[i-1].u.hdr.size4x/4;
   22414   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   22415   assert( size>=2 );
   22416   if( size <= MX_SMALL ){
   22417     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
   22418   }else{
   22419     hash = size % N_HASH;
   22420     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
   22421   }
   22422 }
   22423 
   22424 /*
   22425 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   22426 ** will already be held (obtained by code in malloc.c) if
   22427 ** sqlite3GlobalConfig.bMemStat is true.
   22428 */
   22429 static void memsys3Enter(void){
   22430   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
   22431     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   22432   }
   22433   sqlite3_mutex_enter(mem3.mutex);
   22434 }
   22435 static void memsys3Leave(void){
   22436   sqlite3_mutex_leave(mem3.mutex);
   22437 }
   22438 
   22439 /*
   22440 ** Called when we are unable to satisfy an allocation of nBytes.
   22441 */
   22442 static void memsys3OutOfMemory(int nByte){
   22443   if( !mem3.alarmBusy ){
   22444     mem3.alarmBusy = 1;
   22445     assert( sqlite3_mutex_held(mem3.mutex) );
   22446     sqlite3_mutex_leave(mem3.mutex);
   22447     sqlite3_release_memory(nByte);
   22448     sqlite3_mutex_enter(mem3.mutex);
   22449     mem3.alarmBusy = 0;
   22450   }
   22451 }
   22452 
   22453 
   22454 /*
   22455 ** Chunk i is a free chunk that has been unlinked.  Adjust its
   22456 ** size parameters for check-out and return a pointer to the
   22457 ** user portion of the chunk.
   22458 */
   22459 static void *memsys3Checkout(u32 i, u32 nBlock){
   22460   u32 x;
   22461   assert( sqlite3_mutex_held(mem3.mutex) );
   22462   assert( i>=1 );
   22463   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
   22464   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
   22465   x = mem3.aPool[i-1].u.hdr.size4x;
   22466   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
   22467   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
   22468   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
   22469   return &mem3.aPool[i];
   22470 }
   22471 
   22472 /*
   22473 ** Carve a piece off of the end of the mem3.iMaster free chunk.
   22474 ** Return a pointer to the new allocation.  Or, if the master chunk
   22475 ** is not large enough, return 0.
   22476 */
   22477 static void *memsys3FromMaster(u32 nBlock){
   22478   assert( sqlite3_mutex_held(mem3.mutex) );
   22479   assert( mem3.szMaster>=nBlock );
   22480   if( nBlock>=mem3.szMaster-1 ){
   22481     /* Use the entire master */
   22482     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
   22483     mem3.iMaster = 0;
   22484     mem3.szMaster = 0;
   22485     mem3.mnMaster = 0;
   22486     return p;
   22487   }else{
   22488     /* Split the master block.  Return the tail. */
   22489     u32 newi, x;
   22490     newi = mem3.iMaster + mem3.szMaster - nBlock;
   22491     assert( newi > mem3.iMaster+1 );
   22492     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
   22493     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
   22494     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
   22495     mem3.szMaster -= nBlock;
   22496     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
   22497     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   22498     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   22499     if( mem3.szMaster < mem3.mnMaster ){
   22500       mem3.mnMaster = mem3.szMaster;
   22501     }
   22502     return (void*)&mem3.aPool[newi];
   22503   }
   22504 }
   22505 
   22506 /*
   22507 ** *pRoot is the head of a list of free chunks of the same size
   22508 ** or same size hash.  In other words, *pRoot is an entry in either
   22509 ** mem3.aiSmall[] or mem3.aiHash[].
   22510 **
   22511 ** This routine examines all entries on the given list and tries
   22512 ** to coalesce each entries with adjacent free chunks.
   22513 **
   22514 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
   22515 ** the current mem3.iMaster with the new larger chunk.  In order for
   22516 ** this mem3.iMaster replacement to work, the master chunk must be
   22517 ** linked into the hash tables.  That is not the normal state of
   22518 ** affairs, of course.  The calling routine must link the master
   22519 ** chunk before invoking this routine, then must unlink the (possibly
   22520 ** changed) master chunk once this routine has finished.
   22521 */
   22522 static void memsys3Merge(u32 *pRoot){
   22523   u32 iNext, prev, size, i, x;
   22524 
   22525   assert( sqlite3_mutex_held(mem3.mutex) );
   22526   for(i=*pRoot; i>0; i=iNext){
   22527     iNext = mem3.aPool[i].u.list.next;
   22528     size = mem3.aPool[i-1].u.hdr.size4x;
   22529     assert( (size&1)==0 );
   22530     if( (size&2)==0 ){
   22531       memsys3UnlinkFromList(i, pRoot);
   22532       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
   22533       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
   22534       if( prev==iNext ){
   22535         iNext = mem3.aPool[prev].u.list.next;
   22536       }
   22537       memsys3Unlink(prev);
   22538       size = i + size/4 - prev;
   22539       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
   22540       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
   22541       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
   22542       memsys3Link(prev);
   22543       i = prev;
   22544     }else{
   22545       size /= 4;
   22546     }
   22547     if( size>mem3.szMaster ){
   22548       mem3.iMaster = i;
   22549       mem3.szMaster = size;
   22550     }
   22551   }
   22552 }
   22553 
   22554 /*
   22555 ** Return a block of memory of at least nBytes in size.
   22556 ** Return NULL if unable.
   22557 **
   22558 ** This function assumes that the necessary mutexes, if any, are
   22559 ** already held by the caller. Hence "Unsafe".
   22560 */
   22561 static void *memsys3MallocUnsafe(int nByte){
   22562   u32 i;
   22563   u32 nBlock;
   22564   u32 toFree;
   22565 
   22566   assert( sqlite3_mutex_held(mem3.mutex) );
   22567   assert( sizeof(Mem3Block)==8 );
   22568   if( nByte<=12 ){
   22569     nBlock = 2;
   22570   }else{
   22571     nBlock = (nByte + 11)/8;
   22572   }
   22573   assert( nBlock>=2 );
   22574 
   22575   /* STEP 1:
   22576   ** Look for an entry of the correct size in either the small
   22577   ** chunk table or in the large chunk hash table.  This is
   22578   ** successful most of the time (about 9 times out of 10).
   22579   */
   22580   if( nBlock <= MX_SMALL ){
   22581     i = mem3.aiSmall[nBlock-2];
   22582     if( i>0 ){
   22583       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
   22584       return memsys3Checkout(i, nBlock);
   22585     }
   22586   }else{
   22587     int hash = nBlock % N_HASH;
   22588     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
   22589       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
   22590         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   22591         return memsys3Checkout(i, nBlock);
   22592       }
   22593     }
   22594   }
   22595 
   22596   /* STEP 2:
   22597   ** Try to satisfy the allocation by carving a piece off of the end
   22598   ** of the master chunk.  This step usually works if step 1 fails.
   22599   */
   22600   if( mem3.szMaster>=nBlock ){
   22601     return memsys3FromMaster(nBlock);
   22602   }
   22603 
   22604 
   22605   /* STEP 3:
   22606   ** Loop through the entire memory pool.  Coalesce adjacent free
   22607   ** chunks.  Recompute the master chunk as the largest free chunk.
   22608   ** Then try again to satisfy the allocation by carving a piece off
   22609   ** of the end of the master chunk.  This step happens very
   22610   ** rarely (we hope!)
   22611   */
   22612   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
   22613     memsys3OutOfMemory(toFree);
   22614     if( mem3.iMaster ){
   22615       memsys3Link(mem3.iMaster);
   22616       mem3.iMaster = 0;
   22617       mem3.szMaster = 0;
   22618     }
   22619     for(i=0; i<N_HASH; i++){
   22620       memsys3Merge(&mem3.aiHash[i]);
   22621     }
   22622     for(i=0; i<MX_SMALL-1; i++){
   22623       memsys3Merge(&mem3.aiSmall[i]);
   22624     }
   22625     if( mem3.szMaster ){
   22626       memsys3Unlink(mem3.iMaster);
   22627       if( mem3.szMaster>=nBlock ){
   22628         return memsys3FromMaster(nBlock);
   22629       }
   22630     }
   22631   }
   22632 
   22633   /* If none of the above worked, then we fail. */
   22634   return 0;
   22635 }
   22636 
   22637 /*
   22638 ** Free an outstanding memory allocation.
   22639 **
   22640 ** This function assumes that the necessary mutexes, if any, are
   22641 ** already held by the caller. Hence "Unsafe".
   22642 */
   22643 static void memsys3FreeUnsafe(void *pOld){
   22644   Mem3Block *p = (Mem3Block*)pOld;
   22645   int i;
   22646   u32 size, x;
   22647   assert( sqlite3_mutex_held(mem3.mutex) );
   22648   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
   22649   i = p - mem3.aPool;
   22650   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
   22651   size = mem3.aPool[i-1].u.hdr.size4x/4;
   22652   assert( i+size<=mem3.nPool+1 );
   22653   mem3.aPool[i-1].u.hdr.size4x &= ~1;
   22654   mem3.aPool[i+size-1].u.hdr.prevSize = size;
   22655   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
   22656   memsys3Link(i);
   22657 
   22658   /* Try to expand the master using the newly freed chunk */
   22659   if( mem3.iMaster ){
   22660     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
   22661       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
   22662       mem3.iMaster -= size;
   22663       mem3.szMaster += size;
   22664       memsys3Unlink(mem3.iMaster);
   22665       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   22666       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   22667       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   22668     }
   22669     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   22670     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
   22671       memsys3Unlink(mem3.iMaster+mem3.szMaster);
   22672       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
   22673       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   22674       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   22675     }
   22676   }
   22677 }
   22678 
   22679 /*
   22680 ** Return the size of an outstanding allocation, in bytes.  The
   22681 ** size returned omits the 8-byte header overhead.  This only
   22682 ** works for chunks that are currently checked out.
   22683 */
   22684 static int memsys3Size(void *p){
   22685   Mem3Block *pBlock;
   22686   assert( p!=0 );
   22687   pBlock = (Mem3Block*)p;
   22688   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
   22689   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
   22690 }
   22691 
   22692 /*
   22693 ** Round up a request size to the next valid allocation size.
   22694 */
   22695 static int memsys3Roundup(int n){
   22696   if( n<=12 ){
   22697     return 12;
   22698   }else{
   22699     return ((n+11)&~7) - 4;
   22700   }
   22701 }
   22702 
   22703 /*
   22704 ** Allocate nBytes of memory.
   22705 */
   22706 static void *memsys3Malloc(int nBytes){
   22707   sqlite3_int64 *p;
   22708   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
   22709   memsys3Enter();
   22710   p = memsys3MallocUnsafe(nBytes);
   22711   memsys3Leave();
   22712   return (void*)p;
   22713 }
   22714 
   22715 /*
   22716 ** Free memory.
   22717 */
   22718 static void memsys3Free(void *pPrior){
   22719   assert( pPrior );
   22720   memsys3Enter();
   22721   memsys3FreeUnsafe(pPrior);
   22722   memsys3Leave();
   22723 }
   22724 
   22725 /*
   22726 ** Change the size of an existing memory allocation
   22727 */
   22728 static void *memsys3Realloc(void *pPrior, int nBytes){
   22729   int nOld;
   22730   void *p;
   22731   if( pPrior==0 ){
   22732     return sqlite3_malloc(nBytes);
   22733   }
   22734   if( nBytes<=0 ){
   22735     sqlite3_free(pPrior);
   22736     return 0;
   22737   }
   22738   nOld = memsys3Size(pPrior);
   22739   if( nBytes<=nOld && nBytes>=nOld-128 ){
   22740     return pPrior;
   22741   }
   22742   memsys3Enter();
   22743   p = memsys3MallocUnsafe(nBytes);
   22744   if( p ){
   22745     if( nOld<nBytes ){
   22746       memcpy(p, pPrior, nOld);
   22747     }else{
   22748       memcpy(p, pPrior, nBytes);
   22749     }
   22750     memsys3FreeUnsafe(pPrior);
   22751   }
   22752   memsys3Leave();
   22753   return p;
   22754 }
   22755 
   22756 /*
   22757 ** Initialize this module.
   22758 */
   22759 static int memsys3Init(void *NotUsed){
   22760   UNUSED_PARAMETER(NotUsed);
   22761   if( !sqlite3GlobalConfig.pHeap ){
   22762     return SQLITE_ERROR;
   22763   }
   22764 
   22765   /* Store a pointer to the memory block in global structure mem3. */
   22766   assert( sizeof(Mem3Block)==8 );
   22767   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
   22768   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
   22769 
   22770   /* Initialize the master block. */
   22771   mem3.szMaster = mem3.nPool;
   22772   mem3.mnMaster = mem3.szMaster;
   22773   mem3.iMaster = 1;
   22774   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
   22775   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
   22776   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
   22777 
   22778   return SQLITE_OK;
   22779 }
   22780 
   22781 /*
   22782 ** Deinitialize this module.
   22783 */
   22784 static void memsys3Shutdown(void *NotUsed){
   22785   UNUSED_PARAMETER(NotUsed);
   22786   mem3.mutex = 0;
   22787   return;
   22788 }
   22789 
   22790 
   22791 
   22792 /*
   22793 ** Open the file indicated and write a log of all unfreed memory
   22794 ** allocations into that log.
   22795 */
   22796 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
   22797 #ifdef SQLITE_DEBUG
   22798   FILE *out;
   22799   u32 i, j;
   22800   u32 size;
   22801   if( zFilename==0 || zFilename[0]==0 ){
   22802     out = stdout;
   22803   }else{
   22804     out = fopen(zFilename, "w");
   22805     if( out==0 ){
   22806       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   22807                       zFilename);
   22808       return;
   22809     }
   22810   }
   22811   memsys3Enter();
   22812   fprintf(out, "CHUNKS:\n");
   22813   for(i=1; i<=mem3.nPool; i+=size/4){
   22814     size = mem3.aPool[i-1].u.hdr.size4x;
   22815     if( size/4<=1 ){
   22816       fprintf(out, "%p size error\n", &mem3.aPool[i]);
   22817       assert( 0 );
   22818       break;
   22819     }
   22820     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
   22821       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
   22822       assert( 0 );
   22823       break;
   22824     }
   22825     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
   22826       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
   22827       assert( 0 );
   22828       break;
   22829     }
   22830     if( size&1 ){
   22831       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
   22832     }else{
   22833       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
   22834                   i==mem3.iMaster ? " **master**" : "");
   22835     }
   22836   }
   22837   for(i=0; i<MX_SMALL-1; i++){
   22838     if( mem3.aiSmall[i]==0 ) continue;
   22839     fprintf(out, "small(%2d):", i);
   22840     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
   22841       fprintf(out, " %p(%d)", &mem3.aPool[j],
   22842               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   22843     }
   22844     fprintf(out, "\n");
   22845   }
   22846   for(i=0; i<N_HASH; i++){
   22847     if( mem3.aiHash[i]==0 ) continue;
   22848     fprintf(out, "hash(%2d):", i);
   22849     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
   22850       fprintf(out, " %p(%d)", &mem3.aPool[j],
   22851               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   22852     }
   22853     fprintf(out, "\n");
   22854   }
   22855   fprintf(out, "master=%d\n", mem3.iMaster);
   22856   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
   22857   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
   22858   sqlite3_mutex_leave(mem3.mutex);
   22859   if( out==stdout ){
   22860     fflush(stdout);
   22861   }else{
   22862     fclose(out);
   22863   }
   22864 #else
   22865   UNUSED_PARAMETER(zFilename);
   22866 #endif
   22867 }
   22868 
   22869 /*
   22870 ** This routine is the only routine in this file with external
   22871 ** linkage.
   22872 **
   22873 ** Populate the low-level memory allocation function pointers in
   22874 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   22875 ** arguments specify the block of memory to manage.
   22876 **
   22877 ** This routine is only called by sqlite3_config(), and therefore
   22878 ** is not required to be threadsafe (it is not).
   22879 */
   22880 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
   22881   static const sqlite3_mem_methods mempoolMethods = {
   22882      memsys3Malloc,
   22883      memsys3Free,
   22884      memsys3Realloc,
   22885      memsys3Size,
   22886      memsys3Roundup,
   22887      memsys3Init,
   22888      memsys3Shutdown,
   22889      0
   22890   };
   22891   return &mempoolMethods;
   22892 }
   22893 
   22894 #endif /* SQLITE_ENABLE_MEMSYS3 */
   22895 
   22896 /************** End of mem3.c ************************************************/
   22897 /************** Begin file mem5.c ********************************************/
   22898 /*
   22899 ** 2007 October 14
   22900 **
   22901 ** The author disclaims copyright to this source code.  In place of
   22902 ** a legal notice, here is a blessing:
   22903 **
   22904 **    May you do good and not evil.
   22905 **    May you find forgiveness for yourself and forgive others.
   22906 **    May you share freely, never taking more than you give.
   22907 **
   22908 *************************************************************************
   22909 ** This file contains the C functions that implement a memory
   22910 ** allocation subsystem for use by SQLite.
   22911 **
   22912 ** This version of the memory allocation subsystem omits all
   22913 ** use of malloc(). The application gives SQLite a block of memory
   22914 ** before calling sqlite3_initialize() from which allocations
   22915 ** are made and returned by the xMalloc() and xRealloc()
   22916 ** implementations. Once sqlite3_initialize() has been called,
   22917 ** the amount of memory available to SQLite is fixed and cannot
   22918 ** be changed.
   22919 **
   22920 ** This version of the memory allocation subsystem is included
   22921 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
   22922 **
   22923 ** This memory allocator uses the following algorithm:
   22924 **
   22925 **   1.  All memory allocation sizes are rounded up to a power of 2.
   22926 **
   22927 **   2.  If two adjacent free blocks are the halves of a larger block,
   22928 **       then the two blocks are coalesced into the single larger block.
   22929 **
   22930 **   3.  New memory is allocated from the first available free block.
   22931 **
   22932 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
   22933 ** Concerning Dynamic Storage Allocation". Journal of the Association for
   22934 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
   22935 **
   22936 ** Let n be the size of the largest allocation divided by the minimum
   22937 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
   22938 ** be the maximum amount of memory ever outstanding at one time.  Let
   22939 ** N be the total amount of memory available for allocation.  Robson
   22940 ** proved that this memory allocator will never breakdown due to
   22941 ** fragmentation as long as the following constraint holds:
   22942 **
   22943 **      N >=  M*(1 + log2(n)/2) - n + 1
   22944 **
   22945 ** The sqlite3_status() logic tracks the maximum values of n and M so
   22946 ** that an application can, at any time, verify this constraint.
   22947 */
   22948 /* #include "sqliteInt.h" */
   22949 
   22950 /*
   22951 ** This version of the memory allocator is used only when
   22952 ** SQLITE_ENABLE_MEMSYS5 is defined.
   22953 */
   22954 #ifdef SQLITE_ENABLE_MEMSYS5
   22955 
   22956 /*
   22957 ** A minimum allocation is an instance of the following structure.
   22958 ** Larger allocations are an array of these structures where the
   22959 ** size of the array is a power of 2.
   22960 **
   22961 ** The size of this object must be a power of two.  That fact is
   22962 ** verified in memsys5Init().
   22963 */
   22964 typedef struct Mem5Link Mem5Link;
   22965 struct Mem5Link {
   22966   int next;       /* Index of next free chunk */
   22967   int prev;       /* Index of previous free chunk */
   22968 };
   22969 
   22970 /*
   22971 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
   22972 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
   22973 ** it is not actually possible to reach this limit.
   22974 */
   22975 #define LOGMAX 30
   22976 
   22977 /*
   22978 ** Masks used for mem5.aCtrl[] elements.
   22979 */
   22980 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
   22981 #define CTRL_FREE     0x20    /* True if not checked out */
   22982 
   22983 /*
   22984 ** All of the static variables used by this module are collected
   22985 ** into a single structure named "mem5".  This is to keep the
   22986 ** static variables organized and to reduce namespace pollution
   22987 ** when this module is combined with other in the amalgamation.
   22988 */
   22989 static SQLITE_WSD struct Mem5Global {
   22990   /*
   22991   ** Memory available for allocation
   22992   */
   22993   int szAtom;      /* Smallest possible allocation in bytes */
   22994   int nBlock;      /* Number of szAtom sized blocks in zPool */
   22995   u8 *zPool;       /* Memory available to be allocated */
   22996 
   22997   /*
   22998   ** Mutex to control access to the memory allocation subsystem.
   22999   */
   23000   sqlite3_mutex *mutex;
   23001 
   23002 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   23003   /*
   23004   ** Performance statistics
   23005   */
   23006   u64 nAlloc;         /* Total number of calls to malloc */
   23007   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
   23008   u64 totalExcess;    /* Total internal fragmentation */
   23009   u32 currentOut;     /* Current checkout, including internal fragmentation */
   23010   u32 currentCount;   /* Current number of distinct checkouts */
   23011   u32 maxOut;         /* Maximum instantaneous currentOut */
   23012   u32 maxCount;       /* Maximum instantaneous currentCount */
   23013   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
   23014 #endif
   23015 
   23016   /*
   23017   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
   23018   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
   23019   ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
   23020   */
   23021   int aiFreelist[LOGMAX+1];
   23022 
   23023   /*
   23024   ** Space for tracking which blocks are checked out and the size
   23025   ** of each block.  One byte per block.
   23026   */
   23027   u8 *aCtrl;
   23028 
   23029 } mem5;
   23030 
   23031 /*
   23032 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
   23033 */
   23034 #define mem5 GLOBAL(struct Mem5Global, mem5)
   23035 
   23036 /*
   23037 ** Assuming mem5.zPool is divided up into an array of Mem5Link
   23038 ** structures, return a pointer to the idx-th such link.
   23039 */
   23040 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
   23041 
   23042 /*
   23043 ** Unlink the chunk at mem5.aPool[i] from list it is currently
   23044 ** on.  It should be found on mem5.aiFreelist[iLogsize].
   23045 */
   23046 static void memsys5Unlink(int i, int iLogsize){
   23047   int next, prev;
   23048   assert( i>=0 && i<mem5.nBlock );
   23049   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   23050   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   23051 
   23052   next = MEM5LINK(i)->next;
   23053   prev = MEM5LINK(i)->prev;
   23054   if( prev<0 ){
   23055     mem5.aiFreelist[iLogsize] = next;
   23056   }else{
   23057     MEM5LINK(prev)->next = next;
   23058   }
   23059   if( next>=0 ){
   23060     MEM5LINK(next)->prev = prev;
   23061   }
   23062 }
   23063 
   23064 /*
   23065 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
   23066 ** free list.
   23067 */
   23068 static void memsys5Link(int i, int iLogsize){
   23069   int x;
   23070   assert( sqlite3_mutex_held(mem5.mutex) );
   23071   assert( i>=0 && i<mem5.nBlock );
   23072   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   23073   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   23074 
   23075   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
   23076   MEM5LINK(i)->prev = -1;
   23077   if( x>=0 ){
   23078     assert( x<mem5.nBlock );
   23079     MEM5LINK(x)->prev = i;
   23080   }
   23081   mem5.aiFreelist[iLogsize] = i;
   23082 }
   23083 
   23084 /*
   23085 ** Obtain or release the mutex needed to access global data structures.
   23086 */
   23087 static void memsys5Enter(void){
   23088   sqlite3_mutex_enter(mem5.mutex);
   23089 }
   23090 static void memsys5Leave(void){
   23091   sqlite3_mutex_leave(mem5.mutex);
   23092 }
   23093 
   23094 /*
   23095 ** Return the size of an outstanding allocation, in bytes.
   23096 ** This only works for chunks that are currently checked out.
   23097 */
   23098 static int memsys5Size(void *p){
   23099   int iSize, i;
   23100   assert( p!=0 );
   23101   i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
   23102   assert( i>=0 && i<mem5.nBlock );
   23103   iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
   23104   return iSize;
   23105 }
   23106 
   23107 /*
   23108 ** Return a block of memory of at least nBytes in size.
   23109 ** Return NULL if unable.  Return NULL if nBytes==0.
   23110 **
   23111 ** The caller guarantees that nByte is positive.
   23112 **
   23113 ** The caller has obtained a mutex prior to invoking this
   23114 ** routine so there is never any chance that two or more
   23115 ** threads can be in this routine at the same time.
   23116 */
   23117 static void *memsys5MallocUnsafe(int nByte){
   23118   int i;           /* Index of a mem5.aPool[] slot */
   23119   int iBin;        /* Index into mem5.aiFreelist[] */
   23120   int iFullSz;     /* Size of allocation rounded up to power of 2 */
   23121   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
   23122 
   23123   /* nByte must be a positive */
   23124   assert( nByte>0 );
   23125 
   23126   /* No more than 1GiB per allocation */
   23127   if( nByte > 0x40000000 ) return 0;
   23128 
   23129 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   23130   /* Keep track of the maximum allocation request.  Even unfulfilled
   23131   ** requests are counted */
   23132   if( (u32)nByte>mem5.maxRequest ){
   23133     mem5.maxRequest = nByte;
   23134   }
   23135 #endif
   23136 
   23137 
   23138   /* Round nByte up to the next valid power of two */
   23139   for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
   23140 
   23141   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
   23142   ** block.  If not, then split a block of the next larger power of
   23143   ** two in order to create a new free block of size iLogsize.
   23144   */
   23145   for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
   23146   if( iBin>LOGMAX ){
   23147     testcase( sqlite3GlobalConfig.xLog!=0 );
   23148     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
   23149     return 0;
   23150   }
   23151   i = mem5.aiFreelist[iBin];
   23152   memsys5Unlink(i, iBin);
   23153   while( iBin>iLogsize ){
   23154     int newSize;
   23155 
   23156     iBin--;
   23157     newSize = 1 << iBin;
   23158     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
   23159     memsys5Link(i+newSize, iBin);
   23160   }
   23161   mem5.aCtrl[i] = iLogsize;
   23162 
   23163 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   23164   /* Update allocator performance statistics. */
   23165   mem5.nAlloc++;
   23166   mem5.totalAlloc += iFullSz;
   23167   mem5.totalExcess += iFullSz - nByte;
   23168   mem5.currentCount++;
   23169   mem5.currentOut += iFullSz;
   23170   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
   23171   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
   23172 #endif
   23173 
   23174 #ifdef SQLITE_DEBUG
   23175   /* Make sure the allocated memory does not assume that it is set to zero
   23176   ** or retains a value from a previous allocation */
   23177   memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
   23178 #endif
   23179 
   23180   /* Return a pointer to the allocated memory. */
   23181   return (void*)&mem5.zPool[i*mem5.szAtom];
   23182 }
   23183 
   23184 /*
   23185 ** Free an outstanding memory allocation.
   23186 */
   23187 static void memsys5FreeUnsafe(void *pOld){
   23188   u32 size, iLogsize;
   23189   int iBlock;
   23190 
   23191   /* Set iBlock to the index of the block pointed to by pOld in
   23192   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
   23193   */
   23194   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
   23195 
   23196   /* Check that the pointer pOld points to a valid, non-free block. */
   23197   assert( iBlock>=0 && iBlock<mem5.nBlock );
   23198   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
   23199   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
   23200 
   23201   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
   23202   size = 1<<iLogsize;
   23203   assert( iBlock+size-1<(u32)mem5.nBlock );
   23204 
   23205   mem5.aCtrl[iBlock] |= CTRL_FREE;
   23206   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
   23207 
   23208 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   23209   assert( mem5.currentCount>0 );
   23210   assert( mem5.currentOut>=(size*mem5.szAtom) );
   23211   mem5.currentCount--;
   23212   mem5.currentOut -= size*mem5.szAtom;
   23213   assert( mem5.currentOut>0 || mem5.currentCount==0 );
   23214   assert( mem5.currentCount>0 || mem5.currentOut==0 );
   23215 #endif
   23216 
   23217   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   23218   while( ALWAYS(iLogsize<LOGMAX) ){
   23219     int iBuddy;
   23220     if( (iBlock>>iLogsize) & 1 ){
   23221       iBuddy = iBlock - size;
   23222       assert( iBuddy>=0 );
   23223     }else{
   23224       iBuddy = iBlock + size;
   23225       if( iBuddy>=mem5.nBlock ) break;
   23226     }
   23227     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
   23228     memsys5Unlink(iBuddy, iLogsize);
   23229     iLogsize++;
   23230     if( iBuddy<iBlock ){
   23231       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
   23232       mem5.aCtrl[iBlock] = 0;
   23233       iBlock = iBuddy;
   23234     }else{
   23235       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   23236       mem5.aCtrl[iBuddy] = 0;
   23237     }
   23238     size *= 2;
   23239   }
   23240 
   23241 #ifdef SQLITE_DEBUG
   23242   /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
   23243   ** not used after being freed */
   23244   memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
   23245 #endif
   23246 
   23247   memsys5Link(iBlock, iLogsize);
   23248 }
   23249 
   23250 /*
   23251 ** Allocate nBytes of memory.
   23252 */
   23253 static void *memsys5Malloc(int nBytes){
   23254   sqlite3_int64 *p = 0;
   23255   if( nBytes>0 ){
   23256     memsys5Enter();
   23257     p = memsys5MallocUnsafe(nBytes);
   23258     memsys5Leave();
   23259   }
   23260   return (void*)p;
   23261 }
   23262 
   23263 /*
   23264 ** Free memory.
   23265 **
   23266 ** The outer layer memory allocator prevents this routine from
   23267 ** being called with pPrior==0.
   23268 */
   23269 static void memsys5Free(void *pPrior){
   23270   assert( pPrior!=0 );
   23271   memsys5Enter();
   23272   memsys5FreeUnsafe(pPrior);
   23273   memsys5Leave();
   23274 }
   23275 
   23276 /*
   23277 ** Change the size of an existing memory allocation.
   23278 **
   23279 ** The outer layer memory allocator prevents this routine from
   23280 ** being called with pPrior==0.
   23281 **
   23282 ** nBytes is always a value obtained from a prior call to
   23283 ** memsys5Round().  Hence nBytes is always a non-negative power
   23284 ** of two.  If nBytes==0 that means that an oversize allocation
   23285 ** (an allocation larger than 0x40000000) was requested and this
   23286 ** routine should return 0 without freeing pPrior.
   23287 */
   23288 static void *memsys5Realloc(void *pPrior, int nBytes){
   23289   int nOld;
   23290   void *p;
   23291   assert( pPrior!=0 );
   23292   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
   23293   assert( nBytes>=0 );
   23294   if( nBytes==0 ){
   23295     return 0;
   23296   }
   23297   nOld = memsys5Size(pPrior);
   23298   if( nBytes<=nOld ){
   23299     return pPrior;
   23300   }
   23301   p = memsys5Malloc(nBytes);
   23302   if( p ){
   23303     memcpy(p, pPrior, nOld);
   23304     memsys5Free(pPrior);
   23305   }
   23306   return p;
   23307 }
   23308 
   23309 /*
   23310 ** Round up a request size to the next valid allocation size.  If
   23311 ** the allocation is too large to be handled by this allocation system,
   23312 ** return 0.
   23313 **
   23314 ** All allocations must be a power of two and must be expressed by a
   23315 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
   23316 ** or 1073741824 bytes.
   23317 */
   23318 static int memsys5Roundup(int n){
   23319   int iFullSz;
   23320   if( n > 0x40000000 ) return 0;
   23321   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
   23322   return iFullSz;
   23323 }
   23324 
   23325 /*
   23326 ** Return the ceiling of the logarithm base 2 of iValue.
   23327 **
   23328 ** Examples:   memsys5Log(1) -> 0
   23329 **             memsys5Log(2) -> 1
   23330 **             memsys5Log(4) -> 2
   23331 **             memsys5Log(5) -> 3
   23332 **             memsys5Log(8) -> 3
   23333 **             memsys5Log(9) -> 4
   23334 */
   23335 static int memsys5Log(int iValue){
   23336   int iLog;
   23337   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
   23338   return iLog;
   23339 }
   23340 
   23341 /*
   23342 ** Initialize the memory allocator.
   23343 **
   23344 ** This routine is not threadsafe.  The caller must be holding a mutex
   23345 ** to prevent multiple threads from entering at the same time.
   23346 */
   23347 static int memsys5Init(void *NotUsed){
   23348   int ii;            /* Loop counter */
   23349   int nByte;         /* Number of bytes of memory available to this allocator */
   23350   u8 *zByte;         /* Memory usable by this allocator */
   23351   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
   23352   int iOffset;       /* An offset into mem5.aCtrl[] */
   23353 
   23354   UNUSED_PARAMETER(NotUsed);
   23355 
   23356   /* For the purposes of this routine, disable the mutex */
   23357   mem5.mutex = 0;
   23358 
   23359   /* The size of a Mem5Link object must be a power of two.  Verify that
   23360   ** this is case.
   23361   */
   23362   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
   23363 
   23364   nByte = sqlite3GlobalConfig.nHeap;
   23365   zByte = (u8*)sqlite3GlobalConfig.pHeap;
   23366   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
   23367 
   23368   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
   23369   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
   23370   mem5.szAtom = (1<<nMinLog);
   23371   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
   23372     mem5.szAtom = mem5.szAtom << 1;
   23373   }
   23374 
   23375   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
   23376   mem5.zPool = zByte;
   23377   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
   23378 
   23379   for(ii=0; ii<=LOGMAX; ii++){
   23380     mem5.aiFreelist[ii] = -1;
   23381   }
   23382 
   23383   iOffset = 0;
   23384   for(ii=LOGMAX; ii>=0; ii--){
   23385     int nAlloc = (1<<ii);
   23386     if( (iOffset+nAlloc)<=mem5.nBlock ){
   23387       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
   23388       memsys5Link(iOffset, ii);
   23389       iOffset += nAlloc;
   23390     }
   23391     assert((iOffset+nAlloc)>mem5.nBlock);
   23392   }
   23393 
   23394   /* If a mutex is required for normal operation, allocate one */
   23395   if( sqlite3GlobalConfig.bMemstat==0 ){
   23396     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   23397   }
   23398 
   23399   return SQLITE_OK;
   23400 }
   23401 
   23402 /*
   23403 ** Deinitialize this module.
   23404 */
   23405 static void memsys5Shutdown(void *NotUsed){
   23406   UNUSED_PARAMETER(NotUsed);
   23407   mem5.mutex = 0;
   23408   return;
   23409 }
   23410 
   23411 #ifdef SQLITE_TEST
   23412 /*
   23413 ** Open the file indicated and write a log of all unfreed memory
   23414 ** allocations into that log.
   23415 */
   23416 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
   23417   FILE *out;
   23418   int i, j, n;
   23419   int nMinLog;
   23420 
   23421   if( zFilename==0 || zFilename[0]==0 ){
   23422     out = stdout;
   23423   }else{
   23424     out = fopen(zFilename, "w");
   23425     if( out==0 ){
   23426       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   23427                       zFilename);
   23428       return;
   23429     }
   23430   }
   23431   memsys5Enter();
   23432   nMinLog = memsys5Log(mem5.szAtom);
   23433   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
   23434     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
   23435     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
   23436   }
   23437   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
   23438   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
   23439   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
   23440   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
   23441   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
   23442   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
   23443   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
   23444   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
   23445   memsys5Leave();
   23446   if( out==stdout ){
   23447     fflush(stdout);
   23448   }else{
   23449     fclose(out);
   23450   }
   23451 }
   23452 #endif
   23453 
   23454 /*
   23455 ** This routine is the only routine in this file with external
   23456 ** linkage. It returns a pointer to a static sqlite3_mem_methods
   23457 ** struct populated with the memsys5 methods.
   23458 */
   23459 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
   23460   static const sqlite3_mem_methods memsys5Methods = {
   23461      memsys5Malloc,
   23462      memsys5Free,
   23463      memsys5Realloc,
   23464      memsys5Size,
   23465      memsys5Roundup,
   23466      memsys5Init,
   23467      memsys5Shutdown,
   23468      0
   23469   };
   23470   return &memsys5Methods;
   23471 }
   23472 
   23473 #endif /* SQLITE_ENABLE_MEMSYS5 */
   23474 
   23475 /************** End of mem5.c ************************************************/
   23476 /************** Begin file mutex.c *******************************************/
   23477 /*
   23478 ** 2007 August 14
   23479 **
   23480 ** The author disclaims copyright to this source code.  In place of
   23481 ** a legal notice, here is a blessing:
   23482 **
   23483 **    May you do good and not evil.
   23484 **    May you find forgiveness for yourself and forgive others.
   23485 **    May you share freely, never taking more than you give.
   23486 **
   23487 *************************************************************************
   23488 ** This file contains the C functions that implement mutexes.
   23489 **
   23490 ** This file contains code that is common across all mutex implementations.
   23491 */
   23492 /* #include "sqliteInt.h" */
   23493 
   23494 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
   23495 /*
   23496 ** For debugging purposes, record when the mutex subsystem is initialized
   23497 ** and uninitialized so that we can assert() if there is an attempt to
   23498 ** allocate a mutex while the system is uninitialized.
   23499 */
   23500 static SQLITE_WSD int mutexIsInit = 0;
   23501 #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
   23502 
   23503 
   23504 #ifndef SQLITE_MUTEX_OMIT
   23505 
   23506 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
   23507 /*
   23508 ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
   23509 ** the implementation of a wrapper around the system default mutex
   23510 ** implementation (sqlite3DefaultMutex()).
   23511 **
   23512 ** Most calls are passed directly through to the underlying default
   23513 ** mutex implementation. Except, if a mutex is configured by calling
   23514 ** sqlite3MutexWarnOnContention() on it, then if contention is ever
   23515 ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
   23516 **
   23517 ** This type of mutex is used as the database handle mutex when testing
   23518 ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
   23519 */
   23520 
   23521 /*
   23522 ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
   23523 ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
   23524 ** allocated by the system mutex implementation. Variable iType is usually set
   23525 ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
   23526 ** or one of the static mutex identifiers. Or, if this is a recursive mutex
   23527 ** that has been configured using sqlite3MutexWarnOnContention(), it is
   23528 ** set to SQLITE_MUTEX_WARNONCONTENTION.
   23529 */
   23530 typedef struct CheckMutex CheckMutex;
   23531 struct CheckMutex {
   23532   int iType;
   23533   sqlite3_mutex *mutex;
   23534 };
   23535 
   23536 #define SQLITE_MUTEX_WARNONCONTENTION  (-1)
   23537 
   23538 /*
   23539 ** Pointer to real mutex methods object used by the CheckMutex
   23540 ** implementation. Set by checkMutexInit().
   23541 */
   23542 static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
   23543 
   23544 #ifdef SQLITE_DEBUG
   23545 static int checkMutexHeld(sqlite3_mutex *p){
   23546   return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
   23547 }
   23548 static int checkMutexNotheld(sqlite3_mutex *p){
   23549   return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
   23550 }
   23551 #endif
   23552 
   23553 /*
   23554 ** Initialize and deinitialize the mutex subsystem.
   23555 */
   23556 static int checkMutexInit(void){
   23557   pGlobalMutexMethods = sqlite3DefaultMutex();
   23558   return SQLITE_OK;
   23559 }
   23560 static int checkMutexEnd(void){
   23561   pGlobalMutexMethods = 0;
   23562   return SQLITE_OK;
   23563 }
   23564 
   23565 /*
   23566 ** Allocate a mutex.
   23567 */
   23568 static sqlite3_mutex *checkMutexAlloc(int iType){
   23569   static CheckMutex staticMutexes[] = {
   23570     {2, 0}, {3, 0}, {4, 0}, {5, 0},
   23571     {6, 0}, {7, 0}, {8, 0}, {9, 0},
   23572     {10, 0}, {11, 0}, {12, 0}, {13, 0}
   23573   };
   23574   CheckMutex *p = 0;
   23575 
   23576   assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
   23577   if( iType<2 ){
   23578     p = sqlite3MallocZero(sizeof(CheckMutex));
   23579     if( p==0 ) return 0;
   23580     p->iType = iType;
   23581   }else{
   23582 #ifdef SQLITE_ENABLE_API_ARMOR
   23583     if( iType-2>=ArraySize(staticMutexes) ){
   23584       (void)SQLITE_MISUSE_BKPT;
   23585       return 0;
   23586     }
   23587 #endif
   23588     p = &staticMutexes[iType-2];
   23589   }
   23590 
   23591   if( p->mutex==0 ){
   23592     p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
   23593     if( p->mutex==0 ){
   23594       if( iType<2 ){
   23595         sqlite3_free(p);
   23596       }
   23597       p = 0;
   23598     }
   23599   }
   23600 
   23601   return (sqlite3_mutex*)p;
   23602 }
   23603 
   23604 /*
   23605 ** Free a mutex.
   23606 */
   23607 static void checkMutexFree(sqlite3_mutex *p){
   23608   assert( SQLITE_MUTEX_RECURSIVE<2 );
   23609   assert( SQLITE_MUTEX_FAST<2 );
   23610   assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
   23611 
   23612 #if SQLITE_ENABLE_API_ARMOR
   23613   if( ((CheckMutex*)p)->iType<2 )
   23614 #endif
   23615   {
   23616     CheckMutex *pCheck = (CheckMutex*)p;
   23617     pGlobalMutexMethods->xMutexFree(pCheck->mutex);
   23618     sqlite3_free(pCheck);
   23619   }
   23620 #ifdef SQLITE_ENABLE_API_ARMOR
   23621   else{
   23622     (void)SQLITE_MISUSE_BKPT;
   23623   }
   23624 #endif
   23625 }
   23626 
   23627 /*
   23628 ** Enter the mutex.
   23629 */
   23630 static void checkMutexEnter(sqlite3_mutex *p){
   23631   CheckMutex *pCheck = (CheckMutex*)p;
   23632   if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
   23633     if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
   23634       return;
   23635     }
   23636     sqlite3_log(SQLITE_MISUSE,
   23637         "illegal multi-threaded access to database connection"
   23638     );
   23639   }
   23640   pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
   23641 }
   23642 
   23643 /*
   23644 ** Enter the mutex (do not block).
   23645 */
   23646 static int checkMutexTry(sqlite3_mutex *p){
   23647   CheckMutex *pCheck = (CheckMutex*)p;
   23648   return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
   23649 }
   23650 
   23651 /*
   23652 ** Leave the mutex.
   23653 */
   23654 static void checkMutexLeave(sqlite3_mutex *p){
   23655   CheckMutex *pCheck = (CheckMutex*)p;
   23656   pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
   23657 }
   23658 
   23659 sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
   23660   static const sqlite3_mutex_methods sMutex = {
   23661     checkMutexInit,
   23662     checkMutexEnd,
   23663     checkMutexAlloc,
   23664     checkMutexFree,
   23665     checkMutexEnter,
   23666     checkMutexTry,
   23667     checkMutexLeave,
   23668 #ifdef SQLITE_DEBUG
   23669     checkMutexHeld,
   23670     checkMutexNotheld
   23671 #else
   23672     0,
   23673     0
   23674 #endif
   23675   };
   23676   return &sMutex;
   23677 }
   23678 
   23679 /*
   23680 ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
   23681 ** one on which there should be no contention.
   23682 */
   23683 SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
   23684   if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
   23685     CheckMutex *pCheck = (CheckMutex*)p;
   23686     assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
   23687     pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
   23688   }
   23689 }
   23690 #endif   /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
   23691 
   23692 /*
   23693 ** Initialize the mutex system.
   23694 */
   23695 SQLITE_PRIVATE int sqlite3MutexInit(void){
   23696   int rc = SQLITE_OK;
   23697   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
   23698     /* If the xMutexAlloc method has not been set, then the user did not
   23699     ** install a mutex implementation via sqlite3_config() prior to
   23700     ** sqlite3_initialize() being called. This block copies pointers to
   23701     ** the default implementation into the sqlite3GlobalConfig structure.
   23702     */
   23703     sqlite3_mutex_methods const *pFrom;
   23704     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
   23705 
   23706     if( sqlite3GlobalConfig.bCoreMutex ){
   23707 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
   23708       pFrom = multiThreadedCheckMutex();
   23709 #else
   23710       pFrom = sqlite3DefaultMutex();
   23711 #endif
   23712     }else{
   23713       pFrom = sqlite3NoopMutex();
   23714     }
   23715     pTo->xMutexInit = pFrom->xMutexInit;
   23716     pTo->xMutexEnd = pFrom->xMutexEnd;
   23717     pTo->xMutexFree = pFrom->xMutexFree;
   23718     pTo->xMutexEnter = pFrom->xMutexEnter;
   23719     pTo->xMutexTry = pFrom->xMutexTry;
   23720     pTo->xMutexLeave = pFrom->xMutexLeave;
   23721     pTo->xMutexHeld = pFrom->xMutexHeld;
   23722     pTo->xMutexNotheld = pFrom->xMutexNotheld;
   23723     sqlite3MemoryBarrier();
   23724     pTo->xMutexAlloc = pFrom->xMutexAlloc;
   23725   }
   23726   assert( sqlite3GlobalConfig.mutex.xMutexInit );
   23727   rc = sqlite3GlobalConfig.mutex.xMutexInit();
   23728 
   23729 #ifdef SQLITE_DEBUG
   23730   GLOBAL(int, mutexIsInit) = 1;
   23731 #endif
   23732 
   23733   return rc;
   23734 }
   23735 
   23736 /*
   23737 ** Shutdown the mutex system. This call frees resources allocated by
   23738 ** sqlite3MutexInit().
   23739 */
   23740 SQLITE_PRIVATE int sqlite3MutexEnd(void){
   23741   int rc = SQLITE_OK;
   23742   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
   23743     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
   23744   }
   23745 
   23746 #ifdef SQLITE_DEBUG
   23747   GLOBAL(int, mutexIsInit) = 0;
   23748 #endif
   23749 
   23750   return rc;
   23751 }
   23752 
   23753 /*
   23754 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
   23755 */
   23756 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
   23757 #ifndef SQLITE_OMIT_AUTOINIT
   23758   if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
   23759   if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
   23760 #endif
   23761   assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
   23762   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   23763 }
   23764 
   23765 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
   23766   if( !sqlite3GlobalConfig.bCoreMutex ){
   23767     return 0;
   23768   }
   23769   assert( GLOBAL(int, mutexIsInit) );
   23770   assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
   23771   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   23772 }
   23773 
   23774 /*
   23775 ** Free a dynamic mutex.
   23776 */
   23777 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
   23778   if( p ){
   23779     assert( sqlite3GlobalConfig.mutex.xMutexFree );
   23780     sqlite3GlobalConfig.mutex.xMutexFree(p);
   23781   }
   23782 }
   23783 
   23784 /*
   23785 ** Obtain the mutex p. If some other thread already has the mutex, block
   23786 ** until it can be obtained.
   23787 */
   23788 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
   23789   if( p ){
   23790     assert( sqlite3GlobalConfig.mutex.xMutexEnter );
   23791     sqlite3GlobalConfig.mutex.xMutexEnter(p);
   23792   }
   23793 }
   23794 
   23795 /*
   23796 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
   23797 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
   23798 */
   23799 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
   23800   int rc = SQLITE_OK;
   23801   if( p ){
   23802     assert( sqlite3GlobalConfig.mutex.xMutexTry );
   23803     return sqlite3GlobalConfig.mutex.xMutexTry(p);
   23804   }
   23805   return rc;
   23806 }
   23807 
   23808 /*
   23809 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
   23810 ** entered by the same thread.  The behavior is undefined if the mutex
   23811 ** is not currently entered. If a NULL pointer is passed as an argument
   23812 ** this function is a no-op.
   23813 */
   23814 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
   23815   if( p ){
   23816     assert( sqlite3GlobalConfig.mutex.xMutexLeave );
   23817     sqlite3GlobalConfig.mutex.xMutexLeave(p);
   23818   }
   23819 }
   23820 
   23821 #ifndef NDEBUG
   23822 /*
   23823 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   23824 ** intended for use inside assert() statements.
   23825 */
   23826 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
   23827   assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
   23828   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
   23829 }
   23830 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
   23831   assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
   23832   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
   23833 }
   23834 #endif
   23835 
   23836 #endif /* !defined(SQLITE_MUTEX_OMIT) */
   23837 
   23838 
   23839 /************** End of mutex.c ***********************************************/
   23840 /************** Begin file mutex_noop.c **************************************/
   23841 /*
   23842 ** 2008 October 07
   23843 **
   23844 ** The author disclaims copyright to this source code.  In place of
   23845 ** a legal notice, here is a blessing:
   23846 **
   23847 **    May you do good and not evil.
   23848 **    May you find forgiveness for yourself and forgive others.
   23849 **    May you share freely, never taking more than you give.
   23850 **
   23851 *************************************************************************
   23852 ** This file contains the C functions that implement mutexes.
   23853 **
   23854 ** This implementation in this file does not provide any mutual
   23855 ** exclusion and is thus suitable for use only in applications
   23856 ** that use SQLite in a single thread.  The routines defined
   23857 ** here are place-holders.  Applications can substitute working
   23858 ** mutex routines at start-time using the
   23859 **
   23860 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
   23861 **
   23862 ** interface.
   23863 **
   23864 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
   23865 ** that does error checking on mutexes to make sure they are being
   23866 ** called correctly.
   23867 */
   23868 /* #include "sqliteInt.h" */
   23869 
   23870 #ifndef SQLITE_MUTEX_OMIT
   23871 
   23872 #ifndef SQLITE_DEBUG
   23873 /*
   23874 ** Stub routines for all mutex methods.
   23875 **
   23876 ** This routines provide no mutual exclusion or error checking.
   23877 */
   23878 static int noopMutexInit(void){ return SQLITE_OK; }
   23879 static int noopMutexEnd(void){ return SQLITE_OK; }
   23880 static sqlite3_mutex *noopMutexAlloc(int id){
   23881   UNUSED_PARAMETER(id);
   23882   return (sqlite3_mutex*)8;
   23883 }
   23884 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   23885 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   23886 static int noopMutexTry(sqlite3_mutex *p){
   23887   UNUSED_PARAMETER(p);
   23888   return SQLITE_OK;
   23889 }
   23890 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   23891 
   23892 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   23893   static const sqlite3_mutex_methods sMutex = {
   23894     noopMutexInit,
   23895     noopMutexEnd,
   23896     noopMutexAlloc,
   23897     noopMutexFree,
   23898     noopMutexEnter,
   23899     noopMutexTry,
   23900     noopMutexLeave,
   23901 
   23902     0,
   23903     0,
   23904   };
   23905 
   23906   return &sMutex;
   23907 }
   23908 #endif /* !SQLITE_DEBUG */
   23909 
   23910 #ifdef SQLITE_DEBUG
   23911 /*
   23912 ** In this implementation, error checking is provided for testing
   23913 ** and debugging purposes.  The mutexes still do not provide any
   23914 ** mutual exclusion.
   23915 */
   23916 
   23917 /*
   23918 ** The mutex object
   23919 */
   23920 typedef struct sqlite3_debug_mutex {
   23921   int id;     /* The mutex type */
   23922   int cnt;    /* Number of entries without a matching leave */
   23923 } sqlite3_debug_mutex;
   23924 
   23925 /*
   23926 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   23927 ** intended for use inside assert() statements.
   23928 */
   23929 static int debugMutexHeld(sqlite3_mutex *pX){
   23930   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   23931   return p==0 || p->cnt>0;
   23932 }
   23933 static int debugMutexNotheld(sqlite3_mutex *pX){
   23934   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   23935   return p==0 || p->cnt==0;
   23936 }
   23937 
   23938 /*
   23939 ** Initialize and deinitialize the mutex subsystem.
   23940 */
   23941 static int debugMutexInit(void){ return SQLITE_OK; }
   23942 static int debugMutexEnd(void){ return SQLITE_OK; }
   23943 
   23944 /*
   23945 ** The sqlite3_mutex_alloc() routine allocates a new
   23946 ** mutex and returns a pointer to it.  If it returns NULL
   23947 ** that means that a mutex could not be allocated.
   23948 */
   23949 static sqlite3_mutex *debugMutexAlloc(int id){
   23950   static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
   23951   sqlite3_debug_mutex *pNew = 0;
   23952   switch( id ){
   23953     case SQLITE_MUTEX_FAST:
   23954     case SQLITE_MUTEX_RECURSIVE: {
   23955       pNew = sqlite3Malloc(sizeof(*pNew));
   23956       if( pNew ){
   23957         pNew->id = id;
   23958         pNew->cnt = 0;
   23959       }
   23960       break;
   23961     }
   23962     default: {
   23963 #ifdef SQLITE_ENABLE_API_ARMOR
   23964       if( id-2<0 || id-2>=ArraySize(aStatic) ){
   23965         (void)SQLITE_MISUSE_BKPT;
   23966         return 0;
   23967       }
   23968 #endif
   23969       pNew = &aStatic[id-2];
   23970       pNew->id = id;
   23971       break;
   23972     }
   23973   }
   23974   return (sqlite3_mutex*)pNew;
   23975 }
   23976 
   23977 /*
   23978 ** This routine deallocates a previously allocated mutex.
   23979 */
   23980 static void debugMutexFree(sqlite3_mutex *pX){
   23981   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   23982   assert( p->cnt==0 );
   23983   if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
   23984     sqlite3_free(p);
   23985   }else{
   23986 #ifdef SQLITE_ENABLE_API_ARMOR
   23987     (void)SQLITE_MISUSE_BKPT;
   23988 #endif
   23989   }
   23990 }
   23991 
   23992 /*
   23993 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   23994 ** to enter a mutex.  If another thread is already within the mutex,
   23995 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   23996 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   23997 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   23998 ** be entered multiple times by the same thread.  In such cases the,
   23999 ** mutex must be exited an equal number of times before another thread
   24000 ** can enter.  If the same thread tries to enter any other kind of mutex
   24001 ** more than once, the behavior is undefined.
   24002 */
   24003 static void debugMutexEnter(sqlite3_mutex *pX){
   24004   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   24005   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   24006   p->cnt++;
   24007 }
   24008 static int debugMutexTry(sqlite3_mutex *pX){
   24009   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   24010   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   24011   p->cnt++;
   24012   return SQLITE_OK;
   24013 }
   24014 
   24015 /*
   24016 ** The sqlite3_mutex_leave() routine exits a mutex that was
   24017 ** previously entered by the same thread.  The behavior
   24018 ** is undefined if the mutex is not currently entered or
   24019 ** is not currently allocated.  SQLite will never do either.
   24020 */
   24021 static void debugMutexLeave(sqlite3_mutex *pX){
   24022   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   24023   assert( debugMutexHeld(pX) );
   24024   p->cnt--;
   24025   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   24026 }
   24027 
   24028 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   24029   static const sqlite3_mutex_methods sMutex = {
   24030     debugMutexInit,
   24031     debugMutexEnd,
   24032     debugMutexAlloc,
   24033     debugMutexFree,
   24034     debugMutexEnter,
   24035     debugMutexTry,
   24036     debugMutexLeave,
   24037 
   24038     debugMutexHeld,
   24039     debugMutexNotheld
   24040   };
   24041 
   24042   return &sMutex;
   24043 }
   24044 #endif /* SQLITE_DEBUG */
   24045 
   24046 /*
   24047 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
   24048 ** is used regardless of the run-time threadsafety setting.
   24049 */
   24050 #ifdef SQLITE_MUTEX_NOOP
   24051 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   24052   return sqlite3NoopMutex();
   24053 }
   24054 #endif /* defined(SQLITE_MUTEX_NOOP) */
   24055 #endif /* !defined(SQLITE_MUTEX_OMIT) */
   24056 
   24057 /************** End of mutex_noop.c ******************************************/
   24058 /************** Begin file mutex_unix.c **************************************/
   24059 /*
   24060 ** 2007 August 28
   24061 **
   24062 ** The author disclaims copyright to this source code.  In place of
   24063 ** a legal notice, here is a blessing:
   24064 **
   24065 **    May you do good and not evil.
   24066 **    May you find forgiveness for yourself and forgive others.
   24067 **    May you share freely, never taking more than you give.
   24068 **
   24069 *************************************************************************
   24070 ** This file contains the C functions that implement mutexes for pthreads
   24071 */
   24072 /* #include "sqliteInt.h" */
   24073 
   24074 /*
   24075 ** The code in this file is only used if we are compiling threadsafe
   24076 ** under unix with pthreads.
   24077 **
   24078 ** Note that this implementation requires a version of pthreads that
   24079 ** supports recursive mutexes.
   24080 */
   24081 #ifdef SQLITE_MUTEX_PTHREADS
   24082 
   24083 #include <pthread.h>
   24084 
   24085 /*
   24086 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
   24087 ** are necessary under two condidtions:  (1) Debug builds and (2) using
   24088 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
   24089 */
   24090 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
   24091 # define SQLITE_MUTEX_NREF 1
   24092 #else
   24093 # define SQLITE_MUTEX_NREF 0
   24094 #endif
   24095 
   24096 /*
   24097 ** Each recursive mutex is an instance of the following structure.
   24098 */
   24099 struct sqlite3_mutex {
   24100   pthread_mutex_t mutex;     /* Mutex controlling the lock */
   24101 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
   24102   int id;                    /* Mutex type */
   24103 #endif
   24104 #if SQLITE_MUTEX_NREF
   24105   volatile int nRef;         /* Number of entrances */
   24106   volatile pthread_t owner;  /* Thread that is within this mutex */
   24107   int trace;                 /* True to trace changes */
   24108 #endif
   24109 };
   24110 #if SQLITE_MUTEX_NREF
   24111 #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
   24112 #elif defined(SQLITE_ENABLE_API_ARMOR)
   24113 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
   24114 #else
   24115 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
   24116 #endif
   24117 
   24118 /*
   24119 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   24120 ** intended for use only inside assert() statements.  On some platforms,
   24121 ** there might be race conditions that can cause these routines to
   24122 ** deliver incorrect results.  In particular, if pthread_equal() is
   24123 ** not an atomic operation, then these routines might delivery
   24124 ** incorrect results.  On most platforms, pthread_equal() is a
   24125 ** comparison of two integers and is therefore atomic.  But we are
   24126 ** told that HPUX is not such a platform.  If so, then these routines
   24127 ** will not always work correctly on HPUX.
   24128 **
   24129 ** On those platforms where pthread_equal() is not atomic, SQLite
   24130 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
   24131 ** make sure no assert() statements are evaluated and hence these
   24132 ** routines are never called.
   24133 */
   24134 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
   24135 static int pthreadMutexHeld(sqlite3_mutex *p){
   24136   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
   24137 }
   24138 static int pthreadMutexNotheld(sqlite3_mutex *p){
   24139   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
   24140 }
   24141 #endif
   24142 
   24143 /*
   24144 ** Try to provide a memory barrier operation, needed for initialization
   24145 ** and also for the implementation of xShmBarrier in the VFS in cases
   24146 ** where SQLite is compiled without mutexes.
   24147 */
   24148 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
   24149 #if defined(SQLITE_MEMORY_BARRIER)
   24150   SQLITE_MEMORY_BARRIER;
   24151 #elif defined(__GNUC__) && GCC_VERSION>=4001000
   24152   __sync_synchronize();
   24153 #endif
   24154 }
   24155 
   24156 /*
   24157 ** Initialize and deinitialize the mutex subsystem.
   24158 */
   24159 static int pthreadMutexInit(void){ return SQLITE_OK; }
   24160 static int pthreadMutexEnd(void){ return SQLITE_OK; }
   24161 
   24162 /*
   24163 ** The sqlite3_mutex_alloc() routine allocates a new
   24164 ** mutex and returns a pointer to it.  If it returns NULL
   24165 ** that means that a mutex could not be allocated.  SQLite
   24166 ** will unwind its stack and return an error.  The argument
   24167 ** to sqlite3_mutex_alloc() is one of these integer constants:
   24168 **
   24169 ** <ul>
   24170 ** <li>  SQLITE_MUTEX_FAST
   24171 ** <li>  SQLITE_MUTEX_RECURSIVE
   24172 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   24173 ** <li>  SQLITE_MUTEX_STATIC_MEM
   24174 ** <li>  SQLITE_MUTEX_STATIC_OPEN
   24175 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   24176 ** <li>  SQLITE_MUTEX_STATIC_LRU
   24177 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   24178 ** <li>  SQLITE_MUTEX_STATIC_APP1
   24179 ** <li>  SQLITE_MUTEX_STATIC_APP2
   24180 ** <li>  SQLITE_MUTEX_STATIC_APP3
   24181 ** <li>  SQLITE_MUTEX_STATIC_VFS1
   24182 ** <li>  SQLITE_MUTEX_STATIC_VFS2
   24183 ** <li>  SQLITE_MUTEX_STATIC_VFS3
   24184 ** </ul>
   24185 **
   24186 ** The first two constants cause sqlite3_mutex_alloc() to create
   24187 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   24188 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   24189 ** The mutex implementation does not need to make a distinction
   24190 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   24191 ** not want to.  But SQLite will only request a recursive mutex in
   24192 ** cases where it really needs one.  If a faster non-recursive mutex
   24193 ** implementation is available on the host platform, the mutex subsystem
   24194 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   24195 **
   24196 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   24197 ** a pointer to a static preexisting mutex.  Six static mutexes are
   24198 ** used by the current version of SQLite.  Future versions of SQLite
   24199 ** may add additional static mutexes.  Static mutexes are for internal
   24200 ** use by SQLite only.  Applications that use SQLite mutexes should
   24201 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   24202 ** SQLITE_MUTEX_RECURSIVE.
   24203 **
   24204 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   24205 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   24206 ** returns a different mutex on every call.  But for the static
   24207 ** mutex types, the same mutex is returned on every call that has
   24208 ** the same type number.
   24209 */
   24210 static sqlite3_mutex *pthreadMutexAlloc(int iType){
   24211   static sqlite3_mutex staticMutexes[] = {
   24212     SQLITE3_MUTEX_INITIALIZER,
   24213     SQLITE3_MUTEX_INITIALIZER,
   24214     SQLITE3_MUTEX_INITIALIZER,
   24215     SQLITE3_MUTEX_INITIALIZER,
   24216     SQLITE3_MUTEX_INITIALIZER,
   24217     SQLITE3_MUTEX_INITIALIZER,
   24218     SQLITE3_MUTEX_INITIALIZER,
   24219     SQLITE3_MUTEX_INITIALIZER,
   24220     SQLITE3_MUTEX_INITIALIZER,
   24221     SQLITE3_MUTEX_INITIALIZER,
   24222     SQLITE3_MUTEX_INITIALIZER,
   24223     SQLITE3_MUTEX_INITIALIZER
   24224   };
   24225   sqlite3_mutex *p;
   24226   switch( iType ){
   24227     case SQLITE_MUTEX_RECURSIVE: {
   24228       p = sqlite3MallocZero( sizeof(*p) );
   24229       if( p ){
   24230 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   24231         /* If recursive mutexes are not available, we will have to
   24232         ** build our own.  See below. */
   24233         pthread_mutex_init(&p->mutex, 0);
   24234 #else
   24235         /* Use a recursive mutex if it is available */
   24236         pthread_mutexattr_t recursiveAttr;
   24237         pthread_mutexattr_init(&recursiveAttr);
   24238         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
   24239         pthread_mutex_init(&p->mutex, &recursiveAttr);
   24240         pthread_mutexattr_destroy(&recursiveAttr);
   24241 #endif
   24242       }
   24243       break;
   24244     }
   24245     case SQLITE_MUTEX_FAST: {
   24246       p = sqlite3MallocZero( sizeof(*p) );
   24247       if( p ){
   24248         pthread_mutex_init(&p->mutex, 0);
   24249       }
   24250       break;
   24251     }
   24252     default: {
   24253 #ifdef SQLITE_ENABLE_API_ARMOR
   24254       if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
   24255         (void)SQLITE_MISUSE_BKPT;
   24256         return 0;
   24257       }
   24258 #endif
   24259       p = &staticMutexes[iType-2];
   24260       break;
   24261     }
   24262   }
   24263 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
   24264   if( p ) p->id = iType;
   24265 #endif
   24266   return p;
   24267 }
   24268 
   24269 
   24270 /*
   24271 ** This routine deallocates a previously
   24272 ** allocated mutex.  SQLite is careful to deallocate every
   24273 ** mutex that it allocates.
   24274 */
   24275 static void pthreadMutexFree(sqlite3_mutex *p){
   24276   assert( p->nRef==0 );
   24277 #if SQLITE_ENABLE_API_ARMOR
   24278   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
   24279 #endif
   24280   {
   24281     pthread_mutex_destroy(&p->mutex);
   24282     sqlite3_free(p);
   24283   }
   24284 #ifdef SQLITE_ENABLE_API_ARMOR
   24285   else{
   24286     (void)SQLITE_MISUSE_BKPT;
   24287   }
   24288 #endif
   24289 }
   24290 
   24291 /*
   24292 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   24293 ** to enter a mutex.  If another thread is already within the mutex,
   24294 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   24295 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   24296 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   24297 ** be entered multiple times by the same thread.  In such cases the,
   24298 ** mutex must be exited an equal number of times before another thread
   24299 ** can enter.  If the same thread tries to enter any other kind of mutex
   24300 ** more than once, the behavior is undefined.
   24301 */
   24302 static void pthreadMutexEnter(sqlite3_mutex *p){
   24303   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   24304 
   24305 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   24306   /* If recursive mutexes are not available, then we have to grow
   24307   ** our own.  This implementation assumes that pthread_equal()
   24308   ** is atomic - that it cannot be deceived into thinking self
   24309   ** and p->owner are equal if p->owner changes between two values
   24310   ** that are not equal to self while the comparison is taking place.
   24311   ** This implementation also assumes a coherent cache - that
   24312   ** separate processes cannot read different values from the same
   24313   ** address at the same time.  If either of these two conditions
   24314   ** are not met, then the mutexes will fail and problems will result.
   24315   */
   24316   {
   24317     pthread_t self = pthread_self();
   24318     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   24319       p->nRef++;
   24320     }else{
   24321       pthread_mutex_lock(&p->mutex);
   24322       assert( p->nRef==0 );
   24323       p->owner = self;
   24324       p->nRef = 1;
   24325     }
   24326   }
   24327 #else
   24328   /* Use the built-in recursive mutexes if they are available.
   24329   */
   24330   pthread_mutex_lock(&p->mutex);
   24331 #if SQLITE_MUTEX_NREF
   24332   assert( p->nRef>0 || p->owner==0 );
   24333   p->owner = pthread_self();
   24334   p->nRef++;
   24335 #endif
   24336 #endif
   24337 
   24338 #ifdef SQLITE_DEBUG
   24339   if( p->trace ){
   24340     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   24341   }
   24342 #endif
   24343 }
   24344 static int pthreadMutexTry(sqlite3_mutex *p){
   24345   int rc;
   24346   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   24347 
   24348 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   24349   /* If recursive mutexes are not available, then we have to grow
   24350   ** our own.  This implementation assumes that pthread_equal()
   24351   ** is atomic - that it cannot be deceived into thinking self
   24352   ** and p->owner are equal if p->owner changes between two values
   24353   ** that are not equal to self while the comparison is taking place.
   24354   ** This implementation also assumes a coherent cache - that
   24355   ** separate processes cannot read different values from the same
   24356   ** address at the same time.  If either of these two conditions
   24357   ** are not met, then the mutexes will fail and problems will result.
   24358   */
   24359   {
   24360     pthread_t self = pthread_self();
   24361     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   24362       p->nRef++;
   24363       rc = SQLITE_OK;
   24364     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
   24365       assert( p->nRef==0 );
   24366       p->owner = self;
   24367       p->nRef = 1;
   24368       rc = SQLITE_OK;
   24369     }else{
   24370       rc = SQLITE_BUSY;
   24371     }
   24372   }
   24373 #else
   24374   /* Use the built-in recursive mutexes if they are available.
   24375   */
   24376   if( pthread_mutex_trylock(&p->mutex)==0 ){
   24377 #if SQLITE_MUTEX_NREF
   24378     p->owner = pthread_self();
   24379     p->nRef++;
   24380 #endif
   24381     rc = SQLITE_OK;
   24382   }else{
   24383     rc = SQLITE_BUSY;
   24384   }
   24385 #endif
   24386 
   24387 #ifdef SQLITE_DEBUG
   24388   if( rc==SQLITE_OK && p->trace ){
   24389     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   24390   }
   24391 #endif
   24392   return rc;
   24393 }
   24394 
   24395 /*
   24396 ** The sqlite3_mutex_leave() routine exits a mutex that was
   24397 ** previously entered by the same thread.  The behavior
   24398 ** is undefined if the mutex is not currently entered or
   24399 ** is not currently allocated.  SQLite will never do either.
   24400 */
   24401 static void pthreadMutexLeave(sqlite3_mutex *p){
   24402   assert( pthreadMutexHeld(p) );
   24403 #if SQLITE_MUTEX_NREF
   24404   p->nRef--;
   24405   if( p->nRef==0 ) p->owner = 0;
   24406 #endif
   24407   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   24408 
   24409 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   24410   if( p->nRef==0 ){
   24411     pthread_mutex_unlock(&p->mutex);
   24412   }
   24413 #else
   24414   pthread_mutex_unlock(&p->mutex);
   24415 #endif
   24416 
   24417 #ifdef SQLITE_DEBUG
   24418   if( p->trace ){
   24419     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   24420   }
   24421 #endif
   24422 }
   24423 
   24424 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   24425   static const sqlite3_mutex_methods sMutex = {
   24426     pthreadMutexInit,
   24427     pthreadMutexEnd,
   24428     pthreadMutexAlloc,
   24429     pthreadMutexFree,
   24430     pthreadMutexEnter,
   24431     pthreadMutexTry,
   24432     pthreadMutexLeave,
   24433 #ifdef SQLITE_DEBUG
   24434     pthreadMutexHeld,
   24435     pthreadMutexNotheld
   24436 #else
   24437     0,
   24438     0
   24439 #endif
   24440   };
   24441 
   24442   return &sMutex;
   24443 }
   24444 
   24445 #endif /* SQLITE_MUTEX_PTHREADS */
   24446 
   24447 /************** End of mutex_unix.c ******************************************/
   24448 /************** Begin file mutex_w32.c ***************************************/
   24449 /*
   24450 ** 2007 August 14
   24451 **
   24452 ** The author disclaims copyright to this source code.  In place of
   24453 ** a legal notice, here is a blessing:
   24454 **
   24455 **    May you do good and not evil.
   24456 **    May you find forgiveness for yourself and forgive others.
   24457 **    May you share freely, never taking more than you give.
   24458 **
   24459 *************************************************************************
   24460 ** This file contains the C functions that implement mutexes for Win32.
   24461 */
   24462 /* #include "sqliteInt.h" */
   24463 
   24464 #if SQLITE_OS_WIN
   24465 /*
   24466 ** Include code that is common to all os_*.c files
   24467 */
   24468 /************** Include os_common.h in the middle of mutex_w32.c *************/
   24469 /************** Begin file os_common.h ***************************************/
   24470 /*
   24471 ** 2004 May 22
   24472 **
   24473 ** The author disclaims copyright to this source code.  In place of
   24474 ** a legal notice, here is a blessing:
   24475 **
   24476 **    May you do good and not evil.
   24477 **    May you find forgiveness for yourself and forgive others.
   24478 **    May you share freely, never taking more than you give.
   24479 **
   24480 ******************************************************************************
   24481 **
   24482 ** This file contains macros and a little bit of code that is common to
   24483 ** all of the platform-specific files (os_*.c) and is #included into those
   24484 ** files.
   24485 **
   24486 ** This file should be #included by the os_*.c files only.  It is not a
   24487 ** general purpose header file.
   24488 */
   24489 #ifndef _OS_COMMON_H_
   24490 #define _OS_COMMON_H_
   24491 
   24492 /*
   24493 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   24494 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   24495 ** switch.  The following code should catch this problem at compile-time.
   24496 */
   24497 #ifdef MEMORY_DEBUG
   24498 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   24499 #endif
   24500 
   24501 /*
   24502 ** Macros for performance tracing.  Normally turned off.  Only works
   24503 ** on i486 hardware.
   24504 */
   24505 #ifdef SQLITE_PERFORMANCE_TRACE
   24506 
   24507 /*
   24508 ** hwtime.h contains inline assembler code for implementing
   24509 ** high-performance timing routines.
   24510 */
   24511 /************** Include hwtime.h in the middle of os_common.h ****************/
   24512 /************** Begin file hwtime.h ******************************************/
   24513 /*
   24514 ** 2008 May 27
   24515 **
   24516 ** The author disclaims copyright to this source code.  In place of
   24517 ** a legal notice, here is a blessing:
   24518 **
   24519 **    May you do good and not evil.
   24520 **    May you find forgiveness for yourself and forgive others.
   24521 **    May you share freely, never taking more than you give.
   24522 **
   24523 ******************************************************************************
   24524 **
   24525 ** This file contains inline asm code for retrieving "high-performance"
   24526 ** counters for x86 class CPUs.
   24527 */
   24528 #ifndef SQLITE_HWTIME_H
   24529 #define SQLITE_HWTIME_H
   24530 
   24531 /*
   24532 ** The following routine only works on pentium-class (or newer) processors.
   24533 ** It uses the RDTSC opcode to read the cycle count value out of the
   24534 ** processor and returns that value.  This can be used for high-res
   24535 ** profiling.
   24536 */
   24537 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   24538       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   24539 
   24540   #if defined(__GNUC__)
   24541 
   24542   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24543      unsigned int lo, hi;
   24544      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   24545      return (sqlite_uint64)hi << 32 | lo;
   24546   }
   24547 
   24548   #elif defined(_MSC_VER)
   24549 
   24550   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   24551      __asm {
   24552         rdtsc
   24553         ret       ; return value at EDX:EAX
   24554      }
   24555   }
   24556 
   24557   #endif
   24558 
   24559 #elif (defined(__GNUC__) && defined(__x86_64__))
   24560 
   24561   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24562       unsigned long val;
   24563       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   24564       return val;
   24565   }
   24566 
   24567 #elif (defined(__GNUC__) && defined(__ppc__))
   24568 
   24569   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   24570       unsigned long long retval;
   24571       unsigned long junk;
   24572       __asm__ __volatile__ ("\n\
   24573           1:      mftbu   %1\n\
   24574                   mftb    %L0\n\
   24575                   mftbu   %0\n\
   24576                   cmpw    %0,%1\n\
   24577                   bne     1b"
   24578                   : "=r" (retval), "=r" (junk));
   24579       return retval;
   24580   }
   24581 
   24582 #else
   24583 
   24584   #error Need implementation of sqlite3Hwtime() for your platform.
   24585 
   24586   /*
   24587   ** To compile without implementing sqlite3Hwtime() for your platform,
   24588   ** you can remove the above #error and use the following
   24589   ** stub function.  You will lose timing support for many
   24590   ** of the debugging and testing utilities, but it should at
   24591   ** least compile and run.
   24592   */
   24593 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   24594 
   24595 #endif
   24596 
   24597 #endif /* !defined(SQLITE_HWTIME_H) */
   24598 
   24599 /************** End of hwtime.h **********************************************/
   24600 /************** Continuing where we left off in os_common.h ******************/
   24601 
   24602 static sqlite_uint64 g_start;
   24603 static sqlite_uint64 g_elapsed;
   24604 #define TIMER_START       g_start=sqlite3Hwtime()
   24605 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   24606 #define TIMER_ELAPSED     g_elapsed
   24607 #else
   24608 #define TIMER_START
   24609 #define TIMER_END
   24610 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   24611 #endif
   24612 
   24613 /*
   24614 ** If we compile with the SQLITE_TEST macro set, then the following block
   24615 ** of code will give us the ability to simulate a disk I/O error.  This
   24616 ** is used for testing the I/O recovery logic.
   24617 */
   24618 #if defined(SQLITE_TEST)
   24619 SQLITE_API extern int sqlite3_io_error_hit;
   24620 SQLITE_API extern int sqlite3_io_error_hardhit;
   24621 SQLITE_API extern int sqlite3_io_error_pending;
   24622 SQLITE_API extern int sqlite3_io_error_persist;
   24623 SQLITE_API extern int sqlite3_io_error_benign;
   24624 SQLITE_API extern int sqlite3_diskfull_pending;
   24625 SQLITE_API extern int sqlite3_diskfull;
   24626 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   24627 #define SimulateIOError(CODE)  \
   24628   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   24629        || sqlite3_io_error_pending-- == 1 )  \
   24630               { local_ioerr(); CODE; }
   24631 static void local_ioerr(){
   24632   IOTRACE(("IOERR\n"));
   24633   sqlite3_io_error_hit++;
   24634   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   24635 }
   24636 #define SimulateDiskfullError(CODE) \
   24637    if( sqlite3_diskfull_pending ){ \
   24638      if( sqlite3_diskfull_pending == 1 ){ \
   24639        local_ioerr(); \
   24640        sqlite3_diskfull = 1; \
   24641        sqlite3_io_error_hit = 1; \
   24642        CODE; \
   24643      }else{ \
   24644        sqlite3_diskfull_pending--; \
   24645      } \
   24646    }
   24647 #else
   24648 #define SimulateIOErrorBenign(X)
   24649 #define SimulateIOError(A)
   24650 #define SimulateDiskfullError(A)
   24651 #endif /* defined(SQLITE_TEST) */
   24652 
   24653 /*
   24654 ** When testing, keep a count of the number of open files.
   24655 */
   24656 #if defined(SQLITE_TEST)
   24657 SQLITE_API extern int sqlite3_open_file_count;
   24658 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   24659 #else
   24660 #define OpenCounter(X)
   24661 #endif /* defined(SQLITE_TEST) */
   24662 
   24663 #endif /* !defined(_OS_COMMON_H_) */
   24664 
   24665 /************** End of os_common.h *******************************************/
   24666 /************** Continuing where we left off in mutex_w32.c ******************/
   24667 
   24668 /*
   24669 ** Include the header file for the Windows VFS.
   24670 */
   24671 /************** Include os_win.h in the middle of mutex_w32.c ****************/
   24672 /************** Begin file os_win.h ******************************************/
   24673 /*
   24674 ** 2013 November 25
   24675 **
   24676 ** The author disclaims copyright to this source code.  In place of
   24677 ** a legal notice, here is a blessing:
   24678 **
   24679 **    May you do good and not evil.
   24680 **    May you find forgiveness for yourself and forgive others.
   24681 **    May you share freely, never taking more than you give.
   24682 **
   24683 ******************************************************************************
   24684 **
   24685 ** This file contains code that is specific to Windows.
   24686 */
   24687 #ifndef SQLITE_OS_WIN_H
   24688 #define SQLITE_OS_WIN_H
   24689 
   24690 /*
   24691 ** Include the primary Windows SDK header file.
   24692 */
   24693 #include "windows.h"
   24694 
   24695 #ifdef __CYGWIN__
   24696 # include <sys/cygwin.h>
   24697 # include <errno.h> /* amalgamator: dontcache */
   24698 #endif
   24699 
   24700 /*
   24701 ** Determine if we are dealing with Windows NT.
   24702 **
   24703 ** We ought to be able to determine if we are compiling for Windows 9x or
   24704 ** Windows NT using the _WIN32_WINNT macro as follows:
   24705 **
   24706 ** #if defined(_WIN32_WINNT)
   24707 ** # define SQLITE_OS_WINNT 1
   24708 ** #else
   24709 ** # define SQLITE_OS_WINNT 0
   24710 ** #endif
   24711 **
   24712 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
   24713 ** it ought to, so the above test does not work.  We'll just assume that
   24714 ** everything is Windows NT unless the programmer explicitly says otherwise
   24715 ** by setting SQLITE_OS_WINNT to 0.
   24716 */
   24717 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
   24718 # define SQLITE_OS_WINNT 1
   24719 #endif
   24720 
   24721 /*
   24722 ** Determine if we are dealing with Windows CE - which has a much reduced
   24723 ** API.
   24724 */
   24725 #if defined(_WIN32_WCE)
   24726 # define SQLITE_OS_WINCE 1
   24727 #else
   24728 # define SQLITE_OS_WINCE 0
   24729 #endif
   24730 
   24731 /*
   24732 ** Determine if we are dealing with WinRT, which provides only a subset of
   24733 ** the full Win32 API.
   24734 */
   24735 #if !defined(SQLITE_OS_WINRT)
   24736 # define SQLITE_OS_WINRT 0
   24737 #endif
   24738 
   24739 /*
   24740 ** For WinCE, some API function parameters do not appear to be declared as
   24741 ** volatile.
   24742 */
   24743 #if SQLITE_OS_WINCE
   24744 # define SQLITE_WIN32_VOLATILE
   24745 #else
   24746 # define SQLITE_WIN32_VOLATILE volatile
   24747 #endif
   24748 
   24749 /*
   24750 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
   24751 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
   24752 */
   24753 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
   24754     SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
   24755 # define SQLITE_OS_WIN_THREADS 1
   24756 #else
   24757 # define SQLITE_OS_WIN_THREADS 0
   24758 #endif
   24759 
   24760 #endif /* SQLITE_OS_WIN_H */
   24761 
   24762 /************** End of os_win.h **********************************************/
   24763 /************** Continuing where we left off in mutex_w32.c ******************/
   24764 #endif
   24765 
   24766 /*
   24767 ** The code in this file is only used if we are compiling multithreaded
   24768 ** on a Win32 system.
   24769 */
   24770 #ifdef SQLITE_MUTEX_W32
   24771 
   24772 /*
   24773 ** Each recursive mutex is an instance of the following structure.
   24774 */
   24775 struct sqlite3_mutex {
   24776   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
   24777   int id;                    /* Mutex type */
   24778 #ifdef SQLITE_DEBUG
   24779   volatile int nRef;         /* Number of enterances */
   24780   volatile DWORD owner;      /* Thread holding this mutex */
   24781   volatile int trace;        /* True to trace changes */
   24782 #endif
   24783 };
   24784 
   24785 /*
   24786 ** These are the initializer values used when declaring a "static" mutex
   24787 ** on Win32.  It should be noted that all mutexes require initialization
   24788 ** on the Win32 platform.
   24789 */
   24790 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
   24791 
   24792 #ifdef SQLITE_DEBUG
   24793 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
   24794                                     0L, (DWORD)0, 0 }
   24795 #else
   24796 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
   24797 #endif
   24798 
   24799 #ifdef SQLITE_DEBUG
   24800 /*
   24801 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   24802 ** intended for use only inside assert() statements.
   24803 */
   24804 static int winMutexHeld(sqlite3_mutex *p){
   24805   return p->nRef!=0 && p->owner==GetCurrentThreadId();
   24806 }
   24807 
   24808 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
   24809   return p->nRef==0 || p->owner!=tid;
   24810 }
   24811 
   24812 static int winMutexNotheld(sqlite3_mutex *p){
   24813   DWORD tid = GetCurrentThreadId();
   24814   return winMutexNotheld2(p, tid);
   24815 }
   24816 #endif
   24817 
   24818 /*
   24819 ** Try to provide a memory barrier operation, needed for initialization
   24820 ** and also for the xShmBarrier method of the VFS in cases when SQLite is
   24821 ** compiled without mutexes (SQLITE_THREADSAFE=0).
   24822 */
   24823 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
   24824 #if defined(SQLITE_MEMORY_BARRIER)
   24825   SQLITE_MEMORY_BARRIER;
   24826 #elif defined(__GNUC__)
   24827   __sync_synchronize();
   24828 #elif MSVC_VERSION>=1300
   24829   _ReadWriteBarrier();
   24830 #elif defined(MemoryBarrier)
   24831   MemoryBarrier();
   24832 #endif
   24833 }
   24834 
   24835 /*
   24836 ** Initialize and deinitialize the mutex subsystem.
   24837 */
   24838 static sqlite3_mutex winMutex_staticMutexes[] = {
   24839   SQLITE3_MUTEX_INITIALIZER,
   24840   SQLITE3_MUTEX_INITIALIZER,
   24841   SQLITE3_MUTEX_INITIALIZER,
   24842   SQLITE3_MUTEX_INITIALIZER,
   24843   SQLITE3_MUTEX_INITIALIZER,
   24844   SQLITE3_MUTEX_INITIALIZER,
   24845   SQLITE3_MUTEX_INITIALIZER,
   24846   SQLITE3_MUTEX_INITIALIZER,
   24847   SQLITE3_MUTEX_INITIALIZER,
   24848   SQLITE3_MUTEX_INITIALIZER,
   24849   SQLITE3_MUTEX_INITIALIZER,
   24850   SQLITE3_MUTEX_INITIALIZER
   24851 };
   24852 
   24853 static int winMutex_isInit = 0;
   24854 static int winMutex_isNt = -1; /* <0 means "need to query" */
   24855 
   24856 /* As the winMutexInit() and winMutexEnd() functions are called as part
   24857 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
   24858 ** "interlocked" magic used here is probably not strictly necessary.
   24859 */
   24860 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
   24861 
   24862 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
   24863 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
   24864 
   24865 static int winMutexInit(void){
   24866   /* The first to increment to 1 does actual initialization */
   24867   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
   24868     int i;
   24869     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   24870 #if SQLITE_OS_WINRT
   24871       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
   24872 #else
   24873       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
   24874 #endif
   24875     }
   24876     winMutex_isInit = 1;
   24877   }else{
   24878     /* Another thread is (in the process of) initializing the static
   24879     ** mutexes */
   24880     while( !winMutex_isInit ){
   24881       sqlite3_win32_sleep(1);
   24882     }
   24883   }
   24884   return SQLITE_OK;
   24885 }
   24886 
   24887 static int winMutexEnd(void){
   24888   /* The first to decrement to 0 does actual shutdown
   24889   ** (which should be the last to shutdown.) */
   24890   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
   24891     if( winMutex_isInit==1 ){
   24892       int i;
   24893       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   24894         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
   24895       }
   24896       winMutex_isInit = 0;
   24897     }
   24898   }
   24899   return SQLITE_OK;
   24900 }
   24901 
   24902 /*
   24903 ** The sqlite3_mutex_alloc() routine allocates a new
   24904 ** mutex and returns a pointer to it.  If it returns NULL
   24905 ** that means that a mutex could not be allocated.  SQLite
   24906 ** will unwind its stack and return an error.  The argument
   24907 ** to sqlite3_mutex_alloc() is one of these integer constants:
   24908 **
   24909 ** <ul>
   24910 ** <li>  SQLITE_MUTEX_FAST
   24911 ** <li>  SQLITE_MUTEX_RECURSIVE
   24912 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   24913 ** <li>  SQLITE_MUTEX_STATIC_MEM
   24914 ** <li>  SQLITE_MUTEX_STATIC_OPEN
   24915 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   24916 ** <li>  SQLITE_MUTEX_STATIC_LRU
   24917 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   24918 ** <li>  SQLITE_MUTEX_STATIC_APP1
   24919 ** <li>  SQLITE_MUTEX_STATIC_APP2
   24920 ** <li>  SQLITE_MUTEX_STATIC_APP3
   24921 ** <li>  SQLITE_MUTEX_STATIC_VFS1
   24922 ** <li>  SQLITE_MUTEX_STATIC_VFS2
   24923 ** <li>  SQLITE_MUTEX_STATIC_VFS3
   24924 ** </ul>
   24925 **
   24926 ** The first two constants cause sqlite3_mutex_alloc() to create
   24927 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   24928 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   24929 ** The mutex implementation does not need to make a distinction
   24930 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   24931 ** not want to.  But SQLite will only request a recursive mutex in
   24932 ** cases where it really needs one.  If a faster non-recursive mutex
   24933 ** implementation is available on the host platform, the mutex subsystem
   24934 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   24935 **
   24936 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   24937 ** a pointer to a static preexisting mutex.  Six static mutexes are
   24938 ** used by the current version of SQLite.  Future versions of SQLite
   24939 ** may add additional static mutexes.  Static mutexes are for internal
   24940 ** use by SQLite only.  Applications that use SQLite mutexes should
   24941 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   24942 ** SQLITE_MUTEX_RECURSIVE.
   24943 **
   24944 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   24945 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   24946 ** returns a different mutex on every call.  But for the static
   24947 ** mutex types, the same mutex is returned on every call that has
   24948 ** the same type number.
   24949 */
   24950 static sqlite3_mutex *winMutexAlloc(int iType){
   24951   sqlite3_mutex *p;
   24952 
   24953   switch( iType ){
   24954     case SQLITE_MUTEX_FAST:
   24955     case SQLITE_MUTEX_RECURSIVE: {
   24956       p = sqlite3MallocZero( sizeof(*p) );
   24957       if( p ){
   24958         p->id = iType;
   24959 #ifdef SQLITE_DEBUG
   24960 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
   24961         p->trace = 1;
   24962 #endif
   24963 #endif
   24964 #if SQLITE_OS_WINRT
   24965         InitializeCriticalSectionEx(&p->mutex, 0, 0);
   24966 #else
   24967         InitializeCriticalSection(&p->mutex);
   24968 #endif
   24969       }
   24970       break;
   24971     }
   24972     default: {
   24973 #ifdef SQLITE_ENABLE_API_ARMOR
   24974       if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
   24975         (void)SQLITE_MISUSE_BKPT;
   24976         return 0;
   24977       }
   24978 #endif
   24979       p = &winMutex_staticMutexes[iType-2];
   24980       p->id = iType;
   24981 #ifdef SQLITE_DEBUG
   24982 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
   24983       p->trace = 1;
   24984 #endif
   24985 #endif
   24986       break;
   24987     }
   24988   }
   24989   return p;
   24990 }
   24991 
   24992 
   24993 /*
   24994 ** This routine deallocates a previously
   24995 ** allocated mutex.  SQLite is careful to deallocate every
   24996 ** mutex that it allocates.
   24997 */
   24998 static void winMutexFree(sqlite3_mutex *p){
   24999   assert( p );
   25000   assert( p->nRef==0 && p->owner==0 );
   25001   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
   25002     DeleteCriticalSection(&p->mutex);
   25003     sqlite3_free(p);
   25004   }else{
   25005 #ifdef SQLITE_ENABLE_API_ARMOR
   25006     (void)SQLITE_MISUSE_BKPT;
   25007 #endif
   25008   }
   25009 }
   25010 
   25011 /*
   25012 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   25013 ** to enter a mutex.  If another thread is already within the mutex,
   25014 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   25015 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   25016 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   25017 ** be entered multiple times by the same thread.  In such cases the,
   25018 ** mutex must be exited an equal number of times before another thread
   25019 ** can enter.  If the same thread tries to enter any other kind of mutex
   25020 ** more than once, the behavior is undefined.
   25021 */
   25022 static void winMutexEnter(sqlite3_mutex *p){
   25023 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   25024   DWORD tid = GetCurrentThreadId();
   25025 #endif
   25026 #ifdef SQLITE_DEBUG
   25027   assert( p );
   25028   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   25029 #else
   25030   assert( p );
   25031 #endif
   25032   assert( winMutex_isInit==1 );
   25033   EnterCriticalSection(&p->mutex);
   25034 #ifdef SQLITE_DEBUG
   25035   assert( p->nRef>0 || p->owner==0 );
   25036   p->owner = tid;
   25037   p->nRef++;
   25038   if( p->trace ){
   25039     OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
   25040              tid, p->id, p, p->trace, p->nRef));
   25041   }
   25042 #endif
   25043 }
   25044 
   25045 static int winMutexTry(sqlite3_mutex *p){
   25046 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   25047   DWORD tid = GetCurrentThreadId();
   25048 #endif
   25049   int rc = SQLITE_BUSY;
   25050   assert( p );
   25051   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   25052   /*
   25053   ** The sqlite3_mutex_try() routine is very rarely used, and when it
   25054   ** is used it is merely an optimization.  So it is OK for it to always
   25055   ** fail.
   25056   **
   25057   ** The TryEnterCriticalSection() interface is only available on WinNT.
   25058   ** And some windows compilers complain if you try to use it without
   25059   ** first doing some #defines that prevent SQLite from building on Win98.
   25060   ** For that reason, we will omit this optimization for now.  See
   25061   ** ticket #2685.
   25062   */
   25063 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
   25064   assert( winMutex_isInit==1 );
   25065   assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
   25066   if( winMutex_isNt<0 ){
   25067     winMutex_isNt = sqlite3_win32_is_nt();
   25068   }
   25069   assert( winMutex_isNt==0 || winMutex_isNt==1 );
   25070   if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
   25071 #ifdef SQLITE_DEBUG
   25072     p->owner = tid;
   25073     p->nRef++;
   25074 #endif
   25075     rc = SQLITE_OK;
   25076   }
   25077 #else
   25078   UNUSED_PARAMETER(p);
   25079 #endif
   25080 #ifdef SQLITE_DEBUG
   25081   if( p->trace ){
   25082     OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
   25083              tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
   25084   }
   25085 #endif
   25086   return rc;
   25087 }
   25088 
   25089 /*
   25090 ** The sqlite3_mutex_leave() routine exits a mutex that was
   25091 ** previously entered by the same thread.  The behavior
   25092 ** is undefined if the mutex is not currently entered or
   25093 ** is not currently allocated.  SQLite will never do either.
   25094 */
   25095 static void winMutexLeave(sqlite3_mutex *p){
   25096 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   25097   DWORD tid = GetCurrentThreadId();
   25098 #endif
   25099   assert( p );
   25100 #ifdef SQLITE_DEBUG
   25101   assert( p->nRef>0 );
   25102   assert( p->owner==tid );
   25103   p->nRef--;
   25104   if( p->nRef==0 ) p->owner = 0;
   25105   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   25106 #endif
   25107   assert( winMutex_isInit==1 );
   25108   LeaveCriticalSection(&p->mutex);
   25109 #ifdef SQLITE_DEBUG
   25110   if( p->trace ){
   25111     OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
   25112              tid, p->id, p, p->trace, p->nRef));
   25113   }
   25114 #endif
   25115 }
   25116 
   25117 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   25118   static const sqlite3_mutex_methods sMutex = {
   25119     winMutexInit,
   25120     winMutexEnd,
   25121     winMutexAlloc,
   25122     winMutexFree,
   25123     winMutexEnter,
   25124     winMutexTry,
   25125     winMutexLeave,
   25126 #ifdef SQLITE_DEBUG
   25127     winMutexHeld,
   25128     winMutexNotheld
   25129 #else
   25130     0,
   25131     0
   25132 #endif
   25133   };
   25134   return &sMutex;
   25135 }
   25136 
   25137 #endif /* SQLITE_MUTEX_W32 */
   25138 
   25139 /************** End of mutex_w32.c *******************************************/
   25140 /************** Begin file malloc.c ******************************************/
   25141 /*
   25142 ** 2001 September 15
   25143 **
   25144 ** The author disclaims copyright to this source code.  In place of
   25145 ** a legal notice, here is a blessing:
   25146 **
   25147 **    May you do good and not evil.
   25148 **    May you find forgiveness for yourself and forgive others.
   25149 **    May you share freely, never taking more than you give.
   25150 **
   25151 *************************************************************************
   25152 **
   25153 ** Memory allocation functions used throughout sqlite.
   25154 */
   25155 /* #include "sqliteInt.h" */
   25156 /* #include <stdarg.h> */
   25157 
   25158 /*
   25159 ** Attempt to release up to n bytes of non-essential memory currently
   25160 ** held by SQLite. An example of non-essential memory is memory used to
   25161 ** cache database pages that are not currently in use.
   25162 */
   25163 SQLITE_API int sqlite3_release_memory(int n){
   25164 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   25165   return sqlite3PcacheReleaseMemory(n);
   25166 #else
   25167   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
   25168   ** is a no-op returning zero if SQLite is not compiled with
   25169   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
   25170   UNUSED_PARAMETER(n);
   25171   return 0;
   25172 #endif
   25173 }
   25174 
   25175 /*
   25176 ** State information local to the memory allocation subsystem.
   25177 */
   25178 static SQLITE_WSD struct Mem0Global {
   25179   sqlite3_mutex *mutex;         /* Mutex to serialize access */
   25180   sqlite3_int64 alarmThreshold; /* The soft heap limit */
   25181 
   25182   /*
   25183   ** True if heap is nearly "full" where "full" is defined by the
   25184   ** sqlite3_soft_heap_limit() setting.
   25185   */
   25186   int nearlyFull;
   25187 } mem0 = { 0, 0, 0 };
   25188 
   25189 #define mem0 GLOBAL(struct Mem0Global, mem0)
   25190 
   25191 /*
   25192 ** Return the memory allocator mutex. sqlite3_status() needs it.
   25193 */
   25194 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
   25195   return mem0.mutex;
   25196 }
   25197 
   25198 #ifndef SQLITE_OMIT_DEPRECATED
   25199 /*
   25200 ** Deprecated external interface.  It used to set an alarm callback
   25201 ** that was invoked when memory usage grew too large.  Now it is a
   25202 ** no-op.
   25203 */
   25204 SQLITE_API int sqlite3_memory_alarm(
   25205   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   25206   void *pArg,
   25207   sqlite3_int64 iThreshold
   25208 ){
   25209   (void)xCallback;
   25210   (void)pArg;
   25211   (void)iThreshold;
   25212   return SQLITE_OK;
   25213 }
   25214 #endif
   25215 
   25216 /*
   25217 ** Set the soft heap-size limit for the library. Passing a zero or
   25218 ** negative value indicates no limit.
   25219 */
   25220 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
   25221   sqlite3_int64 priorLimit;
   25222   sqlite3_int64 excess;
   25223   sqlite3_int64 nUsed;
   25224 #ifndef SQLITE_OMIT_AUTOINIT
   25225   int rc = sqlite3_initialize();
   25226   if( rc ) return -1;
   25227 #endif
   25228   sqlite3_mutex_enter(mem0.mutex);
   25229   priorLimit = mem0.alarmThreshold;
   25230   if( n<0 ){
   25231     sqlite3_mutex_leave(mem0.mutex);
   25232     return priorLimit;
   25233   }
   25234   mem0.alarmThreshold = n;
   25235   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   25236   mem0.nearlyFull = (n>0 && n<=nUsed);
   25237   sqlite3_mutex_leave(mem0.mutex);
   25238   excess = sqlite3_memory_used() - n;
   25239   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
   25240   return priorLimit;
   25241 }
   25242 SQLITE_API void sqlite3_soft_heap_limit(int n){
   25243   if( n<0 ) n = 0;
   25244   sqlite3_soft_heap_limit64(n);
   25245 }
   25246 
   25247 /*
   25248 ** Initialize the memory allocation subsystem.
   25249 */
   25250 SQLITE_PRIVATE int sqlite3MallocInit(void){
   25251   int rc;
   25252   if( sqlite3GlobalConfig.m.xMalloc==0 ){
   25253     sqlite3MemSetDefault();
   25254   }
   25255   memset(&mem0, 0, sizeof(mem0));
   25256   mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   25257   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
   25258       || sqlite3GlobalConfig.nPage<=0 ){
   25259     sqlite3GlobalConfig.pPage = 0;
   25260     sqlite3GlobalConfig.szPage = 0;
   25261   }
   25262   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
   25263   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
   25264   return rc;
   25265 }
   25266 
   25267 /*
   25268 ** Return true if the heap is currently under memory pressure - in other
   25269 ** words if the amount of heap used is close to the limit set by
   25270 ** sqlite3_soft_heap_limit().
   25271 */
   25272 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
   25273   return mem0.nearlyFull;
   25274 }
   25275 
   25276 /*
   25277 ** Deinitialize the memory allocation subsystem.
   25278 */
   25279 SQLITE_PRIVATE void sqlite3MallocEnd(void){
   25280   if( sqlite3GlobalConfig.m.xShutdown ){
   25281     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
   25282   }
   25283   memset(&mem0, 0, sizeof(mem0));
   25284 }
   25285 
   25286 /*
   25287 ** Return the amount of memory currently checked out.
   25288 */
   25289 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
   25290   sqlite3_int64 res, mx;
   25291   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
   25292   return res;
   25293 }
   25294 
   25295 /*
   25296 ** Return the maximum amount of memory that has ever been
   25297 ** checked out since either the beginning of this process
   25298 ** or since the most recent reset.
   25299 */
   25300 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
   25301   sqlite3_int64 res, mx;
   25302   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
   25303   return mx;
   25304 }
   25305 
   25306 /*
   25307 ** Trigger the alarm
   25308 */
   25309 static void sqlite3MallocAlarm(int nByte){
   25310   if( mem0.alarmThreshold<=0 ) return;
   25311   sqlite3_mutex_leave(mem0.mutex);
   25312   sqlite3_release_memory(nByte);
   25313   sqlite3_mutex_enter(mem0.mutex);
   25314 }
   25315 
   25316 /*
   25317 ** Do a memory allocation with statistics and alarms.  Assume the
   25318 ** lock is already held.
   25319 */
   25320 static void mallocWithAlarm(int n, void **pp){
   25321   void *p;
   25322   int nFull;
   25323   assert( sqlite3_mutex_held(mem0.mutex) );
   25324   assert( n>0 );
   25325 
   25326   /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
   25327   ** implementation of malloc_good_size(), which must be called in debug
   25328   ** mode and specifically when the DMD "Dark Matter Detector" is enabled
   25329   ** or else a crash results.  Hence, do not attempt to optimize out the
   25330   ** following xRoundup() call. */
   25331   nFull = sqlite3GlobalConfig.m.xRoundup(n);
   25332 
   25333 #ifdef SQLITE_MAX_MEMORY
   25334   if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
   25335     *pp = 0;
   25336     return;
   25337   }
   25338 #endif
   25339 
   25340   sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
   25341   if( mem0.alarmThreshold>0 ){
   25342     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   25343     if( nUsed >= mem0.alarmThreshold - nFull ){
   25344       mem0.nearlyFull = 1;
   25345       sqlite3MallocAlarm(nFull);
   25346     }else{
   25347       mem0.nearlyFull = 0;
   25348     }
   25349   }
   25350   p = sqlite3GlobalConfig.m.xMalloc(nFull);
   25351 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   25352   if( p==0 && mem0.alarmThreshold>0 ){
   25353     sqlite3MallocAlarm(nFull);
   25354     p = sqlite3GlobalConfig.m.xMalloc(nFull);
   25355   }
   25356 #endif
   25357   if( p ){
   25358     nFull = sqlite3MallocSize(p);
   25359     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
   25360     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
   25361   }
   25362   *pp = p;
   25363 }
   25364 
   25365 /*
   25366 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
   25367 ** assumes the memory subsystem has already been initialized.
   25368 */
   25369 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
   25370   void *p;
   25371   if( n==0 || n>=0x7fffff00 ){
   25372     /* A memory allocation of a number of bytes which is near the maximum
   25373     ** signed integer value might cause an integer overflow inside of the
   25374     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
   25375     ** 255 bytes of overhead.  SQLite itself will never use anything near
   25376     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
   25377     p = 0;
   25378   }else if( sqlite3GlobalConfig.bMemstat ){
   25379     sqlite3_mutex_enter(mem0.mutex);
   25380     mallocWithAlarm((int)n, &p);
   25381     sqlite3_mutex_leave(mem0.mutex);
   25382   }else{
   25383     p = sqlite3GlobalConfig.m.xMalloc((int)n);
   25384   }
   25385   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
   25386   return p;
   25387 }
   25388 
   25389 /*
   25390 ** This version of the memory allocation is for use by the application.
   25391 ** First make sure the memory subsystem is initialized, then do the
   25392 ** allocation.
   25393 */
   25394 SQLITE_API void *sqlite3_malloc(int n){
   25395 #ifndef SQLITE_OMIT_AUTOINIT
   25396   if( sqlite3_initialize() ) return 0;
   25397 #endif
   25398   return n<=0 ? 0 : sqlite3Malloc(n);
   25399 }
   25400 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
   25401 #ifndef SQLITE_OMIT_AUTOINIT
   25402   if( sqlite3_initialize() ) return 0;
   25403 #endif
   25404   return sqlite3Malloc(n);
   25405 }
   25406 
   25407 /*
   25408 ** TRUE if p is a lookaside memory allocation from db
   25409 */
   25410 #ifndef SQLITE_OMIT_LOOKASIDE
   25411 static int isLookaside(sqlite3 *db, void *p){
   25412   return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
   25413 }
   25414 #else
   25415 #define isLookaside(A,B) 0
   25416 #endif
   25417 
   25418 /*
   25419 ** Return the size of a memory allocation previously obtained from
   25420 ** sqlite3Malloc() or sqlite3_malloc().
   25421 */
   25422 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
   25423   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   25424   return sqlite3GlobalConfig.m.xSize(p);
   25425 }
   25426 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
   25427   assert( p!=0 );
   25428   if( db==0 || !isLookaside(db,p) ){
   25429 #ifdef SQLITE_DEBUG
   25430     if( db==0 ){
   25431       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
   25432       assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   25433     }else{
   25434       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   25435       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   25436     }
   25437 #endif
   25438     return sqlite3GlobalConfig.m.xSize(p);
   25439   }else{
   25440     assert( sqlite3_mutex_held(db->mutex) );
   25441     return db->lookaside.sz;
   25442   }
   25443 }
   25444 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
   25445   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
   25446   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   25447   return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
   25448 }
   25449 
   25450 /*
   25451 ** Free memory previously obtained from sqlite3Malloc().
   25452 */
   25453 SQLITE_API void sqlite3_free(void *p){
   25454   if( p==0 ) return;  /* IMP: R-49053-54554 */
   25455   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   25456   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
   25457   if( sqlite3GlobalConfig.bMemstat ){
   25458     sqlite3_mutex_enter(mem0.mutex);
   25459     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
   25460     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
   25461     sqlite3GlobalConfig.m.xFree(p);
   25462     sqlite3_mutex_leave(mem0.mutex);
   25463   }else{
   25464     sqlite3GlobalConfig.m.xFree(p);
   25465   }
   25466 }
   25467 
   25468 /*
   25469 ** Add the size of memory allocation "p" to the count in
   25470 ** *db->pnBytesFreed.
   25471 */
   25472 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
   25473   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
   25474 }
   25475 
   25476 /*
   25477 ** Free memory that might be associated with a particular database
   25478 ** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
   25479 ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
   25480 */
   25481 SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
   25482   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   25483   assert( p!=0 );
   25484   if( db ){
   25485     if( db->pnBytesFreed ){
   25486       measureAllocationSize(db, p);
   25487       return;
   25488     }
   25489     if( isLookaside(db, p) ){
   25490       LookasideSlot *pBuf = (LookasideSlot*)p;
   25491 #ifdef SQLITE_DEBUG
   25492       /* Trash all content in the buffer being freed */
   25493       memset(p, 0xaa, db->lookaside.sz);
   25494 #endif
   25495       pBuf->pNext = db->lookaside.pFree;
   25496       db->lookaside.pFree = pBuf;
   25497       return;
   25498     }
   25499   }
   25500   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   25501   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   25502   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   25503   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   25504   sqlite3_free(p);
   25505 }
   25506 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
   25507   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   25508   if( p ) sqlite3DbFreeNN(db, p);
   25509 }
   25510 
   25511 /*
   25512 ** Change the size of an existing memory allocation
   25513 */
   25514 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
   25515   int nOld, nNew, nDiff;
   25516   void *pNew;
   25517   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
   25518   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
   25519   if( pOld==0 ){
   25520     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
   25521   }
   25522   if( nBytes==0 ){
   25523     sqlite3_free(pOld); /* IMP: R-26507-47431 */
   25524     return 0;
   25525   }
   25526   if( nBytes>=0x7fffff00 ){
   25527     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
   25528     return 0;
   25529   }
   25530   nOld = sqlite3MallocSize(pOld);
   25531   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
   25532   ** argument to xRealloc is always a value returned by a prior call to
   25533   ** xRoundup. */
   25534   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
   25535   if( nOld==nNew ){
   25536     pNew = pOld;
   25537   }else if( sqlite3GlobalConfig.bMemstat ){
   25538     sqlite3_mutex_enter(mem0.mutex);
   25539     sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
   25540     nDiff = nNew - nOld;
   25541     if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
   25542           mem0.alarmThreshold-nDiff ){
   25543       sqlite3MallocAlarm(nDiff);
   25544     }
   25545     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   25546     if( pNew==0 && mem0.alarmThreshold>0 ){
   25547       sqlite3MallocAlarm((int)nBytes);
   25548       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   25549     }
   25550     if( pNew ){
   25551       nNew = sqlite3MallocSize(pNew);
   25552       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
   25553     }
   25554     sqlite3_mutex_leave(mem0.mutex);
   25555   }else{
   25556     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   25557   }
   25558   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
   25559   return pNew;
   25560 }
   25561 
   25562 /*
   25563 ** The public interface to sqlite3Realloc.  Make sure that the memory
   25564 ** subsystem is initialized prior to invoking sqliteRealloc.
   25565 */
   25566 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
   25567 #ifndef SQLITE_OMIT_AUTOINIT
   25568   if( sqlite3_initialize() ) return 0;
   25569 #endif
   25570   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
   25571   return sqlite3Realloc(pOld, n);
   25572 }
   25573 SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
   25574 #ifndef SQLITE_OMIT_AUTOINIT
   25575   if( sqlite3_initialize() ) return 0;
   25576 #endif
   25577   return sqlite3Realloc(pOld, n);
   25578 }
   25579 
   25580 
   25581 /*
   25582 ** Allocate and zero memory.
   25583 */
   25584 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
   25585   void *p = sqlite3Malloc(n);
   25586   if( p ){
   25587     memset(p, 0, (size_t)n);
   25588   }
   25589   return p;
   25590 }
   25591 
   25592 /*
   25593 ** Allocate and zero memory.  If the allocation fails, make
   25594 ** the mallocFailed flag in the connection pointer.
   25595 */
   25596 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
   25597   void *p;
   25598   testcase( db==0 );
   25599   p = sqlite3DbMallocRaw(db, n);
   25600   if( p ) memset(p, 0, (size_t)n);
   25601   return p;
   25602 }
   25603 
   25604 
   25605 /* Finish the work of sqlite3DbMallocRawNN for the unusual and
   25606 ** slower case when the allocation cannot be fulfilled using lookaside.
   25607 */
   25608 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
   25609   void *p;
   25610   assert( db!=0 );
   25611   p = sqlite3Malloc(n);
   25612   if( !p ) sqlite3OomFault(db);
   25613   sqlite3MemdebugSetType(p,
   25614          (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
   25615   return p;
   25616 }
   25617 
   25618 /*
   25619 ** Allocate memory, either lookaside (if possible) or heap.
   25620 ** If the allocation fails, set the mallocFailed flag in
   25621 ** the connection pointer.
   25622 **
   25623 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
   25624 ** failure on the same database connection) then always return 0.
   25625 ** Hence for a particular database connection, once malloc starts
   25626 ** failing, it fails consistently until mallocFailed is reset.
   25627 ** This is an important assumption.  There are many places in the
   25628 ** code that do things like this:
   25629 **
   25630 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
   25631 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
   25632 **         if( b ) a[10] = 9;
   25633 **
   25634 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
   25635 ** that all prior mallocs (ex: "a") worked too.
   25636 **
   25637 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
   25638 ** not a NULL pointer.
   25639 */
   25640 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
   25641   void *p;
   25642   if( db ) return sqlite3DbMallocRawNN(db, n);
   25643   p = sqlite3Malloc(n);
   25644   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   25645   return p;
   25646 }
   25647 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
   25648 #ifndef SQLITE_OMIT_LOOKASIDE
   25649   LookasideSlot *pBuf;
   25650   assert( db!=0 );
   25651   assert( sqlite3_mutex_held(db->mutex) );
   25652   assert( db->pnBytesFreed==0 );
   25653   if( db->lookaside.bDisable==0 ){
   25654     assert( db->mallocFailed==0 );
   25655     if( n>db->lookaside.sz ){
   25656       db->lookaside.anStat[1]++;
   25657     }else if( (pBuf = db->lookaside.pFree)!=0 ){
   25658       db->lookaside.pFree = pBuf->pNext;
   25659       db->lookaside.anStat[0]++;
   25660       return (void*)pBuf;
   25661     }else if( (pBuf = db->lookaside.pInit)!=0 ){
   25662       db->lookaside.pInit = pBuf->pNext;
   25663       db->lookaside.anStat[0]++;
   25664       return (void*)pBuf;
   25665     }else{
   25666       db->lookaside.anStat[2]++;
   25667     }
   25668   }else if( db->mallocFailed ){
   25669     return 0;
   25670   }
   25671 #else
   25672   assert( db!=0 );
   25673   assert( sqlite3_mutex_held(db->mutex) );
   25674   assert( db->pnBytesFreed==0 );
   25675   if( db->mallocFailed ){
   25676     return 0;
   25677   }
   25678 #endif
   25679   return dbMallocRawFinish(db, n);
   25680 }
   25681 
   25682 /* Forward declaration */
   25683 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
   25684 
   25685 /*
   25686 ** Resize the block of memory pointed to by p to n bytes. If the
   25687 ** resize fails, set the mallocFailed flag in the connection object.
   25688 */
   25689 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
   25690   assert( db!=0 );
   25691   if( p==0 ) return sqlite3DbMallocRawNN(db, n);
   25692   assert( sqlite3_mutex_held(db->mutex) );
   25693   if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
   25694   return dbReallocFinish(db, p, n);
   25695 }
   25696 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
   25697   void *pNew = 0;
   25698   assert( db!=0 );
   25699   assert( p!=0 );
   25700   if( db->mallocFailed==0 ){
   25701     if( isLookaside(db, p) ){
   25702       pNew = sqlite3DbMallocRawNN(db, n);
   25703       if( pNew ){
   25704         memcpy(pNew, p, db->lookaside.sz);
   25705         sqlite3DbFree(db, p);
   25706       }
   25707     }else{
   25708       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   25709       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   25710       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   25711       pNew = sqlite3_realloc64(p, n);
   25712       if( !pNew ){
   25713         sqlite3OomFault(db);
   25714       }
   25715       sqlite3MemdebugSetType(pNew,
   25716             (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   25717     }
   25718   }
   25719   return pNew;
   25720 }
   25721 
   25722 /*
   25723 ** Attempt to reallocate p.  If the reallocation fails, then free p
   25724 ** and set the mallocFailed flag in the database connection.
   25725 */
   25726 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
   25727   void *pNew;
   25728   pNew = sqlite3DbRealloc(db, p, n);
   25729   if( !pNew ){
   25730     sqlite3DbFree(db, p);
   25731   }
   25732   return pNew;
   25733 }
   25734 
   25735 /*
   25736 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
   25737 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
   25738 ** is because when memory debugging is turned on, these two functions are
   25739 ** called via macros that record the current file and line number in the
   25740 ** ThreadData structure.
   25741 */
   25742 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
   25743   char *zNew;
   25744   size_t n;
   25745   if( z==0 ){
   25746     return 0;
   25747   }
   25748   n = strlen(z) + 1;
   25749   zNew = sqlite3DbMallocRaw(db, n);
   25750   if( zNew ){
   25751     memcpy(zNew, z, n);
   25752   }
   25753   return zNew;
   25754 }
   25755 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
   25756   char *zNew;
   25757   assert( db!=0 );
   25758   if( z==0 ){
   25759     return 0;
   25760   }
   25761   assert( (n&0x7fffffff)==n );
   25762   zNew = sqlite3DbMallocRawNN(db, n+1);
   25763   if( zNew ){
   25764     memcpy(zNew, z, (size_t)n);
   25765     zNew[n] = 0;
   25766   }
   25767   return zNew;
   25768 }
   25769 
   25770 /*
   25771 ** The text between zStart and zEnd represents a phrase within a larger
   25772 ** SQL statement.  Make a copy of this phrase in space obtained form
   25773 ** sqlite3DbMalloc().  Omit leading and trailing whitespace.
   25774 */
   25775 SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
   25776   int n;
   25777   while( sqlite3Isspace(zStart[0]) ) zStart++;
   25778   n = (int)(zEnd - zStart);
   25779   while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
   25780   return sqlite3DbStrNDup(db, zStart, n);
   25781 }
   25782 
   25783 /*
   25784 ** Free any prior content in *pz and replace it with a copy of zNew.
   25785 */
   25786 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
   25787   sqlite3DbFree(db, *pz);
   25788   *pz = sqlite3DbStrDup(db, zNew);
   25789 }
   25790 
   25791 /*
   25792 ** Call this routine to record the fact that an OOM (out-of-memory) error
   25793 ** has happened.  This routine will set db->mallocFailed, and also
   25794 ** temporarily disable the lookaside memory allocator and interrupt
   25795 ** any running VDBEs.
   25796 */
   25797 SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
   25798   if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
   25799     db->mallocFailed = 1;
   25800     if( db->nVdbeExec>0 ){
   25801       db->u1.isInterrupted = 1;
   25802     }
   25803     db->lookaside.bDisable++;
   25804   }
   25805 }
   25806 
   25807 /*
   25808 ** This routine reactivates the memory allocator and clears the
   25809 ** db->mallocFailed flag as necessary.
   25810 **
   25811 ** The memory allocator is not restarted if there are running
   25812 ** VDBEs.
   25813 */
   25814 SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
   25815   if( db->mallocFailed && db->nVdbeExec==0 ){
   25816     db->mallocFailed = 0;
   25817     db->u1.isInterrupted = 0;
   25818     assert( db->lookaside.bDisable>0 );
   25819     db->lookaside.bDisable--;
   25820   }
   25821 }
   25822 
   25823 /*
   25824 ** Take actions at the end of an API call to indicate an OOM error
   25825 */
   25826 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
   25827   sqlite3OomClear(db);
   25828   sqlite3Error(db, SQLITE_NOMEM);
   25829   return SQLITE_NOMEM_BKPT;
   25830 }
   25831 
   25832 /*
   25833 ** This function must be called before exiting any API function (i.e.
   25834 ** returning control to the user) that has called sqlite3_malloc or
   25835 ** sqlite3_realloc.
   25836 **
   25837 ** The returned value is normally a copy of the second argument to this
   25838 ** function. However, if a malloc() failure has occurred since the previous
   25839 ** invocation SQLITE_NOMEM is returned instead.
   25840 **
   25841 ** If an OOM as occurred, then the connection error-code (the value
   25842 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
   25843 */
   25844 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
   25845   /* If the db handle must hold the connection handle mutex here.
   25846   ** Otherwise the read (and possible write) of db->mallocFailed
   25847   ** is unsafe, as is the call to sqlite3Error().
   25848   */
   25849   assert( db!=0 );
   25850   assert( sqlite3_mutex_held(db->mutex) );
   25851   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
   25852     return apiOomError(db);
   25853   }
   25854   return rc & db->errMask;
   25855 }
   25856 
   25857 /************** End of malloc.c **********************************************/
   25858 /************** Begin file printf.c ******************************************/
   25859 /*
   25860 ** The "printf" code that follows dates from the 1980's.  It is in
   25861 ** the public domain.
   25862 **
   25863 **************************************************************************
   25864 **
   25865 ** This file contains code for a set of "printf"-like routines.  These
   25866 ** routines format strings much like the printf() from the standard C
   25867 ** library, though the implementation here has enhancements to support
   25868 ** SQLite.
   25869 */
   25870 /* #include "sqliteInt.h" */
   25871 
   25872 /*
   25873 ** Conversion types fall into various categories as defined by the
   25874 ** following enumeration.
   25875 */
   25876 #define etRADIX       0 /* non-decimal integer types.  %x %o */
   25877 #define etFLOAT       1 /* Floating point.  %f */
   25878 #define etEXP         2 /* Exponentional notation. %e and %E */
   25879 #define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
   25880 #define etSIZE        4 /* Return number of characters processed so far. %n */
   25881 #define etSTRING      5 /* Strings. %s */
   25882 #define etDYNSTRING   6 /* Dynamically allocated strings. %z */
   25883 #define etPERCENT     7 /* Percent symbol. %% */
   25884 #define etCHARX       8 /* Characters. %c */
   25885 /* The rest are extensions, not normally found in printf() */
   25886 #define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
   25887 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
   25888                           NULL pointers replaced by SQL NULL.  %Q */
   25889 #define etTOKEN      11 /* a pointer to a Token structure */
   25890 #define etSRCLIST    12 /* a pointer to a SrcList */
   25891 #define etPOINTER    13 /* The %p conversion */
   25892 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
   25893 #define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
   25894 #define etDECIMAL    16 /* %d or %u, but not %x, %o */
   25895 
   25896 #define etINVALID    17 /* Any unrecognized conversion type */
   25897 
   25898 
   25899 /*
   25900 ** An "etByte" is an 8-bit unsigned value.
   25901 */
   25902 typedef unsigned char etByte;
   25903 
   25904 /*
   25905 ** Each builtin conversion character (ex: the 'd' in "%d") is described
   25906 ** by an instance of the following structure
   25907 */
   25908 typedef struct et_info {   /* Information about each format field */
   25909   char fmttype;            /* The format field code letter */
   25910   etByte base;             /* The base for radix conversion */
   25911   etByte flags;            /* One or more of FLAG_ constants below */
   25912   etByte type;             /* Conversion paradigm */
   25913   etByte charset;          /* Offset into aDigits[] of the digits string */
   25914   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
   25915 } et_info;
   25916 
   25917 /*
   25918 ** Allowed values for et_info.flags
   25919 */
   25920 #define FLAG_SIGNED    1     /* True if the value to convert is signed */
   25921 #define FLAG_STRING    4     /* Allow infinite precision */
   25922 
   25923 
   25924 /*
   25925 ** The following table is searched linearly, so it is good to put the
   25926 ** most frequently used conversion types first.
   25927 */
   25928 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
   25929 static const char aPrefix[] = "-x0\000X0";
   25930 static const et_info fmtinfo[] = {
   25931   {  'd', 10, 1, etDECIMAL,    0,  0 },
   25932   {  's',  0, 4, etSTRING,     0,  0 },
   25933   {  'g',  0, 1, etGENERIC,    30, 0 },
   25934   {  'z',  0, 4, etDYNSTRING,  0,  0 },
   25935   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
   25936   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
   25937   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
   25938   {  'c',  0, 0, etCHARX,      0,  0 },
   25939   {  'o',  8, 0, etRADIX,      0,  2 },
   25940   {  'u', 10, 0, etDECIMAL,    0,  0 },
   25941   {  'x', 16, 0, etRADIX,      16, 1 },
   25942   {  'X', 16, 0, etRADIX,      0,  4 },
   25943 #ifndef SQLITE_OMIT_FLOATING_POINT
   25944   {  'f',  0, 1, etFLOAT,      0,  0 },
   25945   {  'e',  0, 1, etEXP,        30, 0 },
   25946   {  'E',  0, 1, etEXP,        14, 0 },
   25947   {  'G',  0, 1, etGENERIC,    14, 0 },
   25948 #endif
   25949   {  'i', 10, 1, etDECIMAL,    0,  0 },
   25950   {  'n',  0, 0, etSIZE,       0,  0 },
   25951   {  '%',  0, 0, etPERCENT,    0,  0 },
   25952   {  'p', 16, 0, etPOINTER,    0,  1 },
   25953 
   25954   /* All the rest are undocumented and are for internal use only */
   25955   {  'T',  0, 0, etTOKEN,      0,  0 },
   25956   {  'S',  0, 0, etSRCLIST,    0,  0 },
   25957   {  'r', 10, 1, etORDINAL,    0,  0 },
   25958 };
   25959 
   25960 /*
   25961 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
   25962 ** conversions will work.
   25963 */
   25964 #ifndef SQLITE_OMIT_FLOATING_POINT
   25965 /*
   25966 ** "*val" is a double such that 0.1 <= *val < 10.0
   25967 ** Return the ascii code for the leading digit of *val, then
   25968 ** multiply "*val" by 10.0 to renormalize.
   25969 **
   25970 ** Example:
   25971 **     input:     *val = 3.14159
   25972 **     output:    *val = 1.4159    function return = '3'
   25973 **
   25974 ** The counter *cnt is incremented each time.  After counter exceeds
   25975 ** 16 (the number of significant digits in a 64-bit float) '0' is
   25976 ** always returned.
   25977 */
   25978 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
   25979   int digit;
   25980   LONGDOUBLE_TYPE d;
   25981   if( (*cnt)<=0 ) return '0';
   25982   (*cnt)--;
   25983   digit = (int)*val;
   25984   d = digit;
   25985   digit += '0';
   25986   *val = (*val - d)*10.0;
   25987   return (char)digit;
   25988 }
   25989 #endif /* SQLITE_OMIT_FLOATING_POINT */
   25990 
   25991 /*
   25992 ** Set the StrAccum object to an error mode.
   25993 */
   25994 static void setStrAccumError(StrAccum *p, u8 eError){
   25995   assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
   25996   p->accError = eError;
   25997   p->nAlloc = 0;
   25998 }
   25999 
   26000 /*
   26001 ** Extra argument values from a PrintfArguments object
   26002 */
   26003 static sqlite3_int64 getIntArg(PrintfArguments *p){
   26004   if( p->nArg<=p->nUsed ) return 0;
   26005   return sqlite3_value_int64(p->apArg[p->nUsed++]);
   26006 }
   26007 static double getDoubleArg(PrintfArguments *p){
   26008   if( p->nArg<=p->nUsed ) return 0.0;
   26009   return sqlite3_value_double(p->apArg[p->nUsed++]);
   26010 }
   26011 static char *getTextArg(PrintfArguments *p){
   26012   if( p->nArg<=p->nUsed ) return 0;
   26013   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
   26014 }
   26015 
   26016 
   26017 /*
   26018 ** On machines with a small stack size, you can redefine the
   26019 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
   26020 */
   26021 #ifndef SQLITE_PRINT_BUF_SIZE
   26022 # define SQLITE_PRINT_BUF_SIZE 70
   26023 #endif
   26024 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
   26025 
   26026 /*
   26027 ** Render a string given by "fmt" into the StrAccum object.
   26028 */
   26029 SQLITE_PRIVATE void sqlite3VXPrintf(
   26030   StrAccum *pAccum,          /* Accumulate results here */
   26031   const char *fmt,           /* Format string */
   26032   va_list ap                 /* arguments */
   26033 ){
   26034   int c;                     /* Next character in the format string */
   26035   char *bufpt;               /* Pointer to the conversion buffer */
   26036   int precision;             /* Precision of the current field */
   26037   int length;                /* Length of the field */
   26038   int idx;                   /* A general purpose loop counter */
   26039   int width;                 /* Width of the current field */
   26040   etByte flag_leftjustify;   /* True if "-" flag is present */
   26041   etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
   26042   etByte flag_alternateform; /* True if "#" flag is present */
   26043   etByte flag_altform2;      /* True if "!" flag is present */
   26044   etByte flag_zeropad;       /* True if field width constant starts with zero */
   26045   etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
   26046   etByte done;               /* Loop termination flag */
   26047   etByte cThousand;          /* Thousands separator for %d and %u */
   26048   etByte xtype = etINVALID;  /* Conversion paradigm */
   26049   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
   26050   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
   26051   sqlite_uint64 longvalue;   /* Value for integer types */
   26052   LONGDOUBLE_TYPE realvalue; /* Value for real types */
   26053   const et_info *infop;      /* Pointer to the appropriate info structure */
   26054   char *zOut;                /* Rendering buffer */
   26055   int nOut;                  /* Size of the rendering buffer */
   26056   char *zExtra = 0;          /* Malloced memory used by some conversion */
   26057 #ifndef SQLITE_OMIT_FLOATING_POINT
   26058   int  exp, e2;              /* exponent of real numbers */
   26059   int nsd;                   /* Number of significant digits returned */
   26060   double rounder;            /* Used for rounding floating point values */
   26061   etByte flag_dp;            /* True if decimal point should be shown */
   26062   etByte flag_rtz;           /* True if trailing zeros should be removed */
   26063 #endif
   26064   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
   26065   char buf[etBUFSIZE];       /* Conversion buffer */
   26066 
   26067   bufpt = 0;
   26068   if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
   26069     pArgList = va_arg(ap, PrintfArguments*);
   26070     bArgList = 1;
   26071   }else{
   26072     bArgList = 0;
   26073   }
   26074   for(; (c=(*fmt))!=0; ++fmt){
   26075     if( c!='%' ){
   26076       bufpt = (char *)fmt;
   26077 #if HAVE_STRCHRNUL
   26078       fmt = strchrnul(fmt, '%');
   26079 #else
   26080       do{ fmt++; }while( *fmt && *fmt != '%' );
   26081 #endif
   26082       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
   26083       if( *fmt==0 ) break;
   26084     }
   26085     if( (c=(*++fmt))==0 ){
   26086       sqlite3StrAccumAppend(pAccum, "%", 1);
   26087       break;
   26088     }
   26089     /* Find out what flags are present */
   26090     flag_leftjustify = flag_prefix = cThousand =
   26091      flag_alternateform = flag_altform2 = flag_zeropad = 0;
   26092     done = 0;
   26093     do{
   26094       switch( c ){
   26095         case '-':   flag_leftjustify = 1;     break;
   26096         case '+':   flag_prefix = '+';        break;
   26097         case ' ':   flag_prefix = ' ';        break;
   26098         case '#':   flag_alternateform = 1;   break;
   26099         case '!':   flag_altform2 = 1;        break;
   26100         case '0':   flag_zeropad = 1;         break;
   26101         case ',':   cThousand = ',';          break;
   26102         default:    done = 1;                 break;
   26103       }
   26104     }while( !done && (c=(*++fmt))!=0 );
   26105     /* Get the field width */
   26106     if( c=='*' ){
   26107       if( bArgList ){
   26108         width = (int)getIntArg(pArgList);
   26109       }else{
   26110         width = va_arg(ap,int);
   26111       }
   26112       if( width<0 ){
   26113         flag_leftjustify = 1;
   26114         width = width >= -2147483647 ? -width : 0;
   26115       }
   26116       c = *++fmt;
   26117     }else{
   26118       unsigned wx = 0;
   26119       while( c>='0' && c<='9' ){
   26120         wx = wx*10 + c - '0';
   26121         c = *++fmt;
   26122       }
   26123       testcase( wx>0x7fffffff );
   26124       width = wx & 0x7fffffff;
   26125     }
   26126     assert( width>=0 );
   26127 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
   26128     if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
   26129       width = SQLITE_PRINTF_PRECISION_LIMIT;
   26130     }
   26131 #endif
   26132 
   26133     /* Get the precision */
   26134     if( c=='.' ){
   26135       c = *++fmt;
   26136       if( c=='*' ){
   26137         if( bArgList ){
   26138           precision = (int)getIntArg(pArgList);
   26139         }else{
   26140           precision = va_arg(ap,int);
   26141         }
   26142         c = *++fmt;
   26143         if( precision<0 ){
   26144           precision = precision >= -2147483647 ? -precision : -1;
   26145         }
   26146       }else{
   26147         unsigned px = 0;
   26148         while( c>='0' && c<='9' ){
   26149           px = px*10 + c - '0';
   26150           c = *++fmt;
   26151         }
   26152         testcase( px>0x7fffffff );
   26153         precision = px & 0x7fffffff;
   26154       }
   26155     }else{
   26156       precision = -1;
   26157     }
   26158     assert( precision>=(-1) );
   26159 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
   26160     if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
   26161       precision = SQLITE_PRINTF_PRECISION_LIMIT;
   26162     }
   26163 #endif
   26164 
   26165 
   26166     /* Get the conversion type modifier */
   26167     if( c=='l' ){
   26168       flag_long = 1;
   26169       c = *++fmt;
   26170       if( c=='l' ){
   26171         flag_long = 2;
   26172         c = *++fmt;
   26173       }
   26174     }else{
   26175       flag_long = 0;
   26176     }
   26177     /* Fetch the info entry for the field */
   26178     infop = &fmtinfo[0];
   26179     xtype = etINVALID;
   26180     for(idx=0; idx<ArraySize(fmtinfo); idx++){
   26181       if( c==fmtinfo[idx].fmttype ){
   26182         infop = &fmtinfo[idx];
   26183         xtype = infop->type;
   26184         break;
   26185       }
   26186     }
   26187 
   26188     /*
   26189     ** At this point, variables are initialized as follows:
   26190     **
   26191     **   flag_alternateform          TRUE if a '#' is present.
   26192     **   flag_altform2               TRUE if a '!' is present.
   26193     **   flag_prefix                 '+' or ' ' or zero
   26194     **   flag_leftjustify            TRUE if a '-' is present or if the
   26195     **                               field width was negative.
   26196     **   flag_zeropad                TRUE if the width began with 0.
   26197     **   flag_long                   1 for "l", 2 for "ll"
   26198     **   width                       The specified field width.  This is
   26199     **                               always non-negative.  Zero is the default.
   26200     **   precision                   The specified precision.  The default
   26201     **                               is -1.
   26202     **   xtype                       The class of the conversion.
   26203     **   infop                       Pointer to the appropriate info struct.
   26204     */
   26205     switch( xtype ){
   26206       case etPOINTER:
   26207         flag_long = sizeof(char*)==sizeof(i64) ? 2 :
   26208                      sizeof(char*)==sizeof(long int) ? 1 : 0;
   26209         /* Fall through into the next case */
   26210       case etORDINAL:
   26211       case etRADIX:
   26212         cThousand = 0;
   26213         /* Fall through into the next case */
   26214       case etDECIMAL:
   26215         if( infop->flags & FLAG_SIGNED ){
   26216           i64 v;
   26217           if( bArgList ){
   26218             v = getIntArg(pArgList);
   26219           }else if( flag_long ){
   26220             if( flag_long==2 ){
   26221               v = va_arg(ap,i64) ;
   26222             }else{
   26223               v = va_arg(ap,long int);
   26224             }
   26225           }else{
   26226             v = va_arg(ap,int);
   26227           }
   26228           if( v<0 ){
   26229             if( v==SMALLEST_INT64 ){
   26230               longvalue = ((u64)1)<<63;
   26231             }else{
   26232               longvalue = -v;
   26233             }
   26234             prefix = '-';
   26235           }else{
   26236             longvalue = v;
   26237             prefix = flag_prefix;
   26238           }
   26239         }else{
   26240           if( bArgList ){
   26241             longvalue = (u64)getIntArg(pArgList);
   26242           }else if( flag_long ){
   26243             if( flag_long==2 ){
   26244               longvalue = va_arg(ap,u64);
   26245             }else{
   26246               longvalue = va_arg(ap,unsigned long int);
   26247             }
   26248           }else{
   26249             longvalue = va_arg(ap,unsigned int);
   26250           }
   26251           prefix = 0;
   26252         }
   26253         if( longvalue==0 ) flag_alternateform = 0;
   26254         if( flag_zeropad && precision<width-(prefix!=0) ){
   26255           precision = width-(prefix!=0);
   26256         }
   26257         if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
   26258           nOut = etBUFSIZE;
   26259           zOut = buf;
   26260         }else{
   26261           u64 n = (u64)precision + 10 + precision/3;
   26262           zOut = zExtra = sqlite3Malloc( n );
   26263           if( zOut==0 ){
   26264             setStrAccumError(pAccum, STRACCUM_NOMEM);
   26265             return;
   26266           }
   26267           nOut = (int)n;
   26268         }
   26269         bufpt = &zOut[nOut-1];
   26270         if( xtype==etORDINAL ){
   26271           static const char zOrd[] = "thstndrd";
   26272           int x = (int)(longvalue % 10);
   26273           if( x>=4 || (longvalue/10)%10==1 ){
   26274             x = 0;
   26275           }
   26276           *(--bufpt) = zOrd[x*2+1];
   26277           *(--bufpt) = zOrd[x*2];
   26278         }
   26279         {
   26280           const char *cset = &aDigits[infop->charset];
   26281           u8 base = infop->base;
   26282           do{                                           /* Convert to ascii */
   26283             *(--bufpt) = cset[longvalue%base];
   26284             longvalue = longvalue/base;
   26285           }while( longvalue>0 );
   26286         }
   26287         length = (int)(&zOut[nOut-1]-bufpt);
   26288         while( precision>length ){
   26289           *(--bufpt) = '0';                             /* Zero pad */
   26290           length++;
   26291         }
   26292         if( cThousand ){
   26293           int nn = (length - 1)/3;  /* Number of "," to insert */
   26294           int ix = (length - 1)%3 + 1;
   26295           bufpt -= nn;
   26296           for(idx=0; nn>0; idx++){
   26297             bufpt[idx] = bufpt[idx+nn];
   26298             ix--;
   26299             if( ix==0 ){
   26300               bufpt[++idx] = cThousand;
   26301               nn--;
   26302               ix = 3;
   26303             }
   26304           }
   26305         }
   26306         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
   26307         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
   26308           const char *pre;
   26309           char x;
   26310           pre = &aPrefix[infop->prefix];
   26311           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
   26312         }
   26313         length = (int)(&zOut[nOut-1]-bufpt);
   26314         break;
   26315       case etFLOAT:
   26316       case etEXP:
   26317       case etGENERIC:
   26318         if( bArgList ){
   26319           realvalue = getDoubleArg(pArgList);
   26320         }else{
   26321           realvalue = va_arg(ap,double);
   26322         }
   26323 #ifdef SQLITE_OMIT_FLOATING_POINT
   26324         length = 0;
   26325 #else
   26326         if( precision<0 ) precision = 6;         /* Set default precision */
   26327         if( realvalue<0.0 ){
   26328           realvalue = -realvalue;
   26329           prefix = '-';
   26330         }else{
   26331           prefix = flag_prefix;
   26332         }
   26333         if( xtype==etGENERIC && precision>0 ) precision--;
   26334         testcase( precision>0xfff );
   26335         for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
   26336         if( xtype==etFLOAT ) realvalue += rounder;
   26337         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
   26338         exp = 0;
   26339         if( sqlite3IsNaN((double)realvalue) ){
   26340           bufpt = "NaN";
   26341           length = 3;
   26342           break;
   26343         }
   26344         if( realvalue>0.0 ){
   26345           LONGDOUBLE_TYPE scale = 1.0;
   26346           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
   26347           while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
   26348           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
   26349           realvalue /= scale;
   26350           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
   26351           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
   26352           if( exp>350 ){
   26353             bufpt = buf;
   26354             buf[0] = prefix;
   26355             memcpy(buf+(prefix!=0),"Inf",4);
   26356             length = 3+(prefix!=0);
   26357             break;
   26358           }
   26359         }
   26360         bufpt = buf;
   26361         /*
   26362         ** If the field type is etGENERIC, then convert to either etEXP
   26363         ** or etFLOAT, as appropriate.
   26364         */
   26365         if( xtype!=etFLOAT ){
   26366           realvalue += rounder;
   26367           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
   26368         }
   26369         if( xtype==etGENERIC ){
   26370           flag_rtz = !flag_alternateform;
   26371           if( exp<-4 || exp>precision ){
   26372             xtype = etEXP;
   26373           }else{
   26374             precision = precision - exp;
   26375             xtype = etFLOAT;
   26376           }
   26377         }else{
   26378           flag_rtz = flag_altform2;
   26379         }
   26380         if( xtype==etEXP ){
   26381           e2 = 0;
   26382         }else{
   26383           e2 = exp;
   26384         }
   26385         if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
   26386           bufpt = zExtra
   26387               = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
   26388           if( bufpt==0 ){
   26389             setStrAccumError(pAccum, STRACCUM_NOMEM);
   26390             return;
   26391           }
   26392         }
   26393         zOut = bufpt;
   26394         nsd = 16 + flag_altform2*10;
   26395         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
   26396         /* The sign in front of the number */
   26397         if( prefix ){
   26398           *(bufpt++) = prefix;
   26399         }
   26400         /* Digits prior to the decimal point */
   26401         if( e2<0 ){
   26402           *(bufpt++) = '0';
   26403         }else{
   26404           for(; e2>=0; e2--){
   26405             *(bufpt++) = et_getdigit(&realvalue,&nsd);
   26406           }
   26407         }
   26408         /* The decimal point */
   26409         if( flag_dp ){
   26410           *(bufpt++) = '.';
   26411         }
   26412         /* "0" digits after the decimal point but before the first
   26413         ** significant digit of the number */
   26414         for(e2++; e2<0; precision--, e2++){
   26415           assert( precision>0 );
   26416           *(bufpt++) = '0';
   26417         }
   26418         /* Significant digits after the decimal point */
   26419         while( (precision--)>0 ){
   26420           *(bufpt++) = et_getdigit(&realvalue,&nsd);
   26421         }
   26422         /* Remove trailing zeros and the "." if no digits follow the "." */
   26423         if( flag_rtz && flag_dp ){
   26424           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
   26425           assert( bufpt>zOut );
   26426           if( bufpt[-1]=='.' ){
   26427             if( flag_altform2 ){
   26428               *(bufpt++) = '0';
   26429             }else{
   26430               *(--bufpt) = 0;
   26431             }
   26432           }
   26433         }
   26434         /* Add the "eNNN" suffix */
   26435         if( xtype==etEXP ){
   26436           *(bufpt++) = aDigits[infop->charset];
   26437           if( exp<0 ){
   26438             *(bufpt++) = '-'; exp = -exp;
   26439           }else{
   26440             *(bufpt++) = '+';
   26441           }
   26442           if( exp>=100 ){
   26443             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
   26444             exp %= 100;
   26445           }
   26446           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
   26447           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
   26448         }
   26449         *bufpt = 0;
   26450 
   26451         /* The converted number is in buf[] and zero terminated. Output it.
   26452         ** Note that the number is in the usual order, not reversed as with
   26453         ** integer conversions. */
   26454         length = (int)(bufpt-zOut);
   26455         bufpt = zOut;
   26456 
   26457         /* Special case:  Add leading zeros if the flag_zeropad flag is
   26458         ** set and we are not left justified */
   26459         if( flag_zeropad && !flag_leftjustify && length < width){
   26460           int i;
   26461           int nPad = width - length;
   26462           for(i=width; i>=nPad; i--){
   26463             bufpt[i] = bufpt[i-nPad];
   26464           }
   26465           i = prefix!=0;
   26466           while( nPad-- ) bufpt[i++] = '0';
   26467           length = width;
   26468         }
   26469 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
   26470         break;
   26471       case etSIZE:
   26472         if( !bArgList ){
   26473           *(va_arg(ap,int*)) = pAccum->nChar;
   26474         }
   26475         length = width = 0;
   26476         break;
   26477       case etPERCENT:
   26478         buf[0] = '%';
   26479         bufpt = buf;
   26480         length = 1;
   26481         break;
   26482       case etCHARX:
   26483         if( bArgList ){
   26484           bufpt = getTextArg(pArgList);
   26485           c = bufpt ? bufpt[0] : 0;
   26486         }else{
   26487           c = va_arg(ap,int);
   26488         }
   26489         if( precision>1 ){
   26490           width -= precision-1;
   26491           if( width>1 && !flag_leftjustify ){
   26492             sqlite3AppendChar(pAccum, width-1, ' ');
   26493             width = 0;
   26494           }
   26495           sqlite3AppendChar(pAccum, precision-1, c);
   26496         }
   26497         length = 1;
   26498         buf[0] = c;
   26499         bufpt = buf;
   26500         break;
   26501       case etSTRING:
   26502       case etDYNSTRING:
   26503         if( bArgList ){
   26504           bufpt = getTextArg(pArgList);
   26505           xtype = etSTRING;
   26506         }else{
   26507           bufpt = va_arg(ap,char*);
   26508         }
   26509         if( bufpt==0 ){
   26510           bufpt = "";
   26511         }else if( xtype==etDYNSTRING ){
   26512           zExtra = bufpt;
   26513         }
   26514         if( precision>=0 ){
   26515           for(length=0; length<precision && bufpt[length]; length++){}
   26516         }else{
   26517           length = 0x7fffffff & (int)strlen(bufpt);
   26518         }
   26519         break;
   26520       case etSQLESCAPE:           /* Escape ' characters */
   26521       case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
   26522       case etSQLESCAPE3: {        /* Escape " characters */
   26523         int i, j, k, n, isnull;
   26524         int needQuote;
   26525         char ch;
   26526         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
   26527         char *escarg;
   26528 
   26529         if( bArgList ){
   26530           escarg = getTextArg(pArgList);
   26531         }else{
   26532           escarg = va_arg(ap,char*);
   26533         }
   26534         isnull = escarg==0;
   26535         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
   26536         k = precision;
   26537         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
   26538           if( ch==q )  n++;
   26539         }
   26540         needQuote = !isnull && xtype==etSQLESCAPE2;
   26541         n += i + 3;
   26542         if( n>etBUFSIZE ){
   26543           bufpt = zExtra = sqlite3Malloc( n );
   26544           if( bufpt==0 ){
   26545             setStrAccumError(pAccum, STRACCUM_NOMEM);
   26546             return;
   26547           }
   26548         }else{
   26549           bufpt = buf;
   26550         }
   26551         j = 0;
   26552         if( needQuote ) bufpt[j++] = q;
   26553         k = i;
   26554         for(i=0; i<k; i++){
   26555           bufpt[j++] = ch = escarg[i];
   26556           if( ch==q ) bufpt[j++] = ch;
   26557         }
   26558         if( needQuote ) bufpt[j++] = q;
   26559         bufpt[j] = 0;
   26560         length = j;
   26561         /* The precision in %q and %Q means how many input characters to
   26562         ** consume, not the length of the output...
   26563         ** if( precision>=0 && precision<length ) length = precision; */
   26564         break;
   26565       }
   26566       case etTOKEN: {
   26567         Token *pToken;
   26568         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
   26569         pToken = va_arg(ap, Token*);
   26570         assert( bArgList==0 );
   26571         if( pToken && pToken->n ){
   26572           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
   26573         }
   26574         length = width = 0;
   26575         break;
   26576       }
   26577       case etSRCLIST: {
   26578         SrcList *pSrc;
   26579         int k;
   26580         struct SrcList_item *pItem;
   26581         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
   26582         pSrc = va_arg(ap, SrcList*);
   26583         k = va_arg(ap, int);
   26584         pItem = &pSrc->a[k];
   26585         assert( bArgList==0 );
   26586         assert( k>=0 && k<pSrc->nSrc );
   26587         if( pItem->zDatabase ){
   26588           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
   26589           sqlite3StrAccumAppend(pAccum, ".", 1);
   26590         }
   26591         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
   26592         length = width = 0;
   26593         break;
   26594       }
   26595       default: {
   26596         assert( xtype==etINVALID );
   26597         return;
   26598       }
   26599     }/* End switch over the format type */
   26600     /*
   26601     ** The text of the conversion is pointed to by "bufpt" and is
   26602     ** "length" characters long.  The field width is "width".  Do
   26603     ** the output.
   26604     */
   26605     width -= length;
   26606     if( width>0 ){
   26607       if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
   26608       sqlite3StrAccumAppend(pAccum, bufpt, length);
   26609       if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
   26610     }else{
   26611       sqlite3StrAccumAppend(pAccum, bufpt, length);
   26612     }
   26613 
   26614     if( zExtra ){
   26615       sqlite3DbFree(pAccum->db, zExtra);
   26616       zExtra = 0;
   26617     }
   26618   }/* End for loop over the format string */
   26619 } /* End of function */
   26620 
   26621 /*
   26622 ** Enlarge the memory allocation on a StrAccum object so that it is
   26623 ** able to accept at least N more bytes of text.
   26624 **
   26625 ** Return the number of bytes of text that StrAccum is able to accept
   26626 ** after the attempted enlargement.  The value returned might be zero.
   26627 */
   26628 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
   26629   char *zNew;
   26630   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
   26631   if( p->accError ){
   26632     testcase(p->accError==STRACCUM_TOOBIG);
   26633     testcase(p->accError==STRACCUM_NOMEM);
   26634     return 0;
   26635   }
   26636   if( p->mxAlloc==0 ){
   26637     N = p->nAlloc - p->nChar - 1;
   26638     setStrAccumError(p, STRACCUM_TOOBIG);
   26639     return N;
   26640   }else{
   26641     char *zOld = isMalloced(p) ? p->zText : 0;
   26642     i64 szNew = p->nChar;
   26643     szNew += N + 1;
   26644     if( szNew+p->nChar<=p->mxAlloc ){
   26645       /* Force exponential buffer size growth as long as it does not overflow,
   26646       ** to avoid having to call this routine too often */
   26647       szNew += p->nChar;
   26648     }
   26649     if( szNew > p->mxAlloc ){
   26650       sqlite3StrAccumReset(p);
   26651       setStrAccumError(p, STRACCUM_TOOBIG);
   26652       return 0;
   26653     }else{
   26654       p->nAlloc = (int)szNew;
   26655     }
   26656     if( p->db ){
   26657       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
   26658     }else{
   26659       zNew = sqlite3_realloc64(zOld, p->nAlloc);
   26660     }
   26661     if( zNew ){
   26662       assert( p->zText!=0 || p->nChar==0 );
   26663       if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
   26664       p->zText = zNew;
   26665       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
   26666       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
   26667     }else{
   26668       sqlite3StrAccumReset(p);
   26669       setStrAccumError(p, STRACCUM_NOMEM);
   26670       return 0;
   26671     }
   26672   }
   26673   return N;
   26674 }
   26675 
   26676 /*
   26677 ** Append N copies of character c to the given string buffer.
   26678 */
   26679 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
   26680   testcase( p->nChar + (i64)N > 0x7fffffff );
   26681   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
   26682     return;
   26683   }
   26684   while( (N--)>0 ) p->zText[p->nChar++] = c;
   26685 }
   26686 
   26687 /*
   26688 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
   26689 ** So enlarge if first, then do the append.
   26690 **
   26691 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
   26692 ** work (enlarging the buffer) using tail recursion, so that the
   26693 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
   26694 */
   26695 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
   26696   N = sqlite3StrAccumEnlarge(p, N);
   26697   if( N>0 ){
   26698     memcpy(&p->zText[p->nChar], z, N);
   26699     p->nChar += N;
   26700   }
   26701 }
   26702 
   26703 /*
   26704 ** Append N bytes of text from z to the StrAccum object.  Increase the
   26705 ** size of the memory allocation for StrAccum if necessary.
   26706 */
   26707 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
   26708   assert( z!=0 || N==0 );
   26709   assert( p->zText!=0 || p->nChar==0 || p->accError );
   26710   assert( N>=0 );
   26711   assert( p->accError==0 || p->nAlloc==0 );
   26712   if( p->nChar+N >= p->nAlloc ){
   26713     enlargeAndAppend(p,z,N);
   26714   }else if( N ){
   26715     assert( p->zText );
   26716     p->nChar += N;
   26717     memcpy(&p->zText[p->nChar-N], z, N);
   26718   }
   26719 }
   26720 
   26721 /*
   26722 ** Append the complete text of zero-terminated string z[] to the p string.
   26723 */
   26724 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
   26725   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
   26726 }
   26727 
   26728 
   26729 /*
   26730 ** Finish off a string by making sure it is zero-terminated.
   26731 ** Return a pointer to the resulting string.  Return a NULL
   26732 ** pointer if any kind of error was encountered.
   26733 */
   26734 static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
   26735   char *zText;
   26736   assert( p->mxAlloc>0 && !isMalloced(p) );
   26737   zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
   26738   if( zText ){
   26739     memcpy(zText, p->zText, p->nChar+1);
   26740     p->printfFlags |= SQLITE_PRINTF_MALLOCED;
   26741   }else{
   26742     setStrAccumError(p, STRACCUM_NOMEM);
   26743   }
   26744   p->zText = zText;
   26745   return zText;
   26746 }
   26747 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
   26748   if( p->zText ){
   26749     p->zText[p->nChar] = 0;
   26750     if( p->mxAlloc>0 && !isMalloced(p) ){
   26751       return strAccumFinishRealloc(p);
   26752     }
   26753   }
   26754   return p->zText;
   26755 }
   26756 
   26757 /*
   26758 ** Reset an StrAccum string.  Reclaim all malloced memory.
   26759 */
   26760 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
   26761   if( isMalloced(p) ){
   26762     sqlite3DbFree(p->db, p->zText);
   26763     p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
   26764   }
   26765   p->zText = 0;
   26766 }
   26767 
   26768 /*
   26769 ** Initialize a string accumulator.
   26770 **
   26771 ** p:     The accumulator to be initialized.
   26772 ** db:    Pointer to a database connection.  May be NULL.  Lookaside
   26773 **        memory is used if not NULL. db->mallocFailed is set appropriately
   26774 **        when not NULL.
   26775 ** zBase: An initial buffer.  May be NULL in which case the initial buffer
   26776 **        is malloced.
   26777 ** n:     Size of zBase in bytes.  If total space requirements never exceed
   26778 **        n then no memory allocations ever occur.
   26779 ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
   26780 **        allocations will ever occur.
   26781 */
   26782 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
   26783   p->zText = zBase;
   26784   p->db = db;
   26785   p->nAlloc = n;
   26786   p->mxAlloc = mx;
   26787   p->nChar = 0;
   26788   p->accError = 0;
   26789   p->printfFlags = 0;
   26790 }
   26791 
   26792 /*
   26793 ** Print into memory obtained from sqliteMalloc().  Use the internal
   26794 ** %-conversion extensions.
   26795 */
   26796 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
   26797   char *z;
   26798   char zBase[SQLITE_PRINT_BUF_SIZE];
   26799   StrAccum acc;
   26800   assert( db!=0 );
   26801   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
   26802                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   26803   acc.printfFlags = SQLITE_PRINTF_INTERNAL;
   26804   sqlite3VXPrintf(&acc, zFormat, ap);
   26805   z = sqlite3StrAccumFinish(&acc);
   26806   if( acc.accError==STRACCUM_NOMEM ){
   26807     sqlite3OomFault(db);
   26808   }
   26809   return z;
   26810 }
   26811 
   26812 /*
   26813 ** Print into memory obtained from sqliteMalloc().  Use the internal
   26814 ** %-conversion extensions.
   26815 */
   26816 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
   26817   va_list ap;
   26818   char *z;
   26819   va_start(ap, zFormat);
   26820   z = sqlite3VMPrintf(db, zFormat, ap);
   26821   va_end(ap);
   26822   return z;
   26823 }
   26824 
   26825 /*
   26826 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
   26827 ** %-conversion extensions.
   26828 */
   26829 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
   26830   char *z;
   26831   char zBase[SQLITE_PRINT_BUF_SIZE];
   26832   StrAccum acc;
   26833 
   26834 #ifdef SQLITE_ENABLE_API_ARMOR
   26835   if( zFormat==0 ){
   26836     (void)SQLITE_MISUSE_BKPT;
   26837     return 0;
   26838   }
   26839 #endif
   26840 #ifndef SQLITE_OMIT_AUTOINIT
   26841   if( sqlite3_initialize() ) return 0;
   26842 #endif
   26843   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
   26844   sqlite3VXPrintf(&acc, zFormat, ap);
   26845   z = sqlite3StrAccumFinish(&acc);
   26846   return z;
   26847 }
   26848 
   26849 /*
   26850 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
   26851 ** %-conversion extensions.
   26852 */
   26853 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
   26854   va_list ap;
   26855   char *z;
   26856 #ifndef SQLITE_OMIT_AUTOINIT
   26857   if( sqlite3_initialize() ) return 0;
   26858 #endif
   26859   va_start(ap, zFormat);
   26860   z = sqlite3_vmprintf(zFormat, ap);
   26861   va_end(ap);
   26862   return z;
   26863 }
   26864 
   26865 /*
   26866 ** sqlite3_snprintf() works like snprintf() except that it ignores the
   26867 ** current locale settings.  This is important for SQLite because we
   26868 ** are not able to use a "," as the decimal point in place of "." as
   26869 ** specified by some locales.
   26870 **
   26871 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
   26872 ** from the snprintf() standard.  Unfortunately, it is too late to change
   26873 ** this without breaking compatibility, so we just have to live with the
   26874 ** mistake.
   26875 **
   26876 ** sqlite3_vsnprintf() is the varargs version.
   26877 */
   26878 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
   26879   StrAccum acc;
   26880   if( n<=0 ) return zBuf;
   26881 #ifdef SQLITE_ENABLE_API_ARMOR
   26882   if( zBuf==0 || zFormat==0 ) {
   26883     (void)SQLITE_MISUSE_BKPT;
   26884     if( zBuf ) zBuf[0] = 0;
   26885     return zBuf;
   26886   }
   26887 #endif
   26888   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
   26889   sqlite3VXPrintf(&acc, zFormat, ap);
   26890   zBuf[acc.nChar] = 0;
   26891   return zBuf;
   26892 }
   26893 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
   26894   char *z;
   26895   va_list ap;
   26896   va_start(ap,zFormat);
   26897   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
   26898   va_end(ap);
   26899   return z;
   26900 }
   26901 
   26902 /*
   26903 ** This is the routine that actually formats the sqlite3_log() message.
   26904 ** We house it in a separate routine from sqlite3_log() to avoid using
   26905 ** stack space on small-stack systems when logging is disabled.
   26906 **
   26907 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
   26908 ** allocate memory because it might be called while the memory allocator
   26909 ** mutex is held.
   26910 **
   26911 ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
   26912 ** certain format characters (%q) or for very large precisions or widths.
   26913 ** Care must be taken that any sqlite3_log() calls that occur while the
   26914 ** memory mutex is held do not use these mechanisms.
   26915 */
   26916 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
   26917   StrAccum acc;                          /* String accumulator */
   26918   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
   26919 
   26920   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
   26921   sqlite3VXPrintf(&acc, zFormat, ap);
   26922   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
   26923                            sqlite3StrAccumFinish(&acc));
   26924 }
   26925 
   26926 /*
   26927 ** Format and write a message to the log if logging is enabled.
   26928 */
   26929 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
   26930   va_list ap;                             /* Vararg list */
   26931   if( sqlite3GlobalConfig.xLog ){
   26932     va_start(ap, zFormat);
   26933     renderLogMsg(iErrCode, zFormat, ap);
   26934     va_end(ap);
   26935   }
   26936 }
   26937 
   26938 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
   26939 /*
   26940 ** A version of printf() that understands %lld.  Used for debugging.
   26941 ** The printf() built into some versions of windows does not understand %lld
   26942 ** and segfaults if you give it a long long int.
   26943 */
   26944 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
   26945   va_list ap;
   26946   StrAccum acc;
   26947   char zBuf[500];
   26948   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
   26949   va_start(ap,zFormat);
   26950   sqlite3VXPrintf(&acc, zFormat, ap);
   26951   va_end(ap);
   26952   sqlite3StrAccumFinish(&acc);
   26953 #ifdef SQLITE_OS_TRACE_PROC
   26954   {
   26955     extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
   26956     SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
   26957   }
   26958 #else
   26959   fprintf(stdout,"%s", zBuf);
   26960   fflush(stdout);
   26961 #endif
   26962 }
   26963 #endif
   26964 
   26965 
   26966 /*
   26967 ** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
   26968 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
   26969 */
   26970 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
   26971   va_list ap;
   26972   va_start(ap,zFormat);
   26973   sqlite3VXPrintf(p, zFormat, ap);
   26974   va_end(ap);
   26975 }
   26976 
   26977 /************** End of printf.c **********************************************/
   26978 /************** Begin file treeview.c ****************************************/
   26979 /*
   26980 ** 2015-06-08
   26981 **
   26982 ** The author disclaims copyright to this source code.  In place of
   26983 ** a legal notice, here is a blessing:
   26984 **
   26985 **    May you do good and not evil.
   26986 **    May you find forgiveness for yourself and forgive others.
   26987 **    May you share freely, never taking more than you give.
   26988 **
   26989 *************************************************************************
   26990 **
   26991 ** This file contains C code to implement the TreeView debugging routines.
   26992 ** These routines print a parse tree to standard output for debugging and
   26993 ** analysis.
   26994 **
   26995 ** The interfaces in this file is only available when compiling
   26996 ** with SQLITE_DEBUG.
   26997 */
   26998 /* #include "sqliteInt.h" */
   26999 #ifdef SQLITE_DEBUG
   27000 
   27001 /*
   27002 ** Add a new subitem to the tree.  The moreToFollow flag indicates that this
   27003 ** is not the last item in the tree.
   27004 */
   27005 static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
   27006   if( p==0 ){
   27007     p = sqlite3_malloc64( sizeof(*p) );
   27008     if( p==0 ) return 0;
   27009     memset(p, 0, sizeof(*p));
   27010   }else{
   27011     p->iLevel++;
   27012   }
   27013   assert( moreToFollow==0 || moreToFollow==1 );
   27014   if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
   27015   return p;
   27016 }
   27017 
   27018 /*
   27019 ** Finished with one layer of the tree
   27020 */
   27021 static void sqlite3TreeViewPop(TreeView *p){
   27022   if( p==0 ) return;
   27023   p->iLevel--;
   27024   if( p->iLevel<0 ) sqlite3_free(p);
   27025 }
   27026 
   27027 /*
   27028 ** Generate a single line of output for the tree, with a prefix that contains
   27029 ** all the appropriate tree lines
   27030 */
   27031 static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
   27032   va_list ap;
   27033   int i;
   27034   StrAccum acc;
   27035   char zBuf[500];
   27036   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
   27037   if( p ){
   27038     for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
   27039       sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
   27040     }
   27041     sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
   27042   }
   27043   va_start(ap, zFormat);
   27044   sqlite3VXPrintf(&acc, zFormat, ap);
   27045   va_end(ap);
   27046   assert( acc.nChar>0 );
   27047   if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
   27048   sqlite3StrAccumFinish(&acc);
   27049   fprintf(stdout,"%s", zBuf);
   27050   fflush(stdout);
   27051 }
   27052 
   27053 /*
   27054 ** Shorthand for starting a new tree item that consists of a single label
   27055 */
   27056 static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
   27057   p = sqlite3TreeViewPush(p, moreFollows);
   27058   sqlite3TreeViewLine(p, "%s", zLabel);
   27059 }
   27060 
   27061 /*
   27062 ** Generate a human-readable description of a WITH clause.
   27063 */
   27064 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
   27065   int i;
   27066   if( pWith==0 ) return;
   27067   if( pWith->nCte==0 ) return;
   27068   if( pWith->pOuter ){
   27069     sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
   27070   }else{
   27071     sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
   27072   }
   27073   if( pWith->nCte>0 ){
   27074     pView = sqlite3TreeViewPush(pView, 1);
   27075     for(i=0; i<pWith->nCte; i++){
   27076       StrAccum x;
   27077       char zLine[1000];
   27078       const struct Cte *pCte = &pWith->a[i];
   27079       sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
   27080       sqlite3XPrintf(&x, "%s", pCte->zName);
   27081       if( pCte->pCols && pCte->pCols->nExpr>0 ){
   27082         char cSep = '(';
   27083         int j;
   27084         for(j=0; j<pCte->pCols->nExpr; j++){
   27085           sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
   27086           cSep = ',';
   27087         }
   27088         sqlite3XPrintf(&x, ")");
   27089       }
   27090       sqlite3XPrintf(&x, " AS");
   27091       sqlite3StrAccumFinish(&x);
   27092       sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
   27093       sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
   27094       sqlite3TreeViewPop(pView);
   27095     }
   27096     sqlite3TreeViewPop(pView);
   27097   }
   27098 }
   27099 
   27100 
   27101 /*
   27102 ** Generate a human-readable description of a Select object.
   27103 */
   27104 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
   27105   int n = 0;
   27106   int cnt = 0;
   27107   if( p==0 ){
   27108     sqlite3TreeViewLine(pView, "nil-SELECT");
   27109     return;
   27110   }
   27111   pView = sqlite3TreeViewPush(pView, moreToFollow);
   27112   if( p->pWith ){
   27113     sqlite3TreeViewWith(pView, p->pWith, 1);
   27114     cnt = 1;
   27115     sqlite3TreeViewPush(pView, 1);
   27116   }
   27117   do{
   27118     sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
   27119       ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
   27120       ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
   27121       (int)p->nSelectRow
   27122     );
   27123     if( cnt++ ) sqlite3TreeViewPop(pView);
   27124     if( p->pPrior ){
   27125       n = 1000;
   27126     }else{
   27127       n = 0;
   27128       if( p->pSrc && p->pSrc->nSrc ) n++;
   27129       if( p->pWhere ) n++;
   27130       if( p->pGroupBy ) n++;
   27131       if( p->pHaving ) n++;
   27132       if( p->pOrderBy ) n++;
   27133       if( p->pLimit ) n++;
   27134     }
   27135     sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
   27136     if( p->pSrc && p->pSrc->nSrc ){
   27137       int i;
   27138       pView = sqlite3TreeViewPush(pView, (n--)>0);
   27139       sqlite3TreeViewLine(pView, "FROM");
   27140       for(i=0; i<p->pSrc->nSrc; i++){
   27141         struct SrcList_item *pItem = &p->pSrc->a[i];
   27142         StrAccum x;
   27143         char zLine[100];
   27144         sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
   27145         sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
   27146         if( pItem->zDatabase ){
   27147           sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
   27148         }else if( pItem->zName ){
   27149           sqlite3XPrintf(&x, " %s", pItem->zName);
   27150         }
   27151         if( pItem->pTab ){
   27152           sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
   27153         }
   27154         if( pItem->zAlias ){
   27155           sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
   27156         }
   27157         if( pItem->fg.jointype & JT_LEFT ){
   27158           sqlite3XPrintf(&x, " LEFT-JOIN");
   27159         }
   27160         sqlite3StrAccumFinish(&x);
   27161         sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
   27162         if( pItem->pSelect ){
   27163           sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
   27164         }
   27165         if( pItem->fg.isTabFunc ){
   27166           sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
   27167         }
   27168         sqlite3TreeViewPop(pView);
   27169       }
   27170       sqlite3TreeViewPop(pView);
   27171     }
   27172     if( p->pWhere ){
   27173       sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
   27174       sqlite3TreeViewExpr(pView, p->pWhere, 0);
   27175       sqlite3TreeViewPop(pView);
   27176     }
   27177     if( p->pGroupBy ){
   27178       sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
   27179     }
   27180     if( p->pHaving ){
   27181       sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
   27182       sqlite3TreeViewExpr(pView, p->pHaving, 0);
   27183       sqlite3TreeViewPop(pView);
   27184     }
   27185     if( p->pOrderBy ){
   27186       sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
   27187     }
   27188     if( p->pLimit ){
   27189       sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
   27190       sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
   27191       if( p->pLimit->pRight ){
   27192         sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
   27193         sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
   27194         sqlite3TreeViewPop(pView);
   27195       }
   27196       sqlite3TreeViewPop(pView);
   27197     }
   27198     if( p->pPrior ){
   27199       const char *zOp = "UNION";
   27200       switch( p->op ){
   27201         case TK_ALL:         zOp = "UNION ALL";  break;
   27202         case TK_INTERSECT:   zOp = "INTERSECT";  break;
   27203         case TK_EXCEPT:      zOp = "EXCEPT";     break;
   27204       }
   27205       sqlite3TreeViewItem(pView, zOp, 1);
   27206     }
   27207     p = p->pPrior;
   27208   }while( p!=0 );
   27209   sqlite3TreeViewPop(pView);
   27210 }
   27211 
   27212 /*
   27213 ** Generate a human-readable explanation of an expression tree.
   27214 */
   27215 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
   27216   const char *zBinOp = 0;   /* Binary operator */
   27217   const char *zUniOp = 0;   /* Unary operator */
   27218   char zFlgs[60];
   27219   pView = sqlite3TreeViewPush(pView, moreToFollow);
   27220   if( pExpr==0 ){
   27221     sqlite3TreeViewLine(pView, "nil");
   27222     sqlite3TreeViewPop(pView);
   27223     return;
   27224   }
   27225   if( pExpr->flags ){
   27226     if( ExprHasProperty(pExpr, EP_FromJoin) ){
   27227       sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x iRJT=%d",
   27228                        pExpr->flags, pExpr->iRightJoinTable);
   27229     }else{
   27230       sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
   27231     }
   27232   }else{
   27233     zFlgs[0] = 0;
   27234   }
   27235   switch( pExpr->op ){
   27236     case TK_AGG_COLUMN: {
   27237       sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
   27238             pExpr->iTable, pExpr->iColumn, zFlgs);
   27239       break;
   27240     }
   27241     case TK_COLUMN: {
   27242       if( pExpr->iTable<0 ){
   27243         /* This only happens when coding check constraints */
   27244         sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
   27245       }else{
   27246         sqlite3TreeViewLine(pView, "{%d:%d}%s",
   27247                              pExpr->iTable, pExpr->iColumn, zFlgs);
   27248       }
   27249       break;
   27250     }
   27251     case TK_INTEGER: {
   27252       if( pExpr->flags & EP_IntValue ){
   27253         sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
   27254       }else{
   27255         sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
   27256       }
   27257       break;
   27258     }
   27259 #ifndef SQLITE_OMIT_FLOATING_POINT
   27260     case TK_FLOAT: {
   27261       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
   27262       break;
   27263     }
   27264 #endif
   27265     case TK_STRING: {
   27266       sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
   27267       break;
   27268     }
   27269     case TK_NULL: {
   27270       sqlite3TreeViewLine(pView,"NULL");
   27271       break;
   27272     }
   27273 #ifndef SQLITE_OMIT_BLOB_LITERAL
   27274     case TK_BLOB: {
   27275       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
   27276       break;
   27277     }
   27278 #endif
   27279     case TK_VARIABLE: {
   27280       sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
   27281                           pExpr->u.zToken, pExpr->iColumn);
   27282       break;
   27283     }
   27284     case TK_REGISTER: {
   27285       sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
   27286       break;
   27287     }
   27288     case TK_ID: {
   27289       sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
   27290       break;
   27291     }
   27292 #ifndef SQLITE_OMIT_CAST
   27293     case TK_CAST: {
   27294       /* Expressions of the form:   CAST(pLeft AS token) */
   27295       sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
   27296       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
   27297       break;
   27298     }
   27299 #endif /* SQLITE_OMIT_CAST */
   27300     case TK_LT:      zBinOp = "LT";     break;
   27301     case TK_LE:      zBinOp = "LE";     break;
   27302     case TK_GT:      zBinOp = "GT";     break;
   27303     case TK_GE:      zBinOp = "GE";     break;
   27304     case TK_NE:      zBinOp = "NE";     break;
   27305     case TK_EQ:      zBinOp = "EQ";     break;
   27306     case TK_IS:      zBinOp = "IS";     break;
   27307     case TK_ISNOT:   zBinOp = "ISNOT";  break;
   27308     case TK_AND:     zBinOp = "AND";    break;
   27309     case TK_OR:      zBinOp = "OR";     break;
   27310     case TK_PLUS:    zBinOp = "ADD";    break;
   27311     case TK_STAR:    zBinOp = "MUL";    break;
   27312     case TK_MINUS:   zBinOp = "SUB";    break;
   27313     case TK_REM:     zBinOp = "REM";    break;
   27314     case TK_BITAND:  zBinOp = "BITAND"; break;
   27315     case TK_BITOR:   zBinOp = "BITOR";  break;
   27316     case TK_SLASH:   zBinOp = "DIV";    break;
   27317     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
   27318     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
   27319     case TK_CONCAT:  zBinOp = "CONCAT"; break;
   27320     case TK_DOT:     zBinOp = "DOT";    break;
   27321 
   27322     case TK_UMINUS:  zUniOp = "UMINUS"; break;
   27323     case TK_UPLUS:   zUniOp = "UPLUS";  break;
   27324     case TK_BITNOT:  zUniOp = "BITNOT"; break;
   27325     case TK_NOT:     zUniOp = "NOT";    break;
   27326     case TK_ISNULL:  zUniOp = "ISNULL"; break;
   27327     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
   27328 
   27329     case TK_SPAN: {
   27330       sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
   27331       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
   27332       break;
   27333     }
   27334 
   27335     case TK_COLLATE: {
   27336       sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
   27337       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
   27338       break;
   27339     }
   27340 
   27341     case TK_AGG_FUNCTION:
   27342     case TK_FUNCTION: {
   27343       ExprList *pFarg;       /* List of function arguments */
   27344       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
   27345         pFarg = 0;
   27346       }else{
   27347         pFarg = pExpr->x.pList;
   27348       }
   27349       if( pExpr->op==TK_AGG_FUNCTION ){
   27350         sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
   27351                              pExpr->op2, pExpr->u.zToken);
   27352       }else{
   27353         sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
   27354       }
   27355       if( pFarg ){
   27356         sqlite3TreeViewExprList(pView, pFarg, 0, 0);
   27357       }
   27358       break;
   27359     }
   27360 #ifndef SQLITE_OMIT_SUBQUERY
   27361     case TK_EXISTS: {
   27362       sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
   27363       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
   27364       break;
   27365     }
   27366     case TK_SELECT: {
   27367       sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
   27368       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
   27369       break;
   27370     }
   27371     case TK_IN: {
   27372       sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
   27373       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
   27374       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   27375         sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
   27376       }else{
   27377         sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
   27378       }
   27379       break;
   27380     }
   27381 #endif /* SQLITE_OMIT_SUBQUERY */
   27382 
   27383     /*
   27384     **    x BETWEEN y AND z
   27385     **
   27386     ** This is equivalent to
   27387     **
   27388     **    x>=y AND x<=z
   27389     **
   27390     ** X is stored in pExpr->pLeft.
   27391     ** Y is stored in pExpr->pList->a[0].pExpr.
   27392     ** Z is stored in pExpr->pList->a[1].pExpr.
   27393     */
   27394     case TK_BETWEEN: {
   27395       Expr *pX = pExpr->pLeft;
   27396       Expr *pY = pExpr->x.pList->a[0].pExpr;
   27397       Expr *pZ = pExpr->x.pList->a[1].pExpr;
   27398       sqlite3TreeViewLine(pView, "BETWEEN");
   27399       sqlite3TreeViewExpr(pView, pX, 1);
   27400       sqlite3TreeViewExpr(pView, pY, 1);
   27401       sqlite3TreeViewExpr(pView, pZ, 0);
   27402       break;
   27403     }
   27404     case TK_TRIGGER: {
   27405       /* If the opcode is TK_TRIGGER, then the expression is a reference
   27406       ** to a column in the new.* or old.* pseudo-tables available to
   27407       ** trigger programs. In this case Expr.iTable is set to 1 for the
   27408       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   27409       ** is set to the column of the pseudo-table to read, or to -1 to
   27410       ** read the rowid field.
   27411       */
   27412       sqlite3TreeViewLine(pView, "%s(%d)",
   27413           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
   27414       break;
   27415     }
   27416     case TK_CASE: {
   27417       sqlite3TreeViewLine(pView, "CASE");
   27418       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
   27419       sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
   27420       break;
   27421     }
   27422 #ifndef SQLITE_OMIT_TRIGGER
   27423     case TK_RAISE: {
   27424       const char *zType = "unk";
   27425       switch( pExpr->affinity ){
   27426         case OE_Rollback:   zType = "rollback";  break;
   27427         case OE_Abort:      zType = "abort";     break;
   27428         case OE_Fail:       zType = "fail";      break;
   27429         case OE_Ignore:     zType = "ignore";    break;
   27430       }
   27431       sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
   27432       break;
   27433     }
   27434 #endif
   27435     case TK_MATCH: {
   27436       sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
   27437                           pExpr->iTable, pExpr->iColumn, zFlgs);
   27438       sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
   27439       break;
   27440     }
   27441     case TK_VECTOR: {
   27442       sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
   27443       break;
   27444     }
   27445     case TK_SELECT_COLUMN: {
   27446       sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
   27447       sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
   27448       break;
   27449     }
   27450     case TK_IF_NULL_ROW: {
   27451       sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
   27452       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
   27453       break;
   27454     }
   27455     default: {
   27456       sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
   27457       break;
   27458     }
   27459   }
   27460   if( zBinOp ){
   27461     sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
   27462     sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
   27463     sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
   27464   }else if( zUniOp ){
   27465     sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
   27466     sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
   27467   }
   27468   sqlite3TreeViewPop(pView);
   27469 }
   27470 
   27471 
   27472 /*
   27473 ** Generate a human-readable explanation of an expression list.
   27474 */
   27475 SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
   27476   TreeView *pView,
   27477   const ExprList *pList,
   27478   const char *zLabel
   27479 ){
   27480   if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
   27481   if( pList==0 ){
   27482     sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
   27483   }else{
   27484     int i;
   27485     sqlite3TreeViewLine(pView, "%s", zLabel);
   27486     for(i=0; i<pList->nExpr; i++){
   27487       int j = pList->a[i].u.x.iOrderByCol;
   27488       char *zName = pList->a[i].zName;
   27489       if( j || zName ){
   27490         sqlite3TreeViewPush(pView, 0);
   27491       }
   27492       if( zName ){
   27493         sqlite3TreeViewLine(pView, "AS %s", zName);
   27494       }
   27495       if( j ){
   27496         sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
   27497       }
   27498       sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
   27499       if( j || zName ){
   27500         sqlite3TreeViewPop(pView);
   27501       }
   27502     }
   27503   }
   27504 }
   27505 SQLITE_PRIVATE void sqlite3TreeViewExprList(
   27506   TreeView *pView,
   27507   const ExprList *pList,
   27508   u8 moreToFollow,
   27509   const char *zLabel
   27510 ){
   27511   pView = sqlite3TreeViewPush(pView, moreToFollow);
   27512   sqlite3TreeViewBareExprList(pView, pList, zLabel);
   27513   sqlite3TreeViewPop(pView);
   27514 }
   27515 
   27516 #endif /* SQLITE_DEBUG */
   27517 
   27518 /************** End of treeview.c ********************************************/
   27519 /************** Begin file random.c ******************************************/
   27520 /*
   27521 ** 2001 September 15
   27522 **
   27523 ** The author disclaims copyright to this source code.  In place of
   27524 ** a legal notice, here is a blessing:
   27525 **
   27526 **    May you do good and not evil.
   27527 **    May you find forgiveness for yourself and forgive others.
   27528 **    May you share freely, never taking more than you give.
   27529 **
   27530 *************************************************************************
   27531 ** This file contains code to implement a pseudo-random number
   27532 ** generator (PRNG) for SQLite.
   27533 **
   27534 ** Random numbers are used by some of the database backends in order
   27535 ** to generate random integer keys for tables or random filenames.
   27536 */
   27537 /* #include "sqliteInt.h" */
   27538 
   27539 
   27540 /* All threads share a single random number generator.
   27541 ** This structure is the current state of the generator.
   27542 */
   27543 static SQLITE_WSD struct sqlite3PrngType {
   27544   unsigned char isInit;          /* True if initialized */
   27545   unsigned char i, j;            /* State variables */
   27546   unsigned char s[256];          /* State variables */
   27547 } sqlite3Prng;
   27548 
   27549 /*
   27550 ** Return N random bytes.
   27551 */
   27552 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
   27553   unsigned char t;
   27554   unsigned char *zBuf = pBuf;
   27555 
   27556   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
   27557   ** state vector.  If writable static data is unsupported on the target,
   27558   ** we have to locate the state vector at run-time.  In the more common
   27559   ** case where writable static data is supported, wsdPrng can refer directly
   27560   ** to the "sqlite3Prng" state vector declared above.
   27561   */
   27562 #ifdef SQLITE_OMIT_WSD
   27563   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
   27564 # define wsdPrng p[0]
   27565 #else
   27566 # define wsdPrng sqlite3Prng
   27567 #endif
   27568 
   27569 #if SQLITE_THREADSAFE
   27570   sqlite3_mutex *mutex;
   27571 #endif
   27572 
   27573 #ifndef SQLITE_OMIT_AUTOINIT
   27574   if( sqlite3_initialize() ) return;
   27575 #endif
   27576 
   27577 #if SQLITE_THREADSAFE
   27578   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
   27579 #endif
   27580 
   27581   sqlite3_mutex_enter(mutex);
   27582   if( N<=0 || pBuf==0 ){
   27583     wsdPrng.isInit = 0;
   27584     sqlite3_mutex_leave(mutex);
   27585     return;
   27586   }
   27587 
   27588   /* Initialize the state of the random number generator once,
   27589   ** the first time this routine is called.  The seed value does
   27590   ** not need to contain a lot of randomness since we are not
   27591   ** trying to do secure encryption or anything like that...
   27592   **
   27593   ** Nothing in this file or anywhere else in SQLite does any kind of
   27594   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
   27595   ** number generator) not as an encryption device.
   27596   */
   27597   if( !wsdPrng.isInit ){
   27598     int i;
   27599     char k[256];
   27600     wsdPrng.j = 0;
   27601     wsdPrng.i = 0;
   27602     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
   27603     for(i=0; i<256; i++){
   27604       wsdPrng.s[i] = (u8)i;
   27605     }
   27606     for(i=0; i<256; i++){
   27607       wsdPrng.j += wsdPrng.s[i] + k[i];
   27608       t = wsdPrng.s[wsdPrng.j];
   27609       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
   27610       wsdPrng.s[i] = t;
   27611     }
   27612     wsdPrng.isInit = 1;
   27613   }
   27614 
   27615   assert( N>0 );
   27616   do{
   27617     wsdPrng.i++;
   27618     t = wsdPrng.s[wsdPrng.i];
   27619     wsdPrng.j += t;
   27620     wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
   27621     wsdPrng.s[wsdPrng.j] = t;
   27622     t += wsdPrng.s[wsdPrng.i];
   27623     *(zBuf++) = wsdPrng.s[t];
   27624   }while( --N );
   27625   sqlite3_mutex_leave(mutex);
   27626 }
   27627 
   27628 #ifndef SQLITE_UNTESTABLE
   27629 /*
   27630 ** For testing purposes, we sometimes want to preserve the state of
   27631 ** PRNG and restore the PRNG to its saved state at a later time, or
   27632 ** to reset the PRNG to its initial state.  These routines accomplish
   27633 ** those tasks.
   27634 **
   27635 ** The sqlite3_test_control() interface calls these routines to
   27636 ** control the PRNG.
   27637 */
   27638 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
   27639 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
   27640   memcpy(
   27641     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   27642     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   27643     sizeof(sqlite3Prng)
   27644   );
   27645 }
   27646 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
   27647   memcpy(
   27648     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   27649     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   27650     sizeof(sqlite3Prng)
   27651   );
   27652 }
   27653 #endif /* SQLITE_UNTESTABLE */
   27654 
   27655 /************** End of random.c **********************************************/
   27656 /************** Begin file threads.c *****************************************/
   27657 /*
   27658 ** 2012 July 21
   27659 **
   27660 ** The author disclaims copyright to this source code.  In place of
   27661 ** a legal notice, here is a blessing:
   27662 **
   27663 **    May you do good and not evil.
   27664 **    May you find forgiveness for yourself and forgive others.
   27665 **    May you share freely, never taking more than you give.
   27666 **
   27667 ******************************************************************************
   27668 **
   27669 ** This file presents a simple cross-platform threading interface for
   27670 ** use internally by SQLite.
   27671 **
   27672 ** A "thread" can be created using sqlite3ThreadCreate().  This thread
   27673 ** runs independently of its creator until it is joined using
   27674 ** sqlite3ThreadJoin(), at which point it terminates.
   27675 **
   27676 ** Threads do not have to be real.  It could be that the work of the
   27677 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
   27678 ** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
   27679 ** single threaded systems.  Nothing in SQLite requires multiple threads.
   27680 ** This interface exists so that applications that want to take advantage
   27681 ** of multiple cores can do so, while also allowing applications to stay
   27682 ** single-threaded if desired.
   27683 */
   27684 /* #include "sqliteInt.h" */
   27685 #if SQLITE_OS_WIN
   27686 /* #  include "os_win.h" */
   27687 #endif
   27688 
   27689 #if SQLITE_MAX_WORKER_THREADS>0
   27690 
   27691 /********************************* Unix Pthreads ****************************/
   27692 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
   27693 
   27694 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
   27695 /* #include <pthread.h> */
   27696 
   27697 /* A running thread */
   27698 struct SQLiteThread {
   27699   pthread_t tid;                 /* Thread ID */
   27700   int done;                      /* Set to true when thread finishes */
   27701   void *pOut;                    /* Result returned by the thread */
   27702   void *(*xTask)(void*);         /* The thread routine */
   27703   void *pIn;                     /* Argument to the thread */
   27704 };
   27705 
   27706 /* Create a new thread */
   27707 SQLITE_PRIVATE int sqlite3ThreadCreate(
   27708   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
   27709   void *(*xTask)(void*),    /* Routine to run in a separate thread */
   27710   void *pIn                 /* Argument passed into xTask() */
   27711 ){
   27712   SQLiteThread *p;
   27713   int rc;
   27714 
   27715   assert( ppThread!=0 );
   27716   assert( xTask!=0 );
   27717   /* This routine is never used in single-threaded mode */
   27718   assert( sqlite3GlobalConfig.bCoreMutex!=0 );
   27719 
   27720   *ppThread = 0;
   27721   p = sqlite3Malloc(sizeof(*p));
   27722   if( p==0 ) return SQLITE_NOMEM_BKPT;
   27723   memset(p, 0, sizeof(*p));
   27724   p->xTask = xTask;
   27725   p->pIn = pIn;
   27726   /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
   27727   ** function that returns SQLITE_ERROR when passed the argument 200, that
   27728   ** forces worker threads to run sequentially and deterministically
   27729   ** for testing purposes. */
   27730   if( sqlite3FaultSim(200) ){
   27731     rc = 1;
   27732   }else{
   27733     rc = pthread_create(&p->tid, 0, xTask, pIn);
   27734   }
   27735   if( rc ){
   27736     p->done = 1;
   27737     p->pOut = xTask(pIn);
   27738   }
   27739   *ppThread = p;
   27740   return SQLITE_OK;
   27741 }
   27742 
   27743 /* Get the results of the thread */
   27744 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
   27745   int rc;
   27746 
   27747   assert( ppOut!=0 );
   27748   if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
   27749   if( p->done ){
   27750     *ppOut = p->pOut;
   27751     rc = SQLITE_OK;
   27752   }else{
   27753     rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
   27754   }
   27755   sqlite3_free(p);
   27756   return rc;
   27757 }
   27758 
   27759 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
   27760 /******************************** End Unix Pthreads *************************/
   27761 
   27762 
   27763 /********************************* Win32 Threads ****************************/
   27764 #if SQLITE_OS_WIN_THREADS
   27765 
   27766 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
   27767 #include <process.h>
   27768 
   27769 /* A running thread */
   27770 struct SQLiteThread {
   27771   void *tid;               /* The thread handle */
   27772   unsigned id;             /* The thread identifier */
   27773   void *(*xTask)(void*);   /* The routine to run as a thread */
   27774   void *pIn;               /* Argument to xTask */
   27775   void *pResult;           /* Result of xTask */
   27776 };
   27777 
   27778 /* Thread procedure Win32 compatibility shim */
   27779 static unsigned __stdcall sqlite3ThreadProc(
   27780   void *pArg  /* IN: Pointer to the SQLiteThread structure */
   27781 ){
   27782   SQLiteThread *p = (SQLiteThread *)pArg;
   27783 
   27784   assert( p!=0 );
   27785 #if 0
   27786   /*
   27787   ** This assert appears to trigger spuriously on certain
   27788   ** versions of Windows, possibly due to _beginthreadex()
   27789   ** and/or CreateThread() not fully setting their thread
   27790   ** ID parameter before starting the thread.
   27791   */
   27792   assert( p->id==GetCurrentThreadId() );
   27793 #endif
   27794   assert( p->xTask!=0 );
   27795   p->pResult = p->xTask(p->pIn);
   27796 
   27797   _endthreadex(0);
   27798   return 0; /* NOT REACHED */
   27799 }
   27800 
   27801 /* Create a new thread */
   27802 SQLITE_PRIVATE int sqlite3ThreadCreate(
   27803   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
   27804   void *(*xTask)(void*),    /* Routine to run in a separate thread */
   27805   void *pIn                 /* Argument passed into xTask() */
   27806 ){
   27807   SQLiteThread *p;
   27808 
   27809   assert( ppThread!=0 );
   27810   assert( xTask!=0 );
   27811   *ppThread = 0;
   27812   p = sqlite3Malloc(sizeof(*p));
   27813   if( p==0 ) return SQLITE_NOMEM_BKPT;
   27814   /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
   27815   ** function that returns SQLITE_ERROR when passed the argument 200, that
   27816   ** forces worker threads to run sequentially and deterministically
   27817   ** (via the sqlite3FaultSim() term of the conditional) for testing
   27818   ** purposes. */
   27819   if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
   27820     memset(p, 0, sizeof(*p));
   27821   }else{
   27822     p->xTask = xTask;
   27823     p->pIn = pIn;
   27824     p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
   27825     if( p->tid==0 ){
   27826       memset(p, 0, sizeof(*p));
   27827     }
   27828   }
   27829   if( p->xTask==0 ){
   27830     p->id = GetCurrentThreadId();
   27831     p->pResult = xTask(pIn);
   27832   }
   27833   *ppThread = p;
   27834   return SQLITE_OK;
   27835 }
   27836 
   27837 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
   27838 
   27839 /* Get the results of the thread */
   27840 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
   27841   DWORD rc;
   27842   BOOL bRc;
   27843 
   27844   assert( ppOut!=0 );
   27845   if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
   27846   if( p->xTask==0 ){
   27847     /* assert( p->id==GetCurrentThreadId() ); */
   27848     rc = WAIT_OBJECT_0;
   27849     assert( p->tid==0 );
   27850   }else{
   27851     assert( p->id!=0 && p->id!=GetCurrentThreadId() );
   27852     rc = sqlite3Win32Wait((HANDLE)p->tid);
   27853     assert( rc!=WAIT_IO_COMPLETION );
   27854     bRc = CloseHandle((HANDLE)p->tid);
   27855     assert( bRc );
   27856   }
   27857   if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
   27858   sqlite3_free(p);
   27859   return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
   27860 }
   27861 
   27862 #endif /* SQLITE_OS_WIN_THREADS */
   27863 /******************************** End Win32 Threads *************************/
   27864 
   27865 
   27866 /********************************* Single-Threaded **************************/
   27867 #ifndef SQLITE_THREADS_IMPLEMENTED
   27868 /*
   27869 ** This implementation does not actually create a new thread.  It does the
   27870 ** work of the thread in the main thread, when either the thread is created
   27871 ** or when it is joined
   27872 */
   27873 
   27874 /* A running thread */
   27875 struct SQLiteThread {
   27876   void *(*xTask)(void*);   /* The routine to run as a thread */
   27877   void *pIn;               /* Argument to xTask */
   27878   void *pResult;           /* Result of xTask */
   27879 };
   27880 
   27881 /* Create a new thread */
   27882 SQLITE_PRIVATE int sqlite3ThreadCreate(
   27883   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
   27884   void *(*xTask)(void*),    /* Routine to run in a separate thread */
   27885   void *pIn                 /* Argument passed into xTask() */
   27886 ){
   27887   SQLiteThread *p;
   27888 
   27889   assert( ppThread!=0 );
   27890   assert( xTask!=0 );
   27891   *ppThread = 0;
   27892   p = sqlite3Malloc(sizeof(*p));
   27893   if( p==0 ) return SQLITE_NOMEM_BKPT;
   27894   if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
   27895     p->xTask = xTask;
   27896     p->pIn = pIn;
   27897   }else{
   27898     p->xTask = 0;
   27899     p->pResult = xTask(pIn);
   27900   }
   27901   *ppThread = p;
   27902   return SQLITE_OK;
   27903 }
   27904 
   27905 /* Get the results of the thread */
   27906 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
   27907 
   27908   assert( ppOut!=0 );
   27909   if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
   27910   if( p->xTask ){
   27911     *ppOut = p->xTask(p->pIn);
   27912   }else{
   27913     *ppOut = p->pResult;
   27914   }
   27915   sqlite3_free(p);
   27916 
   27917 #if defined(SQLITE_TEST)
   27918   {
   27919     void *pTstAlloc = sqlite3Malloc(10);
   27920     if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
   27921     sqlite3_free(pTstAlloc);
   27922   }
   27923 #endif
   27924 
   27925   return SQLITE_OK;
   27926 }
   27927 
   27928 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
   27929 /****************************** End Single-Threaded *************************/
   27930 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
   27931 
   27932 /************** End of threads.c *********************************************/
   27933 /************** Begin file utf.c *********************************************/
   27934 /*
   27935 ** 2004 April 13
   27936 **
   27937 ** The author disclaims copyright to this source code.  In place of
   27938 ** a legal notice, here is a blessing:
   27939 **
   27940 **    May you do good and not evil.
   27941 **    May you find forgiveness for yourself and forgive others.
   27942 **    May you share freely, never taking more than you give.
   27943 **
   27944 *************************************************************************
   27945 ** This file contains routines used to translate between UTF-8,
   27946 ** UTF-16, UTF-16BE, and UTF-16LE.
   27947 **
   27948 ** Notes on UTF-8:
   27949 **
   27950 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
   27951 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
   27952 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
   27953 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
   27954 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
   27955 **
   27956 **
   27957 ** Notes on UTF-16:  (with wwww+1==uuuuu)
   27958 **
   27959 **      Word-0               Word-1          Value
   27960 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
   27961 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
   27962 **
   27963 **
   27964 ** BOM or Byte Order Mark:
   27965 **     0xff 0xfe   little-endian utf-16 follows
   27966 **     0xfe 0xff   big-endian utf-16 follows
   27967 **
   27968 */
   27969 /* #include "sqliteInt.h" */
   27970 /* #include <assert.h> */
   27971 /* #include "vdbeInt.h" */
   27972 
   27973 #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
   27974 /*
   27975 ** The following constant value is used by the SQLITE_BIGENDIAN and
   27976 ** SQLITE_LITTLEENDIAN macros.
   27977 */
   27978 SQLITE_PRIVATE const int sqlite3one = 1;
   27979 #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
   27980 
   27981 /*
   27982 ** This lookup table is used to help decode the first byte of
   27983 ** a multi-byte UTF8 character.
   27984 */
   27985 static const unsigned char sqlite3Utf8Trans1[] = {
   27986   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   27987   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   27988   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   27989   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   27990   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   27991   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   27992   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   27993   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   27994 };
   27995 
   27996 
   27997 #define WRITE_UTF8(zOut, c) {                          \
   27998   if( c<0x00080 ){                                     \
   27999     *zOut++ = (u8)(c&0xFF);                            \
   28000   }                                                    \
   28001   else if( c<0x00800 ){                                \
   28002     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   28003     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   28004   }                                                    \
   28005   else if( c<0x10000 ){                                \
   28006     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   28007     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   28008     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   28009   }else{                                               \
   28010     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   28011     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   28012     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   28013     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   28014   }                                                    \
   28015 }
   28016 
   28017 #define WRITE_UTF16LE(zOut, c) {                                    \
   28018   if( c<=0xFFFF ){                                                  \
   28019     *zOut++ = (u8)(c&0x00FF);                                       \
   28020     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   28021   }else{                                                            \
   28022     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   28023     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   28024     *zOut++ = (u8)(c&0x00FF);                                       \
   28025     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   28026   }                                                                 \
   28027 }
   28028 
   28029 #define WRITE_UTF16BE(zOut, c) {                                    \
   28030   if( c<=0xFFFF ){                                                  \
   28031     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   28032     *zOut++ = (u8)(c&0x00FF);                                       \
   28033   }else{                                                            \
   28034     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   28035     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   28036     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   28037     *zOut++ = (u8)(c&0x00FF);                                       \
   28038   }                                                                 \
   28039 }
   28040 
   28041 #define READ_UTF16LE(zIn, TERM, c){                                   \
   28042   c = (*zIn++);                                                       \
   28043   c += ((*zIn++)<<8);                                                 \
   28044   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   28045     int c2 = (*zIn++);                                                \
   28046     c2 += ((*zIn++)<<8);                                              \
   28047     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   28048   }                                                                   \
   28049 }
   28050 
   28051 #define READ_UTF16BE(zIn, TERM, c){                                   \
   28052   c = ((*zIn++)<<8);                                                  \
   28053   c += (*zIn++);                                                      \
   28054   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   28055     int c2 = ((*zIn++)<<8);                                           \
   28056     c2 += (*zIn++);                                                   \
   28057     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   28058   }                                                                   \
   28059 }
   28060 
   28061 /*
   28062 ** Translate a single UTF-8 character.  Return the unicode value.
   28063 **
   28064 ** During translation, assume that the byte that zTerm points
   28065 ** is a 0x00.
   28066 **
   28067 ** Write a pointer to the next unread byte back into *pzNext.
   28068 **
   28069 ** Notes On Invalid UTF-8:
   28070 **
   28071 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
   28072 **     be encoded as a multi-byte character.  Any multi-byte character that
   28073 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
   28074 **
   28075 **  *  This routine never allows a UTF16 surrogate value to be encoded.
   28076 **     If a multi-byte character attempts to encode a value between
   28077 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
   28078 **
   28079 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
   28080 **     byte of a character are interpreted as single-byte characters
   28081 **     and rendered as themselves even though they are technically
   28082 **     invalid characters.
   28083 **
   28084 **  *  This routine accepts over-length UTF8 encodings
   28085 **     for unicode values 0x80 and greater.  It does not change over-length
   28086 **     encodings to 0xfffd as some systems recommend.
   28087 */
   28088 #define READ_UTF8(zIn, zTerm, c)                           \
   28089   c = *(zIn++);                                            \
   28090   if( c>=0xc0 ){                                           \
   28091     c = sqlite3Utf8Trans1[c-0xc0];                         \
   28092     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   28093       c = (c<<6) + (0x3f & *(zIn++));                      \
   28094     }                                                      \
   28095     if( c<0x80                                             \
   28096         || (c&0xFFFFF800)==0xD800                          \
   28097         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   28098   }
   28099 SQLITE_PRIVATE u32 sqlite3Utf8Read(
   28100   const unsigned char **pz    /* Pointer to string from which to read char */
   28101 ){
   28102   unsigned int c;
   28103 
   28104   /* Same as READ_UTF8() above but without the zTerm parameter.
   28105   ** For this routine, we assume the UTF8 string is always zero-terminated.
   28106   */
   28107   c = *((*pz)++);
   28108   if( c>=0xc0 ){
   28109     c = sqlite3Utf8Trans1[c-0xc0];
   28110     while( (*(*pz) & 0xc0)==0x80 ){
   28111       c = (c<<6) + (0x3f & *((*pz)++));
   28112     }
   28113     if( c<0x80
   28114         || (c&0xFFFFF800)==0xD800
   28115         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
   28116   }
   28117   return c;
   28118 }
   28119 
   28120 
   28121 
   28122 
   28123 /*
   28124 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
   28125 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
   28126 */
   28127 /* #define TRANSLATE_TRACE 1 */
   28128 
   28129 #ifndef SQLITE_OMIT_UTF16
   28130 /*
   28131 ** This routine transforms the internal text encoding used by pMem to
   28132 ** desiredEnc. It is an error if the string is already of the desired
   28133 ** encoding, or if *pMem does not contain a string value.
   28134 */
   28135 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
   28136   int len;                    /* Maximum length of output string in bytes */
   28137   unsigned char *zOut;                  /* Output buffer */
   28138   unsigned char *zIn;                   /* Input iterator */
   28139   unsigned char *zTerm;                 /* End of input */
   28140   unsigned char *z;                     /* Output iterator */
   28141   unsigned int c;
   28142 
   28143   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   28144   assert( pMem->flags&MEM_Str );
   28145   assert( pMem->enc!=desiredEnc );
   28146   assert( pMem->enc!=0 );
   28147   assert( pMem->n>=0 );
   28148 
   28149 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   28150   {
   28151     char zBuf[100];
   28152     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   28153     fprintf(stderr, "INPUT:  %s\n", zBuf);
   28154   }
   28155 #endif
   28156 
   28157   /* If the translation is between UTF-16 little and big endian, then
   28158   ** all that is required is to swap the byte order. This case is handled
   28159   ** differently from the others.
   28160   */
   28161   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
   28162     u8 temp;
   28163     int rc;
   28164     rc = sqlite3VdbeMemMakeWriteable(pMem);
   28165     if( rc!=SQLITE_OK ){
   28166       assert( rc==SQLITE_NOMEM );
   28167       return SQLITE_NOMEM_BKPT;
   28168     }
   28169     zIn = (u8*)pMem->z;
   28170     zTerm = &zIn[pMem->n&~1];
   28171     while( zIn<zTerm ){
   28172       temp = *zIn;
   28173       *zIn = *(zIn+1);
   28174       zIn++;
   28175       *zIn++ = temp;
   28176     }
   28177     pMem->enc = desiredEnc;
   28178     goto translate_out;
   28179   }
   28180 
   28181   /* Set len to the maximum number of bytes required in the output buffer. */
   28182   if( desiredEnc==SQLITE_UTF8 ){
   28183     /* When converting from UTF-16, the maximum growth results from
   28184     ** translating a 2-byte character to a 4-byte UTF-8 character.
   28185     ** A single byte is required for the output string
   28186     ** nul-terminator.
   28187     */
   28188     pMem->n &= ~1;
   28189     len = pMem->n * 2 + 1;
   28190   }else{
   28191     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
   28192     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
   28193     ** character. Two bytes are required in the output buffer for the
   28194     ** nul-terminator.
   28195     */
   28196     len = pMem->n * 2 + 2;
   28197   }
   28198 
   28199   /* Set zIn to point at the start of the input buffer and zTerm to point 1
   28200   ** byte past the end.
   28201   **
   28202   ** Variable zOut is set to point at the output buffer, space obtained
   28203   ** from sqlite3_malloc().
   28204   */
   28205   zIn = (u8*)pMem->z;
   28206   zTerm = &zIn[pMem->n];
   28207   zOut = sqlite3DbMallocRaw(pMem->db, len);
   28208   if( !zOut ){
   28209     return SQLITE_NOMEM_BKPT;
   28210   }
   28211   z = zOut;
   28212 
   28213   if( pMem->enc==SQLITE_UTF8 ){
   28214     if( desiredEnc==SQLITE_UTF16LE ){
   28215       /* UTF-8 -> UTF-16 Little-endian */
   28216       while( zIn<zTerm ){
   28217         READ_UTF8(zIn, zTerm, c);
   28218         WRITE_UTF16LE(z, c);
   28219       }
   28220     }else{
   28221       assert( desiredEnc==SQLITE_UTF16BE );
   28222       /* UTF-8 -> UTF-16 Big-endian */
   28223       while( zIn<zTerm ){
   28224         READ_UTF8(zIn, zTerm, c);
   28225         WRITE_UTF16BE(z, c);
   28226       }
   28227     }
   28228     pMem->n = (int)(z - zOut);
   28229     *z++ = 0;
   28230   }else{
   28231     assert( desiredEnc==SQLITE_UTF8 );
   28232     if( pMem->enc==SQLITE_UTF16LE ){
   28233       /* UTF-16 Little-endian -> UTF-8 */
   28234       while( zIn<zTerm ){
   28235         READ_UTF16LE(zIn, zIn<zTerm, c);
   28236         WRITE_UTF8(z, c);
   28237       }
   28238     }else{
   28239       /* UTF-16 Big-endian -> UTF-8 */
   28240       while( zIn<zTerm ){
   28241         READ_UTF16BE(zIn, zIn<zTerm, c);
   28242         WRITE_UTF8(z, c);
   28243       }
   28244     }
   28245     pMem->n = (int)(z - zOut);
   28246   }
   28247   *z = 0;
   28248   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
   28249 
   28250   c = pMem->flags;
   28251   sqlite3VdbeMemRelease(pMem);
   28252   pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
   28253   pMem->enc = desiredEnc;
   28254   pMem->z = (char*)zOut;
   28255   pMem->zMalloc = pMem->z;
   28256   pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
   28257 
   28258 translate_out:
   28259 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   28260   {
   28261     char zBuf[100];
   28262     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   28263     fprintf(stderr, "OUTPUT: %s\n", zBuf);
   28264   }
   28265 #endif
   28266   return SQLITE_OK;
   28267 }
   28268 #endif /* SQLITE_OMIT_UTF16 */
   28269 
   28270 #ifndef SQLITE_OMIT_UTF16
   28271 /*
   28272 ** This routine checks for a byte-order mark at the beginning of the
   28273 ** UTF-16 string stored in *pMem. If one is present, it is removed and
   28274 ** the encoding of the Mem adjusted. This routine does not do any
   28275 ** byte-swapping, it just sets Mem.enc appropriately.
   28276 **
   28277 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
   28278 ** changed by this function.
   28279 */
   28280 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
   28281   int rc = SQLITE_OK;
   28282   u8 bom = 0;
   28283 
   28284   assert( pMem->n>=0 );
   28285   if( pMem->n>1 ){
   28286     u8 b1 = *(u8 *)pMem->z;
   28287     u8 b2 = *(((u8 *)pMem->z) + 1);
   28288     if( b1==0xFE && b2==0xFF ){
   28289       bom = SQLITE_UTF16BE;
   28290     }
   28291     if( b1==0xFF && b2==0xFE ){
   28292       bom = SQLITE_UTF16LE;
   28293     }
   28294   }
   28295 
   28296   if( bom ){
   28297     rc = sqlite3VdbeMemMakeWriteable(pMem);
   28298     if( rc==SQLITE_OK ){
   28299       pMem->n -= 2;
   28300       memmove(pMem->z, &pMem->z[2], pMem->n);
   28301       pMem->z[pMem->n] = '\0';
   28302       pMem->z[pMem->n+1] = '\0';
   28303       pMem->flags |= MEM_Term;
   28304       pMem->enc = bom;
   28305     }
   28306   }
   28307   return rc;
   28308 }
   28309 #endif /* SQLITE_OMIT_UTF16 */
   28310 
   28311 /*
   28312 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
   28313 ** return the number of unicode characters in pZ up to (but not including)
   28314 ** the first 0x00 byte. If nByte is not less than zero, return the
   28315 ** number of unicode characters in the first nByte of pZ (or up to
   28316 ** the first 0x00, whichever comes first).
   28317 */
   28318 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
   28319   int r = 0;
   28320   const u8 *z = (const u8*)zIn;
   28321   const u8 *zTerm;
   28322   if( nByte>=0 ){
   28323     zTerm = &z[nByte];
   28324   }else{
   28325     zTerm = (const u8*)(-1);
   28326   }
   28327   assert( z<=zTerm );
   28328   while( *z!=0 && z<zTerm ){
   28329     SQLITE_SKIP_UTF8(z);
   28330     r++;
   28331   }
   28332   return r;
   28333 }
   28334 
   28335 /* This test function is not currently used by the automated test-suite.
   28336 ** Hence it is only available in debug builds.
   28337 */
   28338 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   28339 /*
   28340 ** Translate UTF-8 to UTF-8.
   28341 **
   28342 ** This has the effect of making sure that the string is well-formed
   28343 ** UTF-8.  Miscoded characters are removed.
   28344 **
   28345 ** The translation is done in-place and aborted if the output
   28346 ** overruns the input.
   28347 */
   28348 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
   28349   unsigned char *zOut = zIn;
   28350   unsigned char *zStart = zIn;
   28351   u32 c;
   28352 
   28353   while( zIn[0] && zOut<=zIn ){
   28354     c = sqlite3Utf8Read((const u8**)&zIn);
   28355     if( c!=0xfffd ){
   28356       WRITE_UTF8(zOut, c);
   28357     }
   28358   }
   28359   *zOut = 0;
   28360   return (int)(zOut - zStart);
   28361 }
   28362 #endif
   28363 
   28364 #ifndef SQLITE_OMIT_UTF16
   28365 /*
   28366 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
   28367 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
   28368 ** be freed by the calling function.
   28369 **
   28370 ** NULL is returned if there is an allocation error.
   28371 */
   28372 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
   28373   Mem m;
   28374   memset(&m, 0, sizeof(m));
   28375   m.db = db;
   28376   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
   28377   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
   28378   if( db->mallocFailed ){
   28379     sqlite3VdbeMemRelease(&m);
   28380     m.z = 0;
   28381   }
   28382   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
   28383   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
   28384   assert( m.z || db->mallocFailed );
   28385   return m.z;
   28386 }
   28387 
   28388 /*
   28389 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
   28390 ** Return the number of bytes in the first nChar unicode characters
   28391 ** in pZ.  nChar must be non-negative.
   28392 */
   28393 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
   28394   int c;
   28395   unsigned char const *z = zIn;
   28396   int n = 0;
   28397 
   28398   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
   28399     while( n<nChar ){
   28400       READ_UTF16BE(z, 1, c);
   28401       n++;
   28402     }
   28403   }else{
   28404     while( n<nChar ){
   28405       READ_UTF16LE(z, 1, c);
   28406       n++;
   28407     }
   28408   }
   28409   return (int)(z-(unsigned char const *)zIn);
   28410 }
   28411 
   28412 #if defined(SQLITE_TEST)
   28413 /*
   28414 ** This routine is called from the TCL test function "translate_selftest".
   28415 ** It checks that the primitives for serializing and deserializing
   28416 ** characters in each encoding are inverses of each other.
   28417 */
   28418 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
   28419   unsigned int i, t;
   28420   unsigned char zBuf[20];
   28421   unsigned char *z;
   28422   int n;
   28423   unsigned int c;
   28424 
   28425   for(i=0; i<0x00110000; i++){
   28426     z = zBuf;
   28427     WRITE_UTF8(z, i);
   28428     n = (int)(z-zBuf);
   28429     assert( n>0 && n<=4 );
   28430     z[0] = 0;
   28431     z = zBuf;
   28432     c = sqlite3Utf8Read((const u8**)&z);
   28433     t = i;
   28434     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
   28435     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
   28436     assert( c==t );
   28437     assert( (z-zBuf)==n );
   28438   }
   28439   for(i=0; i<0x00110000; i++){
   28440     if( i>=0xD800 && i<0xE000 ) continue;
   28441     z = zBuf;
   28442     WRITE_UTF16LE(z, i);
   28443     n = (int)(z-zBuf);
   28444     assert( n>0 && n<=4 );
   28445     z[0] = 0;
   28446     z = zBuf;
   28447     READ_UTF16LE(z, 1, c);
   28448     assert( c==i );
   28449     assert( (z-zBuf)==n );
   28450   }
   28451   for(i=0; i<0x00110000; i++){
   28452     if( i>=0xD800 && i<0xE000 ) continue;
   28453     z = zBuf;
   28454     WRITE_UTF16BE(z, i);
   28455     n = (int)(z-zBuf);
   28456     assert( n>0 && n<=4 );
   28457     z[0] = 0;
   28458     z = zBuf;
   28459     READ_UTF16BE(z, 1, c);
   28460     assert( c==i );
   28461     assert( (z-zBuf)==n );
   28462   }
   28463 }
   28464 #endif /* SQLITE_TEST */
   28465 #endif /* SQLITE_OMIT_UTF16 */
   28466 
   28467 /************** End of utf.c *************************************************/
   28468 /************** Begin file util.c ********************************************/
   28469 /*
   28470 ** 2001 September 15
   28471 **
   28472 ** The author disclaims copyright to this source code.  In place of
   28473 ** a legal notice, here is a blessing:
   28474 **
   28475 **    May you do good and not evil.
   28476 **    May you find forgiveness for yourself and forgive others.
   28477 **    May you share freely, never taking more than you give.
   28478 **
   28479 *************************************************************************
   28480 ** Utility functions used throughout sqlite.
   28481 **
   28482 ** This file contains functions for allocating memory, comparing
   28483 ** strings, and stuff like that.
   28484 **
   28485 */
   28486 /* #include "sqliteInt.h" */
   28487 /* #include <stdarg.h> */
   28488 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
   28489 # include <math.h>
   28490 #endif
   28491 
   28492 /*
   28493 ** Routine needed to support the testcase() macro.
   28494 */
   28495 #ifdef SQLITE_COVERAGE_TEST
   28496 SQLITE_PRIVATE void sqlite3Coverage(int x){
   28497   static unsigned dummy = 0;
   28498   dummy += (unsigned)x;
   28499 }
   28500 #endif
   28501 
   28502 /*
   28503 ** Give a callback to the test harness that can be used to simulate faults
   28504 ** in places where it is difficult or expensive to do so purely by means
   28505 ** of inputs.
   28506 **
   28507 ** The intent of the integer argument is to let the fault simulator know
   28508 ** which of multiple sqlite3FaultSim() calls has been hit.
   28509 **
   28510 ** Return whatever integer value the test callback returns, or return
   28511 ** SQLITE_OK if no test callback is installed.
   28512 */
   28513 #ifndef SQLITE_UNTESTABLE
   28514 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
   28515   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
   28516   return xCallback ? xCallback(iTest) : SQLITE_OK;
   28517 }
   28518 #endif
   28519 
   28520 #ifndef SQLITE_OMIT_FLOATING_POINT
   28521 /*
   28522 ** Return true if the floating point value is Not a Number (NaN).
   28523 **
   28524 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
   28525 ** Otherwise, we have our own implementation that works on most systems.
   28526 */
   28527 SQLITE_PRIVATE int sqlite3IsNaN(double x){
   28528   int rc;   /* The value return */
   28529 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
   28530   /*
   28531   ** Systems that support the isnan() library function should probably
   28532   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
   28533   ** found that many systems do not have a working isnan() function so
   28534   ** this implementation is provided as an alternative.
   28535   **
   28536   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
   28537   ** On the other hand, the use of -ffast-math comes with the following
   28538   ** warning:
   28539   **
   28540   **      This option [-ffast-math] should never be turned on by any
   28541   **      -O option since it can result in incorrect output for programs
   28542   **      which depend on an exact implementation of IEEE or ISO
   28543   **      rules/specifications for math functions.
   28544   **
   28545   ** Under MSVC, this NaN test may fail if compiled with a floating-
   28546   ** point precision mode other than /fp:precise.  From the MSDN
   28547   ** documentation:
   28548   **
   28549   **      The compiler [with /fp:precise] will properly handle comparisons
   28550   **      involving NaN. For example, x != x evaluates to true if x is NaN
   28551   **      ...
   28552   */
   28553 #ifdef __FAST_MATH__
   28554 # error SQLite will not work correctly with the -ffast-math option of GCC.
   28555 #endif
   28556   volatile double y = x;
   28557   volatile double z = y;
   28558   rc = (y!=z);
   28559 #else  /* if HAVE_ISNAN */
   28560   rc = isnan(x);
   28561 #endif /* HAVE_ISNAN */
   28562   testcase( rc );
   28563   return rc;
   28564 }
   28565 #endif /* SQLITE_OMIT_FLOATING_POINT */
   28566 
   28567 /*
   28568 ** Compute a string length that is limited to what can be stored in
   28569 ** lower 30 bits of a 32-bit signed integer.
   28570 **
   28571 ** The value returned will never be negative.  Nor will it ever be greater
   28572 ** than the actual length of the string.  For very long strings (greater
   28573 ** than 1GiB) the value returned might be less than the true string length.
   28574 */
   28575 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
   28576   if( z==0 ) return 0;
   28577   return 0x3fffffff & (int)strlen(z);
   28578 }
   28579 
   28580 /*
   28581 ** Return the declared type of a column.  Or return zDflt if the column
   28582 ** has no declared type.
   28583 **
   28584 ** The column type is an extra string stored after the zero-terminator on
   28585 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
   28586 */
   28587 SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
   28588   if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
   28589   return pCol->zName + strlen(pCol->zName) + 1;
   28590 }
   28591 
   28592 /*
   28593 ** Helper function for sqlite3Error() - called rarely.  Broken out into
   28594 ** a separate routine to avoid unnecessary register saves on entry to
   28595 ** sqlite3Error().
   28596 */
   28597 static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
   28598   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
   28599   sqlite3SystemError(db, err_code);
   28600 }
   28601 
   28602 /*
   28603 ** Set the current error code to err_code and clear any prior error message.
   28604 ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
   28605 ** that would be appropriate.
   28606 */
   28607 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
   28608   assert( db!=0 );
   28609   db->errCode = err_code;
   28610   if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
   28611 }
   28612 
   28613 /*
   28614 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
   28615 ** to do based on the SQLite error code in rc.
   28616 */
   28617 SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
   28618   if( rc==SQLITE_IOERR_NOMEM ) return;
   28619   rc &= 0xff;
   28620   if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
   28621     db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
   28622   }
   28623 }
   28624 
   28625 /*
   28626 ** Set the most recent error code and error string for the sqlite
   28627 ** handle "db". The error code is set to "err_code".
   28628 **
   28629 ** If it is not NULL, string zFormat specifies the format of the
   28630 ** error string in the style of the printf functions: The following
   28631 ** format characters are allowed:
   28632 **
   28633 **      %s      Insert a string
   28634 **      %z      A string that should be freed after use
   28635 **      %d      Insert an integer
   28636 **      %T      Insert a token
   28637 **      %S      Insert the first element of a SrcList
   28638 **
   28639 ** zFormat and any string tokens that follow it are assumed to be
   28640 ** encoded in UTF-8.
   28641 **
   28642 ** To clear the most recent error for sqlite handle "db", sqlite3Error
   28643 ** should be called with err_code set to SQLITE_OK and zFormat set
   28644 ** to NULL.
   28645 */
   28646 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
   28647   assert( db!=0 );
   28648   db->errCode = err_code;
   28649   sqlite3SystemError(db, err_code);
   28650   if( zFormat==0 ){
   28651     sqlite3Error(db, err_code);
   28652   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
   28653     char *z;
   28654     va_list ap;
   28655     va_start(ap, zFormat);
   28656     z = sqlite3VMPrintf(db, zFormat, ap);
   28657     va_end(ap);
   28658     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
   28659   }
   28660 }
   28661 
   28662 /*
   28663 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
   28664 ** The following formatting characters are allowed:
   28665 **
   28666 **      %s      Insert a string
   28667 **      %z      A string that should be freed after use
   28668 **      %d      Insert an integer
   28669 **      %T      Insert a token
   28670 **      %S      Insert the first element of a SrcList
   28671 **
   28672 ** This function should be used to report any error that occurs while
   28673 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
   28674 ** last thing the sqlite3_prepare() function does is copy the error
   28675 ** stored by this function into the database handle using sqlite3Error().
   28676 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
   28677 ** during statement execution (sqlite3_step() etc.).
   28678 */
   28679 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
   28680   char *zMsg;
   28681   va_list ap;
   28682   sqlite3 *db = pParse->db;
   28683   va_start(ap, zFormat);
   28684   zMsg = sqlite3VMPrintf(db, zFormat, ap);
   28685   va_end(ap);
   28686   if( db->suppressErr ){
   28687     sqlite3DbFree(db, zMsg);
   28688   }else{
   28689     pParse->nErr++;
   28690     sqlite3DbFree(db, pParse->zErrMsg);
   28691     pParse->zErrMsg = zMsg;
   28692     pParse->rc = SQLITE_ERROR;
   28693   }
   28694 }
   28695 
   28696 /*
   28697 ** Convert an SQL-style quoted string into a normal string by removing
   28698 ** the quote characters.  The conversion is done in-place.  If the
   28699 ** input does not begin with a quote character, then this routine
   28700 ** is a no-op.
   28701 **
   28702 ** The input string must be zero-terminated.  A new zero-terminator
   28703 ** is added to the dequoted string.
   28704 **
   28705 ** The return value is -1 if no dequoting occurs or the length of the
   28706 ** dequoted string, exclusive of the zero terminator, if dequoting does
   28707 ** occur.
   28708 **
   28709 ** 2002-Feb-14: This routine is extended to remove MS-Access style
   28710 ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
   28711 ** "a-b-c".
   28712 */
   28713 SQLITE_PRIVATE void sqlite3Dequote(char *z){
   28714   char quote;
   28715   int i, j;
   28716   if( z==0 ) return;
   28717   quote = z[0];
   28718   if( !sqlite3Isquote(quote) ) return;
   28719   if( quote=='[' ) quote = ']';
   28720   for(i=1, j=0;; i++){
   28721     assert( z[i] );
   28722     if( z[i]==quote ){
   28723       if( z[i+1]==quote ){
   28724         z[j++] = quote;
   28725         i++;
   28726       }else{
   28727         break;
   28728       }
   28729     }else{
   28730       z[j++] = z[i];
   28731     }
   28732   }
   28733   z[j] = 0;
   28734 }
   28735 
   28736 /*
   28737 ** Generate a Token object from a string
   28738 */
   28739 SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
   28740   p->z = z;
   28741   p->n = sqlite3Strlen30(z);
   28742 }
   28743 
   28744 /* Convenient short-hand */
   28745 #define UpperToLower sqlite3UpperToLower
   28746 
   28747 /*
   28748 ** Some systems have stricmp().  Others have strcasecmp().  Because
   28749 ** there is no consistency, we will define our own.
   28750 **
   28751 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
   28752 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
   28753 ** the contents of two buffers containing UTF-8 strings in a
   28754 ** case-independent fashion, using the same definition of "case
   28755 ** independence" that SQLite uses internally when comparing identifiers.
   28756 */
   28757 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
   28758   if( zLeft==0 ){
   28759     return zRight ? -1 : 0;
   28760   }else if( zRight==0 ){
   28761     return 1;
   28762   }
   28763   return sqlite3StrICmp(zLeft, zRight);
   28764 }
   28765 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
   28766   unsigned char *a, *b;
   28767   int c;
   28768   a = (unsigned char *)zLeft;
   28769   b = (unsigned char *)zRight;
   28770   for(;;){
   28771     c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
   28772     if( c || *a==0 ) break;
   28773     a++;
   28774     b++;
   28775   }
   28776   return c;
   28777 }
   28778 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
   28779   register unsigned char *a, *b;
   28780   if( zLeft==0 ){
   28781     return zRight ? -1 : 0;
   28782   }else if( zRight==0 ){
   28783     return 1;
   28784   }
   28785   a = (unsigned char *)zLeft;
   28786   b = (unsigned char *)zRight;
   28787   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   28788   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
   28789 }
   28790 
   28791 /*
   28792 ** Compute 10 to the E-th power.  Examples:  E==1 results in 10.
   28793 ** E==2 results in 100.  E==50 results in 1.0e50.
   28794 **
   28795 ** This routine only works for values of E between 1 and 341.
   28796 */
   28797 static LONGDOUBLE_TYPE sqlite3Pow10(int E){
   28798 #if defined(_MSC_VER)
   28799   static const LONGDOUBLE_TYPE x[] = {
   28800     1.0e+001,
   28801     1.0e+002,
   28802     1.0e+004,
   28803     1.0e+008,
   28804     1.0e+016,
   28805     1.0e+032,
   28806     1.0e+064,
   28807     1.0e+128,
   28808     1.0e+256
   28809   };
   28810   LONGDOUBLE_TYPE r = 1.0;
   28811   int i;
   28812   assert( E>=0 && E<=307 );
   28813   for(i=0; E!=0; i++, E >>=1){
   28814     if( E & 1 ) r *= x[i];
   28815   }
   28816   return r;
   28817 #else
   28818   LONGDOUBLE_TYPE x = 10.0;
   28819   LONGDOUBLE_TYPE r = 1.0;
   28820   while(1){
   28821     if( E & 1 ) r *= x;
   28822     E >>= 1;
   28823     if( E==0 ) break;
   28824     x *= x;
   28825   }
   28826   return r;
   28827 #endif
   28828 }
   28829 
   28830 /*
   28831 ** The string z[] is an text representation of a real number.
   28832 ** Convert this string to a double and write it into *pResult.
   28833 **
   28834 ** The string z[] is length bytes in length (bytes, not characters) and
   28835 ** uses the encoding enc.  The string is not necessarily zero-terminated.
   28836 **
   28837 ** Return TRUE if the result is a valid real number (or integer) and FALSE
   28838 ** if the string is empty or contains extraneous text.  Valid numbers
   28839 ** are in one of these formats:
   28840 **
   28841 **    [+-]digits[E[+-]digits]
   28842 **    [+-]digits.[digits][E[+-]digits]
   28843 **    [+-].digits[E[+-]digits]
   28844 **
   28845 ** Leading and trailing whitespace is ignored for the purpose of determining
   28846 ** validity.
   28847 **
   28848 ** If some prefix of the input string is a valid number, this routine
   28849 ** returns FALSE but it still converts the prefix and writes the result
   28850 ** into *pResult.
   28851 */
   28852 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
   28853 #ifndef SQLITE_OMIT_FLOATING_POINT
   28854   int incr;
   28855   const char *zEnd = z + length;
   28856   /* sign * significand * (10 ^ (esign * exponent)) */
   28857   int sign = 1;    /* sign of significand */
   28858   i64 s = 0;       /* significand */
   28859   int d = 0;       /* adjust exponent for shifting decimal point */
   28860   int esign = 1;   /* sign of exponent */
   28861   int e = 0;       /* exponent */
   28862   int eValid = 1;  /* True exponent is either not used or is well-formed */
   28863   double result;
   28864   int nDigits = 0;
   28865   int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
   28866 
   28867   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   28868   *pResult = 0.0;   /* Default return value, in case of an error */
   28869 
   28870   if( enc==SQLITE_UTF8 ){
   28871     incr = 1;
   28872   }else{
   28873     int i;
   28874     incr = 2;
   28875     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   28876     for(i=3-enc; i<length && z[i]==0; i+=2){}
   28877     nonNum = i<length;
   28878     zEnd = &z[i^1];
   28879     z += (enc&1);
   28880   }
   28881 
   28882   /* skip leading spaces */
   28883   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   28884   if( z>=zEnd ) return 0;
   28885 
   28886   /* get sign of significand */
   28887   if( *z=='-' ){
   28888     sign = -1;
   28889     z+=incr;
   28890   }else if( *z=='+' ){
   28891     z+=incr;
   28892   }
   28893 
   28894   /* copy max significant digits to significand */
   28895   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   28896     s = s*10 + (*z - '0');
   28897     z+=incr; nDigits++;
   28898   }
   28899 
   28900   /* skip non-significant significand digits
   28901   ** (increase exponent by d to shift decimal left) */
   28902   while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
   28903   if( z>=zEnd ) goto do_atof_calc;
   28904 
   28905   /* if decimal point is present */
   28906   if( *z=='.' ){
   28907     z+=incr;
   28908     /* copy digits from after decimal to significand
   28909     ** (decrease exponent by d to shift decimal right) */
   28910     while( z<zEnd && sqlite3Isdigit(*z) ){
   28911       if( s<((LARGEST_INT64-9)/10) ){
   28912         s = s*10 + (*z - '0');
   28913         d--;
   28914       }
   28915       z+=incr; nDigits++;
   28916     }
   28917   }
   28918   if( z>=zEnd ) goto do_atof_calc;
   28919 
   28920   /* if exponent is present */
   28921   if( *z=='e' || *z=='E' ){
   28922     z+=incr;
   28923     eValid = 0;
   28924 
   28925     /* This branch is needed to avoid a (harmless) buffer overread.  The
   28926     ** special comment alerts the mutation tester that the correct answer
   28927     ** is obtained even if the branch is omitted */
   28928     if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
   28929 
   28930     /* get sign of exponent */
   28931     if( *z=='-' ){
   28932       esign = -1;
   28933       z+=incr;
   28934     }else if( *z=='+' ){
   28935       z+=incr;
   28936     }
   28937     /* copy digits to exponent */
   28938     while( z<zEnd && sqlite3Isdigit(*z) ){
   28939       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
   28940       z+=incr;
   28941       eValid = 1;
   28942     }
   28943   }
   28944 
   28945   /* skip trailing spaces */
   28946   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   28947 
   28948 do_atof_calc:
   28949   /* adjust exponent by d, and update sign */
   28950   e = (e*esign) + d;
   28951   if( e<0 ) {
   28952     esign = -1;
   28953     e *= -1;
   28954   } else {
   28955     esign = 1;
   28956   }
   28957 
   28958   if( s==0 ) {
   28959     /* In the IEEE 754 standard, zero is signed. */
   28960     result = sign<0 ? -(double)0 : (double)0;
   28961   } else {
   28962     /* Attempt to reduce exponent.
   28963     **
   28964     ** Branches that are not required for the correct answer but which only
   28965     ** help to obtain the correct answer faster are marked with special
   28966     ** comments, as a hint to the mutation tester.
   28967     */
   28968     while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
   28969       if( esign>0 ){
   28970         if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
   28971         s *= 10;
   28972       }else{
   28973         if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
   28974         s /= 10;
   28975       }
   28976       e--;
   28977     }
   28978 
   28979     /* adjust the sign of significand */
   28980     s = sign<0 ? -s : s;
   28981 
   28982     if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
   28983       result = (double)s;
   28984     }else{
   28985       /* attempt to handle extremely small/large numbers better */
   28986       if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
   28987         if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
   28988           LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
   28989           if( esign<0 ){
   28990             result = s / scale;
   28991             result /= 1.0e+308;
   28992           }else{
   28993             result = s * scale;
   28994             result *= 1.0e+308;
   28995           }
   28996         }else{ assert( e>=342 );
   28997           if( esign<0 ){
   28998             result = 0.0*s;
   28999           }else{
   29000 #ifdef INFINITY
   29001             result = INFINITY*s;
   29002 #else
   29003             result = 1e308*1e308*s;  /* Infinity */
   29004 #endif
   29005           }
   29006         }
   29007       }else{
   29008         LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
   29009         if( esign<0 ){
   29010           result = s / scale;
   29011         }else{
   29012           result = s * scale;
   29013         }
   29014       }
   29015     }
   29016   }
   29017 
   29018   /* store the result */
   29019   *pResult = result;
   29020 
   29021   /* return true if number and no extra non-whitespace chracters after */
   29022   return z==zEnd && nDigits>0 && eValid && nonNum==0;
   29023 #else
   29024   return !sqlite3Atoi64(z, pResult, length, enc);
   29025 #endif /* SQLITE_OMIT_FLOATING_POINT */
   29026 }
   29027 
   29028 /*
   29029 ** Compare the 19-character string zNum against the text representation
   29030 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
   29031 ** if zNum is less than, equal to, or greater than the string.
   29032 ** Note that zNum must contain exactly 19 characters.
   29033 **
   29034 ** Unlike memcmp() this routine is guaranteed to return the difference
   29035 ** in the values of the last digit if the only difference is in the
   29036 ** last digit.  So, for example,
   29037 **
   29038 **      compare2pow63("9223372036854775800", 1)
   29039 **
   29040 ** will return -8.
   29041 */
   29042 static int compare2pow63(const char *zNum, int incr){
   29043   int c = 0;
   29044   int i;
   29045                     /* 012345678901234567 */
   29046   const char *pow63 = "922337203685477580";
   29047   for(i=0; c==0 && i<18; i++){
   29048     c = (zNum[i*incr]-pow63[i])*10;
   29049   }
   29050   if( c==0 ){
   29051     c = zNum[18*incr] - '8';
   29052     testcase( c==(-1) );
   29053     testcase( c==0 );
   29054     testcase( c==(+1) );
   29055   }
   29056   return c;
   29057 }
   29058 
   29059 /*
   29060 ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
   29061 ** routine does *not* accept hexadecimal notation.
   29062 **
   29063 ** Returns:
   29064 **
   29065 **     0    Successful transformation.  Fits in a 64-bit signed integer.
   29066 **     1    Excess text after the integer value
   29067 **     2    Integer too large for a 64-bit signed integer or is malformed
   29068 **     3    Special case of 9223372036854775808
   29069 **
   29070 ** length is the number of bytes in the string (bytes, not characters).
   29071 ** The string is not necessarily zero-terminated.  The encoding is
   29072 ** given by enc.
   29073 */
   29074 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
   29075   int incr;
   29076   u64 u = 0;
   29077   int neg = 0; /* assume positive */
   29078   int i;
   29079   int c = 0;
   29080   int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
   29081   int rc;          /* Baseline return code */
   29082   const char *zStart;
   29083   const char *zEnd = zNum + length;
   29084   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   29085   if( enc==SQLITE_UTF8 ){
   29086     incr = 1;
   29087   }else{
   29088     incr = 2;
   29089     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   29090     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
   29091     nonNum = i<length;
   29092     zEnd = &zNum[i^1];
   29093     zNum += (enc&1);
   29094   }
   29095   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
   29096   if( zNum<zEnd ){
   29097     if( *zNum=='-' ){
   29098       neg = 1;
   29099       zNum+=incr;
   29100     }else if( *zNum=='+' ){
   29101       zNum+=incr;
   29102     }
   29103   }
   29104   zStart = zNum;
   29105   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
   29106   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
   29107     u = u*10 + c - '0';
   29108   }
   29109   if( u>LARGEST_INT64 ){
   29110     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
   29111   }else if( neg ){
   29112     *pNum = -(i64)u;
   29113   }else{
   29114     *pNum = (i64)u;
   29115   }
   29116   testcase( i==18 );
   29117   testcase( i==19 );
   29118   testcase( i==20 );
   29119   if( &zNum[i]<zEnd              /* Extra bytes at the end */
   29120    || (i==0 && zStart==zNum)     /* No digits */
   29121    || nonNum                     /* UTF16 with high-order bytes non-zero */
   29122   ){
   29123     rc = 1;
   29124   }else{
   29125     rc = 0;
   29126   }
   29127   if( i>19*incr ){                /* Too many digits */
   29128     /* zNum is empty or contains non-numeric text or is longer
   29129     ** than 19 digits (thus guaranteeing that it is too large) */
   29130     return 2;
   29131   }else if( i<19*incr ){
   29132     /* Less than 19 digits, so we know that it fits in 64 bits */
   29133     assert( u<=LARGEST_INT64 );
   29134     return rc;
   29135   }else{
   29136     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
   29137     c = compare2pow63(zNum, incr);
   29138     if( c<0 ){
   29139       /* zNum is less than 9223372036854775808 so it fits */
   29140       assert( u<=LARGEST_INT64 );
   29141       return rc;
   29142     }else if( c>0 ){
   29143       /* zNum is greater than 9223372036854775808 so it overflows */
   29144       return 2;
   29145     }else{
   29146       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
   29147       ** special case 2 overflow if positive */
   29148       assert( u-1==LARGEST_INT64 );
   29149       return neg ? rc : 3;
   29150     }
   29151   }
   29152 }
   29153 
   29154 /*
   29155 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
   29156 ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
   29157 ** whereas sqlite3Atoi64() does not.
   29158 **
   29159 ** Returns:
   29160 **
   29161 **     0    Successful transformation.  Fits in a 64-bit signed integer.
   29162 **     1    Excess text after the integer value
   29163 **     2    Integer too large for a 64-bit signed integer or is malformed
   29164 **     3    Special case of 9223372036854775808
   29165 */
   29166 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
   29167 #ifndef SQLITE_OMIT_HEX_INTEGER
   29168   if( z[0]=='0'
   29169    && (z[1]=='x' || z[1]=='X')
   29170   ){
   29171     u64 u = 0;
   29172     int i, k;
   29173     for(i=2; z[i]=='0'; i++){}
   29174     for(k=i; sqlite3Isxdigit(z[k]); k++){
   29175       u = u*16 + sqlite3HexToInt(z[k]);
   29176     }
   29177     memcpy(pOut, &u, 8);
   29178     return (z[k]==0 && k-i<=16) ? 0 : 2;
   29179   }else
   29180 #endif /* SQLITE_OMIT_HEX_INTEGER */
   29181   {
   29182     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
   29183   }
   29184 }
   29185 
   29186 /*
   29187 ** If zNum represents an integer that will fit in 32-bits, then set
   29188 ** *pValue to that integer and return true.  Otherwise return false.
   29189 **
   29190 ** This routine accepts both decimal and hexadecimal notation for integers.
   29191 **
   29192 ** Any non-numeric characters that following zNum are ignored.
   29193 ** This is different from sqlite3Atoi64() which requires the
   29194 ** input number to be zero-terminated.
   29195 */
   29196 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
   29197   sqlite_int64 v = 0;
   29198   int i, c;
   29199   int neg = 0;
   29200   if( zNum[0]=='-' ){
   29201     neg = 1;
   29202     zNum++;
   29203   }else if( zNum[0]=='+' ){
   29204     zNum++;
   29205   }
   29206 #ifndef SQLITE_OMIT_HEX_INTEGER
   29207   else if( zNum[0]=='0'
   29208         && (zNum[1]=='x' || zNum[1]=='X')
   29209         && sqlite3Isxdigit(zNum[2])
   29210   ){
   29211     u32 u = 0;
   29212     zNum += 2;
   29213     while( zNum[0]=='0' ) zNum++;
   29214     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
   29215       u = u*16 + sqlite3HexToInt(zNum[i]);
   29216     }
   29217     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
   29218       memcpy(pValue, &u, 4);
   29219       return 1;
   29220     }else{
   29221       return 0;
   29222     }
   29223   }
   29224 #endif
   29225   if( !sqlite3Isdigit(zNum[0]) ) return 0;
   29226   while( zNum[0]=='0' ) zNum++;
   29227   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
   29228     v = v*10 + c;
   29229   }
   29230 
   29231   /* The longest decimal representation of a 32 bit integer is 10 digits:
   29232   **
   29233   **             1234567890
   29234   **     2^31 -> 2147483648
   29235   */
   29236   testcase( i==10 );
   29237   if( i>10 ){
   29238     return 0;
   29239   }
   29240   testcase( v-neg==2147483647 );
   29241   if( v-neg>2147483647 ){
   29242     return 0;
   29243   }
   29244   if( neg ){
   29245     v = -v;
   29246   }
   29247   *pValue = (int)v;
   29248   return 1;
   29249 }
   29250 
   29251 /*
   29252 ** Return a 32-bit integer value extracted from a string.  If the
   29253 ** string is not an integer, just return 0.
   29254 */
   29255 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
   29256   int x = 0;
   29257   if( z ) sqlite3GetInt32(z, &x);
   29258   return x;
   29259 }
   29260 
   29261 /*
   29262 ** The variable-length integer encoding is as follows:
   29263 **
   29264 ** KEY:
   29265 **         A = 0xxxxxxx    7 bits of data and one flag bit
   29266 **         B = 1xxxxxxx    7 bits of data and one flag bit
   29267 **         C = xxxxxxxx    8 bits of data
   29268 **
   29269 **  7 bits - A
   29270 ** 14 bits - BA
   29271 ** 21 bits - BBA
   29272 ** 28 bits - BBBA
   29273 ** 35 bits - BBBBA
   29274 ** 42 bits - BBBBBA
   29275 ** 49 bits - BBBBBBA
   29276 ** 56 bits - BBBBBBBA
   29277 ** 64 bits - BBBBBBBBC
   29278 */
   29279 
   29280 /*
   29281 ** Write a 64-bit variable-length integer to memory starting at p[0].
   29282 ** The length of data write will be between 1 and 9 bytes.  The number
   29283 ** of bytes written is returned.
   29284 **
   29285 ** A variable-length integer consists of the lower 7 bits of each byte
   29286 ** for all bytes that have the 8th bit set and one byte with the 8th
   29287 ** bit clear.  Except, if we get to the 9th byte, it stores the full
   29288 ** 8 bits and is the last byte.
   29289 */
   29290 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
   29291   int i, j, n;
   29292   u8 buf[10];
   29293   if( v & (((u64)0xff000000)<<32) ){
   29294     p[8] = (u8)v;
   29295     v >>= 8;
   29296     for(i=7; i>=0; i--){
   29297       p[i] = (u8)((v & 0x7f) | 0x80);
   29298       v >>= 7;
   29299     }
   29300     return 9;
   29301   }
   29302   n = 0;
   29303   do{
   29304     buf[n++] = (u8)((v & 0x7f) | 0x80);
   29305     v >>= 7;
   29306   }while( v!=0 );
   29307   buf[0] &= 0x7f;
   29308   assert( n<=9 );
   29309   for(i=0, j=n-1; j>=0; j--, i++){
   29310     p[i] = buf[j];
   29311   }
   29312   return n;
   29313 }
   29314 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
   29315   if( v<=0x7f ){
   29316     p[0] = v&0x7f;
   29317     return 1;
   29318   }
   29319   if( v<=0x3fff ){
   29320     p[0] = ((v>>7)&0x7f)|0x80;
   29321     p[1] = v&0x7f;
   29322     return 2;
   29323   }
   29324   return putVarint64(p,v);
   29325 }
   29326 
   29327 /*
   29328 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
   29329 ** are defined here rather than simply putting the constant expressions
   29330 ** inline in order to work around bugs in the RVT compiler.
   29331 **
   29332 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
   29333 **
   29334 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
   29335 */
   29336 #define SLOT_2_0     0x001fc07f
   29337 #define SLOT_4_2_0   0xf01fc07f
   29338 
   29339 
   29340 /*
   29341 ** Read a 64-bit variable-length integer from memory starting at p[0].
   29342 ** Return the number of bytes read.  The value is stored in *v.
   29343 */
   29344 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
   29345   u32 a,b,s;
   29346 
   29347   a = *p;
   29348   /* a: p0 (unmasked) */
   29349   if (!(a&0x80))
   29350   {
   29351     *v = a;
   29352     return 1;
   29353   }
   29354 
   29355   p++;
   29356   b = *p;
   29357   /* b: p1 (unmasked) */
   29358   if (!(b&0x80))
   29359   {
   29360     a &= 0x7f;
   29361     a = a<<7;
   29362     a |= b;
   29363     *v = a;
   29364     return 2;
   29365   }
   29366 
   29367   /* Verify that constants are precomputed correctly */
   29368   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
   29369   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
   29370 
   29371   p++;
   29372   a = a<<14;
   29373   a |= *p;
   29374   /* a: p0<<14 | p2 (unmasked) */
   29375   if (!(a&0x80))
   29376   {
   29377     a &= SLOT_2_0;
   29378     b &= 0x7f;
   29379     b = b<<7;
   29380     a |= b;
   29381     *v = a;
   29382     return 3;
   29383   }
   29384 
   29385   /* CSE1 from below */
   29386   a &= SLOT_2_0;
   29387   p++;
   29388   b = b<<14;
   29389   b |= *p;
   29390   /* b: p1<<14 | p3 (unmasked) */
   29391   if (!(b&0x80))
   29392   {
   29393     b &= SLOT_2_0;
   29394     /* moved CSE1 up */
   29395     /* a &= (0x7f<<14)|(0x7f); */
   29396     a = a<<7;
   29397     a |= b;
   29398     *v = a;
   29399     return 4;
   29400   }
   29401 
   29402   /* a: p0<<14 | p2 (masked) */
   29403   /* b: p1<<14 | p3 (unmasked) */
   29404   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   29405   /* moved CSE1 up */
   29406   /* a &= (0x7f<<14)|(0x7f); */
   29407   b &= SLOT_2_0;
   29408   s = a;
   29409   /* s: p0<<14 | p2 (masked) */
   29410 
   29411   p++;
   29412   a = a<<14;
   29413   a |= *p;
   29414   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   29415   if (!(a&0x80))
   29416   {
   29417     /* we can skip these cause they were (effectively) done above
   29418     ** while calculating s */
   29419     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   29420     /* b &= (0x7f<<14)|(0x7f); */
   29421     b = b<<7;
   29422     a |= b;
   29423     s = s>>18;
   29424     *v = ((u64)s)<<32 | a;
   29425     return 5;
   29426   }
   29427 
   29428   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   29429   s = s<<7;
   29430   s |= b;
   29431   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   29432 
   29433   p++;
   29434   b = b<<14;
   29435   b |= *p;
   29436   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
   29437   if (!(b&0x80))
   29438   {
   29439     /* we can skip this cause it was (effectively) done above in calc'ing s */
   29440     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   29441     a &= SLOT_2_0;
   29442     a = a<<7;
   29443     a |= b;
   29444     s = s>>18;
   29445     *v = ((u64)s)<<32 | a;
   29446     return 6;
   29447   }
   29448 
   29449   p++;
   29450   a = a<<14;
   29451   a |= *p;
   29452   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
   29453   if (!(a&0x80))
   29454   {
   29455     a &= SLOT_4_2_0;
   29456     b &= SLOT_2_0;
   29457     b = b<<7;
   29458     a |= b;
   29459     s = s>>11;
   29460     *v = ((u64)s)<<32 | a;
   29461     return 7;
   29462   }
   29463 
   29464   /* CSE2 from below */
   29465   a &= SLOT_2_0;
   29466   p++;
   29467   b = b<<14;
   29468   b |= *p;
   29469   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
   29470   if (!(b&0x80))
   29471   {
   29472     b &= SLOT_4_2_0;
   29473     /* moved CSE2 up */
   29474     /* a &= (0x7f<<14)|(0x7f); */
   29475     a = a<<7;
   29476     a |= b;
   29477     s = s>>4;
   29478     *v = ((u64)s)<<32 | a;
   29479     return 8;
   29480   }
   29481 
   29482   p++;
   29483   a = a<<15;
   29484   a |= *p;
   29485   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
   29486 
   29487   /* moved CSE2 up */
   29488   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
   29489   b &= SLOT_2_0;
   29490   b = b<<8;
   29491   a |= b;
   29492 
   29493   s = s<<4;
   29494   b = p[-4];
   29495   b &= 0x7f;
   29496   b = b>>3;
   29497   s |= b;
   29498 
   29499   *v = ((u64)s)<<32 | a;
   29500 
   29501   return 9;
   29502 }
   29503 
   29504 /*
   29505 ** Read a 32-bit variable-length integer from memory starting at p[0].
   29506 ** Return the number of bytes read.  The value is stored in *v.
   29507 **
   29508 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
   29509 ** integer, then set *v to 0xffffffff.
   29510 **
   29511 ** A MACRO version, getVarint32, is provided which inlines the
   29512 ** single-byte case.  All code should use the MACRO version as
   29513 ** this function assumes the single-byte case has already been handled.
   29514 */
   29515 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
   29516   u32 a,b;
   29517 
   29518   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
   29519   ** by the getVarin32() macro */
   29520   a = *p;
   29521   /* a: p0 (unmasked) */
   29522 #ifndef getVarint32
   29523   if (!(a&0x80))
   29524   {
   29525     /* Values between 0 and 127 */
   29526     *v = a;
   29527     return 1;
   29528   }
   29529 #endif
   29530 
   29531   /* The 2-byte case */
   29532   p++;
   29533   b = *p;
   29534   /* b: p1 (unmasked) */
   29535   if (!(b&0x80))
   29536   {
   29537     /* Values between 128 and 16383 */
   29538     a &= 0x7f;
   29539     a = a<<7;
   29540     *v = a | b;
   29541     return 2;
   29542   }
   29543 
   29544   /* The 3-byte case */
   29545   p++;
   29546   a = a<<14;
   29547   a |= *p;
   29548   /* a: p0<<14 | p2 (unmasked) */
   29549   if (!(a&0x80))
   29550   {
   29551     /* Values between 16384 and 2097151 */
   29552     a &= (0x7f<<14)|(0x7f);
   29553     b &= 0x7f;
   29554     b = b<<7;
   29555     *v = a | b;
   29556     return 3;
   29557   }
   29558 
   29559   /* A 32-bit varint is used to store size information in btrees.
   29560   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
   29561   ** A 3-byte varint is sufficient, for example, to record the size
   29562   ** of a 1048569-byte BLOB or string.
   29563   **
   29564   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
   29565   ** rare larger cases can be handled by the slower 64-bit varint
   29566   ** routine.
   29567   */
   29568 #if 1
   29569   {
   29570     u64 v64;
   29571     u8 n;
   29572 
   29573     p -= 2;
   29574     n = sqlite3GetVarint(p, &v64);
   29575     assert( n>3 && n<=9 );
   29576     if( (v64 & SQLITE_MAX_U32)!=v64 ){
   29577       *v = 0xffffffff;
   29578     }else{
   29579       *v = (u32)v64;
   29580     }
   29581     return n;
   29582   }
   29583 
   29584 #else
   29585   /* For following code (kept for historical record only) shows an
   29586   ** unrolling for the 3- and 4-byte varint cases.  This code is
   29587   ** slightly faster, but it is also larger and much harder to test.
   29588   */
   29589   p++;
   29590   b = b<<14;
   29591   b |= *p;
   29592   /* b: p1<<14 | p3 (unmasked) */
   29593   if (!(b&0x80))
   29594   {
   29595     /* Values between 2097152 and 268435455 */
   29596     b &= (0x7f<<14)|(0x7f);
   29597     a &= (0x7f<<14)|(0x7f);
   29598     a = a<<7;
   29599     *v = a | b;
   29600     return 4;
   29601   }
   29602 
   29603   p++;
   29604   a = a<<14;
   29605   a |= *p;
   29606   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   29607   if (!(a&0x80))
   29608   {
   29609     /* Values  between 268435456 and 34359738367 */
   29610     a &= SLOT_4_2_0;
   29611     b &= SLOT_4_2_0;
   29612     b = b<<7;
   29613     *v = a | b;
   29614     return 5;
   29615   }
   29616 
   29617   /* We can only reach this point when reading a corrupt database
   29618   ** file.  In that case we are not in any hurry.  Use the (relatively
   29619   ** slow) general-purpose sqlite3GetVarint() routine to extract the
   29620   ** value. */
   29621   {
   29622     u64 v64;
   29623     u8 n;
   29624 
   29625     p -= 4;
   29626     n = sqlite3GetVarint(p, &v64);
   29627     assert( n>5 && n<=9 );
   29628     *v = (u32)v64;
   29629     return n;
   29630   }
   29631 #endif
   29632 }
   29633 
   29634 /*
   29635 ** Return the number of bytes that will be needed to store the given
   29636 ** 64-bit integer.
   29637 */
   29638 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
   29639   int i;
   29640   for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
   29641   return i;
   29642 }
   29643 
   29644 
   29645 /*
   29646 ** Read or write a four-byte big-endian integer value.
   29647 */
   29648 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
   29649 #if SQLITE_BYTEORDER==4321
   29650   u32 x;
   29651   memcpy(&x,p,4);
   29652   return x;
   29653 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
   29654   u32 x;
   29655   memcpy(&x,p,4);
   29656   return __builtin_bswap32(x);
   29657 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   29658   u32 x;
   29659   memcpy(&x,p,4);
   29660   return _byteswap_ulong(x);
   29661 #else
   29662   testcase( p[0]&0x80 );
   29663   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
   29664 #endif
   29665 }
   29666 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
   29667 #if SQLITE_BYTEORDER==4321
   29668   memcpy(p,&v,4);
   29669 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
   29670   u32 x = __builtin_bswap32(v);
   29671   memcpy(p,&x,4);
   29672 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   29673   u32 x = _byteswap_ulong(v);
   29674   memcpy(p,&x,4);
   29675 #else
   29676   p[0] = (u8)(v>>24);
   29677   p[1] = (u8)(v>>16);
   29678   p[2] = (u8)(v>>8);
   29679   p[3] = (u8)v;
   29680 #endif
   29681 }
   29682 
   29683 
   29684 
   29685 /*
   29686 ** Translate a single byte of Hex into an integer.
   29687 ** This routine only works if h really is a valid hexadecimal
   29688 ** character:  0..9a..fA..F
   29689 */
   29690 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
   29691   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
   29692 #ifdef SQLITE_ASCII
   29693   h += 9*(1&(h>>6));
   29694 #endif
   29695 #ifdef SQLITE_EBCDIC
   29696   h += 9*(1&~(h>>4));
   29697 #endif
   29698   return (u8)(h & 0xf);
   29699 }
   29700 
   29701 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
   29702 /*
   29703 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
   29704 ** value.  Return a pointer to its binary value.  Space to hold the
   29705 ** binary value has been obtained from malloc and must be freed by
   29706 ** the calling routine.
   29707 */
   29708 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
   29709   char *zBlob;
   29710   int i;
   29711 
   29712   zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
   29713   n--;
   29714   if( zBlob ){
   29715     for(i=0; i<n; i+=2){
   29716       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
   29717     }
   29718     zBlob[i/2] = 0;
   29719   }
   29720   return zBlob;
   29721 }
   29722 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
   29723 
   29724 /*
   29725 ** Log an error that is an API call on a connection pointer that should
   29726 ** not have been used.  The "type" of connection pointer is given as the
   29727 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
   29728 */
   29729 static void logBadConnection(const char *zType){
   29730   sqlite3_log(SQLITE_MISUSE,
   29731      "API call with %s database connection pointer",
   29732      zType
   29733   );
   29734 }
   29735 
   29736 /*
   29737 ** Check to make sure we have a valid db pointer.  This test is not
   29738 ** foolproof but it does provide some measure of protection against
   29739 ** misuse of the interface such as passing in db pointers that are
   29740 ** NULL or which have been previously closed.  If this routine returns
   29741 ** 1 it means that the db pointer is valid and 0 if it should not be
   29742 ** dereferenced for any reason.  The calling function should invoke
   29743 ** SQLITE_MISUSE immediately.
   29744 **
   29745 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
   29746 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
   29747 ** open properly and is not fit for general use but which can be
   29748 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
   29749 */
   29750 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
   29751   u32 magic;
   29752   if( db==0 ){
   29753     logBadConnection("NULL");
   29754     return 0;
   29755   }
   29756   magic = db->magic;
   29757   if( magic!=SQLITE_MAGIC_OPEN ){
   29758     if( sqlite3SafetyCheckSickOrOk(db) ){
   29759       testcase( sqlite3GlobalConfig.xLog!=0 );
   29760       logBadConnection("unopened");
   29761     }
   29762     return 0;
   29763   }else{
   29764     return 1;
   29765   }
   29766 }
   29767 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
   29768   u32 magic;
   29769   magic = db->magic;
   29770   if( magic!=SQLITE_MAGIC_SICK &&
   29771       magic!=SQLITE_MAGIC_OPEN &&
   29772       magic!=SQLITE_MAGIC_BUSY ){
   29773     testcase( sqlite3GlobalConfig.xLog!=0 );
   29774     logBadConnection("invalid");
   29775     return 0;
   29776   }else{
   29777     return 1;
   29778   }
   29779 }
   29780 
   29781 /*
   29782 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
   29783 ** the other 64-bit signed integer at *pA and store the result in *pA.
   29784 ** Return 0 on success.  Or if the operation would have resulted in an
   29785 ** overflow, leave *pA unchanged and return 1.
   29786 */
   29787 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
   29788 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
   29789   return __builtin_add_overflow(*pA, iB, pA);
   29790 #else
   29791   i64 iA = *pA;
   29792   testcase( iA==0 ); testcase( iA==1 );
   29793   testcase( iB==-1 ); testcase( iB==0 );
   29794   if( iB>=0 ){
   29795     testcase( iA>0 && LARGEST_INT64 - iA == iB );
   29796     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
   29797     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
   29798   }else{
   29799     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
   29800     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
   29801     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
   29802   }
   29803   *pA += iB;
   29804   return 0;
   29805 #endif
   29806 }
   29807 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
   29808 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
   29809   return __builtin_sub_overflow(*pA, iB, pA);
   29810 #else
   29811   testcase( iB==SMALLEST_INT64+1 );
   29812   if( iB==SMALLEST_INT64 ){
   29813     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
   29814     if( (*pA)>=0 ) return 1;
   29815     *pA -= iB;
   29816     return 0;
   29817   }else{
   29818     return sqlite3AddInt64(pA, -iB);
   29819   }
   29820 #endif
   29821 }
   29822 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
   29823 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
   29824   return __builtin_mul_overflow(*pA, iB, pA);
   29825 #else
   29826   i64 iA = *pA;
   29827   if( iB>0 ){
   29828     if( iA>LARGEST_INT64/iB ) return 1;
   29829     if( iA<SMALLEST_INT64/iB ) return 1;
   29830   }else if( iB<0 ){
   29831     if( iA>0 ){
   29832       if( iB<SMALLEST_INT64/iA ) return 1;
   29833     }else if( iA<0 ){
   29834       if( iB==SMALLEST_INT64 ) return 1;
   29835       if( iA==SMALLEST_INT64 ) return 1;
   29836       if( -iA>LARGEST_INT64/-iB ) return 1;
   29837     }
   29838   }
   29839   *pA = iA*iB;
   29840   return 0;
   29841 #endif
   29842 }
   29843 
   29844 /*
   29845 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
   29846 ** if the integer has a value of -2147483648, return +2147483647
   29847 */
   29848 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
   29849   if( x>=0 ) return x;
   29850   if( x==(int)0x80000000 ) return 0x7fffffff;
   29851   return -x;
   29852 }
   29853 
   29854 #ifdef SQLITE_ENABLE_8_3_NAMES
   29855 /*
   29856 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
   29857 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
   29858 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
   29859 ** three characters, then shorten the suffix on z[] to be the last three
   29860 ** characters of the original suffix.
   29861 **
   29862 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
   29863 ** do the suffix shortening regardless of URI parameter.
   29864 **
   29865 ** Examples:
   29866 **
   29867 **     test.db-journal    =>   test.nal
   29868 **     test.db-wal        =>   test.wal
   29869 **     test.db-shm        =>   test.shm
   29870 **     test.db-mj7f3319fa =>   test.9fa
   29871 */
   29872 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
   29873 #if SQLITE_ENABLE_8_3_NAMES<2
   29874   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
   29875 #endif
   29876   {
   29877     int i, sz;
   29878     sz = sqlite3Strlen30(z);
   29879     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
   29880     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
   29881   }
   29882 }
   29883 #endif
   29884 
   29885 /*
   29886 ** Find (an approximate) sum of two LogEst values.  This computation is
   29887 ** not a simple "+" operator because LogEst is stored as a logarithmic
   29888 ** value.
   29889 **
   29890 */
   29891 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
   29892   static const unsigned char x[] = {
   29893      10, 10,                         /* 0,1 */
   29894       9, 9,                          /* 2,3 */
   29895       8, 8,                          /* 4,5 */
   29896       7, 7, 7,                       /* 6,7,8 */
   29897       6, 6, 6,                       /* 9,10,11 */
   29898       5, 5, 5,                       /* 12-14 */
   29899       4, 4, 4, 4,                    /* 15-18 */
   29900       3, 3, 3, 3, 3, 3,              /* 19-24 */
   29901       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
   29902   };
   29903   if( a>=b ){
   29904     if( a>b+49 ) return a;
   29905     if( a>b+31 ) return a+1;
   29906     return a+x[a-b];
   29907   }else{
   29908     if( b>a+49 ) return b;
   29909     if( b>a+31 ) return b+1;
   29910     return b+x[b-a];
   29911   }
   29912 }
   29913 
   29914 /*
   29915 ** Convert an integer into a LogEst.  In other words, compute an
   29916 ** approximation for 10*log2(x).
   29917 */
   29918 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
   29919   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
   29920   LogEst y = 40;
   29921   if( x<8 ){
   29922     if( x<2 ) return 0;
   29923     while( x<8 ){  y -= 10; x <<= 1; }
   29924   }else{
   29925 #if GCC_VERSION>=5004000
   29926     int i = 60 - __builtin_clzll(x);
   29927     y += i*10;
   29928     x >>= i;
   29929 #else
   29930     while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
   29931     while( x>15 ){  y += 10; x >>= 1; }
   29932 #endif
   29933   }
   29934   return a[x&7] + y - 10;
   29935 }
   29936 
   29937 #ifndef SQLITE_OMIT_VIRTUALTABLE
   29938 /*
   29939 ** Convert a double into a LogEst
   29940 ** In other words, compute an approximation for 10*log2(x).
   29941 */
   29942 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
   29943   u64 a;
   29944   LogEst e;
   29945   assert( sizeof(x)==8 && sizeof(a)==8 );
   29946   if( x<=1 ) return 0;
   29947   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
   29948   memcpy(&a, &x, 8);
   29949   e = (a>>52) - 1022;
   29950   return e*10;
   29951 }
   29952 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   29953 
   29954 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
   29955     defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
   29956     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
   29957 /*
   29958 ** Convert a LogEst into an integer.
   29959 **
   29960 ** Note that this routine is only used when one or more of various
   29961 ** non-standard compile-time options is enabled.
   29962 */
   29963 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
   29964   u64 n;
   29965   n = x%10;
   29966   x /= 10;
   29967   if( n>=5 ) n -= 2;
   29968   else if( n>=1 ) n -= 1;
   29969 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
   29970     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
   29971   if( x>60 ) return (u64)LARGEST_INT64;
   29972 #else
   29973   /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
   29974   ** possible to this routine is 310, resulting in a maximum x of 31 */
   29975   assert( x<=60 );
   29976 #endif
   29977   return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
   29978 }
   29979 #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
   29980 
   29981 /*
   29982 ** Add a new name/number pair to a VList.  This might require that the
   29983 ** VList object be reallocated, so return the new VList.  If an OOM
   29984 ** error occurs, the original VList returned and the
   29985 ** db->mallocFailed flag is set.
   29986 **
   29987 ** A VList is really just an array of integers.  To destroy a VList,
   29988 ** simply pass it to sqlite3DbFree().
   29989 **
   29990 ** The first integer is the number of integers allocated for the whole
   29991 ** VList.  The second integer is the number of integers actually used.
   29992 ** Each name/number pair is encoded by subsequent groups of 3 or more
   29993 ** integers.
   29994 **
   29995 ** Each name/number pair starts with two integers which are the numeric
   29996 ** value for the pair and the size of the name/number pair, respectively.
   29997 ** The text name overlays one or more following integers.  The text name
   29998 ** is always zero-terminated.
   29999 **
   30000 ** Conceptually:
   30001 **
   30002 **    struct VList {
   30003 **      int nAlloc;   // Number of allocated slots
   30004 **      int nUsed;    // Number of used slots
   30005 **      struct VListEntry {
   30006 **        int iValue;    // Value for this entry
   30007 **        int nSlot;     // Slots used by this entry
   30008 **        // ... variable name goes here
   30009 **      } a[0];
   30010 **    }
   30011 **
   30012 ** During code generation, pointers to the variable names within the
   30013 ** VList are taken.  When that happens, nAlloc is set to zero as an
   30014 ** indication that the VList may never again be enlarged, since the
   30015 ** accompanying realloc() would invalidate the pointers.
   30016 */
   30017 SQLITE_PRIVATE VList *sqlite3VListAdd(
   30018   sqlite3 *db,           /* The database connection used for malloc() */
   30019   VList *pIn,            /* The input VList.  Might be NULL */
   30020   const char *zName,     /* Name of symbol to add */
   30021   int nName,             /* Bytes of text in zName */
   30022   int iVal               /* Value to associate with zName */
   30023 ){
   30024   int nInt;              /* number of sizeof(int) objects needed for zName */
   30025   char *z;               /* Pointer to where zName will be stored */
   30026   int i;                 /* Index in pIn[] where zName is stored */
   30027 
   30028   nInt = nName/4 + 3;
   30029   assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
   30030   if( pIn==0 || pIn[1]+nInt > pIn[0] ){
   30031     /* Enlarge the allocation */
   30032     int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
   30033     VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
   30034     if( pOut==0 ) return pIn;
   30035     if( pIn==0 ) pOut[1] = 2;
   30036     pIn = pOut;
   30037     pIn[0] = nAlloc;
   30038   }
   30039   i = pIn[1];
   30040   pIn[i] = iVal;
   30041   pIn[i+1] = nInt;
   30042   z = (char*)&pIn[i+2];
   30043   pIn[1] = i+nInt;
   30044   assert( pIn[1]<=pIn[0] );
   30045   memcpy(z, zName, nName);
   30046   z[nName] = 0;
   30047   return pIn;
   30048 }
   30049 
   30050 /*
   30051 ** Return a pointer to the name of a variable in the given VList that
   30052 ** has the value iVal.  Or return a NULL if there is no such variable in
   30053 ** the list
   30054 */
   30055 SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
   30056   int i, mx;
   30057   if( pIn==0 ) return 0;
   30058   mx = pIn[1];
   30059   i = 2;
   30060   do{
   30061     if( pIn[i]==iVal ) return (char*)&pIn[i+2];
   30062     i += pIn[i+1];
   30063   }while( i<mx );
   30064   return 0;
   30065 }
   30066 
   30067 /*
   30068 ** Return the number of the variable named zName, if it is in VList.
   30069 ** or return 0 if there is no such variable.
   30070 */
   30071 SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
   30072   int i, mx;
   30073   if( pIn==0 ) return 0;
   30074   mx = pIn[1];
   30075   i = 2;
   30076   do{
   30077     const char *z = (const char*)&pIn[i+2];
   30078     if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
   30079     i += pIn[i+1];
   30080   }while( i<mx );
   30081   return 0;
   30082 }
   30083 
   30084 /************** End of util.c ************************************************/
   30085 /************** Begin file hash.c ********************************************/
   30086 /*
   30087 ** 2001 September 22
   30088 **
   30089 ** The author disclaims copyright to this source code.  In place of
   30090 ** a legal notice, here is a blessing:
   30091 **
   30092 **    May you do good and not evil.
   30093 **    May you find forgiveness for yourself and forgive others.
   30094 **    May you share freely, never taking more than you give.
   30095 **
   30096 *************************************************************************
   30097 ** This is the implementation of generic hash-tables
   30098 ** used in SQLite.
   30099 */
   30100 /* #include "sqliteInt.h" */
   30101 /* #include <assert.h> */
   30102 
   30103 /* Turn bulk memory into a hash table object by initializing the
   30104 ** fields of the Hash structure.
   30105 **
   30106 ** "pNew" is a pointer to the hash table that is to be initialized.
   30107 */
   30108 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
   30109   assert( pNew!=0 );
   30110   pNew->first = 0;
   30111   pNew->count = 0;
   30112   pNew->htsize = 0;
   30113   pNew->ht = 0;
   30114 }
   30115 
   30116 /* Remove all entries from a hash table.  Reclaim all memory.
   30117 ** Call this routine to delete a hash table or to reset a hash table
   30118 ** to the empty state.
   30119 */
   30120 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
   30121   HashElem *elem;         /* For looping over all elements of the table */
   30122 
   30123   assert( pH!=0 );
   30124   elem = pH->first;
   30125   pH->first = 0;
   30126   sqlite3_free(pH->ht);
   30127   pH->ht = 0;
   30128   pH->htsize = 0;
   30129   while( elem ){
   30130     HashElem *next_elem = elem->next;
   30131     sqlite3_free(elem);
   30132     elem = next_elem;
   30133   }
   30134   pH->count = 0;
   30135 }
   30136 
   30137 /*
   30138 ** The hashing function.
   30139 */
   30140 static unsigned int strHash(const char *z){
   30141   unsigned int h = 0;
   30142   unsigned char c;
   30143   while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
   30144     /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).
   30145     ** 0x9e3779b1 is 2654435761 which is the closest prime number to
   30146     ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
   30147     h += sqlite3UpperToLower[c];
   30148     h *= 0x9e3779b1;
   30149   }
   30150   return h;
   30151 }
   30152 
   30153 
   30154 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
   30155 ** insert pNew into the pEntry hash bucket.
   30156 */
   30157 static void insertElement(
   30158   Hash *pH,              /* The complete hash table */
   30159   struct _ht *pEntry,    /* The entry into which pNew is inserted */
   30160   HashElem *pNew         /* The element to be inserted */
   30161 ){
   30162   HashElem *pHead;       /* First element already in pEntry */
   30163   if( pEntry ){
   30164     pHead = pEntry->count ? pEntry->chain : 0;
   30165     pEntry->count++;
   30166     pEntry->chain = pNew;
   30167   }else{
   30168     pHead = 0;
   30169   }
   30170   if( pHead ){
   30171     pNew->next = pHead;
   30172     pNew->prev = pHead->prev;
   30173     if( pHead->prev ){ pHead->prev->next = pNew; }
   30174     else             { pH->first = pNew; }
   30175     pHead->prev = pNew;
   30176   }else{
   30177     pNew->next = pH->first;
   30178     if( pH->first ){ pH->first->prev = pNew; }
   30179     pNew->prev = 0;
   30180     pH->first = pNew;
   30181   }
   30182 }
   30183 
   30184 
   30185 /* Resize the hash table so that it cantains "new_size" buckets.
   30186 **
   30187 ** The hash table might fail to resize if sqlite3_malloc() fails or
   30188 ** if the new size is the same as the prior size.
   30189 ** Return TRUE if the resize occurs and false if not.
   30190 */
   30191 static int rehash(Hash *pH, unsigned int new_size){
   30192   struct _ht *new_ht;            /* The new hash table */
   30193   HashElem *elem, *next_elem;    /* For looping over existing elements */
   30194 
   30195 #if SQLITE_MALLOC_SOFT_LIMIT>0
   30196   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
   30197     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
   30198   }
   30199   if( new_size==pH->htsize ) return 0;
   30200 #endif
   30201 
   30202   /* The inability to allocates space for a larger hash table is
   30203   ** a performance hit but it is not a fatal error.  So mark the
   30204   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
   30205   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
   30206   ** only zeroes the requested number of bytes whereas this module will
   30207   ** use the actual amount of space allocated for the hash table (which
   30208   ** may be larger than the requested amount).
   30209   */
   30210   sqlite3BeginBenignMalloc();
   30211   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
   30212   sqlite3EndBenignMalloc();
   30213 
   30214   if( new_ht==0 ) return 0;
   30215   sqlite3_free(pH->ht);
   30216   pH->ht = new_ht;
   30217   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
   30218   memset(new_ht, 0, new_size*sizeof(struct _ht));
   30219   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   30220     unsigned int h = strHash(elem->pKey) % new_size;
   30221     next_elem = elem->next;
   30222     insertElement(pH, &new_ht[h], elem);
   30223   }
   30224   return 1;
   30225 }
   30226 
   30227 /* This function (for internal use only) locates an element in an
   30228 ** hash table that matches the given key.  If no element is found,
   30229 ** a pointer to a static null element with HashElem.data==0 is returned.
   30230 ** If pH is not NULL, then the hash for this key is written to *pH.
   30231 */
   30232 static HashElem *findElementWithHash(
   30233   const Hash *pH,     /* The pH to be searched */
   30234   const char *pKey,   /* The key we are searching for */
   30235   unsigned int *pHash /* Write the hash value here */
   30236 ){
   30237   HashElem *elem;                /* Used to loop thru the element list */
   30238   int count;                     /* Number of elements left to test */
   30239   unsigned int h;                /* The computed hash */
   30240   static HashElem nullElement = { 0, 0, 0, 0 };
   30241 
   30242   if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
   30243     struct _ht *pEntry;
   30244     h = strHash(pKey) % pH->htsize;
   30245     pEntry = &pH->ht[h];
   30246     elem = pEntry->chain;
   30247     count = pEntry->count;
   30248   }else{
   30249     h = 0;
   30250     elem = pH->first;
   30251     count = pH->count;
   30252   }
   30253   if( pHash ) *pHash = h;
   30254   while( count-- ){
   30255     assert( elem!=0 );
   30256     if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
   30257       return elem;
   30258     }
   30259     elem = elem->next;
   30260   }
   30261   return &nullElement;
   30262 }
   30263 
   30264 /* Remove a single entry from the hash table given a pointer to that
   30265 ** element and a hash on the element's key.
   30266 */
   30267 static void removeElementGivenHash(
   30268   Hash *pH,         /* The pH containing "elem" */
   30269   HashElem* elem,   /* The element to be removed from the pH */
   30270   unsigned int h    /* Hash value for the element */
   30271 ){
   30272   struct _ht *pEntry;
   30273   if( elem->prev ){
   30274     elem->prev->next = elem->next;
   30275   }else{
   30276     pH->first = elem->next;
   30277   }
   30278   if( elem->next ){
   30279     elem->next->prev = elem->prev;
   30280   }
   30281   if( pH->ht ){
   30282     pEntry = &pH->ht[h];
   30283     if( pEntry->chain==elem ){
   30284       pEntry->chain = elem->next;
   30285     }
   30286     pEntry->count--;
   30287     assert( pEntry->count>=0 );
   30288   }
   30289   sqlite3_free( elem );
   30290   pH->count--;
   30291   if( pH->count==0 ){
   30292     assert( pH->first==0 );
   30293     assert( pH->count==0 );
   30294     sqlite3HashClear(pH);
   30295   }
   30296 }
   30297 
   30298 /* Attempt to locate an element of the hash table pH with a key
   30299 ** that matches pKey.  Return the data for this element if it is
   30300 ** found, or NULL if there is no match.
   30301 */
   30302 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
   30303   assert( pH!=0 );
   30304   assert( pKey!=0 );
   30305   return findElementWithHash(pH, pKey, 0)->data;
   30306 }
   30307 
   30308 /* Insert an element into the hash table pH.  The key is pKey
   30309 ** and the data is "data".
   30310 **
   30311 ** If no element exists with a matching key, then a new
   30312 ** element is created and NULL is returned.
   30313 **
   30314 ** If another element already exists with the same key, then the
   30315 ** new data replaces the old data and the old data is returned.
   30316 ** The key is not copied in this instance.  If a malloc fails, then
   30317 ** the new data is returned and the hash table is unchanged.
   30318 **
   30319 ** If the "data" parameter to this function is NULL, then the
   30320 ** element corresponding to "key" is removed from the hash table.
   30321 */
   30322 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
   30323   unsigned int h;       /* the hash of the key modulo hash table size */
   30324   HashElem *elem;       /* Used to loop thru the element list */
   30325   HashElem *new_elem;   /* New element added to the pH */
   30326 
   30327   assert( pH!=0 );
   30328   assert( pKey!=0 );
   30329   elem = findElementWithHash(pH,pKey,&h);
   30330   if( elem->data ){
   30331     void *old_data = elem->data;
   30332     if( data==0 ){
   30333       removeElementGivenHash(pH,elem,h);
   30334     }else{
   30335       elem->data = data;
   30336       elem->pKey = pKey;
   30337     }
   30338     return old_data;
   30339   }
   30340   if( data==0 ) return 0;
   30341   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
   30342   if( new_elem==0 ) return data;
   30343   new_elem->pKey = pKey;
   30344   new_elem->data = data;
   30345   pH->count++;
   30346   if( pH->count>=10 && pH->count > 2*pH->htsize ){
   30347     if( rehash(pH, pH->count*2) ){
   30348       assert( pH->htsize>0 );
   30349       h = strHash(pKey) % pH->htsize;
   30350     }
   30351   }
   30352   insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
   30353   return 0;
   30354 }
   30355 
   30356 /************** End of hash.c ************************************************/
   30357 /************** Begin file opcodes.c *****************************************/
   30358 /* Automatically generated.  Do not edit */
   30359 /* See the tool/mkopcodec.tcl script for details. */
   30360 #if !defined(SQLITE_OMIT_EXPLAIN) \
   30361  || defined(VDBE_PROFILE) \
   30362  || defined(SQLITE_DEBUG)
   30363 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
   30364 # define OpHelp(X) "\0" X
   30365 #else
   30366 # define OpHelp(X)
   30367 #endif
   30368 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
   30369  static const char *const azName[] = {
   30370     /*   0 */ "Savepoint"        OpHelp(""),
   30371     /*   1 */ "AutoCommit"       OpHelp(""),
   30372     /*   2 */ "Transaction"      OpHelp(""),
   30373     /*   3 */ "SorterNext"       OpHelp(""),
   30374     /*   4 */ "PrevIfOpen"       OpHelp(""),
   30375     /*   5 */ "NextIfOpen"       OpHelp(""),
   30376     /*   6 */ "Prev"             OpHelp(""),
   30377     /*   7 */ "Next"             OpHelp(""),
   30378     /*   8 */ "Checkpoint"       OpHelp(""),
   30379     /*   9 */ "JournalMode"      OpHelp(""),
   30380     /*  10 */ "Vacuum"           OpHelp(""),
   30381     /*  11 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
   30382     /*  12 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
   30383     /*  13 */ "Goto"             OpHelp(""),
   30384     /*  14 */ "Gosub"            OpHelp(""),
   30385     /*  15 */ "InitCoroutine"    OpHelp(""),
   30386     /*  16 */ "Yield"            OpHelp(""),
   30387     /*  17 */ "MustBeInt"        OpHelp(""),
   30388     /*  18 */ "Jump"             OpHelp(""),
   30389     /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
   30390     /*  20 */ "Once"             OpHelp(""),
   30391     /*  21 */ "If"               OpHelp(""),
   30392     /*  22 */ "IfNot"            OpHelp(""),
   30393     /*  23 */ "IfNullRow"        OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
   30394     /*  24 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
   30395     /*  25 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
   30396     /*  26 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
   30397     /*  27 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
   30398     /*  28 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
   30399     /*  29 */ "NotFound"         OpHelp("key=r[P3@P4]"),
   30400     /*  30 */ "Found"            OpHelp("key=r[P3@P4]"),
   30401     /*  31 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
   30402     /*  32 */ "NotExists"        OpHelp("intkey=r[P3]"),
   30403     /*  33 */ "Last"             OpHelp(""),
   30404     /*  34 */ "IfSmaller"        OpHelp(""),
   30405     /*  35 */ "SorterSort"       OpHelp(""),
   30406     /*  36 */ "Sort"             OpHelp(""),
   30407     /*  37 */ "Rewind"           OpHelp(""),
   30408     /*  38 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
   30409     /*  39 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
   30410     /*  40 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
   30411     /*  41 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
   30412     /*  42 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
   30413     /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
   30414     /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
   30415     /*  45 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
   30416     /*  46 */ "Program"          OpHelp(""),
   30417     /*  47 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
   30418     /*  48 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
   30419     /*  49 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
   30420     /*  50 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
   30421     /*  51 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
   30422     /*  52 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
   30423     /*  53 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
   30424     /*  54 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
   30425     /*  55 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
   30426     /*  56 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
   30427     /*  57 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
   30428     /*  58 */ "ElseNotEq"        OpHelp(""),
   30429     /*  59 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
   30430     /*  60 */ "IncrVacuum"       OpHelp(""),
   30431     /*  61 */ "VNext"            OpHelp(""),
   30432     /*  62 */ "Init"             OpHelp("Start at P2"),
   30433     /*  63 */ "Return"           OpHelp(""),
   30434     /*  64 */ "EndCoroutine"     OpHelp(""),
   30435     /*  65 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
   30436     /*  66 */ "Halt"             OpHelp(""),
   30437     /*  67 */ "Integer"          OpHelp("r[P2]=P1"),
   30438     /*  68 */ "Int64"            OpHelp("r[P2]=P4"),
   30439     /*  69 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
   30440     /*  70 */ "Null"             OpHelp("r[P2..P3]=NULL"),
   30441     /*  71 */ "SoftNull"         OpHelp("r[P1]=NULL"),
   30442     /*  72 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
   30443     /*  73 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
   30444     /*  74 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
   30445     /*  75 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
   30446     /*  76 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
   30447     /*  77 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
   30448     /*  78 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
   30449     /*  79 */ "CollSeq"          OpHelp(""),
   30450     /*  80 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
   30451     /*  81 */ "RealAffinity"     OpHelp(""),
   30452     /*  82 */ "Cast"             OpHelp("affinity(r[P1])"),
   30453     /*  83 */ "Permutation"      OpHelp(""),
   30454     /*  84 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
   30455     /*  85 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
   30456     /*  86 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
   30457     /*  87 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
   30458     /*  88 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
   30459     /*  89 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
   30460     /*  90 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
   30461     /*  91 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
   30462     /*  92 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
   30463     /*  93 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
   30464     /*  94 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
   30465     /*  95 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
   30466     /*  96 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
   30467     /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
   30468     /*  98 */ "Column"           OpHelp("r[P3]=PX"),
   30469     /*  99 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
   30470     /* 100 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
   30471     /* 101 */ "Count"            OpHelp("r[P2]=count()"),
   30472     /* 102 */ "ReadCookie"       OpHelp(""),
   30473     /* 103 */ "SetCookie"        OpHelp(""),
   30474     /* 104 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
   30475     /* 105 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
   30476     /* 106 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
   30477     /* 107 */ "OpenDup"          OpHelp(""),
   30478     /* 108 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
   30479     /* 109 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
   30480     /* 110 */ "SorterOpen"       OpHelp(""),
   30481     /* 111 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
   30482     /* 112 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
   30483     /* 113 */ "Close"            OpHelp(""),
   30484     /* 114 */ "ColumnsUsed"      OpHelp(""),
   30485     /* 115 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
   30486     /* 116 */ "NewRowid"         OpHelp("r[P2]=rowid"),
   30487     /* 117 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
   30488     /* 118 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
   30489     /* 119 */ "Delete"           OpHelp(""),
   30490     /* 120 */ "ResetCount"       OpHelp(""),
   30491     /* 121 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
   30492     /* 122 */ "SorterData"       OpHelp("r[P2]=data"),
   30493     /* 123 */ "RowData"          OpHelp("r[P2]=data"),
   30494     /* 124 */ "Rowid"            OpHelp("r[P2]=rowid"),
   30495     /* 125 */ "NullRow"          OpHelp(""),
   30496     /* 126 */ "SeekEnd"          OpHelp(""),
   30497     /* 127 */ "SorterInsert"     OpHelp("key=r[P2]"),
   30498     /* 128 */ "IdxInsert"        OpHelp("key=r[P2]"),
   30499     /* 129 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
   30500     /* 130 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
   30501     /* 131 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
   30502     /* 132 */ "Real"             OpHelp("r[P2]=P4"),
   30503     /* 133 */ "Destroy"          OpHelp(""),
   30504     /* 134 */ "Clear"            OpHelp(""),
   30505     /* 135 */ "ResetSorter"      OpHelp(""),
   30506     /* 136 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
   30507     /* 137 */ "SqlExec"          OpHelp(""),
   30508     /* 138 */ "ParseSchema"      OpHelp(""),
   30509     /* 139 */ "LoadAnalysis"     OpHelp(""),
   30510     /* 140 */ "DropTable"        OpHelp(""),
   30511     /* 141 */ "DropIndex"        OpHelp(""),
   30512     /* 142 */ "DropTrigger"      OpHelp(""),
   30513     /* 143 */ "IntegrityCk"      OpHelp(""),
   30514     /* 144 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
   30515     /* 145 */ "Param"            OpHelp(""),
   30516     /* 146 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
   30517     /* 147 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
   30518     /* 148 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
   30519     /* 149 */ "AggStep0"         OpHelp("accum=r[P3] step(r[P2@P5])"),
   30520     /* 150 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
   30521     /* 151 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
   30522     /* 152 */ "Expire"           OpHelp(""),
   30523     /* 153 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
   30524     /* 154 */ "VBegin"           OpHelp(""),
   30525     /* 155 */ "VCreate"          OpHelp(""),
   30526     /* 156 */ "VDestroy"         OpHelp(""),
   30527     /* 157 */ "VOpen"            OpHelp(""),
   30528     /* 158 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
   30529     /* 159 */ "VRename"          OpHelp(""),
   30530     /* 160 */ "Pagecount"        OpHelp(""),
   30531     /* 161 */ "MaxPgcnt"         OpHelp(""),
   30532     /* 162 */ "PureFunc0"        OpHelp(""),
   30533     /* 163 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
   30534     /* 164 */ "PureFunc"         OpHelp(""),
   30535     /* 165 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
   30536     /* 166 */ "Trace"            OpHelp(""),
   30537     /* 167 */ "CursorHint"       OpHelp(""),
   30538     /* 168 */ "Noop"             OpHelp(""),
   30539     /* 169 */ "Explain"          OpHelp(""),
   30540   };
   30541   return azName[i];
   30542 }
   30543 #endif
   30544 
   30545 /************** End of opcodes.c *********************************************/
   30546 /************** Begin file os_unix.c *****************************************/
   30547 /*
   30548 ** 2004 May 22
   30549 **
   30550 ** The author disclaims copyright to this source code.  In place of
   30551 ** a legal notice, here is a blessing:
   30552 **
   30553 **    May you do good and not evil.
   30554 **    May you find forgiveness for yourself and forgive others.
   30555 **    May you share freely, never taking more than you give.
   30556 **
   30557 ******************************************************************************
   30558 **
   30559 ** This file contains the VFS implementation for unix-like operating systems
   30560 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
   30561 **
   30562 ** There are actually several different VFS implementations in this file.
   30563 ** The differences are in the way that file locking is done.  The default
   30564 ** implementation uses Posix Advisory Locks.  Alternative implementations
   30565 ** use flock(), dot-files, various proprietary locking schemas, or simply
   30566 ** skip locking all together.
   30567 **
   30568 ** This source file is organized into divisions where the logic for various
   30569 ** subfunctions is contained within the appropriate division.  PLEASE
   30570 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
   30571 ** in the correct division and should be clearly labeled.
   30572 **
   30573 ** The layout of divisions is as follows:
   30574 **
   30575 **   *  General-purpose declarations and utility functions.
   30576 **   *  Unique file ID logic used by VxWorks.
   30577 **   *  Various locking primitive implementations (all except proxy locking):
   30578 **      + for Posix Advisory Locks
   30579 **      + for no-op locks
   30580 **      + for dot-file locks
   30581 **      + for flock() locking
   30582 **      + for named semaphore locks (VxWorks only)
   30583 **      + for AFP filesystem locks (MacOSX only)
   30584 **   *  sqlite3_file methods not associated with locking.
   30585 **   *  Definitions of sqlite3_io_methods objects for all locking
   30586 **      methods plus "finder" functions for each locking method.
   30587 **   *  sqlite3_vfs method implementations.
   30588 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
   30589 **   *  Definitions of sqlite3_vfs objects for all locking methods
   30590 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
   30591 */
   30592 /* #include "sqliteInt.h" */
   30593 #if SQLITE_OS_UNIX              /* This file is used on unix only */
   30594 
   30595 /*
   30596 ** There are various methods for file locking used for concurrency
   30597 ** control:
   30598 **
   30599 **   1. POSIX locking (the default),
   30600 **   2. No locking,
   30601 **   3. Dot-file locking,
   30602 **   4. flock() locking,
   30603 **   5. AFP locking (OSX only),
   30604 **   6. Named POSIX semaphores (VXWorks only),
   30605 **   7. proxy locking. (OSX only)
   30606 **
   30607 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
   30608 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
   30609 ** selection of the appropriate locking style based on the filesystem
   30610 ** where the database is located.
   30611 */
   30612 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   30613 #  if defined(__APPLE__)
   30614 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   30615 #  else
   30616 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   30617 #  endif
   30618 #endif
   30619 
   30620 /* Use pread() and pwrite() if they are available */
   30621 #if defined(__APPLE__)
   30622 # define HAVE_PREAD 1
   30623 # define HAVE_PWRITE 1
   30624 #endif
   30625 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
   30626 # undef USE_PREAD
   30627 # define USE_PREAD64 1
   30628 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
   30629 # undef USE_PREAD64
   30630 # define USE_PREAD 1
   30631 #endif
   30632 
   30633 /*
   30634 ** standard include files.
   30635 */
   30636 #include <sys/types.h>
   30637 #include <sys/stat.h>
   30638 #include <fcntl.h>
   30639 #include <sys/ioctl.h>
   30640 #include <unistd.h>
   30641 /* #include <time.h> */
   30642 #include <sys/time.h>
   30643 #include <errno.h>
   30644 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   30645 # include <sys/mman.h>
   30646 #endif
   30647 
   30648 #if SQLITE_ENABLE_LOCKING_STYLE
   30649 /* # include <sys/ioctl.h> */
   30650 # include <sys/file.h>
   30651 # include <sys/param.h>
   30652 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   30653 
   30654 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
   30655                            (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
   30656 #  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
   30657        && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
   30658 #    define HAVE_GETHOSTUUID 1
   30659 #  else
   30660 #    warning "gethostuuid() is disabled."
   30661 #  endif
   30662 #endif
   30663 
   30664 
   30665 #if OS_VXWORKS
   30666 /* # include <sys/ioctl.h> */
   30667 # include <semaphore.h>
   30668 # include <limits.h>
   30669 #endif /* OS_VXWORKS */
   30670 
   30671 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   30672 # include <sys/mount.h>
   30673 #endif
   30674 
   30675 #ifdef HAVE_UTIME
   30676 # include <utime.h>
   30677 #endif
   30678 
   30679 /*
   30680 ** Allowed values of unixFile.fsFlags
   30681 */
   30682 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
   30683 
   30684 /*
   30685 ** If we are to be thread-safe, include the pthreads header and define
   30686 ** the SQLITE_UNIX_THREADS macro.
   30687 */
   30688 #if SQLITE_THREADSAFE
   30689 /* # include <pthread.h> */
   30690 # define SQLITE_UNIX_THREADS 1
   30691 #endif
   30692 
   30693 /*
   30694 ** Default permissions when creating a new file
   30695 */
   30696 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
   30697 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
   30698 #endif
   30699 
   30700 /*
   30701 ** Default permissions when creating auto proxy dir
   30702 */
   30703 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   30704 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
   30705 #endif
   30706 
   30707 /*
   30708 ** Maximum supported path-length.
   30709 */
   30710 #define MAX_PATHNAME 512
   30711 
   30712 /*
   30713 ** Maximum supported symbolic links
   30714 */
   30715 #define SQLITE_MAX_SYMLINKS 100
   30716 
   30717 /* Always cast the getpid() return type for compatibility with
   30718 ** kernel modules in VxWorks. */
   30719 #define osGetpid(X) (pid_t)getpid()
   30720 
   30721 /*
   30722 ** Only set the lastErrno if the error code is a real error and not
   30723 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
   30724 */
   30725 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
   30726 
   30727 /* Forward references */
   30728 typedef struct unixShm unixShm;               /* Connection shared memory */
   30729 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
   30730 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
   30731 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
   30732 
   30733 /*
   30734 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
   30735 ** cannot be closed immediately. In these cases, instances of the following
   30736 ** structure are used to store the file descriptor while waiting for an
   30737 ** opportunity to either close or reuse it.
   30738 */
   30739 struct UnixUnusedFd {
   30740   int fd;                   /* File descriptor to close */
   30741   int flags;                /* Flags this file descriptor was opened with */
   30742   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
   30743 };
   30744 
   30745 /*
   30746 ** The unixFile structure is subclass of sqlite3_file specific to the unix
   30747 ** VFS implementations.
   30748 */
   30749 typedef struct unixFile unixFile;
   30750 struct unixFile {
   30751   sqlite3_io_methods const *pMethod;  /* Always the first entry */
   30752   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
   30753   unixInodeInfo *pInode;              /* Info about locks on this inode */
   30754   int h;                              /* The file descriptor */
   30755   unsigned char eFileLock;            /* The type of lock held on this fd */
   30756   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
   30757   int lastErrno;                      /* The unix errno from last I/O error */
   30758   void *lockingContext;               /* Locking style specific state */
   30759   UnixUnusedFd *pPreallocatedUnused;  /* Pre-allocated UnixUnusedFd */
   30760   const char *zPath;                  /* Name of the file */
   30761   unixShm *pShm;                      /* Shared memory segment information */
   30762   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
   30763 #if SQLITE_MAX_MMAP_SIZE>0
   30764   int nFetchOut;                      /* Number of outstanding xFetch refs */
   30765   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
   30766   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
   30767   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
   30768   void *pMapRegion;                   /* Memory mapped region */
   30769 #endif
   30770   int sectorSize;                     /* Device sector size */
   30771   int deviceCharacteristics;          /* Precomputed device characteristics */
   30772 #if SQLITE_ENABLE_LOCKING_STYLE
   30773   int openFlags;                      /* The flags specified at open() */
   30774 #endif
   30775 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
   30776   unsigned fsFlags;                   /* cached details from statfs() */
   30777 #endif
   30778 #if OS_VXWORKS
   30779   struct vxworksFileId *pId;          /* Unique file ID */
   30780 #endif
   30781 #ifdef SQLITE_DEBUG
   30782   /* The next group of variables are used to track whether or not the
   30783   ** transaction counter in bytes 24-27 of database files are updated
   30784   ** whenever any part of the database changes.  An assertion fault will
   30785   ** occur if a file is updated without also updating the transaction
   30786   ** counter.  This test is made to avoid new problems similar to the
   30787   ** one described by ticket #3584.
   30788   */
   30789   unsigned char transCntrChng;   /* True if the transaction counter changed */
   30790   unsigned char dbUpdate;        /* True if any part of database file changed */
   30791   unsigned char inNormalWrite;   /* True if in a normal write operation */
   30792 
   30793 #endif
   30794 
   30795 #ifdef SQLITE_TEST
   30796   /* In test mode, increase the size of this structure a bit so that
   30797   ** it is larger than the struct CrashFile defined in test6.c.
   30798   */
   30799   char aPadding[32];
   30800 #endif
   30801 };
   30802 
   30803 /* This variable holds the process id (pid) from when the xRandomness()
   30804 ** method was called.  If xOpen() is called from a different process id,
   30805 ** indicating that a fork() has occurred, the PRNG will be reset.
   30806 */
   30807 static pid_t randomnessPid = 0;
   30808 
   30809 /*
   30810 ** Allowed values for the unixFile.ctrlFlags bitmask:
   30811 */
   30812 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
   30813 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
   30814 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
   30815 #ifndef SQLITE_DISABLE_DIRSYNC
   30816 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
   30817 #else
   30818 # define UNIXFILE_DIRSYNC    0x00
   30819 #endif
   30820 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   30821 #define UNIXFILE_DELETE      0x20     /* Delete on close */
   30822 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
   30823 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
   30824 
   30825 /*
   30826 ** Include code that is common to all os_*.c files
   30827 */
   30828 /************** Include os_common.h in the middle of os_unix.c ***************/
   30829 /************** Begin file os_common.h ***************************************/
   30830 /*
   30831 ** 2004 May 22
   30832 **
   30833 ** The author disclaims copyright to this source code.  In place of
   30834 ** a legal notice, here is a blessing:
   30835 **
   30836 **    May you do good and not evil.
   30837 **    May you find forgiveness for yourself and forgive others.
   30838 **    May you share freely, never taking more than you give.
   30839 **
   30840 ******************************************************************************
   30841 **
   30842 ** This file contains macros and a little bit of code that is common to
   30843 ** all of the platform-specific files (os_*.c) and is #included into those
   30844 ** files.
   30845 **
   30846 ** This file should be #included by the os_*.c files only.  It is not a
   30847 ** general purpose header file.
   30848 */
   30849 #ifndef _OS_COMMON_H_
   30850 #define _OS_COMMON_H_
   30851 
   30852 /*
   30853 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   30854 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   30855 ** switch.  The following code should catch this problem at compile-time.
   30856 */
   30857 #ifdef MEMORY_DEBUG
   30858 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   30859 #endif
   30860 
   30861 /*
   30862 ** Macros for performance tracing.  Normally turned off.  Only works
   30863 ** on i486 hardware.
   30864 */
   30865 #ifdef SQLITE_PERFORMANCE_TRACE
   30866 
   30867 /*
   30868 ** hwtime.h contains inline assembler code for implementing
   30869 ** high-performance timing routines.
   30870 */
   30871 /************** Include hwtime.h in the middle of os_common.h ****************/
   30872 /************** Begin file hwtime.h ******************************************/
   30873 /*
   30874 ** 2008 May 27
   30875 **
   30876 ** The author disclaims copyright to this source code.  In place of
   30877 ** a legal notice, here is a blessing:
   30878 **
   30879 **    May you do good and not evil.
   30880 **    May you find forgiveness for yourself and forgive others.
   30881 **    May you share freely, never taking more than you give.
   30882 **
   30883 ******************************************************************************
   30884 **
   30885 ** This file contains inline asm code for retrieving "high-performance"
   30886 ** counters for x86 class CPUs.
   30887 */
   30888 #ifndef SQLITE_HWTIME_H
   30889 #define SQLITE_HWTIME_H
   30890 
   30891 /*
   30892 ** The following routine only works on pentium-class (or newer) processors.
   30893 ** It uses the RDTSC opcode to read the cycle count value out of the
   30894 ** processor and returns that value.  This can be used for high-res
   30895 ** profiling.
   30896 */
   30897 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   30898       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   30899 
   30900   #if defined(__GNUC__)
   30901 
   30902   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   30903      unsigned int lo, hi;
   30904      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   30905      return (sqlite_uint64)hi << 32 | lo;
   30906   }
   30907 
   30908   #elif defined(_MSC_VER)
   30909 
   30910   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   30911      __asm {
   30912         rdtsc
   30913         ret       ; return value at EDX:EAX
   30914      }
   30915   }
   30916 
   30917   #endif
   30918 
   30919 #elif (defined(__GNUC__) && defined(__x86_64__))
   30920 
   30921   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   30922       unsigned long val;
   30923       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   30924       return val;
   30925   }
   30926 
   30927 #elif (defined(__GNUC__) && defined(__ppc__))
   30928 
   30929   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   30930       unsigned long long retval;
   30931       unsigned long junk;
   30932       __asm__ __volatile__ ("\n\
   30933           1:      mftbu   %1\n\
   30934                   mftb    %L0\n\
   30935                   mftbu   %0\n\
   30936                   cmpw    %0,%1\n\
   30937                   bne     1b"
   30938                   : "=r" (retval), "=r" (junk));
   30939       return retval;
   30940   }
   30941 
   30942 #else
   30943 
   30944   #error Need implementation of sqlite3Hwtime() for your platform.
   30945 
   30946   /*
   30947   ** To compile without implementing sqlite3Hwtime() for your platform,
   30948   ** you can remove the above #error and use the following
   30949   ** stub function.  You will lose timing support for many
   30950   ** of the debugging and testing utilities, but it should at
   30951   ** least compile and run.
   30952   */
   30953 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   30954 
   30955 #endif
   30956 
   30957 #endif /* !defined(SQLITE_HWTIME_H) */
   30958 
   30959 /************** End of hwtime.h **********************************************/
   30960 /************** Continuing where we left off in os_common.h ******************/
   30961 
   30962 static sqlite_uint64 g_start;
   30963 static sqlite_uint64 g_elapsed;
   30964 #define TIMER_START       g_start=sqlite3Hwtime()
   30965 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   30966 #define TIMER_ELAPSED     g_elapsed
   30967 #else
   30968 #define TIMER_START
   30969 #define TIMER_END
   30970 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   30971 #endif
   30972 
   30973 /*
   30974 ** If we compile with the SQLITE_TEST macro set, then the following block
   30975 ** of code will give us the ability to simulate a disk I/O error.  This
   30976 ** is used for testing the I/O recovery logic.
   30977 */
   30978 #if defined(SQLITE_TEST)
   30979 SQLITE_API extern int sqlite3_io_error_hit;
   30980 SQLITE_API extern int sqlite3_io_error_hardhit;
   30981 SQLITE_API extern int sqlite3_io_error_pending;
   30982 SQLITE_API extern int sqlite3_io_error_persist;
   30983 SQLITE_API extern int sqlite3_io_error_benign;
   30984 SQLITE_API extern int sqlite3_diskfull_pending;
   30985 SQLITE_API extern int sqlite3_diskfull;
   30986 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   30987 #define SimulateIOError(CODE)  \
   30988   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   30989        || sqlite3_io_error_pending-- == 1 )  \
   30990               { local_ioerr(); CODE; }
   30991 static void local_ioerr(){
   30992   IOTRACE(("IOERR\n"));
   30993   sqlite3_io_error_hit++;
   30994   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   30995 }
   30996 #define SimulateDiskfullError(CODE) \
   30997    if( sqlite3_diskfull_pending ){ \
   30998      if( sqlite3_diskfull_pending == 1 ){ \
   30999        local_ioerr(); \
   31000        sqlite3_diskfull = 1; \
   31001        sqlite3_io_error_hit = 1; \
   31002        CODE; \
   31003      }else{ \
   31004        sqlite3_diskfull_pending--; \
   31005      } \
   31006    }
   31007 #else
   31008 #define SimulateIOErrorBenign(X)
   31009 #define SimulateIOError(A)
   31010 #define SimulateDiskfullError(A)
   31011 #endif /* defined(SQLITE_TEST) */
   31012 
   31013 /*
   31014 ** When testing, keep a count of the number of open files.
   31015 */
   31016 #if defined(SQLITE_TEST)
   31017 SQLITE_API extern int sqlite3_open_file_count;
   31018 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   31019 #else
   31020 #define OpenCounter(X)
   31021 #endif /* defined(SQLITE_TEST) */
   31022 
   31023 #endif /* !defined(_OS_COMMON_H_) */
   31024 
   31025 /************** End of os_common.h *******************************************/
   31026 /************** Continuing where we left off in os_unix.c ********************/
   31027 
   31028 /*
   31029 ** Define various macros that are missing from some systems.
   31030 */
   31031 #ifndef O_LARGEFILE
   31032 # define O_LARGEFILE 0
   31033 #endif
   31034 #ifdef SQLITE_DISABLE_LFS
   31035 # undef O_LARGEFILE
   31036 # define O_LARGEFILE 0
   31037 #endif
   31038 #ifndef O_NOFOLLOW
   31039 # define O_NOFOLLOW 0
   31040 #endif
   31041 #ifndef O_BINARY
   31042 # define O_BINARY 0
   31043 #endif
   31044 
   31045 /*
   31046 ** The threadid macro resolves to the thread-id or to 0.  Used for
   31047 ** testing and debugging only.
   31048 */
   31049 #if SQLITE_THREADSAFE
   31050 #define threadid pthread_self()
   31051 #else
   31052 #define threadid 0
   31053 #endif
   31054 
   31055 /*
   31056 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
   31057 */
   31058 #if !defined(HAVE_MREMAP)
   31059 # if defined(__linux__) && defined(_GNU_SOURCE)
   31060 #  define HAVE_MREMAP 1
   31061 # else
   31062 #  define HAVE_MREMAP 0
   31063 # endif
   31064 #endif
   31065 
   31066 /*
   31067 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
   31068 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
   31069 */
   31070 #ifdef __ANDROID__
   31071 # define lseek lseek64
   31072 #endif
   31073 
   31074 #ifdef __linux__
   31075 /*
   31076 ** Linux-specific IOCTL magic numbers used for controlling F2FS
   31077 */
   31078 #define F2FS_IOCTL_MAGIC        0xf5
   31079 #define F2FS_IOC_START_ATOMIC_WRITE     _IO(F2FS_IOCTL_MAGIC, 1)
   31080 #define F2FS_IOC_COMMIT_ATOMIC_WRITE    _IO(F2FS_IOCTL_MAGIC, 2)
   31081 #define F2FS_IOC_START_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 3)
   31082 #define F2FS_IOC_ABORT_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 5)
   31083 #define F2FS_IOC_GET_FEATURES           _IOR(F2FS_IOCTL_MAGIC, 12, u32)
   31084 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
   31085 #endif /* __linux__ */
   31086 
   31087 
   31088 /*
   31089 ** Different Unix systems declare open() in different ways.  Same use
   31090 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
   31091 ** The difference is important when using a pointer to the function.
   31092 **
   31093 ** The safest way to deal with the problem is to always use this wrapper
   31094 ** which always has the same well-defined interface.
   31095 */
   31096 static int posixOpen(const char *zFile, int flags, int mode){
   31097   return open(zFile, flags, mode);
   31098 }
   31099 
   31100 /* Forward reference */
   31101 static int openDirectory(const char*, int*);
   31102 static int unixGetpagesize(void);
   31103 
   31104 /*
   31105 ** Many system calls are accessed through pointer-to-functions so that
   31106 ** they may be overridden at runtime to facilitate fault injection during
   31107 ** testing and sandboxing.  The following array holds the names and pointers
   31108 ** to all overrideable system calls.
   31109 */
   31110 static struct unix_syscall {
   31111   const char *zName;            /* Name of the system call */
   31112   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   31113   sqlite3_syscall_ptr pDefault; /* Default value */
   31114 } aSyscall[] = {
   31115   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
   31116 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
   31117 
   31118   { "close",        (sqlite3_syscall_ptr)close,      0  },
   31119 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
   31120 
   31121   { "access",       (sqlite3_syscall_ptr)access,     0  },
   31122 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
   31123 
   31124   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
   31125 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
   31126 
   31127   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
   31128 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
   31129 
   31130 /*
   31131 ** The DJGPP compiler environment looks mostly like Unix, but it
   31132 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   31133 ** that always succeeds.  This means that locking does not occur under
   31134 ** DJGPP.  But it is DOS - what did you expect?
   31135 */
   31136 #ifdef __DJGPP__
   31137   { "fstat",        0,                 0  },
   31138 #define osFstat(a,b,c)    0
   31139 #else
   31140   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
   31141 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
   31142 #endif
   31143 
   31144   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
   31145 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
   31146 
   31147   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
   31148 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
   31149 
   31150   { "read",         (sqlite3_syscall_ptr)read,       0  },
   31151 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
   31152 
   31153 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
   31154   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
   31155 #else
   31156   { "pread",        (sqlite3_syscall_ptr)0,          0  },
   31157 #endif
   31158 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
   31159 
   31160 #if defined(USE_PREAD64)
   31161   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
   31162 #else
   31163   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
   31164 #endif
   31165 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
   31166 
   31167   { "write",        (sqlite3_syscall_ptr)write,      0  },
   31168 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
   31169 
   31170 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
   31171   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
   31172 #else
   31173   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
   31174 #endif
   31175 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
   31176                     aSyscall[12].pCurrent)
   31177 
   31178 #if defined(USE_PREAD64)
   31179   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
   31180 #else
   31181   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
   31182 #endif
   31183 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
   31184                     aSyscall[13].pCurrent)
   31185 
   31186   { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
   31187 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
   31188 
   31189 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   31190   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
   31191 #else
   31192   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
   31193 #endif
   31194 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
   31195 
   31196   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
   31197 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
   31198 
   31199   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
   31200 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
   31201 
   31202   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
   31203 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
   31204 
   31205   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
   31206 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
   31207 
   31208 #if defined(HAVE_FCHOWN)
   31209   { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
   31210 #else
   31211   { "fchown",       (sqlite3_syscall_ptr)0,               0 },
   31212 #endif
   31213 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
   31214 
   31215   { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
   31216 #define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
   31217 
   31218 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   31219   { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
   31220 #else
   31221   { "mmap",         (sqlite3_syscall_ptr)0,               0 },
   31222 #endif
   31223 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
   31224 
   31225 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   31226   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
   31227 #else
   31228   { "munmap",       (sqlite3_syscall_ptr)0,               0 },
   31229 #endif
   31230 #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
   31231 
   31232 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
   31233   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
   31234 #else
   31235   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
   31236 #endif
   31237 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
   31238 
   31239 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   31240   { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
   31241 #else
   31242   { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
   31243 #endif
   31244 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
   31245 
   31246 #if defined(HAVE_READLINK)
   31247   { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
   31248 #else
   31249   { "readlink",     (sqlite3_syscall_ptr)0,               0 },
   31250 #endif
   31251 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
   31252 
   31253 #if defined(HAVE_LSTAT)
   31254   { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
   31255 #else
   31256   { "lstat",         (sqlite3_syscall_ptr)0,              0 },
   31257 #endif
   31258 #define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
   31259 
   31260 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   31261   { "ioctl",         (sqlite3_syscall_ptr)ioctl,          0 },
   31262 #else
   31263   { "ioctl",         (sqlite3_syscall_ptr)0,              0 },
   31264 #endif
   31265 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
   31266 
   31267 }; /* End of the overrideable system calls */
   31268 
   31269 
   31270 /*
   31271 ** On some systems, calls to fchown() will trigger a message in a security
   31272 ** log if they come from non-root processes.  So avoid calling fchown() if
   31273 ** we are not running as root.
   31274 */
   31275 static int robustFchown(int fd, uid_t uid, gid_t gid){
   31276 #if defined(HAVE_FCHOWN)
   31277   return osGeteuid() ? 0 : osFchown(fd,uid,gid);
   31278 #else
   31279   return 0;
   31280 #endif
   31281 }
   31282 
   31283 /*
   31284 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   31285 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
   31286 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   31287 ** system call named zName.
   31288 */
   31289 static int unixSetSystemCall(
   31290   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   31291   const char *zName,            /* Name of system call to override */
   31292   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   31293 ){
   31294   unsigned int i;
   31295   int rc = SQLITE_NOTFOUND;
   31296 
   31297   UNUSED_PARAMETER(pNotUsed);
   31298   if( zName==0 ){
   31299     /* If no zName is given, restore all system calls to their default
   31300     ** settings and return NULL
   31301     */
   31302     rc = SQLITE_OK;
   31303     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   31304       if( aSyscall[i].pDefault ){
   31305         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   31306       }
   31307     }
   31308   }else{
   31309     /* If zName is specified, operate on only the one system call
   31310     ** specified.
   31311     */
   31312     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   31313       if( strcmp(zName, aSyscall[i].zName)==0 ){
   31314         if( aSyscall[i].pDefault==0 ){
   31315           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   31316         }
   31317         rc = SQLITE_OK;
   31318         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   31319         aSyscall[i].pCurrent = pNewFunc;
   31320         break;
   31321       }
   31322     }
   31323   }
   31324   return rc;
   31325 }
   31326 
   31327 /*
   31328 ** Return the value of a system call.  Return NULL if zName is not a
   31329 ** recognized system call name.  NULL is also returned if the system call
   31330 ** is currently undefined.
   31331 */
   31332 static sqlite3_syscall_ptr unixGetSystemCall(
   31333   sqlite3_vfs *pNotUsed,
   31334   const char *zName
   31335 ){
   31336   unsigned int i;
   31337 
   31338   UNUSED_PARAMETER(pNotUsed);
   31339   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   31340     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   31341   }
   31342   return 0;
   31343 }
   31344 
   31345 /*
   31346 ** Return the name of the first system call after zName.  If zName==NULL
   31347 ** then return the name of the first system call.  Return NULL if zName
   31348 ** is the last system call or if zName is not the name of a valid
   31349 ** system call.
   31350 */
   31351 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
   31352   int i = -1;
   31353 
   31354   UNUSED_PARAMETER(p);
   31355   if( zName ){
   31356     for(i=0; i<ArraySize(aSyscall)-1; i++){
   31357       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   31358     }
   31359   }
   31360   for(i++; i<ArraySize(aSyscall); i++){
   31361     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   31362   }
   31363   return 0;
   31364 }
   31365 
   31366 /*
   31367 ** Do not accept any file descriptor less than this value, in order to avoid
   31368 ** opening database file using file descriptors that are commonly used for
   31369 ** standard input, output, and error.
   31370 */
   31371 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
   31372 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
   31373 #endif
   31374 
   31375 /*
   31376 ** Invoke open().  Do so multiple times, until it either succeeds or
   31377 ** fails for some reason other than EINTR.
   31378 **
   31379 ** If the file creation mode "m" is 0 then set it to the default for
   31380 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
   31381 ** 0644) as modified by the system umask.  If m is not 0, then
   31382 ** make the file creation mode be exactly m ignoring the umask.
   31383 **
   31384 ** The m parameter will be non-zero only when creating -wal, -journal,
   31385 ** and -shm files.  We want those files to have *exactly* the same
   31386 ** permissions as their original database, unadulterated by the umask.
   31387 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
   31388 ** transaction crashes and leaves behind hot journals, then any
   31389 ** process that is able to write to the database will also be able to
   31390 ** recover the hot journals.
   31391 */
   31392 static int robust_open(const char *z, int f, mode_t m){
   31393   int fd;
   31394   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
   31395   while(1){
   31396 #if defined(O_CLOEXEC)
   31397     fd = osOpen(z,f|O_CLOEXEC,m2);
   31398 #else
   31399     fd = osOpen(z,f,m2);
   31400 #endif
   31401     if( fd<0 ){
   31402       if( errno==EINTR ) continue;
   31403       break;
   31404     }
   31405     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
   31406     osClose(fd);
   31407     sqlite3_log(SQLITE_WARNING,
   31408                 "attempt to open \"%s\" as file descriptor %d", z, fd);
   31409     fd = -1;
   31410     if( osOpen("/dev/null", f, m)<0 ) break;
   31411   }
   31412   if( fd>=0 ){
   31413     if( m!=0 ){
   31414       struct stat statbuf;
   31415       if( osFstat(fd, &statbuf)==0
   31416        && statbuf.st_size==0
   31417        && (statbuf.st_mode&0777)!=m
   31418       ){
   31419         osFchmod(fd, m);
   31420       }
   31421     }
   31422 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
   31423     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   31424 #endif
   31425   }
   31426   return fd;
   31427 }
   31428 
   31429 /*
   31430 ** Helper functions to obtain and relinquish the global mutex. The
   31431 ** global mutex is used to protect the unixInodeInfo and
   31432 ** vxworksFileId objects used by this file, all of which may be
   31433 ** shared by multiple threads.
   31434 **
   31435 ** Function unixMutexHeld() is used to assert() that the global mutex
   31436 ** is held when required. This function is only used as part of assert()
   31437 ** statements. e.g.
   31438 **
   31439 **   unixEnterMutex()
   31440 **     assert( unixMutexHeld() );
   31441 **   unixEnterLeave()
   31442 */
   31443 static void unixEnterMutex(void){
   31444   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
   31445 }
   31446 static void unixLeaveMutex(void){
   31447   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
   31448 }
   31449 #ifdef SQLITE_DEBUG
   31450 static int unixMutexHeld(void) {
   31451   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
   31452 }
   31453 #endif
   31454 
   31455 
   31456 #ifdef SQLITE_HAVE_OS_TRACE
   31457 /*
   31458 ** Helper function for printing out trace information from debugging
   31459 ** binaries. This returns the string representation of the supplied
   31460 ** integer lock-type.
   31461 */
   31462 static const char *azFileLock(int eFileLock){
   31463   switch( eFileLock ){
   31464     case NO_LOCK: return "NONE";
   31465     case SHARED_LOCK: return "SHARED";
   31466     case RESERVED_LOCK: return "RESERVED";
   31467     case PENDING_LOCK: return "PENDING";
   31468     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   31469   }
   31470   return "ERROR";
   31471 }
   31472 #endif
   31473 
   31474 #ifdef SQLITE_LOCK_TRACE
   31475 /*
   31476 ** Print out information about all locking operations.
   31477 **
   31478 ** This routine is used for troubleshooting locks on multithreaded
   31479 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   31480 ** command-line option on the compiler.  This code is normally
   31481 ** turned off.
   31482 */
   31483 static int lockTrace(int fd, int op, struct flock *p){
   31484   char *zOpName, *zType;
   31485   int s;
   31486   int savedErrno;
   31487   if( op==F_GETLK ){
   31488     zOpName = "GETLK";
   31489   }else if( op==F_SETLK ){
   31490     zOpName = "SETLK";
   31491   }else{
   31492     s = osFcntl(fd, op, p);
   31493     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   31494     return s;
   31495   }
   31496   if( p->l_type==F_RDLCK ){
   31497     zType = "RDLCK";
   31498   }else if( p->l_type==F_WRLCK ){
   31499     zType = "WRLCK";
   31500   }else if( p->l_type==F_UNLCK ){
   31501     zType = "UNLCK";
   31502   }else{
   31503     assert( 0 );
   31504   }
   31505   assert( p->l_whence==SEEK_SET );
   31506   s = osFcntl(fd, op, p);
   31507   savedErrno = errno;
   31508   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   31509      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   31510      (int)p->l_pid, s);
   31511   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   31512     struct flock l2;
   31513     l2 = *p;
   31514     osFcntl(fd, F_GETLK, &l2);
   31515     if( l2.l_type==F_RDLCK ){
   31516       zType = "RDLCK";
   31517     }else if( l2.l_type==F_WRLCK ){
   31518       zType = "WRLCK";
   31519     }else if( l2.l_type==F_UNLCK ){
   31520       zType = "UNLCK";
   31521     }else{
   31522       assert( 0 );
   31523     }
   31524     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   31525        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   31526   }
   31527   errno = savedErrno;
   31528   return s;
   31529 }
   31530 #undef osFcntl
   31531 #define osFcntl lockTrace
   31532 #endif /* SQLITE_LOCK_TRACE */
   31533 
   31534 /*
   31535 ** Retry ftruncate() calls that fail due to EINTR
   31536 **
   31537 ** All calls to ftruncate() within this file should be made through
   31538 ** this wrapper.  On the Android platform, bypassing the logic below
   31539 ** could lead to a corrupt database.
   31540 */
   31541 static int robust_ftruncate(int h, sqlite3_int64 sz){
   31542   int rc;
   31543 #ifdef __ANDROID__
   31544   /* On Android, ftruncate() always uses 32-bit offsets, even if
   31545   ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
   31546   ** truncate a file to any size larger than 2GiB. Silently ignore any
   31547   ** such attempts.  */
   31548   if( sz>(sqlite3_int64)0x7FFFFFFF ){
   31549     rc = SQLITE_OK;
   31550   }else
   31551 #endif
   31552   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
   31553   return rc;
   31554 }
   31555 
   31556 /*
   31557 ** This routine translates a standard POSIX errno code into something
   31558 ** useful to the clients of the sqlite3 functions.  Specifically, it is
   31559 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
   31560 ** and a variety of "please close the file descriptor NOW" errors into
   31561 ** SQLITE_IOERR
   31562 **
   31563 ** Errors during initialization of locks, or file system support for locks,
   31564 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
   31565 */
   31566 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
   31567   assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
   31568           (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
   31569           (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
   31570           (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
   31571   switch (posixError) {
   31572   case EACCES:
   31573   case EAGAIN:
   31574   case ETIMEDOUT:
   31575   case EBUSY:
   31576   case EINTR:
   31577   case ENOLCK:
   31578     /* random NFS retry error, unless during file system support
   31579      * introspection, in which it actually means what it says */
   31580     return SQLITE_BUSY;
   31581 
   31582   case EPERM:
   31583     return SQLITE_PERM;
   31584 
   31585   default:
   31586     return sqliteIOErr;
   31587   }
   31588 }
   31589 
   31590 
   31591 /******************************************************************************
   31592 ****************** Begin Unique File ID Utility Used By VxWorks ***************
   31593 **
   31594 ** On most versions of unix, we can get a unique ID for a file by concatenating
   31595 ** the device number and the inode number.  But this does not work on VxWorks.
   31596 ** On VxWorks, a unique file id must be based on the canonical filename.
   31597 **
   31598 ** A pointer to an instance of the following structure can be used as a
   31599 ** unique file ID in VxWorks.  Each instance of this structure contains
   31600 ** a copy of the canonical filename.  There is also a reference count.
   31601 ** The structure is reclaimed when the number of pointers to it drops to
   31602 ** zero.
   31603 **
   31604 ** There are never very many files open at one time and lookups are not
   31605 ** a performance-critical path, so it is sufficient to put these
   31606 ** structures on a linked list.
   31607 */
   31608 struct vxworksFileId {
   31609   struct vxworksFileId *pNext;  /* Next in a list of them all */
   31610   int nRef;                     /* Number of references to this one */
   31611   int nName;                    /* Length of the zCanonicalName[] string */
   31612   char *zCanonicalName;         /* Canonical filename */
   31613 };
   31614 
   31615 #if OS_VXWORKS
   31616 /*
   31617 ** All unique filenames are held on a linked list headed by this
   31618 ** variable:
   31619 */
   31620 static struct vxworksFileId *vxworksFileList = 0;
   31621 
   31622 /*
   31623 ** Simplify a filename into its canonical form
   31624 ** by making the following changes:
   31625 **
   31626 **  * removing any trailing and duplicate /
   31627 **  * convert /./ into just /
   31628 **  * convert /A/../ where A is any simple name into just /
   31629 **
   31630 ** Changes are made in-place.  Return the new name length.
   31631 **
   31632 ** The original filename is in z[0..n-1].  Return the number of
   31633 ** characters in the simplified name.
   31634 */
   31635 static int vxworksSimplifyName(char *z, int n){
   31636   int i, j;
   31637   while( n>1 && z[n-1]=='/' ){ n--; }
   31638   for(i=j=0; i<n; i++){
   31639     if( z[i]=='/' ){
   31640       if( z[i+1]=='/' ) continue;
   31641       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
   31642         i += 1;
   31643         continue;
   31644       }
   31645       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
   31646         while( j>0 && z[j-1]!='/' ){ j--; }
   31647         if( j>0 ){ j--; }
   31648         i += 2;
   31649         continue;
   31650       }
   31651     }
   31652     z[j++] = z[i];
   31653   }
   31654   z[j] = 0;
   31655   return j;
   31656 }
   31657 
   31658 /*
   31659 ** Find a unique file ID for the given absolute pathname.  Return
   31660 ** a pointer to the vxworksFileId object.  This pointer is the unique
   31661 ** file ID.
   31662 **
   31663 ** The nRef field of the vxworksFileId object is incremented before
   31664 ** the object is returned.  A new vxworksFileId object is created
   31665 ** and added to the global list if necessary.
   31666 **
   31667 ** If a memory allocation error occurs, return NULL.
   31668 */
   31669 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   31670   struct vxworksFileId *pNew;         /* search key and new file ID */
   31671   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
   31672   int n;                              /* Length of zAbsoluteName string */
   31673 
   31674   assert( zAbsoluteName[0]=='/' );
   31675   n = (int)strlen(zAbsoluteName);
   31676   pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
   31677   if( pNew==0 ) return 0;
   31678   pNew->zCanonicalName = (char*)&pNew[1];
   31679   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
   31680   n = vxworksSimplifyName(pNew->zCanonicalName, n);
   31681 
   31682   /* Search for an existing entry that matching the canonical name.
   31683   ** If found, increment the reference count and return a pointer to
   31684   ** the existing file ID.
   31685   */
   31686   unixEnterMutex();
   31687   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
   31688     if( pCandidate->nName==n
   31689      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
   31690     ){
   31691        sqlite3_free(pNew);
   31692        pCandidate->nRef++;
   31693        unixLeaveMutex();
   31694        return pCandidate;
   31695     }
   31696   }
   31697 
   31698   /* No match was found.  We will make a new file ID */
   31699   pNew->nRef = 1;
   31700   pNew->nName = n;
   31701   pNew->pNext = vxworksFileList;
   31702   vxworksFileList = pNew;
   31703   unixLeaveMutex();
   31704   return pNew;
   31705 }
   31706 
   31707 /*
   31708 ** Decrement the reference count on a vxworksFileId object.  Free
   31709 ** the object when the reference count reaches zero.
   31710 */
   31711 static void vxworksReleaseFileId(struct vxworksFileId *pId){
   31712   unixEnterMutex();
   31713   assert( pId->nRef>0 );
   31714   pId->nRef--;
   31715   if( pId->nRef==0 ){
   31716     struct vxworksFileId **pp;
   31717     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
   31718     assert( *pp==pId );
   31719     *pp = pId->pNext;
   31720     sqlite3_free(pId);
   31721   }
   31722   unixLeaveMutex();
   31723 }
   31724 #endif /* OS_VXWORKS */
   31725 /*************** End of Unique File ID Utility Used By VxWorks ****************
   31726 ******************************************************************************/
   31727 
   31728 
   31729 /******************************************************************************
   31730 *************************** Posix Advisory Locking ****************************
   31731 **
   31732 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
   31733 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   31734 ** sets or clears a lock, that operation overrides any prior locks set
   31735 ** by the same process.  It does not explicitly say so, but this implies
   31736 ** that it overrides locks set by the same process using a different
   31737 ** file descriptor.  Consider this test case:
   31738 **
   31739 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   31740 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   31741 **
   31742 ** Suppose ./file1 and ./file2 are really the same file (because
   31743 ** one is a hard or symbolic link to the other) then if you set
   31744 ** an exclusive lock on fd1, then try to get an exclusive lock
   31745 ** on fd2, it works.  I would have expected the second lock to
   31746 ** fail since there was already a lock on the file due to fd1.
   31747 ** But not so.  Since both locks came from the same process, the
   31748 ** second overrides the first, even though they were on different
   31749 ** file descriptors opened on different file names.
   31750 **
   31751 ** This means that we cannot use POSIX locks to synchronize file access
   31752 ** among competing threads of the same process.  POSIX locks will work fine
   31753 ** to synchronize access for threads in separate processes, but not
   31754 ** threads within the same process.
   31755 **
   31756 ** To work around the problem, SQLite has to manage file locks internally
   31757 ** on its own.  Whenever a new database is opened, we have to find the
   31758 ** specific inode of the database file (the inode is determined by the
   31759 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   31760 ** and check for locks already existing on that inode.  When locks are
   31761 ** created or removed, we have to look at our own internal record of the
   31762 ** locks to see if another thread has previously set a lock on that same
   31763 ** inode.
   31764 **
   31765 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
   31766 ** For VxWorks, we have to use the alternative unique ID system based on
   31767 ** canonical filename and implemented in the previous division.)
   31768 **
   31769 ** The sqlite3_file structure for POSIX is no longer just an integer file
   31770 ** descriptor.  It is now a structure that holds the integer file
   31771 ** descriptor and a pointer to a structure that describes the internal
   31772 ** locks on the corresponding inode.  There is one locking structure
   31773 ** per inode, so if the same inode is opened twice, both unixFile structures
   31774 ** point to the same locking structure.  The locking structure keeps
   31775 ** a reference count (so we will know when to delete it) and a "cnt"
   31776 ** field that tells us its internal lock status.  cnt==0 means the
   31777 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   31778 ** cnt>0 means there are cnt shared locks on the file.
   31779 **
   31780 ** Any attempt to lock or unlock a file first checks the locking
   31781 ** structure.  The fcntl() system call is only invoked to set a
   31782 ** POSIX lock if the internal lock structure transitions between
   31783 ** a locked and an unlocked state.
   31784 **
   31785 ** But wait:  there are yet more problems with POSIX advisory locks.
   31786 **
   31787 ** If you close a file descriptor that points to a file that has locks,
   31788 ** all locks on that file that are owned by the current process are
   31789 ** released.  To work around this problem, each unixInodeInfo object
   31790 ** maintains a count of the number of pending locks on tha inode.
   31791 ** When an attempt is made to close an unixFile, if there are
   31792 ** other unixFile open on the same inode that are holding locks, the call
   31793 ** to close() the file descriptor is deferred until all of the locks clear.
   31794 ** The unixInodeInfo structure keeps a list of file descriptors that need to
   31795 ** be closed and that list is walked (and cleared) when the last lock
   31796 ** clears.
   31797 **
   31798 ** Yet another problem:  LinuxThreads do not play well with posix locks.
   31799 **
   31800 ** Many older versions of linux use the LinuxThreads library which is
   31801 ** not posix compliant.  Under LinuxThreads, a lock created by thread
   31802 ** A cannot be modified or overridden by a different thread B.
   31803 ** Only thread A can modify the lock.  Locking behavior is correct
   31804 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
   31805 ** on linux - with NPTL a lock created by thread A can override locks
   31806 ** in thread B.  But there is no way to know at compile-time which
   31807 ** threading library is being used.  So there is no way to know at
   31808 ** compile-time whether or not thread A can override locks on thread B.
   31809 ** One has to do a run-time check to discover the behavior of the
   31810 ** current process.
   31811 **
   31812 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
   31813 ** was dropped beginning with version 3.7.0.  SQLite will still work with
   31814 ** LinuxThreads provided that (1) there is no more than one connection
   31815 ** per database file in the same process and (2) database connections
   31816 ** do not move across threads.
   31817 */
   31818 
   31819 /*
   31820 ** An instance of the following structure serves as the key used
   31821 ** to locate a particular unixInodeInfo object.
   31822 */
   31823 struct unixFileId {
   31824   dev_t dev;                  /* Device number */
   31825 #if OS_VXWORKS
   31826   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
   31827 #else
   31828   /* We are told that some versions of Android contain a bug that
   31829   ** sizes ino_t at only 32-bits instead of 64-bits. (See
   31830   ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
   31831   ** To work around this, always allocate 64-bits for the inode number.
   31832   ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
   31833   ** but that should not be a big deal. */
   31834   /* WAS:  ino_t ino;   */
   31835   u64 ino;                   /* Inode number */
   31836 #endif
   31837 };
   31838 
   31839 /*
   31840 ** An instance of the following structure is allocated for each open
   31841 ** inode.  Or, on LinuxThreads, there is one of these structures for
   31842 ** each inode opened by each thread.
   31843 **
   31844 ** A single inode can have multiple file descriptors, so each unixFile
   31845 ** structure contains a pointer to an instance of this object and this
   31846 ** object keeps a count of the number of unixFile pointing to it.
   31847 */
   31848 struct unixInodeInfo {
   31849   struct unixFileId fileId;       /* The lookup key */
   31850   int nShared;                    /* Number of SHARED locks held */
   31851   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   31852   unsigned char bProcessLock;     /* An exclusive process lock is held */
   31853   int nRef;                       /* Number of pointers to this structure */
   31854   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
   31855   int nLock;                      /* Number of outstanding file locks */
   31856   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
   31857   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
   31858   unixInodeInfo *pPrev;           /*    .... doubly linked */
   31859 #if SQLITE_ENABLE_LOCKING_STYLE
   31860   unsigned long long sharedByte;  /* for AFP simulated shared lock */
   31861 #endif
   31862 #if OS_VXWORKS
   31863   sem_t *pSem;                    /* Named POSIX semaphore */
   31864   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
   31865 #endif
   31866 };
   31867 
   31868 /*
   31869 ** A lists of all unixInodeInfo objects.
   31870 */
   31871 static unixInodeInfo *inodeList = 0;  /* All unixInodeInfo objects */
   31872 static unsigned int nUnusedFd = 0;    /* Total unused file descriptors */
   31873 
   31874 /*
   31875 **
   31876 ** This function - unixLogErrorAtLine(), is only ever called via the macro
   31877 ** unixLogError().
   31878 **
   31879 ** It is invoked after an error occurs in an OS function and errno has been
   31880 ** set. It logs a message using sqlite3_log() containing the current value of
   31881 ** errno and, if possible, the human-readable equivalent from strerror() or
   31882 ** strerror_r().
   31883 **
   31884 ** The first argument passed to the macro should be the error code that
   31885 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   31886 ** The two subsequent arguments should be the name of the OS function that
   31887 ** failed (e.g. "unlink", "open") and the associated file-system path,
   31888 ** if any.
   31889 */
   31890 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
   31891 static int unixLogErrorAtLine(
   31892   int errcode,                    /* SQLite error code */
   31893   const char *zFunc,              /* Name of OS function that failed */
   31894   const char *zPath,              /* File path associated with error */
   31895   int iLine                       /* Source line number where error occurred */
   31896 ){
   31897   char *zErr;                     /* Message from strerror() or equivalent */
   31898   int iErrno = errno;             /* Saved syscall error number */
   31899 
   31900   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
   31901   ** the strerror() function to obtain the human-readable error message
   31902   ** equivalent to errno. Otherwise, use strerror_r().
   31903   */
   31904 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
   31905   char aErr[80];
   31906   memset(aErr, 0, sizeof(aErr));
   31907   zErr = aErr;
   31908 
   31909   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
   31910   ** assume that the system provides the GNU version of strerror_r() that
   31911   ** returns a pointer to a buffer containing the error message. That pointer
   31912   ** may point to aErr[], or it may point to some static storage somewhere.
   31913   ** Otherwise, assume that the system provides the POSIX version of
   31914   ** strerror_r(), which always writes an error message into aErr[].
   31915   **
   31916   ** If the code incorrectly assumes that it is the POSIX version that is
   31917   ** available, the error message will often be an empty string. Not a
   31918   ** huge problem. Incorrectly concluding that the GNU version is available
   31919   ** could lead to a segfault though.
   31920   */
   31921 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
   31922   zErr =
   31923 # endif
   31924   strerror_r(iErrno, aErr, sizeof(aErr)-1);
   31925 
   31926 #elif SQLITE_THREADSAFE
   31927   /* This is a threadsafe build, but strerror_r() is not available. */
   31928   zErr = "";
   31929 #else
   31930   /* Non-threadsafe build, use strerror(). */
   31931   zErr = strerror(iErrno);
   31932 #endif
   31933 
   31934   if( zPath==0 ) zPath = "";
   31935   sqlite3_log(errcode,
   31936       "os_unix.c:%d: (%d) %s(%s) - %s",
   31937       iLine, iErrno, zFunc, zPath, zErr
   31938   );
   31939 
   31940   return errcode;
   31941 }
   31942 
   31943 /*
   31944 ** Close a file descriptor.
   31945 **
   31946 ** We assume that close() almost always works, since it is only in a
   31947 ** very sick application or on a very sick platform that it might fail.
   31948 ** If it does fail, simply leak the file descriptor, but do log the
   31949 ** error.
   31950 **
   31951 ** Note that it is not safe to retry close() after EINTR since the
   31952 ** file descriptor might have already been reused by another thread.
   31953 ** So we don't even try to recover from an EINTR.  Just log the error
   31954 ** and move on.
   31955 */
   31956 static void robust_close(unixFile *pFile, int h, int lineno){
   31957   if( osClose(h) ){
   31958     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
   31959                        pFile ? pFile->zPath : 0, lineno);
   31960   }
   31961 }
   31962 
   31963 /*
   31964 ** Set the pFile->lastErrno.  Do this in a subroutine as that provides
   31965 ** a convenient place to set a breakpoint.
   31966 */
   31967 static void storeLastErrno(unixFile *pFile, int error){
   31968   pFile->lastErrno = error;
   31969 }
   31970 
   31971 /*
   31972 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
   31973 */
   31974 static void closePendingFds(unixFile *pFile){
   31975   unixInodeInfo *pInode = pFile->pInode;
   31976   UnixUnusedFd *p;
   31977   UnixUnusedFd *pNext;
   31978   for(p=pInode->pUnused; p; p=pNext){
   31979     pNext = p->pNext;
   31980     robust_close(pFile, p->fd, __LINE__);
   31981     sqlite3_free(p);
   31982     nUnusedFd--;
   31983   }
   31984   pInode->pUnused = 0;
   31985 }
   31986 
   31987 /*
   31988 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
   31989 **
   31990 ** The mutex entered using the unixEnterMutex() function must be held
   31991 ** when this function is called.
   31992 */
   31993 static void releaseInodeInfo(unixFile *pFile){
   31994   unixInodeInfo *pInode = pFile->pInode;
   31995   assert( unixMutexHeld() );
   31996   if( ALWAYS(pInode) ){
   31997     pInode->nRef--;
   31998     if( pInode->nRef==0 ){
   31999       assert( pInode->pShmNode==0 );
   32000       closePendingFds(pFile);
   32001       if( pInode->pPrev ){
   32002         assert( pInode->pPrev->pNext==pInode );
   32003         pInode->pPrev->pNext = pInode->pNext;
   32004       }else{
   32005         assert( inodeList==pInode );
   32006         inodeList = pInode->pNext;
   32007       }
   32008       if( pInode->pNext ){
   32009         assert( pInode->pNext->pPrev==pInode );
   32010         pInode->pNext->pPrev = pInode->pPrev;
   32011       }
   32012       sqlite3_free(pInode);
   32013     }
   32014   }
   32015   assert( inodeList!=0 || nUnusedFd==0 );
   32016 }
   32017 
   32018 /*
   32019 ** Given a file descriptor, locate the unixInodeInfo object that
   32020 ** describes that file descriptor.  Create a new one if necessary.  The
   32021 ** return value might be uninitialized if an error occurs.
   32022 **
   32023 ** The mutex entered using the unixEnterMutex() function must be held
   32024 ** when this function is called.
   32025 **
   32026 ** Return an appropriate error code.
   32027 */
   32028 static int findInodeInfo(
   32029   unixFile *pFile,               /* Unix file with file desc used in the key */
   32030   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
   32031 ){
   32032   int rc;                        /* System call return code */
   32033   int fd;                        /* The file descriptor for pFile */
   32034   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
   32035   struct stat statbuf;           /* Low-level file information */
   32036   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
   32037 
   32038   assert( unixMutexHeld() );
   32039 
   32040   /* Get low-level information about the file that we can used to
   32041   ** create a unique name for the file.
   32042   */
   32043   fd = pFile->h;
   32044   rc = osFstat(fd, &statbuf);
   32045   if( rc!=0 ){
   32046     storeLastErrno(pFile, errno);
   32047 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
   32048     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   32049 #endif
   32050     return SQLITE_IOERR;
   32051   }
   32052 
   32053 #ifdef __APPLE__
   32054   /* On OS X on an msdos filesystem, the inode number is reported
   32055   ** incorrectly for zero-size files.  See ticket #3260.  To work
   32056   ** around this problem (we consider it a bug in OS X, not SQLite)
   32057   ** we always increase the file size to 1 by writing a single byte
   32058   ** prior to accessing the inode number.  The one byte written is
   32059   ** an ASCII 'S' character which also happens to be the first byte
   32060   ** in the header of every SQLite database.  In this way, if there
   32061   ** is a race condition such that another thread has already populated
   32062   ** the first page of the database, no damage is done.
   32063   */
   32064   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
   32065     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
   32066     if( rc!=1 ){
   32067       storeLastErrno(pFile, errno);
   32068       return SQLITE_IOERR;
   32069     }
   32070     rc = osFstat(fd, &statbuf);
   32071     if( rc!=0 ){
   32072       storeLastErrno(pFile, errno);
   32073       return SQLITE_IOERR;
   32074     }
   32075   }
   32076 #endif
   32077 
   32078   memset(&fileId, 0, sizeof(fileId));
   32079   fileId.dev = statbuf.st_dev;
   32080 #if OS_VXWORKS
   32081   fileId.pId = pFile->pId;
   32082 #else
   32083   fileId.ino = (u64)statbuf.st_ino;
   32084 #endif
   32085   assert( inodeList!=0 || nUnusedFd==0 );
   32086   pInode = inodeList;
   32087   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
   32088     pInode = pInode->pNext;
   32089   }
   32090   if( pInode==0 ){
   32091     pInode = sqlite3_malloc64( sizeof(*pInode) );
   32092     if( pInode==0 ){
   32093       return SQLITE_NOMEM_BKPT;
   32094     }
   32095     memset(pInode, 0, sizeof(*pInode));
   32096     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
   32097     pInode->nRef = 1;
   32098     pInode->pNext = inodeList;
   32099     pInode->pPrev = 0;
   32100     if( inodeList ) inodeList->pPrev = pInode;
   32101     inodeList = pInode;
   32102   }else{
   32103     pInode->nRef++;
   32104   }
   32105   *ppInode = pInode;
   32106   return SQLITE_OK;
   32107 }
   32108 
   32109 /*
   32110 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
   32111 */
   32112 static int fileHasMoved(unixFile *pFile){
   32113 #if OS_VXWORKS
   32114   return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
   32115 #else
   32116   struct stat buf;
   32117   return pFile->pInode!=0 &&
   32118       (osStat(pFile->zPath, &buf)!=0
   32119          || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
   32120 #endif
   32121 }
   32122 
   32123 
   32124 /*
   32125 ** Check a unixFile that is a database.  Verify the following:
   32126 **
   32127 ** (1) There is exactly one hard link on the file
   32128 ** (2) The file is not a symbolic link
   32129 ** (3) The file has not been renamed or unlinked
   32130 **
   32131 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
   32132 */
   32133 static void verifyDbFile(unixFile *pFile){
   32134   struct stat buf;
   32135   int rc;
   32136 
   32137   /* These verifications occurs for the main database only */
   32138   if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
   32139 
   32140   rc = osFstat(pFile->h, &buf);
   32141   if( rc!=0 ){
   32142     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
   32143     return;
   32144   }
   32145   if( buf.st_nlink==0 ){
   32146     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
   32147     return;
   32148   }
   32149   if( buf.st_nlink>1 ){
   32150     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
   32151     return;
   32152   }
   32153   if( fileHasMoved(pFile) ){
   32154     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
   32155     return;
   32156   }
   32157 }
   32158 
   32159 
   32160 /*
   32161 ** This routine checks if there is a RESERVED lock held on the specified
   32162 ** file by this or any other process. If such a lock is held, set *pResOut
   32163 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   32164 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   32165 */
   32166 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   32167   int rc = SQLITE_OK;
   32168   int reserved = 0;
   32169   unixFile *pFile = (unixFile*)id;
   32170 
   32171   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   32172 
   32173   assert( pFile );
   32174   assert( pFile->eFileLock<=SHARED_LOCK );
   32175   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   32176 
   32177   /* Check if a thread in this process holds such a lock */
   32178   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   32179     reserved = 1;
   32180   }
   32181 
   32182   /* Otherwise see if some other process holds it.
   32183   */
   32184 #ifndef __DJGPP__
   32185   if( !reserved && !pFile->pInode->bProcessLock ){
   32186     struct flock lock;
   32187     lock.l_whence = SEEK_SET;
   32188     lock.l_start = RESERVED_BYTE;
   32189     lock.l_len = 1;
   32190     lock.l_type = F_WRLCK;
   32191     if( osFcntl(pFile->h, F_GETLK, &lock) ){
   32192       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
   32193       storeLastErrno(pFile, errno);
   32194     } else if( lock.l_type!=F_UNLCK ){
   32195       reserved = 1;
   32196     }
   32197   }
   32198 #endif
   32199 
   32200   unixLeaveMutex();
   32201   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
   32202 
   32203   *pResOut = reserved;
   32204   return rc;
   32205 }
   32206 
   32207 /*
   32208 ** Attempt to set a system-lock on the file pFile.  The lock is
   32209 ** described by pLock.
   32210 **
   32211 ** If the pFile was opened read/write from unix-excl, then the only lock
   32212 ** ever obtained is an exclusive lock, and it is obtained exactly once
   32213 ** the first time any lock is attempted.  All subsequent system locking
   32214 ** operations become no-ops.  Locking operations still happen internally,
   32215 ** in order to coordinate access between separate database connections
   32216 ** within this process, but all of that is handled in memory and the
   32217 ** operating system does not participate.
   32218 **
   32219 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
   32220 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
   32221 ** and is read-only.
   32222 **
   32223 ** Zero is returned if the call completes successfully, or -1 if a call
   32224 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
   32225 */
   32226 static int unixFileLock(unixFile *pFile, struct flock *pLock){
   32227   int rc;
   32228   unixInodeInfo *pInode = pFile->pInode;
   32229   assert( unixMutexHeld() );
   32230   assert( pInode!=0 );
   32231   if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
   32232     if( pInode->bProcessLock==0 ){
   32233       struct flock lock;
   32234       assert( pInode->nLock==0 );
   32235       lock.l_whence = SEEK_SET;
   32236       lock.l_start = SHARED_FIRST;
   32237       lock.l_len = SHARED_SIZE;
   32238       lock.l_type = F_WRLCK;
   32239       rc = osFcntl(pFile->h, F_SETLK, &lock);
   32240       if( rc<0 ) return rc;
   32241       pInode->bProcessLock = 1;
   32242       pInode->nLock++;
   32243     }else{
   32244       rc = 0;
   32245     }
   32246   }else{
   32247     rc = osFcntl(pFile->h, F_SETLK, pLock);
   32248   }
   32249   return rc;
   32250 }
   32251 
   32252 /*
   32253 ** Lock the file with the lock specified by parameter eFileLock - one
   32254 ** of the following:
   32255 **
   32256 **     (1) SHARED_LOCK
   32257 **     (2) RESERVED_LOCK
   32258 **     (3) PENDING_LOCK
   32259 **     (4) EXCLUSIVE_LOCK
   32260 **
   32261 ** Sometimes when requesting one lock state, additional lock states
   32262 ** are inserted in between.  The locking might fail on one of the later
   32263 ** transitions leaving the lock state different from what it started but
   32264 ** still short of its goal.  The following chart shows the allowed
   32265 ** transitions and the inserted intermediate states:
   32266 **
   32267 **    UNLOCKED -> SHARED
   32268 **    SHARED -> RESERVED
   32269 **    SHARED -> (PENDING) -> EXCLUSIVE
   32270 **    RESERVED -> (PENDING) -> EXCLUSIVE
   32271 **    PENDING -> EXCLUSIVE
   32272 **
   32273 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   32274 ** routine to lower a locking level.
   32275 */
   32276 static int unixLock(sqlite3_file *id, int eFileLock){
   32277   /* The following describes the implementation of the various locks and
   32278   ** lock transitions in terms of the POSIX advisory shared and exclusive
   32279   ** lock primitives (called read-locks and write-locks below, to avoid
   32280   ** confusion with SQLite lock names). The algorithms are complicated
   32281   ** slightly in order to be compatible with Windows95 systems simultaneously
   32282   ** accessing the same database file, in case that is ever required.
   32283   **
   32284   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   32285   ** byte', each single bytes at well known offsets, and the 'shared byte
   32286   ** range', a range of 510 bytes at a well known offset.
   32287   **
   32288   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   32289   ** byte'.  If this is successful, 'shared byte range' is read-locked
   32290   ** and the lock on the 'pending byte' released.  (Legacy note:  When
   32291   ** SQLite was first developed, Windows95 systems were still very common,
   32292   ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a
   32293   ** single randomly selected by from the 'shared byte range' is locked.
   32294   ** Windows95 is now pretty much extinct, but this work-around for the
   32295   ** lack of shared-locks on Windows95 lives on, for backwards
   32296   ** compatibility.)
   32297   **
   32298   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   32299   ** A RESERVED lock is implemented by grabbing a write-lock on the
   32300   ** 'reserved byte'.
   32301   **
   32302   ** A process may only obtain a PENDING lock after it has obtained a
   32303   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   32304   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   32305   ** obtained, but existing SHARED locks are allowed to persist. A process
   32306   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   32307   ** This property is used by the algorithm for rolling back a journal file
   32308   ** after a crash.
   32309   **
   32310   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   32311   ** implemented by obtaining a write-lock on the entire 'shared byte
   32312   ** range'. Since all other locks require a read-lock on one of the bytes
   32313   ** within this range, this ensures that no other locks are held on the
   32314   ** database.
   32315   */
   32316   int rc = SQLITE_OK;
   32317   unixFile *pFile = (unixFile*)id;
   32318   unixInodeInfo *pInode;
   32319   struct flock lock;
   32320   int tErrno = 0;
   32321 
   32322   assert( pFile );
   32323   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   32324       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   32325       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
   32326       osGetpid(0)));
   32327 
   32328   /* If there is already a lock of this type or more restrictive on the
   32329   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   32330   ** unixEnterMutex() hasn't been called yet.
   32331   */
   32332   if( pFile->eFileLock>=eFileLock ){
   32333     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   32334             azFileLock(eFileLock)));
   32335     return SQLITE_OK;
   32336   }
   32337 
   32338   /* Make sure the locking sequence is correct.
   32339   **  (1) We never move from unlocked to anything higher than shared lock.
   32340   **  (2) SQLite never explicitly requests a pendig lock.
   32341   **  (3) A shared lock is always held when a reserve lock is requested.
   32342   */
   32343   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   32344   assert( eFileLock!=PENDING_LOCK );
   32345   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   32346 
   32347   /* This mutex is needed because pFile->pInode is shared across threads
   32348   */
   32349   unixEnterMutex();
   32350   pInode = pFile->pInode;
   32351 
   32352   /* If some thread using this PID has a lock via a different unixFile*
   32353   ** handle that precludes the requested lock, return BUSY.
   32354   */
   32355   if( (pFile->eFileLock!=pInode->eFileLock &&
   32356           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   32357   ){
   32358     rc = SQLITE_BUSY;
   32359     goto end_lock;
   32360   }
   32361 
   32362   /* If a SHARED lock is requested, and some thread using this PID already
   32363   ** has a SHARED or RESERVED lock, then increment reference counts and
   32364   ** return SQLITE_OK.
   32365   */
   32366   if( eFileLock==SHARED_LOCK &&
   32367       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   32368     assert( eFileLock==SHARED_LOCK );
   32369     assert( pFile->eFileLock==0 );
   32370     assert( pInode->nShared>0 );
   32371     pFile->eFileLock = SHARED_LOCK;
   32372     pInode->nShared++;
   32373     pInode->nLock++;
   32374     goto end_lock;
   32375   }
   32376 
   32377 
   32378   /* A PENDING lock is needed before acquiring a SHARED lock and before
   32379   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   32380   ** be released.
   32381   */
   32382   lock.l_len = 1L;
   32383   lock.l_whence = SEEK_SET;
   32384   if( eFileLock==SHARED_LOCK
   32385       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   32386   ){
   32387     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
   32388     lock.l_start = PENDING_BYTE;
   32389     if( unixFileLock(pFile, &lock) ){
   32390       tErrno = errno;
   32391       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   32392       if( rc!=SQLITE_BUSY ){
   32393         storeLastErrno(pFile, tErrno);
   32394       }
   32395       goto end_lock;
   32396     }
   32397   }
   32398 
   32399 
   32400   /* If control gets to this point, then actually go ahead and make
   32401   ** operating system calls for the specified lock.
   32402   */
   32403   if( eFileLock==SHARED_LOCK ){
   32404     assert( pInode->nShared==0 );
   32405     assert( pInode->eFileLock==0 );
   32406     assert( rc==SQLITE_OK );
   32407 
   32408     /* Now get the read-lock */
   32409     lock.l_start = SHARED_FIRST;
   32410     lock.l_len = SHARED_SIZE;
   32411     if( unixFileLock(pFile, &lock) ){
   32412       tErrno = errno;
   32413       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   32414     }
   32415 
   32416     /* Drop the temporary PENDING lock */
   32417     lock.l_start = PENDING_BYTE;
   32418     lock.l_len = 1L;
   32419     lock.l_type = F_UNLCK;
   32420     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
   32421       /* This could happen with a network mount */
   32422       tErrno = errno;
   32423       rc = SQLITE_IOERR_UNLOCK;
   32424     }
   32425 
   32426     if( rc ){
   32427       if( rc!=SQLITE_BUSY ){
   32428         storeLastErrno(pFile, tErrno);
   32429       }
   32430       goto end_lock;
   32431     }else{
   32432       pFile->eFileLock = SHARED_LOCK;
   32433       pInode->nLock++;
   32434       pInode->nShared = 1;
   32435     }
   32436   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   32437     /* We are trying for an exclusive lock but another thread in this
   32438     ** same process is still holding a shared lock. */
   32439     rc = SQLITE_BUSY;
   32440   }else{
   32441     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   32442     ** assumed that there is a SHARED or greater lock on the file
   32443     ** already.
   32444     */
   32445     assert( 0!=pFile->eFileLock );
   32446     lock.l_type = F_WRLCK;
   32447 
   32448     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
   32449     if( eFileLock==RESERVED_LOCK ){
   32450       lock.l_start = RESERVED_BYTE;
   32451       lock.l_len = 1L;
   32452     }else{
   32453       lock.l_start = SHARED_FIRST;
   32454       lock.l_len = SHARED_SIZE;
   32455     }
   32456 
   32457     if( unixFileLock(pFile, &lock) ){
   32458       tErrno = errno;
   32459       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   32460       if( rc!=SQLITE_BUSY ){
   32461         storeLastErrno(pFile, tErrno);
   32462       }
   32463     }
   32464   }
   32465 
   32466 
   32467 #ifdef SQLITE_DEBUG
   32468   /* Set up the transaction-counter change checking flags when
   32469   ** transitioning from a SHARED to a RESERVED lock.  The change
   32470   ** from SHARED to RESERVED marks the beginning of a normal
   32471   ** write operation (not a hot journal rollback).
   32472   */
   32473   if( rc==SQLITE_OK
   32474    && pFile->eFileLock<=SHARED_LOCK
   32475    && eFileLock==RESERVED_LOCK
   32476   ){
   32477     pFile->transCntrChng = 0;
   32478     pFile->dbUpdate = 0;
   32479     pFile->inNormalWrite = 1;
   32480   }
   32481 #endif
   32482 
   32483 
   32484   if( rc==SQLITE_OK ){
   32485     pFile->eFileLock = eFileLock;
   32486     pInode->eFileLock = eFileLock;
   32487   }else if( eFileLock==EXCLUSIVE_LOCK ){
   32488     pFile->eFileLock = PENDING_LOCK;
   32489     pInode->eFileLock = PENDING_LOCK;
   32490   }
   32491 
   32492 end_lock:
   32493   unixLeaveMutex();
   32494   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
   32495       rc==SQLITE_OK ? "ok" : "failed"));
   32496   return rc;
   32497 }
   32498 
   32499 /*
   32500 ** Add the file descriptor used by file handle pFile to the corresponding
   32501 ** pUnused list.
   32502 */
   32503 static void setPendingFd(unixFile *pFile){
   32504   unixInodeInfo *pInode = pFile->pInode;
   32505   UnixUnusedFd *p = pFile->pPreallocatedUnused;
   32506   p->pNext = pInode->pUnused;
   32507   pInode->pUnused = p;
   32508   pFile->h = -1;
   32509   pFile->pPreallocatedUnused = 0;
   32510   nUnusedFd++;
   32511 }
   32512 
   32513 /*
   32514 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   32515 ** must be either NO_LOCK or SHARED_LOCK.
   32516 **
   32517 ** If the locking level of the file descriptor is already at or below
   32518 ** the requested locking level, this routine is a no-op.
   32519 **
   32520 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
   32521 ** the byte range is divided into 2 parts and the first part is unlocked then
   32522 ** set to a read lock, then the other part is simply unlocked.  This works
   32523 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
   32524 ** remove the write lock on a region when a read lock is set.
   32525 */
   32526 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
   32527   unixFile *pFile = (unixFile*)id;
   32528   unixInodeInfo *pInode;
   32529   struct flock lock;
   32530   int rc = SQLITE_OK;
   32531 
   32532   assert( pFile );
   32533   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
   32534       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   32535       osGetpid(0)));
   32536 
   32537   assert( eFileLock<=SHARED_LOCK );
   32538   if( pFile->eFileLock<=eFileLock ){
   32539     return SQLITE_OK;
   32540   }
   32541   unixEnterMutex();
   32542   pInode = pFile->pInode;
   32543   assert( pInode->nShared!=0 );
   32544   if( pFile->eFileLock>SHARED_LOCK ){
   32545     assert( pInode->eFileLock==pFile->eFileLock );
   32546 
   32547 #ifdef SQLITE_DEBUG
   32548     /* When reducing a lock such that other processes can start
   32549     ** reading the database file again, make sure that the
   32550     ** transaction counter was updated if any part of the database
   32551     ** file changed.  If the transaction counter is not updated,
   32552     ** other connections to the same file might not realize that
   32553     ** the file has changed and hence might not know to flush their
   32554     ** cache.  The use of a stale cache can lead to database corruption.
   32555     */
   32556     pFile->inNormalWrite = 0;
   32557 #endif
   32558 
   32559     /* downgrading to a shared lock on NFS involves clearing the write lock
   32560     ** before establishing the readlock - to avoid a race condition we downgrade
   32561     ** the lock in 2 blocks, so that part of the range will be covered by a
   32562     ** write lock until the rest is covered by a read lock:
   32563     **  1:   [WWWWW]
   32564     **  2:   [....W]
   32565     **  3:   [RRRRW]
   32566     **  4:   [RRRR.]
   32567     */
   32568     if( eFileLock==SHARED_LOCK ){
   32569 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
   32570       (void)handleNFSUnlock;
   32571       assert( handleNFSUnlock==0 );
   32572 #endif
   32573 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   32574       if( handleNFSUnlock ){
   32575         int tErrno;               /* Error code from system call errors */
   32576         off_t divSize = SHARED_SIZE - 1;
   32577 
   32578         lock.l_type = F_UNLCK;
   32579         lock.l_whence = SEEK_SET;
   32580         lock.l_start = SHARED_FIRST;
   32581         lock.l_len = divSize;
   32582         if( unixFileLock(pFile, &lock)==(-1) ){
   32583           tErrno = errno;
   32584           rc = SQLITE_IOERR_UNLOCK;
   32585           storeLastErrno(pFile, tErrno);
   32586           goto end_unlock;
   32587         }
   32588         lock.l_type = F_RDLCK;
   32589         lock.l_whence = SEEK_SET;
   32590         lock.l_start = SHARED_FIRST;
   32591         lock.l_len = divSize;
   32592         if( unixFileLock(pFile, &lock)==(-1) ){
   32593           tErrno = errno;
   32594           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   32595           if( IS_LOCK_ERROR(rc) ){
   32596             storeLastErrno(pFile, tErrno);
   32597           }
   32598           goto end_unlock;
   32599         }
   32600         lock.l_type = F_UNLCK;
   32601         lock.l_whence = SEEK_SET;
   32602         lock.l_start = SHARED_FIRST+divSize;
   32603         lock.l_len = SHARED_SIZE-divSize;
   32604         if( unixFileLock(pFile, &lock)==(-1) ){
   32605           tErrno = errno;
   32606           rc = SQLITE_IOERR_UNLOCK;
   32607           storeLastErrno(pFile, tErrno);
   32608           goto end_unlock;
   32609         }
   32610       }else
   32611 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   32612       {
   32613         lock.l_type = F_RDLCK;
   32614         lock.l_whence = SEEK_SET;
   32615         lock.l_start = SHARED_FIRST;
   32616         lock.l_len = SHARED_SIZE;
   32617         if( unixFileLock(pFile, &lock) ){
   32618           /* In theory, the call to unixFileLock() cannot fail because another
   32619           ** process is holding an incompatible lock. If it does, this
   32620           ** indicates that the other process is not following the locking
   32621           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
   32622           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
   32623           ** an assert to fail). */
   32624           rc = SQLITE_IOERR_RDLOCK;
   32625           storeLastErrno(pFile, errno);
   32626           goto end_unlock;
   32627         }
   32628       }
   32629     }
   32630     lock.l_type = F_UNLCK;
   32631     lock.l_whence = SEEK_SET;
   32632     lock.l_start = PENDING_BYTE;
   32633     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   32634     if( unixFileLock(pFile, &lock)==0 ){
   32635       pInode->eFileLock = SHARED_LOCK;
   32636     }else{
   32637       rc = SQLITE_IOERR_UNLOCK;
   32638       storeLastErrno(pFile, errno);
   32639       goto end_unlock;
   32640     }
   32641   }
   32642   if( eFileLock==NO_LOCK ){
   32643     /* Decrement the shared lock counter.  Release the lock using an
   32644     ** OS call only when all threads in this same process have released
   32645     ** the lock.
   32646     */
   32647     pInode->nShared--;
   32648     if( pInode->nShared==0 ){
   32649       lock.l_type = F_UNLCK;
   32650       lock.l_whence = SEEK_SET;
   32651       lock.l_start = lock.l_len = 0L;
   32652       if( unixFileLock(pFile, &lock)==0 ){
   32653         pInode->eFileLock = NO_LOCK;
   32654       }else{
   32655         rc = SQLITE_IOERR_UNLOCK;
   32656         storeLastErrno(pFile, errno);
   32657         pInode->eFileLock = NO_LOCK;
   32658         pFile->eFileLock = NO_LOCK;
   32659       }
   32660     }
   32661 
   32662     /* Decrement the count of locks against this same file.  When the
   32663     ** count reaches zero, close any other file descriptors whose close
   32664     ** was deferred because of outstanding locks.
   32665     */
   32666     pInode->nLock--;
   32667     assert( pInode->nLock>=0 );
   32668     if( pInode->nLock==0 ){
   32669       closePendingFds(pFile);
   32670     }
   32671   }
   32672 
   32673 end_unlock:
   32674   unixLeaveMutex();
   32675   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   32676   return rc;
   32677 }
   32678 
   32679 /*
   32680 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   32681 ** must be either NO_LOCK or SHARED_LOCK.
   32682 **
   32683 ** If the locking level of the file descriptor is already at or below
   32684 ** the requested locking level, this routine is a no-op.
   32685 */
   32686 static int unixUnlock(sqlite3_file *id, int eFileLock){
   32687 #if SQLITE_MAX_MMAP_SIZE>0
   32688   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
   32689 #endif
   32690   return posixUnlock(id, eFileLock, 0);
   32691 }
   32692 
   32693 #if SQLITE_MAX_MMAP_SIZE>0
   32694 static int unixMapfile(unixFile *pFd, i64 nByte);
   32695 static void unixUnmapfile(unixFile *pFd);
   32696 #endif
   32697 
   32698 /*
   32699 ** This function performs the parts of the "close file" operation
   32700 ** common to all locking schemes. It closes the directory and file
   32701 ** handles, if they are valid, and sets all fields of the unixFile
   32702 ** structure to 0.
   32703 **
   32704 ** It is *not* necessary to hold the mutex when this routine is called,
   32705 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   32706 ** vxworksReleaseFileId() routine.
   32707 */
   32708 static int closeUnixFile(sqlite3_file *id){
   32709   unixFile *pFile = (unixFile*)id;
   32710 #if SQLITE_MAX_MMAP_SIZE>0
   32711   unixUnmapfile(pFile);
   32712 #endif
   32713   if( pFile->h>=0 ){
   32714     robust_close(pFile, pFile->h, __LINE__);
   32715     pFile->h = -1;
   32716   }
   32717 #if OS_VXWORKS
   32718   if( pFile->pId ){
   32719     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   32720       osUnlink(pFile->pId->zCanonicalName);
   32721     }
   32722     vxworksReleaseFileId(pFile->pId);
   32723     pFile->pId = 0;
   32724   }
   32725 #endif
   32726 #ifdef SQLITE_UNLINK_AFTER_CLOSE
   32727   if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   32728     osUnlink(pFile->zPath);
   32729     sqlite3_free(*(char**)&pFile->zPath);
   32730     pFile->zPath = 0;
   32731   }
   32732 #endif
   32733   OSTRACE(("CLOSE   %-3d\n", pFile->h));
   32734   OpenCounter(-1);
   32735   sqlite3_free(pFile->pPreallocatedUnused);
   32736   memset(pFile, 0, sizeof(unixFile));
   32737   return SQLITE_OK;
   32738 }
   32739 
   32740 /*
   32741 ** Close a file.
   32742 */
   32743 static int unixClose(sqlite3_file *id){
   32744   int rc = SQLITE_OK;
   32745   unixFile *pFile = (unixFile *)id;
   32746   verifyDbFile(pFile);
   32747   unixUnlock(id, NO_LOCK);
   32748   unixEnterMutex();
   32749 
   32750   /* unixFile.pInode is always valid here. Otherwise, a different close
   32751   ** routine (e.g. nolockClose()) would be called instead.
   32752   */
   32753   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
   32754   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
   32755     /* If there are outstanding locks, do not actually close the file just
   32756     ** yet because that would clear those locks.  Instead, add the file
   32757     ** descriptor to pInode->pUnused list.  It will be automatically closed
   32758     ** when the last lock is cleared.
   32759     */
   32760     setPendingFd(pFile);
   32761   }
   32762   releaseInodeInfo(pFile);
   32763   rc = closeUnixFile(id);
   32764   unixLeaveMutex();
   32765   return rc;
   32766 }
   32767 
   32768 /************** End of the posix advisory lock implementation *****************
   32769 ******************************************************************************/
   32770 
   32771 /******************************************************************************
   32772 ****************************** No-op Locking **********************************
   32773 **
   32774 ** Of the various locking implementations available, this is by far the
   32775 ** simplest:  locking is ignored.  No attempt is made to lock the database
   32776 ** file for reading or writing.
   32777 **
   32778 ** This locking mode is appropriate for use on read-only databases
   32779 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   32780 ** also be used if the application employs some external mechanism to
   32781 ** prevent simultaneous access of the same database by two or more
   32782 ** database connections.  But there is a serious risk of database
   32783 ** corruption if this locking mode is used in situations where multiple
   32784 ** database connections are accessing the same database file at the same
   32785 ** time and one or more of those connections are writing.
   32786 */
   32787 
   32788 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   32789   UNUSED_PARAMETER(NotUsed);
   32790   *pResOut = 0;
   32791   return SQLITE_OK;
   32792 }
   32793 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   32794   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   32795   return SQLITE_OK;
   32796 }
   32797 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   32798   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   32799   return SQLITE_OK;
   32800 }
   32801 
   32802 /*
   32803 ** Close the file.
   32804 */
   32805 static int nolockClose(sqlite3_file *id) {
   32806   return closeUnixFile(id);
   32807 }
   32808 
   32809 /******************* End of the no-op lock implementation *********************
   32810 ******************************************************************************/
   32811 
   32812 /******************************************************************************
   32813 ************************* Begin dot-file Locking ******************************
   32814 **
   32815 ** The dotfile locking implementation uses the existence of separate lock
   32816 ** files (really a directory) to control access to the database.  This works
   32817 ** on just about every filesystem imaginable.  But there are serious downsides:
   32818 **
   32819 **    (1)  There is zero concurrency.  A single reader blocks all other
   32820 **         connections from reading or writing the database.
   32821 **
   32822 **    (2)  An application crash or power loss can leave stale lock files
   32823 **         sitting around that need to be cleared manually.
   32824 **
   32825 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   32826 ** other locking strategy is available.
   32827 **
   32828 ** Dotfile locking works by creating a subdirectory in the same directory as
   32829 ** the database and with the same name but with a ".lock" extension added.
   32830 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
   32831 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   32832 */
   32833 
   32834 /*
   32835 ** The file suffix added to the data base filename in order to create the
   32836 ** lock directory.
   32837 */
   32838 #define DOTLOCK_SUFFIX ".lock"
   32839 
   32840 /*
   32841 ** This routine checks if there is a RESERVED lock held on the specified
   32842 ** file by this or any other process. If such a lock is held, set *pResOut
   32843 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   32844 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   32845 **
   32846 ** In dotfile locking, either a lock exists or it does not.  So in this
   32847 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   32848 ** is held on the file and false if the file is unlocked.
   32849 */
   32850 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   32851   int rc = SQLITE_OK;
   32852   int reserved = 0;
   32853   unixFile *pFile = (unixFile*)id;
   32854 
   32855   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   32856 
   32857   assert( pFile );
   32858   reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
   32859   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
   32860   *pResOut = reserved;
   32861   return rc;
   32862 }
   32863 
   32864 /*
   32865 ** Lock the file with the lock specified by parameter eFileLock - one
   32866 ** of the following:
   32867 **
   32868 **     (1) SHARED_LOCK
   32869 **     (2) RESERVED_LOCK
   32870 **     (3) PENDING_LOCK
   32871 **     (4) EXCLUSIVE_LOCK
   32872 **
   32873 ** Sometimes when requesting one lock state, additional lock states
   32874 ** are inserted in between.  The locking might fail on one of the later
   32875 ** transitions leaving the lock state different from what it started but
   32876 ** still short of its goal.  The following chart shows the allowed
   32877 ** transitions and the inserted intermediate states:
   32878 **
   32879 **    UNLOCKED -> SHARED
   32880 **    SHARED -> RESERVED
   32881 **    SHARED -> (PENDING) -> EXCLUSIVE
   32882 **    RESERVED -> (PENDING) -> EXCLUSIVE
   32883 **    PENDING -> EXCLUSIVE
   32884 **
   32885 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   32886 ** routine to lower a locking level.
   32887 **
   32888 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   32889 ** But we track the other locking levels internally.
   32890 */
   32891 static int dotlockLock(sqlite3_file *id, int eFileLock) {
   32892   unixFile *pFile = (unixFile*)id;
   32893   char *zLockFile = (char *)pFile->lockingContext;
   32894   int rc = SQLITE_OK;
   32895 
   32896 
   32897   /* If we have any lock, then the lock file already exists.  All we have
   32898   ** to do is adjust our internal record of the lock level.
   32899   */
   32900   if( pFile->eFileLock > NO_LOCK ){
   32901     pFile->eFileLock = eFileLock;
   32902     /* Always update the timestamp on the old file */
   32903 #ifdef HAVE_UTIME
   32904     utime(zLockFile, NULL);
   32905 #else
   32906     utimes(zLockFile, NULL);
   32907 #endif
   32908     return SQLITE_OK;
   32909   }
   32910 
   32911   /* grab an exclusive lock */
   32912   rc = osMkdir(zLockFile, 0777);
   32913   if( rc<0 ){
   32914     /* failed to open/create the lock directory */
   32915     int tErrno = errno;
   32916     if( EEXIST == tErrno ){
   32917       rc = SQLITE_BUSY;
   32918     } else {
   32919       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   32920       if( rc!=SQLITE_BUSY ){
   32921         storeLastErrno(pFile, tErrno);
   32922       }
   32923     }
   32924     return rc;
   32925   }
   32926 
   32927   /* got it, set the type and return ok */
   32928   pFile->eFileLock = eFileLock;
   32929   return rc;
   32930 }
   32931 
   32932 /*
   32933 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   32934 ** must be either NO_LOCK or SHARED_LOCK.
   32935 **
   32936 ** If the locking level of the file descriptor is already at or below
   32937 ** the requested locking level, this routine is a no-op.
   32938 **
   32939 ** When the locking level reaches NO_LOCK, delete the lock file.
   32940 */
   32941 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   32942   unixFile *pFile = (unixFile*)id;
   32943   char *zLockFile = (char *)pFile->lockingContext;
   32944   int rc;
   32945 
   32946   assert( pFile );
   32947   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
   32948            pFile->eFileLock, osGetpid(0)));
   32949   assert( eFileLock<=SHARED_LOCK );
   32950 
   32951   /* no-op if possible */
   32952   if( pFile->eFileLock==eFileLock ){
   32953     return SQLITE_OK;
   32954   }
   32955 
   32956   /* To downgrade to shared, simply update our internal notion of the
   32957   ** lock state.  No need to mess with the file on disk.
   32958   */
   32959   if( eFileLock==SHARED_LOCK ){
   32960     pFile->eFileLock = SHARED_LOCK;
   32961     return SQLITE_OK;
   32962   }
   32963 
   32964   /* To fully unlock the database, delete the lock file */
   32965   assert( eFileLock==NO_LOCK );
   32966   rc = osRmdir(zLockFile);
   32967   if( rc<0 ){
   32968     int tErrno = errno;
   32969     if( tErrno==ENOENT ){
   32970       rc = SQLITE_OK;
   32971     }else{
   32972       rc = SQLITE_IOERR_UNLOCK;
   32973       storeLastErrno(pFile, tErrno);
   32974     }
   32975     return rc;
   32976   }
   32977   pFile->eFileLock = NO_LOCK;
   32978   return SQLITE_OK;
   32979 }
   32980 
   32981 /*
   32982 ** Close a file.  Make sure the lock has been released before closing.
   32983 */
   32984 static int dotlockClose(sqlite3_file *id) {
   32985   unixFile *pFile = (unixFile*)id;
   32986   assert( id!=0 );
   32987   dotlockUnlock(id, NO_LOCK);
   32988   sqlite3_free(pFile->lockingContext);
   32989   return closeUnixFile(id);
   32990 }
   32991 /****************** End of the dot-file lock implementation *******************
   32992 ******************************************************************************/
   32993 
   32994 /******************************************************************************
   32995 ************************** Begin flock Locking ********************************
   32996 **
   32997 ** Use the flock() system call to do file locking.
   32998 **
   32999 ** flock() locking is like dot-file locking in that the various
   33000 ** fine-grain locking levels supported by SQLite are collapsed into
   33001 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   33002 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   33003 ** still works when you do this, but concurrency is reduced since
   33004 ** only a single process can be reading the database at a time.
   33005 **
   33006 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
   33007 */
   33008 #if SQLITE_ENABLE_LOCKING_STYLE
   33009 
   33010 /*
   33011 ** Retry flock() calls that fail with EINTR
   33012 */
   33013 #ifdef EINTR
   33014 static int robust_flock(int fd, int op){
   33015   int rc;
   33016   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
   33017   return rc;
   33018 }
   33019 #else
   33020 # define robust_flock(a,b) flock(a,b)
   33021 #endif
   33022 
   33023 
   33024 /*
   33025 ** This routine checks if there is a RESERVED lock held on the specified
   33026 ** file by this or any other process. If such a lock is held, set *pResOut
   33027 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   33028 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   33029 */
   33030 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   33031   int rc = SQLITE_OK;
   33032   int reserved = 0;
   33033   unixFile *pFile = (unixFile*)id;
   33034 
   33035   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   33036 
   33037   assert( pFile );
   33038 
   33039   /* Check if a thread in this process holds such a lock */
   33040   if( pFile->eFileLock>SHARED_LOCK ){
   33041     reserved = 1;
   33042   }
   33043 
   33044   /* Otherwise see if some other process holds it. */
   33045   if( !reserved ){
   33046     /* attempt to get the lock */
   33047     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
   33048     if( !lrc ){
   33049       /* got the lock, unlock it */
   33050       lrc = robust_flock(pFile->h, LOCK_UN);
   33051       if ( lrc ) {
   33052         int tErrno = errno;
   33053         /* unlock failed with an error */
   33054         lrc = SQLITE_IOERR_UNLOCK;
   33055         storeLastErrno(pFile, tErrno);
   33056         rc = lrc;
   33057       }
   33058     } else {
   33059       int tErrno = errno;
   33060       reserved = 1;
   33061       /* someone else might have it reserved */
   33062       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   33063       if( IS_LOCK_ERROR(lrc) ){
   33064         storeLastErrno(pFile, tErrno);
   33065         rc = lrc;
   33066       }
   33067     }
   33068   }
   33069   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
   33070 
   33071 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   33072   if( (rc & 0xff) == SQLITE_IOERR ){
   33073     rc = SQLITE_OK;
   33074     reserved=1;
   33075   }
   33076 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   33077   *pResOut = reserved;
   33078   return rc;
   33079 }
   33080 
   33081 /*
   33082 ** Lock the file with the lock specified by parameter eFileLock - one
   33083 ** of the following:
   33084 **
   33085 **     (1) SHARED_LOCK
   33086 **     (2) RESERVED_LOCK
   33087 **     (3) PENDING_LOCK
   33088 **     (4) EXCLUSIVE_LOCK
   33089 **
   33090 ** Sometimes when requesting one lock state, additional lock states
   33091 ** are inserted in between.  The locking might fail on one of the later
   33092 ** transitions leaving the lock state different from what it started but
   33093 ** still short of its goal.  The following chart shows the allowed
   33094 ** transitions and the inserted intermediate states:
   33095 **
   33096 **    UNLOCKED -> SHARED
   33097 **    SHARED -> RESERVED
   33098 **    SHARED -> (PENDING) -> EXCLUSIVE
   33099 **    RESERVED -> (PENDING) -> EXCLUSIVE
   33100 **    PENDING -> EXCLUSIVE
   33101 **
   33102 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   33103 ** lock states in the sqlite3_file structure, but all locks SHARED or
   33104 ** above are really EXCLUSIVE locks and exclude all other processes from
   33105 ** access the file.
   33106 **
   33107 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   33108 ** routine to lower a locking level.
   33109 */
   33110 static int flockLock(sqlite3_file *id, int eFileLock) {
   33111   int rc = SQLITE_OK;
   33112   unixFile *pFile = (unixFile*)id;
   33113 
   33114   assert( pFile );
   33115 
   33116   /* if we already have a lock, it is exclusive.
   33117   ** Just adjust level and punt on outta here. */
   33118   if (pFile->eFileLock > NO_LOCK) {
   33119     pFile->eFileLock = eFileLock;
   33120     return SQLITE_OK;
   33121   }
   33122 
   33123   /* grab an exclusive lock */
   33124 
   33125   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
   33126     int tErrno = errno;
   33127     /* didn't get, must be busy */
   33128     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   33129     if( IS_LOCK_ERROR(rc) ){
   33130       storeLastErrno(pFile, tErrno);
   33131     }
   33132   } else {
   33133     /* got it, set the type and return ok */
   33134     pFile->eFileLock = eFileLock;
   33135   }
   33136   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
   33137            rc==SQLITE_OK ? "ok" : "failed"));
   33138 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   33139   if( (rc & 0xff) == SQLITE_IOERR ){
   33140     rc = SQLITE_BUSY;
   33141   }
   33142 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   33143   return rc;
   33144 }
   33145 
   33146 
   33147 /*
   33148 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   33149 ** must be either NO_LOCK or SHARED_LOCK.
   33150 **
   33151 ** If the locking level of the file descriptor is already at or below
   33152 ** the requested locking level, this routine is a no-op.
   33153 */
   33154 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   33155   unixFile *pFile = (unixFile*)id;
   33156 
   33157   assert( pFile );
   33158   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
   33159            pFile->eFileLock, osGetpid(0)));
   33160   assert( eFileLock<=SHARED_LOCK );
   33161 
   33162   /* no-op if possible */
   33163   if( pFile->eFileLock==eFileLock ){
   33164     return SQLITE_OK;
   33165   }
   33166 
   33167   /* shared can just be set because we always have an exclusive */
   33168   if (eFileLock==SHARED_LOCK) {
   33169     pFile->eFileLock = eFileLock;
   33170     return SQLITE_OK;
   33171   }
   33172 
   33173   /* no, really, unlock. */
   33174   if( robust_flock(pFile->h, LOCK_UN) ){
   33175 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   33176     return SQLITE_OK;
   33177 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   33178     return SQLITE_IOERR_UNLOCK;
   33179   }else{
   33180     pFile->eFileLock = NO_LOCK;
   33181     return SQLITE_OK;
   33182   }
   33183 }
   33184 
   33185 /*
   33186 ** Close a file.
   33187 */
   33188 static int flockClose(sqlite3_file *id) {
   33189   assert( id!=0 );
   33190   flockUnlock(id, NO_LOCK);
   33191   return closeUnixFile(id);
   33192 }
   33193 
   33194 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   33195 
   33196 /******************* End of the flock lock implementation *********************
   33197 ******************************************************************************/
   33198 
   33199 /******************************************************************************
   33200 ************************ Begin Named Semaphore Locking ************************
   33201 **
   33202 ** Named semaphore locking is only supported on VxWorks.
   33203 **
   33204 ** Semaphore locking is like dot-lock and flock in that it really only
   33205 ** supports EXCLUSIVE locking.  Only a single process can read or write
   33206 ** the database file at a time.  This reduces potential concurrency, but
   33207 ** makes the lock implementation much easier.
   33208 */
   33209 #if OS_VXWORKS
   33210 
   33211 /*
   33212 ** This routine checks if there is a RESERVED lock held on the specified
   33213 ** file by this or any other process. If such a lock is held, set *pResOut
   33214 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   33215 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   33216 */
   33217 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
   33218   int rc = SQLITE_OK;
   33219   int reserved = 0;
   33220   unixFile *pFile = (unixFile*)id;
   33221 
   33222   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   33223 
   33224   assert( pFile );
   33225 
   33226   /* Check if a thread in this process holds such a lock */
   33227   if( pFile->eFileLock>SHARED_LOCK ){
   33228     reserved = 1;
   33229   }
   33230 
   33231   /* Otherwise see if some other process holds it. */
   33232   if( !reserved ){
   33233     sem_t *pSem = pFile->pInode->pSem;
   33234 
   33235     if( sem_trywait(pSem)==-1 ){
   33236       int tErrno = errno;
   33237       if( EAGAIN != tErrno ){
   33238         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   33239         storeLastErrno(pFile, tErrno);
   33240       } else {
   33241         /* someone else has the lock when we are in NO_LOCK */
   33242         reserved = (pFile->eFileLock < SHARED_LOCK);
   33243       }
   33244     }else{
   33245       /* we could have it if we want it */
   33246       sem_post(pSem);
   33247     }
   33248   }
   33249   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
   33250 
   33251   *pResOut = reserved;
   33252   return rc;
   33253 }
   33254 
   33255 /*
   33256 ** Lock the file with the lock specified by parameter eFileLock - one
   33257 ** of the following:
   33258 **
   33259 **     (1) SHARED_LOCK
   33260 **     (2) RESERVED_LOCK
   33261 **     (3) PENDING_LOCK
   33262 **     (4) EXCLUSIVE_LOCK
   33263 **
   33264 ** Sometimes when requesting one lock state, additional lock states
   33265 ** are inserted in between.  The locking might fail on one of the later
   33266 ** transitions leaving the lock state different from what it started but
   33267 ** still short of its goal.  The following chart shows the allowed
   33268 ** transitions and the inserted intermediate states:
   33269 **
   33270 **    UNLOCKED -> SHARED
   33271 **    SHARED -> RESERVED
   33272 **    SHARED -> (PENDING) -> EXCLUSIVE
   33273 **    RESERVED -> (PENDING) -> EXCLUSIVE
   33274 **    PENDING -> EXCLUSIVE
   33275 **
   33276 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   33277 ** lock states in the sqlite3_file structure, but all locks SHARED or
   33278 ** above are really EXCLUSIVE locks and exclude all other processes from
   33279 ** access the file.
   33280 **
   33281 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   33282 ** routine to lower a locking level.
   33283 */
   33284 static int semXLock(sqlite3_file *id, int eFileLock) {
   33285   unixFile *pFile = (unixFile*)id;
   33286   sem_t *pSem = pFile->pInode->pSem;
   33287   int rc = SQLITE_OK;
   33288 
   33289   /* if we already have a lock, it is exclusive.
   33290   ** Just adjust level and punt on outta here. */
   33291   if (pFile->eFileLock > NO_LOCK) {
   33292     pFile->eFileLock = eFileLock;
   33293     rc = SQLITE_OK;
   33294     goto sem_end_lock;
   33295   }
   33296 
   33297   /* lock semaphore now but bail out when already locked. */
   33298   if( sem_trywait(pSem)==-1 ){
   33299     rc = SQLITE_BUSY;
   33300     goto sem_end_lock;
   33301   }
   33302 
   33303   /* got it, set the type and return ok */
   33304   pFile->eFileLock = eFileLock;
   33305 
   33306  sem_end_lock:
   33307   return rc;
   33308 }
   33309 
   33310 /*
   33311 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   33312 ** must be either NO_LOCK or SHARED_LOCK.
   33313 **
   33314 ** If the locking level of the file descriptor is already at or below
   33315 ** the requested locking level, this routine is a no-op.
   33316 */
   33317 static int semXUnlock(sqlite3_file *id, int eFileLock) {
   33318   unixFile *pFile = (unixFile*)id;
   33319   sem_t *pSem = pFile->pInode->pSem;
   33320 
   33321   assert( pFile );
   33322   assert( pSem );
   33323   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
   33324            pFile->eFileLock, osGetpid(0)));
   33325   assert( eFileLock<=SHARED_LOCK );
   33326 
   33327   /* no-op if possible */
   33328   if( pFile->eFileLock==eFileLock ){
   33329     return SQLITE_OK;
   33330   }
   33331 
   33332   /* shared can just be set because we always have an exclusive */
   33333   if (eFileLock==SHARED_LOCK) {
   33334     pFile->eFileLock = eFileLock;
   33335     return SQLITE_OK;
   33336   }
   33337 
   33338   /* no, really unlock. */
   33339   if ( sem_post(pSem)==-1 ) {
   33340     int rc, tErrno = errno;
   33341     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   33342     if( IS_LOCK_ERROR(rc) ){
   33343       storeLastErrno(pFile, tErrno);
   33344     }
   33345     return rc;
   33346   }
   33347   pFile->eFileLock = NO_LOCK;
   33348   return SQLITE_OK;
   33349 }
   33350 
   33351 /*
   33352  ** Close a file.
   33353  */
   33354 static int semXClose(sqlite3_file *id) {
   33355   if( id ){
   33356     unixFile *pFile = (unixFile*)id;
   33357     semXUnlock(id, NO_LOCK);
   33358     assert( pFile );
   33359     unixEnterMutex();
   33360     releaseInodeInfo(pFile);
   33361     unixLeaveMutex();
   33362     closeUnixFile(id);
   33363   }
   33364   return SQLITE_OK;
   33365 }
   33366 
   33367 #endif /* OS_VXWORKS */
   33368 /*
   33369 ** Named semaphore locking is only available on VxWorks.
   33370 **
   33371 *************** End of the named semaphore lock implementation ****************
   33372 ******************************************************************************/
   33373 
   33374 
   33375 /******************************************************************************
   33376 *************************** Begin AFP Locking *********************************
   33377 **
   33378 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   33379 ** on Apple Macintosh computers - both OS9 and OSX.
   33380 **
   33381 ** Third-party implementations of AFP are available.  But this code here
   33382 ** only works on OSX.
   33383 */
   33384 
   33385 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   33386 /*
   33387 ** The afpLockingContext structure contains all afp lock specific state
   33388 */
   33389 typedef struct afpLockingContext afpLockingContext;
   33390 struct afpLockingContext {
   33391   int reserved;
   33392   const char *dbPath;             /* Name of the open file */
   33393 };
   33394 
   33395 struct ByteRangeLockPB2
   33396 {
   33397   unsigned long long offset;        /* offset to first byte to lock */
   33398   unsigned long long length;        /* nbr of bytes to lock */
   33399   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   33400   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   33401   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   33402   int fd;                           /* file desc to assoc this lock with */
   33403 };
   33404 
   33405 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   33406 
   33407 /*
   33408 ** This is a utility for setting or clearing a bit-range lock on an
   33409 ** AFP filesystem.
   33410 **
   33411 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   33412 */
   33413 static int afpSetLock(
   33414   const char *path,              /* Name of the file to be locked or unlocked */
   33415   unixFile *pFile,               /* Open file descriptor on path */
   33416   unsigned long long offset,     /* First byte to be locked */
   33417   unsigned long long length,     /* Number of bytes to lock */
   33418   int setLockFlag                /* True to set lock.  False to clear lock */
   33419 ){
   33420   struct ByteRangeLockPB2 pb;
   33421   int err;
   33422 
   33423   pb.unLockFlag = setLockFlag ? 0 : 1;
   33424   pb.startEndFlag = 0;
   33425   pb.offset = offset;
   33426   pb.length = length;
   33427   pb.fd = pFile->h;
   33428 
   33429   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   33430     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   33431     offset, length));
   33432   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   33433   if ( err==-1 ) {
   33434     int rc;
   33435     int tErrno = errno;
   33436     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   33437              path, tErrno, strerror(tErrno)));
   33438 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   33439     rc = SQLITE_BUSY;
   33440 #else
   33441     rc = sqliteErrorFromPosixError(tErrno,
   33442                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   33443 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   33444     if( IS_LOCK_ERROR(rc) ){
   33445       storeLastErrno(pFile, tErrno);
   33446     }
   33447     return rc;
   33448   } else {
   33449     return SQLITE_OK;
   33450   }
   33451 }
   33452 
   33453 /*
   33454 ** This routine checks if there is a RESERVED lock held on the specified
   33455 ** file by this or any other process. If such a lock is held, set *pResOut
   33456 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   33457 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   33458 */
   33459 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   33460   int rc = SQLITE_OK;
   33461   int reserved = 0;
   33462   unixFile *pFile = (unixFile*)id;
   33463   afpLockingContext *context;
   33464 
   33465   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   33466 
   33467   assert( pFile );
   33468   context = (afpLockingContext *) pFile->lockingContext;
   33469   if( context->reserved ){
   33470     *pResOut = 1;
   33471     return SQLITE_OK;
   33472   }
   33473   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   33474 
   33475   /* Check if a thread in this process holds such a lock */
   33476   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   33477     reserved = 1;
   33478   }
   33479 
   33480   /* Otherwise see if some other process holds it.
   33481    */
   33482   if( !reserved ){
   33483     /* lock the RESERVED byte */
   33484     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   33485     if( SQLITE_OK==lrc ){
   33486       /* if we succeeded in taking the reserved lock, unlock it to restore
   33487       ** the original state */
   33488       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   33489     } else {
   33490       /* if we failed to get the lock then someone else must have it */
   33491       reserved = 1;
   33492     }
   33493     if( IS_LOCK_ERROR(lrc) ){
   33494       rc=lrc;
   33495     }
   33496   }
   33497 
   33498   unixLeaveMutex();
   33499   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
   33500 
   33501   *pResOut = reserved;
   33502   return rc;
   33503 }
   33504 
   33505 /*
   33506 ** Lock the file with the lock specified by parameter eFileLock - one
   33507 ** of the following:
   33508 **
   33509 **     (1) SHARED_LOCK
   33510 **     (2) RESERVED_LOCK
   33511 **     (3) PENDING_LOCK
   33512 **     (4) EXCLUSIVE_LOCK
   33513 **
   33514 ** Sometimes when requesting one lock state, additional lock states
   33515 ** are inserted in between.  The locking might fail on one of the later
   33516 ** transitions leaving the lock state different from what it started but
   33517 ** still short of its goal.  The following chart shows the allowed
   33518 ** transitions and the inserted intermediate states:
   33519 **
   33520 **    UNLOCKED -> SHARED
   33521 **    SHARED -> RESERVED
   33522 **    SHARED -> (PENDING) -> EXCLUSIVE
   33523 **    RESERVED -> (PENDING) -> EXCLUSIVE
   33524 **    PENDING -> EXCLUSIVE
   33525 **
   33526 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   33527 ** routine to lower a locking level.
   33528 */
   33529 static int afpLock(sqlite3_file *id, int eFileLock){
   33530   int rc = SQLITE_OK;
   33531   unixFile *pFile = (unixFile*)id;
   33532   unixInodeInfo *pInode = pFile->pInode;
   33533   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   33534 
   33535   assert( pFile );
   33536   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
   33537            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   33538            azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
   33539 
   33540   /* If there is already a lock of this type or more restrictive on the
   33541   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   33542   ** unixEnterMutex() hasn't been called yet.
   33543   */
   33544   if( pFile->eFileLock>=eFileLock ){
   33545     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   33546            azFileLock(eFileLock)));
   33547     return SQLITE_OK;
   33548   }
   33549 
   33550   /* Make sure the locking sequence is correct
   33551   **  (1) We never move from unlocked to anything higher than shared lock.
   33552   **  (2) SQLite never explicitly requests a pendig lock.
   33553   **  (3) A shared lock is always held when a reserve lock is requested.
   33554   */
   33555   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   33556   assert( eFileLock!=PENDING_LOCK );
   33557   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   33558 
   33559   /* This mutex is needed because pFile->pInode is shared across threads
   33560   */
   33561   unixEnterMutex();
   33562   pInode = pFile->pInode;
   33563 
   33564   /* If some thread using this PID has a lock via a different unixFile*
   33565   ** handle that precludes the requested lock, return BUSY.
   33566   */
   33567   if( (pFile->eFileLock!=pInode->eFileLock &&
   33568        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   33569      ){
   33570     rc = SQLITE_BUSY;
   33571     goto afp_end_lock;
   33572   }
   33573 
   33574   /* If a SHARED lock is requested, and some thread using this PID already
   33575   ** has a SHARED or RESERVED lock, then increment reference counts and
   33576   ** return SQLITE_OK.
   33577   */
   33578   if( eFileLock==SHARED_LOCK &&
   33579      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   33580     assert( eFileLock==SHARED_LOCK );
   33581     assert( pFile->eFileLock==0 );
   33582     assert( pInode->nShared>0 );
   33583     pFile->eFileLock = SHARED_LOCK;
   33584     pInode->nShared++;
   33585     pInode->nLock++;
   33586     goto afp_end_lock;
   33587   }
   33588 
   33589   /* A PENDING lock is needed before acquiring a SHARED lock and before
   33590   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   33591   ** be released.
   33592   */
   33593   if( eFileLock==SHARED_LOCK
   33594       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   33595   ){
   33596     int failed;
   33597     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   33598     if (failed) {
   33599       rc = failed;
   33600       goto afp_end_lock;
   33601     }
   33602   }
   33603 
   33604   /* If control gets to this point, then actually go ahead and make
   33605   ** operating system calls for the specified lock.
   33606   */
   33607   if( eFileLock==SHARED_LOCK ){
   33608     int lrc1, lrc2, lrc1Errno = 0;
   33609     long lk, mask;
   33610 
   33611     assert( pInode->nShared==0 );
   33612     assert( pInode->eFileLock==0 );
   33613 
   33614     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
   33615     /* Now get the read-lock SHARED_LOCK */
   33616     /* note that the quality of the randomness doesn't matter that much */
   33617     lk = random();
   33618     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
   33619     lrc1 = afpSetLock(context->dbPath, pFile,
   33620           SHARED_FIRST+pInode->sharedByte, 1, 1);
   33621     if( IS_LOCK_ERROR(lrc1) ){
   33622       lrc1Errno = pFile->lastErrno;
   33623     }
   33624     /* Drop the temporary PENDING lock */
   33625     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   33626 
   33627     if( IS_LOCK_ERROR(lrc1) ) {
   33628       storeLastErrno(pFile, lrc1Errno);
   33629       rc = lrc1;
   33630       goto afp_end_lock;
   33631     } else if( IS_LOCK_ERROR(lrc2) ){
   33632       rc = lrc2;
   33633       goto afp_end_lock;
   33634     } else if( lrc1 != SQLITE_OK ) {
   33635       rc = lrc1;
   33636     } else {
   33637       pFile->eFileLock = SHARED_LOCK;
   33638       pInode->nLock++;
   33639       pInode->nShared = 1;
   33640     }
   33641   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   33642     /* We are trying for an exclusive lock but another thread in this
   33643      ** same process is still holding a shared lock. */
   33644     rc = SQLITE_BUSY;
   33645   }else{
   33646     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   33647     ** assumed that there is a SHARED or greater lock on the file
   33648     ** already.
   33649     */
   33650     int failed = 0;
   33651     assert( 0!=pFile->eFileLock );
   33652     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
   33653         /* Acquire a RESERVED lock */
   33654         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   33655       if( !failed ){
   33656         context->reserved = 1;
   33657       }
   33658     }
   33659     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
   33660       /* Acquire an EXCLUSIVE lock */
   33661 
   33662       /* Remove the shared lock before trying the range.  we'll need to
   33663       ** reestablish the shared lock if we can't get the  afpUnlock
   33664       */
   33665       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   33666                          pInode->sharedByte, 1, 0)) ){
   33667         int failed2 = SQLITE_OK;
   33668         /* now attemmpt to get the exclusive lock range */
   33669         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   33670                                SHARED_SIZE, 1);
   33671         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   33672                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
   33673           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   33674           ** a critical I/O error
   33675           */
   33676           rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
   33677                SQLITE_IOERR_LOCK;
   33678           goto afp_end_lock;
   33679         }
   33680       }else{
   33681         rc = failed;
   33682       }
   33683     }
   33684     if( failed ){
   33685       rc = failed;
   33686     }
   33687   }
   33688 
   33689   if( rc==SQLITE_OK ){
   33690     pFile->eFileLock = eFileLock;
   33691     pInode->eFileLock = eFileLock;
   33692   }else if( eFileLock==EXCLUSIVE_LOCK ){
   33693     pFile->eFileLock = PENDING_LOCK;
   33694     pInode->eFileLock = PENDING_LOCK;
   33695   }
   33696 
   33697 afp_end_lock:
   33698   unixLeaveMutex();
   33699   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
   33700          rc==SQLITE_OK ? "ok" : "failed"));
   33701   return rc;
   33702 }
   33703 
   33704 /*
   33705 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   33706 ** must be either NO_LOCK or SHARED_LOCK.
   33707 **
   33708 ** If the locking level of the file descriptor is already at or below
   33709 ** the requested locking level, this routine is a no-op.
   33710 */
   33711 static int afpUnlock(sqlite3_file *id, int eFileLock) {
   33712   int rc = SQLITE_OK;
   33713   unixFile *pFile = (unixFile*)id;
   33714   unixInodeInfo *pInode;
   33715   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   33716   int skipShared = 0;
   33717 #ifdef SQLITE_TEST
   33718   int h = pFile->h;
   33719 #endif
   33720 
   33721   assert( pFile );
   33722   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
   33723            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   33724            osGetpid(0)));
   33725 
   33726   assert( eFileLock<=SHARED_LOCK );
   33727   if( pFile->eFileLock<=eFileLock ){
   33728     return SQLITE_OK;
   33729   }
   33730   unixEnterMutex();
   33731   pInode = pFile->pInode;
   33732   assert( pInode->nShared!=0 );
   33733   if( pFile->eFileLock>SHARED_LOCK ){
   33734     assert( pInode->eFileLock==pFile->eFileLock );
   33735     SimulateIOErrorBenign(1);
   33736     SimulateIOError( h=(-1) )
   33737     SimulateIOErrorBenign(0);
   33738 
   33739 #ifdef SQLITE_DEBUG
   33740     /* When reducing a lock such that other processes can start
   33741     ** reading the database file again, make sure that the
   33742     ** transaction counter was updated if any part of the database
   33743     ** file changed.  If the transaction counter is not updated,
   33744     ** other connections to the same file might not realize that
   33745     ** the file has changed and hence might not know to flush their
   33746     ** cache.  The use of a stale cache can lead to database corruption.
   33747     */
   33748     assert( pFile->inNormalWrite==0
   33749            || pFile->dbUpdate==0
   33750            || pFile->transCntrChng==1 );
   33751     pFile->inNormalWrite = 0;
   33752 #endif
   33753 
   33754     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
   33755       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   33756       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
   33757         /* only re-establish the shared lock if necessary */
   33758         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   33759         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
   33760       } else {
   33761         skipShared = 1;
   33762       }
   33763     }
   33764     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
   33765       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   33766     }
   33767     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
   33768       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   33769       if( !rc ){
   33770         context->reserved = 0;
   33771       }
   33772     }
   33773     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
   33774       pInode->eFileLock = SHARED_LOCK;
   33775     }
   33776   }
   33777   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
   33778 
   33779     /* Decrement the shared lock counter.  Release the lock using an
   33780     ** OS call only when all threads in this same process have released
   33781     ** the lock.
   33782     */
   33783     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   33784     pInode->nShared--;
   33785     if( pInode->nShared==0 ){
   33786       SimulateIOErrorBenign(1);
   33787       SimulateIOError( h=(-1) )
   33788       SimulateIOErrorBenign(0);
   33789       if( !skipShared ){
   33790         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
   33791       }
   33792       if( !rc ){
   33793         pInode->eFileLock = NO_LOCK;
   33794         pFile->eFileLock = NO_LOCK;
   33795       }
   33796     }
   33797     if( rc==SQLITE_OK ){
   33798       pInode->nLock--;
   33799       assert( pInode->nLock>=0 );
   33800       if( pInode->nLock==0 ){
   33801         closePendingFds(pFile);
   33802       }
   33803     }
   33804   }
   33805 
   33806   unixLeaveMutex();
   33807   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   33808   return rc;
   33809 }
   33810 
   33811 /*
   33812 ** Close a file & cleanup AFP specific locking context
   33813 */
   33814 static int afpClose(sqlite3_file *id) {
   33815   int rc = SQLITE_OK;
   33816   unixFile *pFile = (unixFile*)id;
   33817   assert( id!=0 );
   33818   afpUnlock(id, NO_LOCK);
   33819   unixEnterMutex();
   33820   if( pFile->pInode && pFile->pInode->nLock ){
   33821     /* If there are outstanding locks, do not actually close the file just
   33822     ** yet because that would clear those locks.  Instead, add the file
   33823     ** descriptor to pInode->aPending.  It will be automatically closed when
   33824     ** the last lock is cleared.
   33825     */
   33826     setPendingFd(pFile);
   33827   }
   33828   releaseInodeInfo(pFile);
   33829   sqlite3_free(pFile->lockingContext);
   33830   rc = closeUnixFile(id);
   33831   unixLeaveMutex();
   33832   return rc;
   33833 }
   33834 
   33835 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   33836 /*
   33837 ** The code above is the AFP lock implementation.  The code is specific
   33838 ** to MacOSX and does not work on other unix platforms.  No alternative
   33839 ** is available.  If you don't compile for a mac, then the "unix-afp"
   33840 ** VFS is not available.
   33841 **
   33842 ********************* End of the AFP lock implementation **********************
   33843 ******************************************************************************/
   33844 
   33845 /******************************************************************************
   33846 *************************** Begin NFS Locking ********************************/
   33847 
   33848 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   33849 /*
   33850  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   33851  ** must be either NO_LOCK or SHARED_LOCK.
   33852  **
   33853  ** If the locking level of the file descriptor is already at or below
   33854  ** the requested locking level, this routine is a no-op.
   33855  */
   33856 static int nfsUnlock(sqlite3_file *id, int eFileLock){
   33857   return posixUnlock(id, eFileLock, 1);
   33858 }
   33859 
   33860 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   33861 /*
   33862 ** The code above is the NFS lock implementation.  The code is specific
   33863 ** to MacOSX and does not work on other unix platforms.  No alternative
   33864 ** is available.
   33865 **
   33866 ********************* End of the NFS lock implementation **********************
   33867 ******************************************************************************/
   33868 
   33869 /******************************************************************************
   33870 **************** Non-locking sqlite3_file methods *****************************
   33871 **
   33872 ** The next division contains implementations for all methods of the
   33873 ** sqlite3_file object other than the locking methods.  The locking
   33874 ** methods were defined in divisions above (one locking method per
   33875 ** division).  Those methods that are common to all locking modes
   33876 ** are gather together into this division.
   33877 */
   33878 
   33879 /*
   33880 ** Seek to the offset passed as the second argument, then read cnt
   33881 ** bytes into pBuf. Return the number of bytes actually read.
   33882 **
   33883 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   33884 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   33885 ** one system to another.  Since SQLite does not define USE_PREAD
   33886 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
   33887 ** See tickets #2741 and #2681.
   33888 **
   33889 ** To avoid stomping the errno value on a failed read the lastErrno value
   33890 ** is set before returning.
   33891 */
   33892 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   33893   int got;
   33894   int prior = 0;
   33895 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   33896   i64 newOffset;
   33897 #endif
   33898   TIMER_START;
   33899   assert( cnt==(cnt&0x1ffff) );
   33900   assert( id->h>2 );
   33901   do{
   33902 #if defined(USE_PREAD)
   33903     got = osPread(id->h, pBuf, cnt, offset);
   33904     SimulateIOError( got = -1 );
   33905 #elif defined(USE_PREAD64)
   33906     got = osPread64(id->h, pBuf, cnt, offset);
   33907     SimulateIOError( got = -1 );
   33908 #else
   33909     newOffset = lseek(id->h, offset, SEEK_SET);
   33910     SimulateIOError( newOffset = -1 );
   33911     if( newOffset<0 ){
   33912       storeLastErrno((unixFile*)id, errno);
   33913       return -1;
   33914     }
   33915     got = osRead(id->h, pBuf, cnt);
   33916 #endif
   33917     if( got==cnt ) break;
   33918     if( got<0 ){
   33919       if( errno==EINTR ){ got = 1; continue; }
   33920       prior = 0;
   33921       storeLastErrno((unixFile*)id,  errno);
   33922       break;
   33923     }else if( got>0 ){
   33924       cnt -= got;
   33925       offset += got;
   33926       prior += got;
   33927       pBuf = (void*)(got + (char*)pBuf);
   33928     }
   33929   }while( got>0 );
   33930   TIMER_END;
   33931   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
   33932             id->h, got+prior, offset-prior, TIMER_ELAPSED));
   33933   return got+prior;
   33934 }
   33935 
   33936 /*
   33937 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   33938 ** bytes were read successfully and SQLITE_IOERR if anything goes
   33939 ** wrong.
   33940 */
   33941 static int unixRead(
   33942   sqlite3_file *id,
   33943   void *pBuf,
   33944   int amt,
   33945   sqlite3_int64 offset
   33946 ){
   33947   unixFile *pFile = (unixFile *)id;
   33948   int got;
   33949   assert( id );
   33950   assert( offset>=0 );
   33951   assert( amt>0 );
   33952 
   33953   /* If this is a database file (not a journal, master-journal or temp
   33954   ** file), the bytes in the locking range should never be read or written. */
   33955 #if 0
   33956   assert( pFile->pPreallocatedUnused==0
   33957        || offset>=PENDING_BYTE+512
   33958        || offset+amt<=PENDING_BYTE
   33959   );
   33960 #endif
   33961 
   33962 #if SQLITE_MAX_MMAP_SIZE>0
   33963   /* Deal with as much of this read request as possible by transfering
   33964   ** data from the memory mapping using memcpy().  */
   33965   if( offset<pFile->mmapSize ){
   33966     if( offset+amt <= pFile->mmapSize ){
   33967       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
   33968       return SQLITE_OK;
   33969     }else{
   33970       int nCopy = pFile->mmapSize - offset;
   33971       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
   33972       pBuf = &((u8 *)pBuf)[nCopy];
   33973       amt -= nCopy;
   33974       offset += nCopy;
   33975     }
   33976   }
   33977 #endif
   33978 
   33979   got = seekAndRead(pFile, offset, pBuf, amt);
   33980   if( got==amt ){
   33981     return SQLITE_OK;
   33982   }else if( got<0 ){
   33983     /* lastErrno set by seekAndRead */
   33984     return SQLITE_IOERR_READ;
   33985   }else{
   33986     storeLastErrno(pFile, 0);   /* not a system error */
   33987     /* Unread parts of the buffer must be zero-filled */
   33988     memset(&((char*)pBuf)[got], 0, amt-got);
   33989     return SQLITE_IOERR_SHORT_READ;
   33990   }
   33991 }
   33992 
   33993 /*
   33994 ** Attempt to seek the file-descriptor passed as the first argument to
   33995 ** absolute offset iOff, then attempt to write nBuf bytes of data from
   33996 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
   33997 ** return the actual number of bytes written (which may be less than
   33998 ** nBuf).
   33999 */
   34000 static int seekAndWriteFd(
   34001   int fd,                         /* File descriptor to write to */
   34002   i64 iOff,                       /* File offset to begin writing at */
   34003   const void *pBuf,               /* Copy data from this buffer to the file */
   34004   int nBuf,                       /* Size of buffer pBuf in bytes */
   34005   int *piErrno                    /* OUT: Error number if error occurs */
   34006 ){
   34007   int rc = 0;                     /* Value returned by system call */
   34008 
   34009   assert( nBuf==(nBuf&0x1ffff) );
   34010   assert( fd>2 );
   34011   assert( piErrno!=0 );
   34012   nBuf &= 0x1ffff;
   34013   TIMER_START;
   34014 
   34015 #if defined(USE_PREAD)
   34016   do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
   34017 #elif defined(USE_PREAD64)
   34018   do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
   34019 #else
   34020   do{
   34021     i64 iSeek = lseek(fd, iOff, SEEK_SET);
   34022     SimulateIOError( iSeek = -1 );
   34023     if( iSeek<0 ){
   34024       rc = -1;
   34025       break;
   34026     }
   34027     rc = osWrite(fd, pBuf, nBuf);
   34028   }while( rc<0 && errno==EINTR );
   34029 #endif
   34030 
   34031   TIMER_END;
   34032   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
   34033 
   34034   if( rc<0 ) *piErrno = errno;
   34035   return rc;
   34036 }
   34037 
   34038 
   34039 /*
   34040 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   34041 ** Return the number of bytes actually read.  Update the offset.
   34042 **
   34043 ** To avoid stomping the errno value on a failed write the lastErrno value
   34044 ** is set before returning.
   34045 */
   34046 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   34047   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
   34048 }
   34049 
   34050 
   34051 /*
   34052 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   34053 ** or some other error code on failure.
   34054 */
   34055 static int unixWrite(
   34056   sqlite3_file *id,
   34057   const void *pBuf,
   34058   int amt,
   34059   sqlite3_int64 offset
   34060 ){
   34061   unixFile *pFile = (unixFile*)id;
   34062   int wrote = 0;
   34063   assert( id );
   34064   assert( amt>0 );
   34065 
   34066   /* If this is a database file (not a journal, master-journal or temp
   34067   ** file), the bytes in the locking range should never be read or written. */
   34068 #if 0
   34069   assert( pFile->pPreallocatedUnused==0
   34070        || offset>=PENDING_BYTE+512
   34071        || offset+amt<=PENDING_BYTE
   34072   );
   34073 #endif
   34074 
   34075 #ifdef SQLITE_DEBUG
   34076   /* If we are doing a normal write to a database file (as opposed to
   34077   ** doing a hot-journal rollback or a write to some file other than a
   34078   ** normal database file) then record the fact that the database
   34079   ** has changed.  If the transaction counter is modified, record that
   34080   ** fact too.
   34081   */
   34082   if( pFile->inNormalWrite ){
   34083     pFile->dbUpdate = 1;  /* The database has been modified */
   34084     if( offset<=24 && offset+amt>=27 ){
   34085       int rc;
   34086       char oldCntr[4];
   34087       SimulateIOErrorBenign(1);
   34088       rc = seekAndRead(pFile, 24, oldCntr, 4);
   34089       SimulateIOErrorBenign(0);
   34090       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   34091         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   34092       }
   34093     }
   34094   }
   34095 #endif
   34096 
   34097 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
   34098   /* Deal with as much of this write request as possible by transfering
   34099   ** data from the memory mapping using memcpy().  */
   34100   if( offset<pFile->mmapSize ){
   34101     if( offset+amt <= pFile->mmapSize ){
   34102       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
   34103       return SQLITE_OK;
   34104     }else{
   34105       int nCopy = pFile->mmapSize - offset;
   34106       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
   34107       pBuf = &((u8 *)pBuf)[nCopy];
   34108       amt -= nCopy;
   34109       offset += nCopy;
   34110     }
   34111   }
   34112 #endif
   34113 
   34114   while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
   34115     amt -= wrote;
   34116     offset += wrote;
   34117     pBuf = &((char*)pBuf)[wrote];
   34118   }
   34119   SimulateIOError(( wrote=(-1), amt=1 ));
   34120   SimulateDiskfullError(( wrote=0, amt=1 ));
   34121 
   34122   if( amt>wrote ){
   34123     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
   34124       /* lastErrno set by seekAndWrite */
   34125       return SQLITE_IOERR_WRITE;
   34126     }else{
   34127       storeLastErrno(pFile, 0); /* not a system error */
   34128       return SQLITE_FULL;
   34129     }
   34130   }
   34131 
   34132   return SQLITE_OK;
   34133 }
   34134 
   34135 #ifdef SQLITE_TEST
   34136 /*
   34137 ** Count the number of fullsyncs and normal syncs.  This is used to test
   34138 ** that syncs and fullsyncs are occurring at the right times.
   34139 */
   34140 SQLITE_API int sqlite3_sync_count = 0;
   34141 SQLITE_API int sqlite3_fullsync_count = 0;
   34142 #endif
   34143 
   34144 /*
   34145 ** We do not trust systems to provide a working fdatasync().  Some do.
   34146 ** Others do no.  To be safe, we will stick with the (slightly slower)
   34147 ** fsync(). If you know that your system does support fdatasync() correctly,
   34148 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
   34149 */
   34150 #if !defined(fdatasync) && !HAVE_FDATASYNC
   34151 # define fdatasync fsync
   34152 #endif
   34153 
   34154 /*
   34155 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   34156 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   34157 ** only available on Mac OS X.  But that could change.
   34158 */
   34159 #ifdef F_FULLFSYNC
   34160 # define HAVE_FULLFSYNC 1
   34161 #else
   34162 # define HAVE_FULLFSYNC 0
   34163 #endif
   34164 
   34165 
   34166 /*
   34167 ** The fsync() system call does not work as advertised on many
   34168 ** unix systems.  The following procedure is an attempt to make
   34169 ** it work better.
   34170 **
   34171 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   34172 ** for testing when we want to run through the test suite quickly.
   34173 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   34174 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   34175 ** or power failure will likely corrupt the database file.
   34176 **
   34177 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   34178 ** The idea behind dataOnly is that it should only write the file content
   34179 ** to disk, not the inode.  We only set dataOnly if the file size is
   34180 ** unchanged since the file size is part of the inode.  However,
   34181 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   34182 ** file size has changed.  The only real difference between fdatasync()
   34183 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   34184 ** inode if the mtime or owner or other inode attributes have changed.
   34185 ** We only care about the file size, not the other file attributes, so
   34186 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   34187 ** So, we always use fdatasync() if it is available, regardless of
   34188 ** the value of the dataOnly flag.
   34189 */
   34190 static int full_fsync(int fd, int fullSync, int dataOnly){
   34191   int rc;
   34192 
   34193   /* The following "ifdef/elif/else/" block has the same structure as
   34194   ** the one below. It is replicated here solely to avoid cluttering
   34195   ** up the real code with the UNUSED_PARAMETER() macros.
   34196   */
   34197 #ifdef SQLITE_NO_SYNC
   34198   UNUSED_PARAMETER(fd);
   34199   UNUSED_PARAMETER(fullSync);
   34200   UNUSED_PARAMETER(dataOnly);
   34201 #elif HAVE_FULLFSYNC
   34202   UNUSED_PARAMETER(dataOnly);
   34203 #else
   34204   UNUSED_PARAMETER(fullSync);
   34205   UNUSED_PARAMETER(dataOnly);
   34206 #endif
   34207 
   34208   /* Record the number of times that we do a normal fsync() and
   34209   ** FULLSYNC.  This is used during testing to verify that this procedure
   34210   ** gets called with the correct arguments.
   34211   */
   34212 #ifdef SQLITE_TEST
   34213   if( fullSync ) sqlite3_fullsync_count++;
   34214   sqlite3_sync_count++;
   34215 #endif
   34216 
   34217   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   34218   ** no-op.  But go ahead and call fstat() to validate the file
   34219   ** descriptor as we need a method to provoke a failure during
   34220   ** coverate testing.
   34221   */
   34222 #ifdef SQLITE_NO_SYNC
   34223   {
   34224     struct stat buf;
   34225     rc = osFstat(fd, &buf);
   34226   }
   34227 #elif HAVE_FULLFSYNC
   34228   if( fullSync ){
   34229     rc = osFcntl(fd, F_FULLFSYNC, 0);
   34230   }else{
   34231     rc = 1;
   34232   }
   34233   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   34234   ** It shouldn't be possible for fullfsync to fail on the local
   34235   ** file system (on OSX), so failure indicates that FULLFSYNC
   34236   ** isn't supported for this file system. So, attempt an fsync
   34237   ** and (for now) ignore the overhead of a superfluous fcntl call.
   34238   ** It'd be better to detect fullfsync support once and avoid
   34239   ** the fcntl call every time sync is called.
   34240   */
   34241   if( rc ) rc = fsync(fd);
   34242 
   34243 #elif defined(__APPLE__)
   34244   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
   34245   ** so currently we default to the macro that redefines fdatasync to fsync
   34246   */
   34247   rc = fsync(fd);
   34248 #else
   34249   rc = fdatasync(fd);
   34250 #if OS_VXWORKS
   34251   if( rc==-1 && errno==ENOTSUP ){
   34252     rc = fsync(fd);
   34253   }
   34254 #endif /* OS_VXWORKS */
   34255 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   34256 
   34257   if( OS_VXWORKS && rc!= -1 ){
   34258     rc = 0;
   34259   }
   34260   return rc;
   34261 }
   34262 
   34263 /*
   34264 ** Open a file descriptor to the directory containing file zFilename.
   34265 ** If successful, *pFd is set to the opened file descriptor and
   34266 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   34267 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   34268 ** value.
   34269 **
   34270 ** The directory file descriptor is used for only one thing - to
   34271 ** fsync() a directory to make sure file creation and deletion events
   34272 ** are flushed to disk.  Such fsyncs are not needed on newer
   34273 ** journaling filesystems, but are required on older filesystems.
   34274 **
   34275 ** This routine can be overridden using the xSetSysCall interface.
   34276 ** The ability to override this routine was added in support of the
   34277 ** chromium sandbox.  Opening a directory is a security risk (we are
   34278 ** told) so making it overrideable allows the chromium sandbox to
   34279 ** replace this routine with a harmless no-op.  To make this routine
   34280 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
   34281 ** *pFd set to a negative number.
   34282 **
   34283 ** If SQLITE_OK is returned, the caller is responsible for closing
   34284 ** the file descriptor *pFd using close().
   34285 */
   34286 static int openDirectory(const char *zFilename, int *pFd){
   34287   int ii;
   34288   int fd = -1;
   34289   char zDirname[MAX_PATHNAME+1];
   34290 
   34291   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   34292   for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
   34293   if( ii>0 ){
   34294     zDirname[ii] = '\0';
   34295   }else{
   34296     if( zDirname[0]!='/' ) zDirname[0] = '.';
   34297     zDirname[1] = 0;
   34298   }
   34299   fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
   34300   if( fd>=0 ){
   34301     OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
   34302   }
   34303   *pFd = fd;
   34304   if( fd>=0 ) return SQLITE_OK;
   34305   return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
   34306 }
   34307 
   34308 /*
   34309 ** Make sure all writes to a particular file are committed to disk.
   34310 **
   34311 ** If dataOnly==0 then both the file itself and its metadata (file
   34312 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   34313 ** file data is synced.
   34314 **
   34315 ** Under Unix, also make sure that the directory entry for the file
   34316 ** has been created by fsync-ing the directory that contains the file.
   34317 ** If we do not do this and we encounter a power failure, the directory
   34318 ** entry for the journal might not exist after we reboot.  The next
   34319 ** SQLite to access the file will not know that the journal exists (because
   34320 ** the directory entry for the journal was never created) and the transaction
   34321 ** will not roll back - possibly leading to database corruption.
   34322 */
   34323 static int unixSync(sqlite3_file *id, int flags){
   34324   int rc;
   34325   unixFile *pFile = (unixFile*)id;
   34326 
   34327   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   34328   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   34329 
   34330   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   34331   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   34332       || (flags&0x0F)==SQLITE_SYNC_FULL
   34333   );
   34334 
   34335   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   34336   ** line is to test that doing so does not cause any problems.
   34337   */
   34338   SimulateDiskfullError( return SQLITE_FULL );
   34339 
   34340   assert( pFile );
   34341   OSTRACE(("SYNC    %-3d\n", pFile->h));
   34342   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   34343   SimulateIOError( rc=1 );
   34344   if( rc ){
   34345     storeLastErrno(pFile, errno);
   34346     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
   34347   }
   34348 
   34349   /* Also fsync the directory containing the file if the DIRSYNC flag
   34350   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
   34351   ** are unable to fsync a directory, so ignore errors on the fsync.
   34352   */
   34353   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
   34354     int dirfd;
   34355     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
   34356             HAVE_FULLFSYNC, isFullsync));
   34357     rc = osOpenDirectory(pFile->zPath, &dirfd);
   34358     if( rc==SQLITE_OK ){
   34359       full_fsync(dirfd, 0, 0);
   34360       robust_close(pFile, dirfd, __LINE__);
   34361     }else{
   34362       assert( rc==SQLITE_CANTOPEN );
   34363       rc = SQLITE_OK;
   34364     }
   34365     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
   34366   }
   34367   return rc;
   34368 }
   34369 
   34370 /*
   34371 ** Truncate an open file to a specified size
   34372 */
   34373 static int unixTruncate(sqlite3_file *id, i64 nByte){
   34374   unixFile *pFile = (unixFile *)id;
   34375   int rc;
   34376   assert( pFile );
   34377   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   34378 
   34379   /* If the user has configured a chunk-size for this file, truncate the
   34380   ** file so that it consists of an integer number of chunks (i.e. the
   34381   ** actual file size after the operation may be larger than the requested
   34382   ** size).
   34383   */
   34384   if( pFile->szChunk>0 ){
   34385     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   34386   }
   34387 
   34388   rc = robust_ftruncate(pFile->h, nByte);
   34389   if( rc ){
   34390     storeLastErrno(pFile, errno);
   34391     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   34392   }else{
   34393 #ifdef SQLITE_DEBUG
   34394     /* If we are doing a normal write to a database file (as opposed to
   34395     ** doing a hot-journal rollback or a write to some file other than a
   34396     ** normal database file) and we truncate the file to zero length,
   34397     ** that effectively updates the change counter.  This might happen
   34398     ** when restoring a database using the backup API from a zero-length
   34399     ** source.
   34400     */
   34401     if( pFile->inNormalWrite && nByte==0 ){
   34402       pFile->transCntrChng = 1;
   34403     }
   34404 #endif
   34405 
   34406 #if SQLITE_MAX_MMAP_SIZE>0
   34407     /* If the file was just truncated to a size smaller than the currently
   34408     ** mapped region, reduce the effective mapping size as well. SQLite will
   34409     ** use read() and write() to access data beyond this point from now on.
   34410     */
   34411     if( nByte<pFile->mmapSize ){
   34412       pFile->mmapSize = nByte;
   34413     }
   34414 #endif
   34415 
   34416     return SQLITE_OK;
   34417   }
   34418 }
   34419 
   34420 /*
   34421 ** Determine the current size of a file in bytes
   34422 */
   34423 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   34424   int rc;
   34425   struct stat buf;
   34426   assert( id );
   34427   rc = osFstat(((unixFile*)id)->h, &buf);
   34428   SimulateIOError( rc=1 );
   34429   if( rc!=0 ){
   34430     storeLastErrno((unixFile*)id, errno);
   34431     return SQLITE_IOERR_FSTAT;
   34432   }
   34433   *pSize = buf.st_size;
   34434 
   34435   /* When opening a zero-size database, the findInodeInfo() procedure
   34436   ** writes a single byte into that file in order to work around a bug
   34437   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   34438   ** layers, we need to report this file size as zero even though it is
   34439   ** really 1.   Ticket #3260.
   34440   */
   34441   if( *pSize==1 ) *pSize = 0;
   34442 
   34443 
   34444   return SQLITE_OK;
   34445 }
   34446 
   34447 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   34448 /*
   34449 ** Handler for proxy-locking file-control verbs.  Defined below in the
   34450 ** proxying locking division.
   34451 */
   34452 static int proxyFileControl(sqlite3_file*,int,void*);
   34453 #endif
   34454 
   34455 /*
   34456 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
   34457 ** file-control operation.  Enlarge the database to nBytes in size
   34458 ** (rounded up to the next chunk-size).  If the database is already
   34459 ** nBytes or larger, this routine is a no-op.
   34460 */
   34461 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   34462   if( pFile->szChunk>0 ){
   34463     i64 nSize;                    /* Required file size */
   34464     struct stat buf;              /* Used to hold return values of fstat() */
   34465 
   34466     if( osFstat(pFile->h, &buf) ){
   34467       return SQLITE_IOERR_FSTAT;
   34468     }
   34469 
   34470     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
   34471     if( nSize>(i64)buf.st_size ){
   34472 
   34473 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   34474       /* The code below is handling the return value of osFallocate()
   34475       ** correctly. posix_fallocate() is defined to "returns zero on success,
   34476       ** or an error number on  failure". See the manpage for details. */
   34477       int err;
   34478       do{
   34479         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
   34480       }while( err==EINTR );
   34481       if( err ) return SQLITE_IOERR_WRITE;
   34482 #else
   34483       /* If the OS does not have posix_fallocate(), fake it. Write a
   34484       ** single byte to the last byte in each block that falls entirely
   34485       ** within the extended region. Then, if required, a single byte
   34486       ** at offset (nSize-1), to set the size of the file correctly.
   34487       ** This is a similar technique to that used by glibc on systems
   34488       ** that do not have a real fallocate() call.
   34489       */
   34490       int nBlk = buf.st_blksize;  /* File-system block size */
   34491       int nWrite = 0;             /* Number of bytes written by seekAndWrite */
   34492       i64 iWrite;                 /* Next offset to write to */
   34493 
   34494       iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
   34495       assert( iWrite>=buf.st_size );
   34496       assert( ((iWrite+1)%nBlk)==0 );
   34497       for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
   34498         if( iWrite>=nSize ) iWrite = nSize - 1;
   34499         nWrite = seekAndWrite(pFile, iWrite, "", 1);
   34500         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
   34501       }
   34502 #endif
   34503     }
   34504   }
   34505 
   34506 #if SQLITE_MAX_MMAP_SIZE>0
   34507   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
   34508     int rc;
   34509     if( pFile->szChunk<=0 ){
   34510       if( robust_ftruncate(pFile->h, nByte) ){
   34511         storeLastErrno(pFile, errno);
   34512         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   34513       }
   34514     }
   34515 
   34516     rc = unixMapfile(pFile, nByte);
   34517     return rc;
   34518   }
   34519 #endif
   34520 
   34521   return SQLITE_OK;
   34522 }
   34523 
   34524 /*
   34525 ** If *pArg is initially negative then this is a query.  Set *pArg to
   34526 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   34527 **
   34528 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   34529 */
   34530 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
   34531   if( *pArg<0 ){
   34532     *pArg = (pFile->ctrlFlags & mask)!=0;
   34533   }else if( (*pArg)==0 ){
   34534     pFile->ctrlFlags &= ~mask;
   34535   }else{
   34536     pFile->ctrlFlags |= mask;
   34537   }
   34538 }
   34539 
   34540 /* Forward declaration */
   34541 static int unixGetTempname(int nBuf, char *zBuf);
   34542 
   34543 /*
   34544 ** Information and control of an open file handle.
   34545 */
   34546 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   34547   unixFile *pFile = (unixFile*)id;
   34548   switch( op ){
   34549 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   34550     case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
   34551       int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
   34552       return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
   34553     }
   34554     case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
   34555       int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
   34556       return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
   34557     }
   34558     case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
   34559       int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
   34560       return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
   34561     }
   34562 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
   34563 
   34564     case SQLITE_FCNTL_LOCKSTATE: {
   34565       *(int*)pArg = pFile->eFileLock;
   34566       return SQLITE_OK;
   34567     }
   34568     case SQLITE_FCNTL_LAST_ERRNO: {
   34569       *(int*)pArg = pFile->lastErrno;
   34570       return SQLITE_OK;
   34571     }
   34572     case SQLITE_FCNTL_CHUNK_SIZE: {
   34573       pFile->szChunk = *(int *)pArg;
   34574       return SQLITE_OK;
   34575     }
   34576     case SQLITE_FCNTL_SIZE_HINT: {
   34577       int rc;
   34578       SimulateIOErrorBenign(1);
   34579       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
   34580       SimulateIOErrorBenign(0);
   34581       return rc;
   34582     }
   34583     case SQLITE_FCNTL_PERSIST_WAL: {
   34584       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
   34585       return SQLITE_OK;
   34586     }
   34587     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   34588       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
   34589       return SQLITE_OK;
   34590     }
   34591     case SQLITE_FCNTL_VFSNAME: {
   34592       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   34593       return SQLITE_OK;
   34594     }
   34595     case SQLITE_FCNTL_TEMPFILENAME: {
   34596       char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
   34597       if( zTFile ){
   34598         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
   34599         *(char**)pArg = zTFile;
   34600       }
   34601       return SQLITE_OK;
   34602     }
   34603     case SQLITE_FCNTL_HAS_MOVED: {
   34604       *(int*)pArg = fileHasMoved(pFile);
   34605       return SQLITE_OK;
   34606     }
   34607 #if SQLITE_MAX_MMAP_SIZE>0
   34608     case SQLITE_FCNTL_MMAP_SIZE: {
   34609       i64 newLimit = *(i64*)pArg;
   34610       int rc = SQLITE_OK;
   34611       if( newLimit>sqlite3GlobalConfig.mxMmap ){
   34612         newLimit = sqlite3GlobalConfig.mxMmap;
   34613       }
   34614 
   34615       /* The value of newLimit may be eventually cast to (size_t) and passed
   34616       ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
   34617       ** 64-bit type. */
   34618       if( newLimit>0 && sizeof(size_t)<8 ){
   34619         newLimit = (newLimit & 0x7FFFFFFF);
   34620       }
   34621 
   34622       *(i64*)pArg = pFile->mmapSizeMax;
   34623       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
   34624         pFile->mmapSizeMax = newLimit;
   34625         if( pFile->mmapSize>0 ){
   34626           unixUnmapfile(pFile);
   34627           rc = unixMapfile(pFile, -1);
   34628         }
   34629       }
   34630       return rc;
   34631     }
   34632 #endif
   34633 #ifdef SQLITE_DEBUG
   34634     /* The pager calls this method to signal that it has done
   34635     ** a rollback and that the database is therefore unchanged and
   34636     ** it hence it is OK for the transaction change counter to be
   34637     ** unchanged.
   34638     */
   34639     case SQLITE_FCNTL_DB_UNCHANGED: {
   34640       ((unixFile*)id)->dbUpdate = 0;
   34641       return SQLITE_OK;
   34642     }
   34643 #endif
   34644 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   34645     case SQLITE_FCNTL_SET_LOCKPROXYFILE:
   34646     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
   34647       return proxyFileControl(id,op,pArg);
   34648     }
   34649 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   34650   }
   34651   return SQLITE_NOTFOUND;
   34652 }
   34653 
   34654 /*
   34655 ** If pFd->sectorSize is non-zero when this function is called, it is a
   34656 ** no-op. Otherwise, the values of pFd->sectorSize and
   34657 ** pFd->deviceCharacteristics are set according to the file-system
   34658 ** characteristics.
   34659 **
   34660 ** There are two versions of this function. One for QNX and one for all
   34661 ** other systems.
   34662 */
   34663 #ifndef __QNXNTO__
   34664 static void setDeviceCharacteristics(unixFile *pFd){
   34665   assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
   34666   if( pFd->sectorSize==0 ){
   34667 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   34668     int res;
   34669     u32 f = 0;
   34670 
   34671     /* Check for support for F2FS atomic batch writes. */
   34672     res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
   34673     if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
   34674       pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
   34675     }
   34676 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
   34677 
   34678     /* Set the POWERSAFE_OVERWRITE flag if requested. */
   34679     if( pFd->ctrlFlags & UNIXFILE_PSOW ){
   34680       pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
   34681     }
   34682 
   34683     pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
   34684   }
   34685 }
   34686 #else
   34687 #include <sys/dcmd_blk.h>
   34688 #include <sys/statvfs.h>
   34689 static void setDeviceCharacteristics(unixFile *pFile){
   34690   if( pFile->sectorSize == 0 ){
   34691     struct statvfs fsInfo;
   34692 
   34693     /* Set defaults for non-supported filesystems */
   34694     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
   34695     pFile->deviceCharacteristics = 0;
   34696     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
   34697       return;
   34698     }
   34699 
   34700     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
   34701       pFile->sectorSize = fsInfo.f_bsize;
   34702       pFile->deviceCharacteristics =
   34703         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
   34704         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   34705                                       ** the write succeeds */
   34706         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   34707                                       ** so it is ordered */
   34708         0;
   34709     }else if( strstr(fsInfo.f_basetype, "etfs") ){
   34710       pFile->sectorSize = fsInfo.f_bsize;
   34711       pFile->deviceCharacteristics =
   34712         /* etfs cluster size writes are atomic */
   34713         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
   34714         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   34715                                       ** the write succeeds */
   34716         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   34717                                       ** so it is ordered */
   34718         0;
   34719     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
   34720       pFile->sectorSize = fsInfo.f_bsize;
   34721       pFile->deviceCharacteristics =
   34722         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
   34723         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   34724                                       ** the write succeeds */
   34725         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   34726                                       ** so it is ordered */
   34727         0;
   34728     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
   34729       pFile->sectorSize = fsInfo.f_bsize;
   34730       pFile->deviceCharacteristics =
   34731         /* full bitset of atomics from max sector size and smaller */
   34732         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
   34733         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   34734                                       ** so it is ordered */
   34735         0;
   34736     }else if( strstr(fsInfo.f_basetype, "dos") ){
   34737       pFile->sectorSize = fsInfo.f_bsize;
   34738       pFile->deviceCharacteristics =
   34739         /* full bitset of atomics from max sector size and smaller */
   34740         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
   34741         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
   34742                                       ** so it is ordered */
   34743         0;
   34744     }else{
   34745       pFile->deviceCharacteristics =
   34746         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
   34747         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
   34748                                       ** the write succeeds */
   34749         0;
   34750     }
   34751   }
   34752   /* Last chance verification.  If the sector size isn't a multiple of 512
   34753   ** then it isn't valid.*/
   34754   if( pFile->sectorSize % 512 != 0 ){
   34755     pFile->deviceCharacteristics = 0;
   34756     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
   34757   }
   34758 }
   34759 #endif
   34760 
   34761 /*
   34762 ** Return the sector size in bytes of the underlying block device for
   34763 ** the specified file. This is almost always 512 bytes, but may be
   34764 ** larger for some devices.
   34765 **
   34766 ** SQLite code assumes this function cannot fail. It also assumes that
   34767 ** if two files are created in the same file-system directory (i.e.
   34768 ** a database and its journal file) that the sector size will be the
   34769 ** same for both.
   34770 */
   34771 static int unixSectorSize(sqlite3_file *id){
   34772   unixFile *pFd = (unixFile*)id;
   34773   setDeviceCharacteristics(pFd);
   34774   return pFd->sectorSize;
   34775 }
   34776 
   34777 /*
   34778 ** Return the device characteristics for the file.
   34779 **
   34780 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
   34781 ** However, that choice is controversial since technically the underlying
   34782 ** file system does not always provide powersafe overwrites.  (In other
   34783 ** words, after a power-loss event, parts of the file that were never
   34784 ** written might end up being altered.)  However, non-PSOW behavior is very,
   34785 ** very rare.  And asserting PSOW makes a large reduction in the amount
   34786 ** of required I/O for journaling, since a lot of padding is eliminated.
   34787 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
   34788 ** available to turn it off and URI query parameter available to turn it off.
   34789 */
   34790 static int unixDeviceCharacteristics(sqlite3_file *id){
   34791   unixFile *pFd = (unixFile*)id;
   34792   setDeviceCharacteristics(pFd);
   34793   return pFd->deviceCharacteristics;
   34794 }
   34795 
   34796 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   34797 
   34798 /*
   34799 ** Return the system page size.
   34800 **
   34801 ** This function should not be called directly by other code in this file.
   34802 ** Instead, it should be called via macro osGetpagesize().
   34803 */
   34804 static int unixGetpagesize(void){
   34805 #if OS_VXWORKS
   34806   return 1024;
   34807 #elif defined(_BSD_SOURCE)
   34808   return getpagesize();
   34809 #else
   34810   return (int)sysconf(_SC_PAGESIZE);
   34811 #endif
   34812 }
   34813 
   34814 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
   34815 
   34816 #ifndef SQLITE_OMIT_WAL
   34817 
   34818 /*
   34819 ** Object used to represent an shared memory buffer.
   34820 **
   34821 ** When multiple threads all reference the same wal-index, each thread
   34822 ** has its own unixShm object, but they all point to a single instance
   34823 ** of this unixShmNode object.  In other words, each wal-index is opened
   34824 ** only once per process.
   34825 **
   34826 ** Each unixShmNode object is connected to a single unixInodeInfo object.
   34827 ** We could coalesce this object into unixInodeInfo, but that would mean
   34828 ** every open file that does not use shared memory (in other words, most
   34829 ** open files) would have to carry around this extra information.  So
   34830 ** the unixInodeInfo object contains a pointer to this unixShmNode object
   34831 ** and the unixShmNode object is created only when needed.
   34832 **
   34833 ** unixMutexHeld() must be true when creating or destroying
   34834 ** this object or while reading or writing the following fields:
   34835 **
   34836 **      nRef
   34837 **
   34838 ** The following fields are read-only after the object is created:
   34839 **
   34840 **      fid
   34841 **      zFilename
   34842 **
   34843 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
   34844 ** unixMutexHeld() is true when reading or writing any other field
   34845 ** in this structure.
   34846 */
   34847 struct unixShmNode {
   34848   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
   34849   sqlite3_mutex *mutex;      /* Mutex to access this object */
   34850   char *zFilename;           /* Name of the mmapped file */
   34851   int h;                     /* Open file descriptor */
   34852   int szRegion;              /* Size of shared-memory regions */
   34853   u16 nRegion;               /* Size of array apRegion */
   34854   u8 isReadonly;             /* True if read-only */
   34855   u8 isUnlocked;             /* True if no DMS lock held */
   34856   char **apRegion;           /* Array of mapped shared-memory regions */
   34857   int nRef;                  /* Number of unixShm objects pointing to this */
   34858   unixShm *pFirst;           /* All unixShm objects pointing to this */
   34859 #ifdef SQLITE_DEBUG
   34860   u8 exclMask;               /* Mask of exclusive locks held */
   34861   u8 sharedMask;             /* Mask of shared locks held */
   34862   u8 nextShmId;              /* Next available unixShm.id value */
   34863 #endif
   34864 };
   34865 
   34866 /*
   34867 ** Structure used internally by this VFS to record the state of an
   34868 ** open shared memory connection.
   34869 **
   34870 ** The following fields are initialized when this object is created and
   34871 ** are read-only thereafter:
   34872 **
   34873 **    unixShm.pFile
   34874 **    unixShm.id
   34875 **
   34876 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
   34877 ** while accessing any read/write fields.
   34878 */
   34879 struct unixShm {
   34880   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
   34881   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
   34882   u8 hasMutex;               /* True if holding the unixShmNode mutex */
   34883   u8 id;                     /* Id of this connection within its unixShmNode */
   34884   u16 sharedMask;            /* Mask of shared locks held */
   34885   u16 exclMask;              /* Mask of exclusive locks held */
   34886 };
   34887 
   34888 /*
   34889 ** Constants used for locking
   34890 */
   34891 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
   34892 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   34893 
   34894 /*
   34895 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
   34896 **
   34897 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
   34898 ** otherwise.
   34899 */
   34900 static int unixShmSystemLock(
   34901   unixFile *pFile,       /* Open connection to the WAL file */
   34902   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
   34903   int ofst,              /* First byte of the locking range */
   34904   int n                  /* Number of bytes to lock */
   34905 ){
   34906   unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
   34907   struct flock f;        /* The posix advisory locking structure */
   34908   int rc = SQLITE_OK;    /* Result code form fcntl() */
   34909 
   34910   /* Access to the unixShmNode object is serialized by the caller */
   34911   pShmNode = pFile->pInode->pShmNode;
   34912   assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
   34913 
   34914   /* Shared locks never span more than one byte */
   34915   assert( n==1 || lockType!=F_RDLCK );
   34916 
   34917   /* Locks are within range */
   34918   assert( n>=1 && n<=SQLITE_SHM_NLOCK );
   34919 
   34920   if( pShmNode->h>=0 ){
   34921     /* Initialize the locking parameters */
   34922     memset(&f, 0, sizeof(f));
   34923     f.l_type = lockType;
   34924     f.l_whence = SEEK_SET;
   34925     f.l_start = ofst;
   34926     f.l_len = n;
   34927 
   34928     rc = osFcntl(pShmNode->h, F_SETLK, &f);
   34929     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
   34930   }
   34931 
   34932   /* Update the global lock state and do debug tracing */
   34933 #ifdef SQLITE_DEBUG
   34934   { u16 mask;
   34935   OSTRACE(("SHM-LOCK "));
   34936   mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
   34937   if( rc==SQLITE_OK ){
   34938     if( lockType==F_UNLCK ){
   34939       OSTRACE(("unlock %d ok", ofst));
   34940       pShmNode->exclMask &= ~mask;
   34941       pShmNode->sharedMask &= ~mask;
   34942     }else if( lockType==F_RDLCK ){
   34943       OSTRACE(("read-lock %d ok", ofst));
   34944       pShmNode->exclMask &= ~mask;
   34945       pShmNode->sharedMask |= mask;
   34946     }else{
   34947       assert( lockType==F_WRLCK );
   34948       OSTRACE(("write-lock %d ok", ofst));
   34949       pShmNode->exclMask |= mask;
   34950       pShmNode->sharedMask &= ~mask;
   34951     }
   34952   }else{
   34953     if( lockType==F_UNLCK ){
   34954       OSTRACE(("unlock %d failed", ofst));
   34955     }else if( lockType==F_RDLCK ){
   34956       OSTRACE(("read-lock failed"));
   34957     }else{
   34958       assert( lockType==F_WRLCK );
   34959       OSTRACE(("write-lock %d failed", ofst));
   34960     }
   34961   }
   34962   OSTRACE((" - afterwards %03x,%03x\n",
   34963            pShmNode->sharedMask, pShmNode->exclMask));
   34964   }
   34965 #endif
   34966 
   34967   return rc;
   34968 }
   34969 
   34970 /*
   34971 ** Return the minimum number of 32KB shm regions that should be mapped at
   34972 ** a time, assuming that each mapping must be an integer multiple of the
   34973 ** current system page-size.
   34974 **
   34975 ** Usually, this is 1. The exception seems to be systems that are configured
   34976 ** to use 64KB pages - in this case each mapping must cover at least two
   34977 ** shm regions.
   34978 */
   34979 static int unixShmRegionPerMap(void){
   34980   int shmsz = 32*1024;            /* SHM region size */
   34981   int pgsz = osGetpagesize();   /* System page size */
   34982   assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
   34983   if( pgsz<shmsz ) return 1;
   34984   return pgsz/shmsz;
   34985 }
   34986 
   34987 /*
   34988 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
   34989 **
   34990 ** This is not a VFS shared-memory method; it is a utility function called
   34991 ** by VFS shared-memory methods.
   34992 */
   34993 static void unixShmPurge(unixFile *pFd){
   34994   unixShmNode *p = pFd->pInode->pShmNode;
   34995   assert( unixMutexHeld() );
   34996   if( p && ALWAYS(p->nRef==0) ){
   34997     int nShmPerMap = unixShmRegionPerMap();
   34998     int i;
   34999     assert( p->pInode==pFd->pInode );
   35000     sqlite3_mutex_free(p->mutex);
   35001     for(i=0; i<p->nRegion; i+=nShmPerMap){
   35002       if( p->h>=0 ){
   35003         osMunmap(p->apRegion[i], p->szRegion);
   35004       }else{
   35005         sqlite3_free(p->apRegion[i]);
   35006       }
   35007     }
   35008     sqlite3_free(p->apRegion);
   35009     if( p->h>=0 ){
   35010       robust_close(pFd, p->h, __LINE__);
   35011       p->h = -1;
   35012     }
   35013     p->pInode->pShmNode = 0;
   35014     sqlite3_free(p);
   35015   }
   35016 }
   35017 
   35018 /*
   35019 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
   35020 ** take it now. Return SQLITE_OK if successful, or an SQLite error
   35021 ** code otherwise.
   35022 **
   35023 ** If the DMS cannot be locked because this is a readonly_shm=1
   35024 ** connection and no other process already holds a lock, return
   35025 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
   35026 */
   35027 static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
   35028   struct flock lock;
   35029   int rc = SQLITE_OK;
   35030 
   35031   /* Use F_GETLK to determine the locks other processes are holding
   35032   ** on the DMS byte. If it indicates that another process is holding
   35033   ** a SHARED lock, then this process may also take a SHARED lock
   35034   ** and proceed with opening the *-shm file.
   35035   **
   35036   ** Or, if no other process is holding any lock, then this process
   35037   ** is the first to open it. In this case take an EXCLUSIVE lock on the
   35038   ** DMS byte and truncate the *-shm file to zero bytes in size. Then
   35039   ** downgrade to a SHARED lock on the DMS byte.
   35040   **
   35041   ** If another process is holding an EXCLUSIVE lock on the DMS byte,
   35042   ** return SQLITE_BUSY to the caller (it will try again). An earlier
   35043   ** version of this code attempted the SHARED lock at this point. But
   35044   ** this introduced a subtle race condition: if the process holding
   35045   ** EXCLUSIVE failed just before truncating the *-shm file, then this
   35046   ** process might open and use the *-shm file without truncating it.
   35047   ** And if the *-shm file has been corrupted by a power failure or
   35048   ** system crash, the database itself may also become corrupt.  */
   35049   lock.l_whence = SEEK_SET;
   35050   lock.l_start = UNIX_SHM_DMS;
   35051   lock.l_len = 1;
   35052   lock.l_type = F_WRLCK;
   35053   if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
   35054     rc = SQLITE_IOERR_LOCK;
   35055   }else if( lock.l_type==F_UNLCK ){
   35056     if( pShmNode->isReadonly ){
   35057       pShmNode->isUnlocked = 1;
   35058       rc = SQLITE_READONLY_CANTINIT;
   35059     }else{
   35060       rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
   35061       if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
   35062         rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
   35063       }
   35064     }
   35065   }else if( lock.l_type==F_WRLCK ){
   35066     rc = SQLITE_BUSY;
   35067   }
   35068 
   35069   if( rc==SQLITE_OK ){
   35070     assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
   35071     rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
   35072   }
   35073   return rc;
   35074 }
   35075 
   35076 /*
   35077 ** Open a shared-memory area associated with open database file pDbFd.
   35078 ** This particular implementation uses mmapped files.
   35079 **
   35080 ** The file used to implement shared-memory is in the same directory
   35081 ** as the open database file and has the same name as the open database
   35082 ** file with the "-shm" suffix added.  For example, if the database file
   35083 ** is "/home/user1/config.db" then the file that is created and mmapped
   35084 ** for shared memory will be called "/home/user1/config.db-shm".
   35085 **
   35086 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
   35087 ** some other tmpfs mount. But if a file in a different directory
   35088 ** from the database file is used, then differing access permissions
   35089 ** or a chroot() might cause two different processes on the same
   35090 ** database to end up using different files for shared memory -
   35091 ** meaning that their memory would not really be shared - resulting
   35092 ** in database corruption.  Nevertheless, this tmpfs file usage
   35093 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
   35094 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
   35095 ** option results in an incompatible build of SQLite;  builds of SQLite
   35096 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
   35097 ** same database file at the same time, database corruption will likely
   35098 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
   35099 ** "unsupported" and may go away in a future SQLite release.
   35100 **
   35101 ** When opening a new shared-memory file, if no other instances of that
   35102 ** file are currently open, in this process or in other processes, then
   35103 ** the file must be truncated to zero length or have its header cleared.
   35104 **
   35105 ** If the original database file (pDbFd) is using the "unix-excl" VFS
   35106 ** that means that an exclusive lock is held on the database file and
   35107 ** that no other processes are able to read or write the database.  In
   35108 ** that case, we do not really need shared memory.  No shared memory
   35109 ** file is created.  The shared memory will be simulated with heap memory.
   35110 */
   35111 static int unixOpenSharedMemory(unixFile *pDbFd){
   35112   struct unixShm *p = 0;          /* The connection to be opened */
   35113   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
   35114   int rc = SQLITE_OK;             /* Result code */
   35115   unixInodeInfo *pInode;          /* The inode of fd */
   35116   char *zShm;             /* Name of the file used for SHM */
   35117   int nShmFilename;               /* Size of the SHM filename in bytes */
   35118 
   35119   /* Allocate space for the new unixShm object. */
   35120   p = sqlite3_malloc64( sizeof(*p) );
   35121   if( p==0 ) return SQLITE_NOMEM_BKPT;
   35122   memset(p, 0, sizeof(*p));
   35123   assert( pDbFd->pShm==0 );
   35124 
   35125   /* Check to see if a unixShmNode object already exists. Reuse an existing
   35126   ** one if present. Create a new one if necessary.
   35127   */
   35128   unixEnterMutex();
   35129   pInode = pDbFd->pInode;
   35130   pShmNode = pInode->pShmNode;
   35131   if( pShmNode==0 ){
   35132     struct stat sStat;                 /* fstat() info for database file */
   35133 #ifndef SQLITE_SHM_DIRECTORY
   35134     const char *zBasePath = pDbFd->zPath;
   35135 #endif
   35136 
   35137     /* Call fstat() to figure out the permissions on the database file. If
   35138     ** a new *-shm file is created, an attempt will be made to create it
   35139     ** with the same permissions.
   35140     */
   35141     if( osFstat(pDbFd->h, &sStat) ){
   35142       rc = SQLITE_IOERR_FSTAT;
   35143       goto shm_open_err;
   35144     }
   35145 
   35146 #ifdef SQLITE_SHM_DIRECTORY
   35147     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
   35148 #else
   35149     nShmFilename = 6 + (int)strlen(zBasePath);
   35150 #endif
   35151     pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
   35152     if( pShmNode==0 ){
   35153       rc = SQLITE_NOMEM_BKPT;
   35154       goto shm_open_err;
   35155     }
   35156     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
   35157     zShm = pShmNode->zFilename = (char*)&pShmNode[1];
   35158 #ifdef SQLITE_SHM_DIRECTORY
   35159     sqlite3_snprintf(nShmFilename, zShm,
   35160                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
   35161                      (u32)sStat.st_ino, (u32)sStat.st_dev);
   35162 #else
   35163     sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
   35164     sqlite3FileSuffix3(pDbFd->zPath, zShm);
   35165 #endif
   35166     pShmNode->h = -1;
   35167     pDbFd->pInode->pShmNode = pShmNode;
   35168     pShmNode->pInode = pDbFd->pInode;
   35169     if( sqlite3GlobalConfig.bCoreMutex ){
   35170       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   35171       if( pShmNode->mutex==0 ){
   35172         rc = SQLITE_NOMEM_BKPT;
   35173         goto shm_open_err;
   35174       }
   35175     }
   35176 
   35177     if( pInode->bProcessLock==0 ){
   35178       if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
   35179         pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
   35180       }
   35181       if( pShmNode->h<0 ){
   35182         pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
   35183         if( pShmNode->h<0 ){
   35184           rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
   35185           goto shm_open_err;
   35186         }
   35187         pShmNode->isReadonly = 1;
   35188       }
   35189 
   35190       /* If this process is running as root, make sure that the SHM file
   35191       ** is owned by the same user that owns the original database.  Otherwise,
   35192       ** the original owner will not be able to connect.
   35193       */
   35194       robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
   35195 
   35196       rc = unixLockSharedMemory(pDbFd, pShmNode);
   35197       if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
   35198     }
   35199   }
   35200 
   35201   /* Make the new connection a child of the unixShmNode */
   35202   p->pShmNode = pShmNode;
   35203 #ifdef SQLITE_DEBUG
   35204   p->id = pShmNode->nextShmId++;
   35205 #endif
   35206   pShmNode->nRef++;
   35207   pDbFd->pShm = p;
   35208   unixLeaveMutex();
   35209 
   35210   /* The reference count on pShmNode has already been incremented under
   35211   ** the cover of the unixEnterMutex() mutex and the pointer from the
   35212   ** new (struct unixShm) object to the pShmNode has been set. All that is
   35213   ** left to do is to link the new object into the linked list starting
   35214   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   35215   ** mutex.
   35216   */
   35217   sqlite3_mutex_enter(pShmNode->mutex);
   35218   p->pNext = pShmNode->pFirst;
   35219   pShmNode->pFirst = p;
   35220   sqlite3_mutex_leave(pShmNode->mutex);
   35221   return rc;
   35222 
   35223   /* Jump here on any error */
   35224 shm_open_err:
   35225   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
   35226   sqlite3_free(p);
   35227   unixLeaveMutex();
   35228   return rc;
   35229 }
   35230 
   35231 /*
   35232 ** This function is called to obtain a pointer to region iRegion of the
   35233 ** shared-memory associated with the database file fd. Shared-memory regions
   35234 ** are numbered starting from zero. Each shared-memory region is szRegion
   35235 ** bytes in size.
   35236 **
   35237 ** If an error occurs, an error code is returned and *pp is set to NULL.
   35238 **
   35239 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   35240 ** region has not been allocated (by any client, including one running in a
   35241 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   35242 ** bExtend is non-zero and the requested shared-memory region has not yet
   35243 ** been allocated, it is allocated by this function.
   35244 **
   35245 ** If the shared-memory region has already been allocated or is allocated by
   35246 ** this call as described above, then it is mapped into this processes
   35247 ** address space (if it is not already), *pp is set to point to the mapped
   35248 ** memory and SQLITE_OK returned.
   35249 */
   35250 static int unixShmMap(
   35251   sqlite3_file *fd,               /* Handle open on database file */
   35252   int iRegion,                    /* Region to retrieve */
   35253   int szRegion,                   /* Size of regions */
   35254   int bExtend,                    /* True to extend file if necessary */
   35255   void volatile **pp              /* OUT: Mapped memory */
   35256 ){
   35257   unixFile *pDbFd = (unixFile*)fd;
   35258   unixShm *p;
   35259   unixShmNode *pShmNode;
   35260   int rc = SQLITE_OK;
   35261   int nShmPerMap = unixShmRegionPerMap();
   35262   int nReqRegion;
   35263 
   35264   /* If the shared-memory file has not yet been opened, open it now. */
   35265   if( pDbFd->pShm==0 ){
   35266     rc = unixOpenSharedMemory(pDbFd);
   35267     if( rc!=SQLITE_OK ) return rc;
   35268   }
   35269 
   35270   p = pDbFd->pShm;
   35271   pShmNode = p->pShmNode;
   35272   sqlite3_mutex_enter(pShmNode->mutex);
   35273   if( pShmNode->isUnlocked ){
   35274     rc = unixLockSharedMemory(pDbFd, pShmNode);
   35275     if( rc!=SQLITE_OK ) goto shmpage_out;
   35276     pShmNode->isUnlocked = 0;
   35277   }
   35278   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   35279   assert( pShmNode->pInode==pDbFd->pInode );
   35280   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   35281   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   35282 
   35283   /* Minimum number of regions required to be mapped. */
   35284   nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
   35285 
   35286   if( pShmNode->nRegion<nReqRegion ){
   35287     char **apNew;                      /* New apRegion[] array */
   35288     int nByte = nReqRegion*szRegion;   /* Minimum required file size */
   35289     struct stat sStat;                 /* Used by fstat() */
   35290 
   35291     pShmNode->szRegion = szRegion;
   35292 
   35293     if( pShmNode->h>=0 ){
   35294       /* The requested region is not mapped into this processes address space.
   35295       ** Check to see if it has been allocated (i.e. if the wal-index file is
   35296       ** large enough to contain the requested region).
   35297       */
   35298       if( osFstat(pShmNode->h, &sStat) ){
   35299         rc = SQLITE_IOERR_SHMSIZE;
   35300         goto shmpage_out;
   35301       }
   35302 
   35303       if( sStat.st_size<nByte ){
   35304         /* The requested memory region does not exist. If bExtend is set to
   35305         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
   35306         */
   35307         if( !bExtend ){
   35308           goto shmpage_out;
   35309         }
   35310 
   35311         /* Alternatively, if bExtend is true, extend the file. Do this by
   35312         ** writing a single byte to the end of each (OS) page being
   35313         ** allocated or extended. Technically, we need only write to the
   35314         ** last page in order to extend the file. But writing to all new
   35315         ** pages forces the OS to allocate them immediately, which reduces
   35316         ** the chances of SIGBUS while accessing the mapped region later on.
   35317         */
   35318         else{
   35319           static const int pgsz = 4096;
   35320           int iPg;
   35321 
   35322           /* Write to the last byte of each newly allocated or extended page */
   35323           assert( (nByte % pgsz)==0 );
   35324           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
   35325             int x = 0;
   35326             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
   35327               const char *zFile = pShmNode->zFilename;
   35328               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
   35329               goto shmpage_out;
   35330             }
   35331           }
   35332         }
   35333       }
   35334     }
   35335 
   35336     /* Map the requested memory region into this processes address space. */
   35337     apNew = (char **)sqlite3_realloc(
   35338         pShmNode->apRegion, nReqRegion*sizeof(char *)
   35339     );
   35340     if( !apNew ){
   35341       rc = SQLITE_IOERR_NOMEM_BKPT;
   35342       goto shmpage_out;
   35343     }
   35344     pShmNode->apRegion = apNew;
   35345     while( pShmNode->nRegion<nReqRegion ){
   35346       int nMap = szRegion*nShmPerMap;
   35347       int i;
   35348       void *pMem;
   35349       if( pShmNode->h>=0 ){
   35350         pMem = osMmap(0, nMap,
   35351             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
   35352             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
   35353         );
   35354         if( pMem==MAP_FAILED ){
   35355           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
   35356           goto shmpage_out;
   35357         }
   35358       }else{
   35359         pMem = sqlite3_malloc64(szRegion);
   35360         if( pMem==0 ){
   35361           rc = SQLITE_NOMEM_BKPT;
   35362           goto shmpage_out;
   35363         }
   35364         memset(pMem, 0, szRegion);
   35365       }
   35366 
   35367       for(i=0; i<nShmPerMap; i++){
   35368         pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
   35369       }
   35370       pShmNode->nRegion += nShmPerMap;
   35371     }
   35372   }
   35373 
   35374 shmpage_out:
   35375   if( pShmNode->nRegion>iRegion ){
   35376     *pp = pShmNode->apRegion[iRegion];
   35377   }else{
   35378     *pp = 0;
   35379   }
   35380   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
   35381   sqlite3_mutex_leave(pShmNode->mutex);
   35382   return rc;
   35383 }
   35384 
   35385 /*
   35386 ** Change the lock state for a shared-memory segment.
   35387 **
   35388 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   35389 ** different here than in posix.  In xShmLock(), one can go from unlocked
   35390 ** to shared and back or from unlocked to exclusive and back.  But one may
   35391 ** not go from shared to exclusive or from exclusive to shared.
   35392 */
   35393 static int unixShmLock(
   35394   sqlite3_file *fd,          /* Database file holding the shared memory */
   35395   int ofst,                  /* First lock to acquire or release */
   35396   int n,                     /* Number of locks to acquire or release */
   35397   int flags                  /* What to do with the lock */
   35398 ){
   35399   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   35400   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
   35401   unixShm *pX;                          /* For looping over all siblings */
   35402   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   35403   int rc = SQLITE_OK;                   /* Result code */
   35404   u16 mask;                             /* Mask of locks to take or release */
   35405 
   35406   assert( pShmNode==pDbFd->pInode->pShmNode );
   35407   assert( pShmNode->pInode==pDbFd->pInode );
   35408   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   35409   assert( n>=1 );
   35410   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   35411        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   35412        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   35413        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   35414   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   35415   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   35416   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   35417 
   35418   mask = (1<<(ofst+n)) - (1<<ofst);
   35419   assert( n>1 || mask==(1<<ofst) );
   35420   sqlite3_mutex_enter(pShmNode->mutex);
   35421   if( flags & SQLITE_SHM_UNLOCK ){
   35422     u16 allMask = 0; /* Mask of locks held by siblings */
   35423 
   35424     /* See if any siblings hold this same lock */
   35425     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35426       if( pX==p ) continue;
   35427       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   35428       allMask |= pX->sharedMask;
   35429     }
   35430 
   35431     /* Unlock the system-level locks */
   35432     if( (mask & allMask)==0 ){
   35433       rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
   35434     }else{
   35435       rc = SQLITE_OK;
   35436     }
   35437 
   35438     /* Undo the local locks */
   35439     if( rc==SQLITE_OK ){
   35440       p->exclMask &= ~mask;
   35441       p->sharedMask &= ~mask;
   35442     }
   35443   }else if( flags & SQLITE_SHM_SHARED ){
   35444     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   35445 
   35446     /* Find out which shared locks are already held by sibling connections.
   35447     ** If any sibling already holds an exclusive lock, go ahead and return
   35448     ** SQLITE_BUSY.
   35449     */
   35450     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35451       if( (pX->exclMask & mask)!=0 ){
   35452         rc = SQLITE_BUSY;
   35453         break;
   35454       }
   35455       allShared |= pX->sharedMask;
   35456     }
   35457 
   35458     /* Get shared locks at the system level, if necessary */
   35459     if( rc==SQLITE_OK ){
   35460       if( (allShared & mask)==0 ){
   35461         rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
   35462       }else{
   35463         rc = SQLITE_OK;
   35464       }
   35465     }
   35466 
   35467     /* Get the local shared locks */
   35468     if( rc==SQLITE_OK ){
   35469       p->sharedMask |= mask;
   35470     }
   35471   }else{
   35472     /* Make sure no sibling connections hold locks that will block this
   35473     ** lock.  If any do, return SQLITE_BUSY right away.
   35474     */
   35475     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   35476       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   35477         rc = SQLITE_BUSY;
   35478         break;
   35479       }
   35480     }
   35481 
   35482     /* Get the exclusive locks at the system level.  Then if successful
   35483     ** also mark the local connection as being locked.
   35484     */
   35485     if( rc==SQLITE_OK ){
   35486       rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
   35487       if( rc==SQLITE_OK ){
   35488         assert( (p->sharedMask & mask)==0 );
   35489         p->exclMask |= mask;
   35490       }
   35491     }
   35492   }
   35493   sqlite3_mutex_leave(pShmNode->mutex);
   35494   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
   35495            p->id, osGetpid(0), p->sharedMask, p->exclMask));
   35496   return rc;
   35497 }
   35498 
   35499 /*
   35500 ** Implement a memory barrier or memory fence on shared memory.
   35501 **
   35502 ** All loads and stores begun before the barrier must complete before
   35503 ** any load or store begun after the barrier.
   35504 */
   35505 static void unixShmBarrier(
   35506   sqlite3_file *fd                /* Database file holding the shared memory */
   35507 ){
   35508   UNUSED_PARAMETER(fd);
   35509   sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
   35510   unixEnterMutex();               /* Also mutex, for redundancy */
   35511   unixLeaveMutex();
   35512 }
   35513 
   35514 /*
   35515 ** Close a connection to shared-memory.  Delete the underlying
   35516 ** storage if deleteFlag is true.
   35517 **
   35518 ** If there is no shared memory associated with the connection then this
   35519 ** routine is a harmless no-op.
   35520 */
   35521 static int unixShmUnmap(
   35522   sqlite3_file *fd,               /* The underlying database file */
   35523   int deleteFlag                  /* Delete shared-memory if true */
   35524 ){
   35525   unixShm *p;                     /* The connection to be closed */
   35526   unixShmNode *pShmNode;          /* The underlying shared-memory file */
   35527   unixShm **pp;                   /* For looping over sibling connections */
   35528   unixFile *pDbFd;                /* The underlying database file */
   35529 
   35530   pDbFd = (unixFile*)fd;
   35531   p = pDbFd->pShm;
   35532   if( p==0 ) return SQLITE_OK;
   35533   pShmNode = p->pShmNode;
   35534 
   35535   assert( pShmNode==pDbFd->pInode->pShmNode );
   35536   assert( pShmNode->pInode==pDbFd->pInode );
   35537 
   35538   /* Remove connection p from the set of connections associated
   35539   ** with pShmNode */
   35540   sqlite3_mutex_enter(pShmNode->mutex);
   35541   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   35542   *pp = p->pNext;
   35543 
   35544   /* Free the connection p */
   35545   sqlite3_free(p);
   35546   pDbFd->pShm = 0;
   35547   sqlite3_mutex_leave(pShmNode->mutex);
   35548 
   35549   /* If pShmNode->nRef has reached 0, then close the underlying
   35550   ** shared-memory file, too */
   35551   unixEnterMutex();
   35552   assert( pShmNode->nRef>0 );
   35553   pShmNode->nRef--;
   35554   if( pShmNode->nRef==0 ){
   35555     if( deleteFlag && pShmNode->h>=0 ){
   35556       osUnlink(pShmNode->zFilename);
   35557     }
   35558     unixShmPurge(pDbFd);
   35559   }
   35560   unixLeaveMutex();
   35561 
   35562   return SQLITE_OK;
   35563 }
   35564 
   35565 
   35566 #else
   35567 # define unixShmMap     0
   35568 # define unixShmLock    0
   35569 # define unixShmBarrier 0
   35570 # define unixShmUnmap   0
   35571 #endif /* #ifndef SQLITE_OMIT_WAL */
   35572 
   35573 #if SQLITE_MAX_MMAP_SIZE>0
   35574 /*
   35575 ** If it is currently memory mapped, unmap file pFd.
   35576 */
   35577 static void unixUnmapfile(unixFile *pFd){
   35578   assert( pFd->nFetchOut==0 );
   35579   if( pFd->pMapRegion ){
   35580     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
   35581     pFd->pMapRegion = 0;
   35582     pFd->mmapSize = 0;
   35583     pFd->mmapSizeActual = 0;
   35584   }
   35585 }
   35586 
   35587 /*
   35588 ** Attempt to set the size of the memory mapping maintained by file
   35589 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
   35590 **
   35591 ** If successful, this function sets the following variables:
   35592 **
   35593 **       unixFile.pMapRegion
   35594 **       unixFile.mmapSize
   35595 **       unixFile.mmapSizeActual
   35596 **
   35597 ** If unsuccessful, an error message is logged via sqlite3_log() and
   35598 ** the three variables above are zeroed. In this case SQLite should
   35599 ** continue accessing the database using the xRead() and xWrite()
   35600 ** methods.
   35601 */
   35602 static void unixRemapfile(
   35603   unixFile *pFd,                  /* File descriptor object */
   35604   i64 nNew                        /* Required mapping size */
   35605 ){
   35606   const char *zErr = "mmap";
   35607   int h = pFd->h;                      /* File descriptor open on db file */
   35608   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
   35609   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
   35610   u8 *pNew = 0;                        /* Location of new mapping */
   35611   int flags = PROT_READ;               /* Flags to pass to mmap() */
   35612 
   35613   assert( pFd->nFetchOut==0 );
   35614   assert( nNew>pFd->mmapSize );
   35615   assert( nNew<=pFd->mmapSizeMax );
   35616   assert( nNew>0 );
   35617   assert( pFd->mmapSizeActual>=pFd->mmapSize );
   35618   assert( MAP_FAILED!=0 );
   35619 
   35620 #ifdef SQLITE_MMAP_READWRITE
   35621   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
   35622 #endif
   35623 
   35624   if( pOrig ){
   35625 #if HAVE_MREMAP
   35626     i64 nReuse = pFd->mmapSize;
   35627 #else
   35628     const int szSyspage = osGetpagesize();
   35629     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
   35630 #endif
   35631     u8 *pReq = &pOrig[nReuse];
   35632 
   35633     /* Unmap any pages of the existing mapping that cannot be reused. */
   35634     if( nReuse!=nOrig ){
   35635       osMunmap(pReq, nOrig-nReuse);
   35636     }
   35637 
   35638 #if HAVE_MREMAP
   35639     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
   35640     zErr = "mremap";
   35641 #else
   35642     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
   35643     if( pNew!=MAP_FAILED ){
   35644       if( pNew!=pReq ){
   35645         osMunmap(pNew, nNew - nReuse);
   35646         pNew = 0;
   35647       }else{
   35648         pNew = pOrig;
   35649       }
   35650     }
   35651 #endif
   35652 
   35653     /* The attempt to extend the existing mapping failed. Free it. */
   35654     if( pNew==MAP_FAILED || pNew==0 ){
   35655       osMunmap(pOrig, nReuse);
   35656     }
   35657   }
   35658 
   35659   /* If pNew is still NULL, try to create an entirely new mapping. */
   35660   if( pNew==0 ){
   35661     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
   35662   }
   35663 
   35664   if( pNew==MAP_FAILED ){
   35665     pNew = 0;
   35666     nNew = 0;
   35667     unixLogError(SQLITE_OK, zErr, pFd->zPath);
   35668 
   35669     /* If the mmap() above failed, assume that all subsequent mmap() calls
   35670     ** will probably fail too. Fall back to using xRead/xWrite exclusively
   35671     ** in this case.  */
   35672     pFd->mmapSizeMax = 0;
   35673   }
   35674   pFd->pMapRegion = (void *)pNew;
   35675   pFd->mmapSize = pFd->mmapSizeActual = nNew;
   35676 }
   35677 
   35678 /*
   35679 ** Memory map or remap the file opened by file-descriptor pFd (if the file
   35680 ** is already mapped, the existing mapping is replaced by the new). Or, if
   35681 ** there already exists a mapping for this file, and there are still
   35682 ** outstanding xFetch() references to it, this function is a no-op.
   35683 **
   35684 ** If parameter nByte is non-negative, then it is the requested size of
   35685 ** the mapping to create. Otherwise, if nByte is less than zero, then the
   35686 ** requested size is the size of the file on disk. The actual size of the
   35687 ** created mapping is either the requested size or the value configured
   35688 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
   35689 **
   35690 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
   35691 ** recreated as a result of outstanding references) or an SQLite error
   35692 ** code otherwise.
   35693 */
   35694 static int unixMapfile(unixFile *pFd, i64 nMap){
   35695   assert( nMap>=0 || pFd->nFetchOut==0 );
   35696   assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
   35697   if( pFd->nFetchOut>0 ) return SQLITE_OK;
   35698 
   35699   if( nMap<0 ){
   35700     struct stat statbuf;          /* Low-level file information */
   35701     if( osFstat(pFd->h, &statbuf) ){
   35702       return SQLITE_IOERR_FSTAT;
   35703     }
   35704     nMap = statbuf.st_size;
   35705   }
   35706   if( nMap>pFd->mmapSizeMax ){
   35707     nMap = pFd->mmapSizeMax;
   35708   }
   35709 
   35710   assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
   35711   if( nMap!=pFd->mmapSize ){
   35712     unixRemapfile(pFd, nMap);
   35713   }
   35714 
   35715   return SQLITE_OK;
   35716 }
   35717 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   35718 
   35719 /*
   35720 ** If possible, return a pointer to a mapping of file fd starting at offset
   35721 ** iOff. The mapping must be valid for at least nAmt bytes.
   35722 **
   35723 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
   35724 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
   35725 ** Finally, if an error does occur, return an SQLite error code. The final
   35726 ** value of *pp is undefined in this case.
   35727 **
   35728 ** If this function does return a pointer, the caller must eventually
   35729 ** release the reference by calling unixUnfetch().
   35730 */
   35731 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
   35732 #if SQLITE_MAX_MMAP_SIZE>0
   35733   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
   35734 #endif
   35735   *pp = 0;
   35736 
   35737 #if SQLITE_MAX_MMAP_SIZE>0
   35738   if( pFd->mmapSizeMax>0 ){
   35739     if( pFd->pMapRegion==0 ){
   35740       int rc = unixMapfile(pFd, -1);
   35741       if( rc!=SQLITE_OK ) return rc;
   35742     }
   35743     if( pFd->mmapSize >= iOff+nAmt ){
   35744       *pp = &((u8 *)pFd->pMapRegion)[iOff];
   35745       pFd->nFetchOut++;
   35746     }
   35747   }
   35748 #endif
   35749   return SQLITE_OK;
   35750 }
   35751 
   35752 /*
   35753 ** If the third argument is non-NULL, then this function releases a
   35754 ** reference obtained by an earlier call to unixFetch(). The second
   35755 ** argument passed to this function must be the same as the corresponding
   35756 ** argument that was passed to the unixFetch() invocation.
   35757 **
   35758 ** Or, if the third argument is NULL, then this function is being called
   35759 ** to inform the VFS layer that, according to POSIX, any existing mapping
   35760 ** may now be invalid and should be unmapped.
   35761 */
   35762 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
   35763 #if SQLITE_MAX_MMAP_SIZE>0
   35764   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
   35765   UNUSED_PARAMETER(iOff);
   35766 
   35767   /* If p==0 (unmap the entire file) then there must be no outstanding
   35768   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
   35769   ** then there must be at least one outstanding.  */
   35770   assert( (p==0)==(pFd->nFetchOut==0) );
   35771 
   35772   /* If p!=0, it must match the iOff value. */
   35773   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
   35774 
   35775   if( p ){
   35776     pFd->nFetchOut--;
   35777   }else{
   35778     unixUnmapfile(pFd);
   35779   }
   35780 
   35781   assert( pFd->nFetchOut>=0 );
   35782 #else
   35783   UNUSED_PARAMETER(fd);
   35784   UNUSED_PARAMETER(p);
   35785   UNUSED_PARAMETER(iOff);
   35786 #endif
   35787   return SQLITE_OK;
   35788 }
   35789 
   35790 /*
   35791 ** Here ends the implementation of all sqlite3_file methods.
   35792 **
   35793 ********************** End sqlite3_file Methods *******************************
   35794 ******************************************************************************/
   35795 
   35796 /*
   35797 ** This division contains definitions of sqlite3_io_methods objects that
   35798 ** implement various file locking strategies.  It also contains definitions
   35799 ** of "finder" functions.  A finder-function is used to locate the appropriate
   35800 ** sqlite3_io_methods object for a particular database file.  The pAppData
   35801 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   35802 ** the correct finder-function for that VFS.
   35803 **
   35804 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   35805 ** object.  The only interesting finder-function is autolockIoFinder, which
   35806 ** looks at the filesystem type and tries to guess the best locking
   35807 ** strategy from that.
   35808 **
   35809 ** For finder-function F, two objects are created:
   35810 **
   35811 **    (1) The real finder-function named "FImpt()".
   35812 **
   35813 **    (2) A constant pointer to this function named just "F".
   35814 **
   35815 **
   35816 ** A pointer to the F pointer is used as the pAppData value for VFS
   35817 ** objects.  We have to do this instead of letting pAppData point
   35818 ** directly at the finder-function since C90 rules prevent a void*
   35819 ** from be cast into a function pointer.
   35820 **
   35821 **
   35822 ** Each instance of this macro generates two objects:
   35823 **
   35824 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   35825 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   35826 **
   35827 **   *  An I/O method finder function called FINDER that returns a pointer
   35828 **      to the METHOD object in the previous bullet.
   35829 */
   35830 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
   35831 static const sqlite3_io_methods METHOD = {                                   \
   35832    VERSION,                    /* iVersion */                                \
   35833    CLOSE,                      /* xClose */                                  \
   35834    unixRead,                   /* xRead */                                   \
   35835    unixWrite,                  /* xWrite */                                  \
   35836    unixTruncate,               /* xTruncate */                               \
   35837    unixSync,                   /* xSync */                                   \
   35838    unixFileSize,               /* xFileSize */                               \
   35839    LOCK,                       /* xLock */                                   \
   35840    UNLOCK,                     /* xUnlock */                                 \
   35841    CKLOCK,                     /* xCheckReservedLock */                      \
   35842    unixFileControl,            /* xFileControl */                            \
   35843    unixSectorSize,             /* xSectorSize */                             \
   35844    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
   35845    SHMMAP,                     /* xShmMap */                                 \
   35846    unixShmLock,                /* xShmLock */                                \
   35847    unixShmBarrier,             /* xShmBarrier */                             \
   35848    unixShmUnmap,               /* xShmUnmap */                               \
   35849    unixFetch,                  /* xFetch */                                  \
   35850    unixUnfetch,                /* xUnfetch */                                \
   35851 };                                                                           \
   35852 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   35853   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   35854   return &METHOD;                                                            \
   35855 }                                                                            \
   35856 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   35857     = FINDER##Impl;
   35858 
   35859 /*
   35860 ** Here are all of the sqlite3_io_methods objects for each of the
   35861 ** locking strategies.  Functions that return pointers to these methods
   35862 ** are also created.
   35863 */
   35864 IOMETHODS(
   35865   posixIoFinder,            /* Finder function name */
   35866   posixIoMethods,           /* sqlite3_io_methods object name */
   35867   3,                        /* shared memory and mmap are enabled */
   35868   unixClose,                /* xClose method */
   35869   unixLock,                 /* xLock method */
   35870   unixUnlock,               /* xUnlock method */
   35871   unixCheckReservedLock,    /* xCheckReservedLock method */
   35872   unixShmMap                /* xShmMap method */
   35873 )
   35874 IOMETHODS(
   35875   nolockIoFinder,           /* Finder function name */
   35876   nolockIoMethods,          /* sqlite3_io_methods object name */
   35877   3,                        /* shared memory is disabled */
   35878   nolockClose,              /* xClose method */
   35879   nolockLock,               /* xLock method */
   35880   nolockUnlock,             /* xUnlock method */
   35881   nolockCheckReservedLock,  /* xCheckReservedLock method */
   35882   0                         /* xShmMap method */
   35883 )
   35884 IOMETHODS(
   35885   dotlockIoFinder,          /* Finder function name */
   35886   dotlockIoMethods,         /* sqlite3_io_methods object name */
   35887   1,                        /* shared memory is disabled */
   35888   dotlockClose,             /* xClose method */
   35889   dotlockLock,              /* xLock method */
   35890   dotlockUnlock,            /* xUnlock method */
   35891   dotlockCheckReservedLock, /* xCheckReservedLock method */
   35892   0                         /* xShmMap method */
   35893 )
   35894 
   35895 #if SQLITE_ENABLE_LOCKING_STYLE
   35896 IOMETHODS(
   35897   flockIoFinder,            /* Finder function name */
   35898   flockIoMethods,           /* sqlite3_io_methods object name */
   35899   1,                        /* shared memory is disabled */
   35900   flockClose,               /* xClose method */
   35901   flockLock,                /* xLock method */
   35902   flockUnlock,              /* xUnlock method */
   35903   flockCheckReservedLock,   /* xCheckReservedLock method */
   35904   0                         /* xShmMap method */
   35905 )
   35906 #endif
   35907 
   35908 #if OS_VXWORKS
   35909 IOMETHODS(
   35910   semIoFinder,              /* Finder function name */
   35911   semIoMethods,             /* sqlite3_io_methods object name */
   35912   1,                        /* shared memory is disabled */
   35913   semXClose,                /* xClose method */
   35914   semXLock,                 /* xLock method */
   35915   semXUnlock,               /* xUnlock method */
   35916   semXCheckReservedLock,    /* xCheckReservedLock method */
   35917   0                         /* xShmMap method */
   35918 )
   35919 #endif
   35920 
   35921 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   35922 IOMETHODS(
   35923   afpIoFinder,              /* Finder function name */
   35924   afpIoMethods,             /* sqlite3_io_methods object name */
   35925   1,                        /* shared memory is disabled */
   35926   afpClose,                 /* xClose method */
   35927   afpLock,                  /* xLock method */
   35928   afpUnlock,                /* xUnlock method */
   35929   afpCheckReservedLock,     /* xCheckReservedLock method */
   35930   0                         /* xShmMap method */
   35931 )
   35932 #endif
   35933 
   35934 /*
   35935 ** The proxy locking method is a "super-method" in the sense that it
   35936 ** opens secondary file descriptors for the conch and lock files and
   35937 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   35938 ** secondary files.  For this reason, the division that implements
   35939 ** proxy locking is located much further down in the file.  But we need
   35940 ** to go ahead and define the sqlite3_io_methods and finder function
   35941 ** for proxy locking here.  So we forward declare the I/O methods.
   35942 */
   35943 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   35944 static int proxyClose(sqlite3_file*);
   35945 static int proxyLock(sqlite3_file*, int);
   35946 static int proxyUnlock(sqlite3_file*, int);
   35947 static int proxyCheckReservedLock(sqlite3_file*, int*);
   35948 IOMETHODS(
   35949   proxyIoFinder,            /* Finder function name */
   35950   proxyIoMethods,           /* sqlite3_io_methods object name */
   35951   1,                        /* shared memory is disabled */
   35952   proxyClose,               /* xClose method */
   35953   proxyLock,                /* xLock method */
   35954   proxyUnlock,              /* xUnlock method */
   35955   proxyCheckReservedLock,   /* xCheckReservedLock method */
   35956   0                         /* xShmMap method */
   35957 )
   35958 #endif
   35959 
   35960 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
   35961 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   35962 IOMETHODS(
   35963   nfsIoFinder,               /* Finder function name */
   35964   nfsIoMethods,              /* sqlite3_io_methods object name */
   35965   1,                         /* shared memory is disabled */
   35966   unixClose,                 /* xClose method */
   35967   unixLock,                  /* xLock method */
   35968   nfsUnlock,                 /* xUnlock method */
   35969   unixCheckReservedLock,     /* xCheckReservedLock method */
   35970   0                          /* xShmMap method */
   35971 )
   35972 #endif
   35973 
   35974 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   35975 /*
   35976 ** This "finder" function attempts to determine the best locking strategy
   35977 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   35978 ** object that implements that strategy.
   35979 **
   35980 ** This is for MacOSX only.
   35981 */
   35982 static const sqlite3_io_methods *autolockIoFinderImpl(
   35983   const char *filePath,    /* name of the database file */
   35984   unixFile *pNew           /* open file object for the database file */
   35985 ){
   35986   static const struct Mapping {
   35987     const char *zFilesystem;              /* Filesystem type name */
   35988     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   35989   } aMap[] = {
   35990     { "hfs",    &posixIoMethods },
   35991     { "ufs",    &posixIoMethods },
   35992     { "afpfs",  &afpIoMethods },
   35993     { "smbfs",  &afpIoMethods },
   35994     { "webdav", &nolockIoMethods },
   35995     { 0, 0 }
   35996   };
   35997   int i;
   35998   struct statfs fsInfo;
   35999   struct flock lockInfo;
   36000 
   36001   if( !filePath ){
   36002     /* If filePath==NULL that means we are dealing with a transient file
   36003     ** that does not need to be locked. */
   36004     return &nolockIoMethods;
   36005   }
   36006   if( statfs(filePath, &fsInfo) != -1 ){
   36007     if( fsInfo.f_flags & MNT_RDONLY ){
   36008       return &nolockIoMethods;
   36009     }
   36010     for(i=0; aMap[i].zFilesystem; i++){
   36011       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   36012         return aMap[i].pMethods;
   36013       }
   36014     }
   36015   }
   36016 
   36017   /* Default case. Handles, amongst others, "nfs".
   36018   ** Test byte-range lock using fcntl(). If the call succeeds,
   36019   ** assume that the file-system supports POSIX style locks.
   36020   */
   36021   lockInfo.l_len = 1;
   36022   lockInfo.l_start = 0;
   36023   lockInfo.l_whence = SEEK_SET;
   36024   lockInfo.l_type = F_RDLCK;
   36025   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   36026     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
   36027       return &nfsIoMethods;
   36028     } else {
   36029       return &posixIoMethods;
   36030     }
   36031   }else{
   36032     return &dotlockIoMethods;
   36033   }
   36034 }
   36035 static const sqlite3_io_methods
   36036   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   36037 
   36038 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   36039 
   36040 #if OS_VXWORKS
   36041 /*
   36042 ** This "finder" function for VxWorks checks to see if posix advisory
   36043 ** locking works.  If it does, then that is what is used.  If it does not
   36044 ** work, then fallback to named semaphore locking.
   36045 */
   36046 static const sqlite3_io_methods *vxworksIoFinderImpl(
   36047   const char *filePath,    /* name of the database file */
   36048   unixFile *pNew           /* the open file object */
   36049 ){
   36050   struct flock lockInfo;
   36051 
   36052   if( !filePath ){
   36053     /* If filePath==NULL that means we are dealing with a transient file
   36054     ** that does not need to be locked. */
   36055     return &nolockIoMethods;
   36056   }
   36057 
   36058   /* Test if fcntl() is supported and use POSIX style locks.
   36059   ** Otherwise fall back to the named semaphore method.
   36060   */
   36061   lockInfo.l_len = 1;
   36062   lockInfo.l_start = 0;
   36063   lockInfo.l_whence = SEEK_SET;
   36064   lockInfo.l_type = F_RDLCK;
   36065   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   36066     return &posixIoMethods;
   36067   }else{
   36068     return &semIoMethods;
   36069   }
   36070 }
   36071 static const sqlite3_io_methods
   36072   *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
   36073 
   36074 #endif /* OS_VXWORKS */
   36075 
   36076 /*
   36077 ** An abstract type for a pointer to an IO method finder function:
   36078 */
   36079 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   36080 
   36081 
   36082 /****************************************************************************
   36083 **************************** sqlite3_vfs methods ****************************
   36084 **
   36085 ** This division contains the implementation of methods on the
   36086 ** sqlite3_vfs object.
   36087 */
   36088 
   36089 /*
   36090 ** Initialize the contents of the unixFile structure pointed to by pId.
   36091 */
   36092 static int fillInUnixFile(
   36093   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   36094   int h,                  /* Open file descriptor of file being opened */
   36095   sqlite3_file *pId,      /* Write to the unixFile structure here */
   36096   const char *zFilename,  /* Name of the file being opened */
   36097   int ctrlFlags           /* Zero or more UNIXFILE_* values */
   36098 ){
   36099   const sqlite3_io_methods *pLockingStyle;
   36100   unixFile *pNew = (unixFile *)pId;
   36101   int rc = SQLITE_OK;
   36102 
   36103   assert( pNew->pInode==NULL );
   36104 
   36105   /* No locking occurs in temporary files */
   36106   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
   36107 
   36108   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
   36109   pNew->h = h;
   36110   pNew->pVfs = pVfs;
   36111   pNew->zPath = zFilename;
   36112   pNew->ctrlFlags = (u8)ctrlFlags;
   36113 #if SQLITE_MAX_MMAP_SIZE>0
   36114   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
   36115 #endif
   36116   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
   36117                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   36118     pNew->ctrlFlags |= UNIXFILE_PSOW;
   36119   }
   36120   if( strcmp(pVfs->zName,"unix-excl")==0 ){
   36121     pNew->ctrlFlags |= UNIXFILE_EXCL;
   36122   }
   36123 
   36124 #if OS_VXWORKS
   36125   pNew->pId = vxworksFindFileId(zFilename);
   36126   if( pNew->pId==0 ){
   36127     ctrlFlags |= UNIXFILE_NOLOCK;
   36128     rc = SQLITE_NOMEM_BKPT;
   36129   }
   36130 #endif
   36131 
   36132   if( ctrlFlags & UNIXFILE_NOLOCK ){
   36133     pLockingStyle = &nolockIoMethods;
   36134   }else{
   36135     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   36136 #if SQLITE_ENABLE_LOCKING_STYLE
   36137     /* Cache zFilename in the locking context (AFP and dotlock override) for
   36138     ** proxyLock activation is possible (remote proxy is based on db name)
   36139     ** zFilename remains valid until file is closed, to support */
   36140     pNew->lockingContext = (void*)zFilename;
   36141 #endif
   36142   }
   36143 
   36144   if( pLockingStyle == &posixIoMethods
   36145 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   36146     || pLockingStyle == &nfsIoMethods
   36147 #endif
   36148   ){
   36149     unixEnterMutex();
   36150     rc = findInodeInfo(pNew, &pNew->pInode);
   36151     if( rc!=SQLITE_OK ){
   36152       /* If an error occurred in findInodeInfo(), close the file descriptor
   36153       ** immediately, before releasing the mutex. findInodeInfo() may fail
   36154       ** in two scenarios:
   36155       **
   36156       **   (a) A call to fstat() failed.
   36157       **   (b) A malloc failed.
   36158       **
   36159       ** Scenario (b) may only occur if the process is holding no other
   36160       ** file descriptors open on the same file. If there were other file
   36161       ** descriptors on this file, then no malloc would be required by
   36162       ** findInodeInfo(). If this is the case, it is quite safe to close
   36163       ** handle h - as it is guaranteed that no posix locks will be released
   36164       ** by doing so.
   36165       **
   36166       ** If scenario (a) caused the error then things are not so safe. The
   36167       ** implicit assumption here is that if fstat() fails, things are in
   36168       ** such bad shape that dropping a lock or two doesn't matter much.
   36169       */
   36170       robust_close(pNew, h, __LINE__);
   36171       h = -1;
   36172     }
   36173     unixLeaveMutex();
   36174   }
   36175 
   36176 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   36177   else if( pLockingStyle == &afpIoMethods ){
   36178     /* AFP locking uses the file path so it needs to be included in
   36179     ** the afpLockingContext.
   36180     */
   36181     afpLockingContext *pCtx;
   36182     pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
   36183     if( pCtx==0 ){
   36184       rc = SQLITE_NOMEM_BKPT;
   36185     }else{
   36186       /* NB: zFilename exists and remains valid until the file is closed
   36187       ** according to requirement F11141.  So we do not need to make a
   36188       ** copy of the filename. */
   36189       pCtx->dbPath = zFilename;
   36190       pCtx->reserved = 0;
   36191       srandomdev();
   36192       unixEnterMutex();
   36193       rc = findInodeInfo(pNew, &pNew->pInode);
   36194       if( rc!=SQLITE_OK ){
   36195         sqlite3_free(pNew->lockingContext);
   36196         robust_close(pNew, h, __LINE__);
   36197         h = -1;
   36198       }
   36199       unixLeaveMutex();
   36200     }
   36201   }
   36202 #endif
   36203 
   36204   else if( pLockingStyle == &dotlockIoMethods ){
   36205     /* Dotfile locking uses the file path so it needs to be included in
   36206     ** the dotlockLockingContext
   36207     */
   36208     char *zLockFile;
   36209     int nFilename;
   36210     assert( zFilename!=0 );
   36211     nFilename = (int)strlen(zFilename) + 6;
   36212     zLockFile = (char *)sqlite3_malloc64(nFilename);
   36213     if( zLockFile==0 ){
   36214       rc = SQLITE_NOMEM_BKPT;
   36215     }else{
   36216       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   36217     }
   36218     pNew->lockingContext = zLockFile;
   36219   }
   36220 
   36221 #if OS_VXWORKS
   36222   else if( pLockingStyle == &semIoMethods ){
   36223     /* Named semaphore locking uses the file path so it needs to be
   36224     ** included in the semLockingContext
   36225     */
   36226     unixEnterMutex();
   36227     rc = findInodeInfo(pNew, &pNew->pInode);
   36228     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
   36229       char *zSemName = pNew->pInode->aSemName;
   36230       int n;
   36231       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   36232                        pNew->pId->zCanonicalName);
   36233       for( n=1; zSemName[n]; n++ )
   36234         if( zSemName[n]=='/' ) zSemName[n] = '_';
   36235       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   36236       if( pNew->pInode->pSem == SEM_FAILED ){
   36237         rc = SQLITE_NOMEM_BKPT;
   36238         pNew->pInode->aSemName[0] = '\0';
   36239       }
   36240     }
   36241     unixLeaveMutex();
   36242   }
   36243 #endif
   36244 
   36245   storeLastErrno(pNew, 0);
   36246 #if OS_VXWORKS
   36247   if( rc!=SQLITE_OK ){
   36248     if( h>=0 ) robust_close(pNew, h, __LINE__);
   36249     h = -1;
   36250     osUnlink(zFilename);
   36251     pNew->ctrlFlags |= UNIXFILE_DELETE;
   36252   }
   36253 #endif
   36254   if( rc!=SQLITE_OK ){
   36255     if( h>=0 ) robust_close(pNew, h, __LINE__);
   36256   }else{
   36257     pNew->pMethod = pLockingStyle;
   36258     OpenCounter(+1);
   36259     verifyDbFile(pNew);
   36260   }
   36261   return rc;
   36262 }
   36263 
   36264 /*
   36265 ** Return the name of a directory in which to put temporary files.
   36266 ** If no suitable temporary file directory can be found, return NULL.
   36267 */
   36268 static const char *unixTempFileDir(void){
   36269   static const char *azDirs[] = {
   36270      0,
   36271      0,
   36272      "/var/tmp",
   36273      "/usr/tmp",
   36274      "/tmp",
   36275      "."
   36276   };
   36277   unsigned int i = 0;
   36278   struct stat buf;
   36279   const char *zDir = sqlite3_temp_directory;
   36280 
   36281   if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
   36282   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   36283   while(1){
   36284     if( zDir!=0
   36285      && osStat(zDir, &buf)==0
   36286      && S_ISDIR(buf.st_mode)
   36287      && osAccess(zDir, 03)==0
   36288     ){
   36289       return zDir;
   36290     }
   36291     if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
   36292     zDir = azDirs[i++];
   36293   }
   36294   return 0;
   36295 }
   36296 
   36297 /*
   36298 ** Create a temporary file name in zBuf.  zBuf must be allocated
   36299 ** by the calling process and must be big enough to hold at least
   36300 ** pVfs->mxPathname bytes.
   36301 */
   36302 static int unixGetTempname(int nBuf, char *zBuf){
   36303   const char *zDir;
   36304   int iLimit = 0;
   36305 
   36306   /* It's odd to simulate an io-error here, but really this is just
   36307   ** using the io-error infrastructure to test that SQLite handles this
   36308   ** function failing.
   36309   */
   36310   zBuf[0] = 0;
   36311   SimulateIOError( return SQLITE_IOERR );
   36312 
   36313   zDir = unixTempFileDir();
   36314   if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
   36315   do{
   36316     u64 r;
   36317     sqlite3_randomness(sizeof(r), &r);
   36318     assert( nBuf>2 );
   36319     zBuf[nBuf-2] = 0;
   36320     sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
   36321                      zDir, r, 0);
   36322     if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
   36323   }while( osAccess(zBuf,0)==0 );
   36324   return SQLITE_OK;
   36325 }
   36326 
   36327 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   36328 /*
   36329 ** Routine to transform a unixFile into a proxy-locking unixFile.
   36330 ** Implementation in the proxy-lock division, but used by unixOpen()
   36331 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   36332 */
   36333 static int proxyTransformUnixFile(unixFile*, const char*);
   36334 #endif
   36335 
   36336 /*
   36337 ** Search for an unused file descriptor that was opened on the database
   36338 ** file (not a journal or master-journal file) identified by pathname
   36339 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   36340 ** argument to this function.
   36341 **
   36342 ** Such a file descriptor may exist if a database connection was closed
   36343 ** but the associated file descriptor could not be closed because some
   36344 ** other file descriptor open on the same file is holding a file-lock.
   36345 ** Refer to comments in the unixClose() function and the lengthy comment
   36346 ** describing "Posix Advisory Locking" at the start of this file for
   36347 ** further details. Also, ticket #4018.
   36348 **
   36349 ** If a suitable file descriptor is found, then it is returned. If no
   36350 ** such file descriptor is located, -1 is returned.
   36351 */
   36352 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   36353   UnixUnusedFd *pUnused = 0;
   36354 
   36355   /* Do not search for an unused file descriptor on vxworks. Not because
   36356   ** vxworks would not benefit from the change (it might, we're not sure),
   36357   ** but because no way to test it is currently available. It is better
   36358   ** not to risk breaking vxworks support for the sake of such an obscure
   36359   ** feature.  */
   36360 #if !OS_VXWORKS
   36361   struct stat sStat;                   /* Results of stat() call */
   36362 
   36363   unixEnterMutex();
   36364 
   36365   /* A stat() call may fail for various reasons. If this happens, it is
   36366   ** almost certain that an open() call on the same path will also fail.
   36367   ** For this reason, if an error occurs in the stat() call here, it is
   36368   ** ignored and -1 is returned. The caller will try to open a new file
   36369   ** descriptor on the same path, fail, and return an error to SQLite.
   36370   **
   36371   ** Even if a subsequent open() call does succeed, the consequences of
   36372   ** not searching for a reusable file descriptor are not dire.  */
   36373   if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
   36374     unixInodeInfo *pInode;
   36375 
   36376     pInode = inodeList;
   36377     while( pInode && (pInode->fileId.dev!=sStat.st_dev
   36378                      || pInode->fileId.ino!=(u64)sStat.st_ino) ){
   36379        pInode = pInode->pNext;
   36380     }
   36381     if( pInode ){
   36382       UnixUnusedFd **pp;
   36383       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   36384       pUnused = *pp;
   36385       if( pUnused ){
   36386         nUnusedFd--;
   36387         *pp = pUnused->pNext;
   36388       }
   36389     }
   36390   }
   36391   unixLeaveMutex();
   36392 #endif    /* if !OS_VXWORKS */
   36393   return pUnused;
   36394 }
   36395 
   36396 /*
   36397 ** Find the mode, uid and gid of file zFile.
   36398 */
   36399 static int getFileMode(
   36400   const char *zFile,              /* File name */
   36401   mode_t *pMode,                  /* OUT: Permissions of zFile */
   36402   uid_t *pUid,                    /* OUT: uid of zFile. */
   36403   gid_t *pGid                     /* OUT: gid of zFile. */
   36404 ){
   36405   struct stat sStat;              /* Output of stat() on database file */
   36406   int rc = SQLITE_OK;
   36407   if( 0==osStat(zFile, &sStat) ){
   36408     *pMode = sStat.st_mode & 0777;
   36409     *pUid = sStat.st_uid;
   36410     *pGid = sStat.st_gid;
   36411   }else{
   36412     rc = SQLITE_IOERR_FSTAT;
   36413   }
   36414   return rc;
   36415 }
   36416 
   36417 /*
   36418 ** This function is called by unixOpen() to determine the unix permissions
   36419 ** to create new files with. If no error occurs, then SQLITE_OK is returned
   36420 ** and a value suitable for passing as the third argument to open(2) is
   36421 ** written to *pMode. If an IO error occurs, an SQLite error code is
   36422 ** returned and the value of *pMode is not modified.
   36423 **
   36424 ** In most cases, this routine sets *pMode to 0, which will become
   36425 ** an indication to robust_open() to create the file using
   36426 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
   36427 ** But if the file being opened is a WAL or regular journal file, then
   36428 ** this function queries the file-system for the permissions on the
   36429 ** corresponding database file and sets *pMode to this value. Whenever
   36430 ** possible, WAL and journal files are created using the same permissions
   36431 ** as the associated database file.
   36432 **
   36433 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
   36434 ** original filename is unavailable.  But 8_3_NAMES is only used for
   36435 ** FAT filesystems and permissions do not matter there, so just use
   36436 ** the default permissions.
   36437 */
   36438 static int findCreateFileMode(
   36439   const char *zPath,              /* Path of file (possibly) being created */
   36440   int flags,                      /* Flags passed as 4th argument to xOpen() */
   36441   mode_t *pMode,                  /* OUT: Permissions to open file with */
   36442   uid_t *pUid,                    /* OUT: uid to set on the file */
   36443   gid_t *pGid                     /* OUT: gid to set on the file */
   36444 ){
   36445   int rc = SQLITE_OK;             /* Return Code */
   36446   *pMode = 0;
   36447   *pUid = 0;
   36448   *pGid = 0;
   36449   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   36450     char zDb[MAX_PATHNAME+1];     /* Database file path */
   36451     int nDb;                      /* Number of valid bytes in zDb */
   36452 
   36453     /* zPath is a path to a WAL or journal file. The following block derives
   36454     ** the path to the associated database file from zPath. This block handles
   36455     ** the following naming conventions:
   36456     **
   36457     **   "<path to db>-journal"
   36458     **   "<path to db>-wal"
   36459     **   "<path to db>-journalNN"
   36460     **   "<path to db>-walNN"
   36461     **
   36462     ** where NN is a decimal number. The NN naming schemes are
   36463     ** used by the test_multiplex.c module.
   36464     */
   36465     nDb = sqlite3Strlen30(zPath) - 1;
   36466     while( zPath[nDb]!='-' ){
   36467       /* In normal operation, the journal file name will always contain
   36468       ** a '-' character.  However in 8+3 filename mode, or if a corrupt
   36469       ** rollback journal specifies a master journal with a goofy name, then
   36470       ** the '-' might be missing. */
   36471       if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
   36472       nDb--;
   36473     }
   36474     memcpy(zDb, zPath, nDb);
   36475     zDb[nDb] = '\0';
   36476 
   36477     rc = getFileMode(zDb, pMode, pUid, pGid);
   36478   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   36479     *pMode = 0600;
   36480   }else if( flags & SQLITE_OPEN_URI ){
   36481     /* If this is a main database file and the file was opened using a URI
   36482     ** filename, check for the "modeof" parameter. If present, interpret
   36483     ** its value as a filename and try to copy the mode, uid and gid from
   36484     ** that file.  */
   36485     const char *z = sqlite3_uri_parameter(zPath, "modeof");
   36486     if( z ){
   36487       rc = getFileMode(z, pMode, pUid, pGid);
   36488     }
   36489   }
   36490   return rc;
   36491 }
   36492 
   36493 /*
   36494 ** Open the file zPath.
   36495 **
   36496 ** Previously, the SQLite OS layer used three functions in place of this
   36497 ** one:
   36498 **
   36499 **     sqlite3OsOpenReadWrite();
   36500 **     sqlite3OsOpenReadOnly();
   36501 **     sqlite3OsOpenExclusive();
   36502 **
   36503 ** These calls correspond to the following combinations of flags:
   36504 **
   36505 **     ReadWrite() ->     (READWRITE | CREATE)
   36506 **     ReadOnly()  ->     (READONLY)
   36507 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   36508 **
   36509 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   36510 ** true, the file was configured to be automatically deleted when the
   36511 ** file handle closed. To achieve the same effect using this new
   36512 ** interface, add the DELETEONCLOSE flag to those specified above for
   36513 ** OpenExclusive().
   36514 */
   36515 static int unixOpen(
   36516   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   36517   const char *zPath,           /* Pathname of file to be opened */
   36518   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   36519   int flags,                   /* Input flags to control the opening */
   36520   int *pOutFlags               /* Output flags returned to SQLite core */
   36521 ){
   36522   unixFile *p = (unixFile *)pFile;
   36523   int fd = -1;                   /* File descriptor returned by open() */
   36524   int openFlags = 0;             /* Flags to pass to open() */
   36525   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   36526   int noLock;                    /* True to omit locking primitives */
   36527   int rc = SQLITE_OK;            /* Function Return Code */
   36528   int ctrlFlags = 0;             /* UNIXFILE_* flags */
   36529 
   36530   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   36531   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   36532   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   36533   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   36534   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   36535 #if SQLITE_ENABLE_LOCKING_STYLE
   36536   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
   36537 #endif
   36538 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   36539   struct statfs fsInfo;
   36540 #endif
   36541 
   36542   /* If creating a master or main-file journal, this function will open
   36543   ** a file-descriptor on the directory too. The first time unixSync()
   36544   ** is called the directory file descriptor will be fsync()ed and close()d.
   36545   */
   36546   int isNewJrnl = (isCreate && (
   36547         eType==SQLITE_OPEN_MASTER_JOURNAL
   36548      || eType==SQLITE_OPEN_MAIN_JOURNAL
   36549      || eType==SQLITE_OPEN_WAL
   36550   ));
   36551 
   36552   /* If argument zPath is a NULL pointer, this function is required to open
   36553   ** a temporary file. Use this buffer to store the file name in.
   36554   */
   36555   char zTmpname[MAX_PATHNAME+2];
   36556   const char *zName = zPath;
   36557 
   36558   /* Check the following statements are true:
   36559   **
   36560   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   36561   **   (b) if CREATE is set, then READWRITE must also be set, and
   36562   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   36563   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   36564   */
   36565   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   36566   assert(isCreate==0 || isReadWrite);
   36567   assert(isExclusive==0 || isCreate);
   36568   assert(isDelete==0 || isCreate);
   36569 
   36570   /* The main DB, main journal, WAL file and master journal are never
   36571   ** automatically deleted. Nor are they ever temporary files.  */
   36572   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   36573   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   36574   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   36575   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   36576 
   36577   /* Assert that the upper layer has set one of the "file-type" flags. */
   36578   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   36579        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   36580        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   36581        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   36582   );
   36583 
   36584   /* Detect a pid change and reset the PRNG.  There is a race condition
   36585   ** here such that two or more threads all trying to open databases at
   36586   ** the same instant might all reset the PRNG.  But multiple resets
   36587   ** are harmless.
   36588   */
   36589   if( randomnessPid!=osGetpid(0) ){
   36590     randomnessPid = osGetpid(0);
   36591     sqlite3_randomness(0,0);
   36592   }
   36593 
   36594   memset(p, 0, sizeof(unixFile));
   36595 
   36596   if( eType==SQLITE_OPEN_MAIN_DB ){
   36597     UnixUnusedFd *pUnused;
   36598     pUnused = findReusableFd(zName, flags);
   36599     if( pUnused ){
   36600       fd = pUnused->fd;
   36601     }else{
   36602       pUnused = sqlite3_malloc64(sizeof(*pUnused));
   36603       if( !pUnused ){
   36604         return SQLITE_NOMEM_BKPT;
   36605       }
   36606     }
   36607     p->pPreallocatedUnused = pUnused;
   36608 
   36609     /* Database filenames are double-zero terminated if they are not
   36610     ** URIs with parameters.  Hence, they can always be passed into
   36611     ** sqlite3_uri_parameter(). */
   36612     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
   36613 
   36614   }else if( !zName ){
   36615     /* If zName is NULL, the upper layer is requesting a temp file. */
   36616     assert(isDelete && !isNewJrnl);
   36617     rc = unixGetTempname(pVfs->mxPathname, zTmpname);
   36618     if( rc!=SQLITE_OK ){
   36619       return rc;
   36620     }
   36621     zName = zTmpname;
   36622 
   36623     /* Generated temporary filenames are always double-zero terminated
   36624     ** for use by sqlite3_uri_parameter(). */
   36625     assert( zName[strlen(zName)+1]==0 );
   36626   }
   36627 
   36628   /* Determine the value of the flags parameter passed to POSIX function
   36629   ** open(). These must be calculated even if open() is not called, as
   36630   ** they may be stored as part of the file handle and used by the
   36631   ** 'conch file' locking functions later on.  */
   36632   if( isReadonly )  openFlags |= O_RDONLY;
   36633   if( isReadWrite ) openFlags |= O_RDWR;
   36634   if( isCreate )    openFlags |= O_CREAT;
   36635   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   36636   openFlags |= (O_LARGEFILE|O_BINARY);
   36637 
   36638   if( fd<0 ){
   36639     mode_t openMode;              /* Permissions to create file with */
   36640     uid_t uid;                    /* Userid for the file */
   36641     gid_t gid;                    /* Groupid for the file */
   36642     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
   36643     if( rc!=SQLITE_OK ){
   36644       assert( !p->pPreallocatedUnused );
   36645       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
   36646       return rc;
   36647     }
   36648     fd = robust_open(zName, openFlags, openMode);
   36649     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
   36650     assert( !isExclusive || (openFlags & O_CREAT)!=0 );
   36651     if( fd<0 ){
   36652       if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
   36653         /* If unable to create a journal because the directory is not
   36654         ** writable, change the error code to indicate that. */
   36655         rc = SQLITE_READONLY_DIRECTORY;
   36656       }else if( errno!=EISDIR && isReadWrite ){
   36657         /* Failed to open the file for read/write access. Try read-only. */
   36658         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   36659         openFlags &= ~(O_RDWR|O_CREAT);
   36660         flags |= SQLITE_OPEN_READONLY;
   36661         openFlags |= O_RDONLY;
   36662         isReadonly = 1;
   36663         fd = robust_open(zName, openFlags, openMode);
   36664       }
   36665     }
   36666     if( fd<0 ){
   36667       int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
   36668       if( rc==SQLITE_OK ) rc = rc2;
   36669       goto open_finished;
   36670     }
   36671 
   36672     /* If this process is running as root and if creating a new rollback
   36673     ** journal or WAL file, set the ownership of the journal or WAL to be
   36674     ** the same as the original database.
   36675     */
   36676     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   36677       robustFchown(fd, uid, gid);
   36678     }
   36679   }
   36680   assert( fd>=0 );
   36681   if( pOutFlags ){
   36682     *pOutFlags = flags;
   36683   }
   36684 
   36685   if( p->pPreallocatedUnused ){
   36686     p->pPreallocatedUnused->fd = fd;
   36687     p->pPreallocatedUnused->flags = flags;
   36688   }
   36689 
   36690   if( isDelete ){
   36691 #if OS_VXWORKS
   36692     zPath = zName;
   36693 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
   36694     zPath = sqlite3_mprintf("%s", zName);
   36695     if( zPath==0 ){
   36696       robust_close(p, fd, __LINE__);
   36697       return SQLITE_NOMEM_BKPT;
   36698     }
   36699 #else
   36700     osUnlink(zName);
   36701 #endif
   36702   }
   36703 #if SQLITE_ENABLE_LOCKING_STYLE
   36704   else{
   36705     p->openFlags = openFlags;
   36706   }
   36707 #endif
   36708 
   36709 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   36710   if( fstatfs(fd, &fsInfo) == -1 ){
   36711     storeLastErrno(p, errno);
   36712     robust_close(p, fd, __LINE__);
   36713     return SQLITE_IOERR_ACCESS;
   36714   }
   36715   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
   36716     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   36717   }
   36718   if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
   36719     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   36720   }
   36721 #endif
   36722 
   36723   /* Set up appropriate ctrlFlags */
   36724   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
   36725   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
   36726   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   36727   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
   36728   if( isNewJrnl )               ctrlFlags |= UNIXFILE_DIRSYNC;
   36729   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
   36730 
   36731 #if SQLITE_ENABLE_LOCKING_STYLE
   36732 #if SQLITE_PREFER_PROXY_LOCKING
   36733   isAutoProxy = 1;
   36734 #endif
   36735   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
   36736     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   36737     int useProxy = 0;
   36738 
   36739     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   36740     ** never use proxy, NULL means use proxy for non-local files only.  */
   36741     if( envforce!=NULL ){
   36742       useProxy = atoi(envforce)>0;
   36743     }else{
   36744       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   36745     }
   36746     if( useProxy ){
   36747       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   36748       if( rc==SQLITE_OK ){
   36749         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   36750         if( rc!=SQLITE_OK ){
   36751           /* Use unixClose to clean up the resources added in fillInUnixFile
   36752           ** and clear all the structure's references.  Specifically,
   36753           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
   36754           */
   36755           unixClose(pFile);
   36756           return rc;
   36757         }
   36758       }
   36759       goto open_finished;
   36760     }
   36761   }
   36762 #endif
   36763 
   36764   assert( zPath==0 || zPath[0]=='/'
   36765       || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
   36766   );
   36767   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   36768 
   36769 open_finished:
   36770   if( rc!=SQLITE_OK ){
   36771     sqlite3_free(p->pPreallocatedUnused);
   36772   }
   36773   return rc;
   36774 }
   36775 
   36776 
   36777 /*
   36778 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   36779 ** the directory after deleting the file.
   36780 */
   36781 static int unixDelete(
   36782   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   36783   const char *zPath,        /* Name of file to be deleted */
   36784   int dirSync               /* If true, fsync() directory after deleting file */
   36785 ){
   36786   int rc = SQLITE_OK;
   36787   UNUSED_PARAMETER(NotUsed);
   36788   SimulateIOError(return SQLITE_IOERR_DELETE);
   36789   if( osUnlink(zPath)==(-1) ){
   36790     if( errno==ENOENT
   36791 #if OS_VXWORKS
   36792         || osAccess(zPath,0)!=0
   36793 #endif
   36794     ){
   36795       rc = SQLITE_IOERR_DELETE_NOENT;
   36796     }else{
   36797       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
   36798     }
   36799     return rc;
   36800   }
   36801 #ifndef SQLITE_DISABLE_DIRSYNC
   36802   if( (dirSync & 1)!=0 ){
   36803     int fd;
   36804     rc = osOpenDirectory(zPath, &fd);
   36805     if( rc==SQLITE_OK ){
   36806       if( full_fsync(fd,0,0) ){
   36807         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
   36808       }
   36809       robust_close(0, fd, __LINE__);
   36810     }else{
   36811       assert( rc==SQLITE_CANTOPEN );
   36812       rc = SQLITE_OK;
   36813     }
   36814   }
   36815 #endif
   36816   return rc;
   36817 }
   36818 
   36819 /*
   36820 ** Test the existence of or access permissions of file zPath. The
   36821 ** test performed depends on the value of flags:
   36822 **
   36823 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   36824 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   36825 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   36826 **
   36827 ** Otherwise return 0.
   36828 */
   36829 static int unixAccess(
   36830   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   36831   const char *zPath,      /* Path of the file to examine */
   36832   int flags,              /* What do we want to learn about the zPath file? */
   36833   int *pResOut            /* Write result boolean here */
   36834 ){
   36835   UNUSED_PARAMETER(NotUsed);
   36836   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   36837   assert( pResOut!=0 );
   36838 
   36839   /* The spec says there are three possible values for flags.  But only
   36840   ** two of them are actually used */
   36841   assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
   36842 
   36843   if( flags==SQLITE_ACCESS_EXISTS ){
   36844     struct stat buf;
   36845     *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
   36846   }else{
   36847     *pResOut = osAccess(zPath, W_OK|R_OK)==0;
   36848   }
   36849   return SQLITE_OK;
   36850 }
   36851 
   36852 /*
   36853 **
   36854 */
   36855 static int mkFullPathname(
   36856   const char *zPath,              /* Input path */
   36857   char *zOut,                     /* Output buffer */
   36858   int nOut                        /* Allocated size of buffer zOut */
   36859 ){
   36860   int nPath = sqlite3Strlen30(zPath);
   36861   int iOff = 0;
   36862   if( zPath[0]!='/' ){
   36863     if( osGetcwd(zOut, nOut-2)==0 ){
   36864       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
   36865     }
   36866     iOff = sqlite3Strlen30(zOut);
   36867     zOut[iOff++] = '/';
   36868   }
   36869   if( (iOff+nPath+1)>nOut ){
   36870     /* SQLite assumes that xFullPathname() nul-terminates the output buffer
   36871     ** even if it returns an error.  */
   36872     zOut[iOff] = '\0';
   36873     return SQLITE_CANTOPEN_BKPT;
   36874   }
   36875   sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
   36876   return SQLITE_OK;
   36877 }
   36878 
   36879 /*
   36880 ** Turn a relative pathname into a full pathname. The relative path
   36881 ** is stored as a nul-terminated string in the buffer pointed to by
   36882 ** zPath.
   36883 **
   36884 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   36885 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   36886 ** this buffer before returning.
   36887 */
   36888 static int unixFullPathname(
   36889   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   36890   const char *zPath,            /* Possibly relative input path */
   36891   int nOut,                     /* Size of output buffer in bytes */
   36892   char *zOut                    /* Output buffer */
   36893 ){
   36894 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
   36895   return mkFullPathname(zPath, zOut, nOut);
   36896 #else
   36897   int rc = SQLITE_OK;
   36898   int nByte;
   36899   int nLink = 1;                /* Number of symbolic links followed so far */
   36900   const char *zIn = zPath;      /* Input path for each iteration of loop */
   36901   char *zDel = 0;
   36902 
   36903   assert( pVfs->mxPathname==MAX_PATHNAME );
   36904   UNUSED_PARAMETER(pVfs);
   36905 
   36906   /* It's odd to simulate an io-error here, but really this is just
   36907   ** using the io-error infrastructure to test that SQLite handles this
   36908   ** function failing. This function could fail if, for example, the
   36909   ** current working directory has been unlinked.
   36910   */
   36911   SimulateIOError( return SQLITE_ERROR );
   36912 
   36913   do {
   36914 
   36915     /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
   36916     ** link, or false otherwise.  */
   36917     int bLink = 0;
   36918     struct stat buf;
   36919     if( osLstat(zIn, &buf)!=0 ){
   36920       if( errno!=ENOENT ){
   36921         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
   36922       }
   36923     }else{
   36924       bLink = S_ISLNK(buf.st_mode);
   36925     }
   36926 
   36927     if( bLink ){
   36928       if( zDel==0 ){
   36929         zDel = sqlite3_malloc(nOut);
   36930         if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
   36931       }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
   36932         rc = SQLITE_CANTOPEN_BKPT;
   36933       }
   36934 
   36935       if( rc==SQLITE_OK ){
   36936         nByte = osReadlink(zIn, zDel, nOut-1);
   36937         if( nByte<0 ){
   36938           rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
   36939         }else{
   36940           if( zDel[0]!='/' ){
   36941             int n;
   36942             for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
   36943             if( nByte+n+1>nOut ){
   36944               rc = SQLITE_CANTOPEN_BKPT;
   36945             }else{
   36946               memmove(&zDel[n], zDel, nByte+1);
   36947               memcpy(zDel, zIn, n);
   36948               nByte += n;
   36949             }
   36950           }
   36951           zDel[nByte] = '\0';
   36952         }
   36953       }
   36954 
   36955       zIn = zDel;
   36956     }
   36957 
   36958     assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
   36959     if( rc==SQLITE_OK && zIn!=zOut ){
   36960       rc = mkFullPathname(zIn, zOut, nOut);
   36961     }
   36962     if( bLink==0 ) break;
   36963     zIn = zOut;
   36964   }while( rc==SQLITE_OK );
   36965 
   36966   sqlite3_free(zDel);
   36967   return rc;
   36968 #endif   /* HAVE_READLINK && HAVE_LSTAT */
   36969 }
   36970 
   36971 
   36972 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   36973 /*
   36974 ** Interfaces for opening a shared library, finding entry points
   36975 ** within the shared library, and closing the shared library.
   36976 */
   36977 #include <dlfcn.h>
   36978 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   36979   UNUSED_PARAMETER(NotUsed);
   36980   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   36981 }
   36982 
   36983 /*
   36984 ** SQLite calls this function immediately after a call to unixDlSym() or
   36985 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   36986 ** message is available, it is written to zBufOut. If no error message
   36987 ** is available, zBufOut is left unmodified and SQLite uses a default
   36988 ** error message.
   36989 */
   36990 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   36991   const char *zErr;
   36992   UNUSED_PARAMETER(NotUsed);
   36993   unixEnterMutex();
   36994   zErr = dlerror();
   36995   if( zErr ){
   36996     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   36997   }
   36998   unixLeaveMutex();
   36999 }
   37000 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   37001   /*
   37002   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   37003   ** cast into a pointer to a function.  And yet the library dlsym() routine
   37004   ** returns a void* which is really a pointer to a function.  So how do we
   37005   ** use dlsym() with -pedantic-errors?
   37006   **
   37007   ** Variable x below is defined to be a pointer to a function taking
   37008   ** parameters void* and const char* and returning a pointer to a function.
   37009   ** We initialize x by assigning it a pointer to the dlsym() function.
   37010   ** (That assignment requires a cast.)  Then we call the function that
   37011   ** x points to.
   37012   **
   37013   ** This work-around is unlikely to work correctly on any system where
   37014   ** you really cannot cast a function pointer into void*.  But then, on the
   37015   ** other hand, dlsym() will not work on such a system either, so we have
   37016   ** not really lost anything.
   37017   */
   37018   void (*(*x)(void*,const char*))(void);
   37019   UNUSED_PARAMETER(NotUsed);
   37020   x = (void(*(*)(void*,const char*))(void))dlsym;
   37021   return (*x)(p, zSym);
   37022 }
   37023 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   37024   UNUSED_PARAMETER(NotUsed);
   37025   dlclose(pHandle);
   37026 }
   37027 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   37028   #define unixDlOpen  0
   37029   #define unixDlError 0
   37030   #define unixDlSym   0
   37031   #define unixDlClose 0
   37032 #endif
   37033 
   37034 /*
   37035 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   37036 */
   37037 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   37038   UNUSED_PARAMETER(NotUsed);
   37039   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   37040 
   37041   /* We have to initialize zBuf to prevent valgrind from reporting
   37042   ** errors.  The reports issued by valgrind are incorrect - we would
   37043   ** prefer that the randomness be increased by making use of the
   37044   ** uninitialized space in zBuf - but valgrind errors tend to worry
   37045   ** some users.  Rather than argue, it seems easier just to initialize
   37046   ** the whole array and silence valgrind, even if that means less randomness
   37047   ** in the random seed.
   37048   **
   37049   ** When testing, initializing zBuf[] to zero is all we do.  That means
   37050   ** that we always use the same random number sequence.  This makes the
   37051   ** tests repeatable.
   37052   */
   37053   memset(zBuf, 0, nBuf);
   37054   randomnessPid = osGetpid(0);
   37055 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
   37056   {
   37057     int fd, got;
   37058     fd = robust_open("/dev/urandom", O_RDONLY, 0);
   37059     if( fd<0 ){
   37060       time_t t;
   37061       time(&t);
   37062       memcpy(zBuf, &t, sizeof(t));
   37063       memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
   37064       assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
   37065       nBuf = sizeof(t) + sizeof(randomnessPid);
   37066     }else{
   37067       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
   37068       robust_close(0, fd, __LINE__);
   37069     }
   37070   }
   37071 #endif
   37072   return nBuf;
   37073 }
   37074 
   37075 
   37076 /*
   37077 ** Sleep for a little while.  Return the amount of time slept.
   37078 ** The argument is the number of microseconds we want to sleep.
   37079 ** The return value is the number of microseconds of sleep actually
   37080 ** requested from the underlying operating system, a number which
   37081 ** might be greater than or equal to the argument, but not less
   37082 ** than the argument.
   37083 */
   37084 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   37085 #if OS_VXWORKS
   37086   struct timespec sp;
   37087 
   37088   sp.tv_sec = microseconds / 1000000;
   37089   sp.tv_nsec = (microseconds % 1000000) * 1000;
   37090   nanosleep(&sp, NULL);
   37091   UNUSED_PARAMETER(NotUsed);
   37092   return microseconds;
   37093 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   37094   usleep(microseconds);
   37095   UNUSED_PARAMETER(NotUsed);
   37096   return microseconds;
   37097 #else
   37098   int seconds = (microseconds+999999)/1000000;
   37099   sleep(seconds);
   37100   UNUSED_PARAMETER(NotUsed);
   37101   return seconds*1000000;
   37102 #endif
   37103 }
   37104 
   37105 /*
   37106 ** The following variable, if set to a non-zero value, is interpreted as
   37107 ** the number of seconds since 1970 and is used to set the result of
   37108 ** sqlite3OsCurrentTime() during testing.
   37109 */
   37110 #ifdef SQLITE_TEST
   37111 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   37112 #endif
   37113 
   37114 /*
   37115 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   37116 ** the current time and date as a Julian Day number times 86_400_000.  In
   37117 ** other words, write into *piNow the number of milliseconds since the Julian
   37118 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   37119 ** proleptic Gregorian calendar.
   37120 **
   37121 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   37122 ** cannot be found.
   37123 */
   37124 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
   37125   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   37126   int rc = SQLITE_OK;
   37127 #if defined(NO_GETTOD)
   37128   time_t t;
   37129   time(&t);
   37130   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
   37131 #elif OS_VXWORKS
   37132   struct timespec sNow;
   37133   clock_gettime(CLOCK_REALTIME, &sNow);
   37134   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
   37135 #else
   37136   struct timeval sNow;
   37137   (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
   37138   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
   37139 #endif
   37140 
   37141 #ifdef SQLITE_TEST
   37142   if( sqlite3_current_time ){
   37143     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   37144   }
   37145 #endif
   37146   UNUSED_PARAMETER(NotUsed);
   37147   return rc;
   37148 }
   37149 
   37150 #ifndef SQLITE_OMIT_DEPRECATED
   37151 /*
   37152 ** Find the current time (in Universal Coordinated Time).  Write the
   37153 ** current time and date as a Julian Day number into *prNow and
   37154 ** return 0.  Return 1 if the time and date cannot be found.
   37155 */
   37156 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   37157   sqlite3_int64 i = 0;
   37158   int rc;
   37159   UNUSED_PARAMETER(NotUsed);
   37160   rc = unixCurrentTimeInt64(0, &i);
   37161   *prNow = i/86400000.0;
   37162   return rc;
   37163 }
   37164 #else
   37165 # define unixCurrentTime 0
   37166 #endif
   37167 
   37168 /*
   37169 ** The xGetLastError() method is designed to return a better
   37170 ** low-level error message when operating-system problems come up
   37171 ** during SQLite operation.  Only the integer return code is currently
   37172 ** used.
   37173 */
   37174 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   37175   UNUSED_PARAMETER(NotUsed);
   37176   UNUSED_PARAMETER(NotUsed2);
   37177   UNUSED_PARAMETER(NotUsed3);
   37178   return errno;
   37179 }
   37180 
   37181 
   37182 /*
   37183 ************************ End of sqlite3_vfs methods ***************************
   37184 ******************************************************************************/
   37185 
   37186 /******************************************************************************
   37187 ************************** Begin Proxy Locking ********************************
   37188 **
   37189 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   37190 ** other locking methods on secondary lock files.  Proxy locking is a
   37191 ** meta-layer over top of the primitive locking implemented above.  For
   37192 ** this reason, the division that implements of proxy locking is deferred
   37193 ** until late in the file (here) after all of the other I/O methods have
   37194 ** been defined - so that the primitive locking methods are available
   37195 ** as services to help with the implementation of proxy locking.
   37196 **
   37197 ****
   37198 **
   37199 ** The default locking schemes in SQLite use byte-range locks on the
   37200 ** database file to coordinate safe, concurrent access by multiple readers
   37201 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   37202 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   37203 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   37204 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   37205 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   37206 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   37207 ** address in the shared range is taken for a SHARED lock, the entire
   37208 ** shared range is taken for an EXCLUSIVE lock):
   37209 **
   37210 **      PENDING_BYTE        0x40000000
   37211 **      RESERVED_BYTE       0x40000001
   37212 **      SHARED_RANGE        0x40000002 -> 0x40000200
   37213 **
   37214 ** This works well on the local file system, but shows a nearly 100x
   37215 ** slowdown in read performance on AFP because the AFP client disables
   37216 ** the read cache when byte-range locks are present.  Enabling the read
   37217 ** cache exposes a cache coherency problem that is present on all OS X
   37218 ** supported network file systems.  NFS and AFP both observe the
   37219 ** close-to-open semantics for ensuring cache coherency
   37220 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   37221 ** address the requirements for concurrent database access by multiple
   37222 ** readers and writers
   37223 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   37224 **
   37225 ** To address the performance and cache coherency issues, proxy file locking
   37226 ** changes the way database access is controlled by limiting access to a
   37227 ** single host at a time and moving file locks off of the database file
   37228 ** and onto a proxy file on the local file system.
   37229 **
   37230 **
   37231 ** Using proxy locks
   37232 ** -----------------
   37233 **
   37234 ** C APIs
   37235 **
   37236 **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
   37237 **                       <proxy_path> | ":auto:");
   37238 **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
   37239 **                       &<proxy_path>);
   37240 **
   37241 **
   37242 ** SQL pragmas
   37243 **
   37244 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   37245 **  PRAGMA [database.]lock_proxy_file
   37246 **
   37247 ** Specifying ":auto:" means that if there is a conch file with a matching
   37248 ** host ID in it, the proxy path in the conch file will be used, otherwise
   37249 ** a proxy path based on the user's temp dir
   37250 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   37251 ** actual proxy file name is generated from the name and path of the
   37252 ** database file.  For example:
   37253 **
   37254 **       For database path "/Users/me/foo.db"
   37255 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   37256 **
   37257 ** Once a lock proxy is configured for a database connection, it can not
   37258 ** be removed, however it may be switched to a different proxy path via
   37259 ** the above APIs (assuming the conch file is not being held by another
   37260 ** connection or process).
   37261 **
   37262 **
   37263 ** How proxy locking works
   37264 ** -----------------------
   37265 **
   37266 ** Proxy file locking relies primarily on two new supporting files:
   37267 **
   37268 **   *  conch file to limit access to the database file to a single host
   37269 **      at a time
   37270 **
   37271 **   *  proxy file to act as a proxy for the advisory locks normally
   37272 **      taken on the database
   37273 **
   37274 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   37275 ** by taking an sqlite-style shared lock on the conch file, reading the
   37276 ** contents and comparing the host's unique host ID (see below) and lock
   37277 ** proxy path against the values stored in the conch.  The conch file is
   37278 ** stored in the same directory as the database file and the file name
   37279 ** is patterned after the database file name as ".<databasename>-conch".
   37280 ** If the conch file does not exist, or its contents do not match the
   37281 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   37282 ** lock and the conch file contents is updated with the host ID and proxy
   37283 ** path and the lock is downgraded to a shared lock again.  If the conch
   37284 ** is held by another process (with a shared lock), the exclusive lock
   37285 ** will fail and SQLITE_BUSY is returned.
   37286 **
   37287 ** The proxy file - a single-byte file used for all advisory file locks
   37288 ** normally taken on the database file.   This allows for safe sharing
   37289 ** of the database file for multiple readers and writers on the same
   37290 ** host (the conch ensures that they all use the same local lock file).
   37291 **
   37292 ** Requesting the lock proxy does not immediately take the conch, it is
   37293 ** only taken when the first request to lock database file is made.
   37294 ** This matches the semantics of the traditional locking behavior, where
   37295 ** opening a connection to a database file does not take a lock on it.
   37296 ** The shared lock and an open file descriptor are maintained until
   37297 ** the connection to the database is closed.
   37298 **
   37299 ** The proxy file and the lock file are never deleted so they only need
   37300 ** to be created the first time they are used.
   37301 **
   37302 ** Configuration options
   37303 ** ---------------------
   37304 **
   37305 **  SQLITE_PREFER_PROXY_LOCKING
   37306 **
   37307 **       Database files accessed on non-local file systems are
   37308 **       automatically configured for proxy locking, lock files are
   37309 **       named automatically using the same logic as
   37310 **       PRAGMA lock_proxy_file=":auto:"
   37311 **
   37312 **  SQLITE_PROXY_DEBUG
   37313 **
   37314 **       Enables the logging of error messages during host id file
   37315 **       retrieval and creation
   37316 **
   37317 **  LOCKPROXYDIR
   37318 **
   37319 **       Overrides the default directory used for lock proxy files that
   37320 **       are named automatically via the ":auto:" setting
   37321 **
   37322 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   37323 **
   37324 **       Permissions to use when creating a directory for storing the
   37325 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   37326 **
   37327 **
   37328 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   37329 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   37330 ** force proxy locking to be used for every database file opened, and 0
   37331 ** will force automatic proxy locking to be disabled for all database
   37332 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
   37333 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   37334 */
   37335 
   37336 /*
   37337 ** Proxy locking is only available on MacOSX
   37338 */
   37339 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   37340 
   37341 /*
   37342 ** The proxyLockingContext has the path and file structures for the remote
   37343 ** and local proxy files in it
   37344 */
   37345 typedef struct proxyLockingContext proxyLockingContext;
   37346 struct proxyLockingContext {
   37347   unixFile *conchFile;         /* Open conch file */
   37348   char *conchFilePath;         /* Name of the conch file */
   37349   unixFile *lockProxy;         /* Open proxy lock file */
   37350   char *lockProxyPath;         /* Name of the proxy lock file */
   37351   char *dbPath;                /* Name of the open file */
   37352   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
   37353   int nFails;                  /* Number of conch taking failures */
   37354   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   37355   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   37356 };
   37357 
   37358 /*
   37359 ** The proxy lock file path for the database at dbPath is written into lPath,
   37360 ** which must point to valid, writable memory large enough for a maxLen length
   37361 ** file path.
   37362 */
   37363 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   37364   int len;
   37365   int dbLen;
   37366   int i;
   37367 
   37368 #ifdef LOCKPROXYDIR
   37369   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   37370 #else
   37371 # ifdef _CS_DARWIN_USER_TEMP_DIR
   37372   {
   37373     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
   37374       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
   37375                lPath, errno, osGetpid(0)));
   37376       return SQLITE_IOERR_LOCK;
   37377     }
   37378     len = strlcat(lPath, "sqliteplocks", maxLen);
   37379   }
   37380 # else
   37381   len = strlcpy(lPath, "/tmp/", maxLen);
   37382 # endif
   37383 #endif
   37384 
   37385   if( lPath[len-1]!='/' ){
   37386     len = strlcat(lPath, "/", maxLen);
   37387   }
   37388 
   37389   /* transform the db path to a unique cache name */
   37390   dbLen = (int)strlen(dbPath);
   37391   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
   37392     char c = dbPath[i];
   37393     lPath[i+len] = (c=='/')?'_':c;
   37394   }
   37395   lPath[i+len]='\0';
   37396   strlcat(lPath, ":auto:", maxLen);
   37397   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
   37398   return SQLITE_OK;
   37399 }
   37400 
   37401 /*
   37402  ** Creates the lock file and any missing directories in lockPath
   37403  */
   37404 static int proxyCreateLockPath(const char *lockPath){
   37405   int i, len;
   37406   char buf[MAXPATHLEN];
   37407   int start = 0;
   37408 
   37409   assert(lockPath!=NULL);
   37410   /* try to create all the intermediate directories */
   37411   len = (int)strlen(lockPath);
   37412   buf[0] = lockPath[0];
   37413   for( i=1; i<len; i++ ){
   37414     if( lockPath[i] == '/' && (i - start > 0) ){
   37415       /* only mkdir if leaf dir != "." or "/" or ".." */
   37416       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
   37417          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
   37418         buf[i]='\0';
   37419         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   37420           int err=errno;
   37421           if( err!=EEXIST ) {
   37422             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
   37423                      "'%s' proxy lock path=%s pid=%d\n",
   37424                      buf, strerror(err), lockPath, osGetpid(0)));
   37425             return err;
   37426           }
   37427         }
   37428       }
   37429       start=i+1;
   37430     }
   37431     buf[i] = lockPath[i];
   37432   }
   37433   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
   37434   return 0;
   37435 }
   37436 
   37437 /*
   37438 ** Create a new VFS file descriptor (stored in memory obtained from
   37439 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   37440 **
   37441 ** The caller is responsible not only for closing the file descriptor
   37442 ** but also for freeing the memory associated with the file descriptor.
   37443 */
   37444 static int proxyCreateUnixFile(
   37445     const char *path,        /* path for the new unixFile */
   37446     unixFile **ppFile,       /* unixFile created and returned by ref */
   37447     int islockfile           /* if non zero missing dirs will be created */
   37448 ) {
   37449   int fd = -1;
   37450   unixFile *pNew;
   37451   int rc = SQLITE_OK;
   37452   int openFlags = O_RDWR | O_CREAT;
   37453   sqlite3_vfs dummyVfs;
   37454   int terrno = 0;
   37455   UnixUnusedFd *pUnused = NULL;
   37456 
   37457   /* 1. first try to open/create the file
   37458   ** 2. if that fails, and this is a lock file (not-conch), try creating
   37459   ** the parent directories and then try again.
   37460   ** 3. if that fails, try to open the file read-only
   37461   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
   37462   */
   37463   pUnused = findReusableFd(path, openFlags);
   37464   if( pUnused ){
   37465     fd = pUnused->fd;
   37466   }else{
   37467     pUnused = sqlite3_malloc64(sizeof(*pUnused));
   37468     if( !pUnused ){
   37469       return SQLITE_NOMEM_BKPT;
   37470     }
   37471   }
   37472   if( fd<0 ){
   37473     fd = robust_open(path, openFlags, 0);
   37474     terrno = errno;
   37475     if( fd<0 && errno==ENOENT && islockfile ){
   37476       if( proxyCreateLockPath(path) == SQLITE_OK ){
   37477         fd = robust_open(path, openFlags, 0);
   37478       }
   37479     }
   37480   }
   37481   if( fd<0 ){
   37482     openFlags = O_RDONLY;
   37483     fd = robust_open(path, openFlags, 0);
   37484     terrno = errno;
   37485   }
   37486   if( fd<0 ){
   37487     if( islockfile ){
   37488       return SQLITE_BUSY;
   37489     }
   37490     switch (terrno) {
   37491       case EACCES:
   37492         return SQLITE_PERM;
   37493       case EIO:
   37494         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   37495       default:
   37496         return SQLITE_CANTOPEN_BKPT;
   37497     }
   37498   }
   37499 
   37500   pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
   37501   if( pNew==NULL ){
   37502     rc = SQLITE_NOMEM_BKPT;
   37503     goto end_create_proxy;
   37504   }
   37505   memset(pNew, 0, sizeof(unixFile));
   37506   pNew->openFlags = openFlags;
   37507   memset(&dummyVfs, 0, sizeof(dummyVfs));
   37508   dummyVfs.pAppData = (void*)&autolockIoFinder;
   37509   dummyVfs.zName = "dummy";
   37510   pUnused->fd = fd;
   37511   pUnused->flags = openFlags;
   37512   pNew->pPreallocatedUnused = pUnused;
   37513 
   37514   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
   37515   if( rc==SQLITE_OK ){
   37516     *ppFile = pNew;
   37517     return SQLITE_OK;
   37518   }
   37519 end_create_proxy:
   37520   robust_close(pNew, fd, __LINE__);
   37521   sqlite3_free(pNew);
   37522   sqlite3_free(pUnused);
   37523   return rc;
   37524 }
   37525 
   37526 #ifdef SQLITE_TEST
   37527 /* simulate multiple hosts by creating unique hostid file paths */
   37528 SQLITE_API int sqlite3_hostid_num = 0;
   37529 #endif
   37530 
   37531 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
   37532 
   37533 #ifdef HAVE_GETHOSTUUID
   37534 /* Not always defined in the headers as it ought to be */
   37535 extern int gethostuuid(uuid_t id, const struct timespec *wait);
   37536 #endif
   37537 
   37538 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
   37539 ** bytes of writable memory.
   37540 */
   37541 static int proxyGetHostID(unsigned char *pHostID, int *pError){
   37542   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
   37543   memset(pHostID, 0, PROXY_HOSTIDLEN);
   37544 #ifdef HAVE_GETHOSTUUID
   37545   {
   37546     struct timespec timeout = {1, 0}; /* 1 sec timeout */
   37547     if( gethostuuid(pHostID, &timeout) ){
   37548       int err = errno;
   37549       if( pError ){
   37550         *pError = err;
   37551       }
   37552       return SQLITE_IOERR;
   37553     }
   37554   }
   37555 #else
   37556   UNUSED_PARAMETER(pError);
   37557 #endif
   37558 #ifdef SQLITE_TEST
   37559   /* simulate multiple hosts by creating unique hostid file paths */
   37560   if( sqlite3_hostid_num != 0){
   37561     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   37562   }
   37563 #endif
   37564 
   37565   return SQLITE_OK;
   37566 }
   37567 
   37568 /* The conch file contains the header, host id and lock file path
   37569  */
   37570 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
   37571 #define PROXY_HEADERLEN    1   /* conch file header length */
   37572 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
   37573 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
   37574 
   37575 /*
   37576 ** Takes an open conch file, copies the contents to a new path and then moves
   37577 ** it back.  The newly created file's file descriptor is assigned to the
   37578 ** conch file structure and finally the original conch file descriptor is
   37579 ** closed.  Returns zero if successful.
   37580 */
   37581 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
   37582   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   37583   unixFile *conchFile = pCtx->conchFile;
   37584   char tPath[MAXPATHLEN];
   37585   char buf[PROXY_MAXCONCHLEN];
   37586   char *cPath = pCtx->conchFilePath;
   37587   size_t readLen = 0;
   37588   size_t pathLen = 0;
   37589   char errmsg[64] = "";
   37590   int fd = -1;
   37591   int rc = -1;
   37592   UNUSED_PARAMETER(myHostID);
   37593 
   37594   /* create a new path by replace the trailing '-conch' with '-break' */
   37595   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
   37596   if( pathLen>MAXPATHLEN || pathLen<6 ||
   37597      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
   37598     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
   37599     goto end_breaklock;
   37600   }
   37601   /* read the conch content */
   37602   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
   37603   if( readLen<PROXY_PATHINDEX ){
   37604     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
   37605     goto end_breaklock;
   37606   }
   37607   /* write it out to the temporary break file */
   37608   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
   37609   if( fd<0 ){
   37610     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
   37611     goto end_breaklock;
   37612   }
   37613   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
   37614     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
   37615     goto end_breaklock;
   37616   }
   37617   if( rename(tPath, cPath) ){
   37618     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
   37619     goto end_breaklock;
   37620   }
   37621   rc = 0;
   37622   fprintf(stderr, "broke stale lock on %s\n", cPath);
   37623   robust_close(pFile, conchFile->h, __LINE__);
   37624   conchFile->h = fd;
   37625   conchFile->openFlags = O_RDWR | O_CREAT;
   37626 
   37627 end_breaklock:
   37628   if( rc ){
   37629     if( fd>=0 ){
   37630       osUnlink(tPath);
   37631       robust_close(pFile, fd, __LINE__);
   37632     }
   37633     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
   37634   }
   37635   return rc;
   37636 }
   37637 
   37638 /* Take the requested lock on the conch file and break a stale lock if the
   37639 ** host id matches.
   37640 */
   37641 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
   37642   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   37643   unixFile *conchFile = pCtx->conchFile;
   37644   int rc = SQLITE_OK;
   37645   int nTries = 0;
   37646   struct timespec conchModTime;
   37647 
   37648   memset(&conchModTime, 0, sizeof(conchModTime));
   37649   do {
   37650     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   37651     nTries ++;
   37652     if( rc==SQLITE_BUSY ){
   37653       /* If the lock failed (busy):
   37654        * 1st try: get the mod time of the conch, wait 0.5s and try again.
   37655        * 2nd try: fail if the mod time changed or host id is different, wait
   37656        *           10 sec and try again
   37657        * 3rd try: break the lock unless the mod time has changed.
   37658        */
   37659       struct stat buf;
   37660       if( osFstat(conchFile->h, &buf) ){
   37661         storeLastErrno(pFile, errno);
   37662         return SQLITE_IOERR_LOCK;
   37663       }
   37664 
   37665       if( nTries==1 ){
   37666         conchModTime = buf.st_mtimespec;
   37667         usleep(500000); /* wait 0.5 sec and try the lock again*/
   37668         continue;
   37669       }
   37670 
   37671       assert( nTries>1 );
   37672       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
   37673          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
   37674         return SQLITE_BUSY;
   37675       }
   37676 
   37677       if( nTries==2 ){
   37678         char tBuf[PROXY_MAXCONCHLEN];
   37679         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
   37680         if( len<0 ){
   37681           storeLastErrno(pFile, errno);
   37682           return SQLITE_IOERR_LOCK;
   37683         }
   37684         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
   37685           /* don't break the lock if the host id doesn't match */
   37686           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
   37687             return SQLITE_BUSY;
   37688           }
   37689         }else{
   37690           /* don't break the lock on short read or a version mismatch */
   37691           return SQLITE_BUSY;
   37692         }
   37693         usleep(10000000); /* wait 10 sec and try the lock again */
   37694         continue;
   37695       }
   37696 
   37697       assert( nTries==3 );
   37698       if( 0==proxyBreakConchLock(pFile, myHostID) ){
   37699         rc = SQLITE_OK;
   37700         if( lockType==EXCLUSIVE_LOCK ){
   37701           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   37702         }
   37703         if( !rc ){
   37704           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   37705         }
   37706       }
   37707     }
   37708   } while( rc==SQLITE_BUSY && nTries<3 );
   37709 
   37710   return rc;
   37711 }
   37712 
   37713 /* Takes the conch by taking a shared lock and read the contents conch, if
   37714 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   37715 ** lockPath means that the lockPath in the conch file will be used if the
   37716 ** host IDs match, or a new lock path will be generated automatically
   37717 ** and written to the conch file.
   37718 */
   37719 static int proxyTakeConch(unixFile *pFile){
   37720   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   37721 
   37722   if( pCtx->conchHeld!=0 ){
   37723     return SQLITE_OK;
   37724   }else{
   37725     unixFile *conchFile = pCtx->conchFile;
   37726     uuid_t myHostID;
   37727     int pError = 0;
   37728     char readBuf[PROXY_MAXCONCHLEN];
   37729     char lockPath[MAXPATHLEN];
   37730     char *tempLockPath = NULL;
   37731     int rc = SQLITE_OK;
   37732     int createConch = 0;
   37733     int hostIdMatch = 0;
   37734     int readLen = 0;
   37735     int tryOldLockPath = 0;
   37736     int forceNewLockPath = 0;
   37737 
   37738     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   37739              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   37740              osGetpid(0)));
   37741 
   37742     rc = proxyGetHostID(myHostID, &pError);
   37743     if( (rc&0xff)==SQLITE_IOERR ){
   37744       storeLastErrno(pFile, pError);
   37745       goto end_takeconch;
   37746     }
   37747     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
   37748     if( rc!=SQLITE_OK ){
   37749       goto end_takeconch;
   37750     }
   37751     /* read the existing conch file */
   37752     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
   37753     if( readLen<0 ){
   37754       /* I/O error: lastErrno set by seekAndRead */
   37755       storeLastErrno(pFile, conchFile->lastErrno);
   37756       rc = SQLITE_IOERR_READ;
   37757       goto end_takeconch;
   37758     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
   37759              readBuf[0]!=(char)PROXY_CONCHVERSION ){
   37760       /* a short read or version format mismatch means we need to create a new
   37761       ** conch file.
   37762       */
   37763       createConch = 1;
   37764     }
   37765     /* if the host id matches and the lock path already exists in the conch
   37766     ** we'll try to use the path there, if we can't open that path, we'll
   37767     ** retry with a new auto-generated path
   37768     */
   37769     do { /* in case we need to try again for an :auto: named lock file */
   37770 
   37771       if( !createConch && !forceNewLockPath ){
   37772         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
   37773                                   PROXY_HOSTIDLEN);
   37774         /* if the conch has data compare the contents */
   37775         if( !pCtx->lockProxyPath ){
   37776           /* for auto-named local lock file, just check the host ID and we'll
   37777            ** use the local lock file path that's already in there
   37778            */
   37779           if( hostIdMatch ){
   37780             size_t pathLen = (readLen - PROXY_PATHINDEX);
   37781 
   37782             if( pathLen>=MAXPATHLEN ){
   37783               pathLen=MAXPATHLEN-1;
   37784             }
   37785             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
   37786             lockPath[pathLen] = 0;
   37787             tempLockPath = lockPath;
   37788             tryOldLockPath = 1;
   37789             /* create a copy of the lock path if the conch is taken */
   37790             goto end_takeconch;
   37791           }
   37792         }else if( hostIdMatch
   37793                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
   37794                            readLen-PROXY_PATHINDEX)
   37795         ){
   37796           /* conch host and lock path match */
   37797           goto end_takeconch;
   37798         }
   37799       }
   37800 
   37801       /* if the conch isn't writable and doesn't match, we can't take it */
   37802       if( (conchFile->openFlags&O_RDWR) == 0 ){
   37803         rc = SQLITE_BUSY;
   37804         goto end_takeconch;
   37805       }
   37806 
   37807       /* either the conch didn't match or we need to create a new one */
   37808       if( !pCtx->lockProxyPath ){
   37809         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   37810         tempLockPath = lockPath;
   37811         /* create a copy of the lock path _only_ if the conch is taken */
   37812       }
   37813 
   37814       /* update conch with host and path (this will fail if other process
   37815       ** has a shared lock already), if the host id matches, use the big
   37816       ** stick.
   37817       */
   37818       futimes(conchFile->h, NULL);
   37819       if( hostIdMatch && !createConch ){
   37820         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
   37821           /* We are trying for an exclusive lock but another thread in this
   37822            ** same process is still holding a shared lock. */
   37823           rc = SQLITE_BUSY;
   37824         } else {
   37825           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   37826         }
   37827       }else{
   37828         rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   37829       }
   37830       if( rc==SQLITE_OK ){
   37831         char writeBuffer[PROXY_MAXCONCHLEN];
   37832         int writeSize = 0;
   37833 
   37834         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   37835         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   37836         if( pCtx->lockProxyPath!=NULL ){
   37837           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
   37838                   MAXPATHLEN);
   37839         }else{
   37840           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   37841         }
   37842         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   37843         robust_ftruncate(conchFile->h, writeSize);
   37844         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   37845         full_fsync(conchFile->h,0,0);
   37846         /* If we created a new conch file (not just updated the contents of a
   37847          ** valid conch file), try to match the permissions of the database
   37848          */
   37849         if( rc==SQLITE_OK && createConch ){
   37850           struct stat buf;
   37851           int err = osFstat(pFile->h, &buf);
   37852           if( err==0 ){
   37853             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   37854                                         S_IROTH|S_IWOTH);
   37855             /* try to match the database file R/W permissions, ignore failure */
   37856 #ifndef SQLITE_PROXY_DEBUG
   37857             osFchmod(conchFile->h, cmode);
   37858 #else
   37859             do{
   37860               rc = osFchmod(conchFile->h, cmode);
   37861             }while( rc==(-1) && errno==EINTR );
   37862             if( rc!=0 ){
   37863               int code = errno;
   37864               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   37865                       cmode, code, strerror(code));
   37866             } else {
   37867               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   37868             }
   37869           }else{
   37870             int code = errno;
   37871             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   37872                     err, code, strerror(code));
   37873 #endif
   37874           }
   37875         }
   37876       }
   37877       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   37878 
   37879     end_takeconch:
   37880       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
   37881       if( rc==SQLITE_OK && pFile->openFlags ){
   37882         int fd;
   37883         if( pFile->h>=0 ){
   37884           robust_close(pFile, pFile->h, __LINE__);
   37885         }
   37886         pFile->h = -1;
   37887         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
   37888         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
   37889         if( fd>=0 ){
   37890           pFile->h = fd;
   37891         }else{
   37892           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   37893            during locking */
   37894         }
   37895       }
   37896       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   37897         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   37898         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   37899         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   37900           /* we couldn't create the proxy lock file with the old lock file path
   37901            ** so try again via auto-naming
   37902            */
   37903           forceNewLockPath = 1;
   37904           tryOldLockPath = 0;
   37905           continue; /* go back to the do {} while start point, try again */
   37906         }
   37907       }
   37908       if( rc==SQLITE_OK ){
   37909         /* Need to make a copy of path if we extracted the value
   37910          ** from the conch file or the path was allocated on the stack
   37911          */
   37912         if( tempLockPath ){
   37913           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   37914           if( !pCtx->lockProxyPath ){
   37915             rc = SQLITE_NOMEM_BKPT;
   37916           }
   37917         }
   37918       }
   37919       if( rc==SQLITE_OK ){
   37920         pCtx->conchHeld = 1;
   37921 
   37922         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   37923           afpLockingContext *afpCtx;
   37924           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   37925           afpCtx->dbPath = pCtx->lockProxyPath;
   37926         }
   37927       } else {
   37928         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   37929       }
   37930       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
   37931                rc==SQLITE_OK?"ok":"failed"));
   37932       return rc;
   37933     } while (1); /* in case we need to retry the :auto: lock file -
   37934                  ** we should never get here except via the 'continue' call. */
   37935   }
   37936 }
   37937 
   37938 /*
   37939 ** If pFile holds a lock on a conch file, then release that lock.
   37940 */
   37941 static int proxyReleaseConch(unixFile *pFile){
   37942   int rc = SQLITE_OK;         /* Subroutine return code */
   37943   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   37944   unixFile *conchFile;        /* Name of the conch file */
   37945 
   37946   pCtx = (proxyLockingContext *)pFile->lockingContext;
   37947   conchFile = pCtx->conchFile;
   37948   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   37949            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   37950            osGetpid(0)));
   37951   if( pCtx->conchHeld>0 ){
   37952     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   37953   }
   37954   pCtx->conchHeld = 0;
   37955   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
   37956            (rc==SQLITE_OK ? "ok" : "failed")));
   37957   return rc;
   37958 }
   37959 
   37960 /*
   37961 ** Given the name of a database file, compute the name of its conch file.
   37962 ** Store the conch filename in memory obtained from sqlite3_malloc64().
   37963 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   37964 ** or SQLITE_NOMEM if unable to obtain memory.
   37965 **
   37966 ** The caller is responsible for ensuring that the allocated memory
   37967 ** space is eventually freed.
   37968 **
   37969 ** *pConchPath is set to NULL if a memory allocation error occurs.
   37970 */
   37971 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   37972   int i;                        /* Loop counter */
   37973   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   37974   char *conchPath;              /* buffer in which to construct conch name */
   37975 
   37976   /* Allocate space for the conch filename and initialize the name to
   37977   ** the name of the original database file. */
   37978   *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
   37979   if( conchPath==0 ){
   37980     return SQLITE_NOMEM_BKPT;
   37981   }
   37982   memcpy(conchPath, dbPath, len+1);
   37983 
   37984   /* now insert a "." before the last / character */
   37985   for( i=(len-1); i>=0; i-- ){
   37986     if( conchPath[i]=='/' ){
   37987       i++;
   37988       break;
   37989     }
   37990   }
   37991   conchPath[i]='.';
   37992   while ( i<len ){
   37993     conchPath[i+1]=dbPath[i];
   37994     i++;
   37995   }
   37996 
   37997   /* append the "-conch" suffix to the file */
   37998   memcpy(&conchPath[i+1], "-conch", 7);
   37999   assert( (int)strlen(conchPath) == len+7 );
   38000 
   38001   return SQLITE_OK;
   38002 }
   38003 
   38004 
   38005 /* Takes a fully configured proxy locking-style unix file and switches
   38006 ** the local lock file path
   38007 */
   38008 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   38009   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   38010   char *oldPath = pCtx->lockProxyPath;
   38011   int rc = SQLITE_OK;
   38012 
   38013   if( pFile->eFileLock!=NO_LOCK ){
   38014     return SQLITE_BUSY;
   38015   }
   38016 
   38017   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   38018   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   38019     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   38020     return SQLITE_OK;
   38021   }else{
   38022     unixFile *lockProxy = pCtx->lockProxy;
   38023     pCtx->lockProxy=NULL;
   38024     pCtx->conchHeld = 0;
   38025     if( lockProxy!=NULL ){
   38026       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   38027       if( rc ) return rc;
   38028       sqlite3_free(lockProxy);
   38029     }
   38030     sqlite3_free(oldPath);
   38031     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   38032   }
   38033 
   38034   return rc;
   38035 }
   38036 
   38037 /*
   38038 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   38039 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   38040 **
   38041 ** This routine find the filename associated with pFile and writes it
   38042 ** int dbPath.
   38043 */
   38044 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   38045 #if defined(__APPLE__)
   38046   if( pFile->pMethod == &afpIoMethods ){
   38047     /* afp style keeps a reference to the db path in the filePath field
   38048     ** of the struct */
   38049     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   38050     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
   38051             MAXPATHLEN);
   38052   } else
   38053 #endif
   38054   if( pFile->pMethod == &dotlockIoMethods ){
   38055     /* dot lock style uses the locking context to store the dot lock
   38056     ** file path */
   38057     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   38058     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   38059   }else{
   38060     /* all other styles use the locking context to store the db file path */
   38061     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   38062     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
   38063   }
   38064   return SQLITE_OK;
   38065 }
   38066 
   38067 /*
   38068 ** Takes an already filled in unix file and alters it so all file locking
   38069 ** will be performed on the local proxy lock file.  The following fields
   38070 ** are preserved in the locking context so that they can be restored and
   38071 ** the unix structure properly cleaned up at close time:
   38072 **  ->lockingContext
   38073 **  ->pMethod
   38074 */
   38075 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   38076   proxyLockingContext *pCtx;
   38077   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   38078   char *lockPath=NULL;
   38079   int rc = SQLITE_OK;
   38080 
   38081   if( pFile->eFileLock!=NO_LOCK ){
   38082     return SQLITE_BUSY;
   38083   }
   38084   proxyGetDbPathForUnixFile(pFile, dbPath);
   38085   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   38086     lockPath=NULL;
   38087   }else{
   38088     lockPath=(char *)path;
   38089   }
   38090 
   38091   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   38092            (lockPath ? lockPath : ":auto:"), osGetpid(0)));
   38093 
   38094   pCtx = sqlite3_malloc64( sizeof(*pCtx) );
   38095   if( pCtx==0 ){
   38096     return SQLITE_NOMEM_BKPT;
   38097   }
   38098   memset(pCtx, 0, sizeof(*pCtx));
   38099 
   38100   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   38101   if( rc==SQLITE_OK ){
   38102     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
   38103     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
   38104       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
   38105       ** (c) the file system is read-only, then enable no-locking access.
   38106       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
   38107       ** that openFlags will have only one of O_RDONLY or O_RDWR.
   38108       */
   38109       struct statfs fsInfo;
   38110       struct stat conchInfo;
   38111       int goLockless = 0;
   38112 
   38113       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
   38114         int err = errno;
   38115         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
   38116           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
   38117         }
   38118       }
   38119       if( goLockless ){
   38120         pCtx->conchHeld = -1; /* read only FS/ lockless */
   38121         rc = SQLITE_OK;
   38122       }
   38123     }
   38124   }
   38125   if( rc==SQLITE_OK && lockPath ){
   38126     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   38127   }
   38128 
   38129   if( rc==SQLITE_OK ){
   38130     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   38131     if( pCtx->dbPath==NULL ){
   38132       rc = SQLITE_NOMEM_BKPT;
   38133     }
   38134   }
   38135   if( rc==SQLITE_OK ){
   38136     /* all memory is allocated, proxys are created and assigned,
   38137     ** switch the locking context and pMethod then return.
   38138     */
   38139     pCtx->oldLockingContext = pFile->lockingContext;
   38140     pFile->lockingContext = pCtx;
   38141     pCtx->pOldMethod = pFile->pMethod;
   38142     pFile->pMethod = &proxyIoMethods;
   38143   }else{
   38144     if( pCtx->conchFile ){
   38145       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   38146       sqlite3_free(pCtx->conchFile);
   38147     }
   38148     sqlite3DbFree(0, pCtx->lockProxyPath);
   38149     sqlite3_free(pCtx->conchFilePath);
   38150     sqlite3_free(pCtx);
   38151   }
   38152   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
   38153            (rc==SQLITE_OK ? "ok" : "failed")));
   38154   return rc;
   38155 }
   38156 
   38157 
   38158 /*
   38159 ** This routine handles sqlite3_file_control() calls that are specific
   38160 ** to proxy locking.
   38161 */
   38162 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   38163   switch( op ){
   38164     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
   38165       unixFile *pFile = (unixFile*)id;
   38166       if( pFile->pMethod == &proxyIoMethods ){
   38167         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   38168         proxyTakeConch(pFile);
   38169         if( pCtx->lockProxyPath ){
   38170           *(const char **)pArg = pCtx->lockProxyPath;
   38171         }else{
   38172           *(const char **)pArg = ":auto: (not held)";
   38173         }
   38174       } else {
   38175         *(const char **)pArg = NULL;
   38176       }
   38177       return SQLITE_OK;
   38178     }
   38179     case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
   38180       unixFile *pFile = (unixFile*)id;
   38181       int rc = SQLITE_OK;
   38182       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   38183       if( pArg==NULL || (const char *)pArg==0 ){
   38184         if( isProxyStyle ){
   38185           /* turn off proxy locking - not supported.  If support is added for
   38186           ** switching proxy locking mode off then it will need to fail if
   38187           ** the journal mode is WAL mode.
   38188           */
   38189           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   38190         }else{
   38191           /* turn off proxy locking - already off - NOOP */
   38192           rc = SQLITE_OK;
   38193         }
   38194       }else{
   38195         const char *proxyPath = (const char *)pArg;
   38196         if( isProxyStyle ){
   38197           proxyLockingContext *pCtx =
   38198             (proxyLockingContext*)pFile->lockingContext;
   38199           if( !strcmp(pArg, ":auto:")
   38200            || (pCtx->lockProxyPath &&
   38201                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   38202           ){
   38203             rc = SQLITE_OK;
   38204           }else{
   38205             rc = switchLockProxyPath(pFile, proxyPath);
   38206           }
   38207         }else{
   38208           /* turn on proxy file locking */
   38209           rc = proxyTransformUnixFile(pFile, proxyPath);
   38210         }
   38211       }
   38212       return rc;
   38213     }
   38214     default: {
   38215       assert( 0 );  /* The call assures that only valid opcodes are sent */
   38216     }
   38217   }
   38218   /*NOTREACHED*/
   38219   return SQLITE_ERROR;
   38220 }
   38221 
   38222 /*
   38223 ** Within this division (the proxying locking implementation) the procedures
   38224 ** above this point are all utilities.  The lock-related methods of the
   38225 ** proxy-locking sqlite3_io_method object follow.
   38226 */
   38227 
   38228 
   38229 /*
   38230 ** This routine checks if there is a RESERVED lock held on the specified
   38231 ** file by this or any other process. If such a lock is held, set *pResOut
   38232 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   38233 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   38234 */
   38235 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   38236   unixFile *pFile = (unixFile*)id;
   38237   int rc = proxyTakeConch(pFile);
   38238   if( rc==SQLITE_OK ){
   38239     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   38240     if( pCtx->conchHeld>0 ){
   38241       unixFile *proxy = pCtx->lockProxy;
   38242       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   38243     }else{ /* conchHeld < 0 is lockless */
   38244       pResOut=0;
   38245     }
   38246   }
   38247   return rc;
   38248 }
   38249 
   38250 /*
   38251 ** Lock the file with the lock specified by parameter eFileLock - one
   38252 ** of the following:
   38253 **
   38254 **     (1) SHARED_LOCK
   38255 **     (2) RESERVED_LOCK
   38256 **     (3) PENDING_LOCK
   38257 **     (4) EXCLUSIVE_LOCK
   38258 **
   38259 ** Sometimes when requesting one lock state, additional lock states
   38260 ** are inserted in between.  The locking might fail on one of the later
   38261 ** transitions leaving the lock state different from what it started but
   38262 ** still short of its goal.  The following chart shows the allowed
   38263 ** transitions and the inserted intermediate states:
   38264 **
   38265 **    UNLOCKED -> SHARED
   38266 **    SHARED -> RESERVED
   38267 **    SHARED -> (PENDING) -> EXCLUSIVE
   38268 **    RESERVED -> (PENDING) -> EXCLUSIVE
   38269 **    PENDING -> EXCLUSIVE
   38270 **
   38271 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   38272 ** routine to lower a locking level.
   38273 */
   38274 static int proxyLock(sqlite3_file *id, int eFileLock) {
   38275   unixFile *pFile = (unixFile*)id;
   38276   int rc = proxyTakeConch(pFile);
   38277   if( rc==SQLITE_OK ){
   38278     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   38279     if( pCtx->conchHeld>0 ){
   38280       unixFile *proxy = pCtx->lockProxy;
   38281       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
   38282       pFile->eFileLock = proxy->eFileLock;
   38283     }else{
   38284       /* conchHeld < 0 is lockless */
   38285     }
   38286   }
   38287   return rc;
   38288 }
   38289 
   38290 
   38291 /*
   38292 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   38293 ** must be either NO_LOCK or SHARED_LOCK.
   38294 **
   38295 ** If the locking level of the file descriptor is already at or below
   38296 ** the requested locking level, this routine is a no-op.
   38297 */
   38298 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
   38299   unixFile *pFile = (unixFile*)id;
   38300   int rc = proxyTakeConch(pFile);
   38301   if( rc==SQLITE_OK ){
   38302     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   38303     if( pCtx->conchHeld>0 ){
   38304       unixFile *proxy = pCtx->lockProxy;
   38305       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
   38306       pFile->eFileLock = proxy->eFileLock;
   38307     }else{
   38308       /* conchHeld < 0 is lockless */
   38309     }
   38310   }
   38311   return rc;
   38312 }
   38313 
   38314 /*
   38315 ** Close a file that uses proxy locks.
   38316 */
   38317 static int proxyClose(sqlite3_file *id) {
   38318   if( ALWAYS(id) ){
   38319     unixFile *pFile = (unixFile*)id;
   38320     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   38321     unixFile *lockProxy = pCtx->lockProxy;
   38322     unixFile *conchFile = pCtx->conchFile;
   38323     int rc = SQLITE_OK;
   38324 
   38325     if( lockProxy ){
   38326       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   38327       if( rc ) return rc;
   38328       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   38329       if( rc ) return rc;
   38330       sqlite3_free(lockProxy);
   38331       pCtx->lockProxy = 0;
   38332     }
   38333     if( conchFile ){
   38334       if( pCtx->conchHeld ){
   38335         rc = proxyReleaseConch(pFile);
   38336         if( rc ) return rc;
   38337       }
   38338       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   38339       if( rc ) return rc;
   38340       sqlite3_free(conchFile);
   38341     }
   38342     sqlite3DbFree(0, pCtx->lockProxyPath);
   38343     sqlite3_free(pCtx->conchFilePath);
   38344     sqlite3DbFree(0, pCtx->dbPath);
   38345     /* restore the original locking context and pMethod then close it */
   38346     pFile->lockingContext = pCtx->oldLockingContext;
   38347     pFile->pMethod = pCtx->pOldMethod;
   38348     sqlite3_free(pCtx);
   38349     return pFile->pMethod->xClose(id);
   38350   }
   38351   return SQLITE_OK;
   38352 }
   38353 
   38354 
   38355 
   38356 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   38357 /*
   38358 ** The proxy locking style is intended for use with AFP filesystems.
   38359 ** And since AFP is only supported on MacOSX, the proxy locking is also
   38360 ** restricted to MacOSX.
   38361 **
   38362 **
   38363 ******************* End of the proxy lock implementation **********************
   38364 ******************************************************************************/
   38365 
   38366 /*
   38367 ** Initialize the operating system interface.
   38368 **
   38369 ** This routine registers all VFS implementations for unix-like operating
   38370 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   38371 ** should be the only routines in this file that are visible from other
   38372 ** files.
   38373 **
   38374 ** This routine is called once during SQLite initialization and by a
   38375 ** single thread.  The memory allocation and mutex subsystems have not
   38376 ** necessarily been initialized when this routine is called, and so they
   38377 ** should not be used.
   38378 */
   38379 SQLITE_API int sqlite3_os_init(void){
   38380   /*
   38381   ** The following macro defines an initializer for an sqlite3_vfs object.
   38382   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   38383   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   38384   ** silly C90 rules prohibit a void* from being cast to a function pointer
   38385   ** and so we have to go through the intermediate pointer to avoid problems
   38386   ** when compiling with -pedantic-errors on GCC.)
   38387   **
   38388   ** The FINDER parameter to this macro is the name of the pointer to the
   38389   ** finder-function.  The finder-function returns a pointer to the
   38390   ** sqlite_io_methods object that implements the desired locking
   38391   ** behaviors.  See the division above that contains the IOMETHODS
   38392   ** macro for addition information on finder-functions.
   38393   **
   38394   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   38395   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   38396   ** more than that; it looks at the filesystem type that hosts the
   38397   ** database file and tries to choose an locking method appropriate for
   38398   ** that filesystem time.
   38399   */
   38400   #define UNIXVFS(VFSNAME, FINDER) {                        \
   38401     3,                    /* iVersion */                    \
   38402     sizeof(unixFile),     /* szOsFile */                    \
   38403     MAX_PATHNAME,         /* mxPathname */                  \
   38404     0,                    /* pNext */                       \
   38405     VFSNAME,              /* zName */                       \
   38406     (void*)&FINDER,       /* pAppData */                    \
   38407     unixOpen,             /* xOpen */                       \
   38408     unixDelete,           /* xDelete */                     \
   38409     unixAccess,           /* xAccess */                     \
   38410     unixFullPathname,     /* xFullPathname */               \
   38411     unixDlOpen,           /* xDlOpen */                     \
   38412     unixDlError,          /* xDlError */                    \
   38413     unixDlSym,            /* xDlSym */                      \
   38414     unixDlClose,          /* xDlClose */                    \
   38415     unixRandomness,       /* xRandomness */                 \
   38416     unixSleep,            /* xSleep */                      \
   38417     unixCurrentTime,      /* xCurrentTime */                \
   38418     unixGetLastError,     /* xGetLastError */               \
   38419     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
   38420     unixSetSystemCall,    /* xSetSystemCall */              \
   38421     unixGetSystemCall,    /* xGetSystemCall */              \
   38422     unixNextSystemCall,   /* xNextSystemCall */             \
   38423   }
   38424 
   38425   /*
   38426   ** All default VFSes for unix are contained in the following array.
   38427   **
   38428   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   38429   ** by the SQLite core when the VFS is registered.  So the following
   38430   ** array cannot be const.
   38431   */
   38432   static sqlite3_vfs aVfs[] = {
   38433 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   38434     UNIXVFS("unix",          autolockIoFinder ),
   38435 #elif OS_VXWORKS
   38436     UNIXVFS("unix",          vxworksIoFinder ),
   38437 #else
   38438     UNIXVFS("unix",          posixIoFinder ),
   38439 #endif
   38440     UNIXVFS("unix-none",     nolockIoFinder ),
   38441     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   38442     UNIXVFS("unix-excl",     posixIoFinder ),
   38443 #if OS_VXWORKS
   38444     UNIXVFS("unix-namedsem", semIoFinder ),
   38445 #endif
   38446 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
   38447     UNIXVFS("unix-posix",    posixIoFinder ),
   38448 #endif
   38449 #if SQLITE_ENABLE_LOCKING_STYLE
   38450     UNIXVFS("unix-flock",    flockIoFinder ),
   38451 #endif
   38452 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   38453     UNIXVFS("unix-afp",      afpIoFinder ),
   38454     UNIXVFS("unix-nfs",      nfsIoFinder ),
   38455     UNIXVFS("unix-proxy",    proxyIoFinder ),
   38456 #endif
   38457   };
   38458   unsigned int i;          /* Loop counter */
   38459 
   38460   /* Double-check that the aSyscall[] array has been constructed
   38461   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   38462   assert( ArraySize(aSyscall)==29 );
   38463 
   38464   /* Register all VFSes defined in the aVfs[] array */
   38465   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   38466     sqlite3_vfs_register(&aVfs[i], i==0);
   38467   }
   38468   return SQLITE_OK;
   38469 }
   38470 
   38471 /*
   38472 ** Shutdown the operating system interface.
   38473 **
   38474 ** Some operating systems might need to do some cleanup in this routine,
   38475 ** to release dynamically allocated objects.  But not on unix.
   38476 ** This routine is a no-op for unix.
   38477 */
   38478 SQLITE_API int sqlite3_os_end(void){
   38479   return SQLITE_OK;
   38480 }
   38481 
   38482 #endif /* SQLITE_OS_UNIX */
   38483 
   38484 /************** End of os_unix.c *********************************************/
   38485 /************** Begin file os_win.c ******************************************/
   38486 /*
   38487 ** 2004 May 22
   38488 **
   38489 ** The author disclaims copyright to this source code.  In place of
   38490 ** a legal notice, here is a blessing:
   38491 **
   38492 **    May you do good and not evil.
   38493 **    May you find forgiveness for yourself and forgive others.
   38494 **    May you share freely, never taking more than you give.
   38495 **
   38496 ******************************************************************************
   38497 **
   38498 ** This file contains code that is specific to Windows.
   38499 */
   38500 /* #include "sqliteInt.h" */
   38501 #if SQLITE_OS_WIN               /* This file is used for Windows only */
   38502 
   38503 /*
   38504 ** Include code that is common to all os_*.c files
   38505 */
   38506 /************** Include os_common.h in the middle of os_win.c ****************/
   38507 /************** Begin file os_common.h ***************************************/
   38508 /*
   38509 ** 2004 May 22
   38510 **
   38511 ** The author disclaims copyright to this source code.  In place of
   38512 ** a legal notice, here is a blessing:
   38513 **
   38514 **    May you do good and not evil.
   38515 **    May you find forgiveness for yourself and forgive others.
   38516 **    May you share freely, never taking more than you give.
   38517 **
   38518 ******************************************************************************
   38519 **
   38520 ** This file contains macros and a little bit of code that is common to
   38521 ** all of the platform-specific files (os_*.c) and is #included into those
   38522 ** files.
   38523 **
   38524 ** This file should be #included by the os_*.c files only.  It is not a
   38525 ** general purpose header file.
   38526 */
   38527 #ifndef _OS_COMMON_H_
   38528 #define _OS_COMMON_H_
   38529 
   38530 /*
   38531 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   38532 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   38533 ** switch.  The following code should catch this problem at compile-time.
   38534 */
   38535 #ifdef MEMORY_DEBUG
   38536 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   38537 #endif
   38538 
   38539 /*
   38540 ** Macros for performance tracing.  Normally turned off.  Only works
   38541 ** on i486 hardware.
   38542 */
   38543 #ifdef SQLITE_PERFORMANCE_TRACE
   38544 
   38545 /*
   38546 ** hwtime.h contains inline assembler code for implementing
   38547 ** high-performance timing routines.
   38548 */
   38549 /************** Include hwtime.h in the middle of os_common.h ****************/
   38550 /************** Begin file hwtime.h ******************************************/
   38551 /*
   38552 ** 2008 May 27
   38553 **
   38554 ** The author disclaims copyright to this source code.  In place of
   38555 ** a legal notice, here is a blessing:
   38556 **
   38557 **    May you do good and not evil.
   38558 **    May you find forgiveness for yourself and forgive others.
   38559 **    May you share freely, never taking more than you give.
   38560 **
   38561 ******************************************************************************
   38562 **
   38563 ** This file contains inline asm code for retrieving "high-performance"
   38564 ** counters for x86 class CPUs.
   38565 */
   38566 #ifndef SQLITE_HWTIME_H
   38567 #define SQLITE_HWTIME_H
   38568 
   38569 /*
   38570 ** The following routine only works on pentium-class (or newer) processors.
   38571 ** It uses the RDTSC opcode to read the cycle count value out of the
   38572 ** processor and returns that value.  This can be used for high-res
   38573 ** profiling.
   38574 */
   38575 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   38576       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   38577 
   38578   #if defined(__GNUC__)
   38579 
   38580   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   38581      unsigned int lo, hi;
   38582      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   38583      return (sqlite_uint64)hi << 32 | lo;
   38584   }
   38585 
   38586   #elif defined(_MSC_VER)
   38587 
   38588   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   38589      __asm {
   38590         rdtsc
   38591         ret       ; return value at EDX:EAX
   38592      }
   38593   }
   38594 
   38595   #endif
   38596 
   38597 #elif (defined(__GNUC__) && defined(__x86_64__))
   38598 
   38599   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   38600       unsigned long val;
   38601       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   38602       return val;
   38603   }
   38604 
   38605 #elif (defined(__GNUC__) && defined(__ppc__))
   38606 
   38607   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   38608       unsigned long long retval;
   38609       unsigned long junk;
   38610       __asm__ __volatile__ ("\n\
   38611           1:      mftbu   %1\n\
   38612                   mftb    %L0\n\
   38613                   mftbu   %0\n\
   38614                   cmpw    %0,%1\n\
   38615                   bne     1b"
   38616                   : "=r" (retval), "=r" (junk));
   38617       return retval;
   38618   }
   38619 
   38620 #else
   38621 
   38622   #error Need implementation of sqlite3Hwtime() for your platform.
   38623 
   38624   /*
   38625   ** To compile without implementing sqlite3Hwtime() for your platform,
   38626   ** you can remove the above #error and use the following
   38627   ** stub function.  You will lose timing support for many
   38628   ** of the debugging and testing utilities, but it should at
   38629   ** least compile and run.
   38630   */
   38631 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   38632 
   38633 #endif
   38634 
   38635 #endif /* !defined(SQLITE_HWTIME_H) */
   38636 
   38637 /************** End of hwtime.h **********************************************/
   38638 /************** Continuing where we left off in os_common.h ******************/
   38639 
   38640 static sqlite_uint64 g_start;
   38641 static sqlite_uint64 g_elapsed;
   38642 #define TIMER_START       g_start=sqlite3Hwtime()
   38643 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   38644 #define TIMER_ELAPSED     g_elapsed
   38645 #else
   38646 #define TIMER_START
   38647 #define TIMER_END
   38648 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   38649 #endif
   38650 
   38651 /*
   38652 ** If we compile with the SQLITE_TEST macro set, then the following block
   38653 ** of code will give us the ability to simulate a disk I/O error.  This
   38654 ** is used for testing the I/O recovery logic.
   38655 */
   38656 #if defined(SQLITE_TEST)
   38657 SQLITE_API extern int sqlite3_io_error_hit;
   38658 SQLITE_API extern int sqlite3_io_error_hardhit;
   38659 SQLITE_API extern int sqlite3_io_error_pending;
   38660 SQLITE_API extern int sqlite3_io_error_persist;
   38661 SQLITE_API extern int sqlite3_io_error_benign;
   38662 SQLITE_API extern int sqlite3_diskfull_pending;
   38663 SQLITE_API extern int sqlite3_diskfull;
   38664 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   38665 #define SimulateIOError(CODE)  \
   38666   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   38667        || sqlite3_io_error_pending-- == 1 )  \
   38668               { local_ioerr(); CODE; }
   38669 static void local_ioerr(){
   38670   IOTRACE(("IOERR\n"));
   38671   sqlite3_io_error_hit++;
   38672   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   38673 }
   38674 #define SimulateDiskfullError(CODE) \
   38675    if( sqlite3_diskfull_pending ){ \
   38676      if( sqlite3_diskfull_pending == 1 ){ \
   38677        local_ioerr(); \
   38678        sqlite3_diskfull = 1; \
   38679        sqlite3_io_error_hit = 1; \
   38680        CODE; \
   38681      }else{ \
   38682        sqlite3_diskfull_pending--; \
   38683      } \
   38684    }
   38685 #else
   38686 #define SimulateIOErrorBenign(X)
   38687 #define SimulateIOError(A)
   38688 #define SimulateDiskfullError(A)
   38689 #endif /* defined(SQLITE_TEST) */
   38690 
   38691 /*
   38692 ** When testing, keep a count of the number of open files.
   38693 */
   38694 #if defined(SQLITE_TEST)
   38695 SQLITE_API extern int sqlite3_open_file_count;
   38696 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   38697 #else
   38698 #define OpenCounter(X)
   38699 #endif /* defined(SQLITE_TEST) */
   38700 
   38701 #endif /* !defined(_OS_COMMON_H_) */
   38702 
   38703 /************** End of os_common.h *******************************************/
   38704 /************** Continuing where we left off in os_win.c *********************/
   38705 
   38706 /*
   38707 ** Include the header file for the Windows VFS.
   38708 */
   38709 /* #include "os_win.h" */
   38710 
   38711 /*
   38712 ** Compiling and using WAL mode requires several APIs that are only
   38713 ** available in Windows platforms based on the NT kernel.
   38714 */
   38715 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
   38716 #  error "WAL mode requires support from the Windows NT kernel, compile\
   38717  with SQLITE_OMIT_WAL."
   38718 #endif
   38719 
   38720 #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
   38721 #  error "Memory mapped files require support from the Windows NT kernel,\
   38722  compile with SQLITE_MAX_MMAP_SIZE=0."
   38723 #endif
   38724 
   38725 /*
   38726 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
   38727 ** based on the sub-platform)?
   38728 */
   38729 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
   38730 #  define SQLITE_WIN32_HAS_ANSI
   38731 #endif
   38732 
   38733 /*
   38734 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
   38735 ** based on the sub-platform)?
   38736 */
   38737 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
   38738     !defined(SQLITE_WIN32_NO_WIDE)
   38739 #  define SQLITE_WIN32_HAS_WIDE
   38740 #endif
   38741 
   38742 /*
   38743 ** Make sure at least one set of Win32 APIs is available.
   38744 */
   38745 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
   38746 #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
   38747  must be defined."
   38748 #endif
   38749 
   38750 /*
   38751 ** Define the required Windows SDK version constants if they are not
   38752 ** already available.
   38753 */
   38754 #ifndef NTDDI_WIN8
   38755 #  define NTDDI_WIN8                        0x06020000
   38756 #endif
   38757 
   38758 #ifndef NTDDI_WINBLUE
   38759 #  define NTDDI_WINBLUE                     0x06030000
   38760 #endif
   38761 
   38762 #ifndef NTDDI_WINTHRESHOLD
   38763 #  define NTDDI_WINTHRESHOLD                0x06040000
   38764 #endif
   38765 
   38766 /*
   38767 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
   38768 ** target system.  GetVersionEx was first deprecated in Win8.1.
   38769 */
   38770 #ifndef SQLITE_WIN32_GETVERSIONEX
   38771 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
   38772 #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
   38773 #  else
   38774 #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
   38775 #  endif
   38776 #endif
   38777 
   38778 /*
   38779 ** Check to see if the CreateFileMappingA function is supported on the
   38780 ** target system.  It is unavailable when using "mincore.lib" on Win10.
   38781 ** When compiling for Windows 10, always assume "mincore.lib" is in use.
   38782 */
   38783 #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
   38784 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
   38785 #    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
   38786 #  else
   38787 #    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
   38788 #  endif
   38789 #endif
   38790 
   38791 /*
   38792 ** This constant should already be defined (in the "WinDef.h" SDK file).
   38793 */
   38794 #ifndef MAX_PATH
   38795 #  define MAX_PATH                      (260)
   38796 #endif
   38797 
   38798 /*
   38799 ** Maximum pathname length (in chars) for Win32.  This should normally be
   38800 ** MAX_PATH.
   38801 */
   38802 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
   38803 #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
   38804 #endif
   38805 
   38806 /*
   38807 ** This constant should already be defined (in the "WinNT.h" SDK file).
   38808 */
   38809 #ifndef UNICODE_STRING_MAX_CHARS
   38810 #  define UNICODE_STRING_MAX_CHARS      (32767)
   38811 #endif
   38812 
   38813 /*
   38814 ** Maximum pathname length (in chars) for WinNT.  This should normally be
   38815 ** UNICODE_STRING_MAX_CHARS.
   38816 */
   38817 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
   38818 #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
   38819 #endif
   38820 
   38821 /*
   38822 ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
   38823 ** characters, so we allocate 4 bytes per character assuming worst-case of
   38824 ** 4-bytes-per-character for UTF8.
   38825 */
   38826 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
   38827 #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
   38828 #endif
   38829 
   38830 /*
   38831 ** Maximum pathname length (in bytes) for WinNT.  This should normally be
   38832 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
   38833 */
   38834 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
   38835 #  define SQLITE_WINNT_MAX_PATH_BYTES   \
   38836                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
   38837 #endif
   38838 
   38839 /*
   38840 ** Maximum error message length (in chars) for WinRT.
   38841 */
   38842 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
   38843 #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
   38844 #endif
   38845 
   38846 /*
   38847 ** Returns non-zero if the character should be treated as a directory
   38848 ** separator.
   38849 */
   38850 #ifndef winIsDirSep
   38851 #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
   38852 #endif
   38853 
   38854 /*
   38855 ** This macro is used when a local variable is set to a value that is
   38856 ** [sometimes] not used by the code (e.g. via conditional compilation).
   38857 */
   38858 #ifndef UNUSED_VARIABLE_VALUE
   38859 #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
   38860 #endif
   38861 
   38862 /*
   38863 ** Returns the character that should be used as the directory separator.
   38864 */
   38865 #ifndef winGetDirSep
   38866 #  define winGetDirSep()                '\\'
   38867 #endif
   38868 
   38869 /*
   38870 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
   38871 ** mode or memory mapped files (e.g. these APIs are available in the Windows
   38872 ** CE SDK; however, they are not present in the header file)?
   38873 */
   38874 #if SQLITE_WIN32_FILEMAPPING_API && \
   38875         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
   38876 /*
   38877 ** Two of the file mapping APIs are different under WinRT.  Figure out which
   38878 ** set we need.
   38879 */
   38880 #if SQLITE_OS_WINRT
   38881 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
   38882         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
   38883 
   38884 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
   38885 #else
   38886 #if defined(SQLITE_WIN32_HAS_ANSI)
   38887 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
   38888         DWORD, DWORD, DWORD, LPCSTR);
   38889 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
   38890 
   38891 #if defined(SQLITE_WIN32_HAS_WIDE)
   38892 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
   38893         DWORD, DWORD, DWORD, LPCWSTR);
   38894 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
   38895 
   38896 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
   38897 #endif /* SQLITE_OS_WINRT */
   38898 
   38899 /*
   38900 ** These file mapping APIs are common to both Win32 and WinRT.
   38901 */
   38902 
   38903 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
   38904 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
   38905 #endif /* SQLITE_WIN32_FILEMAPPING_API */
   38906 
   38907 /*
   38908 ** Some Microsoft compilers lack this definition.
   38909 */
   38910 #ifndef INVALID_FILE_ATTRIBUTES
   38911 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   38912 #endif
   38913 
   38914 #ifndef FILE_FLAG_MASK
   38915 # define FILE_FLAG_MASK          (0xFF3C0000)
   38916 #endif
   38917 
   38918 #ifndef FILE_ATTRIBUTE_MASK
   38919 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
   38920 #endif
   38921 
   38922 #ifndef SQLITE_OMIT_WAL
   38923 /* Forward references to structures used for WAL */
   38924 typedef struct winShm winShm;           /* A connection to shared-memory */
   38925 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
   38926 #endif
   38927 
   38928 /*
   38929 ** WinCE lacks native support for file locking so we have to fake it
   38930 ** with some code of our own.
   38931 */
   38932 #if SQLITE_OS_WINCE
   38933 typedef struct winceLock {
   38934   int nReaders;       /* Number of reader locks obtained */
   38935   BOOL bPending;      /* Indicates a pending lock has been obtained */
   38936   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
   38937   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
   38938 } winceLock;
   38939 #endif
   38940 
   38941 /*
   38942 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
   38943 ** portability layer.
   38944 */
   38945 typedef struct winFile winFile;
   38946 struct winFile {
   38947   const sqlite3_io_methods *pMethod; /*** Must be first ***/
   38948   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
   38949   HANDLE h;               /* Handle for accessing the file */
   38950   u8 locktype;            /* Type of lock currently held on this file */
   38951   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   38952   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
   38953   DWORD lastErrno;        /* The Windows errno from the last I/O error */
   38954 #ifndef SQLITE_OMIT_WAL
   38955   winShm *pShm;           /* Instance of shared memory on this file */
   38956 #endif
   38957   const char *zPath;      /* Full pathname of this file */
   38958   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   38959 #if SQLITE_OS_WINCE
   38960   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
   38961   HANDLE hMutex;          /* Mutex used to control access to shared lock */
   38962   HANDLE hShared;         /* Shared memory segment used for locking */
   38963   winceLock local;        /* Locks obtained by this instance of winFile */
   38964   winceLock *shared;      /* Global shared lock memory for the file  */
   38965 #endif
   38966 #if SQLITE_MAX_MMAP_SIZE>0
   38967   int nFetchOut;                /* Number of outstanding xFetch references */
   38968   HANDLE hMap;                  /* Handle for accessing memory mapping */
   38969   void *pMapRegion;             /* Area memory mapped */
   38970   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
   38971   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
   38972   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
   38973 #endif
   38974 };
   38975 
   38976 /*
   38977 ** The winVfsAppData structure is used for the pAppData member for all of the
   38978 ** Win32 VFS variants.
   38979 */
   38980 typedef struct winVfsAppData winVfsAppData;
   38981 struct winVfsAppData {
   38982   const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
   38983   void *pAppData;                    /* The extra pAppData, if any. */
   38984   BOOL bNoLock;                      /* Non-zero if locking is disabled. */
   38985 };
   38986 
   38987 /*
   38988 ** Allowed values for winFile.ctrlFlags
   38989 */
   38990 #define WINFILE_RDONLY          0x02   /* Connection is read only */
   38991 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
   38992 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   38993 
   38994 /*
   38995  * The size of the buffer used by sqlite3_win32_write_debug().
   38996  */
   38997 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
   38998 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
   38999 #endif
   39000 
   39001 /*
   39002  * The value used with sqlite3_win32_set_directory() to specify that
   39003  * the data directory should be changed.
   39004  */
   39005 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
   39006 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
   39007 #endif
   39008 
   39009 /*
   39010  * The value used with sqlite3_win32_set_directory() to specify that
   39011  * the temporary directory should be changed.
   39012  */
   39013 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
   39014 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
   39015 #endif
   39016 
   39017 /*
   39018  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
   39019  * various Win32 API heap functions instead of our own.
   39020  */
   39021 #ifdef SQLITE_WIN32_MALLOC
   39022 
   39023 /*
   39024  * If this is non-zero, an isolated heap will be created by the native Win32
   39025  * allocator subsystem; otherwise, the default process heap will be used.  This
   39026  * setting has no effect when compiling for WinRT.  By default, this is enabled
   39027  * and an isolated heap will be created to store all allocated data.
   39028  *
   39029  ******************************************************************************
   39030  * WARNING: It is important to note that when this setting is non-zero and the
   39031  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
   39032  *          function), all data that was allocated using the isolated heap will
   39033  *          be freed immediately and any attempt to access any of that freed
   39034  *          data will almost certainly result in an immediate access violation.
   39035  ******************************************************************************
   39036  */
   39037 #ifndef SQLITE_WIN32_HEAP_CREATE
   39038 #  define SQLITE_WIN32_HEAP_CREATE        (TRUE)
   39039 #endif
   39040 
   39041 /*
   39042  * This is the maximum possible initial size of the Win32-specific heap, in
   39043  * bytes.
   39044  */
   39045 #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
   39046 #  define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
   39047 #endif
   39048 
   39049 /*
   39050  * This is the extra space for the initial size of the Win32-specific heap,
   39051  * in bytes.  This value may be zero.
   39052  */
   39053 #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
   39054 #  define SQLITE_WIN32_HEAP_INIT_EXTRA  (4194304)
   39055 #endif
   39056 
   39057 /*
   39058  * Calculate the maximum legal cache size, in pages, based on the maximum
   39059  * possible initial heap size and the default page size, setting aside the
   39060  * needed extra space.
   39061  */
   39062 #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
   39063 #  define SQLITE_WIN32_MAX_CACHE_SIZE   (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
   39064                                           (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
   39065                                          (SQLITE_DEFAULT_PAGE_SIZE))
   39066 #endif
   39067 
   39068 /*
   39069  * This is cache size used in the calculation of the initial size of the
   39070  * Win32-specific heap.  It cannot be negative.
   39071  */
   39072 #ifndef SQLITE_WIN32_CACHE_SIZE
   39073 #  if SQLITE_DEFAULT_CACHE_SIZE>=0
   39074 #    define SQLITE_WIN32_CACHE_SIZE     (SQLITE_DEFAULT_CACHE_SIZE)
   39075 #  else
   39076 #    define SQLITE_WIN32_CACHE_SIZE     (-(SQLITE_DEFAULT_CACHE_SIZE))
   39077 #  endif
   39078 #endif
   39079 
   39080 /*
   39081  * Make sure that the calculated cache size, in pages, cannot cause the
   39082  * initial size of the Win32-specific heap to exceed the maximum amount
   39083  * of memory that can be specified in the call to HeapCreate.
   39084  */
   39085 #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
   39086 #  undef SQLITE_WIN32_CACHE_SIZE
   39087 #  define SQLITE_WIN32_CACHE_SIZE       (2000)
   39088 #endif
   39089 
   39090 /*
   39091  * The initial size of the Win32-specific heap.  This value may be zero.
   39092  */
   39093 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
   39094 #  define SQLITE_WIN32_HEAP_INIT_SIZE   ((SQLITE_WIN32_CACHE_SIZE) * \
   39095                                          (SQLITE_DEFAULT_PAGE_SIZE) + \
   39096                                          (SQLITE_WIN32_HEAP_INIT_EXTRA))
   39097 #endif
   39098 
   39099 /*
   39100  * The maximum size of the Win32-specific heap.  This value may be zero.
   39101  */
   39102 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
   39103 #  define SQLITE_WIN32_HEAP_MAX_SIZE    (0)
   39104 #endif
   39105 
   39106 /*
   39107  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
   39108  * zero for the default behavior.
   39109  */
   39110 #ifndef SQLITE_WIN32_HEAP_FLAGS
   39111 #  define SQLITE_WIN32_HEAP_FLAGS       (0)
   39112 #endif
   39113 
   39114 
   39115 /*
   39116 ** The winMemData structure stores information required by the Win32-specific
   39117 ** sqlite3_mem_methods implementation.
   39118 */
   39119 typedef struct winMemData winMemData;
   39120 struct winMemData {
   39121 #ifndef NDEBUG
   39122   u32 magic1;   /* Magic number to detect structure corruption. */
   39123 #endif
   39124   HANDLE hHeap; /* The handle to our heap. */
   39125   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
   39126 #ifndef NDEBUG
   39127   u32 magic2;   /* Magic number to detect structure corruption. */
   39128 #endif
   39129 };
   39130 
   39131 #ifndef NDEBUG
   39132 #define WINMEM_MAGIC1     0x42b2830b
   39133 #define WINMEM_MAGIC2     0xbd4d7cf4
   39134 #endif
   39135 
   39136 static struct winMemData win_mem_data = {
   39137 #ifndef NDEBUG
   39138   WINMEM_MAGIC1,
   39139 #endif
   39140   NULL, FALSE
   39141 #ifndef NDEBUG
   39142   ,WINMEM_MAGIC2
   39143 #endif
   39144 };
   39145 
   39146 #ifndef NDEBUG
   39147 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
   39148 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
   39149 #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
   39150 #else
   39151 #define winMemAssertMagic()
   39152 #endif
   39153 
   39154 #define winMemGetDataPtr()  &win_mem_data
   39155 #define winMemGetHeap()     win_mem_data.hHeap
   39156 #define winMemGetOwned()    win_mem_data.bOwned
   39157 
   39158 static void *winMemMalloc(int nBytes);
   39159 static void winMemFree(void *pPrior);
   39160 static void *winMemRealloc(void *pPrior, int nBytes);
   39161 static int winMemSize(void *p);
   39162 static int winMemRoundup(int n);
   39163 static int winMemInit(void *pAppData);
   39164 static void winMemShutdown(void *pAppData);
   39165 
   39166 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
   39167 #endif /* SQLITE_WIN32_MALLOC */
   39168 
   39169 /*
   39170 ** The following variable is (normally) set once and never changes
   39171 ** thereafter.  It records whether the operating system is Win9x
   39172 ** or WinNT.
   39173 **
   39174 ** 0:   Operating system unknown.
   39175 ** 1:   Operating system is Win9x.
   39176 ** 2:   Operating system is WinNT.
   39177 **
   39178 ** In order to facilitate testing on a WinNT system, the test fixture
   39179 ** can manually set this value to 1 to emulate Win98 behavior.
   39180 */
   39181 #ifdef SQLITE_TEST
   39182 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
   39183 #else
   39184 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
   39185 #endif
   39186 
   39187 #ifndef SYSCALL
   39188 #  define SYSCALL sqlite3_syscall_ptr
   39189 #endif
   39190 
   39191 /*
   39192 ** This function is not available on Windows CE or WinRT.
   39193  */
   39194 
   39195 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
   39196 #  define osAreFileApisANSI()       1
   39197 #endif
   39198 
   39199 /*
   39200 ** Many system calls are accessed through pointer-to-functions so that
   39201 ** they may be overridden at runtime to facilitate fault injection during
   39202 ** testing and sandboxing.  The following array holds the names and pointers
   39203 ** to all overrideable system calls.
   39204 */
   39205 static struct win_syscall {
   39206   const char *zName;            /* Name of the system call */
   39207   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   39208   sqlite3_syscall_ptr pDefault; /* Default value */
   39209 } aSyscall[] = {
   39210 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   39211   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
   39212 #else
   39213   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
   39214 #endif
   39215 
   39216 #ifndef osAreFileApisANSI
   39217 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
   39218 #endif
   39219 
   39220 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   39221   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
   39222 #else
   39223   { "CharLowerW",              (SYSCALL)0,                       0 },
   39224 #endif
   39225 
   39226 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
   39227 
   39228 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   39229   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
   39230 #else
   39231   { "CharUpperW",              (SYSCALL)0,                       0 },
   39232 #endif
   39233 
   39234 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
   39235 
   39236   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
   39237 
   39238 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
   39239 
   39240 #if defined(SQLITE_WIN32_HAS_ANSI)
   39241   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
   39242 #else
   39243   { "CreateFileA",             (SYSCALL)0,                       0 },
   39244 #endif
   39245 
   39246 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
   39247         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
   39248 
   39249 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   39250   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
   39251 #else
   39252   { "CreateFileW",             (SYSCALL)0,                       0 },
   39253 #endif
   39254 
   39255 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
   39256         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
   39257 
   39258 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
   39259         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
   39260         SQLITE_WIN32_CREATEFILEMAPPINGA
   39261   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
   39262 #else
   39263   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
   39264 #endif
   39265 
   39266 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   39267         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
   39268 
   39269 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   39270         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
   39271   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
   39272 #else
   39273   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
   39274 #endif
   39275 
   39276 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   39277         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
   39278 
   39279 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   39280   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
   39281 #else
   39282   { "CreateMutexW",            (SYSCALL)0,                       0 },
   39283 #endif
   39284 
   39285 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
   39286         LPCWSTR))aSyscall[8].pCurrent)
   39287 
   39288 #if defined(SQLITE_WIN32_HAS_ANSI)
   39289   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
   39290 #else
   39291   { "DeleteFileA",             (SYSCALL)0,                       0 },
   39292 #endif
   39293 
   39294 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
   39295 
   39296 #if defined(SQLITE_WIN32_HAS_WIDE)
   39297   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
   39298 #else
   39299   { "DeleteFileW",             (SYSCALL)0,                       0 },
   39300 #endif
   39301 
   39302 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
   39303 
   39304 #if SQLITE_OS_WINCE
   39305   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
   39306 #else
   39307   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
   39308 #endif
   39309 
   39310 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   39311         LPFILETIME))aSyscall[11].pCurrent)
   39312 
   39313 #if SQLITE_OS_WINCE
   39314   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
   39315 #else
   39316   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
   39317 #endif
   39318 
   39319 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   39320         LPSYSTEMTIME))aSyscall[12].pCurrent)
   39321 
   39322   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
   39323 
   39324 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
   39325 
   39326 #if defined(SQLITE_WIN32_HAS_ANSI)
   39327   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
   39328 #else
   39329   { "FormatMessageA",          (SYSCALL)0,                       0 },
   39330 #endif
   39331 
   39332 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
   39333         DWORD,va_list*))aSyscall[14].pCurrent)
   39334 
   39335 #if defined(SQLITE_WIN32_HAS_WIDE)
   39336   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
   39337 #else
   39338   { "FormatMessageW",          (SYSCALL)0,                       0 },
   39339 #endif
   39340 
   39341 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
   39342         DWORD,va_list*))aSyscall[15].pCurrent)
   39343 
   39344 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
   39345   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
   39346 #else
   39347   { "FreeLibrary",             (SYSCALL)0,                       0 },
   39348 #endif
   39349 
   39350 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
   39351 
   39352   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
   39353 
   39354 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
   39355 
   39356 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   39357   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
   39358 #else
   39359   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
   39360 #endif
   39361 
   39362 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
   39363         LPDWORD))aSyscall[18].pCurrent)
   39364 
   39365 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   39366   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
   39367 #else
   39368   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
   39369 #endif
   39370 
   39371 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
   39372         LPDWORD))aSyscall[19].pCurrent)
   39373 
   39374 #if defined(SQLITE_WIN32_HAS_ANSI)
   39375   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
   39376 #else
   39377   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
   39378 #endif
   39379 
   39380 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
   39381 
   39382 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   39383   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
   39384 #else
   39385   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
   39386 #endif
   39387 
   39388 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
   39389 
   39390 #if defined(SQLITE_WIN32_HAS_WIDE)
   39391   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
   39392 #else
   39393   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
   39394 #endif
   39395 
   39396 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
   39397         LPVOID))aSyscall[22].pCurrent)
   39398 
   39399 #if !SQLITE_OS_WINRT
   39400   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
   39401 #else
   39402   { "GetFileSize",             (SYSCALL)0,                       0 },
   39403 #endif
   39404 
   39405 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
   39406 
   39407 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   39408   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
   39409 #else
   39410   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
   39411 #endif
   39412 
   39413 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
   39414         LPSTR*))aSyscall[24].pCurrent)
   39415 
   39416 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   39417   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
   39418 #else
   39419   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
   39420 #endif
   39421 
   39422 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
   39423         LPWSTR*))aSyscall[25].pCurrent)
   39424 
   39425   { "GetLastError",            (SYSCALL)GetLastError,            0 },
   39426 
   39427 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
   39428 
   39429 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
   39430 #if SQLITE_OS_WINCE
   39431   /* The GetProcAddressA() routine is only available on Windows CE. */
   39432   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
   39433 #else
   39434   /* All other Windows platforms expect GetProcAddress() to take
   39435   ** an ANSI string regardless of the _UNICODE setting */
   39436   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
   39437 #endif
   39438 #else
   39439   { "GetProcAddressA",         (SYSCALL)0,                       0 },
   39440 #endif
   39441 
   39442 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
   39443         LPCSTR))aSyscall[27].pCurrent)
   39444 
   39445 #if !SQLITE_OS_WINRT
   39446   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
   39447 #else
   39448   { "GetSystemInfo",           (SYSCALL)0,                       0 },
   39449 #endif
   39450 
   39451 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
   39452 
   39453   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
   39454 
   39455 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
   39456 
   39457 #if !SQLITE_OS_WINCE
   39458   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
   39459 #else
   39460   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
   39461 #endif
   39462 
   39463 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
   39464         LPFILETIME))aSyscall[30].pCurrent)
   39465 
   39466 #if defined(SQLITE_WIN32_HAS_ANSI)
   39467   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
   39468 #else
   39469   { "GetTempPathA",            (SYSCALL)0,                       0 },
   39470 #endif
   39471 
   39472 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
   39473 
   39474 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
   39475   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
   39476 #else
   39477   { "GetTempPathW",            (SYSCALL)0,                       0 },
   39478 #endif
   39479 
   39480 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
   39481 
   39482 #if !SQLITE_OS_WINRT
   39483   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
   39484 #else
   39485   { "GetTickCount",            (SYSCALL)0,                       0 },
   39486 #endif
   39487 
   39488 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
   39489 
   39490 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
   39491   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
   39492 #else
   39493   { "GetVersionExA",           (SYSCALL)0,                       0 },
   39494 #endif
   39495 
   39496 #define osGetVersionExA ((BOOL(WINAPI*)( \
   39497         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
   39498 
   39499 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   39500         SQLITE_WIN32_GETVERSIONEX
   39501   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
   39502 #else
   39503   { "GetVersionExW",           (SYSCALL)0,                       0 },
   39504 #endif
   39505 
   39506 #define osGetVersionExW ((BOOL(WINAPI*)( \
   39507         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
   39508 
   39509   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
   39510 
   39511 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
   39512         SIZE_T))aSyscall[36].pCurrent)
   39513 
   39514 #if !SQLITE_OS_WINRT
   39515   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
   39516 #else
   39517   { "HeapCreate",              (SYSCALL)0,                       0 },
   39518 #endif
   39519 
   39520 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
   39521         SIZE_T))aSyscall[37].pCurrent)
   39522 
   39523 #if !SQLITE_OS_WINRT
   39524   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
   39525 #else
   39526   { "HeapDestroy",             (SYSCALL)0,                       0 },
   39527 #endif
   39528 
   39529 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
   39530 
   39531   { "HeapFree",                (SYSCALL)HeapFree,                0 },
   39532 
   39533 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
   39534 
   39535   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
   39536 
   39537 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
   39538         SIZE_T))aSyscall[40].pCurrent)
   39539 
   39540   { "HeapSize",                (SYSCALL)HeapSize,                0 },
   39541 
   39542 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
   39543         LPCVOID))aSyscall[41].pCurrent)
   39544 
   39545 #if !SQLITE_OS_WINRT
   39546   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
   39547 #else
   39548   { "HeapValidate",            (SYSCALL)0,                       0 },
   39549 #endif
   39550 
   39551 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
   39552         LPCVOID))aSyscall[42].pCurrent)
   39553 
   39554 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   39555   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
   39556 #else
   39557   { "HeapCompact",             (SYSCALL)0,                       0 },
   39558 #endif
   39559 
   39560 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
   39561 
   39562 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   39563   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
   39564 #else
   39565   { "LoadLibraryA",            (SYSCALL)0,                       0 },
   39566 #endif
   39567 
   39568 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
   39569 
   39570 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
   39571         !defined(SQLITE_OMIT_LOAD_EXTENSION)
   39572   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
   39573 #else
   39574   { "LoadLibraryW",            (SYSCALL)0,                       0 },
   39575 #endif
   39576 
   39577 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
   39578 
   39579 #if !SQLITE_OS_WINRT
   39580   { "LocalFree",               (SYSCALL)LocalFree,               0 },
   39581 #else
   39582   { "LocalFree",               (SYSCALL)0,                       0 },
   39583 #endif
   39584 
   39585 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
   39586 
   39587 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   39588   { "LockFile",                (SYSCALL)LockFile,                0 },
   39589 #else
   39590   { "LockFile",                (SYSCALL)0,                       0 },
   39591 #endif
   39592 
   39593 #ifndef osLockFile
   39594 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   39595         DWORD))aSyscall[47].pCurrent)
   39596 #endif
   39597 
   39598 #if !SQLITE_OS_WINCE
   39599   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
   39600 #else
   39601   { "LockFileEx",              (SYSCALL)0,                       0 },
   39602 #endif
   39603 
   39604 #ifndef osLockFileEx
   39605 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
   39606         LPOVERLAPPED))aSyscall[48].pCurrent)
   39607 #endif
   39608 
   39609 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
   39610         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
   39611   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
   39612 #else
   39613   { "MapViewOfFile",           (SYSCALL)0,                       0 },
   39614 #endif
   39615 
   39616 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   39617         SIZE_T))aSyscall[49].pCurrent)
   39618 
   39619   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
   39620 
   39621 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
   39622         int))aSyscall[50].pCurrent)
   39623 
   39624   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
   39625 
   39626 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
   39627         LARGE_INTEGER*))aSyscall[51].pCurrent)
   39628 
   39629   { "ReadFile",                (SYSCALL)ReadFile,                0 },
   39630 
   39631 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
   39632         LPOVERLAPPED))aSyscall[52].pCurrent)
   39633 
   39634   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
   39635 
   39636 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
   39637 
   39638 #if !SQLITE_OS_WINRT
   39639   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
   39640 #else
   39641   { "SetFilePointer",          (SYSCALL)0,                       0 },
   39642 #endif
   39643 
   39644 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
   39645         DWORD))aSyscall[54].pCurrent)
   39646 
   39647 #if !SQLITE_OS_WINRT
   39648   { "Sleep",                   (SYSCALL)Sleep,                   0 },
   39649 #else
   39650   { "Sleep",                   (SYSCALL)0,                       0 },
   39651 #endif
   39652 
   39653 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
   39654 
   39655   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
   39656 
   39657 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
   39658         LPFILETIME))aSyscall[56].pCurrent)
   39659 
   39660 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   39661   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
   39662 #else
   39663   { "UnlockFile",              (SYSCALL)0,                       0 },
   39664 #endif
   39665 
   39666 #ifndef osUnlockFile
   39667 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   39668         DWORD))aSyscall[57].pCurrent)
   39669 #endif
   39670 
   39671 #if !SQLITE_OS_WINCE
   39672   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
   39673 #else
   39674   { "UnlockFileEx",            (SYSCALL)0,                       0 },
   39675 #endif
   39676 
   39677 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   39678         LPOVERLAPPED))aSyscall[58].pCurrent)
   39679 
   39680 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
   39681   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
   39682 #else
   39683   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
   39684 #endif
   39685 
   39686 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
   39687 
   39688   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
   39689 
   39690 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
   39691         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
   39692 
   39693   { "WriteFile",               (SYSCALL)WriteFile,               0 },
   39694 
   39695 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
   39696         LPOVERLAPPED))aSyscall[61].pCurrent)
   39697 
   39698 #if SQLITE_OS_WINRT
   39699   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
   39700 #else
   39701   { "CreateEventExW",          (SYSCALL)0,                       0 },
   39702 #endif
   39703 
   39704 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
   39705         DWORD,DWORD))aSyscall[62].pCurrent)
   39706 
   39707 #if !SQLITE_OS_WINRT
   39708   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
   39709 #else
   39710   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
   39711 #endif
   39712 
   39713 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
   39714         DWORD))aSyscall[63].pCurrent)
   39715 
   39716 #if !SQLITE_OS_WINCE
   39717   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
   39718 #else
   39719   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
   39720 #endif
   39721 
   39722 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
   39723         BOOL))aSyscall[64].pCurrent)
   39724 
   39725 #if SQLITE_OS_WINRT
   39726   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
   39727 #else
   39728   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
   39729 #endif
   39730 
   39731 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
   39732         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
   39733 
   39734 #if SQLITE_OS_WINRT
   39735   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
   39736 #else
   39737   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
   39738 #endif
   39739 
   39740 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
   39741         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
   39742 
   39743 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
   39744   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
   39745 #else
   39746   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
   39747 #endif
   39748 
   39749 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
   39750         SIZE_T))aSyscall[67].pCurrent)
   39751 
   39752 #if SQLITE_OS_WINRT
   39753   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
   39754 #else
   39755   { "CreateFile2",             (SYSCALL)0,                       0 },
   39756 #endif
   39757 
   39758 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
   39759         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
   39760 
   39761 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   39762   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
   39763 #else
   39764   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
   39765 #endif
   39766 
   39767 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
   39768         DWORD))aSyscall[69].pCurrent)
   39769 
   39770 #if SQLITE_OS_WINRT
   39771   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
   39772 #else
   39773   { "GetTickCount64",          (SYSCALL)0,                       0 },
   39774 #endif
   39775 
   39776 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
   39777 
   39778 #if SQLITE_OS_WINRT
   39779   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
   39780 #else
   39781   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
   39782 #endif
   39783 
   39784 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
   39785         LPSYSTEM_INFO))aSyscall[71].pCurrent)
   39786 
   39787 #if defined(SQLITE_WIN32_HAS_ANSI)
   39788   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
   39789 #else
   39790   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
   39791 #endif
   39792 
   39793 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
   39794 
   39795 #if defined(SQLITE_WIN32_HAS_WIDE)
   39796   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
   39797 #else
   39798   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
   39799 #endif
   39800 
   39801 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
   39802 
   39803   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
   39804 
   39805 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
   39806 
   39807 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
   39808   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
   39809 #else
   39810   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
   39811 #endif
   39812 
   39813 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
   39814         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
   39815 
   39816 /*
   39817 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
   39818 **       is really just a macro that uses a compiler intrinsic (e.g. x64).
   39819 **       So do not try to make this is into a redefinable interface.
   39820 */
   39821 #if defined(InterlockedCompareExchange)
   39822   { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
   39823 
   39824 #define osInterlockedCompareExchange InterlockedCompareExchange
   39825 #else
   39826   { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
   39827 
   39828 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
   39829         SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
   39830 #endif /* defined(InterlockedCompareExchange) */
   39831 
   39832 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
   39833   { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
   39834 #else
   39835   { "UuidCreate",               (SYSCALL)0,                      0 },
   39836 #endif
   39837 
   39838 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
   39839 
   39840 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
   39841   { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
   39842 #else
   39843   { "UuidCreateSequential",     (SYSCALL)0,                      0 },
   39844 #endif
   39845 
   39846 #define osUuidCreateSequential \
   39847         ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
   39848 
   39849 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
   39850   { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
   39851 #else
   39852   { "FlushViewOfFile",          (SYSCALL)0,                      0 },
   39853 #endif
   39854 
   39855 #define osFlushViewOfFile \
   39856         ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
   39857 
   39858 }; /* End of the overrideable system calls */
   39859 
   39860 /*
   39861 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   39862 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
   39863 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   39864 ** system call named zName.
   39865 */
   39866 static int winSetSystemCall(
   39867   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   39868   const char *zName,            /* Name of system call to override */
   39869   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   39870 ){
   39871   unsigned int i;
   39872   int rc = SQLITE_NOTFOUND;
   39873 
   39874   UNUSED_PARAMETER(pNotUsed);
   39875   if( zName==0 ){
   39876     /* If no zName is given, restore all system calls to their default
   39877     ** settings and return NULL
   39878     */
   39879     rc = SQLITE_OK;
   39880     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   39881       if( aSyscall[i].pDefault ){
   39882         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   39883       }
   39884     }
   39885   }else{
   39886     /* If zName is specified, operate on only the one system call
   39887     ** specified.
   39888     */
   39889     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   39890       if( strcmp(zName, aSyscall[i].zName)==0 ){
   39891         if( aSyscall[i].pDefault==0 ){
   39892           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   39893         }
   39894         rc = SQLITE_OK;
   39895         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   39896         aSyscall[i].pCurrent = pNewFunc;
   39897         break;
   39898       }
   39899     }
   39900   }
   39901   return rc;
   39902 }
   39903 
   39904 /*
   39905 ** Return the value of a system call.  Return NULL if zName is not a
   39906 ** recognized system call name.  NULL is also returned if the system call
   39907 ** is currently undefined.
   39908 */
   39909 static sqlite3_syscall_ptr winGetSystemCall(
   39910   sqlite3_vfs *pNotUsed,
   39911   const char *zName
   39912 ){
   39913   unsigned int i;
   39914 
   39915   UNUSED_PARAMETER(pNotUsed);
   39916   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   39917     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   39918   }
   39919   return 0;
   39920 }
   39921 
   39922 /*
   39923 ** Return the name of the first system call after zName.  If zName==NULL
   39924 ** then return the name of the first system call.  Return NULL if zName
   39925 ** is the last system call or if zName is not the name of a valid
   39926 ** system call.
   39927 */
   39928 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
   39929   int i = -1;
   39930 
   39931   UNUSED_PARAMETER(p);
   39932   if( zName ){
   39933     for(i=0; i<ArraySize(aSyscall)-1; i++){
   39934       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   39935     }
   39936   }
   39937   for(i++; i<ArraySize(aSyscall); i++){
   39938     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   39939   }
   39940   return 0;
   39941 }
   39942 
   39943 #ifdef SQLITE_WIN32_MALLOC
   39944 /*
   39945 ** If a Win32 native heap has been configured, this function will attempt to
   39946 ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
   39947 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
   39948 ** "pnLargest" argument, if non-zero, will be used to return the size of the
   39949 ** largest committed free block in the heap, in bytes.
   39950 */
   39951 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
   39952   int rc = SQLITE_OK;
   39953   UINT nLargest = 0;
   39954   HANDLE hHeap;
   39955 
   39956   winMemAssertMagic();
   39957   hHeap = winMemGetHeap();
   39958   assert( hHeap!=0 );
   39959   assert( hHeap!=INVALID_HANDLE_VALUE );
   39960 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   39961   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   39962 #endif
   39963 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
   39964   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
   39965     DWORD lastErrno = osGetLastError();
   39966     if( lastErrno==NO_ERROR ){
   39967       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
   39968                   (void*)hHeap);
   39969       rc = SQLITE_NOMEM_BKPT;
   39970     }else{
   39971       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
   39972                   osGetLastError(), (void*)hHeap);
   39973       rc = SQLITE_ERROR;
   39974     }
   39975   }
   39976 #else
   39977   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
   39978               (void*)hHeap);
   39979   rc = SQLITE_NOTFOUND;
   39980 #endif
   39981   if( pnLargest ) *pnLargest = nLargest;
   39982   return rc;
   39983 }
   39984 
   39985 /*
   39986 ** If a Win32 native heap has been configured, this function will attempt to
   39987 ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
   39988 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
   39989 ** be returned and no changes will be made to the Win32 native heap.
   39990 */
   39991 SQLITE_API int sqlite3_win32_reset_heap(){
   39992   int rc;
   39993   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
   39994   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
   39995   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   39996   MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
   39997   sqlite3_mutex_enter(pMaster);
   39998   sqlite3_mutex_enter(pMem);
   39999   winMemAssertMagic();
   40000   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
   40001     /*
   40002     ** At this point, there should be no outstanding memory allocations on
   40003     ** the heap.  Also, since both the master and memsys locks are currently
   40004     ** being held by us, no other function (i.e. from another thread) should
   40005     ** be able to even access the heap.  Attempt to destroy and recreate our
   40006     ** isolated Win32 native heap now.
   40007     */
   40008     assert( winMemGetHeap()!=NULL );
   40009     assert( winMemGetOwned() );
   40010     assert( sqlite3_memory_used()==0 );
   40011     winMemShutdown(winMemGetDataPtr());
   40012     assert( winMemGetHeap()==NULL );
   40013     assert( !winMemGetOwned() );
   40014     assert( sqlite3_memory_used()==0 );
   40015     rc = winMemInit(winMemGetDataPtr());
   40016     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
   40017     assert( rc!=SQLITE_OK || winMemGetOwned() );
   40018     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
   40019   }else{
   40020     /*
   40021     ** The Win32 native heap cannot be modified because it may be in use.
   40022     */
   40023     rc = SQLITE_BUSY;
   40024   }
   40025   sqlite3_mutex_leave(pMem);
   40026   sqlite3_mutex_leave(pMaster);
   40027   return rc;
   40028 }
   40029 #endif /* SQLITE_WIN32_MALLOC */
   40030 
   40031 /*
   40032 ** This function outputs the specified (ANSI) string to the Win32 debugger
   40033 ** (if available).
   40034 */
   40035 
   40036 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
   40037   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
   40038   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
   40039   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
   40040   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
   40041 #ifdef SQLITE_ENABLE_API_ARMOR
   40042   if( !zBuf ){
   40043     (void)SQLITE_MISUSE_BKPT;
   40044     return;
   40045   }
   40046 #endif
   40047 #if defined(SQLITE_WIN32_HAS_ANSI)
   40048   if( nMin>0 ){
   40049     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   40050     memcpy(zDbgBuf, zBuf, nMin);
   40051     osOutputDebugStringA(zDbgBuf);
   40052   }else{
   40053     osOutputDebugStringA(zBuf);
   40054   }
   40055 #elif defined(SQLITE_WIN32_HAS_WIDE)
   40056   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   40057   if ( osMultiByteToWideChar(
   40058           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
   40059           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
   40060     return;
   40061   }
   40062   osOutputDebugStringW((LPCWSTR)zDbgBuf);
   40063 #else
   40064   if( nMin>0 ){
   40065     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
   40066     memcpy(zDbgBuf, zBuf, nMin);
   40067     fprintf(stderr, "%s", zDbgBuf);
   40068   }else{
   40069     fprintf(stderr, "%s", zBuf);
   40070   }
   40071 #endif
   40072 }
   40073 
   40074 /*
   40075 ** The following routine suspends the current thread for at least ms
   40076 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
   40077 */
   40078 #if SQLITE_OS_WINRT
   40079 static HANDLE sleepObj = NULL;
   40080 #endif
   40081 
   40082 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
   40083 #if SQLITE_OS_WINRT
   40084   if ( sleepObj==NULL ){
   40085     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
   40086                                 SYNCHRONIZE);
   40087   }
   40088   assert( sleepObj!=NULL );
   40089   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
   40090 #else
   40091   osSleep(milliseconds);
   40092 #endif
   40093 }
   40094 
   40095 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
   40096         SQLITE_THREADSAFE>0
   40097 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
   40098   DWORD rc;
   40099   while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
   40100                                        TRUE))==WAIT_IO_COMPLETION ){}
   40101   return rc;
   40102 }
   40103 #endif
   40104 
   40105 /*
   40106 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   40107 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   40108 **
   40109 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   40110 ** the LockFileEx() API.  But we can still statically link against that
   40111 ** API as long as we don't call it when running Win95/98/ME.  A call to
   40112 ** this routine is used to determine if the host is Win95/98/ME or
   40113 ** WinNT/2K/XP so that we will know whether or not we can safely call
   40114 ** the LockFileEx() API.
   40115 */
   40116 
   40117 #if !SQLITE_WIN32_GETVERSIONEX
   40118 # define osIsNT()  (1)
   40119 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
   40120 # define osIsNT()  (1)
   40121 #elif !defined(SQLITE_WIN32_HAS_WIDE)
   40122 # define osIsNT()  (0)
   40123 #else
   40124 # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
   40125 #endif
   40126 
   40127 /*
   40128 ** This function determines if the machine is running a version of Windows
   40129 ** based on the NT kernel.
   40130 */
   40131 SQLITE_API int sqlite3_win32_is_nt(void){
   40132 #if SQLITE_OS_WINRT
   40133   /*
   40134   ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
   40135   **       kernel.
   40136   */
   40137   return 1;
   40138 #elif SQLITE_WIN32_GETVERSIONEX
   40139   if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
   40140 #if defined(SQLITE_WIN32_HAS_ANSI)
   40141     OSVERSIONINFOA sInfo;
   40142     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   40143     osGetVersionExA(&sInfo);
   40144     osInterlockedCompareExchange(&sqlite3_os_type,
   40145         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
   40146 #elif defined(SQLITE_WIN32_HAS_WIDE)
   40147     OSVERSIONINFOW sInfo;
   40148     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   40149     osGetVersionExW(&sInfo);
   40150     osInterlockedCompareExchange(&sqlite3_os_type,
   40151         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
   40152 #endif
   40153   }
   40154   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
   40155 #elif SQLITE_TEST
   40156   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
   40157 #else
   40158   /*
   40159   ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
   40160   **       deprecated are always assumed to be based on the NT kernel.
   40161   */
   40162   return 1;
   40163 #endif
   40164 }
   40165 
   40166 #ifdef SQLITE_WIN32_MALLOC
   40167 /*
   40168 ** Allocate nBytes of memory.
   40169 */
   40170 static void *winMemMalloc(int nBytes){
   40171   HANDLE hHeap;
   40172   void *p;
   40173 
   40174   winMemAssertMagic();
   40175   hHeap = winMemGetHeap();
   40176   assert( hHeap!=0 );
   40177   assert( hHeap!=INVALID_HANDLE_VALUE );
   40178 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   40179   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   40180 #endif
   40181   assert( nBytes>=0 );
   40182   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   40183   if( !p ){
   40184     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
   40185                 nBytes, osGetLastError(), (void*)hHeap);
   40186   }
   40187   return p;
   40188 }
   40189 
   40190 /*
   40191 ** Free memory.
   40192 */
   40193 static void winMemFree(void *pPrior){
   40194   HANDLE hHeap;
   40195 
   40196   winMemAssertMagic();
   40197   hHeap = winMemGetHeap();
   40198   assert( hHeap!=0 );
   40199   assert( hHeap!=INVALID_HANDLE_VALUE );
   40200 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   40201   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   40202 #endif
   40203   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
   40204   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
   40205     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
   40206                 pPrior, osGetLastError(), (void*)hHeap);
   40207   }
   40208 }
   40209 
   40210 /*
   40211 ** Change the size of an existing memory allocation
   40212 */
   40213 static void *winMemRealloc(void *pPrior, int nBytes){
   40214   HANDLE hHeap;
   40215   void *p;
   40216 
   40217   winMemAssertMagic();
   40218   hHeap = winMemGetHeap();
   40219   assert( hHeap!=0 );
   40220   assert( hHeap!=INVALID_HANDLE_VALUE );
   40221 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   40222   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   40223 #endif
   40224   assert( nBytes>=0 );
   40225   if( !pPrior ){
   40226     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   40227   }else{
   40228     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
   40229   }
   40230   if( !p ){
   40231     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
   40232                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
   40233                 (void*)hHeap);
   40234   }
   40235   return p;
   40236 }
   40237 
   40238 /*
   40239 ** Return the size of an outstanding allocation, in bytes.
   40240 */
   40241 static int winMemSize(void *p){
   40242   HANDLE hHeap;
   40243   SIZE_T n;
   40244 
   40245   winMemAssertMagic();
   40246   hHeap = winMemGetHeap();
   40247   assert( hHeap!=0 );
   40248   assert( hHeap!=INVALID_HANDLE_VALUE );
   40249 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   40250   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
   40251 #endif
   40252   if( !p ) return 0;
   40253   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
   40254   if( n==(SIZE_T)-1 ){
   40255     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
   40256                 p, osGetLastError(), (void*)hHeap);
   40257     return 0;
   40258   }
   40259   return (int)n;
   40260 }
   40261 
   40262 /*
   40263 ** Round up a request size to the next valid allocation size.
   40264 */
   40265 static int winMemRoundup(int n){
   40266   return n;
   40267 }
   40268 
   40269 /*
   40270 ** Initialize this module.
   40271 */
   40272 static int winMemInit(void *pAppData){
   40273   winMemData *pWinMemData = (winMemData *)pAppData;
   40274 
   40275   if( !pWinMemData ) return SQLITE_ERROR;
   40276   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
   40277   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
   40278 
   40279 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
   40280   if( !pWinMemData->hHeap ){
   40281     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
   40282     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
   40283     if( dwMaximumSize==0 ){
   40284       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
   40285     }else if( dwInitialSize>dwMaximumSize ){
   40286       dwInitialSize = dwMaximumSize;
   40287     }
   40288     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
   40289                                       dwInitialSize, dwMaximumSize);
   40290     if( !pWinMemData->hHeap ){
   40291       sqlite3_log(SQLITE_NOMEM,
   40292           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
   40293           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
   40294           dwMaximumSize);
   40295       return SQLITE_NOMEM_BKPT;
   40296     }
   40297     pWinMemData->bOwned = TRUE;
   40298     assert( pWinMemData->bOwned );
   40299   }
   40300 #else
   40301   pWinMemData->hHeap = osGetProcessHeap();
   40302   if( !pWinMemData->hHeap ){
   40303     sqlite3_log(SQLITE_NOMEM,
   40304         "failed to GetProcessHeap (%lu)", osGetLastError());
   40305     return SQLITE_NOMEM_BKPT;
   40306   }
   40307   pWinMemData->bOwned = FALSE;
   40308   assert( !pWinMemData->bOwned );
   40309 #endif
   40310   assert( pWinMemData->hHeap!=0 );
   40311   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   40312 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   40313   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   40314 #endif
   40315   return SQLITE_OK;
   40316 }
   40317 
   40318 /*
   40319 ** Deinitialize this module.
   40320 */
   40321 static void winMemShutdown(void *pAppData){
   40322   winMemData *pWinMemData = (winMemData *)pAppData;
   40323 
   40324   if( !pWinMemData ) return;
   40325   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
   40326   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
   40327 
   40328   if( pWinMemData->hHeap ){
   40329     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   40330 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
   40331     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   40332 #endif
   40333     if( pWinMemData->bOwned ){
   40334       if( !osHeapDestroy(pWinMemData->hHeap) ){
   40335         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
   40336                     osGetLastError(), (void*)pWinMemData->hHeap);
   40337       }
   40338       pWinMemData->bOwned = FALSE;
   40339     }
   40340     pWinMemData->hHeap = NULL;
   40341   }
   40342 }
   40343 
   40344 /*
   40345 ** Populate the low-level memory allocation function pointers in
   40346 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   40347 ** arguments specify the block of memory to manage.
   40348 **
   40349 ** This routine is only called by sqlite3_config(), and therefore
   40350 ** is not required to be threadsafe (it is not).
   40351 */
   40352 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
   40353   static const sqlite3_mem_methods winMemMethods = {
   40354     winMemMalloc,
   40355     winMemFree,
   40356     winMemRealloc,
   40357     winMemSize,
   40358     winMemRoundup,
   40359     winMemInit,
   40360     winMemShutdown,
   40361     &win_mem_data
   40362   };
   40363   return &winMemMethods;
   40364 }
   40365 
   40366 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   40367   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
   40368 }
   40369 #endif /* SQLITE_WIN32_MALLOC */
   40370 
   40371 /*
   40372 ** Convert a UTF-8 string to Microsoft Unicode.
   40373 **
   40374 ** Space to hold the returned string is obtained from sqlite3_malloc().
   40375 */
   40376 static LPWSTR winUtf8ToUnicode(const char *zText){
   40377   int nChar;
   40378   LPWSTR zWideText;
   40379 
   40380   nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
   40381   if( nChar==0 ){
   40382     return 0;
   40383   }
   40384   zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
   40385   if( zWideText==0 ){
   40386     return 0;
   40387   }
   40388   nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
   40389                                 nChar);
   40390   if( nChar==0 ){
   40391     sqlite3_free(zWideText);
   40392     zWideText = 0;
   40393   }
   40394   return zWideText;
   40395 }
   40396 
   40397 /*
   40398 ** Convert a Microsoft Unicode string to UTF-8.
   40399 **
   40400 ** Space to hold the returned string is obtained from sqlite3_malloc().
   40401 */
   40402 static char *winUnicodeToUtf8(LPCWSTR zWideText){
   40403   int nByte;
   40404   char *zText;
   40405 
   40406   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
   40407   if( nByte == 0 ){
   40408     return 0;
   40409   }
   40410   zText = sqlite3MallocZero( nByte );
   40411   if( zText==0 ){
   40412     return 0;
   40413   }
   40414   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
   40415                                 0, 0);
   40416   if( nByte == 0 ){
   40417     sqlite3_free(zText);
   40418     zText = 0;
   40419   }
   40420   return zText;
   40421 }
   40422 
   40423 /*
   40424 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
   40425 ** code page.
   40426 **
   40427 ** Space to hold the returned string is obtained from sqlite3_malloc().
   40428 */
   40429 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
   40430   int nByte;
   40431   LPWSTR zMbcsText;
   40432   int codepage = useAnsi ? CP_ACP : CP_OEMCP;
   40433 
   40434   nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
   40435                                 0)*sizeof(WCHAR);
   40436   if( nByte==0 ){
   40437     return 0;
   40438   }
   40439   zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
   40440   if( zMbcsText==0 ){
   40441     return 0;
   40442   }
   40443   nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
   40444                                 nByte);
   40445   if( nByte==0 ){
   40446     sqlite3_free(zMbcsText);
   40447     zMbcsText = 0;
   40448   }
   40449   return zMbcsText;
   40450 }
   40451 
   40452 /*
   40453 ** Convert a Microsoft Unicode string to a multi-byte character string,
   40454 ** using the ANSI or OEM code page.
   40455 **
   40456 ** Space to hold the returned string is obtained from sqlite3_malloc().
   40457 */
   40458 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
   40459   int nByte;
   40460   char *zText;
   40461   int codepage = useAnsi ? CP_ACP : CP_OEMCP;
   40462 
   40463   nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
   40464   if( nByte == 0 ){
   40465     return 0;
   40466   }
   40467   zText = sqlite3MallocZero( nByte );
   40468   if( zText==0 ){
   40469     return 0;
   40470   }
   40471   nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
   40472                                 nByte, 0, 0);
   40473   if( nByte == 0 ){
   40474     sqlite3_free(zText);
   40475     zText = 0;
   40476   }
   40477   return zText;
   40478 }
   40479 
   40480 /*
   40481 ** Convert a multi-byte character string to UTF-8.
   40482 **
   40483 ** Space to hold the returned string is obtained from sqlite3_malloc().
   40484 */
   40485 static char *winMbcsToUtf8(const char *zText, int useAnsi){
   40486   char *zTextUtf8;
   40487   LPWSTR zTmpWide;
   40488 
   40489   zTmpWide = winMbcsToUnicode(zText, useAnsi);
   40490   if( zTmpWide==0 ){
   40491     return 0;
   40492   }
   40493   zTextUtf8 = winUnicodeToUtf8(zTmpWide);
   40494   sqlite3_free(zTmpWide);
   40495   return zTextUtf8;
   40496 }
   40497 
   40498 /*
   40499 ** Convert a UTF-8 string to a multi-byte character string.
   40500 **
   40501 ** Space to hold the returned string is obtained from sqlite3_malloc().
   40502 */
   40503 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
   40504   char *zTextMbcs;
   40505   LPWSTR zTmpWide;
   40506 
   40507   zTmpWide = winUtf8ToUnicode(zText);
   40508   if( zTmpWide==0 ){
   40509     return 0;
   40510   }
   40511   zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
   40512   sqlite3_free(zTmpWide);
   40513   return zTextMbcs;
   40514 }
   40515 
   40516 /*
   40517 ** This is a public wrapper for the winUtf8ToUnicode() function.
   40518 */
   40519 SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
   40520 #ifdef SQLITE_ENABLE_API_ARMOR
   40521   if( !zText ){
   40522     (void)SQLITE_MISUSE_BKPT;
   40523     return 0;
   40524   }
   40525 #endif
   40526 #ifndef SQLITE_OMIT_AUTOINIT
   40527   if( sqlite3_initialize() ) return 0;
   40528 #endif
   40529   return winUtf8ToUnicode(zText);
   40530 }
   40531 
   40532 /*
   40533 ** This is a public wrapper for the winUnicodeToUtf8() function.
   40534 */
   40535 SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
   40536 #ifdef SQLITE_ENABLE_API_ARMOR
   40537   if( !zWideText ){
   40538     (void)SQLITE_MISUSE_BKPT;
   40539     return 0;
   40540   }
   40541 #endif
   40542 #ifndef SQLITE_OMIT_AUTOINIT
   40543   if( sqlite3_initialize() ) return 0;
   40544 #endif
   40545   return winUnicodeToUtf8(zWideText);
   40546 }
   40547 
   40548 /*
   40549 ** This is a public wrapper for the winMbcsToUtf8() function.
   40550 */
   40551 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
   40552 #ifdef SQLITE_ENABLE_API_ARMOR
   40553   if( !zText ){
   40554     (void)SQLITE_MISUSE_BKPT;
   40555     return 0;
   40556   }
   40557 #endif
   40558 #ifndef SQLITE_OMIT_AUTOINIT
   40559   if( sqlite3_initialize() ) return 0;
   40560 #endif
   40561   return winMbcsToUtf8(zText, osAreFileApisANSI());
   40562 }
   40563 
   40564 /*
   40565 ** This is a public wrapper for the winMbcsToUtf8() function.
   40566 */
   40567 SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
   40568 #ifdef SQLITE_ENABLE_API_ARMOR
   40569   if( !zText ){
   40570     (void)SQLITE_MISUSE_BKPT;
   40571     return 0;
   40572   }
   40573 #endif
   40574 #ifndef SQLITE_OMIT_AUTOINIT
   40575   if( sqlite3_initialize() ) return 0;
   40576 #endif
   40577   return winMbcsToUtf8(zText, useAnsi);
   40578 }
   40579 
   40580 /*
   40581 ** This is a public wrapper for the winUtf8ToMbcs() function.
   40582 */
   40583 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
   40584 #ifdef SQLITE_ENABLE_API_ARMOR
   40585   if( !zText ){
   40586     (void)SQLITE_MISUSE_BKPT;
   40587     return 0;
   40588   }
   40589 #endif
   40590 #ifndef SQLITE_OMIT_AUTOINIT
   40591   if( sqlite3_initialize() ) return 0;
   40592 #endif
   40593   return winUtf8ToMbcs(zText, osAreFileApisANSI());
   40594 }
   40595 
   40596 /*
   40597 ** This is a public wrapper for the winUtf8ToMbcs() function.
   40598 */
   40599 SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
   40600 #ifdef SQLITE_ENABLE_API_ARMOR
   40601   if( !zText ){
   40602     (void)SQLITE_MISUSE_BKPT;
   40603     return 0;
   40604   }
   40605 #endif
   40606 #ifndef SQLITE_OMIT_AUTOINIT
   40607   if( sqlite3_initialize() ) return 0;
   40608 #endif
   40609   return winUtf8ToMbcs(zText, useAnsi);
   40610 }
   40611 
   40612 /*
   40613 ** This function sets the data directory or the temporary directory based on
   40614 ** the provided arguments.  The type argument must be 1 in order to set the
   40615 ** data directory or 2 in order to set the temporary directory.  The zValue
   40616 ** argument is the name of the directory to use.  The return value will be
   40617 ** SQLITE_OK if successful.
   40618 */
   40619 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
   40620   char **ppDirectory = 0;
   40621 #ifndef SQLITE_OMIT_AUTOINIT
   40622   int rc = sqlite3_initialize();
   40623   if( rc ) return rc;
   40624 #endif
   40625   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
   40626     ppDirectory = &sqlite3_data_directory;
   40627   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
   40628     ppDirectory = &sqlite3_temp_directory;
   40629   }
   40630   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
   40631           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
   40632   );
   40633   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
   40634   if( ppDirectory ){
   40635     char *zValueUtf8 = 0;
   40636     if( zValue && zValue[0] ){
   40637       zValueUtf8 = winUnicodeToUtf8(zValue);
   40638       if ( zValueUtf8==0 ){
   40639         return SQLITE_NOMEM_BKPT;
   40640       }
   40641     }
   40642     sqlite3_free(*ppDirectory);
   40643     *ppDirectory = zValueUtf8;
   40644     return SQLITE_OK;
   40645   }
   40646   return SQLITE_ERROR;
   40647 }
   40648 
   40649 /*
   40650 ** The return value of winGetLastErrorMsg
   40651 ** is zero if the error message fits in the buffer, or non-zero
   40652 ** otherwise (if the message was truncated).
   40653 */
   40654 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
   40655   /* FormatMessage returns 0 on failure.  Otherwise it
   40656   ** returns the number of TCHARs written to the output
   40657   ** buffer, excluding the terminating null char.
   40658   */
   40659   DWORD dwLen = 0;
   40660   char *zOut = 0;
   40661 
   40662   if( osIsNT() ){
   40663 #if SQLITE_OS_WINRT
   40664     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
   40665     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
   40666                              FORMAT_MESSAGE_IGNORE_INSERTS,
   40667                              NULL,
   40668                              lastErrno,
   40669                              0,
   40670                              zTempWide,
   40671                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
   40672                              0);
   40673 #else
   40674     LPWSTR zTempWide = NULL;
   40675     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   40676                              FORMAT_MESSAGE_FROM_SYSTEM |
   40677                              FORMAT_MESSAGE_IGNORE_INSERTS,
   40678                              NULL,
   40679                              lastErrno,
   40680                              0,
   40681                              (LPWSTR) &zTempWide,
   40682                              0,
   40683                              0);
   40684 #endif
   40685     if( dwLen > 0 ){
   40686       /* allocate a buffer and convert to UTF8 */
   40687       sqlite3BeginBenignMalloc();
   40688       zOut = winUnicodeToUtf8(zTempWide);
   40689       sqlite3EndBenignMalloc();
   40690 #if !SQLITE_OS_WINRT
   40691       /* free the system buffer allocated by FormatMessage */
   40692       osLocalFree(zTempWide);
   40693 #endif
   40694     }
   40695   }
   40696 #ifdef SQLITE_WIN32_HAS_ANSI
   40697   else{
   40698     char *zTemp = NULL;
   40699     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   40700                              FORMAT_MESSAGE_FROM_SYSTEM |
   40701                              FORMAT_MESSAGE_IGNORE_INSERTS,
   40702                              NULL,
   40703                              lastErrno,
   40704                              0,
   40705                              (LPSTR) &zTemp,
   40706                              0,
   40707                              0);
   40708     if( dwLen > 0 ){
   40709       /* allocate a buffer and convert to UTF8 */
   40710       sqlite3BeginBenignMalloc();
   40711       zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
   40712       sqlite3EndBenignMalloc();
   40713       /* free the system buffer allocated by FormatMessage */
   40714       osLocalFree(zTemp);
   40715     }
   40716   }
   40717 #endif
   40718   if( 0 == dwLen ){
   40719     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
   40720   }else{
   40721     /* copy a maximum of nBuf chars to output buffer */
   40722     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   40723     /* free the UTF8 buffer */
   40724     sqlite3_free(zOut);
   40725   }
   40726   return 0;
   40727 }
   40728 
   40729 /*
   40730 **
   40731 ** This function - winLogErrorAtLine() - is only ever called via the macro
   40732 ** winLogError().
   40733 **
   40734 ** This routine is invoked after an error occurs in an OS function.
   40735 ** It logs a message using sqlite3_log() containing the current value of
   40736 ** error code and, if possible, the human-readable equivalent from
   40737 ** FormatMessage.
   40738 **
   40739 ** The first argument passed to the macro should be the error code that
   40740 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   40741 ** The two subsequent arguments should be the name of the OS function that
   40742 ** failed and the associated file-system path, if any.
   40743 */
   40744 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
   40745 static int winLogErrorAtLine(
   40746   int errcode,                    /* SQLite error code */
   40747   DWORD lastErrno,                /* Win32 last error */
   40748   const char *zFunc,              /* Name of OS function that failed */
   40749   const char *zPath,              /* File path associated with error */
   40750   int iLine                       /* Source line number where error occurred */
   40751 ){
   40752   char zMsg[500];                 /* Human readable error text */
   40753   int i;                          /* Loop counter */
   40754 
   40755   zMsg[0] = 0;
   40756   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
   40757   assert( errcode!=SQLITE_OK );
   40758   if( zPath==0 ) zPath = "";
   40759   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
   40760   zMsg[i] = 0;
   40761   sqlite3_log(errcode,
   40762       "os_win.c:%d: (%lu) %s(%s) - %s",
   40763       iLine, lastErrno, zFunc, zPath, zMsg
   40764   );
   40765 
   40766   return errcode;
   40767 }
   40768 
   40769 /*
   40770 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
   40771 ** will be retried following a locking error - probably caused by
   40772 ** antivirus software.  Also the initial delay before the first retry.
   40773 ** The delay increases linearly with each retry.
   40774 */
   40775 #ifndef SQLITE_WIN32_IOERR_RETRY
   40776 # define SQLITE_WIN32_IOERR_RETRY 10
   40777 #endif
   40778 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
   40779 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
   40780 #endif
   40781 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
   40782 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
   40783 
   40784 /*
   40785 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
   40786 ** error code obtained via GetLastError() is eligible to be retried.  It
   40787 ** must accept the error code DWORD as its only argument and should return
   40788 ** non-zero if the error code is transient in nature and the operation
   40789 ** responsible for generating the original error might succeed upon being
   40790 ** retried.  The argument to this macro should be a variable.
   40791 **
   40792 ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
   40793 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
   40794 ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
   40795 ** may be used to include additional error codes in the set that should
   40796 ** result in the failing I/O operation being retried by the caller.  If
   40797 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
   40798 ** identical to those of the "winIoerrCanRetry1" macro.
   40799 */
   40800 #if !defined(winIoerrCanRetry1)
   40801 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
   40802                               ((a)==ERROR_SHARING_VIOLATION)    || \
   40803                               ((a)==ERROR_LOCK_VIOLATION)       || \
   40804                               ((a)==ERROR_DEV_NOT_EXIST)        || \
   40805                               ((a)==ERROR_NETNAME_DELETED)      || \
   40806                               ((a)==ERROR_SEM_TIMEOUT)          || \
   40807                               ((a)==ERROR_NETWORK_UNREACHABLE))
   40808 #endif
   40809 
   40810 /*
   40811 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
   40812 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
   40813 ** to give up with an error.
   40814 */
   40815 static int winRetryIoerr(int *pnRetry, DWORD *pError){
   40816   DWORD e = osGetLastError();
   40817   if( *pnRetry>=winIoerrRetry ){
   40818     if( pError ){
   40819       *pError = e;
   40820     }
   40821     return 0;
   40822   }
   40823   if( winIoerrCanRetry1(e) ){
   40824     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
   40825     ++*pnRetry;
   40826     return 1;
   40827   }
   40828 #if defined(winIoerrCanRetry2)
   40829   else if( winIoerrCanRetry2(e) ){
   40830     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
   40831     ++*pnRetry;
   40832     return 1;
   40833   }
   40834 #endif
   40835   if( pError ){
   40836     *pError = e;
   40837   }
   40838   return 0;
   40839 }
   40840 
   40841 /*
   40842 ** Log a I/O error retry episode.
   40843 */
   40844 static void winLogIoerr(int nRetry, int lineno){
   40845   if( nRetry ){
   40846     sqlite3_log(SQLITE_NOTICE,
   40847       "delayed %dms for lock/sharing conflict at line %d",
   40848       winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
   40849     );
   40850   }
   40851 }
   40852 
   40853 /*
   40854 ** This #if does not rely on the SQLITE_OS_WINCE define because the
   40855 ** corresponding section in "date.c" cannot use it.
   40856 */
   40857 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
   40858     (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
   40859 /*
   40860 ** The MSVC CRT on Windows CE may not have a localtime() function.
   40861 ** So define a substitute.
   40862 */
   40863 /* #  include <time.h> */
   40864 struct tm *__cdecl localtime(const time_t *t)
   40865 {
   40866   static struct tm y;
   40867   FILETIME uTm, lTm;
   40868   SYSTEMTIME pTm;
   40869   sqlite3_int64 t64;
   40870   t64 = *t;
   40871   t64 = (t64 + 11644473600)*10000000;
   40872   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   40873   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   40874   osFileTimeToLocalFileTime(&uTm,&lTm);
   40875   osFileTimeToSystemTime(&lTm,&pTm);
   40876   y.tm_year = pTm.wYear - 1900;
   40877   y.tm_mon = pTm.wMonth - 1;
   40878   y.tm_wday = pTm.wDayOfWeek;
   40879   y.tm_mday = pTm.wDay;
   40880   y.tm_hour = pTm.wHour;
   40881   y.tm_min = pTm.wMinute;
   40882   y.tm_sec = pTm.wSecond;
   40883   return &y;
   40884 }
   40885 #endif
   40886 
   40887 #if SQLITE_OS_WINCE
   40888 /*************************************************************************
   40889 ** This section contains code for WinCE only.
   40890 */
   40891 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   40892 
   40893 /*
   40894 ** Acquire a lock on the handle h
   40895 */
   40896 static void winceMutexAcquire(HANDLE h){
   40897    DWORD dwErr;
   40898    do {
   40899      dwErr = osWaitForSingleObject(h, INFINITE);
   40900    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
   40901 }
   40902 /*
   40903 ** Release a lock acquired by winceMutexAcquire()
   40904 */
   40905 #define winceMutexRelease(h) ReleaseMutex(h)
   40906 
   40907 /*
   40908 ** Create the mutex and shared memory used for locking in the file
   40909 ** descriptor pFile
   40910 */
   40911 static int winceCreateLock(const char *zFilename, winFile *pFile){
   40912   LPWSTR zTok;
   40913   LPWSTR zName;
   40914   DWORD lastErrno;
   40915   BOOL bLogged = FALSE;
   40916   BOOL bInit = TRUE;
   40917 
   40918   zName = winUtf8ToUnicode(zFilename);
   40919   if( zName==0 ){
   40920     /* out of memory */
   40921     return SQLITE_IOERR_NOMEM_BKPT;
   40922   }
   40923 
   40924   /* Initialize the local lockdata */
   40925   memset(&pFile->local, 0, sizeof(pFile->local));
   40926 
   40927   /* Replace the backslashes from the filename and lowercase it
   40928   ** to derive a mutex name. */
   40929   zTok = osCharLowerW(zName);
   40930   for (;*zTok;zTok++){
   40931     if (*zTok == '\\') *zTok = '_';
   40932   }
   40933 
   40934   /* Create/open the named mutex */
   40935   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
   40936   if (!pFile->hMutex){
   40937     pFile->lastErrno = osGetLastError();
   40938     sqlite3_free(zName);
   40939     return winLogError(SQLITE_IOERR, pFile->lastErrno,
   40940                        "winceCreateLock1", zFilename);
   40941   }
   40942 
   40943   /* Acquire the mutex before continuing */
   40944   winceMutexAcquire(pFile->hMutex);
   40945 
   40946   /* Since the names of named mutexes, semaphores, file mappings etc are
   40947   ** case-sensitive, take advantage of that by uppercasing the mutex name
   40948   ** and using that as the shared filemapping name.
   40949   */
   40950   osCharUpperW(zName);
   40951   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   40952                                         PAGE_READWRITE, 0, sizeof(winceLock),
   40953                                         zName);
   40954 
   40955   /* Set a flag that indicates we're the first to create the memory so it
   40956   ** must be zero-initialized */
   40957   lastErrno = osGetLastError();
   40958   if (lastErrno == ERROR_ALREADY_EXISTS){
   40959     bInit = FALSE;
   40960   }
   40961 
   40962   sqlite3_free(zName);
   40963 
   40964   /* If we succeeded in making the shared memory handle, map it. */
   40965   if( pFile->hShared ){
   40966     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
   40967              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   40968     /* If mapping failed, close the shared memory handle and erase it */
   40969     if( !pFile->shared ){
   40970       pFile->lastErrno = osGetLastError();
   40971       winLogError(SQLITE_IOERR, pFile->lastErrno,
   40972                   "winceCreateLock2", zFilename);
   40973       bLogged = TRUE;
   40974       osCloseHandle(pFile->hShared);
   40975       pFile->hShared = NULL;
   40976     }
   40977   }
   40978 
   40979   /* If shared memory could not be created, then close the mutex and fail */
   40980   if( pFile->hShared==NULL ){
   40981     if( !bLogged ){
   40982       pFile->lastErrno = lastErrno;
   40983       winLogError(SQLITE_IOERR, pFile->lastErrno,
   40984                   "winceCreateLock3", zFilename);
   40985       bLogged = TRUE;
   40986     }
   40987     winceMutexRelease(pFile->hMutex);
   40988     osCloseHandle(pFile->hMutex);
   40989     pFile->hMutex = NULL;
   40990     return SQLITE_IOERR;
   40991   }
   40992 
   40993   /* Initialize the shared memory if we're supposed to */
   40994   if( bInit ){
   40995     memset(pFile->shared, 0, sizeof(winceLock));
   40996   }
   40997 
   40998   winceMutexRelease(pFile->hMutex);
   40999   return SQLITE_OK;
   41000 }
   41001 
   41002 /*
   41003 ** Destroy the part of winFile that deals with wince locks
   41004 */
   41005 static void winceDestroyLock(winFile *pFile){
   41006   if (pFile->hMutex){
   41007     /* Acquire the mutex */
   41008     winceMutexAcquire(pFile->hMutex);
   41009 
   41010     /* The following blocks should probably assert in debug mode, but they
   41011        are to cleanup in case any locks remained open */
   41012     if (pFile->local.nReaders){
   41013       pFile->shared->nReaders --;
   41014     }
   41015     if (pFile->local.bReserved){
   41016       pFile->shared->bReserved = FALSE;
   41017     }
   41018     if (pFile->local.bPending){
   41019       pFile->shared->bPending = FALSE;
   41020     }
   41021     if (pFile->local.bExclusive){
   41022       pFile->shared->bExclusive = FALSE;
   41023     }
   41024 
   41025     /* De-reference and close our copy of the shared memory handle */
   41026     osUnmapViewOfFile(pFile->shared);
   41027     osCloseHandle(pFile->hShared);
   41028 
   41029     /* Done with the mutex */
   41030     winceMutexRelease(pFile->hMutex);
   41031     osCloseHandle(pFile->hMutex);
   41032     pFile->hMutex = NULL;
   41033   }
   41034 }
   41035 
   41036 /*
   41037 ** An implementation of the LockFile() API of Windows for CE
   41038 */
   41039 static BOOL winceLockFile(
   41040   LPHANDLE phFile,
   41041   DWORD dwFileOffsetLow,
   41042   DWORD dwFileOffsetHigh,
   41043   DWORD nNumberOfBytesToLockLow,
   41044   DWORD nNumberOfBytesToLockHigh
   41045 ){
   41046   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   41047   BOOL bReturn = FALSE;
   41048 
   41049   UNUSED_PARAMETER(dwFileOffsetHigh);
   41050   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   41051 
   41052   if (!pFile->hMutex) return TRUE;
   41053   winceMutexAcquire(pFile->hMutex);
   41054 
   41055   /* Wanting an exclusive lock? */
   41056   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
   41057        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   41058     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
   41059        pFile->shared->bExclusive = TRUE;
   41060        pFile->local.bExclusive = TRUE;
   41061        bReturn = TRUE;
   41062     }
   41063   }
   41064 
   41065   /* Want a read-only lock? */
   41066   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
   41067            nNumberOfBytesToLockLow == 1){
   41068     if (pFile->shared->bExclusive == 0){
   41069       pFile->local.nReaders ++;
   41070       if (pFile->local.nReaders == 1){
   41071         pFile->shared->nReaders ++;
   41072       }
   41073       bReturn = TRUE;
   41074     }
   41075   }
   41076 
   41077   /* Want a pending lock? */
   41078   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
   41079            && nNumberOfBytesToLockLow == 1){
   41080     /* If no pending lock has been acquired, then acquire it */
   41081     if (pFile->shared->bPending == 0) {
   41082       pFile->shared->bPending = TRUE;
   41083       pFile->local.bPending = TRUE;
   41084       bReturn = TRUE;
   41085     }
   41086   }
   41087 
   41088   /* Want a reserved lock? */
   41089   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
   41090            && nNumberOfBytesToLockLow == 1){
   41091     if (pFile->shared->bReserved == 0) {
   41092       pFile->shared->bReserved = TRUE;
   41093       pFile->local.bReserved = TRUE;
   41094       bReturn = TRUE;
   41095     }
   41096   }
   41097 
   41098   winceMutexRelease(pFile->hMutex);
   41099   return bReturn;
   41100 }
   41101 
   41102 /*
   41103 ** An implementation of the UnlockFile API of Windows for CE
   41104 */
   41105 static BOOL winceUnlockFile(
   41106   LPHANDLE phFile,
   41107   DWORD dwFileOffsetLow,
   41108   DWORD dwFileOffsetHigh,
   41109   DWORD nNumberOfBytesToUnlockLow,
   41110   DWORD nNumberOfBytesToUnlockHigh
   41111 ){
   41112   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   41113   BOOL bReturn = FALSE;
   41114 
   41115   UNUSED_PARAMETER(dwFileOffsetHigh);
   41116   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
   41117 
   41118   if (!pFile->hMutex) return TRUE;
   41119   winceMutexAcquire(pFile->hMutex);
   41120 
   41121   /* Releasing a reader lock or an exclusive lock */
   41122   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
   41123     /* Did we have an exclusive lock? */
   41124     if (pFile->local.bExclusive){
   41125       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
   41126       pFile->local.bExclusive = FALSE;
   41127       pFile->shared->bExclusive = FALSE;
   41128       bReturn = TRUE;
   41129     }
   41130 
   41131     /* Did we just have a reader lock? */
   41132     else if (pFile->local.nReaders){
   41133       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
   41134              || nNumberOfBytesToUnlockLow == 1);
   41135       pFile->local.nReaders --;
   41136       if (pFile->local.nReaders == 0)
   41137       {
   41138         pFile->shared->nReaders --;
   41139       }
   41140       bReturn = TRUE;
   41141     }
   41142   }
   41143 
   41144   /* Releasing a pending lock */
   41145   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
   41146            && nNumberOfBytesToUnlockLow == 1){
   41147     if (pFile->local.bPending){
   41148       pFile->local.bPending = FALSE;
   41149       pFile->shared->bPending = FALSE;
   41150       bReturn = TRUE;
   41151     }
   41152   }
   41153   /* Releasing a reserved lock */
   41154   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
   41155            && nNumberOfBytesToUnlockLow == 1){
   41156     if (pFile->local.bReserved) {
   41157       pFile->local.bReserved = FALSE;
   41158       pFile->shared->bReserved = FALSE;
   41159       bReturn = TRUE;
   41160     }
   41161   }
   41162 
   41163   winceMutexRelease(pFile->hMutex);
   41164   return bReturn;
   41165 }
   41166 /*
   41167 ** End of the special code for wince
   41168 *****************************************************************************/
   41169 #endif /* SQLITE_OS_WINCE */
   41170 
   41171 /*
   41172 ** Lock a file region.
   41173 */
   41174 static BOOL winLockFile(
   41175   LPHANDLE phFile,
   41176   DWORD flags,
   41177   DWORD offsetLow,
   41178   DWORD offsetHigh,
   41179   DWORD numBytesLow,
   41180   DWORD numBytesHigh
   41181 ){
   41182 #if SQLITE_OS_WINCE
   41183   /*
   41184   ** NOTE: Windows CE is handled differently here due its lack of the Win32
   41185   **       API LockFile.
   41186   */
   41187   return winceLockFile(phFile, offsetLow, offsetHigh,
   41188                        numBytesLow, numBytesHigh);
   41189 #else
   41190   if( osIsNT() ){
   41191     OVERLAPPED ovlp;
   41192     memset(&ovlp, 0, sizeof(OVERLAPPED));
   41193     ovlp.Offset = offsetLow;
   41194     ovlp.OffsetHigh = offsetHigh;
   41195     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
   41196   }else{
   41197     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
   41198                       numBytesHigh);
   41199   }
   41200 #endif
   41201 }
   41202 
   41203 /*
   41204 ** Unlock a file region.
   41205  */
   41206 static BOOL winUnlockFile(
   41207   LPHANDLE phFile,
   41208   DWORD offsetLow,
   41209   DWORD offsetHigh,
   41210   DWORD numBytesLow,
   41211   DWORD numBytesHigh
   41212 ){
   41213 #if SQLITE_OS_WINCE
   41214   /*
   41215   ** NOTE: Windows CE is handled differently here due its lack of the Win32
   41216   **       API UnlockFile.
   41217   */
   41218   return winceUnlockFile(phFile, offsetLow, offsetHigh,
   41219                          numBytesLow, numBytesHigh);
   41220 #else
   41221   if( osIsNT() ){
   41222     OVERLAPPED ovlp;
   41223     memset(&ovlp, 0, sizeof(OVERLAPPED));
   41224     ovlp.Offset = offsetLow;
   41225     ovlp.OffsetHigh = offsetHigh;
   41226     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
   41227   }else{
   41228     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
   41229                         numBytesHigh);
   41230   }
   41231 #endif
   41232 }
   41233 
   41234 /*****************************************************************************
   41235 ** The next group of routines implement the I/O methods specified
   41236 ** by the sqlite3_io_methods object.
   41237 ******************************************************************************/
   41238 
   41239 /*
   41240 ** Some Microsoft compilers lack this definition.
   41241 */
   41242 #ifndef INVALID_SET_FILE_POINTER
   41243 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
   41244 #endif
   41245 
   41246 /*
   41247 ** Move the current position of the file handle passed as the first
   41248 ** argument to offset iOffset within the file. If successful, return 0.
   41249 ** Otherwise, set pFile->lastErrno and return non-zero.
   41250 */
   41251 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
   41252 #if !SQLITE_OS_WINRT
   41253   LONG upperBits;                 /* Most sig. 32 bits of new offset */
   41254   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
   41255   DWORD dwRet;                    /* Value returned by SetFilePointer() */
   41256   DWORD lastErrno;                /* Value returned by GetLastError() */
   41257 
   41258   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
   41259 
   41260   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
   41261   lowerBits = (LONG)(iOffset & 0xffffffff);
   41262 
   41263   /* API oddity: If successful, SetFilePointer() returns a dword
   41264   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
   41265   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
   41266   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
   41267   ** whether an error has actually occurred, it is also necessary to call
   41268   ** GetLastError().
   41269   */
   41270   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   41271 
   41272   if( (dwRet==INVALID_SET_FILE_POINTER
   41273       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
   41274     pFile->lastErrno = lastErrno;
   41275     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   41276                 "winSeekFile", pFile->zPath);
   41277     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
   41278     return 1;
   41279   }
   41280 
   41281   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
   41282   return 0;
   41283 #else
   41284   /*
   41285   ** Same as above, except that this implementation works for WinRT.
   41286   */
   41287 
   41288   LARGE_INTEGER x;                /* The new offset */
   41289   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
   41290 
   41291   x.QuadPart = iOffset;
   41292   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
   41293 
   41294   if(!bRet){
   41295     pFile->lastErrno = osGetLastError();
   41296     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   41297                 "winSeekFile", pFile->zPath);
   41298     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
   41299     return 1;
   41300   }
   41301 
   41302   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
   41303   return 0;
   41304 #endif
   41305 }
   41306 
   41307 #if SQLITE_MAX_MMAP_SIZE>0
   41308 /* Forward references to VFS helper methods used for memory mapped files */
   41309 static int winMapfile(winFile*, sqlite3_int64);
   41310 static int winUnmapfile(winFile*);
   41311 #endif
   41312 
   41313 /*
   41314 ** Close a file.
   41315 **
   41316 ** It is reported that an attempt to close a handle might sometimes
   41317 ** fail.  This is a very unreasonable result, but Windows is notorious
   41318 ** for being unreasonable so I do not doubt that it might happen.  If
   41319 ** the close fails, we pause for 100 milliseconds and try again.  As
   41320 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
   41321 ** giving up and returning an error.
   41322 */
   41323 #define MX_CLOSE_ATTEMPT 3
   41324 static int winClose(sqlite3_file *id){
   41325   int rc, cnt = 0;
   41326   winFile *pFile = (winFile*)id;
   41327 
   41328   assert( id!=0 );
   41329 #ifndef SQLITE_OMIT_WAL
   41330   assert( pFile->pShm==0 );
   41331 #endif
   41332   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
   41333   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
   41334            osGetCurrentProcessId(), pFile, pFile->h));
   41335 
   41336 #if SQLITE_MAX_MMAP_SIZE>0
   41337   winUnmapfile(pFile);
   41338 #endif
   41339 
   41340   do{
   41341     rc = osCloseHandle(pFile->h);
   41342     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
   41343   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
   41344 #if SQLITE_OS_WINCE
   41345 #define WINCE_DELETION_ATTEMPTS 3
   41346   {
   41347     winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
   41348     if( pAppData==NULL || !pAppData->bNoLock ){
   41349       winceDestroyLock(pFile);
   41350     }
   41351   }
   41352   if( pFile->zDeleteOnClose ){
   41353     int cnt = 0;
   41354     while(
   41355            osDeleteFileW(pFile->zDeleteOnClose)==0
   41356         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
   41357         && cnt++ < WINCE_DELETION_ATTEMPTS
   41358     ){
   41359        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
   41360     }
   41361     sqlite3_free(pFile->zDeleteOnClose);
   41362   }
   41363 #endif
   41364   if( rc ){
   41365     pFile->h = NULL;
   41366   }
   41367   OpenCounter(-1);
   41368   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
   41369            osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
   41370   return rc ? SQLITE_OK
   41371             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
   41372                           "winClose", pFile->zPath);
   41373 }
   41374 
   41375 /*
   41376 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   41377 ** bytes were read successfully and SQLITE_IOERR if anything goes
   41378 ** wrong.
   41379 */
   41380 static int winRead(
   41381   sqlite3_file *id,          /* File to read from */
   41382   void *pBuf,                /* Write content into this buffer */
   41383   int amt,                   /* Number of bytes to read */
   41384   sqlite3_int64 offset       /* Begin reading at this offset */
   41385 ){
   41386 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
   41387   OVERLAPPED overlapped;          /* The offset for ReadFile. */
   41388 #endif
   41389   winFile *pFile = (winFile*)id;  /* file handle */
   41390   DWORD nRead;                    /* Number of bytes actually read from file */
   41391   int nRetry = 0;                 /* Number of retrys */
   41392 
   41393   assert( id!=0 );
   41394   assert( amt>0 );
   41395   assert( offset>=0 );
   41396   SimulateIOError(return SQLITE_IOERR_READ);
   41397   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
   41398            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
   41399            pFile->h, pBuf, amt, offset, pFile->locktype));
   41400 
   41401 #if SQLITE_MAX_MMAP_SIZE>0
   41402   /* Deal with as much of this read request as possible by transfering
   41403   ** data from the memory mapping using memcpy().  */
   41404   if( offset<pFile->mmapSize ){
   41405     if( offset+amt <= pFile->mmapSize ){
   41406       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
   41407       OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
   41408                osGetCurrentProcessId(), pFile, pFile->h));
   41409       return SQLITE_OK;
   41410     }else{
   41411       int nCopy = (int)(pFile->mmapSize - offset);
   41412       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
   41413       pBuf = &((u8 *)pBuf)[nCopy];
   41414       amt -= nCopy;
   41415       offset += nCopy;
   41416     }
   41417   }
   41418 #endif
   41419 
   41420 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
   41421   if( winSeekFile(pFile, offset) ){
   41422     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
   41423              osGetCurrentProcessId(), pFile, pFile->h));
   41424     return SQLITE_FULL;
   41425   }
   41426   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
   41427 #else
   41428   memset(&overlapped, 0, sizeof(OVERLAPPED));
   41429   overlapped.Offset = (LONG)(offset & 0xffffffff);
   41430   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   41431   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
   41432          osGetLastError()!=ERROR_HANDLE_EOF ){
   41433 #endif
   41434     DWORD lastErrno;
   41435     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
   41436     pFile->lastErrno = lastErrno;
   41437     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
   41438              osGetCurrentProcessId(), pFile, pFile->h));
   41439     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
   41440                        "winRead", pFile->zPath);
   41441   }
   41442   winLogIoerr(nRetry, __LINE__);
   41443   if( nRead<(DWORD)amt ){
   41444     /* Unread parts of the buffer must be zero-filled */
   41445     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
   41446     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
   41447              osGetCurrentProcessId(), pFile, pFile->h));
   41448     return SQLITE_IOERR_SHORT_READ;
   41449   }
   41450 
   41451   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
   41452            osGetCurrentProcessId(), pFile, pFile->h));
   41453   return SQLITE_OK;
   41454 }
   41455 
   41456 /*
   41457 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   41458 ** or some other error code on failure.
   41459 */
   41460 static int winWrite(
   41461   sqlite3_file *id,               /* File to write into */
   41462   const void *pBuf,               /* The bytes to be written */
   41463   int amt,                        /* Number of bytes to write */
   41464   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   41465 ){
   41466   int rc = 0;                     /* True if error has occurred, else false */
   41467   winFile *pFile = (winFile*)id;  /* File handle */
   41468   int nRetry = 0;                 /* Number of retries */
   41469 
   41470   assert( amt>0 );
   41471   assert( pFile );
   41472   SimulateIOError(return SQLITE_IOERR_WRITE);
   41473   SimulateDiskfullError(return SQLITE_FULL);
   41474 
   41475   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
   41476            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
   41477            pFile->h, pBuf, amt, offset, pFile->locktype));
   41478 
   41479 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
   41480   /* Deal with as much of this write request as possible by transfering
   41481   ** data from the memory mapping using memcpy().  */
   41482   if( offset<pFile->mmapSize ){
   41483     if( offset+amt <= pFile->mmapSize ){
   41484       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
   41485       OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
   41486                osGetCurrentProcessId(), pFile, pFile->h));
   41487       return SQLITE_OK;
   41488     }else{
   41489       int nCopy = (int)(pFile->mmapSize - offset);
   41490       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
   41491       pBuf = &((u8 *)pBuf)[nCopy];
   41492       amt -= nCopy;
   41493       offset += nCopy;
   41494     }
   41495   }
   41496 #endif
   41497 
   41498 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
   41499   rc = winSeekFile(pFile, offset);
   41500   if( rc==0 ){
   41501 #else
   41502   {
   41503 #endif
   41504 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
   41505     OVERLAPPED overlapped;        /* The offset for WriteFile. */
   41506 #endif
   41507     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
   41508     int nRem = amt;               /* Number of bytes yet to be written */
   41509     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
   41510     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
   41511 
   41512 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
   41513     memset(&overlapped, 0, sizeof(OVERLAPPED));
   41514     overlapped.Offset = (LONG)(offset & 0xffffffff);
   41515     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   41516 #endif
   41517 
   41518     while( nRem>0 ){
   41519 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
   41520       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
   41521 #else
   41522       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
   41523 #endif
   41524         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
   41525         break;
   41526       }
   41527       assert( nWrite==0 || nWrite<=(DWORD)nRem );
   41528       if( nWrite==0 || nWrite>(DWORD)nRem ){
   41529         lastErrno = osGetLastError();
   41530         break;
   41531       }
   41532 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
   41533       offset += nWrite;
   41534       overlapped.Offset = (LONG)(offset & 0xffffffff);
   41535       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
   41536 #endif
   41537       aRem += nWrite;
   41538       nRem -= nWrite;
   41539     }
   41540     if( nRem>0 ){
   41541       pFile->lastErrno = lastErrno;
   41542       rc = 1;
   41543     }
   41544   }
   41545 
   41546   if( rc ){
   41547     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
   41548        || ( pFile->lastErrno==ERROR_DISK_FULL )){
   41549       OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
   41550                osGetCurrentProcessId(), pFile, pFile->h));
   41551       return winLogError(SQLITE_FULL, pFile->lastErrno,
   41552                          "winWrite1", pFile->zPath);
   41553     }
   41554     OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
   41555              osGetCurrentProcessId(), pFile, pFile->h));
   41556     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
   41557                        "winWrite2", pFile->zPath);
   41558   }else{
   41559     winLogIoerr(nRetry, __LINE__);
   41560   }
   41561   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
   41562            osGetCurrentProcessId(), pFile, pFile->h));
   41563   return SQLITE_OK;
   41564 }
   41565 
   41566 /*
   41567 ** Truncate an open file to a specified size
   41568 */
   41569 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
   41570   winFile *pFile = (winFile*)id;  /* File handle object */
   41571   int rc = SQLITE_OK;             /* Return code for this function */
   41572   DWORD lastErrno;
   41573 
   41574   assert( pFile );
   41575   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
   41576   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
   41577            osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
   41578 
   41579   /* If the user has configured a chunk-size for this file, truncate the
   41580   ** file so that it consists of an integer number of chunks (i.e. the
   41581   ** actual file size after the operation may be larger than the requested
   41582   ** size).
   41583   */
   41584   if( pFile->szChunk>0 ){
   41585     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   41586   }
   41587 
   41588   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
   41589   if( winSeekFile(pFile, nByte) ){
   41590     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   41591                      "winTruncate1", pFile->zPath);
   41592   }else if( 0==osSetEndOfFile(pFile->h) &&
   41593             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
   41594     pFile->lastErrno = lastErrno;
   41595     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   41596                      "winTruncate2", pFile->zPath);
   41597   }
   41598 
   41599 #if SQLITE_MAX_MMAP_SIZE>0
   41600   /* If the file was truncated to a size smaller than the currently
   41601   ** mapped region, reduce the effective mapping size as well. SQLite will
   41602   ** use read() and write() to access data beyond this point from now on.
   41603   */
   41604   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
   41605     pFile->mmapSize = nByte;
   41606   }
   41607 #endif
   41608 
   41609   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
   41610            osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
   41611   return rc;
   41612 }
   41613 
   41614 #ifdef SQLITE_TEST
   41615 /*
   41616 ** Count the number of fullsyncs and normal syncs.  This is used to test
   41617 ** that syncs and fullsyncs are occuring at the right times.
   41618 */
   41619 SQLITE_API int sqlite3_sync_count = 0;
   41620 SQLITE_API int sqlite3_fullsync_count = 0;
   41621 #endif
   41622 
   41623 /*
   41624 ** Make sure all writes to a particular file are committed to disk.
   41625 */
   41626 static int winSync(sqlite3_file *id, int flags){
   41627 #ifndef SQLITE_NO_SYNC
   41628   /*
   41629   ** Used only when SQLITE_NO_SYNC is not defined.
   41630    */
   41631   BOOL rc;
   41632 #endif
   41633 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
   41634     defined(SQLITE_HAVE_OS_TRACE)
   41635   /*
   41636   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
   41637   ** OSTRACE() macros.
   41638    */
   41639   winFile *pFile = (winFile*)id;
   41640 #else
   41641   UNUSED_PARAMETER(id);
   41642 #endif
   41643 
   41644   assert( pFile );
   41645   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   41646   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   41647       || (flags&0x0F)==SQLITE_SYNC_FULL
   41648   );
   41649 
   41650   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   41651   ** line is to test that doing so does not cause any problems.
   41652   */
   41653   SimulateDiskfullError( return SQLITE_FULL );
   41654 
   41655   OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
   41656            osGetCurrentProcessId(), pFile, pFile->h, flags,
   41657            pFile->locktype));
   41658 
   41659 #ifndef SQLITE_TEST
   41660   UNUSED_PARAMETER(flags);
   41661 #else
   41662   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
   41663     sqlite3_fullsync_count++;
   41664   }
   41665   sqlite3_sync_count++;
   41666 #endif
   41667 
   41668   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   41669   ** no-op
   41670   */
   41671 #ifdef SQLITE_NO_SYNC
   41672   OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
   41673            osGetCurrentProcessId(), pFile, pFile->h));
   41674   return SQLITE_OK;
   41675 #else
   41676 #if SQLITE_MAX_MMAP_SIZE>0
   41677   if( pFile->pMapRegion ){
   41678     if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
   41679       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
   41680                "rc=SQLITE_OK\n", osGetCurrentProcessId(),
   41681                pFile, pFile->pMapRegion));
   41682     }else{
   41683       pFile->lastErrno = osGetLastError();
   41684       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
   41685                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
   41686                pFile, pFile->pMapRegion));
   41687       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
   41688                          "winSync1", pFile->zPath);
   41689     }
   41690   }
   41691 #endif
   41692   rc = osFlushFileBuffers(pFile->h);
   41693   SimulateIOError( rc=FALSE );
   41694   if( rc ){
   41695     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
   41696              osGetCurrentProcessId(), pFile, pFile->h));
   41697     return SQLITE_OK;
   41698   }else{
   41699     pFile->lastErrno = osGetLastError();
   41700     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
   41701              osGetCurrentProcessId(), pFile, pFile->h));
   41702     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
   41703                        "winSync2", pFile->zPath);
   41704   }
   41705 #endif
   41706 }
   41707 
   41708 /*
   41709 ** Determine the current size of a file in bytes
   41710 */
   41711 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
   41712   winFile *pFile = (winFile*)id;
   41713   int rc = SQLITE_OK;
   41714 
   41715   assert( id!=0 );
   41716   assert( pSize!=0 );
   41717   SimulateIOError(return SQLITE_IOERR_FSTAT);
   41718   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
   41719 
   41720 #if SQLITE_OS_WINRT
   41721   {
   41722     FILE_STANDARD_INFO info;
   41723     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
   41724                                      &info, sizeof(info)) ){
   41725       *pSize = info.EndOfFile.QuadPart;
   41726     }else{
   41727       pFile->lastErrno = osGetLastError();
   41728       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   41729                        "winFileSize", pFile->zPath);
   41730     }
   41731   }
   41732 #else
   41733   {
   41734     DWORD upperBits;
   41735     DWORD lowerBits;
   41736     DWORD lastErrno;
   41737 
   41738     lowerBits = osGetFileSize(pFile->h, &upperBits);
   41739     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
   41740     if(   (lowerBits == INVALID_FILE_SIZE)
   41741        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
   41742       pFile->lastErrno = lastErrno;
   41743       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   41744                        "winFileSize", pFile->zPath);
   41745     }
   41746   }
   41747 #endif
   41748   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
   41749            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
   41750   return rc;
   41751 }
   41752 
   41753 /*
   41754 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
   41755 */
   41756 #ifndef LOCKFILE_FAIL_IMMEDIATELY
   41757 # define LOCKFILE_FAIL_IMMEDIATELY 1
   41758 #endif
   41759 
   41760 #ifndef LOCKFILE_EXCLUSIVE_LOCK
   41761 # define LOCKFILE_EXCLUSIVE_LOCK 2
   41762 #endif
   41763 
   41764 /*
   41765 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
   41766 ** When the LockFile function was used, it was always expected to fail
   41767 ** immediately if the lock could not be obtained.  Also, it always expected to
   41768 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
   41769 ** and reflect those expectations; therefore, they should not be changed.
   41770 */
   41771 #ifndef SQLITE_LOCKFILE_FLAGS
   41772 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
   41773                                   LOCKFILE_EXCLUSIVE_LOCK)
   41774 #endif
   41775 
   41776 /*
   41777 ** Currently, SQLite never calls the LockFileEx function without wanting the
   41778 ** call to fail immediately if the lock cannot be obtained.
   41779 */
   41780 #ifndef SQLITE_LOCKFILEEX_FLAGS
   41781 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
   41782 #endif
   41783 
   41784 /*
   41785 ** Acquire a reader lock.
   41786 ** Different API routines are called depending on whether or not this
   41787 ** is Win9x or WinNT.
   41788 */
   41789 static int winGetReadLock(winFile *pFile){
   41790   int res;
   41791   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
   41792   if( osIsNT() ){
   41793 #if SQLITE_OS_WINCE
   41794     /*
   41795     ** NOTE: Windows CE is handled differently here due its lack of the Win32
   41796     **       API LockFileEx.
   41797     */
   41798     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
   41799 #else
   41800     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
   41801                       SHARED_SIZE, 0);
   41802 #endif
   41803   }
   41804 #ifdef SQLITE_WIN32_HAS_ANSI
   41805   else{
   41806     int lk;
   41807     sqlite3_randomness(sizeof(lk), &lk);
   41808     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
   41809     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
   41810                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   41811   }
   41812 #endif
   41813   if( res == 0 ){
   41814     pFile->lastErrno = osGetLastError();
   41815     /* No need to log a failure to lock */
   41816   }
   41817   OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
   41818   return res;
   41819 }
   41820 
   41821 /*
   41822 ** Undo a readlock
   41823 */
   41824 static int winUnlockReadLock(winFile *pFile){
   41825   int res;
   41826   DWORD lastErrno;
   41827   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
   41828   if( osIsNT() ){
   41829     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   41830   }
   41831 #ifdef SQLITE_WIN32_HAS_ANSI
   41832   else{
   41833     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   41834   }
   41835 #endif
   41836   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
   41837     pFile->lastErrno = lastErrno;
   41838     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
   41839                 "winUnlockReadLock", pFile->zPath);
   41840   }
   41841   OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
   41842   return res;
   41843 }
   41844 
   41845 /*
   41846 ** Lock the file with the lock specified by parameter locktype - one
   41847 ** of the following:
   41848 **
   41849 **     (1) SHARED_LOCK
   41850 **     (2) RESERVED_LOCK
   41851 **     (3) PENDING_LOCK
   41852 **     (4) EXCLUSIVE_LOCK
   41853 **
   41854 ** Sometimes when requesting one lock state, additional lock states
   41855 ** are inserted in between.  The locking might fail on one of the later
   41856 ** transitions leaving the lock state different from what it started but
   41857 ** still short of its goal.  The following chart shows the allowed
   41858 ** transitions and the inserted intermediate states:
   41859 **
   41860 **    UNLOCKED -> SHARED
   41861 **    SHARED -> RESERVED
   41862 **    SHARED -> (PENDING) -> EXCLUSIVE
   41863 **    RESERVED -> (PENDING) -> EXCLUSIVE
   41864 **    PENDING -> EXCLUSIVE
   41865 **
   41866 ** This routine will only increase a lock.  The winUnlock() routine
   41867 ** erases all locks at once and returns us immediately to locking level 0.
   41868 ** It is not possible to lower the locking level one step at a time.  You
   41869 ** must go straight to locking level 0.
   41870 */
   41871 static int winLock(sqlite3_file *id, int locktype){
   41872   int rc = SQLITE_OK;    /* Return code from subroutines */
   41873   int res = 1;           /* Result of a Windows lock call */
   41874   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   41875   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   41876   winFile *pFile = (winFile*)id;
   41877   DWORD lastErrno = NO_ERROR;
   41878 
   41879   assert( id!=0 );
   41880   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
   41881            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
   41882 
   41883   /* If there is already a lock of this type or more restrictive on the
   41884   ** OsFile, do nothing. Don't use the end_lock: exit path, as
   41885   ** sqlite3OsEnterMutex() hasn't been called yet.
   41886   */
   41887   if( pFile->locktype>=locktype ){
   41888     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
   41889     return SQLITE_OK;
   41890   }
   41891 
   41892   /* Do not allow any kind of write-lock on a read-only database
   41893   */
   41894   if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
   41895     return SQLITE_IOERR_LOCK;
   41896   }
   41897 
   41898   /* Make sure the locking sequence is correct
   41899   */
   41900   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   41901   assert( locktype!=PENDING_LOCK );
   41902   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   41903 
   41904   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   41905   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   41906   ** the PENDING_LOCK byte is temporary.
   41907   */
   41908   newLocktype = pFile->locktype;
   41909   if( pFile->locktype==NO_LOCK
   41910    || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
   41911   ){
   41912     int cnt = 3;
   41913     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
   41914                                          PENDING_BYTE, 0, 1, 0))==0 ){
   41915       /* Try 3 times to get the pending lock.  This is needed to work
   41916       ** around problems caused by indexing and/or anti-virus software on
   41917       ** Windows systems.
   41918       ** If you are using this code as a model for alternative VFSes, do not
   41919       ** copy this retry logic.  It is a hack intended for Windows only.
   41920       */
   41921       lastErrno = osGetLastError();
   41922       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
   41923                pFile->h, cnt, res));
   41924       if( lastErrno==ERROR_INVALID_HANDLE ){
   41925         pFile->lastErrno = lastErrno;
   41926         rc = SQLITE_IOERR_LOCK;
   41927         OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
   41928                  pFile->h, cnt, sqlite3ErrName(rc)));
   41929         return rc;
   41930       }
   41931       if( cnt ) sqlite3_win32_sleep(1);
   41932     }
   41933     gotPendingLock = res;
   41934     if( !res ){
   41935       lastErrno = osGetLastError();
   41936     }
   41937   }
   41938 
   41939   /* Acquire a shared lock
   41940   */
   41941   if( locktype==SHARED_LOCK && res ){
   41942     assert( pFile->locktype==NO_LOCK );
   41943     res = winGetReadLock(pFile);
   41944     if( res ){
   41945       newLocktype = SHARED_LOCK;
   41946     }else{
   41947       lastErrno = osGetLastError();
   41948     }
   41949   }
   41950 
   41951   /* Acquire a RESERVED lock
   41952   */
   41953   if( locktype==RESERVED_LOCK && res ){
   41954     assert( pFile->locktype==SHARED_LOCK );
   41955     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
   41956     if( res ){
   41957       newLocktype = RESERVED_LOCK;
   41958     }else{
   41959       lastErrno = osGetLastError();
   41960     }
   41961   }
   41962 
   41963   /* Acquire a PENDING lock
   41964   */
   41965   if( locktype==EXCLUSIVE_LOCK && res ){
   41966     newLocktype = PENDING_LOCK;
   41967     gotPendingLock = 0;
   41968   }
   41969 
   41970   /* Acquire an EXCLUSIVE lock
   41971   */
   41972   if( locktype==EXCLUSIVE_LOCK && res ){
   41973     assert( pFile->locktype>=SHARED_LOCK );
   41974     res = winUnlockReadLock(pFile);
   41975     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
   41976                       SHARED_SIZE, 0);
   41977     if( res ){
   41978       newLocktype = EXCLUSIVE_LOCK;
   41979     }else{
   41980       lastErrno = osGetLastError();
   41981       winGetReadLock(pFile);
   41982     }
   41983   }
   41984 
   41985   /* If we are holding a PENDING lock that ought to be released, then
   41986   ** release it now.
   41987   */
   41988   if( gotPendingLock && locktype==SHARED_LOCK ){
   41989     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
   41990   }
   41991 
   41992   /* Update the state of the lock has held in the file descriptor then
   41993   ** return the appropriate result code.
   41994   */
   41995   if( res ){
   41996     rc = SQLITE_OK;
   41997   }else{
   41998     pFile->lastErrno = lastErrno;
   41999     rc = SQLITE_BUSY;
   42000     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
   42001              pFile->h, locktype, newLocktype));
   42002   }
   42003   pFile->locktype = (u8)newLocktype;
   42004   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
   42005            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
   42006   return rc;
   42007 }
   42008 
   42009 /*
   42010 ** This routine checks if there is a RESERVED lock held on the specified
   42011 ** file by this or any other process. If such a lock is held, return
   42012 ** non-zero, otherwise zero.
   42013 */
   42014 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
   42015   int res;
   42016   winFile *pFile = (winFile*)id;
   42017 
   42018   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   42019   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
   42020 
   42021   assert( id!=0 );
   42022   if( pFile->locktype>=RESERVED_LOCK ){
   42023     res = 1;
   42024     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
   42025   }else{
   42026     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
   42027     if( res ){
   42028       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
   42029     }
   42030     res = !res;
   42031     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
   42032   }
   42033   *pResOut = res;
   42034   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
   42035            pFile->h, pResOut, *pResOut));
   42036   return SQLITE_OK;
   42037 }
   42038 
   42039 /*
   42040 ** Lower the locking level on file descriptor id to locktype.  locktype
   42041 ** must be either NO_LOCK or SHARED_LOCK.
   42042 **
   42043 ** If the locking level of the file descriptor is already at or below
   42044 ** the requested locking level, this routine is a no-op.
   42045 **
   42046 ** It is not possible for this routine to fail if the second argument
   42047 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   42048 ** might return SQLITE_IOERR;
   42049 */
   42050 static int winUnlock(sqlite3_file *id, int locktype){
   42051   int type;
   42052   winFile *pFile = (winFile*)id;
   42053   int rc = SQLITE_OK;
   42054   assert( pFile!=0 );
   42055   assert( locktype<=SHARED_LOCK );
   42056   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
   42057            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
   42058   type = pFile->locktype;
   42059   if( type>=EXCLUSIVE_LOCK ){
   42060     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   42061     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
   42062       /* This should never happen.  We should always be able to
   42063       ** reacquire the read lock */
   42064       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
   42065                        "winUnlock", pFile->zPath);
   42066     }
   42067   }
   42068   if( type>=RESERVED_LOCK ){
   42069     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
   42070   }
   42071   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   42072     winUnlockReadLock(pFile);
   42073   }
   42074   if( type>=PENDING_LOCK ){
   42075     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
   42076   }
   42077   pFile->locktype = (u8)locktype;
   42078   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
   42079            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
   42080   return rc;
   42081 }
   42082 
   42083 /******************************************************************************
   42084 ****************************** No-op Locking **********************************
   42085 **
   42086 ** Of the various locking implementations available, this is by far the
   42087 ** simplest:  locking is ignored.  No attempt is made to lock the database
   42088 ** file for reading or writing.
   42089 **
   42090 ** This locking mode is appropriate for use on read-only databases
   42091 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   42092 ** also be used if the application employs some external mechanism to
   42093 ** prevent simultaneous access of the same database by two or more
   42094 ** database connections.  But there is a serious risk of database
   42095 ** corruption if this locking mode is used in situations where multiple
   42096 ** database connections are accessing the same database file at the same
   42097 ** time and one or more of those connections are writing.
   42098 */
   42099 
   42100 static int winNolockLock(sqlite3_file *id, int locktype){
   42101   UNUSED_PARAMETER(id);
   42102   UNUSED_PARAMETER(locktype);
   42103   return SQLITE_OK;
   42104 }
   42105 
   42106 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
   42107   UNUSED_PARAMETER(id);
   42108   UNUSED_PARAMETER(pResOut);
   42109   return SQLITE_OK;
   42110 }
   42111 
   42112 static int winNolockUnlock(sqlite3_file *id, int locktype){
   42113   UNUSED_PARAMETER(id);
   42114   UNUSED_PARAMETER(locktype);
   42115   return SQLITE_OK;
   42116 }
   42117 
   42118 /******************* End of the no-op lock implementation *********************
   42119 ******************************************************************************/
   42120 
   42121 /*
   42122 ** If *pArg is initially negative then this is a query.  Set *pArg to
   42123 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   42124 **
   42125 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   42126 */
   42127 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
   42128   if( *pArg<0 ){
   42129     *pArg = (pFile->ctrlFlags & mask)!=0;
   42130   }else if( (*pArg)==0 ){
   42131     pFile->ctrlFlags &= ~mask;
   42132   }else{
   42133     pFile->ctrlFlags |= mask;
   42134   }
   42135 }
   42136 
   42137 /* Forward references to VFS helper methods used for temporary files */
   42138 static int winGetTempname(sqlite3_vfs *, char **);
   42139 static int winIsDir(const void *);
   42140 static BOOL winIsDriveLetterAndColon(const char *);
   42141 
   42142 /*
   42143 ** Control and query of the open file handle.
   42144 */
   42145 static int winFileControl(sqlite3_file *id, int op, void *pArg){
   42146   winFile *pFile = (winFile*)id;
   42147   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
   42148   switch( op ){
   42149     case SQLITE_FCNTL_LOCKSTATE: {
   42150       *(int*)pArg = pFile->locktype;
   42151       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42152       return SQLITE_OK;
   42153     }
   42154     case SQLITE_FCNTL_LAST_ERRNO: {
   42155       *(int*)pArg = (int)pFile->lastErrno;
   42156       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42157       return SQLITE_OK;
   42158     }
   42159     case SQLITE_FCNTL_CHUNK_SIZE: {
   42160       pFile->szChunk = *(int *)pArg;
   42161       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42162       return SQLITE_OK;
   42163     }
   42164     case SQLITE_FCNTL_SIZE_HINT: {
   42165       if( pFile->szChunk>0 ){
   42166         sqlite3_int64 oldSz;
   42167         int rc = winFileSize(id, &oldSz);
   42168         if( rc==SQLITE_OK ){
   42169           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
   42170           if( newSz>oldSz ){
   42171             SimulateIOErrorBenign(1);
   42172             rc = winTruncate(id, newSz);
   42173             SimulateIOErrorBenign(0);
   42174           }
   42175         }
   42176         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   42177         return rc;
   42178       }
   42179       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42180       return SQLITE_OK;
   42181     }
   42182     case SQLITE_FCNTL_PERSIST_WAL: {
   42183       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
   42184       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42185       return SQLITE_OK;
   42186     }
   42187     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   42188       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
   42189       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42190       return SQLITE_OK;
   42191     }
   42192     case SQLITE_FCNTL_VFSNAME: {
   42193       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   42194       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42195       return SQLITE_OK;
   42196     }
   42197     case SQLITE_FCNTL_WIN32_AV_RETRY: {
   42198       int *a = (int*)pArg;
   42199       if( a[0]>0 ){
   42200         winIoerrRetry = a[0];
   42201       }else{
   42202         a[0] = winIoerrRetry;
   42203       }
   42204       if( a[1]>0 ){
   42205         winIoerrRetryDelay = a[1];
   42206       }else{
   42207         a[1] = winIoerrRetryDelay;
   42208       }
   42209       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42210       return SQLITE_OK;
   42211     }
   42212     case SQLITE_FCNTL_WIN32_GET_HANDLE: {
   42213       LPHANDLE phFile = (LPHANDLE)pArg;
   42214       *phFile = pFile->h;
   42215       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
   42216       return SQLITE_OK;
   42217     }
   42218 #ifdef SQLITE_TEST
   42219     case SQLITE_FCNTL_WIN32_SET_HANDLE: {
   42220       LPHANDLE phFile = (LPHANDLE)pArg;
   42221       HANDLE hOldFile = pFile->h;
   42222       pFile->h = *phFile;
   42223       *phFile = hOldFile;
   42224       OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
   42225                hOldFile, pFile->h));
   42226       return SQLITE_OK;
   42227     }
   42228 #endif
   42229     case SQLITE_FCNTL_TEMPFILENAME: {
   42230       char *zTFile = 0;
   42231       int rc = winGetTempname(pFile->pVfs, &zTFile);
   42232       if( rc==SQLITE_OK ){
   42233         *(char**)pArg = zTFile;
   42234       }
   42235       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   42236       return rc;
   42237     }
   42238 #if SQLITE_MAX_MMAP_SIZE>0
   42239     case SQLITE_FCNTL_MMAP_SIZE: {
   42240       i64 newLimit = *(i64*)pArg;
   42241       int rc = SQLITE_OK;
   42242       if( newLimit>sqlite3GlobalConfig.mxMmap ){
   42243         newLimit = sqlite3GlobalConfig.mxMmap;
   42244       }
   42245 
   42246       /* The value of newLimit may be eventually cast to (SIZE_T) and passed
   42247       ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
   42248       ** least a 64-bit type. */
   42249       if( newLimit>0 && sizeof(SIZE_T)<8 ){
   42250         newLimit = (newLimit & 0x7FFFFFFF);
   42251       }
   42252 
   42253       *(i64*)pArg = pFile->mmapSizeMax;
   42254       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
   42255         pFile->mmapSizeMax = newLimit;
   42256         if( pFile->mmapSize>0 ){
   42257           winUnmapfile(pFile);
   42258           rc = winMapfile(pFile, -1);
   42259         }
   42260       }
   42261       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
   42262       return rc;
   42263     }
   42264 #endif
   42265   }
   42266   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
   42267   return SQLITE_NOTFOUND;
   42268 }
   42269 
   42270 /*
   42271 ** Return the sector size in bytes of the underlying block device for
   42272 ** the specified file. This is almost always 512 bytes, but may be
   42273 ** larger for some devices.
   42274 **
   42275 ** SQLite code assumes this function cannot fail. It also assumes that
   42276 ** if two files are created in the same file-system directory (i.e.
   42277 ** a database and its journal file) that the sector size will be the
   42278 ** same for both.
   42279 */
   42280 static int winSectorSize(sqlite3_file *id){
   42281   (void)id;
   42282   return SQLITE_DEFAULT_SECTOR_SIZE;
   42283 }
   42284 
   42285 /*
   42286 ** Return a vector of device characteristics.
   42287 */
   42288 static int winDeviceCharacteristics(sqlite3_file *id){
   42289   winFile *p = (winFile*)id;
   42290   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
   42291          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
   42292 }
   42293 
   42294 /*
   42295 ** Windows will only let you create file view mappings
   42296 ** on allocation size granularity boundaries.
   42297 ** During sqlite3_os_init() we do a GetSystemInfo()
   42298 ** to get the granularity size.
   42299 */
   42300 static SYSTEM_INFO winSysInfo;
   42301 
   42302 #ifndef SQLITE_OMIT_WAL
   42303 
   42304 /*
   42305 ** Helper functions to obtain and relinquish the global mutex. The
   42306 ** global mutex is used to protect the winLockInfo objects used by
   42307 ** this file, all of which may be shared by multiple threads.
   42308 **
   42309 ** Function winShmMutexHeld() is used to assert() that the global mutex
   42310 ** is held when required. This function is only used as part of assert()
   42311 ** statements. e.g.
   42312 **
   42313 **   winShmEnterMutex()
   42314 **     assert( winShmMutexHeld() );
   42315 **   winShmLeaveMutex()
   42316 */
   42317 static void winShmEnterMutex(void){
   42318   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
   42319 }
   42320 static void winShmLeaveMutex(void){
   42321   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
   42322 }
   42323 #ifndef NDEBUG
   42324 static int winShmMutexHeld(void) {
   42325   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
   42326 }
   42327 #endif
   42328 
   42329 /*
   42330 ** Object used to represent a single file opened and mmapped to provide
   42331 ** shared memory.  When multiple threads all reference the same
   42332 ** log-summary, each thread has its own winFile object, but they all
   42333 ** point to a single instance of this object.  In other words, each
   42334 ** log-summary is opened only once per process.
   42335 **
   42336 ** winShmMutexHeld() must be true when creating or destroying
   42337 ** this object or while reading or writing the following fields:
   42338 **
   42339 **      nRef
   42340 **      pNext
   42341 **
   42342 ** The following fields are read-only after the object is created:
   42343 **
   42344 **      fid
   42345 **      zFilename
   42346 **
   42347 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
   42348 ** winShmMutexHeld() is true when reading or writing any other field
   42349 ** in this structure.
   42350 **
   42351 */
   42352 struct winShmNode {
   42353   sqlite3_mutex *mutex;      /* Mutex to access this object */
   42354   char *zFilename;           /* Name of the file */
   42355   winFile hFile;             /* File handle from winOpen */
   42356 
   42357   int szRegion;              /* Size of shared-memory regions */
   42358   int nRegion;               /* Size of array apRegion */
   42359   u8 isReadonly;             /* True if read-only */
   42360   u8 isUnlocked;             /* True if no DMS lock held */
   42361 
   42362   struct ShmRegion {
   42363     HANDLE hMap;             /* File handle from CreateFileMapping */
   42364     void *pMap;
   42365   } *aRegion;
   42366   DWORD lastErrno;           /* The Windows errno from the last I/O error */
   42367 
   42368   int nRef;                  /* Number of winShm objects pointing to this */
   42369   winShm *pFirst;            /* All winShm objects pointing to this */
   42370   winShmNode *pNext;         /* Next in list of all winShmNode objects */
   42371 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
   42372   u8 nextShmId;              /* Next available winShm.id value */
   42373 #endif
   42374 };
   42375 
   42376 /*
   42377 ** A global array of all winShmNode objects.
   42378 **
   42379 ** The winShmMutexHeld() must be true while reading or writing this list.
   42380 */
   42381 static winShmNode *winShmNodeList = 0;
   42382 
   42383 /*
   42384 ** Structure used internally by this VFS to record the state of an
   42385 ** open shared memory connection.
   42386 **
   42387 ** The following fields are initialized when this object is created and
   42388 ** are read-only thereafter:
   42389 **
   42390 **    winShm.pShmNode
   42391 **    winShm.id
   42392 **
   42393 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
   42394 ** while accessing any read/write fields.
   42395 */
   42396 struct winShm {
   42397   winShmNode *pShmNode;      /* The underlying winShmNode object */
   42398   winShm *pNext;             /* Next winShm with the same winShmNode */
   42399   u8 hasMutex;               /* True if holding the winShmNode mutex */
   42400   u16 sharedMask;            /* Mask of shared locks held */
   42401   u16 exclMask;              /* Mask of exclusive locks held */
   42402 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
   42403   u8 id;                     /* Id of this connection with its winShmNode */
   42404 #endif
   42405 };
   42406 
   42407 /*
   42408 ** Constants used for locking
   42409 */
   42410 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
   42411 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   42412 
   42413 /*
   42414 ** Apply advisory locks for all n bytes beginning at ofst.
   42415 */
   42416 #define WINSHM_UNLCK  1
   42417 #define WINSHM_RDLCK  2
   42418 #define WINSHM_WRLCK  3
   42419 static int winShmSystemLock(
   42420   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
   42421   int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
   42422   int ofst,             /* Offset to first byte to be locked/unlocked */
   42423   int nByte             /* Number of bytes to lock or unlock */
   42424 ){
   42425   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
   42426 
   42427   /* Access to the winShmNode object is serialized by the caller */
   42428   assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
   42429 
   42430   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
   42431            pFile->hFile.h, lockType, ofst, nByte));
   42432 
   42433   /* Release/Acquire the system-level lock */
   42434   if( lockType==WINSHM_UNLCK ){
   42435     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
   42436   }else{
   42437     /* Initialize the locking parameters */
   42438     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
   42439     if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
   42440     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
   42441   }
   42442 
   42443   if( rc!= 0 ){
   42444     rc = SQLITE_OK;
   42445   }else{
   42446     pFile->lastErrno =  osGetLastError();
   42447     rc = SQLITE_BUSY;
   42448   }
   42449 
   42450   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
   42451            pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
   42452            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
   42453 
   42454   return rc;
   42455 }
   42456 
   42457 /* Forward references to VFS methods */
   42458 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
   42459 static int winDelete(sqlite3_vfs *,const char*,int);
   42460 
   42461 /*
   42462 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
   42463 **
   42464 ** This is not a VFS shared-memory method; it is a utility function called
   42465 ** by VFS shared-memory methods.
   42466 */
   42467 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
   42468   winShmNode **pp;
   42469   winShmNode *p;
   42470   assert( winShmMutexHeld() );
   42471   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
   42472            osGetCurrentProcessId(), deleteFlag));
   42473   pp = &winShmNodeList;
   42474   while( (p = *pp)!=0 ){
   42475     if( p->nRef==0 ){
   42476       int i;
   42477       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
   42478       for(i=0; i<p->nRegion; i++){
   42479         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
   42480         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
   42481                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
   42482         UNUSED_VARIABLE_VALUE(bRc);
   42483         bRc = osCloseHandle(p->aRegion[i].hMap);
   42484         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
   42485                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
   42486         UNUSED_VARIABLE_VALUE(bRc);
   42487       }
   42488       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
   42489         SimulateIOErrorBenign(1);
   42490         winClose((sqlite3_file *)&p->hFile);
   42491         SimulateIOErrorBenign(0);
   42492       }
   42493       if( deleteFlag ){
   42494         SimulateIOErrorBenign(1);
   42495         sqlite3BeginBenignMalloc();
   42496         winDelete(pVfs, p->zFilename, 0);
   42497         sqlite3EndBenignMalloc();
   42498         SimulateIOErrorBenign(0);
   42499       }
   42500       *pp = p->pNext;
   42501       sqlite3_free(p->aRegion);
   42502       sqlite3_free(p);
   42503     }else{
   42504       pp = &p->pNext;
   42505     }
   42506   }
   42507 }
   42508 
   42509 /*
   42510 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
   42511 ** take it now. Return SQLITE_OK if successful, or an SQLite error
   42512 ** code otherwise.
   42513 **
   42514 ** If the DMS cannot be locked because this is a readonly_shm=1
   42515 ** connection and no other process already holds a lock, return
   42516 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
   42517 */
   42518 static int winLockSharedMemory(winShmNode *pShmNode){
   42519   int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
   42520 
   42521   if( rc==SQLITE_OK ){
   42522     if( pShmNode->isReadonly ){
   42523       pShmNode->isUnlocked = 1;
   42524       winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
   42525       return SQLITE_READONLY_CANTINIT;
   42526     }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
   42527       winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
   42528       return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
   42529                          "winLockSharedMemory", pShmNode->zFilename);
   42530     }
   42531   }
   42532 
   42533   if( rc==SQLITE_OK ){
   42534     winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
   42535   }
   42536 
   42537   return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
   42538 }
   42539 
   42540 /*
   42541 ** Open the shared-memory area associated with database file pDbFd.
   42542 **
   42543 ** When opening a new shared-memory file, if no other instances of that
   42544 ** file are currently open, in this process or in other processes, then
   42545 ** the file must be truncated to zero length or have its header cleared.
   42546 */
   42547 static int winOpenSharedMemory(winFile *pDbFd){
   42548   struct winShm *p;                  /* The connection to be opened */
   42549   winShmNode *pShmNode = 0;          /* The underlying mmapped file */
   42550   int rc = SQLITE_OK;                /* Result code */
   42551   winShmNode *pNew;                  /* Newly allocated winShmNode */
   42552   int nName;                         /* Size of zName in bytes */
   42553 
   42554   assert( pDbFd->pShm==0 );    /* Not previously opened */
   42555 
   42556   /* Allocate space for the new sqlite3_shm object.  Also speculatively
   42557   ** allocate space for a new winShmNode and filename.
   42558   */
   42559   p = sqlite3MallocZero( sizeof(*p) );
   42560   if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
   42561   nName = sqlite3Strlen30(pDbFd->zPath);
   42562   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
   42563   if( pNew==0 ){
   42564     sqlite3_free(p);
   42565     return SQLITE_IOERR_NOMEM_BKPT;
   42566   }
   42567   pNew->zFilename = (char*)&pNew[1];
   42568   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
   42569   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
   42570 
   42571   /* Look to see if there is an existing winShmNode that can be used.
   42572   ** If no matching winShmNode currently exists, create a new one.
   42573   */
   42574   winShmEnterMutex();
   42575   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
   42576     /* TBD need to come up with better match here.  Perhaps
   42577     ** use FILE_ID_BOTH_DIR_INFO Structure.
   42578     */
   42579     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
   42580   }
   42581   if( pShmNode ){
   42582     sqlite3_free(pNew);
   42583   }else{
   42584     int inFlags = SQLITE_OPEN_WAL;
   42585     int outFlags = 0;
   42586 
   42587     pShmNode = pNew;
   42588     pNew = 0;
   42589     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
   42590     pShmNode->pNext = winShmNodeList;
   42591     winShmNodeList = pShmNode;
   42592 
   42593     if( sqlite3GlobalConfig.bCoreMutex ){
   42594       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   42595       if( pShmNode->mutex==0 ){
   42596         rc = SQLITE_IOERR_NOMEM_BKPT;
   42597         goto shm_open_err;
   42598       }
   42599     }
   42600 
   42601     if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
   42602       inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
   42603     }else{
   42604       inFlags |= SQLITE_OPEN_READONLY;
   42605     }
   42606     rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
   42607                  (sqlite3_file*)&pShmNode->hFile,
   42608                  inFlags, &outFlags);
   42609     if( rc!=SQLITE_OK ){
   42610       rc = winLogError(rc, osGetLastError(), "winOpenShm",
   42611                        pShmNode->zFilename);
   42612       goto shm_open_err;
   42613     }
   42614     if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
   42615 
   42616     rc = winLockSharedMemory(pShmNode);
   42617     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
   42618   }
   42619 
   42620   /* Make the new connection a child of the winShmNode */
   42621   p->pShmNode = pShmNode;
   42622 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
   42623   p->id = pShmNode->nextShmId++;
   42624 #endif
   42625   pShmNode->nRef++;
   42626   pDbFd->pShm = p;
   42627   winShmLeaveMutex();
   42628 
   42629   /* The reference count on pShmNode has already been incremented under
   42630   ** the cover of the winShmEnterMutex() mutex and the pointer from the
   42631   ** new (struct winShm) object to the pShmNode has been set. All that is
   42632   ** left to do is to link the new object into the linked list starting
   42633   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   42634   ** mutex.
   42635   */
   42636   sqlite3_mutex_enter(pShmNode->mutex);
   42637   p->pNext = pShmNode->pFirst;
   42638   pShmNode->pFirst = p;
   42639   sqlite3_mutex_leave(pShmNode->mutex);
   42640   return rc;
   42641 
   42642   /* Jump here on any error */
   42643 shm_open_err:
   42644   winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
   42645   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
   42646   sqlite3_free(p);
   42647   sqlite3_free(pNew);
   42648   winShmLeaveMutex();
   42649   return rc;
   42650 }
   42651 
   42652 /*
   42653 ** Close a connection to shared-memory.  Delete the underlying
   42654 ** storage if deleteFlag is true.
   42655 */
   42656 static int winShmUnmap(
   42657   sqlite3_file *fd,          /* Database holding shared memory */
   42658   int deleteFlag             /* Delete after closing if true */
   42659 ){
   42660   winFile *pDbFd;       /* Database holding shared-memory */
   42661   winShm *p;            /* The connection to be closed */
   42662   winShmNode *pShmNode; /* The underlying shared-memory file */
   42663   winShm **pp;          /* For looping over sibling connections */
   42664 
   42665   pDbFd = (winFile*)fd;
   42666   p = pDbFd->pShm;
   42667   if( p==0 ) return SQLITE_OK;
   42668   pShmNode = p->pShmNode;
   42669 
   42670   /* Remove connection p from the set of connections associated
   42671   ** with pShmNode */
   42672   sqlite3_mutex_enter(pShmNode->mutex);
   42673   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   42674   *pp = p->pNext;
   42675 
   42676   /* Free the connection p */
   42677   sqlite3_free(p);
   42678   pDbFd->pShm = 0;
   42679   sqlite3_mutex_leave(pShmNode->mutex);
   42680 
   42681   /* If pShmNode->nRef has reached 0, then close the underlying
   42682   ** shared-memory file, too */
   42683   winShmEnterMutex();
   42684   assert( pShmNode->nRef>0 );
   42685   pShmNode->nRef--;
   42686   if( pShmNode->nRef==0 ){
   42687     winShmPurge(pDbFd->pVfs, deleteFlag);
   42688   }
   42689   winShmLeaveMutex();
   42690 
   42691   return SQLITE_OK;
   42692 }
   42693 
   42694 /*
   42695 ** Change the lock state for a shared-memory segment.
   42696 */
   42697 static int winShmLock(
   42698   sqlite3_file *fd,          /* Database file holding the shared memory */
   42699   int ofst,                  /* First lock to acquire or release */
   42700   int n,                     /* Number of locks to acquire or release */
   42701   int flags                  /* What to do with the lock */
   42702 ){
   42703   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
   42704   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
   42705   winShm *pX;                           /* For looping over all siblings */
   42706   winShmNode *pShmNode = p->pShmNode;
   42707   int rc = SQLITE_OK;                   /* Result code */
   42708   u16 mask;                             /* Mask of locks to take or release */
   42709 
   42710   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   42711   assert( n>=1 );
   42712   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   42713        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   42714        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   42715        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   42716   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   42717 
   42718   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
   42719   assert( n>1 || mask==(1<<ofst) );
   42720   sqlite3_mutex_enter(pShmNode->mutex);
   42721   if( flags & SQLITE_SHM_UNLOCK ){
   42722     u16 allMask = 0; /* Mask of locks held by siblings */
   42723 
   42724     /* See if any siblings hold this same lock */
   42725     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   42726       if( pX==p ) continue;
   42727       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   42728       allMask |= pX->sharedMask;
   42729     }
   42730 
   42731     /* Unlock the system-level locks */
   42732     if( (mask & allMask)==0 ){
   42733       rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
   42734     }else{
   42735       rc = SQLITE_OK;
   42736     }
   42737 
   42738     /* Undo the local locks */
   42739     if( rc==SQLITE_OK ){
   42740       p->exclMask &= ~mask;
   42741       p->sharedMask &= ~mask;
   42742     }
   42743   }else if( flags & SQLITE_SHM_SHARED ){
   42744     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   42745 
   42746     /* Find out which shared locks are already held by sibling connections.
   42747     ** If any sibling already holds an exclusive lock, go ahead and return
   42748     ** SQLITE_BUSY.
   42749     */
   42750     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   42751       if( (pX->exclMask & mask)!=0 ){
   42752         rc = SQLITE_BUSY;
   42753         break;
   42754       }
   42755       allShared |= pX->sharedMask;
   42756     }
   42757 
   42758     /* Get shared locks at the system level, if necessary */
   42759     if( rc==SQLITE_OK ){
   42760       if( (allShared & mask)==0 ){
   42761         rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
   42762       }else{
   42763         rc = SQLITE_OK;
   42764       }
   42765     }
   42766 
   42767     /* Get the local shared locks */
   42768     if( rc==SQLITE_OK ){
   42769       p->sharedMask |= mask;
   42770     }
   42771   }else{
   42772     /* Make sure no sibling connections hold locks that will block this
   42773     ** lock.  If any do, return SQLITE_BUSY right away.
   42774     */
   42775     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   42776       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   42777         rc = SQLITE_BUSY;
   42778         break;
   42779       }
   42780     }
   42781 
   42782     /* Get the exclusive locks at the system level.  Then if successful
   42783     ** also mark the local connection as being locked.
   42784     */
   42785     if( rc==SQLITE_OK ){
   42786       rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
   42787       if( rc==SQLITE_OK ){
   42788         assert( (p->sharedMask & mask)==0 );
   42789         p->exclMask |= mask;
   42790       }
   42791     }
   42792   }
   42793   sqlite3_mutex_leave(pShmNode->mutex);
   42794   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
   42795            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
   42796            sqlite3ErrName(rc)));
   42797   return rc;
   42798 }
   42799 
   42800 /*
   42801 ** Implement a memory barrier or memory fence on shared memory.
   42802 **
   42803 ** All loads and stores begun before the barrier must complete before
   42804 ** any load or store begun after the barrier.
   42805 */
   42806 static void winShmBarrier(
   42807   sqlite3_file *fd          /* Database holding the shared memory */
   42808 ){
   42809   UNUSED_PARAMETER(fd);
   42810   sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
   42811   winShmEnterMutex();       /* Also mutex, for redundancy */
   42812   winShmLeaveMutex();
   42813 }
   42814 
   42815 /*
   42816 ** This function is called to obtain a pointer to region iRegion of the
   42817 ** shared-memory associated with the database file fd. Shared-memory regions
   42818 ** are numbered starting from zero. Each shared-memory region is szRegion
   42819 ** bytes in size.
   42820 **
   42821 ** If an error occurs, an error code is returned and *pp is set to NULL.
   42822 **
   42823 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
   42824 ** region has not been allocated (by any client, including one running in a
   42825 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   42826 ** isWrite is non-zero and the requested shared-memory region has not yet
   42827 ** been allocated, it is allocated by this function.
   42828 **
   42829 ** If the shared-memory region has already been allocated or is allocated by
   42830 ** this call as described above, then it is mapped into this processes
   42831 ** address space (if it is not already), *pp is set to point to the mapped
   42832 ** memory and SQLITE_OK returned.
   42833 */
   42834 static int winShmMap(
   42835   sqlite3_file *fd,               /* Handle open on database file */
   42836   int iRegion,                    /* Region to retrieve */
   42837   int szRegion,                   /* Size of regions */
   42838   int isWrite,                    /* True to extend file if necessary */
   42839   void volatile **pp              /* OUT: Mapped memory */
   42840 ){
   42841   winFile *pDbFd = (winFile*)fd;
   42842   winShm *pShm = pDbFd->pShm;
   42843   winShmNode *pShmNode;
   42844   DWORD protect = PAGE_READWRITE;
   42845   DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
   42846   int rc = SQLITE_OK;
   42847 
   42848   if( !pShm ){
   42849     rc = winOpenSharedMemory(pDbFd);
   42850     if( rc!=SQLITE_OK ) return rc;
   42851     pShm = pDbFd->pShm;
   42852   }
   42853   pShmNode = pShm->pShmNode;
   42854 
   42855   sqlite3_mutex_enter(pShmNode->mutex);
   42856   if( pShmNode->isUnlocked ){
   42857     rc = winLockSharedMemory(pShmNode);
   42858     if( rc!=SQLITE_OK ) goto shmpage_out;
   42859     pShmNode->isUnlocked = 0;
   42860   }
   42861   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   42862 
   42863   if( pShmNode->nRegion<=iRegion ){
   42864     struct ShmRegion *apNew;           /* New aRegion[] array */
   42865     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   42866     sqlite3_int64 sz;                  /* Current size of wal-index file */
   42867 
   42868     pShmNode->szRegion = szRegion;
   42869 
   42870     /* The requested region is not mapped into this processes address space.
   42871     ** Check to see if it has been allocated (i.e. if the wal-index file is
   42872     ** large enough to contain the requested region).
   42873     */
   42874     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
   42875     if( rc!=SQLITE_OK ){
   42876       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   42877                        "winShmMap1", pDbFd->zPath);
   42878       goto shmpage_out;
   42879     }
   42880 
   42881     if( sz<nByte ){
   42882       /* The requested memory region does not exist. If isWrite is set to
   42883       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
   42884       **
   42885       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
   42886       ** the requested memory region.
   42887       */
   42888       if( !isWrite ) goto shmpage_out;
   42889       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
   42890       if( rc!=SQLITE_OK ){
   42891         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   42892                          "winShmMap2", pDbFd->zPath);
   42893         goto shmpage_out;
   42894       }
   42895     }
   42896 
   42897     /* Map the requested memory region into this processes address space. */
   42898     apNew = (struct ShmRegion *)sqlite3_realloc64(
   42899         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
   42900     );
   42901     if( !apNew ){
   42902       rc = SQLITE_IOERR_NOMEM_BKPT;
   42903       goto shmpage_out;
   42904     }
   42905     pShmNode->aRegion = apNew;
   42906 
   42907     if( pShmNode->isReadonly ){
   42908       protect = PAGE_READONLY;
   42909       flags = FILE_MAP_READ;
   42910     }
   42911 
   42912     while( pShmNode->nRegion<=iRegion ){
   42913       HANDLE hMap = NULL;         /* file-mapping handle */
   42914       void *pMap = 0;             /* Mapped memory region */
   42915 
   42916 #if SQLITE_OS_WINRT
   42917       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
   42918           NULL, protect, nByte, NULL
   42919       );
   42920 #elif defined(SQLITE_WIN32_HAS_WIDE)
   42921       hMap = osCreateFileMappingW(pShmNode->hFile.h,
   42922           NULL, protect, 0, nByte, NULL
   42923       );
   42924 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
   42925       hMap = osCreateFileMappingA(pShmNode->hFile.h,
   42926           NULL, protect, 0, nByte, NULL
   42927       );
   42928 #endif
   42929       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
   42930                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
   42931                hMap ? "ok" : "failed"));
   42932       if( hMap ){
   42933         int iOffset = pShmNode->nRegion*szRegion;
   42934         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   42935 #if SQLITE_OS_WINRT
   42936         pMap = osMapViewOfFileFromApp(hMap, flags,
   42937             iOffset - iOffsetShift, szRegion + iOffsetShift
   42938         );
   42939 #else
   42940         pMap = osMapViewOfFile(hMap, flags,
   42941             0, iOffset - iOffsetShift, szRegion + iOffsetShift
   42942         );
   42943 #endif
   42944         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
   42945                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
   42946                  szRegion, pMap ? "ok" : "failed"));
   42947       }
   42948       if( !pMap ){
   42949         pShmNode->lastErrno = osGetLastError();
   42950         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
   42951                          "winShmMap3", pDbFd->zPath);
   42952         if( hMap ) osCloseHandle(hMap);
   42953         goto shmpage_out;
   42954       }
   42955 
   42956       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
   42957       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
   42958       pShmNode->nRegion++;
   42959     }
   42960   }
   42961 
   42962 shmpage_out:
   42963   if( pShmNode->nRegion>iRegion ){
   42964     int iOffset = iRegion*szRegion;
   42965     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   42966     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
   42967     *pp = (void *)&p[iOffsetShift];
   42968   }else{
   42969     *pp = 0;
   42970   }
   42971   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
   42972   sqlite3_mutex_leave(pShmNode->mutex);
   42973   return rc;
   42974 }
   42975 
   42976 #else
   42977 # define winShmMap     0
   42978 # define winShmLock    0
   42979 # define winShmBarrier 0
   42980 # define winShmUnmap   0
   42981 #endif /* #ifndef SQLITE_OMIT_WAL */
   42982 
   42983 /*
   42984 ** Cleans up the mapped region of the specified file, if any.
   42985 */
   42986 #if SQLITE_MAX_MMAP_SIZE>0
   42987 static int winUnmapfile(winFile *pFile){
   42988   assert( pFile!=0 );
   42989   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
   42990            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
   42991            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
   42992            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
   42993   if( pFile->pMapRegion ){
   42994     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
   42995       pFile->lastErrno = osGetLastError();
   42996       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
   42997                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
   42998                pFile->pMapRegion));
   42999       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
   43000                          "winUnmapfile1", pFile->zPath);
   43001     }
   43002     pFile->pMapRegion = 0;
   43003     pFile->mmapSize = 0;
   43004     pFile->mmapSizeActual = 0;
   43005   }
   43006   if( pFile->hMap!=NULL ){
   43007     if( !osCloseHandle(pFile->hMap) ){
   43008       pFile->lastErrno = osGetLastError();
   43009       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
   43010                osGetCurrentProcessId(), pFile, pFile->hMap));
   43011       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
   43012                          "winUnmapfile2", pFile->zPath);
   43013     }
   43014     pFile->hMap = NULL;
   43015   }
   43016   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   43017            osGetCurrentProcessId(), pFile));
   43018   return SQLITE_OK;
   43019 }
   43020 
   43021 /*
   43022 ** Memory map or remap the file opened by file-descriptor pFd (if the file
   43023 ** is already mapped, the existing mapping is replaced by the new). Or, if
   43024 ** there already exists a mapping for this file, and there are still
   43025 ** outstanding xFetch() references to it, this function is a no-op.
   43026 **
   43027 ** If parameter nByte is non-negative, then it is the requested size of
   43028 ** the mapping to create. Otherwise, if nByte is less than zero, then the
   43029 ** requested size is the size of the file on disk. The actual size of the
   43030 ** created mapping is either the requested size or the value configured
   43031 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
   43032 **
   43033 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
   43034 ** recreated as a result of outstanding references) or an SQLite error
   43035 ** code otherwise.
   43036 */
   43037 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
   43038   sqlite3_int64 nMap = nByte;
   43039   int rc;
   43040 
   43041   assert( nMap>=0 || pFd->nFetchOut==0 );
   43042   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
   43043            osGetCurrentProcessId(), pFd, nByte));
   43044 
   43045   if( pFd->nFetchOut>0 ) return SQLITE_OK;
   43046 
   43047   if( nMap<0 ){
   43048     rc = winFileSize((sqlite3_file*)pFd, &nMap);
   43049     if( rc ){
   43050       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
   43051                osGetCurrentProcessId(), pFd));
   43052       return SQLITE_IOERR_FSTAT;
   43053     }
   43054   }
   43055   if( nMap>pFd->mmapSizeMax ){
   43056     nMap = pFd->mmapSizeMax;
   43057   }
   43058   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
   43059 
   43060   if( nMap==0 && pFd->mmapSize>0 ){
   43061     winUnmapfile(pFd);
   43062   }
   43063   if( nMap!=pFd->mmapSize ){
   43064     void *pNew = 0;
   43065     DWORD protect = PAGE_READONLY;
   43066     DWORD flags = FILE_MAP_READ;
   43067 
   43068     winUnmapfile(pFd);
   43069 #ifdef SQLITE_MMAP_READWRITE
   43070     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
   43071       protect = PAGE_READWRITE;
   43072       flags |= FILE_MAP_WRITE;
   43073     }
   43074 #endif
   43075 #if SQLITE_OS_WINRT
   43076     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
   43077 #elif defined(SQLITE_WIN32_HAS_WIDE)
   43078     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
   43079                                 (DWORD)((nMap>>32) & 0xffffffff),
   43080                                 (DWORD)(nMap & 0xffffffff), NULL);
   43081 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
   43082     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
   43083                                 (DWORD)((nMap>>32) & 0xffffffff),
   43084                                 (DWORD)(nMap & 0xffffffff), NULL);
   43085 #endif
   43086     if( pFd->hMap==NULL ){
   43087       pFd->lastErrno = osGetLastError();
   43088       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
   43089                        "winMapfile1", pFd->zPath);
   43090       /* Log the error, but continue normal operation using xRead/xWrite */
   43091       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
   43092                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   43093       return SQLITE_OK;
   43094     }
   43095     assert( (nMap % winSysInfo.dwPageSize)==0 );
   43096     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
   43097 #if SQLITE_OS_WINRT
   43098     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
   43099 #else
   43100     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
   43101 #endif
   43102     if( pNew==NULL ){
   43103       osCloseHandle(pFd->hMap);
   43104       pFd->hMap = NULL;
   43105       pFd->lastErrno = osGetLastError();
   43106       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
   43107                        "winMapfile2", pFd->zPath);
   43108       /* Log the error, but continue normal operation using xRead/xWrite */
   43109       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
   43110                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   43111       return SQLITE_OK;
   43112     }
   43113     pFd->pMapRegion = pNew;
   43114     pFd->mmapSize = nMap;
   43115     pFd->mmapSizeActual = nMap;
   43116   }
   43117 
   43118   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   43119            osGetCurrentProcessId(), pFd));
   43120   return SQLITE_OK;
   43121 }
   43122 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   43123 
   43124 /*
   43125 ** If possible, return a pointer to a mapping of file fd starting at offset
   43126 ** iOff. The mapping must be valid for at least nAmt bytes.
   43127 **
   43128 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
   43129 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
   43130 ** Finally, if an error does occur, return an SQLite error code. The final
   43131 ** value of *pp is undefined in this case.
   43132 **
   43133 ** If this function does return a pointer, the caller must eventually
   43134 ** release the reference by calling winUnfetch().
   43135 */
   43136 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
   43137 #if SQLITE_MAX_MMAP_SIZE>0
   43138   winFile *pFd = (winFile*)fd;   /* The underlying database file */
   43139 #endif
   43140   *pp = 0;
   43141 
   43142   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
   43143            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
   43144 
   43145 #if SQLITE_MAX_MMAP_SIZE>0
   43146   if( pFd->mmapSizeMax>0 ){
   43147     if( pFd->pMapRegion==0 ){
   43148       int rc = winMapfile(pFd, -1);
   43149       if( rc!=SQLITE_OK ){
   43150         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
   43151                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
   43152         return rc;
   43153       }
   43154     }
   43155     if( pFd->mmapSize >= iOff+nAmt ){
   43156       *pp = &((u8 *)pFd->pMapRegion)[iOff];
   43157       pFd->nFetchOut++;
   43158     }
   43159   }
   43160 #endif
   43161 
   43162   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
   43163            osGetCurrentProcessId(), fd, pp, *pp));
   43164   return SQLITE_OK;
   43165 }
   43166 
   43167 /*
   43168 ** If the third argument is non-NULL, then this function releases a
   43169 ** reference obtained by an earlier call to winFetch(). The second
   43170 ** argument passed to this function must be the same as the corresponding
   43171 ** argument that was passed to the winFetch() invocation.
   43172 **
   43173 ** Or, if the third argument is NULL, then this function is being called
   43174 ** to inform the VFS layer that, according to POSIX, any existing mapping
   43175 ** may now be invalid and should be unmapped.
   43176 */
   43177 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
   43178 #if SQLITE_MAX_MMAP_SIZE>0
   43179   winFile *pFd = (winFile*)fd;   /* The underlying database file */
   43180 
   43181   /* If p==0 (unmap the entire file) then there must be no outstanding
   43182   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
   43183   ** then there must be at least one outstanding.  */
   43184   assert( (p==0)==(pFd->nFetchOut==0) );
   43185 
   43186   /* If p!=0, it must match the iOff value. */
   43187   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
   43188 
   43189   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
   43190            osGetCurrentProcessId(), pFd, iOff, p));
   43191 
   43192   if( p ){
   43193     pFd->nFetchOut--;
   43194   }else{
   43195     /* FIXME:  If Windows truly always prevents truncating or deleting a
   43196     ** file while a mapping is held, then the following winUnmapfile() call
   43197     ** is unnecessary can be omitted - potentially improving
   43198     ** performance.  */
   43199     winUnmapfile(pFd);
   43200   }
   43201 
   43202   assert( pFd->nFetchOut>=0 );
   43203 #endif
   43204 
   43205   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
   43206            osGetCurrentProcessId(), fd));
   43207   return SQLITE_OK;
   43208 }
   43209 
   43210 /*
   43211 ** Here ends the implementation of all sqlite3_file methods.
   43212 **
   43213 ********************** End sqlite3_file Methods *******************************
   43214 ******************************************************************************/
   43215 
   43216 /*
   43217 ** This vector defines all the methods that can operate on an
   43218 ** sqlite3_file for win32.
   43219 */
   43220 static const sqlite3_io_methods winIoMethod = {
   43221   3,                              /* iVersion */
   43222   winClose,                       /* xClose */
   43223   winRead,                        /* xRead */
   43224   winWrite,                       /* xWrite */
   43225   winTruncate,                    /* xTruncate */
   43226   winSync,                        /* xSync */
   43227   winFileSize,                    /* xFileSize */
   43228   winLock,                        /* xLock */
   43229   winUnlock,                      /* xUnlock */
   43230   winCheckReservedLock,           /* xCheckReservedLock */
   43231   winFileControl,                 /* xFileControl */
   43232   winSectorSize,                  /* xSectorSize */
   43233   winDeviceCharacteristics,       /* xDeviceCharacteristics */
   43234   winShmMap,                      /* xShmMap */
   43235   winShmLock,                     /* xShmLock */
   43236   winShmBarrier,                  /* xShmBarrier */
   43237   winShmUnmap,                    /* xShmUnmap */
   43238   winFetch,                       /* xFetch */
   43239   winUnfetch                      /* xUnfetch */
   43240 };
   43241 
   43242 /*
   43243 ** This vector defines all the methods that can operate on an
   43244 ** sqlite3_file for win32 without performing any locking.
   43245 */
   43246 static const sqlite3_io_methods winIoNolockMethod = {
   43247   3,                              /* iVersion */
   43248   winClose,                       /* xClose */
   43249   winRead,                        /* xRead */
   43250   winWrite,                       /* xWrite */
   43251   winTruncate,                    /* xTruncate */
   43252   winSync,                        /* xSync */
   43253   winFileSize,                    /* xFileSize */
   43254   winNolockLock,                  /* xLock */
   43255   winNolockUnlock,                /* xUnlock */
   43256   winNolockCheckReservedLock,     /* xCheckReservedLock */
   43257   winFileControl,                 /* xFileControl */
   43258   winSectorSize,                  /* xSectorSize */
   43259   winDeviceCharacteristics,       /* xDeviceCharacteristics */
   43260   winShmMap,                      /* xShmMap */
   43261   winShmLock,                     /* xShmLock */
   43262   winShmBarrier,                  /* xShmBarrier */
   43263   winShmUnmap,                    /* xShmUnmap */
   43264   winFetch,                       /* xFetch */
   43265   winUnfetch                      /* xUnfetch */
   43266 };
   43267 
   43268 static winVfsAppData winAppData = {
   43269   &winIoMethod,       /* pMethod */
   43270   0,                  /* pAppData */
   43271   0                   /* bNoLock */
   43272 };
   43273 
   43274 static winVfsAppData winNolockAppData = {
   43275   &winIoNolockMethod, /* pMethod */
   43276   0,                  /* pAppData */
   43277   1                   /* bNoLock */
   43278 };
   43279 
   43280 /****************************************************************************
   43281 **************************** sqlite3_vfs methods ****************************
   43282 **
   43283 ** This division contains the implementation of methods on the
   43284 ** sqlite3_vfs object.
   43285 */
   43286 
   43287 #if defined(__CYGWIN__)
   43288 /*
   43289 ** Convert a filename from whatever the underlying operating system
   43290 ** supports for filenames into UTF-8.  Space to hold the result is
   43291 ** obtained from malloc and must be freed by the calling function.
   43292 */
   43293 static char *winConvertToUtf8Filename(const void *zFilename){
   43294   char *zConverted = 0;
   43295   if( osIsNT() ){
   43296     zConverted = winUnicodeToUtf8(zFilename);
   43297   }
   43298 #ifdef SQLITE_WIN32_HAS_ANSI
   43299   else{
   43300     zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
   43301   }
   43302 #endif
   43303   /* caller will handle out of memory */
   43304   return zConverted;
   43305 }
   43306 #endif
   43307 
   43308 /*
   43309 ** Convert a UTF-8 filename into whatever form the underlying
   43310 ** operating system wants filenames in.  Space to hold the result
   43311 ** is obtained from malloc and must be freed by the calling
   43312 ** function.
   43313 */
   43314 static void *winConvertFromUtf8Filename(const char *zFilename){
   43315   void *zConverted = 0;
   43316   if( osIsNT() ){
   43317     zConverted = winUtf8ToUnicode(zFilename);
   43318   }
   43319 #ifdef SQLITE_WIN32_HAS_ANSI
   43320   else{
   43321     zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
   43322   }
   43323 #endif
   43324   /* caller will handle out of memory */
   43325   return zConverted;
   43326 }
   43327 
   43328 /*
   43329 ** This function returns non-zero if the specified UTF-8 string buffer
   43330 ** ends with a directory separator character or one was successfully
   43331 ** added to it.
   43332 */
   43333 static int winMakeEndInDirSep(int nBuf, char *zBuf){
   43334   if( zBuf ){
   43335     int nLen = sqlite3Strlen30(zBuf);
   43336     if( nLen>0 ){
   43337       if( winIsDirSep(zBuf[nLen-1]) ){
   43338         return 1;
   43339       }else if( nLen+1<nBuf ){
   43340         zBuf[nLen] = winGetDirSep();
   43341         zBuf[nLen+1] = '\0';
   43342         return 1;
   43343       }
   43344     }
   43345   }
   43346   return 0;
   43347 }
   43348 
   43349 /*
   43350 ** Create a temporary file name and store the resulting pointer into pzBuf.
   43351 ** The pointer returned in pzBuf must be freed via sqlite3_free().
   43352 */
   43353 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
   43354   static char zChars[] =
   43355     "abcdefghijklmnopqrstuvwxyz"
   43356     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   43357     "0123456789";
   43358   size_t i, j;
   43359   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
   43360   int nMax, nBuf, nDir, nLen;
   43361   char *zBuf;
   43362 
   43363   /* It's odd to simulate an io-error here, but really this is just
   43364   ** using the io-error infrastructure to test that SQLite handles this
   43365   ** function failing.
   43366   */
   43367   SimulateIOError( return SQLITE_IOERR );
   43368 
   43369   /* Allocate a temporary buffer to store the fully qualified file
   43370   ** name for the temporary file.  If this fails, we cannot continue.
   43371   */
   43372   nMax = pVfs->mxPathname; nBuf = nMax + 2;
   43373   zBuf = sqlite3MallocZero( nBuf );
   43374   if( !zBuf ){
   43375     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43376     return SQLITE_IOERR_NOMEM_BKPT;
   43377   }
   43378 
   43379   /* Figure out the effective temporary directory.  First, check if one
   43380   ** has been explicitly set by the application; otherwise, use the one
   43381   ** configured by the operating system.
   43382   */
   43383   nDir = nMax - (nPre + 15);
   43384   assert( nDir>0 );
   43385   if( sqlite3_temp_directory ){
   43386     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
   43387     if( nDirLen>0 ){
   43388       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
   43389         nDirLen++;
   43390       }
   43391       if( nDirLen>nDir ){
   43392         sqlite3_free(zBuf);
   43393         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   43394         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
   43395       }
   43396       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
   43397     }
   43398   }
   43399 #if defined(__CYGWIN__)
   43400   else{
   43401     static const char *azDirs[] = {
   43402        0, /* getenv("SQLITE_TMPDIR") */
   43403        0, /* getenv("TMPDIR") */
   43404        0, /* getenv("TMP") */
   43405        0, /* getenv("TEMP") */
   43406        0, /* getenv("USERPROFILE") */
   43407        "/var/tmp",
   43408        "/usr/tmp",
   43409        "/tmp",
   43410        ".",
   43411        0        /* List terminator */
   43412     };
   43413     unsigned int i;
   43414     const char *zDir = 0;
   43415 
   43416     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
   43417     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   43418     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
   43419     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
   43420     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
   43421     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   43422       void *zConverted;
   43423       if( zDir==0 ) continue;
   43424       /* If the path starts with a drive letter followed by the colon
   43425       ** character, assume it is already a native Win32 path; otherwise,
   43426       ** it must be converted to a native Win32 path via the Cygwin API
   43427       ** prior to using it.
   43428       */
   43429       if( winIsDriveLetterAndColon(zDir) ){
   43430         zConverted = winConvertFromUtf8Filename(zDir);
   43431         if( !zConverted ){
   43432           sqlite3_free(zBuf);
   43433           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43434           return SQLITE_IOERR_NOMEM_BKPT;
   43435         }
   43436         if( winIsDir(zConverted) ){
   43437           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
   43438           sqlite3_free(zConverted);
   43439           break;
   43440         }
   43441         sqlite3_free(zConverted);
   43442       }else{
   43443         zConverted = sqlite3MallocZero( nMax+1 );
   43444         if( !zConverted ){
   43445           sqlite3_free(zBuf);
   43446           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43447           return SQLITE_IOERR_NOMEM_BKPT;
   43448         }
   43449         if( cygwin_conv_path(
   43450                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
   43451                 zConverted, nMax+1)<0 ){
   43452           sqlite3_free(zConverted);
   43453           sqlite3_free(zBuf);
   43454           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
   43455           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
   43456                              "winGetTempname2", zDir);
   43457         }
   43458         if( winIsDir(zConverted) ){
   43459           /* At this point, we know the candidate directory exists and should
   43460           ** be used.  However, we may need to convert the string containing
   43461           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
   43462           */
   43463           char *zUtf8 = winConvertToUtf8Filename(zConverted);
   43464           if( !zUtf8 ){
   43465             sqlite3_free(zConverted);
   43466             sqlite3_free(zBuf);
   43467             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43468             return SQLITE_IOERR_NOMEM_BKPT;
   43469           }
   43470           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
   43471           sqlite3_free(zUtf8);
   43472           sqlite3_free(zConverted);
   43473           break;
   43474         }
   43475         sqlite3_free(zConverted);
   43476       }
   43477     }
   43478   }
   43479 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
   43480   else if( osIsNT() ){
   43481     char *zMulti;
   43482     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
   43483     if( !zWidePath ){
   43484       sqlite3_free(zBuf);
   43485       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43486       return SQLITE_IOERR_NOMEM_BKPT;
   43487     }
   43488     if( osGetTempPathW(nMax, zWidePath)==0 ){
   43489       sqlite3_free(zWidePath);
   43490       sqlite3_free(zBuf);
   43491       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
   43492       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
   43493                          "winGetTempname2", 0);
   43494     }
   43495     zMulti = winUnicodeToUtf8(zWidePath);
   43496     if( zMulti ){
   43497       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
   43498       sqlite3_free(zMulti);
   43499       sqlite3_free(zWidePath);
   43500     }else{
   43501       sqlite3_free(zWidePath);
   43502       sqlite3_free(zBuf);
   43503       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43504       return SQLITE_IOERR_NOMEM_BKPT;
   43505     }
   43506   }
   43507 #ifdef SQLITE_WIN32_HAS_ANSI
   43508   else{
   43509     char *zUtf8;
   43510     char *zMbcsPath = sqlite3MallocZero( nMax );
   43511     if( !zMbcsPath ){
   43512       sqlite3_free(zBuf);
   43513       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43514       return SQLITE_IOERR_NOMEM_BKPT;
   43515     }
   43516     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
   43517       sqlite3_free(zBuf);
   43518       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
   43519       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
   43520                          "winGetTempname3", 0);
   43521     }
   43522     zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
   43523     if( zUtf8 ){
   43524       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
   43525       sqlite3_free(zUtf8);
   43526     }else{
   43527       sqlite3_free(zBuf);
   43528       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
   43529       return SQLITE_IOERR_NOMEM_BKPT;
   43530     }
   43531   }
   43532 #endif /* SQLITE_WIN32_HAS_ANSI */
   43533 #endif /* !SQLITE_OS_WINRT */
   43534 
   43535   /*
   43536   ** Check to make sure the temporary directory ends with an appropriate
   43537   ** separator.  If it does not and there is not enough space left to add
   43538   ** one, fail.
   43539   */
   43540   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
   43541     sqlite3_free(zBuf);
   43542     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   43543     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
   43544   }
   43545 
   43546   /*
   43547   ** Check that the output buffer is large enough for the temporary file
   43548   ** name in the following format:
   43549   **
   43550   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
   43551   **
   43552   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
   43553   ** account for the space used by the 15 character random suffix and the
   43554   ** two trailing NUL characters.  The final directory separator character
   43555   ** has already added if it was not already present.
   43556   */
   43557   nLen = sqlite3Strlen30(zBuf);
   43558   if( (nLen + nPre + 17) > nBuf ){
   43559     sqlite3_free(zBuf);
   43560     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
   43561     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
   43562   }
   43563 
   43564   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
   43565 
   43566   j = sqlite3Strlen30(zBuf);
   43567   sqlite3_randomness(15, &zBuf[j]);
   43568   for(i=0; i<15; i++, j++){
   43569     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   43570   }
   43571   zBuf[j] = 0;
   43572   zBuf[j+1] = 0;
   43573   *pzBuf = zBuf;
   43574 
   43575   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
   43576   return SQLITE_OK;
   43577 }
   43578 
   43579 /*
   43580 ** Return TRUE if the named file is really a directory.  Return false if
   43581 ** it is something other than a directory, or if there is any kind of memory
   43582 ** allocation failure.
   43583 */
   43584 static int winIsDir(const void *zConverted){
   43585   DWORD attr;
   43586   int rc = 0;
   43587   DWORD lastErrno;
   43588 
   43589   if( osIsNT() ){
   43590     int cnt = 0;
   43591     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   43592     memset(&sAttrData, 0, sizeof(sAttrData));
   43593     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   43594                              GetFileExInfoStandard,
   43595                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
   43596     if( !rc ){
   43597       return 0; /* Invalid name? */
   43598     }
   43599     attr = sAttrData.dwFileAttributes;
   43600 #if SQLITE_OS_WINCE==0
   43601   }else{
   43602     attr = osGetFileAttributesA((char*)zConverted);
   43603 #endif
   43604   }
   43605   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
   43606 }
   43607 
   43608 /* forward reference */
   43609 static int winAccess(
   43610   sqlite3_vfs *pVfs,         /* Not used on win32 */
   43611   const char *zFilename,     /* Name of file to check */
   43612   int flags,                 /* Type of test to make on this file */
   43613   int *pResOut               /* OUT: Result */
   43614 );
   43615 
   43616 /*
   43617 ** Open a file.
   43618 */
   43619 static int winOpen(
   43620   sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
   43621   const char *zName,        /* Name of the file (UTF-8) */
   43622   sqlite3_file *id,         /* Write the SQLite file handle here */
   43623   int flags,                /* Open mode flags */
   43624   int *pOutFlags            /* Status return flags */
   43625 ){
   43626   HANDLE h;
   43627   DWORD lastErrno = 0;
   43628   DWORD dwDesiredAccess;
   43629   DWORD dwShareMode;
   43630   DWORD dwCreationDisposition;
   43631   DWORD dwFlagsAndAttributes = 0;
   43632 #if SQLITE_OS_WINCE
   43633   int isTemp = 0;
   43634 #endif
   43635   winVfsAppData *pAppData;
   43636   winFile *pFile = (winFile*)id;
   43637   void *zConverted;              /* Filename in OS encoding */
   43638   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
   43639   int cnt = 0;
   43640 
   43641   /* If argument zPath is a NULL pointer, this function is required to open
   43642   ** a temporary file. Use this buffer to store the file name in.
   43643   */
   43644   char *zTmpname = 0; /* For temporary filename, if necessary. */
   43645 
   43646   int rc = SQLITE_OK;            /* Function Return Code */
   43647 #if !defined(NDEBUG) || SQLITE_OS_WINCE
   43648   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   43649 #endif
   43650 
   43651   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   43652   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   43653   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   43654   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   43655   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   43656 
   43657 #ifndef NDEBUG
   43658   int isOpenJournal = (isCreate && (
   43659         eType==SQLITE_OPEN_MASTER_JOURNAL
   43660      || eType==SQLITE_OPEN_MAIN_JOURNAL
   43661      || eType==SQLITE_OPEN_WAL
   43662   ));
   43663 #endif
   43664 
   43665   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
   43666            zUtf8Name, id, flags, pOutFlags));
   43667 
   43668   /* Check the following statements are true:
   43669   **
   43670   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   43671   **   (b) if CREATE is set, then READWRITE must also be set, and
   43672   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   43673   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   43674   */
   43675   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   43676   assert(isCreate==0 || isReadWrite);
   43677   assert(isExclusive==0 || isCreate);
   43678   assert(isDelete==0 || isCreate);
   43679 
   43680   /* The main DB, main journal, WAL file and master journal are never
   43681   ** automatically deleted. Nor are they ever temporary files.  */
   43682   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   43683   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   43684   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   43685   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   43686 
   43687   /* Assert that the upper layer has set one of the "file-type" flags. */
   43688   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   43689        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   43690        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   43691        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   43692   );
   43693 
   43694   assert( pFile!=0 );
   43695   memset(pFile, 0, sizeof(winFile));
   43696   pFile->h = INVALID_HANDLE_VALUE;
   43697 
   43698 #if SQLITE_OS_WINRT
   43699   if( !zUtf8Name && !sqlite3_temp_directory ){
   43700     sqlite3_log(SQLITE_ERROR,
   43701         "sqlite3_temp_directory variable should be set for WinRT");
   43702   }
   43703 #endif
   43704 
   43705   /* If the second argument to this function is NULL, generate a
   43706   ** temporary file name to use
   43707   */
   43708   if( !zUtf8Name ){
   43709     assert( isDelete && !isOpenJournal );
   43710     rc = winGetTempname(pVfs, &zTmpname);
   43711     if( rc!=SQLITE_OK ){
   43712       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
   43713       return rc;
   43714     }
   43715     zUtf8Name = zTmpname;
   43716   }
   43717 
   43718   /* Database filenames are double-zero terminated if they are not
   43719   ** URIs with parameters.  Hence, they can always be passed into
   43720   ** sqlite3_uri_parameter().
   43721   */
   43722   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
   43723        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
   43724 
   43725   /* Convert the filename to the system encoding. */
   43726   zConverted = winConvertFromUtf8Filename(zUtf8Name);
   43727   if( zConverted==0 ){
   43728     sqlite3_free(zTmpname);
   43729     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
   43730     return SQLITE_IOERR_NOMEM_BKPT;
   43731   }
   43732 
   43733   if( winIsDir(zConverted) ){
   43734     sqlite3_free(zConverted);
   43735     sqlite3_free(zTmpname);
   43736     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
   43737     return SQLITE_CANTOPEN_ISDIR;
   43738   }
   43739 
   43740   if( isReadWrite ){
   43741     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
   43742   }else{
   43743     dwDesiredAccess = GENERIC_READ;
   43744   }
   43745 
   43746   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   43747   ** created. SQLite doesn't use it to indicate "exclusive access"
   43748   ** as it is usually understood.
   43749   */
   43750   if( isExclusive ){
   43751     /* Creates a new file, only if it does not already exist. */
   43752     /* If the file exists, it fails. */
   43753     dwCreationDisposition = CREATE_NEW;
   43754   }else if( isCreate ){
   43755     /* Open existing file, or create if it doesn't exist */
   43756     dwCreationDisposition = OPEN_ALWAYS;
   43757   }else{
   43758     /* Opens a file, only if it exists. */
   43759     dwCreationDisposition = OPEN_EXISTING;
   43760   }
   43761 
   43762   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
   43763 
   43764   if( isDelete ){
   43765 #if SQLITE_OS_WINCE
   43766     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
   43767     isTemp = 1;
   43768 #else
   43769     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
   43770                                | FILE_ATTRIBUTE_HIDDEN
   43771                                | FILE_FLAG_DELETE_ON_CLOSE;
   43772 #endif
   43773   }else{
   43774     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
   43775   }
   43776   /* Reports from the internet are that performance is always
   43777   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
   43778 #if SQLITE_OS_WINCE
   43779   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
   43780 #endif
   43781 
   43782   if( osIsNT() ){
   43783 #if SQLITE_OS_WINRT
   43784     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
   43785     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
   43786     extendedParameters.dwFileAttributes =
   43787             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
   43788     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
   43789     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
   43790     extendedParameters.lpSecurityAttributes = NULL;
   43791     extendedParameters.hTemplateFile = NULL;
   43792     do{
   43793       h = osCreateFile2((LPCWSTR)zConverted,
   43794                         dwDesiredAccess,
   43795                         dwShareMode,
   43796                         dwCreationDisposition,
   43797                         &extendedParameters);
   43798       if( h!=INVALID_HANDLE_VALUE ) break;
   43799       if( isReadWrite ){
   43800         int rc2, isRO = 0;
   43801         sqlite3BeginBenignMalloc();
   43802         rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
   43803         sqlite3EndBenignMalloc();
   43804         if( rc2==SQLITE_OK && isRO ) break;
   43805       }
   43806     }while( winRetryIoerr(&cnt, &lastErrno) );
   43807 #else
   43808     do{
   43809       h = osCreateFileW((LPCWSTR)zConverted,
   43810                         dwDesiredAccess,
   43811                         dwShareMode, NULL,
   43812                         dwCreationDisposition,
   43813                         dwFlagsAndAttributes,
   43814                         NULL);
   43815       if( h!=INVALID_HANDLE_VALUE ) break;
   43816       if( isReadWrite ){
   43817         int rc2, isRO = 0;
   43818         sqlite3BeginBenignMalloc();
   43819         rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
   43820         sqlite3EndBenignMalloc();
   43821         if( rc2==SQLITE_OK && isRO ) break;
   43822       }
   43823     }while( winRetryIoerr(&cnt, &lastErrno) );
   43824 #endif
   43825   }
   43826 #ifdef SQLITE_WIN32_HAS_ANSI
   43827   else{
   43828     do{
   43829       h = osCreateFileA((LPCSTR)zConverted,
   43830                         dwDesiredAccess,
   43831                         dwShareMode, NULL,
   43832                         dwCreationDisposition,
   43833                         dwFlagsAndAttributes,
   43834                         NULL);
   43835       if( h!=INVALID_HANDLE_VALUE ) break;
   43836       if( isReadWrite ){
   43837         int rc2, isRO = 0;
   43838         sqlite3BeginBenignMalloc();
   43839         rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
   43840         sqlite3EndBenignMalloc();
   43841         if( rc2==SQLITE_OK && isRO ) break;
   43842       }
   43843     }while( winRetryIoerr(&cnt, &lastErrno) );
   43844   }
   43845 #endif
   43846   winLogIoerr(cnt, __LINE__);
   43847 
   43848   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
   43849            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
   43850 
   43851   if( h==INVALID_HANDLE_VALUE ){
   43852     sqlite3_free(zConverted);
   43853     sqlite3_free(zTmpname);
   43854     if( isReadWrite && !isExclusive ){
   43855       return winOpen(pVfs, zName, id,
   43856          ((flags|SQLITE_OPEN_READONLY) &
   43857                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
   43858          pOutFlags);
   43859     }else{
   43860       pFile->lastErrno = lastErrno;
   43861       winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
   43862       return SQLITE_CANTOPEN_BKPT;
   43863     }
   43864   }
   43865 
   43866   if( pOutFlags ){
   43867     if( isReadWrite ){
   43868       *pOutFlags = SQLITE_OPEN_READWRITE;
   43869     }else{
   43870       *pOutFlags = SQLITE_OPEN_READONLY;
   43871     }
   43872   }
   43873 
   43874   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
   43875            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
   43876            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
   43877 
   43878   pAppData = (winVfsAppData*)pVfs->pAppData;
   43879 
   43880 #if SQLITE_OS_WINCE
   43881   {
   43882     if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
   43883          && ((pAppData==NULL) || !pAppData->bNoLock)
   43884          && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
   43885     ){
   43886       osCloseHandle(h);
   43887       sqlite3_free(zConverted);
   43888       sqlite3_free(zTmpname);
   43889       OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
   43890       return rc;
   43891     }
   43892   }
   43893   if( isTemp ){
   43894     pFile->zDeleteOnClose = zConverted;
   43895   }else
   43896 #endif
   43897   {
   43898     sqlite3_free(zConverted);
   43899   }
   43900 
   43901   sqlite3_free(zTmpname);
   43902   pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
   43903   pFile->pVfs = pVfs;
   43904   pFile->h = h;
   43905   if( isReadonly ){
   43906     pFile->ctrlFlags |= WINFILE_RDONLY;
   43907   }
   43908   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   43909     pFile->ctrlFlags |= WINFILE_PSOW;
   43910   }
   43911   pFile->lastErrno = NO_ERROR;
   43912   pFile->zPath = zName;
   43913 #if SQLITE_MAX_MMAP_SIZE>0
   43914   pFile->hMap = NULL;
   43915   pFile->pMapRegion = 0;
   43916   pFile->mmapSize = 0;
   43917   pFile->mmapSizeActual = 0;
   43918   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
   43919 #endif
   43920 
   43921   OpenCounter(+1);
   43922   return rc;
   43923 }
   43924 
   43925 /*
   43926 ** Delete the named file.
   43927 **
   43928 ** Note that Windows does not allow a file to be deleted if some other
   43929 ** process has it open.  Sometimes a virus scanner or indexing program
   43930 ** will open a journal file shortly after it is created in order to do
   43931 ** whatever it does.  While this other process is holding the
   43932 ** file open, we will be unable to delete it.  To work around this
   43933 ** problem, we delay 100 milliseconds and try to delete again.  Up
   43934 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
   43935 ** up and returning an error.
   43936 */
   43937 static int winDelete(
   43938   sqlite3_vfs *pVfs,          /* Not used on win32 */
   43939   const char *zFilename,      /* Name of file to delete */
   43940   int syncDir                 /* Not used on win32 */
   43941 ){
   43942   int cnt = 0;
   43943   int rc;
   43944   DWORD attr;
   43945   DWORD lastErrno = 0;
   43946   void *zConverted;
   43947   UNUSED_PARAMETER(pVfs);
   43948   UNUSED_PARAMETER(syncDir);
   43949 
   43950   SimulateIOError(return SQLITE_IOERR_DELETE);
   43951   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
   43952 
   43953   zConverted = winConvertFromUtf8Filename(zFilename);
   43954   if( zConverted==0 ){
   43955     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
   43956     return SQLITE_IOERR_NOMEM_BKPT;
   43957   }
   43958   if( osIsNT() ){
   43959     do {
   43960 #if SQLITE_OS_WINRT
   43961       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   43962       memset(&sAttrData, 0, sizeof(sAttrData));
   43963       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
   43964                                   &sAttrData) ){
   43965         attr = sAttrData.dwFileAttributes;
   43966       }else{
   43967         lastErrno = osGetLastError();
   43968         if( lastErrno==ERROR_FILE_NOT_FOUND
   43969          || lastErrno==ERROR_PATH_NOT_FOUND ){
   43970           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   43971         }else{
   43972           rc = SQLITE_ERROR;
   43973         }
   43974         break;
   43975       }
   43976 #else
   43977       attr = osGetFileAttributesW(zConverted);
   43978 #endif
   43979       if ( attr==INVALID_FILE_ATTRIBUTES ){
   43980         lastErrno = osGetLastError();
   43981         if( lastErrno==ERROR_FILE_NOT_FOUND
   43982          || lastErrno==ERROR_PATH_NOT_FOUND ){
   43983           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   43984         }else{
   43985           rc = SQLITE_ERROR;
   43986         }
   43987         break;
   43988       }
   43989       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
   43990         rc = SQLITE_ERROR; /* Files only. */
   43991         break;
   43992       }
   43993       if ( osDeleteFileW(zConverted) ){
   43994         rc = SQLITE_OK; /* Deleted OK. */
   43995         break;
   43996       }
   43997       if ( !winRetryIoerr(&cnt, &lastErrno) ){
   43998         rc = SQLITE_ERROR; /* No more retries. */
   43999         break;
   44000       }
   44001     } while(1);
   44002   }
   44003 #ifdef SQLITE_WIN32_HAS_ANSI
   44004   else{
   44005     do {
   44006       attr = osGetFileAttributesA(zConverted);
   44007       if ( attr==INVALID_FILE_ATTRIBUTES ){
   44008         lastErrno = osGetLastError();
   44009         if( lastErrno==ERROR_FILE_NOT_FOUND
   44010          || lastErrno==ERROR_PATH_NOT_FOUND ){
   44011           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
   44012         }else{
   44013           rc = SQLITE_ERROR;
   44014         }
   44015         break;
   44016       }
   44017       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
   44018         rc = SQLITE_ERROR; /* Files only. */
   44019         break;
   44020       }
   44021       if ( osDeleteFileA(zConverted) ){
   44022         rc = SQLITE_OK; /* Deleted OK. */
   44023         break;
   44024       }
   44025       if ( !winRetryIoerr(&cnt, &lastErrno) ){
   44026         rc = SQLITE_ERROR; /* No more retries. */
   44027         break;
   44028       }
   44029     } while(1);
   44030   }
   44031 #endif
   44032   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
   44033     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
   44034   }else{
   44035     winLogIoerr(cnt, __LINE__);
   44036   }
   44037   sqlite3_free(zConverted);
   44038   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
   44039   return rc;
   44040 }
   44041 
   44042 /*
   44043 ** Check the existence and status of a file.
   44044 */
   44045 static int winAccess(
   44046   sqlite3_vfs *pVfs,         /* Not used on win32 */
   44047   const char *zFilename,     /* Name of file to check */
   44048   int flags,                 /* Type of test to make on this file */
   44049   int *pResOut               /* OUT: Result */
   44050 ){
   44051   DWORD attr;
   44052   int rc = 0;
   44053   DWORD lastErrno = 0;
   44054   void *zConverted;
   44055   UNUSED_PARAMETER(pVfs);
   44056 
   44057   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   44058   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
   44059            zFilename, flags, pResOut));
   44060 
   44061   zConverted = winConvertFromUtf8Filename(zFilename);
   44062   if( zConverted==0 ){
   44063     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
   44064     return SQLITE_IOERR_NOMEM_BKPT;
   44065   }
   44066   if( osIsNT() ){
   44067     int cnt = 0;
   44068     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   44069     memset(&sAttrData, 0, sizeof(sAttrData));
   44070     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   44071                              GetFileExInfoStandard,
   44072                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
   44073     if( rc ){
   44074       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
   44075       ** as if it does not exist.
   44076       */
   44077       if(    flags==SQLITE_ACCESS_EXISTS
   44078           && sAttrData.nFileSizeHigh==0
   44079           && sAttrData.nFileSizeLow==0 ){
   44080         attr = INVALID_FILE_ATTRIBUTES;
   44081       }else{
   44082         attr = sAttrData.dwFileAttributes;
   44083       }
   44084     }else{
   44085       winLogIoerr(cnt, __LINE__);
   44086       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
   44087         sqlite3_free(zConverted);
   44088         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
   44089                            zFilename);
   44090       }else{
   44091         attr = INVALID_FILE_ATTRIBUTES;
   44092       }
   44093     }
   44094   }
   44095 #ifdef SQLITE_WIN32_HAS_ANSI
   44096   else{
   44097     attr = osGetFileAttributesA((char*)zConverted);
   44098   }
   44099 #endif
   44100   sqlite3_free(zConverted);
   44101   switch( flags ){
   44102     case SQLITE_ACCESS_READ:
   44103     case SQLITE_ACCESS_EXISTS:
   44104       rc = attr!=INVALID_FILE_ATTRIBUTES;
   44105       break;
   44106     case SQLITE_ACCESS_READWRITE:
   44107       rc = attr!=INVALID_FILE_ATTRIBUTES &&
   44108              (attr & FILE_ATTRIBUTE_READONLY)==0;
   44109       break;
   44110     default:
   44111       assert(!"Invalid flags argument");
   44112   }
   44113   *pResOut = rc;
   44114   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
   44115            zFilename, pResOut, *pResOut));
   44116   return SQLITE_OK;
   44117 }
   44118 
   44119 /*
   44120 ** Returns non-zero if the specified path name starts with a drive letter
   44121 ** followed by a colon character.
   44122 */
   44123 static BOOL winIsDriveLetterAndColon(
   44124   const char *zPathname
   44125 ){
   44126   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
   44127 }
   44128 
   44129 /*
   44130 ** Returns non-zero if the specified path name should be used verbatim.  If
   44131 ** non-zero is returned from this function, the calling function must simply
   44132 ** use the provided path name verbatim -OR- resolve it into a full path name
   44133 ** using the GetFullPathName Win32 API function (if available).
   44134 */
   44135 static BOOL winIsVerbatimPathname(
   44136   const char *zPathname
   44137 ){
   44138   /*
   44139   ** If the path name starts with a forward slash or a backslash, it is either
   44140   ** a legal UNC name, a volume relative path, or an absolute path name in the
   44141   ** "Unix" format on Windows.  There is no easy way to differentiate between
   44142   ** the final two cases; therefore, we return the safer return value of TRUE
   44143   ** so that callers of this function will simply use it verbatim.
   44144   */
   44145   if ( winIsDirSep(zPathname[0]) ){
   44146     return TRUE;
   44147   }
   44148 
   44149   /*
   44150   ** If the path name starts with a letter and a colon it is either a volume
   44151   ** relative path or an absolute path.  Callers of this function must not
   44152   ** attempt to treat it as a relative path name (i.e. they should simply use
   44153   ** it verbatim).
   44154   */
   44155   if ( winIsDriveLetterAndColon(zPathname) ){
   44156     return TRUE;
   44157   }
   44158 
   44159   /*
   44160   ** If we get to this point, the path name should almost certainly be a purely
   44161   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
   44162   */
   44163   return FALSE;
   44164 }
   44165 
   44166 /*
   44167 ** Turn a relative pathname into a full pathname.  Write the full
   44168 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
   44169 ** bytes in size.
   44170 */
   44171 static int winFullPathname(
   44172   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   44173   const char *zRelative,        /* Possibly relative input path */
   44174   int nFull,                    /* Size of output buffer in bytes */
   44175   char *zFull                   /* Output buffer */
   44176 ){
   44177 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
   44178   DWORD nByte;
   44179   void *zConverted;
   44180   char *zOut;
   44181 #endif
   44182 
   44183   /* If this path name begins with "/X:", where "X" is any alphabetic
   44184   ** character, discard the initial "/" from the pathname.
   44185   */
   44186   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
   44187     zRelative++;
   44188   }
   44189 
   44190 #if defined(__CYGWIN__)
   44191   SimulateIOError( return SQLITE_ERROR );
   44192   UNUSED_PARAMETER(nFull);
   44193   assert( nFull>=pVfs->mxPathname );
   44194   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   44195     /*
   44196     ** NOTE: We are dealing with a relative path name and the data
   44197     **       directory has been set.  Therefore, use it as the basis
   44198     **       for converting the relative path name to an absolute
   44199     **       one by prepending the data directory and a slash.
   44200     */
   44201     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
   44202     if( !zOut ){
   44203       return SQLITE_IOERR_NOMEM_BKPT;
   44204     }
   44205     if( cygwin_conv_path(
   44206             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
   44207             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
   44208       sqlite3_free(zOut);
   44209       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
   44210                          "winFullPathname1", zRelative);
   44211     }else{
   44212       char *zUtf8 = winConvertToUtf8Filename(zOut);
   44213       if( !zUtf8 ){
   44214         sqlite3_free(zOut);
   44215         return SQLITE_IOERR_NOMEM_BKPT;
   44216       }
   44217       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   44218                        sqlite3_data_directory, winGetDirSep(), zUtf8);
   44219       sqlite3_free(zUtf8);
   44220       sqlite3_free(zOut);
   44221     }
   44222   }else{
   44223     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
   44224     if( !zOut ){
   44225       return SQLITE_IOERR_NOMEM_BKPT;
   44226     }
   44227     if( cygwin_conv_path(
   44228             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
   44229             zRelative, zOut, pVfs->mxPathname+1)<0 ){
   44230       sqlite3_free(zOut);
   44231       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
   44232                          "winFullPathname2", zRelative);
   44233     }else{
   44234       char *zUtf8 = winConvertToUtf8Filename(zOut);
   44235       if( !zUtf8 ){
   44236         sqlite3_free(zOut);
   44237         return SQLITE_IOERR_NOMEM_BKPT;
   44238       }
   44239       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
   44240       sqlite3_free(zUtf8);
   44241       sqlite3_free(zOut);
   44242     }
   44243   }
   44244   return SQLITE_OK;
   44245 #endif
   44246 
   44247 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
   44248   SimulateIOError( return SQLITE_ERROR );
   44249   /* WinCE has no concept of a relative pathname, or so I am told. */
   44250   /* WinRT has no way to convert a relative path to an absolute one. */
   44251   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   44252     /*
   44253     ** NOTE: We are dealing with a relative path name and the data
   44254     **       directory has been set.  Therefore, use it as the basis
   44255     **       for converting the relative path name to an absolute
   44256     **       one by prepending the data directory and a backslash.
   44257     */
   44258     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   44259                      sqlite3_data_directory, winGetDirSep(), zRelative);
   44260   }else{
   44261     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
   44262   }
   44263   return SQLITE_OK;
   44264 #endif
   44265 
   44266 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
   44267   /* It's odd to simulate an io-error here, but really this is just
   44268   ** using the io-error infrastructure to test that SQLite handles this
   44269   ** function failing. This function could fail if, for example, the
   44270   ** current working directory has been unlinked.
   44271   */
   44272   SimulateIOError( return SQLITE_ERROR );
   44273   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
   44274     /*
   44275     ** NOTE: We are dealing with a relative path name and the data
   44276     **       directory has been set.  Therefore, use it as the basis
   44277     **       for converting the relative path name to an absolute
   44278     **       one by prepending the data directory and a backslash.
   44279     */
   44280     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
   44281                      sqlite3_data_directory, winGetDirSep(), zRelative);
   44282     return SQLITE_OK;
   44283   }
   44284   zConverted = winConvertFromUtf8Filename(zRelative);
   44285   if( zConverted==0 ){
   44286     return SQLITE_IOERR_NOMEM_BKPT;
   44287   }
   44288   if( osIsNT() ){
   44289     LPWSTR zTemp;
   44290     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
   44291     if( nByte==0 ){
   44292       sqlite3_free(zConverted);
   44293       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   44294                          "winFullPathname1", zRelative);
   44295     }
   44296     nByte += 3;
   44297     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
   44298     if( zTemp==0 ){
   44299       sqlite3_free(zConverted);
   44300       return SQLITE_IOERR_NOMEM_BKPT;
   44301     }
   44302     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
   44303     if( nByte==0 ){
   44304       sqlite3_free(zConverted);
   44305       sqlite3_free(zTemp);
   44306       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   44307                          "winFullPathname2", zRelative);
   44308     }
   44309     sqlite3_free(zConverted);
   44310     zOut = winUnicodeToUtf8(zTemp);
   44311     sqlite3_free(zTemp);
   44312   }
   44313 #ifdef SQLITE_WIN32_HAS_ANSI
   44314   else{
   44315     char *zTemp;
   44316     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
   44317     if( nByte==0 ){
   44318       sqlite3_free(zConverted);
   44319       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   44320                          "winFullPathname3", zRelative);
   44321     }
   44322     nByte += 3;
   44323     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
   44324     if( zTemp==0 ){
   44325       sqlite3_free(zConverted);
   44326       return SQLITE_IOERR_NOMEM_BKPT;
   44327     }
   44328     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
   44329     if( nByte==0 ){
   44330       sqlite3_free(zConverted);
   44331       sqlite3_free(zTemp);
   44332       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
   44333                          "winFullPathname4", zRelative);
   44334     }
   44335     sqlite3_free(zConverted);
   44336     zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
   44337     sqlite3_free(zTemp);
   44338   }
   44339 #endif
   44340   if( zOut ){
   44341     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
   44342     sqlite3_free(zOut);
   44343     return SQLITE_OK;
   44344   }else{
   44345     return SQLITE_IOERR_NOMEM_BKPT;
   44346   }
   44347 #endif
   44348 }
   44349 
   44350 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   44351 /*
   44352 ** Interfaces for opening a shared library, finding entry points
   44353 ** within the shared library, and closing the shared library.
   44354 */
   44355 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   44356   HANDLE h;
   44357 #if defined(__CYGWIN__)
   44358   int nFull = pVfs->mxPathname+1;
   44359   char *zFull = sqlite3MallocZero( nFull );
   44360   void *zConverted = 0;
   44361   if( zFull==0 ){
   44362     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   44363     return 0;
   44364   }
   44365   if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
   44366     sqlite3_free(zFull);
   44367     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   44368     return 0;
   44369   }
   44370   zConverted = winConvertFromUtf8Filename(zFull);
   44371   sqlite3_free(zFull);
   44372 #else
   44373   void *zConverted = winConvertFromUtf8Filename(zFilename);
   44374   UNUSED_PARAMETER(pVfs);
   44375 #endif
   44376   if( zConverted==0 ){
   44377     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
   44378     return 0;
   44379   }
   44380   if( osIsNT() ){
   44381 #if SQLITE_OS_WINRT
   44382     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
   44383 #else
   44384     h = osLoadLibraryW((LPCWSTR)zConverted);
   44385 #endif
   44386   }
   44387 #ifdef SQLITE_WIN32_HAS_ANSI
   44388   else{
   44389     h = osLoadLibraryA((char*)zConverted);
   44390   }
   44391 #endif
   44392   OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
   44393   sqlite3_free(zConverted);
   44394   return (void*)h;
   44395 }
   44396 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   44397   UNUSED_PARAMETER(pVfs);
   44398   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
   44399 }
   44400 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
   44401   FARPROC proc;
   44402   UNUSED_PARAMETER(pVfs);
   44403   proc = osGetProcAddressA((HANDLE)pH, zSym);
   44404   OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
   44405            (void*)pH, zSym, (void*)proc));
   44406   return (void(*)(void))proc;
   44407 }
   44408 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
   44409   UNUSED_PARAMETER(pVfs);
   44410   osFreeLibrary((HANDLE)pHandle);
   44411   OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
   44412 }
   44413 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   44414   #define winDlOpen  0
   44415   #define winDlError 0
   44416   #define winDlSym   0
   44417   #define winDlClose 0
   44418 #endif
   44419 
   44420 /* State information for the randomness gatherer. */
   44421 typedef struct EntropyGatherer EntropyGatherer;
   44422 struct EntropyGatherer {
   44423   unsigned char *a;   /* Gather entropy into this buffer */
   44424   int na;             /* Size of a[] in bytes */
   44425   int i;              /* XOR next input into a[i] */
   44426   int nXor;           /* Number of XOR operations done */
   44427 };
   44428 
   44429 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
   44430 /* Mix sz bytes of entropy into p. */
   44431 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
   44432   int j, k;
   44433   for(j=0, k=p->i; j<sz; j++){
   44434     p->a[k++] ^= x[j];
   44435     if( k>=p->na ) k = 0;
   44436   }
   44437   p->i = k;
   44438   p->nXor += sz;
   44439 }
   44440 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
   44441 
   44442 /*
   44443 ** Write up to nBuf bytes of randomness into zBuf.
   44444 */
   44445 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   44446 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
   44447   UNUSED_PARAMETER(pVfs);
   44448   memset(zBuf, 0, nBuf);
   44449   return nBuf;
   44450 #else
   44451   EntropyGatherer e;
   44452   UNUSED_PARAMETER(pVfs);
   44453   memset(zBuf, 0, nBuf);
   44454   e.a = (unsigned char*)zBuf;
   44455   e.na = nBuf;
   44456   e.nXor = 0;
   44457   e.i = 0;
   44458   {
   44459     SYSTEMTIME x;
   44460     osGetSystemTime(&x);
   44461     xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
   44462   }
   44463   {
   44464     DWORD pid = osGetCurrentProcessId();
   44465     xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
   44466   }
   44467 #if SQLITE_OS_WINRT
   44468   {
   44469     ULONGLONG cnt = osGetTickCount64();
   44470     xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
   44471   }
   44472 #else
   44473   {
   44474     DWORD cnt = osGetTickCount();
   44475     xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
   44476   }
   44477 #endif /* SQLITE_OS_WINRT */
   44478   {
   44479     LARGE_INTEGER i;
   44480     osQueryPerformanceCounter(&i);
   44481     xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
   44482   }
   44483 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
   44484   {
   44485     UUID id;
   44486     memset(&id, 0, sizeof(UUID));
   44487     osUuidCreate(&id);
   44488     xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
   44489     memset(&id, 0, sizeof(UUID));
   44490     osUuidCreateSequential(&id);
   44491     xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
   44492   }
   44493 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
   44494   return e.nXor>nBuf ? nBuf : e.nXor;
   44495 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
   44496 }
   44497 
   44498 
   44499 /*
   44500 ** Sleep for a little while.  Return the amount of time slept.
   44501 */
   44502 static int winSleep(sqlite3_vfs *pVfs, int microsec){
   44503   sqlite3_win32_sleep((microsec+999)/1000);
   44504   UNUSED_PARAMETER(pVfs);
   44505   return ((microsec+999)/1000)*1000;
   44506 }
   44507 
   44508 /*
   44509 ** The following variable, if set to a non-zero value, is interpreted as
   44510 ** the number of seconds since 1970 and is used to set the result of
   44511 ** sqlite3OsCurrentTime() during testing.
   44512 */
   44513 #ifdef SQLITE_TEST
   44514 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   44515 #endif
   44516 
   44517 /*
   44518 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   44519 ** the current time and date as a Julian Day number times 86_400_000.  In
   44520 ** other words, write into *piNow the number of milliseconds since the Julian
   44521 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   44522 ** proleptic Gregorian calendar.
   44523 **
   44524 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   44525 ** cannot be found.
   44526 */
   44527 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
   44528   /* FILETIME structure is a 64-bit value representing the number of
   44529      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
   44530   */
   44531   FILETIME ft;
   44532   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
   44533 #ifdef SQLITE_TEST
   44534   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   44535 #endif
   44536   /* 2^32 - to avoid use of LL and warnings in gcc */
   44537   static const sqlite3_int64 max32BitValue =
   44538       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
   44539       (sqlite3_int64)294967296;
   44540 
   44541 #if SQLITE_OS_WINCE
   44542   SYSTEMTIME time;
   44543   osGetSystemTime(&time);
   44544   /* if SystemTimeToFileTime() fails, it returns zero. */
   44545   if (!osSystemTimeToFileTime(&time,&ft)){
   44546     return SQLITE_ERROR;
   44547   }
   44548 #else
   44549   osGetSystemTimeAsFileTime( &ft );
   44550 #endif
   44551 
   44552   *piNow = winFiletimeEpoch +
   44553             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
   44554                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
   44555 
   44556 #ifdef SQLITE_TEST
   44557   if( sqlite3_current_time ){
   44558     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   44559   }
   44560 #endif
   44561   UNUSED_PARAMETER(pVfs);
   44562   return SQLITE_OK;
   44563 }
   44564 
   44565 /*
   44566 ** Find the current time (in Universal Coordinated Time).  Write the
   44567 ** current time and date as a Julian Day number into *prNow and
   44568 ** return 0.  Return 1 if the time and date cannot be found.
   44569 */
   44570 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
   44571   int rc;
   44572   sqlite3_int64 i;
   44573   rc = winCurrentTimeInt64(pVfs, &i);
   44574   if( !rc ){
   44575     *prNow = i/86400000.0;
   44576   }
   44577   return rc;
   44578 }
   44579 
   44580 /*
   44581 ** The idea is that this function works like a combination of
   44582 ** GetLastError() and FormatMessage() on Windows (or errno and
   44583 ** strerror_r() on Unix). After an error is returned by an OS
   44584 ** function, SQLite calls this function with zBuf pointing to
   44585 ** a buffer of nBuf bytes. The OS layer should populate the
   44586 ** buffer with a nul-terminated UTF-8 encoded error message
   44587 ** describing the last IO error to have occurred within the calling
   44588 ** thread.
   44589 **
   44590 ** If the error message is too large for the supplied buffer,
   44591 ** it should be truncated. The return value of xGetLastError
   44592 ** is zero if the error message fits in the buffer, or non-zero
   44593 ** otherwise (if the message was truncated). If non-zero is returned,
   44594 ** then it is not necessary to include the nul-terminator character
   44595 ** in the output buffer.
   44596 **
   44597 ** Not supplying an error message will have no adverse effect
   44598 ** on SQLite. It is fine to have an implementation that never
   44599 ** returns an error message:
   44600 **
   44601 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   44602 **     assert(zBuf[0]=='\0');
   44603 **     return 0;
   44604 **   }
   44605 **
   44606 ** However if an error message is supplied, it will be incorporated
   44607 ** by sqlite into the error message available to the user using
   44608 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   44609 */
   44610 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   44611   DWORD e = osGetLastError();
   44612   UNUSED_PARAMETER(pVfs);
   44613   if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
   44614   return e;
   44615 }
   44616 
   44617 /*
   44618 ** Initialize and deinitialize the operating system interface.
   44619 */
   44620 SQLITE_API int sqlite3_os_init(void){
   44621   static sqlite3_vfs winVfs = {
   44622     3,                     /* iVersion */
   44623     sizeof(winFile),       /* szOsFile */
   44624     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
   44625     0,                     /* pNext */
   44626     "win32",               /* zName */
   44627     &winAppData,           /* pAppData */
   44628     winOpen,               /* xOpen */
   44629     winDelete,             /* xDelete */
   44630     winAccess,             /* xAccess */
   44631     winFullPathname,       /* xFullPathname */
   44632     winDlOpen,             /* xDlOpen */
   44633     winDlError,            /* xDlError */
   44634     winDlSym,              /* xDlSym */
   44635     winDlClose,            /* xDlClose */
   44636     winRandomness,         /* xRandomness */
   44637     winSleep,              /* xSleep */
   44638     winCurrentTime,        /* xCurrentTime */
   44639     winGetLastError,       /* xGetLastError */
   44640     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
   44641     winSetSystemCall,      /* xSetSystemCall */
   44642     winGetSystemCall,      /* xGetSystemCall */
   44643     winNextSystemCall,     /* xNextSystemCall */
   44644   };
   44645 #if defined(SQLITE_WIN32_HAS_WIDE)
   44646   static sqlite3_vfs winLongPathVfs = {
   44647     3,                     /* iVersion */
   44648     sizeof(winFile),       /* szOsFile */
   44649     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
   44650     0,                     /* pNext */
   44651     "win32-longpath",      /* zName */
   44652     &winAppData,           /* pAppData */
   44653     winOpen,               /* xOpen */
   44654     winDelete,             /* xDelete */
   44655     winAccess,             /* xAccess */
   44656     winFullPathname,       /* xFullPathname */
   44657     winDlOpen,             /* xDlOpen */
   44658     winDlError,            /* xDlError */
   44659     winDlSym,              /* xDlSym */
   44660     winDlClose,            /* xDlClose */
   44661     winRandomness,         /* xRandomness */
   44662     winSleep,              /* xSleep */
   44663     winCurrentTime,        /* xCurrentTime */
   44664     winGetLastError,       /* xGetLastError */
   44665     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
   44666     winSetSystemCall,      /* xSetSystemCall */
   44667     winGetSystemCall,      /* xGetSystemCall */
   44668     winNextSystemCall,     /* xNextSystemCall */
   44669   };
   44670 #endif
   44671   static sqlite3_vfs winNolockVfs = {
   44672     3,                     /* iVersion */
   44673     sizeof(winFile),       /* szOsFile */
   44674     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
   44675     0,                     /* pNext */
   44676     "win32-none",          /* zName */
   44677     &winNolockAppData,     /* pAppData */
   44678     winOpen,               /* xOpen */
   44679     winDelete,             /* xDelete */
   44680     winAccess,             /* xAccess */
   44681     winFullPathname,       /* xFullPathname */
   44682     winDlOpen,             /* xDlOpen */
   44683     winDlError,            /* xDlError */
   44684     winDlSym,              /* xDlSym */
   44685     winDlClose,            /* xDlClose */
   44686     winRandomness,         /* xRandomness */
   44687     winSleep,              /* xSleep */
   44688     winCurrentTime,        /* xCurrentTime */
   44689     winGetLastError,       /* xGetLastError */
   44690     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
   44691     winSetSystemCall,      /* xSetSystemCall */
   44692     winGetSystemCall,      /* xGetSystemCall */
   44693     winNextSystemCall,     /* xNextSystemCall */
   44694   };
   44695 #if defined(SQLITE_WIN32_HAS_WIDE)
   44696   static sqlite3_vfs winLongPathNolockVfs = {
   44697     3,                     /* iVersion */
   44698     sizeof(winFile),       /* szOsFile */
   44699     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
   44700     0,                     /* pNext */
   44701     "win32-longpath-none", /* zName */
   44702     &winNolockAppData,     /* pAppData */
   44703     winOpen,               /* xOpen */
   44704     winDelete,             /* xDelete */
   44705     winAccess,             /* xAccess */
   44706     winFullPathname,       /* xFullPathname */
   44707     winDlOpen,             /* xDlOpen */
   44708     winDlError,            /* xDlError */
   44709     winDlSym,              /* xDlSym */
   44710     winDlClose,            /* xDlClose */
   44711     winRandomness,         /* xRandomness */
   44712     winSleep,              /* xSleep */
   44713     winCurrentTime,        /* xCurrentTime */
   44714     winGetLastError,       /* xGetLastError */
   44715     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
   44716     winSetSystemCall,      /* xSetSystemCall */
   44717     winGetSystemCall,      /* xGetSystemCall */
   44718     winNextSystemCall,     /* xNextSystemCall */
   44719   };
   44720 #endif
   44721 
   44722   /* Double-check that the aSyscall[] array has been constructed
   44723   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   44724   assert( ArraySize(aSyscall)==80 );
   44725 
   44726   /* get memory map allocation granularity */
   44727   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
   44728 #if SQLITE_OS_WINRT
   44729   osGetNativeSystemInfo(&winSysInfo);
   44730 #else
   44731   osGetSystemInfo(&winSysInfo);
   44732 #endif
   44733   assert( winSysInfo.dwAllocationGranularity>0 );
   44734   assert( winSysInfo.dwPageSize>0 );
   44735 
   44736   sqlite3_vfs_register(&winVfs, 1);
   44737 
   44738 #if defined(SQLITE_WIN32_HAS_WIDE)
   44739   sqlite3_vfs_register(&winLongPathVfs, 0);
   44740 #endif
   44741 
   44742   sqlite3_vfs_register(&winNolockVfs, 0);
   44743 
   44744 #if defined(SQLITE_WIN32_HAS_WIDE)
   44745   sqlite3_vfs_register(&winLongPathNolockVfs, 0);
   44746 #endif
   44747 
   44748   return SQLITE_OK;
   44749 }
   44750 
   44751 SQLITE_API int sqlite3_os_end(void){
   44752 #if SQLITE_OS_WINRT
   44753   if( sleepObj!=NULL ){
   44754     osCloseHandle(sleepObj);
   44755     sleepObj = NULL;
   44756   }
   44757 #endif
   44758   return SQLITE_OK;
   44759 }
   44760 
   44761 #endif /* SQLITE_OS_WIN */
   44762 
   44763 /************** End of os_win.c **********************************************/
   44764 /************** Begin file bitvec.c ******************************************/
   44765 /*
   44766 ** 2008 February 16
   44767 **
   44768 ** The author disclaims copyright to this source code.  In place of
   44769 ** a legal notice, here is a blessing:
   44770 **
   44771 **    May you do good and not evil.
   44772 **    May you find forgiveness for yourself and forgive others.
   44773 **    May you share freely, never taking more than you give.
   44774 **
   44775 *************************************************************************
   44776 ** This file implements an object that represents a fixed-length
   44777 ** bitmap.  Bits are numbered starting with 1.
   44778 **
   44779 ** A bitmap is used to record which pages of a database file have been
   44780 ** journalled during a transaction, or which pages have the "dont-write"
   44781 ** property.  Usually only a few pages are meet either condition.
   44782 ** So the bitmap is usually sparse and has low cardinality.
   44783 ** But sometimes (for example when during a DROP of a large table) most
   44784 ** or all of the pages in a database can get journalled.  In those cases,
   44785 ** the bitmap becomes dense with high cardinality.  The algorithm needs
   44786 ** to handle both cases well.
   44787 **
   44788 ** The size of the bitmap is fixed when the object is created.
   44789 **
   44790 ** All bits are clear when the bitmap is created.  Individual bits
   44791 ** may be set or cleared one at a time.
   44792 **
   44793 ** Test operations are about 100 times more common that set operations.
   44794 ** Clear operations are exceedingly rare.  There are usually between
   44795 ** 5 and 500 set operations per Bitvec object, though the number of sets can
   44796 ** sometimes grow into tens of thousands or larger.  The size of the
   44797 ** Bitvec object is the number of pages in the database file at the
   44798 ** start of a transaction, and is thus usually less than a few thousand,
   44799 ** but can be as large as 2 billion for a really big database.
   44800 */
   44801 /* #include "sqliteInt.h" */
   44802 
   44803 /* Size of the Bitvec structure in bytes. */
   44804 #define BITVEC_SZ        512
   44805 
   44806 /* Round the union size down to the nearest pointer boundary, since that's how
   44807 ** it will be aligned within the Bitvec struct. */
   44808 #define BITVEC_USIZE \
   44809     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
   44810 
   44811 /* Type of the array "element" for the bitmap representation.
   44812 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
   44813 ** Setting this to the "natural word" size of your CPU may improve
   44814 ** performance. */
   44815 #define BITVEC_TELEM     u8
   44816 /* Size, in bits, of the bitmap element. */
   44817 #define BITVEC_SZELEM    8
   44818 /* Number of elements in a bitmap array. */
   44819 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
   44820 /* Number of bits in the bitmap array. */
   44821 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
   44822 
   44823 /* Number of u32 values in hash table. */
   44824 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
   44825 /* Maximum number of entries in hash table before
   44826 ** sub-dividing and re-hashing. */
   44827 #define BITVEC_MXHASH    (BITVEC_NINT/2)
   44828 /* Hashing function for the aHash representation.
   44829 ** Empirical testing showed that the *37 multiplier
   44830 ** (an arbitrary prime)in the hash function provided
   44831 ** no fewer collisions than the no-op *1. */
   44832 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
   44833 
   44834 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
   44835 
   44836 
   44837 /*
   44838 ** A bitmap is an instance of the following structure.
   44839 **
   44840 ** This bitmap records the existence of zero or more bits
   44841 ** with values between 1 and iSize, inclusive.
   44842 **
   44843 ** There are three possible representations of the bitmap.
   44844 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
   44845 ** bitmap.  The least significant bit is bit 1.
   44846 **
   44847 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
   44848 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
   44849 **
   44850 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
   44851 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
   44852 ** handles up to iDivisor separate values of i.  apSub[0] holds
   44853 ** values between 1 and iDivisor.  apSub[1] holds values between
   44854 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
   44855 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
   44856 ** to hold deal with values between 1 and iDivisor.
   44857 */
   44858 struct Bitvec {
   44859   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
   44860   u32 nSet;       /* Number of bits that are set - only valid for aHash
   44861                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
   44862                   ** this would be 125. */
   44863   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
   44864                   /* Should >=0 for apSub element. */
   44865                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
   44866                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
   44867   union {
   44868     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
   44869     u32 aHash[BITVEC_NINT];      /* Hash table representation */
   44870     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
   44871   } u;
   44872 };
   44873 
   44874 /*
   44875 ** Create a new bitmap object able to handle bits between 0 and iSize,
   44876 ** inclusive.  Return a pointer to the new object.  Return NULL if
   44877 ** malloc fails.
   44878 */
   44879 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
   44880   Bitvec *p;
   44881   assert( sizeof(*p)==BITVEC_SZ );
   44882   p = sqlite3MallocZero( sizeof(*p) );
   44883   if( p ){
   44884     p->iSize = iSize;
   44885   }
   44886   return p;
   44887 }
   44888 
   44889 /*
   44890 ** Check to see if the i-th bit is set.  Return true or false.
   44891 ** If p is NULL (if the bitmap has not been created) or if
   44892 ** i is out of range, then return false.
   44893 */
   44894 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
   44895   assert( p!=0 );
   44896   i--;
   44897   if( i>=p->iSize ) return 0;
   44898   while( p->iDivisor ){
   44899     u32 bin = i/p->iDivisor;
   44900     i = i%p->iDivisor;
   44901     p = p->u.apSub[bin];
   44902     if (!p) {
   44903       return 0;
   44904     }
   44905   }
   44906   if( p->iSize<=BITVEC_NBIT ){
   44907     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
   44908   } else{
   44909     u32 h = BITVEC_HASH(i++);
   44910     while( p->u.aHash[h] ){
   44911       if( p->u.aHash[h]==i ) return 1;
   44912       h = (h+1) % BITVEC_NINT;
   44913     }
   44914     return 0;
   44915   }
   44916 }
   44917 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
   44918   return p!=0 && sqlite3BitvecTestNotNull(p,i);
   44919 }
   44920 
   44921 /*
   44922 ** Set the i-th bit.  Return 0 on success and an error code if
   44923 ** anything goes wrong.
   44924 **
   44925 ** This routine might cause sub-bitmaps to be allocated.  Failing
   44926 ** to get the memory needed to hold the sub-bitmap is the only
   44927 ** that can go wrong with an insert, assuming p and i are valid.
   44928 **
   44929 ** The calling function must ensure that p is a valid Bitvec object
   44930 ** and that the value for "i" is within range of the Bitvec object.
   44931 ** Otherwise the behavior is undefined.
   44932 */
   44933 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
   44934   u32 h;
   44935   if( p==0 ) return SQLITE_OK;
   44936   assert( i>0 );
   44937   assert( i<=p->iSize );
   44938   i--;
   44939   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
   44940     u32 bin = i/p->iDivisor;
   44941     i = i%p->iDivisor;
   44942     if( p->u.apSub[bin]==0 ){
   44943       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
   44944       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
   44945     }
   44946     p = p->u.apSub[bin];
   44947   }
   44948   if( p->iSize<=BITVEC_NBIT ){
   44949     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
   44950     return SQLITE_OK;
   44951   }
   44952   h = BITVEC_HASH(i++);
   44953   /* if there wasn't a hash collision, and this doesn't */
   44954   /* completely fill the hash, then just add it without */
   44955   /* worring about sub-dividing and re-hashing. */
   44956   if( !p->u.aHash[h] ){
   44957     if (p->nSet<(BITVEC_NINT-1)) {
   44958       goto bitvec_set_end;
   44959     } else {
   44960       goto bitvec_set_rehash;
   44961     }
   44962   }
   44963   /* there was a collision, check to see if it's already */
   44964   /* in hash, if not, try to find a spot for it */
   44965   do {
   44966     if( p->u.aHash[h]==i ) return SQLITE_OK;
   44967     h++;
   44968     if( h>=BITVEC_NINT ) h = 0;
   44969   } while( p->u.aHash[h] );
   44970   /* we didn't find it in the hash.  h points to the first */
   44971   /* available free spot. check to see if this is going to */
   44972   /* make our hash too "full".  */
   44973 bitvec_set_rehash:
   44974   if( p->nSet>=BITVEC_MXHASH ){
   44975     unsigned int j;
   44976     int rc;
   44977     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
   44978     if( aiValues==0 ){
   44979       return SQLITE_NOMEM_BKPT;
   44980     }else{
   44981       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   44982       memset(p->u.apSub, 0, sizeof(p->u.apSub));
   44983       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
   44984       rc = sqlite3BitvecSet(p, i);
   44985       for(j=0; j<BITVEC_NINT; j++){
   44986         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
   44987       }
   44988       sqlite3StackFree(0, aiValues);
   44989       return rc;
   44990     }
   44991   }
   44992 bitvec_set_end:
   44993   p->nSet++;
   44994   p->u.aHash[h] = i;
   44995   return SQLITE_OK;
   44996 }
   44997 
   44998 /*
   44999 ** Clear the i-th bit.
   45000 **
   45001 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
   45002 ** that BitvecClear can use to rebuilt its hash table.
   45003 */
   45004 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
   45005   if( p==0 ) return;
   45006   assert( i>0 );
   45007   i--;
   45008   while( p->iDivisor ){
   45009     u32 bin = i/p->iDivisor;
   45010     i = i%p->iDivisor;
   45011     p = p->u.apSub[bin];
   45012     if (!p) {
   45013       return;
   45014     }
   45015   }
   45016   if( p->iSize<=BITVEC_NBIT ){
   45017     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
   45018   }else{
   45019     unsigned int j;
   45020     u32 *aiValues = pBuf;
   45021     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   45022     memset(p->u.aHash, 0, sizeof(p->u.aHash));
   45023     p->nSet = 0;
   45024     for(j=0; j<BITVEC_NINT; j++){
   45025       if( aiValues[j] && aiValues[j]!=(i+1) ){
   45026         u32 h = BITVEC_HASH(aiValues[j]-1);
   45027         p->nSet++;
   45028         while( p->u.aHash[h] ){
   45029           h++;
   45030           if( h>=BITVEC_NINT ) h = 0;
   45031         }
   45032         p->u.aHash[h] = aiValues[j];
   45033       }
   45034     }
   45035   }
   45036 }
   45037 
   45038 /*
   45039 ** Destroy a bitmap object.  Reclaim all memory used.
   45040 */
   45041 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
   45042   if( p==0 ) return;
   45043   if( p->iDivisor ){
   45044     unsigned int i;
   45045     for(i=0; i<BITVEC_NPTR; i++){
   45046       sqlite3BitvecDestroy(p->u.apSub[i]);
   45047     }
   45048   }
   45049   sqlite3_free(p);
   45050 }
   45051 
   45052 /*
   45053 ** Return the value of the iSize parameter specified when Bitvec *p
   45054 ** was created.
   45055 */
   45056 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
   45057   return p->iSize;
   45058 }
   45059 
   45060 #ifndef SQLITE_UNTESTABLE
   45061 /*
   45062 ** Let V[] be an array of unsigned characters sufficient to hold
   45063 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
   45064 ** Then the following macros can be used to set, clear, or test
   45065 ** individual bits within V.
   45066 */
   45067 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
   45068 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
   45069 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
   45070 
   45071 /*
   45072 ** This routine runs an extensive test of the Bitvec code.
   45073 **
   45074 ** The input is an array of integers that acts as a program
   45075 ** to test the Bitvec.  The integers are opcodes followed
   45076 ** by 0, 1, or 3 operands, depending on the opcode.  Another
   45077 ** opcode follows immediately after the last operand.
   45078 **
   45079 ** There are 6 opcodes numbered from 0 through 5.  0 is the
   45080 ** "halt" opcode and causes the test to end.
   45081 **
   45082 **    0          Halt and return the number of errors
   45083 **    1 N S X    Set N bits beginning with S and incrementing by X
   45084 **    2 N S X    Clear N bits beginning with S and incrementing by X
   45085 **    3 N        Set N randomly chosen bits
   45086 **    4 N        Clear N randomly chosen bits
   45087 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
   45088 **
   45089 ** The opcodes 1 through 4 perform set and clear operations are performed
   45090 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
   45091 ** Opcode 5 works on the linear array only, not on the Bitvec.
   45092 ** Opcode 5 is used to deliberately induce a fault in order to
   45093 ** confirm that error detection works.
   45094 **
   45095 ** At the conclusion of the test the linear array is compared
   45096 ** against the Bitvec object.  If there are any differences,
   45097 ** an error is returned.  If they are the same, zero is returned.
   45098 **
   45099 ** If a memory allocation error occurs, return -1.
   45100 */
   45101 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   45102   Bitvec *pBitvec = 0;
   45103   unsigned char *pV = 0;
   45104   int rc = -1;
   45105   int i, nx, pc, op;
   45106   void *pTmpSpace;
   45107 
   45108   /* Allocate the Bitvec to be tested and a linear array of
   45109   ** bits to act as the reference */
   45110   pBitvec = sqlite3BitvecCreate( sz );
   45111   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
   45112   pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
   45113   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
   45114 
   45115   /* NULL pBitvec tests */
   45116   sqlite3BitvecSet(0, 1);
   45117   sqlite3BitvecClear(0, 1, pTmpSpace);
   45118 
   45119   /* Run the program */
   45120   pc = 0;
   45121   while( (op = aOp[pc])!=0 ){
   45122     switch( op ){
   45123       case 1:
   45124       case 2:
   45125       case 5: {
   45126         nx = 4;
   45127         i = aOp[pc+2] - 1;
   45128         aOp[pc+2] += aOp[pc+3];
   45129         break;
   45130       }
   45131       case 3:
   45132       case 4:
   45133       default: {
   45134         nx = 2;
   45135         sqlite3_randomness(sizeof(i), &i);
   45136         break;
   45137       }
   45138     }
   45139     if( (--aOp[pc+1]) > 0 ) nx = 0;
   45140     pc += nx;
   45141     i = (i & 0x7fffffff)%sz;
   45142     if( (op & 1)!=0 ){
   45143       SETBIT(pV, (i+1));
   45144       if( op!=5 ){
   45145         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
   45146       }
   45147     }else{
   45148       CLEARBIT(pV, (i+1));
   45149       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
   45150     }
   45151   }
   45152 
   45153   /* Test to make sure the linear array exactly matches the
   45154   ** Bitvec object.  Start with the assumption that they do
   45155   ** match (rc==0).  Change rc to non-zero if a discrepancy
   45156   ** is found.
   45157   */
   45158   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
   45159           + sqlite3BitvecTest(pBitvec, 0)
   45160           + (sqlite3BitvecSize(pBitvec) - sz);
   45161   for(i=1; i<=sz; i++){
   45162     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
   45163       rc = i;
   45164       break;
   45165     }
   45166   }
   45167 
   45168   /* Free allocated structure */
   45169 bitvec_end:
   45170   sqlite3_free(pTmpSpace);
   45171   sqlite3_free(pV);
   45172   sqlite3BitvecDestroy(pBitvec);
   45173   return rc;
   45174 }
   45175 #endif /* SQLITE_UNTESTABLE */
   45176 
   45177 /************** End of bitvec.c **********************************************/
   45178 /************** Begin file pcache.c ******************************************/
   45179 /*
   45180 ** 2008 August 05
   45181 **
   45182 ** The author disclaims copyright to this source code.  In place of
   45183 ** a legal notice, here is a blessing:
   45184 **
   45185 **    May you do good and not evil.
   45186 **    May you find forgiveness for yourself and forgive others.
   45187 **    May you share freely, never taking more than you give.
   45188 **
   45189 *************************************************************************
   45190 ** This file implements that page cache.
   45191 */
   45192 /* #include "sqliteInt.h" */
   45193 
   45194 /*
   45195 ** A complete page cache is an instance of this structure.  Every
   45196 ** entry in the cache holds a single page of the database file.  The
   45197 ** btree layer only operates on the cached copy of the database pages.
   45198 **
   45199 ** A page cache entry is "clean" if it exactly matches what is currently
   45200 ** on disk.  A page is "dirty" if it has been modified and needs to be
   45201 ** persisted to disk.
   45202 **
   45203 ** pDirty, pDirtyTail, pSynced:
   45204 **   All dirty pages are linked into the doubly linked list using
   45205 **   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
   45206 **   such that p was added to the list more recently than p->pDirtyNext.
   45207 **   PCache.pDirty points to the first (newest) element in the list and
   45208 **   pDirtyTail to the last (oldest).
   45209 **
   45210 **   The PCache.pSynced variable is used to optimize searching for a dirty
   45211 **   page to eject from the cache mid-transaction. It is better to eject
   45212 **   a page that does not require a journal sync than one that does.
   45213 **   Therefore, pSynced is maintained to that it *almost* always points
   45214 **   to either the oldest page in the pDirty/pDirtyTail list that has a
   45215 **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
   45216 **   (so that the right page to eject can be found by following pDirtyPrev
   45217 **   pointers).
   45218 */
   45219 struct PCache {
   45220   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
   45221   PgHdr *pSynced;                     /* Last synced page in dirty page list */
   45222   int nRefSum;                        /* Sum of ref counts over all pages */
   45223   int szCache;                        /* Configured cache size */
   45224   int szSpill;                        /* Size before spilling occurs */
   45225   int szPage;                         /* Size of every page in this cache */
   45226   int szExtra;                        /* Size of extra space for each page */
   45227   u8 bPurgeable;                      /* True if pages are on backing store */
   45228   u8 eCreate;                         /* eCreate value for for xFetch() */
   45229   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
   45230   void *pStress;                      /* Argument to xStress */
   45231   sqlite3_pcache *pCache;             /* Pluggable cache module */
   45232 };
   45233 
   45234 /********************************** Test and Debug Logic **********************/
   45235 /*
   45236 ** Debug tracing macros.  Enable by by changing the "0" to "1" and
   45237 ** recompiling.
   45238 **
   45239 ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
   45240 ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
   45241 ** is displayed for many operations, resulting in a lot of output.
   45242 */
   45243 #if defined(SQLITE_DEBUG) && 0
   45244   int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
   45245   int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
   45246 # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
   45247   void pcacheDump(PCache *pCache){
   45248     int N;
   45249     int i, j;
   45250     sqlite3_pcache_page *pLower;
   45251     PgHdr *pPg;
   45252     unsigned char *a;
   45253 
   45254     if( sqlite3PcacheTrace<2 ) return;
   45255     if( pCache->pCache==0 ) return;
   45256     N = sqlite3PcachePagecount(pCache);
   45257     if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
   45258     for(i=1; i<=N; i++){
   45259        pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
   45260        if( pLower==0 ) continue;
   45261        pPg = (PgHdr*)pLower->pExtra;
   45262        printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
   45263        a = (unsigned char *)pLower->pBuf;
   45264        for(j=0; j<12; j++) printf("%02x", a[j]);
   45265        printf("\n");
   45266        if( pPg->pPage==0 ){
   45267          sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
   45268        }
   45269     }
   45270   }
   45271   #else
   45272 # define pcacheTrace(X)
   45273 # define pcacheDump(X)
   45274 #endif
   45275 
   45276 /*
   45277 ** Check invariants on a PgHdr entry.  Return true if everything is OK.
   45278 ** Return false if any invariant is violated.
   45279 **
   45280 ** This routine is for use inside of assert() statements only.  For
   45281 ** example:
   45282 **
   45283 **          assert( sqlite3PcachePageSanity(pPg) );
   45284 */
   45285 #ifdef SQLITE_DEBUG
   45286 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
   45287   PCache *pCache;
   45288   assert( pPg!=0 );
   45289   assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */
   45290   pCache = pPg->pCache;
   45291   assert( pCache!=0 );      /* Every page has an associated PCache */
   45292   if( pPg->flags & PGHDR_CLEAN ){
   45293     assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
   45294     assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
   45295     assert( pCache->pDirtyTail!=pPg );
   45296   }
   45297   /* WRITEABLE pages must also be DIRTY */
   45298   if( pPg->flags & PGHDR_WRITEABLE ){
   45299     assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
   45300   }
   45301   /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
   45302   ** for example, when using the sqlite3PagerDontWrite() optimization:
   45303   **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
   45304   **    (2)  Page X moved to freelist, WRITEABLE is cleared
   45305   **    (3)  Page X reused, WRITEABLE is set again
   45306   ** If NEED_SYNC had been cleared in step 2, then it would not be reset
   45307   ** in step 3, and page might be written into the database without first
   45308   ** syncing the rollback journal, which might cause corruption on a power
   45309   ** loss.
   45310   **
   45311   ** Another example is when the database page size is smaller than the
   45312   ** disk sector size.  When any page of a sector is journalled, all pages
   45313   ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
   45314   ** in case they are later modified, since all pages in the same sector
   45315   ** must be journalled and synced before any of those pages can be safely
   45316   ** written.
   45317   */
   45318   return 1;
   45319 }
   45320 #endif /* SQLITE_DEBUG */
   45321 
   45322 
   45323 /********************************** Linked List Management ********************/
   45324 
   45325 /* Allowed values for second argument to pcacheManageDirtyList() */
   45326 #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
   45327 #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
   45328 #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
   45329 
   45330 /*
   45331 ** Manage pPage's participation on the dirty list.  Bits of the addRemove
   45332 ** argument determines what operation to do.  The 0x01 bit means first
   45333 ** remove pPage from the dirty list.  The 0x02 means add pPage back to
   45334 ** the dirty list.  Doing both moves pPage to the front of the dirty list.
   45335 */
   45336 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
   45337   PCache *p = pPage->pCache;
   45338 
   45339   pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
   45340                 addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
   45341                 pPage->pgno));
   45342   if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
   45343     assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
   45344     assert( pPage->pDirtyPrev || pPage==p->pDirty );
   45345 
   45346     /* Update the PCache1.pSynced variable if necessary. */
   45347     if( p->pSynced==pPage ){
   45348       p->pSynced = pPage->pDirtyPrev;
   45349     }
   45350 
   45351     if( pPage->pDirtyNext ){
   45352       pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
   45353     }else{
   45354       assert( pPage==p->pDirtyTail );
   45355       p->pDirtyTail = pPage->pDirtyPrev;
   45356     }
   45357     if( pPage->pDirtyPrev ){
   45358       pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
   45359     }else{
   45360       /* If there are now no dirty pages in the cache, set eCreate to 2.
   45361       ** This is an optimization that allows sqlite3PcacheFetch() to skip
   45362       ** searching for a dirty page to eject from the cache when it might
   45363       ** otherwise have to.  */
   45364       assert( pPage==p->pDirty );
   45365       p->pDirty = pPage->pDirtyNext;
   45366       assert( p->bPurgeable || p->eCreate==2 );
   45367       if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
   45368         assert( p->bPurgeable==0 || p->eCreate==1 );
   45369         p->eCreate = 2;
   45370       }
   45371     }
   45372   }
   45373   if( addRemove & PCACHE_DIRTYLIST_ADD ){
   45374     pPage->pDirtyPrev = 0;
   45375     pPage->pDirtyNext = p->pDirty;
   45376     if( pPage->pDirtyNext ){
   45377       assert( pPage->pDirtyNext->pDirtyPrev==0 );
   45378       pPage->pDirtyNext->pDirtyPrev = pPage;
   45379     }else{
   45380       p->pDirtyTail = pPage;
   45381       if( p->bPurgeable ){
   45382         assert( p->eCreate==2 );
   45383         p->eCreate = 1;
   45384       }
   45385     }
   45386     p->pDirty = pPage;
   45387 
   45388     /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
   45389     ** pSynced to point to it. Checking the NEED_SYNC flag is an
   45390     ** optimization, as if pSynced points to a page with the NEED_SYNC
   45391     ** flag set sqlite3PcacheFetchStress() searches through all newer
   45392     ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
   45393     if( !p->pSynced
   45394      && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
   45395     ){
   45396       p->pSynced = pPage;
   45397     }
   45398   }
   45399   pcacheDump(p);
   45400 }
   45401 
   45402 /*
   45403 ** Wrapper around the pluggable caches xUnpin method. If the cache is
   45404 ** being used for an in-memory database, this function is a no-op.
   45405 */
   45406 static void pcacheUnpin(PgHdr *p){
   45407   if( p->pCache->bPurgeable ){
   45408     pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
   45409     sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
   45410     pcacheDump(p->pCache);
   45411   }
   45412 }
   45413 
   45414 /*
   45415 ** Compute the number of pages of cache requested.   p->szCache is the
   45416 ** cache size requested by the "PRAGMA cache_size" statement.
   45417 */
   45418 static int numberOfCachePages(PCache *p){
   45419   if( p->szCache>=0 ){
   45420     /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
   45421     ** suggested cache size is set to N. */
   45422     return p->szCache;
   45423   }else{
   45424     /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
   45425     ** the number of cache pages is adjusted to use approximately abs(N*1024)
   45426     ** bytes of memory. */
   45427     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
   45428   }
   45429 }
   45430 
   45431 /*************************************************** General Interfaces ******
   45432 **
   45433 ** Initialize and shutdown the page cache subsystem. Neither of these
   45434 ** functions are threadsafe.
   45435 */
   45436 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
   45437   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   45438     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
   45439     ** built-in default page cache is used instead of the application defined
   45440     ** page cache. */
   45441     sqlite3PCacheSetDefault();
   45442   }
   45443   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
   45444 }
   45445 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
   45446   if( sqlite3GlobalConfig.pcache2.xShutdown ){
   45447     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
   45448     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
   45449   }
   45450 }
   45451 
   45452 /*
   45453 ** Return the size in bytes of a PCache object.
   45454 */
   45455 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
   45456 
   45457 /*
   45458 ** Create a new PCache object. Storage space to hold the object
   45459 ** has already been allocated and is passed in as the p pointer.
   45460 ** The caller discovers how much space needs to be allocated by
   45461 ** calling sqlite3PcacheSize().
   45462 **
   45463 ** szExtra is some extra space allocated for each page.  The first
   45464 ** 8 bytes of the extra space will be zeroed as the page is allocated,
   45465 ** but remaining content will be uninitialized.  Though it is opaque
   45466 ** to this module, the extra space really ends up being the MemPage
   45467 ** structure in the pager.
   45468 */
   45469 SQLITE_PRIVATE int sqlite3PcacheOpen(
   45470   int szPage,                  /* Size of every page */
   45471   int szExtra,                 /* Extra space associated with each page */
   45472   int bPurgeable,              /* True if pages are on backing store */
   45473   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
   45474   void *pStress,               /* Argument to xStress */
   45475   PCache *p                    /* Preallocated space for the PCache */
   45476 ){
   45477   memset(p, 0, sizeof(PCache));
   45478   p->szPage = 1;
   45479   p->szExtra = szExtra;
   45480   assert( szExtra>=8 );  /* First 8 bytes will be zeroed */
   45481   p->bPurgeable = bPurgeable;
   45482   p->eCreate = 2;
   45483   p->xStress = xStress;
   45484   p->pStress = pStress;
   45485   p->szCache = 100;
   45486   p->szSpill = 1;
   45487   pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
   45488   return sqlite3PcacheSetPageSize(p, szPage);
   45489 }
   45490 
   45491 /*
   45492 ** Change the page size for PCache object. The caller must ensure that there
   45493 ** are no outstanding page references when this function is called.
   45494 */
   45495 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   45496   assert( pCache->nRefSum==0 && pCache->pDirty==0 );
   45497   if( pCache->szPage ){
   45498     sqlite3_pcache *pNew;
   45499     pNew = sqlite3GlobalConfig.pcache2.xCreate(
   45500                 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
   45501                 pCache->bPurgeable
   45502     );
   45503     if( pNew==0 ) return SQLITE_NOMEM_BKPT;
   45504     sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
   45505     if( pCache->pCache ){
   45506       sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   45507     }
   45508     pCache->pCache = pNew;
   45509     pCache->szPage = szPage;
   45510     pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
   45511   }
   45512   return SQLITE_OK;
   45513 }
   45514 
   45515 /*
   45516 ** Try to obtain a page from the cache.
   45517 **
   45518 ** This routine returns a pointer to an sqlite3_pcache_page object if
   45519 ** such an object is already in cache, or if a new one is created.
   45520 ** This routine returns a NULL pointer if the object was not in cache
   45521 ** and could not be created.
   45522 **
   45523 ** The createFlags should be 0 to check for existing pages and should
   45524 ** be 3 (not 1, but 3) to try to create a new page.
   45525 **
   45526 ** If the createFlag is 0, then NULL is always returned if the page
   45527 ** is not already in the cache.  If createFlag is 1, then a new page
   45528 ** is created only if that can be done without spilling dirty pages
   45529 ** and without exceeding the cache size limit.
   45530 **
   45531 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
   45532 ** initialize the sqlite3_pcache_page object and convert it into a
   45533 ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
   45534 ** routines are split this way for performance reasons. When separated
   45535 ** they can both (usually) operate without having to push values to
   45536 ** the stack on entry and pop them back off on exit, which saves a
   45537 ** lot of pushing and popping.
   45538 */
   45539 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
   45540   PCache *pCache,       /* Obtain the page from this cache */
   45541   Pgno pgno,            /* Page number to obtain */
   45542   int createFlag        /* If true, create page if it does not exist already */
   45543 ){
   45544   int eCreate;
   45545   sqlite3_pcache_page *pRes;
   45546 
   45547   assert( pCache!=0 );
   45548   assert( pCache->pCache!=0 );
   45549   assert( createFlag==3 || createFlag==0 );
   45550   assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
   45551 
   45552   /* eCreate defines what to do if the page does not exist.
   45553   **    0     Do not allocate a new page.  (createFlag==0)
   45554   **    1     Allocate a new page if doing so is inexpensive.
   45555   **          (createFlag==1 AND bPurgeable AND pDirty)
   45556   **    2     Allocate a new page even it doing so is difficult.
   45557   **          (createFlag==1 AND !(bPurgeable AND pDirty)
   45558   */
   45559   eCreate = createFlag & pCache->eCreate;
   45560   assert( eCreate==0 || eCreate==1 || eCreate==2 );
   45561   assert( createFlag==0 || pCache->eCreate==eCreate );
   45562   assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
   45563   pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
   45564   pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
   45565                createFlag?" create":"",pRes));
   45566   return pRes;
   45567 }
   45568 
   45569 /*
   45570 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
   45571 ** page because no clean pages are available for reuse and the cache
   45572 ** size limit has been reached, then this routine can be invoked to
   45573 ** try harder to allocate a page.  This routine might invoke the stress
   45574 ** callback to spill dirty pages to the journal.  It will then try to
   45575 ** allocate the new page and will only fail to allocate a new page on
   45576 ** an OOM error.
   45577 **
   45578 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
   45579 */
   45580 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
   45581   PCache *pCache,                 /* Obtain the page from this cache */
   45582   Pgno pgno,                      /* Page number to obtain */
   45583   sqlite3_pcache_page **ppPage    /* Write result here */
   45584 ){
   45585   PgHdr *pPg;
   45586   if( pCache->eCreate==2 ) return 0;
   45587 
   45588   if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
   45589     /* Find a dirty page to write-out and recycle. First try to find a
   45590     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
   45591     ** cleared), but if that is not possible settle for any other
   45592     ** unreferenced dirty page.
   45593     **
   45594     ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
   45595     ** flag is currently referenced, then the following may leave pSynced
   45596     ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
   45597     ** cleared). This is Ok, as pSynced is just an optimization.  */
   45598     for(pPg=pCache->pSynced;
   45599         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
   45600         pPg=pPg->pDirtyPrev
   45601     );
   45602     pCache->pSynced = pPg;
   45603     if( !pPg ){
   45604       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
   45605     }
   45606     if( pPg ){
   45607       int rc;
   45608 #ifdef SQLITE_LOG_CACHE_SPILL
   45609       sqlite3_log(SQLITE_FULL,
   45610                   "spill page %d making room for %d - cache used: %d/%d",
   45611                   pPg->pgno, pgno,
   45612                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
   45613                 numberOfCachePages(pCache));
   45614 #endif
   45615       pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
   45616       rc = pCache->xStress(pCache->pStress, pPg);
   45617       pcacheDump(pCache);
   45618       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   45619         return rc;
   45620       }
   45621     }
   45622   }
   45623   *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
   45624   return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
   45625 }
   45626 
   45627 /*
   45628 ** This is a helper routine for sqlite3PcacheFetchFinish()
   45629 **
   45630 ** In the uncommon case where the page being fetched has not been
   45631 ** initialized, this routine is invoked to do the initialization.
   45632 ** This routine is broken out into a separate function since it
   45633 ** requires extra stack manipulation that can be avoided in the common
   45634 ** case.
   45635 */
   45636 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
   45637   PCache *pCache,             /* Obtain the page from this cache */
   45638   Pgno pgno,                  /* Page number obtained */
   45639   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
   45640 ){
   45641   PgHdr *pPgHdr;
   45642   assert( pPage!=0 );
   45643   pPgHdr = (PgHdr*)pPage->pExtra;
   45644   assert( pPgHdr->pPage==0 );
   45645   memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
   45646   pPgHdr->pPage = pPage;
   45647   pPgHdr->pData = pPage->pBuf;
   45648   pPgHdr->pExtra = (void *)&pPgHdr[1];
   45649   memset(pPgHdr->pExtra, 0, 8);
   45650   pPgHdr->pCache = pCache;
   45651   pPgHdr->pgno = pgno;
   45652   pPgHdr->flags = PGHDR_CLEAN;
   45653   return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
   45654 }
   45655 
   45656 /*
   45657 ** This routine converts the sqlite3_pcache_page object returned by
   45658 ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
   45659 ** must be called after sqlite3PcacheFetch() in order to get a usable
   45660 ** result.
   45661 */
   45662 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
   45663   PCache *pCache,             /* Obtain the page from this cache */
   45664   Pgno pgno,                  /* Page number obtained */
   45665   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
   45666 ){
   45667   PgHdr *pPgHdr;
   45668 
   45669   assert( pPage!=0 );
   45670   pPgHdr = (PgHdr *)pPage->pExtra;
   45671 
   45672   if( !pPgHdr->pPage ){
   45673     return pcacheFetchFinishWithInit(pCache, pgno, pPage);
   45674   }
   45675   pCache->nRefSum++;
   45676   pPgHdr->nRef++;
   45677   assert( sqlite3PcachePageSanity(pPgHdr) );
   45678   return pPgHdr;
   45679 }
   45680 
   45681 /*
   45682 ** Decrement the reference count on a page. If the page is clean and the
   45683 ** reference count drops to 0, then it is made eligible for recycling.
   45684 */
   45685 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
   45686   assert( p->nRef>0 );
   45687   p->pCache->nRefSum--;
   45688   if( (--p->nRef)==0 ){
   45689     if( p->flags&PGHDR_CLEAN ){
   45690       pcacheUnpin(p);
   45691     }else{
   45692       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
   45693     }
   45694   }
   45695 }
   45696 
   45697 /*
   45698 ** Increase the reference count of a supplied page by 1.
   45699 */
   45700 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
   45701   assert(p->nRef>0);
   45702   assert( sqlite3PcachePageSanity(p) );
   45703   p->nRef++;
   45704   p->pCache->nRefSum++;
   45705 }
   45706 
   45707 /*
   45708 ** Drop a page from the cache. There must be exactly one reference to the
   45709 ** page. This function deletes that reference, so after it returns the
   45710 ** page pointed to by p is invalid.
   45711 */
   45712 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
   45713   assert( p->nRef==1 );
   45714   assert( sqlite3PcachePageSanity(p) );
   45715   if( p->flags&PGHDR_DIRTY ){
   45716     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
   45717   }
   45718   p->pCache->nRefSum--;
   45719   sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
   45720 }
   45721 
   45722 /*
   45723 ** Make sure the page is marked as dirty. If it isn't dirty already,
   45724 ** make it so.
   45725 */
   45726 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
   45727   assert( p->nRef>0 );
   45728   assert( sqlite3PcachePageSanity(p) );
   45729   if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
   45730     p->flags &= ~PGHDR_DONT_WRITE;
   45731     if( p->flags & PGHDR_CLEAN ){
   45732       p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
   45733       pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
   45734       assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
   45735       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
   45736     }
   45737     assert( sqlite3PcachePageSanity(p) );
   45738   }
   45739 }
   45740 
   45741 /*
   45742 ** Make sure the page is marked as clean. If it isn't clean already,
   45743 ** make it so.
   45744 */
   45745 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
   45746   assert( sqlite3PcachePageSanity(p) );
   45747   assert( (p->flags & PGHDR_DIRTY)!=0 );
   45748   assert( (p->flags & PGHDR_CLEAN)==0 );
   45749   pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
   45750   p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
   45751   p->flags |= PGHDR_CLEAN;
   45752   pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
   45753   assert( sqlite3PcachePageSanity(p) );
   45754   if( p->nRef==0 ){
   45755     pcacheUnpin(p);
   45756   }
   45757 }
   45758 
   45759 /*
   45760 ** Make every page in the cache clean.
   45761 */
   45762 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
   45763   PgHdr *p;
   45764   pcacheTrace(("%p.CLEAN-ALL\n",pCache));
   45765   while( (p = pCache->pDirty)!=0 ){
   45766     sqlite3PcacheMakeClean(p);
   45767   }
   45768 }
   45769 
   45770 /*
   45771 ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
   45772 */
   45773 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
   45774   PgHdr *p;
   45775   pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
   45776   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   45777     p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
   45778   }
   45779   pCache->pSynced = pCache->pDirtyTail;
   45780 }
   45781 
   45782 /*
   45783 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
   45784 */
   45785 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
   45786   PgHdr *p;
   45787   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   45788     p->flags &= ~PGHDR_NEED_SYNC;
   45789   }
   45790   pCache->pSynced = pCache->pDirtyTail;
   45791 }
   45792 
   45793 /*
   45794 ** Change the page number of page p to newPgno.
   45795 */
   45796 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   45797   PCache *pCache = p->pCache;
   45798   assert( p->nRef>0 );
   45799   assert( newPgno>0 );
   45800   assert( sqlite3PcachePageSanity(p) );
   45801   pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
   45802   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
   45803   p->pgno = newPgno;
   45804   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   45805     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
   45806   }
   45807 }
   45808 
   45809 /*
   45810 ** Drop every cache entry whose page number is greater than "pgno". The
   45811 ** caller must ensure that there are no outstanding references to any pages
   45812 ** other than page 1 with a page number greater than pgno.
   45813 **
   45814 ** If there is a reference to page 1 and the pgno parameter passed to this
   45815 ** function is 0, then the data area associated with page 1 is zeroed, but
   45816 ** the page object is not dropped.
   45817 */
   45818 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
   45819   if( pCache->pCache ){
   45820     PgHdr *p;
   45821     PgHdr *pNext;
   45822     pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
   45823     for(p=pCache->pDirty; p; p=pNext){
   45824       pNext = p->pDirtyNext;
   45825       /* This routine never gets call with a positive pgno except right
   45826       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
   45827       ** it must be that pgno==0.
   45828       */
   45829       assert( p->pgno>0 );
   45830       if( p->pgno>pgno ){
   45831         assert( p->flags&PGHDR_DIRTY );
   45832         sqlite3PcacheMakeClean(p);
   45833       }
   45834     }
   45835     if( pgno==0 && pCache->nRefSum ){
   45836       sqlite3_pcache_page *pPage1;
   45837       pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
   45838       if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
   45839                              ** pCache->nRefSum>0 */
   45840         memset(pPage1->pBuf, 0, pCache->szPage);
   45841         pgno = 1;
   45842       }
   45843     }
   45844     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
   45845   }
   45846 }
   45847 
   45848 /*
   45849 ** Close a cache.
   45850 */
   45851 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   45852   assert( pCache->pCache!=0 );
   45853   pcacheTrace(("%p.CLOSE\n",pCache));
   45854   sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   45855 }
   45856 
   45857 /*
   45858 ** Discard the contents of the cache.
   45859 */
   45860 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
   45861   sqlite3PcacheTruncate(pCache, 0);
   45862 }
   45863 
   45864 /*
   45865 ** Merge two lists of pages connected by pDirty and in pgno order.
   45866 ** Do not bother fixing the pDirtyPrev pointers.
   45867 */
   45868 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
   45869   PgHdr result, *pTail;
   45870   pTail = &result;
   45871   assert( pA!=0 && pB!=0 );
   45872   for(;;){
   45873     if( pA->pgno<pB->pgno ){
   45874       pTail->pDirty = pA;
   45875       pTail = pA;
   45876       pA = pA->pDirty;
   45877       if( pA==0 ){
   45878         pTail->pDirty = pB;
   45879         break;
   45880       }
   45881     }else{
   45882       pTail->pDirty = pB;
   45883       pTail = pB;
   45884       pB = pB->pDirty;
   45885       if( pB==0 ){
   45886         pTail->pDirty = pA;
   45887         break;
   45888       }
   45889     }
   45890   }
   45891   return result.pDirty;
   45892 }
   45893 
   45894 /*
   45895 ** Sort the list of pages in accending order by pgno.  Pages are
   45896 ** connected by pDirty pointers.  The pDirtyPrev pointers are
   45897 ** corrupted by this sort.
   45898 **
   45899 ** Since there cannot be more than 2^31 distinct pages in a database,
   45900 ** there cannot be more than 31 buckets required by the merge sorter.
   45901 ** One extra bucket is added to catch overflow in case something
   45902 ** ever changes to make the previous sentence incorrect.
   45903 */
   45904 #define N_SORT_BUCKET  32
   45905 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
   45906   PgHdr *a[N_SORT_BUCKET], *p;
   45907   int i;
   45908   memset(a, 0, sizeof(a));
   45909   while( pIn ){
   45910     p = pIn;
   45911     pIn = p->pDirty;
   45912     p->pDirty = 0;
   45913     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
   45914       if( a[i]==0 ){
   45915         a[i] = p;
   45916         break;
   45917       }else{
   45918         p = pcacheMergeDirtyList(a[i], p);
   45919         a[i] = 0;
   45920       }
   45921     }
   45922     if( NEVER(i==N_SORT_BUCKET-1) ){
   45923       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
   45924       ** the input list.  But that is impossible.
   45925       */
   45926       a[i] = pcacheMergeDirtyList(a[i], p);
   45927     }
   45928   }
   45929   p = a[0];
   45930   for(i=1; i<N_SORT_BUCKET; i++){
   45931     if( a[i]==0 ) continue;
   45932     p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
   45933   }
   45934   return p;
   45935 }
   45936 
   45937 /*
   45938 ** Return a list of all dirty pages in the cache, sorted by page number.
   45939 */
   45940 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   45941   PgHdr *p;
   45942   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   45943     p->pDirty = p->pDirtyNext;
   45944   }
   45945   return pcacheSortDirtyList(pCache->pDirty);
   45946 }
   45947 
   45948 /*
   45949 ** Return the total number of references to all pages held by the cache.
   45950 **
   45951 ** This is not the total number of pages referenced, but the sum of the
   45952 ** reference count for all pages.
   45953 */
   45954 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
   45955   return pCache->nRefSum;
   45956 }
   45957 
   45958 /*
   45959 ** Return the number of references to the page supplied as an argument.
   45960 */
   45961 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   45962   return p->nRef;
   45963 }
   45964 
   45965 /*
   45966 ** Return the total number of pages in the cache.
   45967 */
   45968 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
   45969   assert( pCache->pCache!=0 );
   45970   return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
   45971 }
   45972 
   45973 #ifdef SQLITE_TEST
   45974 /*
   45975 ** Get the suggested cache-size value.
   45976 */
   45977 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
   45978   return numberOfCachePages(pCache);
   45979 }
   45980 #endif
   45981 
   45982 /*
   45983 ** Set the suggested cache-size value.
   45984 */
   45985 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   45986   assert( pCache->pCache!=0 );
   45987   pCache->szCache = mxPage;
   45988   sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
   45989                                          numberOfCachePages(pCache));
   45990 }
   45991 
   45992 /*
   45993 ** Set the suggested cache-spill value.  Make no changes if if the
   45994 ** argument is zero.  Return the effective cache-spill size, which will
   45995 ** be the larger of the szSpill and szCache.
   45996 */
   45997 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
   45998   int res;
   45999   assert( p->pCache!=0 );
   46000   if( mxPage ){
   46001     if( mxPage<0 ){
   46002       mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
   46003     }
   46004     p->szSpill = mxPage;
   46005   }
   46006   res = numberOfCachePages(p);
   46007   if( res<p->szSpill ) res = p->szSpill;
   46008   return res;
   46009 }
   46010 
   46011 /*
   46012 ** Free up as much memory as possible from the page cache.
   46013 */
   46014 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
   46015   assert( pCache->pCache!=0 );
   46016   sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
   46017 }
   46018 
   46019 /*
   46020 ** Return the size of the header added by this middleware layer
   46021 ** in the page-cache hierarchy.
   46022 */
   46023 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
   46024 
   46025 /*
   46026 ** Return the number of dirty pages currently in the cache, as a percentage
   46027 ** of the configured cache size.
   46028 */
   46029 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
   46030   PgHdr *pDirty;
   46031   int nDirty = 0;
   46032   int nCache = numberOfCachePages(pCache);
   46033   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
   46034   return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
   46035 }
   46036 
   46037 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   46038 /*
   46039 ** For all dirty pages currently in the cache, invoke the specified
   46040 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
   46041 ** defined.
   46042 */
   46043 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
   46044   PgHdr *pDirty;
   46045   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
   46046     xIter(pDirty);
   46047   }
   46048 }
   46049 #endif
   46050 
   46051 /************** End of pcache.c **********************************************/
   46052 /************** Begin file pcache1.c *****************************************/
   46053 /*
   46054 ** 2008 November 05
   46055 **
   46056 ** The author disclaims copyright to this source code.  In place of
   46057 ** a legal notice, here is a blessing:
   46058 **
   46059 **    May you do good and not evil.
   46060 **    May you find forgiveness for yourself and forgive others.
   46061 **    May you share freely, never taking more than you give.
   46062 **
   46063 *************************************************************************
   46064 **
   46065 ** This file implements the default page cache implementation (the
   46066 ** sqlite3_pcache interface). It also contains part of the implementation
   46067 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
   46068 ** If the default page cache implementation is overridden, then neither of
   46069 ** these two features are available.
   46070 **
   46071 ** A Page cache line looks like this:
   46072 **
   46073 **  -------------------------------------------------------------
   46074 **  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
   46075 **  -------------------------------------------------------------
   46076 **
   46077 ** The database page content is up front (so that buffer overreads tend to
   46078 ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
   46079 ** is the extension added by the btree.c module containing information such
   46080 ** as the database page number and how that database page is used.  PgHdr
   46081 ** is added by the pcache.c layer and contains information used to keep track
   46082 ** of which pages are "dirty".  PgHdr1 is an extension added by this
   46083 ** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
   46084 ** PgHdr1 contains information needed to look up a page by its page number.
   46085 ** The superclass sqlite3_pcache_page.pBuf points to the start of the
   46086 ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
   46087 **
   46088 ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
   46089 ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
   46090 ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
   46091 ** size can vary according to architecture, compile-time options, and
   46092 ** SQLite library version number.
   46093 **
   46094 ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
   46095 ** using a separate memory allocation from the database page content.  This
   46096 ** seeks to overcome the "clownshoe" problem (also called "internal
   46097 ** fragmentation" in academic literature) of allocating a few bytes more
   46098 ** than a power of two with the memory allocator rounding up to the next
   46099 ** power of two, and leaving the rounded-up space unused.
   46100 **
   46101 ** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
   46102 ** with this module.  Information is passed back and forth as PgHdr1 pointers.
   46103 **
   46104 ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
   46105 ** The btree.c module deals with pointers to MemPage objects.
   46106 **
   46107 ** SOURCE OF PAGE CACHE MEMORY:
   46108 **
   46109 ** Memory for a page might come from any of three sources:
   46110 **
   46111 **    (1)  The general-purpose memory allocator - sqlite3Malloc()
   46112 **    (2)  Global page-cache memory provided using sqlite3_config() with
   46113 **         SQLITE_CONFIG_PAGECACHE.
   46114 **    (3)  PCache-local bulk allocation.
   46115 **
   46116 ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
   46117 ** that is allocated when the page cache is created.  The size of the local
   46118 ** bulk allocation can be adjusted using
   46119 **
   46120 **     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
   46121 **
   46122 ** If N is positive, then N pages worth of memory are allocated using a single
   46123 ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
   46124 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
   46125 ** for as many pages as can be accomodated.
   46126 **
   46127 ** Only one of (2) or (3) can be used.  Once the memory available to (2) or
   46128 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
   46129 ** memory allocator (1).
   46130 **
   46131 ** Earlier versions of SQLite used only methods (1) and (2).  But experiments
   46132 ** show that method (3) with N==100 provides about a 5% performance boost for
   46133 ** common workloads.
   46134 */
   46135 /* #include "sqliteInt.h" */
   46136 
   46137 typedef struct PCache1 PCache1;
   46138 typedef struct PgHdr1 PgHdr1;
   46139 typedef struct PgFreeslot PgFreeslot;
   46140 typedef struct PGroup PGroup;
   46141 
   46142 /*
   46143 ** Each cache entry is represented by an instance of the following
   46144 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
   46145 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
   46146 ** in memory.
   46147 */
   46148 struct PgHdr1 {
   46149   sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
   46150   unsigned int iKey;             /* Key value (page number) */
   46151   u8 isBulkLocal;                /* This page from bulk local storage */
   46152   u8 isAnchor;                   /* This is the PGroup.lru element */
   46153   PgHdr1 *pNext;                 /* Next in hash table chain */
   46154   PCache1 *pCache;               /* Cache that currently owns this page */
   46155   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   46156   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   46157 };
   46158 
   46159 /*
   46160 ** A page is pinned if it is no on the LRU list
   46161 */
   46162 #define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)
   46163 #define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)
   46164 
   46165 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
   46166 ** of one or more PCaches that are able to recycle each other's unpinned
   46167 ** pages when they are under memory pressure.  A PGroup is an instance of
   46168 ** the following object.
   46169 **
   46170 ** This page cache implementation works in one of two modes:
   46171 **
   46172 **   (1)  Every PCache is the sole member of its own PGroup.  There is
   46173 **        one PGroup per PCache.
   46174 **
   46175 **   (2)  There is a single global PGroup that all PCaches are a member
   46176 **        of.
   46177 **
   46178 ** Mode 1 uses more memory (since PCache instances are not able to rob
   46179 ** unused pages from other PCaches) but it also operates without a mutex,
   46180 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
   46181 ** threadsafe, but recycles pages more efficiently.
   46182 **
   46183 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
   46184 ** PGroup which is the pcache1.grp global variable and its mutex is
   46185 ** SQLITE_MUTEX_STATIC_LRU.
   46186 */
   46187 struct PGroup {
   46188   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
   46189   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
   46190   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
   46191   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
   46192   unsigned int nPurgeable;       /* Number of purgeable pages allocated */
   46193   PgHdr1 lru;                    /* The beginning and end of the LRU list */
   46194 };
   46195 
   46196 /* Each page cache is an instance of the following object.  Every
   46197 ** open database file (including each in-memory database and each
   46198 ** temporary or transient database) has a single page cache which
   46199 ** is an instance of this object.
   46200 **
   46201 ** Pointers to structures of this type are cast and returned as
   46202 ** opaque sqlite3_pcache* handles.
   46203 */
   46204 struct PCache1 {
   46205   /* Cache configuration parameters. Page size (szPage) and the purgeable
   46206   ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
   46207   ** cache is created and are never changed thereafter. nMax may be
   46208   ** modified at any time by a call to the pcache1Cachesize() method.
   46209   ** The PGroup mutex must be held when accessing nMax.
   46210   */
   46211   PGroup *pGroup;                     /* PGroup this cache belongs to */
   46212   unsigned int *pnPurgeable;          /* Pointer to pGroup->nPurgeable */
   46213   int szPage;                         /* Size of database content section */
   46214   int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
   46215   int szAlloc;                        /* Total size of one pcache line */
   46216   int bPurgeable;                     /* True if cache is purgeable */
   46217   unsigned int nMin;                  /* Minimum number of pages reserved */
   46218   unsigned int nMax;                  /* Configured "cache_size" value */
   46219   unsigned int n90pct;                /* nMax*9/10 */
   46220   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
   46221 
   46222   /* Hash table of all pages. The following variables may only be accessed
   46223   ** when the accessor is holding the PGroup mutex.
   46224   */
   46225   unsigned int nRecyclable;           /* Number of pages in the LRU list */
   46226   unsigned int nPage;                 /* Total number of pages in apHash */
   46227   unsigned int nHash;                 /* Number of slots in apHash[] */
   46228   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
   46229   PgHdr1 *pFree;                      /* List of unused pcache-local pages */
   46230   void *pBulk;                        /* Bulk memory used by pcache-local */
   46231 };
   46232 
   46233 /*
   46234 ** Free slots in the allocator used to divide up the global page cache
   46235 ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
   46236 */
   46237 struct PgFreeslot {
   46238   PgFreeslot *pNext;  /* Next free slot */
   46239 };
   46240 
   46241 /*
   46242 ** Global data used by this cache.
   46243 */
   46244 static SQLITE_WSD struct PCacheGlobal {
   46245   PGroup grp;                    /* The global PGroup for mode (2) */
   46246 
   46247   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
   46248   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
   46249   ** fixed at sqlite3_initialize() time and do not require mutex protection.
   46250   ** The nFreeSlot and pFree values do require mutex protection.
   46251   */
   46252   int isInit;                    /* True if initialized */
   46253   int separateCache;             /* Use a new PGroup for each PCache */
   46254   int nInitPage;                 /* Initial bulk allocation size */
   46255   int szSlot;                    /* Size of each free slot */
   46256   int nSlot;                     /* The number of pcache slots */
   46257   int nReserve;                  /* Try to keep nFreeSlot above this */
   46258   void *pStart, *pEnd;           /* Bounds of global page cache memory */
   46259   /* Above requires no mutex.  Use mutex below for variable that follow. */
   46260   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
   46261   PgFreeslot *pFree;             /* Free page blocks */
   46262   int nFreeSlot;                 /* Number of unused pcache slots */
   46263   /* The following value requires a mutex to change.  We skip the mutex on
   46264   ** reading because (1) most platforms read a 32-bit integer atomically and
   46265   ** (2) even if an incorrect value is read, no great harm is done since this
   46266   ** is really just an optimization. */
   46267   int bUnderPressure;            /* True if low on PAGECACHE memory */
   46268 } pcache1_g;
   46269 
   46270 /*
   46271 ** All code in this file should access the global structure above via the
   46272 ** alias "pcache1". This ensures that the WSD emulation is used when
   46273 ** compiling for systems that do not support real WSD.
   46274 */
   46275 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   46276 
   46277 /*
   46278 ** Macros to enter and leave the PCache LRU mutex.
   46279 */
   46280 #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
   46281 # define pcache1EnterMutex(X)  assert((X)->mutex==0)
   46282 # define pcache1LeaveMutex(X)  assert((X)->mutex==0)
   46283 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
   46284 #else
   46285 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
   46286 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
   46287 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
   46288 #endif
   46289 
   46290 /******************************************************************************/
   46291 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
   46292 
   46293 
   46294 /*
   46295 ** This function is called during initialization if a static buffer is
   46296 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
   46297 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
   46298 ** enough to contain 'n' buffers of 'sz' bytes each.
   46299 **
   46300 ** This routine is called from sqlite3_initialize() and so it is guaranteed
   46301 ** to be serialized already.  There is no need for further mutexing.
   46302 */
   46303 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
   46304   if( pcache1.isInit ){
   46305     PgFreeslot *p;
   46306     if( pBuf==0 ) sz = n = 0;
   46307     if( n==0 ) sz = 0;
   46308     sz = ROUNDDOWN8(sz);
   46309     pcache1.szSlot = sz;
   46310     pcache1.nSlot = pcache1.nFreeSlot = n;
   46311     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
   46312     pcache1.pStart = pBuf;
   46313     pcache1.pFree = 0;
   46314     pcache1.bUnderPressure = 0;
   46315     while( n-- ){
   46316       p = (PgFreeslot*)pBuf;
   46317       p->pNext = pcache1.pFree;
   46318       pcache1.pFree = p;
   46319       pBuf = (void*)&((char*)pBuf)[sz];
   46320     }
   46321     pcache1.pEnd = pBuf;
   46322   }
   46323 }
   46324 
   46325 /*
   46326 ** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
   46327 ** true if pCache->pFree ends up containing one or more free pages.
   46328 */
   46329 static int pcache1InitBulk(PCache1 *pCache){
   46330   i64 szBulk;
   46331   char *zBulk;
   46332   if( pcache1.nInitPage==0 ) return 0;
   46333   /* Do not bother with a bulk allocation if the cache size very small */
   46334   if( pCache->nMax<3 ) return 0;
   46335   sqlite3BeginBenignMalloc();
   46336   if( pcache1.nInitPage>0 ){
   46337     szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
   46338   }else{
   46339     szBulk = -1024 * (i64)pcache1.nInitPage;
   46340   }
   46341   if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
   46342     szBulk = pCache->szAlloc*(i64)pCache->nMax;
   46343   }
   46344   zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
   46345   sqlite3EndBenignMalloc();
   46346   if( zBulk ){
   46347     int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
   46348     do{
   46349       PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
   46350       pX->page.pBuf = zBulk;
   46351       pX->page.pExtra = &pX[1];
   46352       pX->isBulkLocal = 1;
   46353       pX->isAnchor = 0;
   46354       pX->pNext = pCache->pFree;
   46355       pCache->pFree = pX;
   46356       zBulk += pCache->szAlloc;
   46357     }while( --nBulk );
   46358   }
   46359   return pCache->pFree!=0;
   46360 }
   46361 
   46362 /*
   46363 ** Malloc function used within this file to allocate space from the buffer
   46364 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
   46365 ** such buffer exists or there is no space left in it, this function falls
   46366 ** back to sqlite3Malloc().
   46367 **
   46368 ** Multiple threads can run this routine at the same time.  Global variables
   46369 ** in pcache1 need to be protected via mutex.
   46370 */
   46371 static void *pcache1Alloc(int nByte){
   46372   void *p = 0;
   46373   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   46374   if( nByte<=pcache1.szSlot ){
   46375     sqlite3_mutex_enter(pcache1.mutex);
   46376     p = (PgHdr1 *)pcache1.pFree;
   46377     if( p ){
   46378       pcache1.pFree = pcache1.pFree->pNext;
   46379       pcache1.nFreeSlot--;
   46380       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   46381       assert( pcache1.nFreeSlot>=0 );
   46382       sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   46383       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
   46384     }
   46385     sqlite3_mutex_leave(pcache1.mutex);
   46386   }
   46387   if( p==0 ){
   46388     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
   46389     ** it from sqlite3Malloc instead.
   46390     */
   46391     p = sqlite3Malloc(nByte);
   46392 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   46393     if( p ){
   46394       int sz = sqlite3MallocSize(p);
   46395       sqlite3_mutex_enter(pcache1.mutex);
   46396       sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   46397       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
   46398       sqlite3_mutex_leave(pcache1.mutex);
   46399     }
   46400 #endif
   46401     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   46402   }
   46403   return p;
   46404 }
   46405 
   46406 /*
   46407 ** Free an allocated buffer obtained from pcache1Alloc().
   46408 */
   46409 static void pcache1Free(void *p){
   46410   if( p==0 ) return;
   46411   if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
   46412     PgFreeslot *pSlot;
   46413     sqlite3_mutex_enter(pcache1.mutex);
   46414     sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
   46415     pSlot = (PgFreeslot*)p;
   46416     pSlot->pNext = pcache1.pFree;
   46417     pcache1.pFree = pSlot;
   46418     pcache1.nFreeSlot++;
   46419     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   46420     assert( pcache1.nFreeSlot<=pcache1.nSlot );
   46421     sqlite3_mutex_leave(pcache1.mutex);
   46422   }else{
   46423     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   46424     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   46425 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   46426     {
   46427       int nFreed = 0;
   46428       nFreed = sqlite3MallocSize(p);
   46429       sqlite3_mutex_enter(pcache1.mutex);
   46430       sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
   46431       sqlite3_mutex_leave(pcache1.mutex);
   46432     }
   46433 #endif
   46434     sqlite3_free(p);
   46435   }
   46436 }
   46437 
   46438 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   46439 /*
   46440 ** Return the size of a pcache allocation
   46441 */
   46442 static int pcache1MemSize(void *p){
   46443   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   46444     return pcache1.szSlot;
   46445   }else{
   46446     int iSize;
   46447     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   46448     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   46449     iSize = sqlite3MallocSize(p);
   46450     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   46451     return iSize;
   46452   }
   46453 }
   46454 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   46455 
   46456 /*
   46457 ** Allocate a new page object initially associated with cache pCache.
   46458 */
   46459 static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
   46460   PgHdr1 *p = 0;
   46461   void *pPg;
   46462 
   46463   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   46464   if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
   46465     p = pCache->pFree;
   46466     pCache->pFree = p->pNext;
   46467     p->pNext = 0;
   46468   }else{
   46469 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   46470     /* The group mutex must be released before pcache1Alloc() is called. This
   46471     ** is because it might call sqlite3_release_memory(), which assumes that
   46472     ** this mutex is not held. */
   46473     assert( pcache1.separateCache==0 );
   46474     assert( pCache->pGroup==&pcache1.grp );
   46475     pcache1LeaveMutex(pCache->pGroup);
   46476 #endif
   46477     if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
   46478 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   46479     pPg = pcache1Alloc(pCache->szPage);
   46480     p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
   46481     if( !pPg || !p ){
   46482       pcache1Free(pPg);
   46483       sqlite3_free(p);
   46484       pPg = 0;
   46485     }
   46486 #else
   46487     pPg = pcache1Alloc(pCache->szAlloc);
   46488     p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
   46489 #endif
   46490     if( benignMalloc ){ sqlite3EndBenignMalloc(); }
   46491 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   46492     pcache1EnterMutex(pCache->pGroup);
   46493 #endif
   46494     if( pPg==0 ) return 0;
   46495     p->page.pBuf = pPg;
   46496     p->page.pExtra = &p[1];
   46497     p->isBulkLocal = 0;
   46498     p->isAnchor = 0;
   46499   }
   46500   (*pCache->pnPurgeable)++;
   46501   return p;
   46502 }
   46503 
   46504 /*
   46505 ** Free a page object allocated by pcache1AllocPage().
   46506 */
   46507 static void pcache1FreePage(PgHdr1 *p){
   46508   PCache1 *pCache;
   46509   assert( p!=0 );
   46510   pCache = p->pCache;
   46511   assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
   46512   if( p->isBulkLocal ){
   46513     p->pNext = pCache->pFree;
   46514     pCache->pFree = p;
   46515   }else{
   46516     pcache1Free(p->page.pBuf);
   46517 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   46518     sqlite3_free(p);
   46519 #endif
   46520   }
   46521   (*pCache->pnPurgeable)--;
   46522 }
   46523 
   46524 /*
   46525 ** Malloc function used by SQLite to obtain space from the buffer configured
   46526 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
   46527 ** exists, this function falls back to sqlite3Malloc().
   46528 */
   46529 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
   46530   return pcache1Alloc(sz);
   46531 }
   46532 
   46533 /*
   46534 ** Free an allocated buffer obtained from sqlite3PageMalloc().
   46535 */
   46536 SQLITE_PRIVATE void sqlite3PageFree(void *p){
   46537   pcache1Free(p);
   46538 }
   46539 
   46540 
   46541 /*
   46542 ** Return true if it desirable to avoid allocating a new page cache
   46543 ** entry.
   46544 **
   46545 ** If memory was allocated specifically to the page cache using
   46546 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
   46547 ** it is desirable to avoid allocating a new page cache entry because
   46548 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
   46549 ** for all page cache needs and we should not need to spill the
   46550 ** allocation onto the heap.
   46551 **
   46552 ** Or, the heap is used for all page cache memory but the heap is
   46553 ** under memory pressure, then again it is desirable to avoid
   46554 ** allocating a new page cache entry in order to avoid stressing
   46555 ** the heap even further.
   46556 */
   46557 static int pcache1UnderMemoryPressure(PCache1 *pCache){
   46558   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
   46559     return pcache1.bUnderPressure;
   46560   }else{
   46561     return sqlite3HeapNearlyFull();
   46562   }
   46563 }
   46564 
   46565 /******************************************************************************/
   46566 /******** General Implementation Functions ************************************/
   46567 
   46568 /*
   46569 ** This function is used to resize the hash table used by the cache passed
   46570 ** as the first argument.
   46571 **
   46572 ** The PCache mutex must be held when this function is called.
   46573 */
   46574 static void pcache1ResizeHash(PCache1 *p){
   46575   PgHdr1 **apNew;
   46576   unsigned int nNew;
   46577   unsigned int i;
   46578 
   46579   assert( sqlite3_mutex_held(p->pGroup->mutex) );
   46580 
   46581   nNew = p->nHash*2;
   46582   if( nNew<256 ){
   46583     nNew = 256;
   46584   }
   46585 
   46586   pcache1LeaveMutex(p->pGroup);
   46587   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
   46588   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
   46589   if( p->nHash ){ sqlite3EndBenignMalloc(); }
   46590   pcache1EnterMutex(p->pGroup);
   46591   if( apNew ){
   46592     for(i=0; i<p->nHash; i++){
   46593       PgHdr1 *pPage;
   46594       PgHdr1 *pNext = p->apHash[i];
   46595       while( (pPage = pNext)!=0 ){
   46596         unsigned int h = pPage->iKey % nNew;
   46597         pNext = pPage->pNext;
   46598         pPage->pNext = apNew[h];
   46599         apNew[h] = pPage;
   46600       }
   46601     }
   46602     sqlite3_free(p->apHash);
   46603     p->apHash = apNew;
   46604     p->nHash = nNew;
   46605   }
   46606 }
   46607 
   46608 /*
   46609 ** This function is used internally to remove the page pPage from the
   46610 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
   46611 ** LRU list, then this function is a no-op.
   46612 **
   46613 ** The PGroup mutex must be held when this function is called.
   46614 */
   46615 static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
   46616   assert( pPage!=0 );
   46617   assert( PAGE_IS_UNPINNED(pPage) );
   46618   assert( pPage->pLruNext );
   46619   assert( pPage->pLruPrev );
   46620   assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
   46621   pPage->pLruPrev->pLruNext = pPage->pLruNext;
   46622   pPage->pLruNext->pLruPrev = pPage->pLruPrev;
   46623   pPage->pLruNext = 0;
   46624   pPage->pLruPrev = 0;
   46625   assert( pPage->isAnchor==0 );
   46626   assert( pPage->pCache->pGroup->lru.isAnchor==1 );
   46627   pPage->pCache->nRecyclable--;
   46628   return pPage;
   46629 }
   46630 
   46631 
   46632 /*
   46633 ** Remove the page supplied as an argument from the hash table
   46634 ** (PCache1.apHash structure) that it is currently stored in.
   46635 ** Also free the page if freePage is true.
   46636 **
   46637 ** The PGroup mutex must be held when this function is called.
   46638 */
   46639 static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
   46640   unsigned int h;
   46641   PCache1 *pCache = pPage->pCache;
   46642   PgHdr1 **pp;
   46643 
   46644   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   46645   h = pPage->iKey % pCache->nHash;
   46646   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
   46647   *pp = (*pp)->pNext;
   46648 
   46649   pCache->nPage--;
   46650   if( freeFlag ) pcache1FreePage(pPage);
   46651 }
   46652 
   46653 /*
   46654 ** If there are currently more than nMaxPage pages allocated, try
   46655 ** to recycle pages to reduce the number allocated to nMaxPage.
   46656 */
   46657 static void pcache1EnforceMaxPage(PCache1 *pCache){
   46658   PGroup *pGroup = pCache->pGroup;
   46659   PgHdr1 *p;
   46660   assert( sqlite3_mutex_held(pGroup->mutex) );
   46661   while( pGroup->nPurgeable>pGroup->nMaxPage
   46662       && (p=pGroup->lru.pLruPrev)->isAnchor==0
   46663   ){
   46664     assert( p->pCache->pGroup==pGroup );
   46665     assert( PAGE_IS_UNPINNED(p) );
   46666     pcache1PinPage(p);
   46667     pcache1RemoveFromHash(p, 1);
   46668   }
   46669   if( pCache->nPage==0 && pCache->pBulk ){
   46670     sqlite3_free(pCache->pBulk);
   46671     pCache->pBulk = pCache->pFree = 0;
   46672   }
   46673 }
   46674 
   46675 /*
   46676 ** Discard all pages from cache pCache with a page number (key value)
   46677 ** greater than or equal to iLimit. Any pinned pages that meet this
   46678 ** criteria are unpinned before they are discarded.
   46679 **
   46680 ** The PCache mutex must be held when this function is called.
   46681 */
   46682 static void pcache1TruncateUnsafe(
   46683   PCache1 *pCache,             /* The cache to truncate */
   46684   unsigned int iLimit          /* Drop pages with this pgno or larger */
   46685 ){
   46686   TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
   46687   unsigned int h, iStop;
   46688   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   46689   assert( pCache->iMaxKey >= iLimit );
   46690   assert( pCache->nHash > 0 );
   46691   if( pCache->iMaxKey - iLimit < pCache->nHash ){
   46692     /* If we are just shaving the last few pages off the end of the
   46693     ** cache, then there is no point in scanning the entire hash table.
   46694     ** Only scan those hash slots that might contain pages that need to
   46695     ** be removed. */
   46696     h = iLimit % pCache->nHash;
   46697     iStop = pCache->iMaxKey % pCache->nHash;
   46698     TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
   46699   }else{
   46700     /* This is the general case where many pages are being removed.
   46701     ** It is necessary to scan the entire hash table */
   46702     h = pCache->nHash/2;
   46703     iStop = h - 1;
   46704   }
   46705   for(;;){
   46706     PgHdr1 **pp;
   46707     PgHdr1 *pPage;
   46708     assert( h<pCache->nHash );
   46709     pp = &pCache->apHash[h];
   46710     while( (pPage = *pp)!=0 ){
   46711       if( pPage->iKey>=iLimit ){
   46712         pCache->nPage--;
   46713         *pp = pPage->pNext;
   46714         if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
   46715         pcache1FreePage(pPage);
   46716       }else{
   46717         pp = &pPage->pNext;
   46718         TESTONLY( if( nPage>=0 ) nPage++; )
   46719       }
   46720     }
   46721     if( h==iStop ) break;
   46722     h = (h+1) % pCache->nHash;
   46723   }
   46724   assert( nPage<0 || pCache->nPage==(unsigned)nPage );
   46725 }
   46726 
   46727 /******************************************************************************/
   46728 /******** sqlite3_pcache Methods **********************************************/
   46729 
   46730 /*
   46731 ** Implementation of the sqlite3_pcache.xInit method.
   46732 */
   46733 static int pcache1Init(void *NotUsed){
   46734   UNUSED_PARAMETER(NotUsed);
   46735   assert( pcache1.isInit==0 );
   46736   memset(&pcache1, 0, sizeof(pcache1));
   46737 
   46738 
   46739   /*
   46740   ** The pcache1.separateCache variable is true if each PCache has its own
   46741   ** private PGroup (mode-1).  pcache1.separateCache is false if the single
   46742   ** PGroup in pcache1.grp is used for all page caches (mode-2).
   46743   **
   46744   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
   46745   **
   46746   **   *  Use a unified cache in single-threaded applications that have
   46747   **      configured a start-time buffer for use as page-cache memory using
   46748   **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
   46749   **      pBuf argument.
   46750   **
   46751   **   *  Otherwise use separate caches (mode-1)
   46752   */
   46753 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
   46754   pcache1.separateCache = 0;
   46755 #elif SQLITE_THREADSAFE
   46756   pcache1.separateCache = sqlite3GlobalConfig.pPage==0
   46757                           || sqlite3GlobalConfig.bCoreMutex>0;
   46758 #else
   46759   pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
   46760 #endif
   46761 
   46762 #if SQLITE_THREADSAFE
   46763   if( sqlite3GlobalConfig.bCoreMutex ){
   46764     pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
   46765     pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
   46766   }
   46767 #endif
   46768   if( pcache1.separateCache
   46769    && sqlite3GlobalConfig.nPage!=0
   46770    && sqlite3GlobalConfig.pPage==0
   46771   ){
   46772     pcache1.nInitPage = sqlite3GlobalConfig.nPage;
   46773   }else{
   46774     pcache1.nInitPage = 0;
   46775   }
   46776   pcache1.grp.mxPinned = 10;
   46777   pcache1.isInit = 1;
   46778   return SQLITE_OK;
   46779 }
   46780 
   46781 /*
   46782 ** Implementation of the sqlite3_pcache.xShutdown method.
   46783 ** Note that the static mutex allocated in xInit does
   46784 ** not need to be freed.
   46785 */
   46786 static void pcache1Shutdown(void *NotUsed){
   46787   UNUSED_PARAMETER(NotUsed);
   46788   assert( pcache1.isInit!=0 );
   46789   memset(&pcache1, 0, sizeof(pcache1));
   46790 }
   46791 
   46792 /* forward declaration */
   46793 static void pcache1Destroy(sqlite3_pcache *p);
   46794 
   46795 /*
   46796 ** Implementation of the sqlite3_pcache.xCreate method.
   46797 **
   46798 ** Allocate a new cache.
   46799 */
   46800 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
   46801   PCache1 *pCache;      /* The newly created page cache */
   46802   PGroup *pGroup;       /* The group the new page cache will belong to */
   46803   int sz;               /* Bytes of memory required to allocate the new cache */
   46804 
   46805   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
   46806   assert( szExtra < 300 );
   46807 
   46808   sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
   46809   pCache = (PCache1 *)sqlite3MallocZero(sz);
   46810   if( pCache ){
   46811     if( pcache1.separateCache ){
   46812       pGroup = (PGroup*)&pCache[1];
   46813       pGroup->mxPinned = 10;
   46814     }else{
   46815       pGroup = &pcache1.grp;
   46816     }
   46817     if( pGroup->lru.isAnchor==0 ){
   46818       pGroup->lru.isAnchor = 1;
   46819       pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
   46820     }
   46821     pCache->pGroup = pGroup;
   46822     pCache->szPage = szPage;
   46823     pCache->szExtra = szExtra;
   46824     pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
   46825     pCache->bPurgeable = (bPurgeable ? 1 : 0);
   46826     pcache1EnterMutex(pGroup);
   46827     pcache1ResizeHash(pCache);
   46828     if( bPurgeable ){
   46829       pCache->nMin = 10;
   46830       pGroup->nMinPage += pCache->nMin;
   46831       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   46832       pCache->pnPurgeable = &pGroup->nPurgeable;
   46833     }else{
   46834       static unsigned int dummyCurrentPage;
   46835       pCache->pnPurgeable = &dummyCurrentPage;
   46836     }
   46837     pcache1LeaveMutex(pGroup);
   46838     if( pCache->nHash==0 ){
   46839       pcache1Destroy((sqlite3_pcache*)pCache);
   46840       pCache = 0;
   46841     }
   46842   }
   46843   return (sqlite3_pcache *)pCache;
   46844 }
   46845 
   46846 /*
   46847 ** Implementation of the sqlite3_pcache.xCachesize method.
   46848 **
   46849 ** Configure the cache_size limit for a cache.
   46850 */
   46851 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   46852   PCache1 *pCache = (PCache1 *)p;
   46853   if( pCache->bPurgeable ){
   46854     PGroup *pGroup = pCache->pGroup;
   46855     pcache1EnterMutex(pGroup);
   46856     pGroup->nMaxPage += (nMax - pCache->nMax);
   46857     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   46858     pCache->nMax = nMax;
   46859     pCache->n90pct = pCache->nMax*9/10;
   46860     pcache1EnforceMaxPage(pCache);
   46861     pcache1LeaveMutex(pGroup);
   46862   }
   46863 }
   46864 
   46865 /*
   46866 ** Implementation of the sqlite3_pcache.xShrink method.
   46867 **
   46868 ** Free up as much memory as possible.
   46869 */
   46870 static void pcache1Shrink(sqlite3_pcache *p){
   46871   PCache1 *pCache = (PCache1*)p;
   46872   if( pCache->bPurgeable ){
   46873     PGroup *pGroup = pCache->pGroup;
   46874     int savedMaxPage;
   46875     pcache1EnterMutex(pGroup);
   46876     savedMaxPage = pGroup->nMaxPage;
   46877     pGroup->nMaxPage = 0;
   46878     pcache1EnforceMaxPage(pCache);
   46879     pGroup->nMaxPage = savedMaxPage;
   46880     pcache1LeaveMutex(pGroup);
   46881   }
   46882 }
   46883 
   46884 /*
   46885 ** Implementation of the sqlite3_pcache.xPagecount method.
   46886 */
   46887 static int pcache1Pagecount(sqlite3_pcache *p){
   46888   int n;
   46889   PCache1 *pCache = (PCache1*)p;
   46890   pcache1EnterMutex(pCache->pGroup);
   46891   n = pCache->nPage;
   46892   pcache1LeaveMutex(pCache->pGroup);
   46893   return n;
   46894 }
   46895 
   46896 
   46897 /*
   46898 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
   46899 ** in the header of the pcache1Fetch() procedure.
   46900 **
   46901 ** This steps are broken out into a separate procedure because they are
   46902 ** usually not needed, and by avoiding the stack initialization required
   46903 ** for these steps, the main pcache1Fetch() procedure can run faster.
   46904 */
   46905 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
   46906   PCache1 *pCache,
   46907   unsigned int iKey,
   46908   int createFlag
   46909 ){
   46910   unsigned int nPinned;
   46911   PGroup *pGroup = pCache->pGroup;
   46912   PgHdr1 *pPage = 0;
   46913 
   46914   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
   46915   assert( pCache->nPage >= pCache->nRecyclable );
   46916   nPinned = pCache->nPage - pCache->nRecyclable;
   46917   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
   46918   assert( pCache->n90pct == pCache->nMax*9/10 );
   46919   if( createFlag==1 && (
   46920         nPinned>=pGroup->mxPinned
   46921      || nPinned>=pCache->n90pct
   46922      || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
   46923   )){
   46924     return 0;
   46925   }
   46926 
   46927   if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
   46928   assert( pCache->nHash>0 && pCache->apHash );
   46929 
   46930   /* Step 4. Try to recycle a page. */
   46931   if( pCache->bPurgeable
   46932    && !pGroup->lru.pLruPrev->isAnchor
   46933    && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
   46934   ){
   46935     PCache1 *pOther;
   46936     pPage = pGroup->lru.pLruPrev;
   46937     assert( PAGE_IS_UNPINNED(pPage) );
   46938     pcache1RemoveFromHash(pPage, 0);
   46939     pcache1PinPage(pPage);
   46940     pOther = pPage->pCache;
   46941     if( pOther->szAlloc != pCache->szAlloc ){
   46942       pcache1FreePage(pPage);
   46943       pPage = 0;
   46944     }else{
   46945       pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
   46946     }
   46947   }
   46948 
   46949   /* Step 5. If a usable page buffer has still not been found,
   46950   ** attempt to allocate a new one.
   46951   */
   46952   if( !pPage ){
   46953     pPage = pcache1AllocPage(pCache, createFlag==1);
   46954   }
   46955 
   46956   if( pPage ){
   46957     unsigned int h = iKey % pCache->nHash;
   46958     pCache->nPage++;
   46959     pPage->iKey = iKey;
   46960     pPage->pNext = pCache->apHash[h];
   46961     pPage->pCache = pCache;
   46962     pPage->pLruPrev = 0;
   46963     pPage->pLruNext = 0;
   46964     *(void **)pPage->page.pExtra = 0;
   46965     pCache->apHash[h] = pPage;
   46966     if( iKey>pCache->iMaxKey ){
   46967       pCache->iMaxKey = iKey;
   46968     }
   46969   }
   46970   return pPage;
   46971 }
   46972 
   46973 /*
   46974 ** Implementation of the sqlite3_pcache.xFetch method.
   46975 **
   46976 ** Fetch a page by key value.
   46977 **
   46978 ** Whether or not a new page may be allocated by this function depends on
   46979 ** the value of the createFlag argument.  0 means do not allocate a new
   46980 ** page.  1 means allocate a new page if space is easily available.  2
   46981 ** means to try really hard to allocate a new page.
   46982 **
   46983 ** For a non-purgeable cache (a cache used as the storage for an in-memory
   46984 ** database) there is really no difference between createFlag 1 and 2.  So
   46985 ** the calling function (pcache.c) will never have a createFlag of 1 on
   46986 ** a non-purgeable cache.
   46987 **
   46988 ** There are three different approaches to obtaining space for a page,
   46989 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
   46990 **
   46991 **   1. Regardless of the value of createFlag, the cache is searched for a
   46992 **      copy of the requested page. If one is found, it is returned.
   46993 **
   46994 **   2. If createFlag==0 and the page is not already in the cache, NULL is
   46995 **      returned.
   46996 **
   46997 **   3. If createFlag is 1, and the page is not already in the cache, then
   46998 **      return NULL (do not allocate a new page) if any of the following
   46999 **      conditions are true:
   47000 **
   47001 **       (a) the number of pages pinned by the cache is greater than
   47002 **           PCache1.nMax, or
   47003 **
   47004 **       (b) the number of pages pinned by the cache is greater than
   47005 **           the sum of nMax for all purgeable caches, less the sum of
   47006 **           nMin for all other purgeable caches, or
   47007 **
   47008 **   4. If none of the first three conditions apply and the cache is marked
   47009 **      as purgeable, and if one of the following is true:
   47010 **
   47011 **       (a) The number of pages allocated for the cache is already
   47012 **           PCache1.nMax, or
   47013 **
   47014 **       (b) The number of pages allocated for all purgeable caches is
   47015 **           already equal to or greater than the sum of nMax for all
   47016 **           purgeable caches,
   47017 **
   47018 **       (c) The system is under memory pressure and wants to avoid
   47019 **           unnecessary pages cache entry allocations
   47020 **
   47021 **      then attempt to recycle a page from the LRU list. If it is the right
   47022 **      size, return the recycled buffer. Otherwise, free the buffer and
   47023 **      proceed to step 5.
   47024 **
   47025 **   5. Otherwise, allocate and return a new page buffer.
   47026 **
   47027 ** There are two versions of this routine.  pcache1FetchWithMutex() is
   47028 ** the general case.  pcache1FetchNoMutex() is a faster implementation for
   47029 ** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
   47030 ** invokes the appropriate routine.
   47031 */
   47032 static PgHdr1 *pcache1FetchNoMutex(
   47033   sqlite3_pcache *p,
   47034   unsigned int iKey,
   47035   int createFlag
   47036 ){
   47037   PCache1 *pCache = (PCache1 *)p;
   47038   PgHdr1 *pPage = 0;
   47039 
   47040   /* Step 1: Search the hash table for an existing entry. */
   47041   pPage = pCache->apHash[iKey % pCache->nHash];
   47042   while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
   47043 
   47044   /* Step 2: If the page was found in the hash table, then return it.
   47045   ** If the page was not in the hash table and createFlag is 0, abort.
   47046   ** Otherwise (page not in hash and createFlag!=0) continue with
   47047   ** subsequent steps to try to create the page. */
   47048   if( pPage ){
   47049     if( PAGE_IS_UNPINNED(pPage) ){
   47050       return pcache1PinPage(pPage);
   47051     }else{
   47052       return pPage;
   47053     }
   47054   }else if( createFlag ){
   47055     /* Steps 3, 4, and 5 implemented by this subroutine */
   47056     return pcache1FetchStage2(pCache, iKey, createFlag);
   47057   }else{
   47058     return 0;
   47059   }
   47060 }
   47061 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
   47062 static PgHdr1 *pcache1FetchWithMutex(
   47063   sqlite3_pcache *p,
   47064   unsigned int iKey,
   47065   int createFlag
   47066 ){
   47067   PCache1 *pCache = (PCache1 *)p;
   47068   PgHdr1 *pPage;
   47069 
   47070   pcache1EnterMutex(pCache->pGroup);
   47071   pPage = pcache1FetchNoMutex(p, iKey, createFlag);
   47072   assert( pPage==0 || pCache->iMaxKey>=iKey );
   47073   pcache1LeaveMutex(pCache->pGroup);
   47074   return pPage;
   47075 }
   47076 #endif
   47077 static sqlite3_pcache_page *pcache1Fetch(
   47078   sqlite3_pcache *p,
   47079   unsigned int iKey,
   47080   int createFlag
   47081 ){
   47082 #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
   47083   PCache1 *pCache = (PCache1 *)p;
   47084 #endif
   47085 
   47086   assert( offsetof(PgHdr1,page)==0 );
   47087   assert( pCache->bPurgeable || createFlag!=1 );
   47088   assert( pCache->bPurgeable || pCache->nMin==0 );
   47089   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
   47090   assert( pCache->nMin==0 || pCache->bPurgeable );
   47091   assert( pCache->nHash>0 );
   47092 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
   47093   if( pCache->pGroup->mutex ){
   47094     return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
   47095   }else
   47096 #endif
   47097   {
   47098     return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
   47099   }
   47100 }
   47101 
   47102 
   47103 /*
   47104 ** Implementation of the sqlite3_pcache.xUnpin method.
   47105 **
   47106 ** Mark a page as unpinned (eligible for asynchronous recycling).
   47107 */
   47108 static void pcache1Unpin(
   47109   sqlite3_pcache *p,
   47110   sqlite3_pcache_page *pPg,
   47111   int reuseUnlikely
   47112 ){
   47113   PCache1 *pCache = (PCache1 *)p;
   47114   PgHdr1 *pPage = (PgHdr1 *)pPg;
   47115   PGroup *pGroup = pCache->pGroup;
   47116 
   47117   assert( pPage->pCache==pCache );
   47118   pcache1EnterMutex(pGroup);
   47119 
   47120   /* It is an error to call this function if the page is already
   47121   ** part of the PGroup LRU list.
   47122   */
   47123   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
   47124   assert( PAGE_IS_PINNED(pPage) );
   47125 
   47126   if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
   47127     pcache1RemoveFromHash(pPage, 1);
   47128   }else{
   47129     /* Add the page to the PGroup LRU list. */
   47130     PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
   47131     pPage->pLruPrev = &pGroup->lru;
   47132     (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
   47133     *ppFirst = pPage;
   47134     pCache->nRecyclable++;
   47135   }
   47136 
   47137   pcache1LeaveMutex(pCache->pGroup);
   47138 }
   47139 
   47140 /*
   47141 ** Implementation of the sqlite3_pcache.xRekey method.
   47142 */
   47143 static void pcache1Rekey(
   47144   sqlite3_pcache *p,
   47145   sqlite3_pcache_page *pPg,
   47146   unsigned int iOld,
   47147   unsigned int iNew
   47148 ){
   47149   PCache1 *pCache = (PCache1 *)p;
   47150   PgHdr1 *pPage = (PgHdr1 *)pPg;
   47151   PgHdr1 **pp;
   47152   unsigned int h;
   47153   assert( pPage->iKey==iOld );
   47154   assert( pPage->pCache==pCache );
   47155 
   47156   pcache1EnterMutex(pCache->pGroup);
   47157 
   47158   h = iOld%pCache->nHash;
   47159   pp = &pCache->apHash[h];
   47160   while( (*pp)!=pPage ){
   47161     pp = &(*pp)->pNext;
   47162   }
   47163   *pp = pPage->pNext;
   47164 
   47165   h = iNew%pCache->nHash;
   47166   pPage->iKey = iNew;
   47167   pPage->pNext = pCache->apHash[h];
   47168   pCache->apHash[h] = pPage;
   47169   if( iNew>pCache->iMaxKey ){
   47170     pCache->iMaxKey = iNew;
   47171   }
   47172 
   47173   pcache1LeaveMutex(pCache->pGroup);
   47174 }
   47175 
   47176 /*
   47177 ** Implementation of the sqlite3_pcache.xTruncate method.
   47178 **
   47179 ** Discard all unpinned pages in the cache with a page number equal to
   47180 ** or greater than parameter iLimit. Any pinned pages with a page number
   47181 ** equal to or greater than iLimit are implicitly unpinned.
   47182 */
   47183 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
   47184   PCache1 *pCache = (PCache1 *)p;
   47185   pcache1EnterMutex(pCache->pGroup);
   47186   if( iLimit<=pCache->iMaxKey ){
   47187     pcache1TruncateUnsafe(pCache, iLimit);
   47188     pCache->iMaxKey = iLimit-1;
   47189   }
   47190   pcache1LeaveMutex(pCache->pGroup);
   47191 }
   47192 
   47193 /*
   47194 ** Implementation of the sqlite3_pcache.xDestroy method.
   47195 **
   47196 ** Destroy a cache allocated using pcache1Create().
   47197 */
   47198 static void pcache1Destroy(sqlite3_pcache *p){
   47199   PCache1 *pCache = (PCache1 *)p;
   47200   PGroup *pGroup = pCache->pGroup;
   47201   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
   47202   pcache1EnterMutex(pGroup);
   47203   if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
   47204   assert( pGroup->nMaxPage >= pCache->nMax );
   47205   pGroup->nMaxPage -= pCache->nMax;
   47206   assert( pGroup->nMinPage >= pCache->nMin );
   47207   pGroup->nMinPage -= pCache->nMin;
   47208   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   47209   pcache1EnforceMaxPage(pCache);
   47210   pcache1LeaveMutex(pGroup);
   47211   sqlite3_free(pCache->pBulk);
   47212   sqlite3_free(pCache->apHash);
   47213   sqlite3_free(pCache);
   47214 }
   47215 
   47216 /*
   47217 ** This function is called during initialization (sqlite3_initialize()) to
   47218 ** install the default pluggable cache module, assuming the user has not
   47219 ** already provided an alternative.
   47220 */
   47221 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
   47222   static const sqlite3_pcache_methods2 defaultMethods = {
   47223     1,                       /* iVersion */
   47224     0,                       /* pArg */
   47225     pcache1Init,             /* xInit */
   47226     pcache1Shutdown,         /* xShutdown */
   47227     pcache1Create,           /* xCreate */
   47228     pcache1Cachesize,        /* xCachesize */
   47229     pcache1Pagecount,        /* xPagecount */
   47230     pcache1Fetch,            /* xFetch */
   47231     pcache1Unpin,            /* xUnpin */
   47232     pcache1Rekey,            /* xRekey */
   47233     pcache1Truncate,         /* xTruncate */
   47234     pcache1Destroy,          /* xDestroy */
   47235     pcache1Shrink            /* xShrink */
   47236   };
   47237   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
   47238 }
   47239 
   47240 /*
   47241 ** Return the size of the header on each page of this PCACHE implementation.
   47242 */
   47243 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
   47244 
   47245 /*
   47246 ** Return the global mutex used by this PCACHE implementation.  The
   47247 ** sqlite3_status() routine needs access to this mutex.
   47248 */
   47249 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
   47250   return pcache1.mutex;
   47251 }
   47252 
   47253 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   47254 /*
   47255 ** This function is called to free superfluous dynamically allocated memory
   47256 ** held by the pager system. Memory in use by any SQLite pager allocated
   47257 ** by the current thread may be sqlite3_free()ed.
   47258 **
   47259 ** nReq is the number of bytes of memory required. Once this much has
   47260 ** been released, the function returns. The return value is the total number
   47261 ** of bytes of memory released.
   47262 */
   47263 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
   47264   int nFree = 0;
   47265   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   47266   assert( sqlite3_mutex_notheld(pcache1.mutex) );
   47267   if( sqlite3GlobalConfig.pPage==0 ){
   47268     PgHdr1 *p;
   47269     pcache1EnterMutex(&pcache1.grp);
   47270     while( (nReq<0 || nFree<nReq)
   47271        &&  (p=pcache1.grp.lru.pLruPrev)!=0
   47272        &&  p->isAnchor==0
   47273     ){
   47274       nFree += pcache1MemSize(p->page.pBuf);
   47275 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   47276       nFree += sqlite3MemSize(p);
   47277 #endif
   47278       assert( PAGE_IS_UNPINNED(p) );
   47279       pcache1PinPage(p);
   47280       pcache1RemoveFromHash(p, 1);
   47281     }
   47282     pcache1LeaveMutex(&pcache1.grp);
   47283   }
   47284   return nFree;
   47285 }
   47286 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   47287 
   47288 #ifdef SQLITE_TEST
   47289 /*
   47290 ** This function is used by test procedures to inspect the internal state
   47291 ** of the global cache.
   47292 */
   47293 SQLITE_PRIVATE void sqlite3PcacheStats(
   47294   int *pnCurrent,      /* OUT: Total number of pages cached */
   47295   int *pnMax,          /* OUT: Global maximum cache size */
   47296   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
   47297   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
   47298 ){
   47299   PgHdr1 *p;
   47300   int nRecyclable = 0;
   47301   for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
   47302     assert( PAGE_IS_UNPINNED(p) );
   47303     nRecyclable++;
   47304   }
   47305   *pnCurrent = pcache1.grp.nPurgeable;
   47306   *pnMax = (int)pcache1.grp.nMaxPage;
   47307   *pnMin = (int)pcache1.grp.nMinPage;
   47308   *pnRecyclable = nRecyclable;
   47309 }
   47310 #endif
   47311 
   47312 /************** End of pcache1.c *********************************************/
   47313 /************** Begin file rowset.c ******************************************/
   47314 /*
   47315 ** 2008 December 3
   47316 **
   47317 ** The author disclaims copyright to this source code.  In place of
   47318 ** a legal notice, here is a blessing:
   47319 **
   47320 **    May you do good and not evil.
   47321 **    May you find forgiveness for yourself and forgive others.
   47322 **    May you share freely, never taking more than you give.
   47323 **
   47324 *************************************************************************
   47325 **
   47326 ** This module implements an object we call a "RowSet".
   47327 **
   47328 ** The RowSet object is a collection of rowids.  Rowids
   47329 ** are inserted into the RowSet in an arbitrary order.  Inserts
   47330 ** can be intermixed with tests to see if a given rowid has been
   47331 ** previously inserted into the RowSet.
   47332 **
   47333 ** After all inserts are finished, it is possible to extract the
   47334 ** elements of the RowSet in sorted order.  Once this extraction
   47335 ** process has started, no new elements may be inserted.
   47336 **
   47337 ** Hence, the primitive operations for a RowSet are:
   47338 **
   47339 **    CREATE
   47340 **    INSERT
   47341 **    TEST
   47342 **    SMALLEST
   47343 **    DESTROY
   47344 **
   47345 ** The CREATE and DESTROY primitives are the constructor and destructor,
   47346 ** obviously.  The INSERT primitive adds a new element to the RowSet.
   47347 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
   47348 ** extracts the least value from the RowSet.
   47349 **
   47350 ** The INSERT primitive might allocate additional memory.  Memory is
   47351 ** allocated in chunks so most INSERTs do no allocation.  There is an
   47352 ** upper bound on the size of allocated memory.  No memory is freed
   47353 ** until DESTROY.
   47354 **
   47355 ** The TEST primitive includes a "batch" number.  The TEST primitive
   47356 ** will only see elements that were inserted before the last change
   47357 ** in the batch number.  In other words, if an INSERT occurs between
   47358 ** two TESTs where the TESTs have the same batch nubmer, then the
   47359 ** value added by the INSERT will not be visible to the second TEST.
   47360 ** The initial batch number is zero, so if the very first TEST contains
   47361 ** a non-zero batch number, it will see all prior INSERTs.
   47362 **
   47363 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
   47364 ** that is attempted.
   47365 **
   47366 ** The cost of an INSERT is roughly constant.  (Sometimes new memory
   47367 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
   47368 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
   47369 ** The cost of a TEST using the same batch number is O(logN).  The cost
   47370 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
   47371 ** primitives are constant time.  The cost of DESTROY is O(N).
   47372 **
   47373 ** TEST and SMALLEST may not be used by the same RowSet.  This used to
   47374 ** be possible, but the feature was not used, so it was removed in order
   47375 ** to simplify the code.
   47376 */
   47377 /* #include "sqliteInt.h" */
   47378 
   47379 
   47380 /*
   47381 ** Target size for allocation chunks.
   47382 */
   47383 #define ROWSET_ALLOCATION_SIZE 1024
   47384 
   47385 /*
   47386 ** The number of rowset entries per allocation chunk.
   47387 */
   47388 #define ROWSET_ENTRY_PER_CHUNK  \
   47389                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
   47390 
   47391 /*
   47392 ** Each entry in a RowSet is an instance of the following object.
   47393 **
   47394 ** This same object is reused to store a linked list of trees of RowSetEntry
   47395 ** objects.  In that alternative use, pRight points to the next entry
   47396 ** in the list, pLeft points to the tree, and v is unused.  The
   47397 ** RowSet.pForest value points to the head of this forest list.
   47398 */
   47399 struct RowSetEntry {
   47400   i64 v;                        /* ROWID value for this entry */
   47401   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   47402   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
   47403 };
   47404 
   47405 /*
   47406 ** RowSetEntry objects are allocated in large chunks (instances of the
   47407 ** following structure) to reduce memory allocation overhead.  The
   47408 ** chunks are kept on a linked list so that they can be deallocated
   47409 ** when the RowSet is destroyed.
   47410 */
   47411 struct RowSetChunk {
   47412   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
   47413   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
   47414 };
   47415 
   47416 /*
   47417 ** A RowSet in an instance of the following structure.
   47418 **
   47419 ** A typedef of this structure if found in sqliteInt.h.
   47420 */
   47421 struct RowSet {
   47422   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
   47423   sqlite3 *db;                   /* The database connection */
   47424   struct RowSetEntry *pEntry;    /* List of entries using pRight */
   47425   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
   47426   struct RowSetEntry *pFresh;    /* Source of new entry objects */
   47427   struct RowSetEntry *pForest;   /* List of binary trees of entries */
   47428   u16 nFresh;                    /* Number of objects on pFresh */
   47429   u16 rsFlags;                   /* Various flags */
   47430   int iBatch;                    /* Current insert batch */
   47431 };
   47432 
   47433 /*
   47434 ** Allowed values for RowSet.rsFlags
   47435 */
   47436 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
   47437 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
   47438 
   47439 /*
   47440 ** Turn bulk memory into a RowSet object.  N bytes of memory
   47441 ** are available at pSpace.  The db pointer is used as a memory context
   47442 ** for any subsequent allocations that need to occur.
   47443 ** Return a pointer to the new RowSet object.
   47444 **
   47445 ** It must be the case that N is sufficient to make a Rowset.  If not
   47446 ** an assertion fault occurs.
   47447 **
   47448 ** If N is larger than the minimum, use the surplus as an initial
   47449 ** allocation of entries available to be filled.
   47450 */
   47451 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
   47452   RowSet *p;
   47453   assert( N >= ROUND8(sizeof(*p)) );
   47454   p = pSpace;
   47455   p->pChunk = 0;
   47456   p->db = db;
   47457   p->pEntry = 0;
   47458   p->pLast = 0;
   47459   p->pForest = 0;
   47460   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
   47461   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
   47462   p->rsFlags = ROWSET_SORTED;
   47463   p->iBatch = 0;
   47464   return p;
   47465 }
   47466 
   47467 /*
   47468 ** Deallocate all chunks from a RowSet.  This frees all memory that
   47469 ** the RowSet has allocated over its lifetime.  This routine is
   47470 ** the destructor for the RowSet.
   47471 */
   47472 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
   47473   struct RowSetChunk *pChunk, *pNextChunk;
   47474   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
   47475     pNextChunk = pChunk->pNextChunk;
   47476     sqlite3DbFree(p->db, pChunk);
   47477   }
   47478   p->pChunk = 0;
   47479   p->nFresh = 0;
   47480   p->pEntry = 0;
   47481   p->pLast = 0;
   47482   p->pForest = 0;
   47483   p->rsFlags = ROWSET_SORTED;
   47484 }
   47485 
   47486 /*
   47487 ** Allocate a new RowSetEntry object that is associated with the
   47488 ** given RowSet.  Return a pointer to the new and completely uninitialized
   47489 ** objected.
   47490 **
   47491 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
   47492 ** routine returns NULL.
   47493 */
   47494 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
   47495   assert( p!=0 );
   47496   if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
   47497     /* We could allocate a fresh RowSetEntry each time one is needed, but it
   47498     ** is more efficient to pull a preallocated entry from the pool */
   47499     struct RowSetChunk *pNew;
   47500     pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
   47501     if( pNew==0 ){
   47502       return 0;
   47503     }
   47504     pNew->pNextChunk = p->pChunk;
   47505     p->pChunk = pNew;
   47506     p->pFresh = pNew->aEntry;
   47507     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
   47508   }
   47509   p->nFresh--;
   47510   return p->pFresh++;
   47511 }
   47512 
   47513 /*
   47514 ** Insert a new value into a RowSet.
   47515 **
   47516 ** The mallocFailed flag of the database connection is set if a
   47517 ** memory allocation fails.
   47518 */
   47519 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
   47520   struct RowSetEntry *pEntry;  /* The new entry */
   47521   struct RowSetEntry *pLast;   /* The last prior entry */
   47522 
   47523   /* This routine is never called after sqlite3RowSetNext() */
   47524   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
   47525 
   47526   pEntry = rowSetEntryAlloc(p);
   47527   if( pEntry==0 ) return;
   47528   pEntry->v = rowid;
   47529   pEntry->pRight = 0;
   47530   pLast = p->pLast;
   47531   if( pLast ){
   47532     if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
   47533       /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
   47534       ** where possible */
   47535       p->rsFlags &= ~ROWSET_SORTED;
   47536     }
   47537     pLast->pRight = pEntry;
   47538   }else{
   47539     p->pEntry = pEntry;
   47540   }
   47541   p->pLast = pEntry;
   47542 }
   47543 
   47544 /*
   47545 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
   47546 **
   47547 ** The input lists are connected via pRight pointers and are
   47548 ** assumed to each already be in sorted order.
   47549 */
   47550 static struct RowSetEntry *rowSetEntryMerge(
   47551   struct RowSetEntry *pA,    /* First sorted list to be merged */
   47552   struct RowSetEntry *pB     /* Second sorted list to be merged */
   47553 ){
   47554   struct RowSetEntry head;
   47555   struct RowSetEntry *pTail;
   47556 
   47557   pTail = &head;
   47558   assert( pA!=0 && pB!=0 );
   47559   for(;;){
   47560     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   47561     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
   47562     if( pA->v<=pB->v ){
   47563       if( pA->v<pB->v ) pTail = pTail->pRight = pA;
   47564       pA = pA->pRight;
   47565       if( pA==0 ){
   47566         pTail->pRight = pB;
   47567         break;
   47568       }
   47569     }else{
   47570       pTail = pTail->pRight = pB;
   47571       pB = pB->pRight;
   47572       if( pB==0 ){
   47573         pTail->pRight = pA;
   47574         break;
   47575       }
   47576     }
   47577   }
   47578   return head.pRight;
   47579 }
   47580 
   47581 /*
   47582 ** Sort all elements on the list of RowSetEntry objects into order of
   47583 ** increasing v.
   47584 */
   47585 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
   47586   unsigned int i;
   47587   struct RowSetEntry *pNext, *aBucket[40];
   47588 
   47589   memset(aBucket, 0, sizeof(aBucket));
   47590   while( pIn ){
   47591     pNext = pIn->pRight;
   47592     pIn->pRight = 0;
   47593     for(i=0; aBucket[i]; i++){
   47594       pIn = rowSetEntryMerge(aBucket[i], pIn);
   47595       aBucket[i] = 0;
   47596     }
   47597     aBucket[i] = pIn;
   47598     pIn = pNext;
   47599   }
   47600   pIn = aBucket[0];
   47601   for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
   47602     if( aBucket[i]==0 ) continue;
   47603     pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
   47604   }
   47605   return pIn;
   47606 }
   47607 
   47608 
   47609 /*
   47610 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
   47611 ** Convert this tree into a linked list connected by the pRight pointers
   47612 ** and return pointers to the first and last elements of the new list.
   47613 */
   47614 static void rowSetTreeToList(
   47615   struct RowSetEntry *pIn,         /* Root of the input tree */
   47616   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
   47617   struct RowSetEntry **ppLast      /* Write tail of the output list here */
   47618 ){
   47619   assert( pIn!=0 );
   47620   if( pIn->pLeft ){
   47621     struct RowSetEntry *p;
   47622     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
   47623     p->pRight = pIn;
   47624   }else{
   47625     *ppFirst = pIn;
   47626   }
   47627   if( pIn->pRight ){
   47628     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
   47629   }else{
   47630     *ppLast = pIn;
   47631   }
   47632   assert( (*ppLast)->pRight==0 );
   47633 }
   47634 
   47635 
   47636 /*
   47637 ** Convert a sorted list of elements (connected by pRight) into a binary
   47638 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
   47639 ** node taken from the head of *ppList.  A depth of 2 means a tree with
   47640 ** three nodes.  And so forth.
   47641 **
   47642 ** Use as many entries from the input list as required and update the
   47643 ** *ppList to point to the unused elements of the list.  If the input
   47644 ** list contains too few elements, then construct an incomplete tree
   47645 ** and leave *ppList set to NULL.
   47646 **
   47647 ** Return a pointer to the root of the constructed binary tree.
   47648 */
   47649 static struct RowSetEntry *rowSetNDeepTree(
   47650   struct RowSetEntry **ppList,
   47651   int iDepth
   47652 ){
   47653   struct RowSetEntry *p;         /* Root of the new tree */
   47654   struct RowSetEntry *pLeft;     /* Left subtree */
   47655   if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
   47656     /* Prevent unnecessary deep recursion when we run out of entries */
   47657     return 0;
   47658   }
   47659   if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
   47660     /* This branch causes a *balanced* tree to be generated.  A valid tree
   47661     ** is still generated without this branch, but the tree is wildly
   47662     ** unbalanced and inefficient. */
   47663     pLeft = rowSetNDeepTree(ppList, iDepth-1);
   47664     p = *ppList;
   47665     if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
   47666       /* It is safe to always return here, but the resulting tree
   47667       ** would be unbalanced */
   47668       return pLeft;
   47669     }
   47670     p->pLeft = pLeft;
   47671     *ppList = p->pRight;
   47672     p->pRight = rowSetNDeepTree(ppList, iDepth-1);
   47673   }else{
   47674     p = *ppList;
   47675     *ppList = p->pRight;
   47676     p->pLeft = p->pRight = 0;
   47677   }
   47678   return p;
   47679 }
   47680 
   47681 /*
   47682 ** Convert a sorted list of elements into a binary tree. Make the tree
   47683 ** as deep as it needs to be in order to contain the entire list.
   47684 */
   47685 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
   47686   int iDepth;           /* Depth of the tree so far */
   47687   struct RowSetEntry *p;       /* Current tree root */
   47688   struct RowSetEntry *pLeft;   /* Left subtree */
   47689 
   47690   assert( pList!=0 );
   47691   p = pList;
   47692   pList = p->pRight;
   47693   p->pLeft = p->pRight = 0;
   47694   for(iDepth=1; pList; iDepth++){
   47695     pLeft = p;
   47696     p = pList;
   47697     pList = p->pRight;
   47698     p->pLeft = pLeft;
   47699     p->pRight = rowSetNDeepTree(&pList, iDepth);
   47700   }
   47701   return p;
   47702 }
   47703 
   47704 /*
   47705 ** Extract the smallest element from the RowSet.
   47706 ** Write the element into *pRowid.  Return 1 on success.  Return
   47707 ** 0 if the RowSet is already empty.
   47708 **
   47709 ** After this routine has been called, the sqlite3RowSetInsert()
   47710 ** routine may not be called again.
   47711 **
   47712 ** This routine may not be called after sqlite3RowSetTest() has
   47713 ** been used.  Older versions of RowSet allowed that, but as the
   47714 ** capability was not used by the code generator, it was removed
   47715 ** for code economy.
   47716 */
   47717 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
   47718   assert( p!=0 );
   47719   assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
   47720 
   47721   /* Merge the forest into a single sorted list on first call */
   47722   if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
   47723     if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
   47724       p->pEntry = rowSetEntrySort(p->pEntry);
   47725     }
   47726     p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
   47727   }
   47728 
   47729   /* Return the next entry on the list */
   47730   if( p->pEntry ){
   47731     *pRowid = p->pEntry->v;
   47732     p->pEntry = p->pEntry->pRight;
   47733     if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
   47734       /* Free memory immediately, rather than waiting on sqlite3_finalize() */
   47735       sqlite3RowSetClear(p);
   47736     }
   47737     return 1;
   47738   }else{
   47739     return 0;
   47740   }
   47741 }
   47742 
   47743 /*
   47744 ** Check to see if element iRowid was inserted into the rowset as
   47745 ** part of any insert batch prior to iBatch.  Return 1 or 0.
   47746 **
   47747 ** If this is the first test of a new batch and if there exist entries
   47748 ** on pRowSet->pEntry, then sort those entries into the forest at
   47749 ** pRowSet->pForest so that they can be tested.
   47750 */
   47751 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
   47752   struct RowSetEntry *p, *pTree;
   47753 
   47754   /* This routine is never called after sqlite3RowSetNext() */
   47755   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
   47756 
   47757   /* Sort entries into the forest on the first test of a new batch.
   47758   ** To save unnecessary work, only do this when the batch number changes.
   47759   */
   47760   if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
   47761     p = pRowSet->pEntry;
   47762     if( p ){
   47763       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
   47764       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
   47765         /* Only sort the current set of entiries if they need it */
   47766         p = rowSetEntrySort(p);
   47767       }
   47768       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
   47769         ppPrevTree = &pTree->pRight;
   47770         if( pTree->pLeft==0 ){
   47771           pTree->pLeft = rowSetListToTree(p);
   47772           break;
   47773         }else{
   47774           struct RowSetEntry *pAux, *pTail;
   47775           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
   47776           pTree->pLeft = 0;
   47777           p = rowSetEntryMerge(pAux, p);
   47778         }
   47779       }
   47780       if( pTree==0 ){
   47781         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
   47782         if( pTree ){
   47783           pTree->v = 0;
   47784           pTree->pRight = 0;
   47785           pTree->pLeft = rowSetListToTree(p);
   47786         }
   47787       }
   47788       pRowSet->pEntry = 0;
   47789       pRowSet->pLast = 0;
   47790       pRowSet->rsFlags |= ROWSET_SORTED;
   47791     }
   47792     pRowSet->iBatch = iBatch;
   47793   }
   47794 
   47795   /* Test to see if the iRowid value appears anywhere in the forest.
   47796   ** Return 1 if it does and 0 if not.
   47797   */
   47798   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
   47799     p = pTree->pLeft;
   47800     while( p ){
   47801       if( p->v<iRowid ){
   47802         p = p->pRight;
   47803       }else if( p->v>iRowid ){
   47804         p = p->pLeft;
   47805       }else{
   47806         return 1;
   47807       }
   47808     }
   47809   }
   47810   return 0;
   47811 }
   47812 
   47813 /************** End of rowset.c **********************************************/
   47814 /************** Begin file pager.c *******************************************/
   47815 /*
   47816 ** 2001 September 15
   47817 **
   47818 ** The author disclaims copyright to this source code.  In place of
   47819 ** a legal notice, here is a blessing:
   47820 **
   47821 **    May you do good and not evil.
   47822 **    May you find forgiveness for yourself and forgive others.
   47823 **    May you share freely, never taking more than you give.
   47824 **
   47825 *************************************************************************
   47826 ** This is the implementation of the page cache subsystem or "pager".
   47827 **
   47828 ** The pager is used to access a database disk file.  It implements
   47829 ** atomic commit and rollback through the use of a journal file that
   47830 ** is separate from the database file.  The pager also implements file
   47831 ** locking to prevent two processes from writing the same database
   47832 ** file simultaneously, or one process from reading the database while
   47833 ** another is writing.
   47834 */
   47835 #ifndef SQLITE_OMIT_DISKIO
   47836 /* #include "sqliteInt.h" */
   47837 /************** Include wal.h in the middle of pager.c ***********************/
   47838 /************** Begin file wal.h *********************************************/
   47839 /*
   47840 ** 2010 February 1
   47841 **
   47842 ** The author disclaims copyright to this source code.  In place of
   47843 ** a legal notice, here is a blessing:
   47844 **
   47845 **    May you do good and not evil.
   47846 **    May you find forgiveness for yourself and forgive others.
   47847 **    May you share freely, never taking more than you give.
   47848 **
   47849 *************************************************************************
   47850 ** This header file defines the interface to the write-ahead logging
   47851 ** system. Refer to the comments below and the header comment attached to
   47852 ** the implementation of each function in log.c for further details.
   47853 */
   47854 
   47855 #ifndef SQLITE_WAL_H
   47856 #define SQLITE_WAL_H
   47857 
   47858 /* #include "sqliteInt.h" */
   47859 
   47860 /* Macros for extracting appropriate sync flags for either transaction
   47861 ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
   47862 */
   47863 #define WAL_SYNC_FLAGS(X)   ((X)&0x03)
   47864 #define CKPT_SYNC_FLAGS(X)  (((X)>>2)&0x03)
   47865 
   47866 #ifdef SQLITE_OMIT_WAL
   47867 # define sqlite3WalOpen(x,y,z)                   0
   47868 # define sqlite3WalLimit(x,y)
   47869 # define sqlite3WalClose(v,w,x,y,z)              0
   47870 # define sqlite3WalBeginReadTransaction(y,z)     0
   47871 # define sqlite3WalEndReadTransaction(z)
   47872 # define sqlite3WalDbsize(y)                     0
   47873 # define sqlite3WalBeginWriteTransaction(y)      0
   47874 # define sqlite3WalEndWriteTransaction(x)        0
   47875 # define sqlite3WalUndo(x,y,z)                   0
   47876 # define sqlite3WalSavepoint(y,z)
   47877 # define sqlite3WalSavepointUndo(y,z)            0
   47878 # define sqlite3WalFrames(u,v,w,x,y,z)           0
   47879 # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
   47880 # define sqlite3WalCallback(z)                   0
   47881 # define sqlite3WalExclusiveMode(y,z)            0
   47882 # define sqlite3WalHeapMemory(z)                 0
   47883 # define sqlite3WalFramesize(z)                  0
   47884 # define sqlite3WalFindFrame(x,y,z)              0
   47885 # define sqlite3WalFile(x)                       0
   47886 #else
   47887 
   47888 #define WAL_SAVEPOINT_NDATA 4
   47889 
   47890 /* Connection to a write-ahead log (WAL) file.
   47891 ** There is one object of this type for each pager.
   47892 */
   47893 typedef struct Wal Wal;
   47894 
   47895 /* Open and close a connection to a write-ahead log. */
   47896 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
   47897 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
   47898 
   47899 /* Set the limiting size of a WAL file. */
   47900 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
   47901 
   47902 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
   47903 ** snapshot is like a read-transaction.  It is the state of the database
   47904 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
   47905 ** preserves the current state even if the other threads or processes
   47906 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
   47907 ** transaction and releases the lock.
   47908 */
   47909 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
   47910 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
   47911 
   47912 /* Read a page from the write-ahead log, if it is present. */
   47913 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
   47914 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
   47915 
   47916 /* If the WAL is not empty, return the size of the database. */
   47917 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
   47918 
   47919 /* Obtain or release the WRITER lock. */
   47920 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
   47921 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
   47922 
   47923 /* Undo any frames written (but not committed) to the log */
   47924 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
   47925 
   47926 /* Return an integer that records the current (uncommitted) write
   47927 ** position in the WAL */
   47928 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
   47929 
   47930 /* Move the write position of the WAL back to iFrame.  Called in
   47931 ** response to a ROLLBACK TO command. */
   47932 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
   47933 
   47934 /* Write a frame or frames to the log. */
   47935 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
   47936 
   47937 /* Copy pages from the log to the database file */
   47938 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   47939   Wal *pWal,                      /* Write-ahead log connection */
   47940   sqlite3 *db,                    /* Check this handle's interrupt flag */
   47941   int eMode,                      /* One of PASSIVE, FULL and RESTART */
   47942   int (*xBusy)(void*),            /* Function to call when busy */
   47943   void *pBusyArg,                 /* Context argument for xBusyHandler */
   47944   int sync_flags,                 /* Flags to sync db file with (or 0) */
   47945   int nBuf,                       /* Size of buffer nBuf */
   47946   u8 *zBuf,                       /* Temporary buffer to use */
   47947   int *pnLog,                     /* OUT: Number of frames in WAL */
   47948   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   47949 );
   47950 
   47951 /* Return the value to pass to a sqlite3_wal_hook callback, the
   47952 ** number of frames in the WAL at the point of the last commit since
   47953 ** sqlite3WalCallback() was called.  If no commits have occurred since
   47954 ** the last call, then return 0.
   47955 */
   47956 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
   47957 
   47958 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
   47959 ** by the pager layer on the database file.
   47960 */
   47961 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
   47962 
   47963 /* Return true if the argument is non-NULL and the WAL module is using
   47964 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   47965 ** WAL module is using shared-memory, return false.
   47966 */
   47967 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
   47968 
   47969 #ifdef SQLITE_ENABLE_SNAPSHOT
   47970 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
   47971 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
   47972 SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
   47973 #endif
   47974 
   47975 #ifdef SQLITE_ENABLE_ZIPVFS
   47976 /* If the WAL file is not empty, return the number of bytes of content
   47977 ** stored in each frame (i.e. the db page-size when the WAL was created).
   47978 */
   47979 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
   47980 #endif
   47981 
   47982 /* Return the sqlite3_file object for the WAL file */
   47983 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
   47984 
   47985 #endif /* ifndef SQLITE_OMIT_WAL */
   47986 #endif /* SQLITE_WAL_H */
   47987 
   47988 /************** End of wal.h *************************************************/
   47989 /************** Continuing where we left off in pager.c **********************/
   47990 
   47991 
   47992 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
   47993 **
   47994 ** This comment block describes invariants that hold when using a rollback
   47995 ** journal.  These invariants do not apply for journal_mode=WAL,
   47996 ** journal_mode=MEMORY, or journal_mode=OFF.
   47997 **
   47998 ** Within this comment block, a page is deemed to have been synced
   47999 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
   48000 ** Otherwise, the page is not synced until the xSync method of the VFS
   48001 ** is called successfully on the file containing the page.
   48002 **
   48003 ** Definition:  A page of the database file is said to be "overwriteable" if
   48004 ** one or more of the following are true about the page:
   48005 **
   48006 **     (a)  The original content of the page as it was at the beginning of
   48007 **          the transaction has been written into the rollback journal and
   48008 **          synced.
   48009 **
   48010 **     (b)  The page was a freelist leaf page at the start of the transaction.
   48011 **
   48012 **     (c)  The page number is greater than the largest page that existed in
   48013 **          the database file at the start of the transaction.
   48014 **
   48015 ** (1) A page of the database file is never overwritten unless one of the
   48016 **     following are true:
   48017 **
   48018 **     (a) The page and all other pages on the same sector are overwriteable.
   48019 **
   48020 **     (b) The atomic page write optimization is enabled, and the entire
   48021 **         transaction other than the update of the transaction sequence
   48022 **         number consists of a single page change.
   48023 **
   48024 ** (2) The content of a page written into the rollback journal exactly matches
   48025 **     both the content in the database when the rollback journal was written
   48026 **     and the content in the database at the beginning of the current
   48027 **     transaction.
   48028 **
   48029 ** (3) Writes to the database file are an integer multiple of the page size
   48030 **     in length and are aligned on a page boundary.
   48031 **
   48032 ** (4) Reads from the database file are either aligned on a page boundary and
   48033 **     an integer multiple of the page size in length or are taken from the
   48034 **     first 100 bytes of the database file.
   48035 **
   48036 ** (5) All writes to the database file are synced prior to the rollback journal
   48037 **     being deleted, truncated, or zeroed.
   48038 **
   48039 ** (6) If a master journal file is used, then all writes to the database file
   48040 **     are synced prior to the master journal being deleted.
   48041 **
   48042 ** Definition: Two databases (or the same database at two points it time)
   48043 ** are said to be "logically equivalent" if they give the same answer to
   48044 ** all queries.  Note in particular the content of freelist leaf
   48045 ** pages can be changed arbitrarily without affecting the logical equivalence
   48046 ** of the database.
   48047 **
   48048 ** (7) At any time, if any subset, including the empty set and the total set,
   48049 **     of the unsynced changes to a rollback journal are removed and the
   48050 **     journal is rolled back, the resulting database file will be logically
   48051 **     equivalent to the database file at the beginning of the transaction.
   48052 **
   48053 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
   48054 **     is called to restore the database file to the same size it was at
   48055 **     the beginning of the transaction.  (In some VFSes, the xTruncate
   48056 **     method is a no-op, but that does not change the fact the SQLite will
   48057 **     invoke it.)
   48058 **
   48059 ** (9) Whenever the database file is modified, at least one bit in the range
   48060 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
   48061 **     the EXCLUSIVE lock, thus signaling other connections on the same
   48062 **     database to flush their caches.
   48063 **
   48064 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
   48065 **      than one billion transactions.
   48066 **
   48067 ** (11) A database file is well-formed at the beginning and at the conclusion
   48068 **      of every transaction.
   48069 **
   48070 ** (12) An EXCLUSIVE lock is held on the database file when writing to
   48071 **      the database file.
   48072 **
   48073 ** (13) A SHARED lock is held on the database file while reading any
   48074 **      content out of the database file.
   48075 **
   48076 ******************************************************************************/
   48077 
   48078 /*
   48079 ** Macros for troubleshooting.  Normally turned off
   48080 */
   48081 #if 0
   48082 int sqlite3PagerTrace=1;  /* True to enable tracing */
   48083 #define sqlite3DebugPrintf printf
   48084 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
   48085 #else
   48086 #define PAGERTRACE(X)
   48087 #endif
   48088 
   48089 /*
   48090 ** The following two macros are used within the PAGERTRACE() macros above
   48091 ** to print out file-descriptors.
   48092 **
   48093 ** PAGERID() takes a pointer to a Pager struct as its argument. The
   48094 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
   48095 ** struct as its argument.
   48096 */
   48097 #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
   48098 #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
   48099 
   48100 /*
   48101 ** The Pager.eState variable stores the current 'state' of a pager. A
   48102 ** pager may be in any one of the seven states shown in the following
   48103 ** state diagram.
   48104 **
   48105 **                            OPEN <------+------+
   48106 **                              |         |      |
   48107 **                              V         |      |
   48108 **               +---------> READER-------+      |
   48109 **               |              |                |
   48110 **               |              V                |
   48111 **               |<-------WRITER_LOCKED------> ERROR
   48112 **               |              |                ^
   48113 **               |              V                |
   48114 **               |<------WRITER_CACHEMOD-------->|
   48115 **               |              |                |
   48116 **               |              V                |
   48117 **               |<-------WRITER_DBMOD---------->|
   48118 **               |              |                |
   48119 **               |              V                |
   48120 **               +<------WRITER_FINISHED-------->+
   48121 **
   48122 **
   48123 ** List of state transitions and the C [function] that performs each:
   48124 **
   48125 **   OPEN              -> READER              [sqlite3PagerSharedLock]
   48126 **   READER            -> OPEN                [pager_unlock]
   48127 **
   48128 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
   48129 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
   48130 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
   48131 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
   48132 **   WRITER_***        -> READER              [pager_end_transaction]
   48133 **
   48134 **   WRITER_***        -> ERROR               [pager_error]
   48135 **   ERROR             -> OPEN                [pager_unlock]
   48136 **
   48137 **
   48138 **  OPEN:
   48139 **
   48140 **    The pager starts up in this state. Nothing is guaranteed in this
   48141 **    state - the file may or may not be locked and the database size is
   48142 **    unknown. The database may not be read or written.
   48143 **
   48144 **    * No read or write transaction is active.
   48145 **    * Any lock, or no lock at all, may be held on the database file.
   48146 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
   48147 **
   48148 **  READER:
   48149 **
   48150 **    In this state all the requirements for reading the database in
   48151 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
   48152 **    was) in exclusive-locking mode, a user-level read transaction is
   48153 **    open. The database size is known in this state.
   48154 **
   48155 **    A connection running with locking_mode=normal enters this state when
   48156 **    it opens a read-transaction on the database and returns to state
   48157 **    OPEN after the read-transaction is completed. However a connection
   48158 **    running in locking_mode=exclusive (including temp databases) remains in
   48159 **    this state even after the read-transaction is closed. The only way
   48160 **    a locking_mode=exclusive connection can transition from READER to OPEN
   48161 **    is via the ERROR state (see below).
   48162 **
   48163 **    * A read transaction may be active (but a write-transaction cannot).
   48164 **    * A SHARED or greater lock is held on the database file.
   48165 **    * The dbSize variable may be trusted (even if a user-level read
   48166 **      transaction is not active). The dbOrigSize and dbFileSize variables
   48167 **      may not be trusted at this point.
   48168 **    * If the database is a WAL database, then the WAL connection is open.
   48169 **    * Even if a read-transaction is not open, it is guaranteed that
   48170 **      there is no hot-journal in the file-system.
   48171 **
   48172 **  WRITER_LOCKED:
   48173 **
   48174 **    The pager moves to this state from READER when a write-transaction
   48175 **    is first opened on the database. In WRITER_LOCKED state, all locks
   48176 **    required to start a write-transaction are held, but no actual
   48177 **    modifications to the cache or database have taken place.
   48178 **
   48179 **    In rollback mode, a RESERVED or (if the transaction was opened with
   48180 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
   48181 **    moving to this state, but the journal file is not written to or opened
   48182 **    to in this state. If the transaction is committed or rolled back while
   48183 **    in WRITER_LOCKED state, all that is required is to unlock the database
   48184 **    file.
   48185 **
   48186 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
   48187 **    If the connection is running with locking_mode=exclusive, an attempt
   48188 **    is made to obtain an EXCLUSIVE lock on the database file.
   48189 **
   48190 **    * A write transaction is active.
   48191 **    * If the connection is open in rollback-mode, a RESERVED or greater
   48192 **      lock is held on the database file.
   48193 **    * If the connection is open in WAL-mode, a WAL write transaction
   48194 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
   48195 **      called).
   48196 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
   48197 **    * The contents of the pager cache have not been modified.
   48198 **    * The journal file may or may not be open.
   48199 **    * Nothing (not even the first header) has been written to the journal.
   48200 **
   48201 **  WRITER_CACHEMOD:
   48202 **
   48203 **    A pager moves from WRITER_LOCKED state to this state when a page is
   48204 **    first modified by the upper layer. In rollback mode the journal file
   48205 **    is opened (if it is not already open) and a header written to the
   48206 **    start of it. The database file on disk has not been modified.
   48207 **
   48208 **    * A write transaction is active.
   48209 **    * A RESERVED or greater lock is held on the database file.
   48210 **    * The journal file is open and the first header has been written
   48211 **      to it, but the header has not been synced to disk.
   48212 **    * The contents of the page cache have been modified.
   48213 **
   48214 **  WRITER_DBMOD:
   48215 **
   48216 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
   48217 **    when it modifies the contents of the database file. WAL connections
   48218 **    never enter this state (since they do not modify the database file,
   48219 **    just the log file).
   48220 **
   48221 **    * A write transaction is active.
   48222 **    * An EXCLUSIVE or greater lock is held on the database file.
   48223 **    * The journal file is open and the first header has been written
   48224 **      and synced to disk.
   48225 **    * The contents of the page cache have been modified (and possibly
   48226 **      written to disk).
   48227 **
   48228 **  WRITER_FINISHED:
   48229 **
   48230 **    It is not possible for a WAL connection to enter this state.
   48231 **
   48232 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
   48233 **    state after the entire transaction has been successfully written into the
   48234 **    database file. In this state the transaction may be committed simply
   48235 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
   48236 **    not possible to modify the database further. At this point, the upper
   48237 **    layer must either commit or rollback the transaction.
   48238 **
   48239 **    * A write transaction is active.
   48240 **    * An EXCLUSIVE or greater lock is held on the database file.
   48241 **    * All writing and syncing of journal and database data has finished.
   48242 **      If no error occurred, all that remains is to finalize the journal to
   48243 **      commit the transaction. If an error did occur, the caller will need
   48244 **      to rollback the transaction.
   48245 **
   48246 **  ERROR:
   48247 **
   48248 **    The ERROR state is entered when an IO or disk-full error (including
   48249 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
   48250 **    difficult to be sure that the in-memory pager state (cache contents,
   48251 **    db size etc.) are consistent with the contents of the file-system.
   48252 **
   48253 **    Temporary pager files may enter the ERROR state, but in-memory pagers
   48254 **    cannot.
   48255 **
   48256 **    For example, if an IO error occurs while performing a rollback,
   48257 **    the contents of the page-cache may be left in an inconsistent state.
   48258 **    At this point it would be dangerous to change back to READER state
   48259 **    (as usually happens after a rollback). Any subsequent readers might
   48260 **    report database corruption (due to the inconsistent cache), and if
   48261 **    they upgrade to writers, they may inadvertently corrupt the database
   48262 **    file. To avoid this hazard, the pager switches into the ERROR state
   48263 **    instead of READER following such an error.
   48264 **
   48265 **    Once it has entered the ERROR state, any attempt to use the pager
   48266 **    to read or write data returns an error. Eventually, once all
   48267 **    outstanding transactions have been abandoned, the pager is able to
   48268 **    transition back to OPEN state, discarding the contents of the
   48269 **    page-cache and any other in-memory state at the same time. Everything
   48270 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
   48271 **    when a read-transaction is next opened on the pager (transitioning
   48272 **    the pager into READER state). At that point the system has recovered
   48273 **    from the error.
   48274 **
   48275 **    Specifically, the pager jumps into the ERROR state if:
   48276 **
   48277 **      1. An error occurs while attempting a rollback. This happens in
   48278 **         function sqlite3PagerRollback().
   48279 **
   48280 **      2. An error occurs while attempting to finalize a journal file
   48281 **         following a commit in function sqlite3PagerCommitPhaseTwo().
   48282 **
   48283 **      3. An error occurs while attempting to write to the journal or
   48284 **         database file in function pagerStress() in order to free up
   48285 **         memory.
   48286 **
   48287 **    In other cases, the error is returned to the b-tree layer. The b-tree
   48288 **    layer then attempts a rollback operation. If the error condition
   48289 **    persists, the pager enters the ERROR state via condition (1) above.
   48290 **
   48291 **    Condition (3) is necessary because it can be triggered by a read-only
   48292 **    statement executed within a transaction. In this case, if the error
   48293 **    code were simply returned to the user, the b-tree layer would not
   48294 **    automatically attempt a rollback, as it assumes that an error in a
   48295 **    read-only statement cannot leave the pager in an internally inconsistent
   48296 **    state.
   48297 **
   48298 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
   48299 **    * There are one or more outstanding references to pages (after the
   48300 **      last reference is dropped the pager should move back to OPEN state).
   48301 **    * The pager is not an in-memory pager.
   48302 **
   48303 **
   48304 ** Notes:
   48305 **
   48306 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
   48307 **     connection is open in WAL mode. A WAL connection is always in one
   48308 **     of the first four states.
   48309 **
   48310 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
   48311 **     state. There are two exceptions: immediately after exclusive-mode has
   48312 **     been turned on (and before any read or write transactions are
   48313 **     executed), and when the pager is leaving the "error state".
   48314 **
   48315 **   * See also: assert_pager_state().
   48316 */
   48317 #define PAGER_OPEN                  0
   48318 #define PAGER_READER                1
   48319 #define PAGER_WRITER_LOCKED         2
   48320 #define PAGER_WRITER_CACHEMOD       3
   48321 #define PAGER_WRITER_DBMOD          4
   48322 #define PAGER_WRITER_FINISHED       5
   48323 #define PAGER_ERROR                 6
   48324 
   48325 /*
   48326 ** The Pager.eLock variable is almost always set to one of the
   48327 ** following locking-states, according to the lock currently held on
   48328 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   48329 ** This variable is kept up to date as locks are taken and released by
   48330 ** the pagerLockDb() and pagerUnlockDb() wrappers.
   48331 **
   48332 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
   48333 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
   48334 ** the operation was successful. In these circumstances pagerLockDb() and
   48335 ** pagerUnlockDb() take a conservative approach - eLock is always updated
   48336 ** when unlocking the file, and only updated when locking the file if the
   48337 ** VFS call is successful. This way, the Pager.eLock variable may be set
   48338 ** to a less exclusive (lower) value than the lock that is actually held
   48339 ** at the system level, but it is never set to a more exclusive value.
   48340 **
   48341 ** This is usually safe. If an xUnlock fails or appears to fail, there may
   48342 ** be a few redundant xLock() calls or a lock may be held for longer than
   48343 ** required, but nothing really goes wrong.
   48344 **
   48345 ** The exception is when the database file is unlocked as the pager moves
   48346 ** from ERROR to OPEN state. At this point there may be a hot-journal file
   48347 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
   48348 ** transition, by the same pager or any other). If the call to xUnlock()
   48349 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
   48350 ** can confuse the call to xCheckReservedLock() call made later as part
   48351 ** of hot-journal detection.
   48352 **
   48353 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
   48354 ** lock held by this process or any others". So xCheckReservedLock may
   48355 ** return true because the caller itself is holding an EXCLUSIVE lock (but
   48356 ** doesn't know it because of a previous error in xUnlock). If this happens
   48357 ** a hot-journal may be mistaken for a journal being created by an active
   48358 ** transaction in another process, causing SQLite to read from the database
   48359 ** without rolling it back.
   48360 **
   48361 ** To work around this, if a call to xUnlock() fails when unlocking the
   48362 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
   48363 ** is only changed back to a real locking state after a successful call
   48364 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
   48365 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
   48366 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
   48367 ** lock on the database file before attempting to roll it back. See function
   48368 ** PagerSharedLock() for more detail.
   48369 **
   48370 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
   48371 ** PAGER_OPEN state.
   48372 */
   48373 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
   48374 
   48375 /*
   48376 ** A macro used for invoking the codec if there is one
   48377 */
   48378 #ifdef SQLITE_HAS_CODEC
   48379 # define CODEC1(P,D,N,X,E) \
   48380     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
   48381 # define CODEC2(P,D,N,X,E,O) \
   48382     if( P->xCodec==0 ){ O=(char*)D; }else \
   48383     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
   48384 #else
   48385 # define CODEC1(P,D,N,X,E)   /* NO-OP */
   48386 # define CODEC2(P,D,N,X,E,O) O=(char*)D
   48387 #endif
   48388 
   48389 /*
   48390 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
   48391 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
   48392 ** This could conceivably cause corruption following a power failure on
   48393 ** such a system. This is currently an undocumented limit.
   48394 */
   48395 #define MAX_SECTOR_SIZE 0x10000
   48396 
   48397 
   48398 /*
   48399 ** An instance of the following structure is allocated for each active
   48400 ** savepoint and statement transaction in the system. All such structures
   48401 ** are stored in the Pager.aSavepoint[] array, which is allocated and
   48402 ** resized using sqlite3Realloc().
   48403 **
   48404 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
   48405 ** set to 0. If a journal-header is written into the main journal while
   48406 ** the savepoint is active, then iHdrOffset is set to the byte offset
   48407 ** immediately following the last journal record written into the main
   48408 ** journal before the journal-header. This is required during savepoint
   48409 ** rollback (see pagerPlaybackSavepoint()).
   48410 */
   48411 typedef struct PagerSavepoint PagerSavepoint;
   48412 struct PagerSavepoint {
   48413   i64 iOffset;                 /* Starting offset in main journal */
   48414   i64 iHdrOffset;              /* See above */
   48415   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   48416   Pgno nOrig;                  /* Original number of pages in file */
   48417   Pgno iSubRec;                /* Index of first record in sub-journal */
   48418 #ifndef SQLITE_OMIT_WAL
   48419   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
   48420 #endif
   48421 };
   48422 
   48423 /*
   48424 ** Bits of the Pager.doNotSpill flag.  See further description below.
   48425 */
   48426 #define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
   48427 #define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
   48428 #define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
   48429 
   48430 /*
   48431 ** An open page cache is an instance of struct Pager. A description of
   48432 ** some of the more important member variables follows:
   48433 **
   48434 ** eState
   48435 **
   48436 **   The current 'state' of the pager object. See the comment and state
   48437 **   diagram above for a description of the pager state.
   48438 **
   48439 ** eLock
   48440 **
   48441 **   For a real on-disk database, the current lock held on the database file -
   48442 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   48443 **
   48444 **   For a temporary or in-memory database (neither of which require any
   48445 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
   48446 **   databases always have Pager.exclusiveMode==1, this tricks the pager
   48447 **   logic into thinking that it already has all the locks it will ever
   48448 **   need (and no reason to release them).
   48449 **
   48450 **   In some (obscure) circumstances, this variable may also be set to
   48451 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
   48452 **   details.
   48453 **
   48454 ** changeCountDone
   48455 **
   48456 **   This boolean variable is used to make sure that the change-counter
   48457 **   (the 4-byte header field at byte offset 24 of the database file) is
   48458 **   not updated more often than necessary.
   48459 **
   48460 **   It is set to true when the change-counter field is updated, which
   48461 **   can only happen if an exclusive lock is held on the database file.
   48462 **   It is cleared (set to false) whenever an exclusive lock is
   48463 **   relinquished on the database file. Each time a transaction is committed,
   48464 **   The changeCountDone flag is inspected. If it is true, the work of
   48465 **   updating the change-counter is omitted for the current transaction.
   48466 **
   48467 **   This mechanism means that when running in exclusive mode, a connection
   48468 **   need only update the change-counter once, for the first transaction
   48469 **   committed.
   48470 **
   48471 ** setMaster
   48472 **
   48473 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
   48474 **   (or may not) specify a master-journal name to be written into the
   48475 **   journal file before it is synced to disk.
   48476 **
   48477 **   Whether or not a journal file contains a master-journal pointer affects
   48478 **   the way in which the journal file is finalized after the transaction is
   48479 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
   48480 **   If a journal file does not contain a master-journal pointer, it is
   48481 **   finalized by overwriting the first journal header with zeroes. If
   48482 **   it does contain a master-journal pointer the journal file is finalized
   48483 **   by truncating it to zero bytes, just as if the connection were
   48484 **   running in "journal_mode=truncate" mode.
   48485 **
   48486 **   Journal files that contain master journal pointers cannot be finalized
   48487 **   simply by overwriting the first journal-header with zeroes, as the
   48488 **   master journal pointer could interfere with hot-journal rollback of any
   48489 **   subsequently interrupted transaction that reuses the journal file.
   48490 **
   48491 **   The flag is cleared as soon as the journal file is finalized (either
   48492 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
   48493 **   journal file from being successfully finalized, the setMaster flag
   48494 **   is cleared anyway (and the pager will move to ERROR state).
   48495 **
   48496 ** doNotSpill
   48497 **
   48498 **   This variables control the behavior of cache-spills  (calls made by
   48499 **   the pcache module to the pagerStress() routine to write cached data
   48500 **   to the file-system in order to free up memory).
   48501 **
   48502 **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
   48503 **   writing to the database from pagerStress() is disabled altogether.
   48504 **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
   48505 **   comes up during savepoint rollback that requires the pcache module
   48506 **   to allocate a new page to prevent the journal file from being written
   48507 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
   48508 **   case is a user preference.
   48509 **
   48510 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
   48511 **   pagerStress() is permitted, but syncing the journal file is not.
   48512 **   This flag is set by sqlite3PagerWrite() when the file-system sector-size
   48513 **   is larger than the database page-size in order to prevent a journal sync
   48514 **   from happening in between the journalling of two pages on the same sector.
   48515 **
   48516 ** subjInMemory
   48517 **
   48518 **   This is a boolean variable. If true, then any required sub-journal
   48519 **   is opened as an in-memory journal file. If false, then in-memory
   48520 **   sub-journals are only used for in-memory pager files.
   48521 **
   48522 **   This variable is updated by the upper layer each time a new
   48523 **   write-transaction is opened.
   48524 **
   48525 ** dbSize, dbOrigSize, dbFileSize
   48526 **
   48527 **   Variable dbSize is set to the number of pages in the database file.
   48528 **   It is valid in PAGER_READER and higher states (all states except for
   48529 **   OPEN and ERROR).
   48530 **
   48531 **   dbSize is set based on the size of the database file, which may be
   48532 **   larger than the size of the database (the value stored at offset
   48533 **   28 of the database header by the btree). If the size of the file
   48534 **   is not an integer multiple of the page-size, the value stored in
   48535 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
   48536 **   Except, any file that is greater than 0 bytes in size is considered
   48537 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
   48538 **   to dbSize==1).
   48539 **
   48540 **   During a write-transaction, if pages with page-numbers greater than
   48541 **   dbSize are modified in the cache, dbSize is updated accordingly.
   48542 **   Similarly, if the database is truncated using PagerTruncateImage(),
   48543 **   dbSize is updated.
   48544 **
   48545 **   Variables dbOrigSize and dbFileSize are valid in states
   48546 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
   48547 **   variable at the start of the transaction. It is used during rollback,
   48548 **   and to determine whether or not pages need to be journalled before
   48549 **   being modified.
   48550 **
   48551 **   Throughout a write-transaction, dbFileSize contains the size of
   48552 **   the file on disk in pages. It is set to a copy of dbSize when the
   48553 **   write-transaction is first opened, and updated when VFS calls are made
   48554 **   to write or truncate the database file on disk.
   48555 **
   48556 **   The only reason the dbFileSize variable is required is to suppress
   48557 **   unnecessary calls to xTruncate() after committing a transaction. If,
   48558 **   when a transaction is committed, the dbFileSize variable indicates
   48559 **   that the database file is larger than the database image (Pager.dbSize),
   48560 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
   48561 **   to measure the database file on disk, and then truncates it if required.
   48562 **   dbFileSize is not used when rolling back a transaction. In this case
   48563 **   pager_truncate() is called unconditionally (which means there may be
   48564 **   a call to xFilesize() that is not strictly required). In either case,
   48565 **   pager_truncate() may cause the file to become smaller or larger.
   48566 **
   48567 ** dbHintSize
   48568 **
   48569 **   The dbHintSize variable is used to limit the number of calls made to
   48570 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
   48571 **
   48572 **   dbHintSize is set to a copy of the dbSize variable when a
   48573 **   write-transaction is opened (at the same time as dbFileSize and
   48574 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
   48575 **   dbHintSize is increased to the number of pages that correspond to the
   48576 **   size-hint passed to the method call. See pager_write_pagelist() for
   48577 **   details.
   48578 **
   48579 ** errCode
   48580 **
   48581 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
   48582 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
   48583 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
   48584 **   sub-codes.
   48585 **
   48586 ** syncFlags, walSyncFlags
   48587 **
   48588 **   syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
   48589 **   syncFlags is used for rollback mode.  walSyncFlags is used for WAL mode
   48590 **   and contains the flags used to sync the checkpoint operations in the
   48591 **   lower two bits, and sync flags used for transaction commits in the WAL
   48592 **   file in bits 0x04 and 0x08.  In other words, to get the correct sync flags
   48593 **   for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
   48594 **   sync flags for transaction commit, use ((walSyncFlags>>2)&0x03).  Note
   48595 **   that with synchronous=NORMAL in WAL mode, transaction commit is not synced
   48596 **   meaning that the 0x04 and 0x08 bits are both zero.
   48597 */
   48598 struct Pager {
   48599   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
   48600   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   48601   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
   48602   u8 useJournal;              /* Use a rollback journal on this file */
   48603   u8 noSync;                  /* Do not sync the journal if true */
   48604   u8 fullSync;                /* Do extra syncs of the journal for robustness */
   48605   u8 extraSync;               /* sync directory after journal delete */
   48606   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
   48607   u8 walSyncFlags;            /* See description above */
   48608   u8 tempFile;                /* zFilename is a temporary or immutable file */
   48609   u8 noLock;                  /* Do not lock (except in WAL mode) */
   48610   u8 readOnly;                /* True for a read-only database */
   48611   u8 memDb;                   /* True to inhibit all file I/O */
   48612 
   48613   /**************************************************************************
   48614   ** The following block contains those class members that change during
   48615   ** routine operation.  Class members not in this block are either fixed
   48616   ** when the pager is first created or else only change when there is a
   48617   ** significant mode change (such as changing the page_size, locking_mode,
   48618   ** or the journal_mode).  From another view, these class members describe
   48619   ** the "state" of the pager, while other class members describe the
   48620   ** "configuration" of the pager.
   48621   */
   48622   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
   48623   u8 eLock;                   /* Current lock held on database file */
   48624   u8 changeCountDone;         /* Set after incrementing the change-counter */
   48625   u8 setMaster;               /* True if a m-j name has been written to jrnl */
   48626   u8 doNotSpill;              /* Do not spill the cache when non-zero */
   48627   u8 subjInMemory;            /* True to use in-memory sub-journals */
   48628   u8 bUseFetch;               /* True to use xFetch() */
   48629   u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
   48630   Pgno dbSize;                /* Number of pages in the database */
   48631   Pgno dbOrigSize;            /* dbSize before the current transaction */
   48632   Pgno dbFileSize;            /* Number of pages in the database file */
   48633   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
   48634   int errCode;                /* One of several kinds of errors */
   48635   int nRec;                   /* Pages journalled since last j-header written */
   48636   u32 cksumInit;              /* Quasi-random value added to every checksum */
   48637   u32 nSubRec;                /* Number of records written to sub-journal */
   48638   Bitvec *pInJournal;         /* One bit for each page in the database file */
   48639   sqlite3_file *fd;           /* File descriptor for database */
   48640   sqlite3_file *jfd;          /* File descriptor for main journal */
   48641   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
   48642   i64 journalOff;             /* Current write offset in the journal file */
   48643   i64 journalHdr;             /* Byte offset to previous journal header */
   48644   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
   48645   PagerSavepoint *aSavepoint; /* Array of active savepoints */
   48646   int nSavepoint;             /* Number of elements in aSavepoint[] */
   48647   u32 iDataVersion;           /* Changes whenever database content changes */
   48648   char dbFileVers[16];        /* Changes whenever database file changes */
   48649 
   48650   int nMmapOut;               /* Number of mmap pages currently outstanding */
   48651   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
   48652   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
   48653   /*
   48654   ** End of the routinely-changing class members
   48655   ***************************************************************************/
   48656 
   48657   u16 nExtra;                 /* Add this many bytes to each in-memory page */
   48658   i16 nReserve;               /* Number of unused bytes at end of each page */
   48659   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   48660   u32 sectorSize;             /* Assumed sector size during rollback */
   48661   int pageSize;               /* Number of bytes in a page */
   48662   Pgno mxPgno;                /* Maximum allowed size of the database */
   48663   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   48664   char *zFilename;            /* Name of the database file */
   48665   char *zJournal;             /* Name of the journal file */
   48666   int (*xBusyHandler)(void*); /* Function to call when busy */
   48667   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
   48668   int aStat[3];               /* Total cache hits, misses and writes */
   48669 #ifdef SQLITE_TEST
   48670   int nRead;                  /* Database pages read */
   48671 #endif
   48672   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   48673   int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
   48674 #ifdef SQLITE_HAS_CODEC
   48675   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
   48676   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
   48677   void (*xCodecFree)(void*);             /* Destructor for the codec */
   48678   void *pCodec;               /* First argument to xCodec... methods */
   48679 #endif
   48680   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   48681   PCache *pPCache;            /* Pointer to page cache object */
   48682 #ifndef SQLITE_OMIT_WAL
   48683   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
   48684   char *zWal;                 /* File name for write-ahead log */
   48685 #endif
   48686 };
   48687 
   48688 /*
   48689 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
   48690 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
   48691 ** or CACHE_WRITE to sqlite3_db_status().
   48692 */
   48693 #define PAGER_STAT_HIT   0
   48694 #define PAGER_STAT_MISS  1
   48695 #define PAGER_STAT_WRITE 2
   48696 
   48697 /*
   48698 ** The following global variables hold counters used for
   48699 ** testing purposes only.  These variables do not exist in
   48700 ** a non-testing build.  These variables are not thread-safe.
   48701 */
   48702 #ifdef SQLITE_TEST
   48703 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
   48704 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
   48705 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
   48706 # define PAGER_INCR(v)  v++
   48707 #else
   48708 # define PAGER_INCR(v)
   48709 #endif
   48710 
   48711 
   48712 
   48713 /*
   48714 ** Journal files begin with the following magic string.  The data
   48715 ** was obtained from /dev/random.  It is used only as a sanity check.
   48716 **
   48717 ** Since version 2.8.0, the journal format contains additional sanity
   48718 ** checking information.  If the power fails while the journal is being
   48719 ** written, semi-random garbage data might appear in the journal
   48720 ** file after power is restored.  If an attempt is then made
   48721 ** to roll the journal back, the database could be corrupted.  The additional
   48722 ** sanity checking data is an attempt to discover the garbage in the
   48723 ** journal and ignore it.
   48724 **
   48725 ** The sanity checking information for the new journal format consists
   48726 ** of a 32-bit checksum on each page of data.  The checksum covers both
   48727 ** the page number and the pPager->pageSize bytes of data for the page.
   48728 ** This cksum is initialized to a 32-bit random value that appears in the
   48729 ** journal file right after the header.  The random initializer is important,
   48730 ** because garbage data that appears at the end of a journal is likely
   48731 ** data that was once in other files that have now been deleted.  If the
   48732 ** garbage data came from an obsolete journal file, the checksums might
   48733 ** be correct.  But by initializing the checksum to random value which
   48734 ** is different for every journal, we minimize that risk.
   48735 */
   48736 static const unsigned char aJournalMagic[] = {
   48737   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
   48738 };
   48739 
   48740 /*
   48741 ** The size of the of each page record in the journal is given by
   48742 ** the following macro.
   48743 */
   48744 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
   48745 
   48746 /*
   48747 ** The journal header size for this pager. This is usually the same
   48748 ** size as a single disk sector. See also setSectorSize().
   48749 */
   48750 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
   48751 
   48752 /*
   48753 ** The macro MEMDB is true if we are dealing with an in-memory database.
   48754 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
   48755 ** the value of MEMDB will be a constant and the compiler will optimize
   48756 ** out code that would never execute.
   48757 */
   48758 #ifdef SQLITE_OMIT_MEMORYDB
   48759 # define MEMDB 0
   48760 #else
   48761 # define MEMDB pPager->memDb
   48762 #endif
   48763 
   48764 /*
   48765 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
   48766 ** interfaces to access the database using memory-mapped I/O.
   48767 */
   48768 #if SQLITE_MAX_MMAP_SIZE>0
   48769 # define USEFETCH(x) ((x)->bUseFetch)
   48770 #else
   48771 # define USEFETCH(x) 0
   48772 #endif
   48773 
   48774 /*
   48775 ** The maximum legal page number is (2^31 - 1).
   48776 */
   48777 #define PAGER_MAX_PGNO 2147483647
   48778 
   48779 /*
   48780 ** The argument to this macro is a file descriptor (type sqlite3_file*).
   48781 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
   48782 **
   48783 ** This is so that expressions can be written as:
   48784 **
   48785 **   if( isOpen(pPager->jfd) ){ ...
   48786 **
   48787 ** instead of
   48788 **
   48789 **   if( pPager->jfd->pMethods ){ ...
   48790 */
   48791 #define isOpen(pFd) ((pFd)->pMethods!=0)
   48792 
   48793 /*
   48794 ** Return true if this pager uses a write-ahead log to read page pgno.
   48795 ** Return false if the pager reads pgno directly from the database.
   48796 */
   48797 #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
   48798 SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
   48799   u32 iRead = 0;
   48800   int rc;
   48801   if( pPager->pWal==0 ) return 0;
   48802   rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
   48803   return rc || iRead;
   48804 }
   48805 #endif
   48806 #ifndef SQLITE_OMIT_WAL
   48807 # define pagerUseWal(x) ((x)->pWal!=0)
   48808 #else
   48809 # define pagerUseWal(x) 0
   48810 # define pagerRollbackWal(x) 0
   48811 # define pagerWalFrames(v,w,x,y) 0
   48812 # define pagerOpenWalIfPresent(z) SQLITE_OK
   48813 # define pagerBeginReadTransaction(z) SQLITE_OK
   48814 #endif
   48815 
   48816 #ifndef NDEBUG
   48817 /*
   48818 ** Usage:
   48819 **
   48820 **   assert( assert_pager_state(pPager) );
   48821 **
   48822 ** This function runs many asserts to try to find inconsistencies in
   48823 ** the internal state of the Pager object.
   48824 */
   48825 static int assert_pager_state(Pager *p){
   48826   Pager *pPager = p;
   48827 
   48828   /* State must be valid. */
   48829   assert( p->eState==PAGER_OPEN
   48830        || p->eState==PAGER_READER
   48831        || p->eState==PAGER_WRITER_LOCKED
   48832        || p->eState==PAGER_WRITER_CACHEMOD
   48833        || p->eState==PAGER_WRITER_DBMOD
   48834        || p->eState==PAGER_WRITER_FINISHED
   48835        || p->eState==PAGER_ERROR
   48836   );
   48837 
   48838   /* Regardless of the current state, a temp-file connection always behaves
   48839   ** as if it has an exclusive lock on the database file. It never updates
   48840   ** the change-counter field, so the changeCountDone flag is always set.
   48841   */
   48842   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
   48843   assert( p->tempFile==0 || pPager->changeCountDone );
   48844 
   48845   /* If the useJournal flag is clear, the journal-mode must be "OFF".
   48846   ** And if the journal-mode is "OFF", the journal file must not be open.
   48847   */
   48848   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
   48849   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
   48850 
   48851   /* Check that MEMDB implies noSync. And an in-memory journal. Since
   48852   ** this means an in-memory pager performs no IO at all, it cannot encounter
   48853   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
   48854   ** a journal file. (although the in-memory journal implementation may
   48855   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
   48856   ** is therefore not possible for an in-memory pager to enter the ERROR
   48857   ** state.
   48858   */
   48859   if( MEMDB ){
   48860     assert( !isOpen(p->fd) );
   48861     assert( p->noSync );
   48862     assert( p->journalMode==PAGER_JOURNALMODE_OFF
   48863          || p->journalMode==PAGER_JOURNALMODE_MEMORY
   48864     );
   48865     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
   48866     assert( pagerUseWal(p)==0 );
   48867   }
   48868 
   48869   /* If changeCountDone is set, a RESERVED lock or greater must be held
   48870   ** on the file.
   48871   */
   48872   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
   48873   assert( p->eLock!=PENDING_LOCK );
   48874 
   48875   switch( p->eState ){
   48876     case PAGER_OPEN:
   48877       assert( !MEMDB );
   48878       assert( pPager->errCode==SQLITE_OK );
   48879       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
   48880       break;
   48881 
   48882     case PAGER_READER:
   48883       assert( pPager->errCode==SQLITE_OK );
   48884       assert( p->eLock!=UNKNOWN_LOCK );
   48885       assert( p->eLock>=SHARED_LOCK );
   48886       break;
   48887 
   48888     case PAGER_WRITER_LOCKED:
   48889       assert( p->eLock!=UNKNOWN_LOCK );
   48890       assert( pPager->errCode==SQLITE_OK );
   48891       if( !pagerUseWal(pPager) ){
   48892         assert( p->eLock>=RESERVED_LOCK );
   48893       }
   48894       assert( pPager->dbSize==pPager->dbOrigSize );
   48895       assert( pPager->dbOrigSize==pPager->dbFileSize );
   48896       assert( pPager->dbOrigSize==pPager->dbHintSize );
   48897       assert( pPager->setMaster==0 );
   48898       break;
   48899 
   48900     case PAGER_WRITER_CACHEMOD:
   48901       assert( p->eLock!=UNKNOWN_LOCK );
   48902       assert( pPager->errCode==SQLITE_OK );
   48903       if( !pagerUseWal(pPager) ){
   48904         /* It is possible that if journal_mode=wal here that neither the
   48905         ** journal file nor the WAL file are open. This happens during
   48906         ** a rollback transaction that switches from journal_mode=off
   48907         ** to journal_mode=wal.
   48908         */
   48909         assert( p->eLock>=RESERVED_LOCK );
   48910         assert( isOpen(p->jfd)
   48911              || p->journalMode==PAGER_JOURNALMODE_OFF
   48912              || p->journalMode==PAGER_JOURNALMODE_WAL
   48913         );
   48914       }
   48915       assert( pPager->dbOrigSize==pPager->dbFileSize );
   48916       assert( pPager->dbOrigSize==pPager->dbHintSize );
   48917       break;
   48918 
   48919     case PAGER_WRITER_DBMOD:
   48920       assert( p->eLock==EXCLUSIVE_LOCK );
   48921       assert( pPager->errCode==SQLITE_OK );
   48922       assert( !pagerUseWal(pPager) );
   48923       assert( p->eLock>=EXCLUSIVE_LOCK );
   48924       assert( isOpen(p->jfd)
   48925            || p->journalMode==PAGER_JOURNALMODE_OFF
   48926            || p->journalMode==PAGER_JOURNALMODE_WAL
   48927            || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
   48928       );
   48929       assert( pPager->dbOrigSize<=pPager->dbHintSize );
   48930       break;
   48931 
   48932     case PAGER_WRITER_FINISHED:
   48933       assert( p->eLock==EXCLUSIVE_LOCK );
   48934       assert( pPager->errCode==SQLITE_OK );
   48935       assert( !pagerUseWal(pPager) );
   48936       assert( isOpen(p->jfd)
   48937            || p->journalMode==PAGER_JOURNALMODE_OFF
   48938            || p->journalMode==PAGER_JOURNALMODE_WAL
   48939            || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
   48940       );
   48941       break;
   48942 
   48943     case PAGER_ERROR:
   48944       /* There must be at least one outstanding reference to the pager if
   48945       ** in ERROR state. Otherwise the pager should have already dropped
   48946       ** back to OPEN state.
   48947       */
   48948       assert( pPager->errCode!=SQLITE_OK );
   48949       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
   48950       break;
   48951   }
   48952 
   48953   return 1;
   48954 }
   48955 #endif /* ifndef NDEBUG */
   48956 
   48957 #ifdef SQLITE_DEBUG
   48958 /*
   48959 ** Return a pointer to a human readable string in a static buffer
   48960 ** containing the state of the Pager object passed as an argument. This
   48961 ** is intended to be used within debuggers. For example, as an alternative
   48962 ** to "print *pPager" in gdb:
   48963 **
   48964 ** (gdb) printf "%s", print_pager_state(pPager)
   48965 */
   48966 static char *print_pager_state(Pager *p){
   48967   static char zRet[1024];
   48968 
   48969   sqlite3_snprintf(1024, zRet,
   48970       "Filename:      %s\n"
   48971       "State:         %s errCode=%d\n"
   48972       "Lock:          %s\n"
   48973       "Locking mode:  locking_mode=%s\n"
   48974       "Journal mode:  journal_mode=%s\n"
   48975       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
   48976       "Journal:       journalOff=%lld journalHdr=%lld\n"
   48977       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
   48978       , p->zFilename
   48979       , p->eState==PAGER_OPEN            ? "OPEN" :
   48980         p->eState==PAGER_READER          ? "READER" :
   48981         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
   48982         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
   48983         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
   48984         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
   48985         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
   48986       , (int)p->errCode
   48987       , p->eLock==NO_LOCK         ? "NO_LOCK" :
   48988         p->eLock==RESERVED_LOCK   ? "RESERVED" :
   48989         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
   48990         p->eLock==SHARED_LOCK     ? "SHARED" :
   48991         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
   48992       , p->exclusiveMode ? "exclusive" : "normal"
   48993       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
   48994         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
   48995         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
   48996         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
   48997         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
   48998         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
   48999       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
   49000       , p->journalOff, p->journalHdr
   49001       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
   49002   );
   49003 
   49004   return zRet;
   49005 }
   49006 #endif
   49007 
   49008 /* Forward references to the various page getters */
   49009 static int getPageNormal(Pager*,Pgno,DbPage**,int);
   49010 static int getPageError(Pager*,Pgno,DbPage**,int);
   49011 #if SQLITE_MAX_MMAP_SIZE>0
   49012 static int getPageMMap(Pager*,Pgno,DbPage**,int);
   49013 #endif
   49014 
   49015 /*
   49016 ** Set the Pager.xGet method for the appropriate routine used to fetch
   49017 ** content from the pager.
   49018 */
   49019 static void setGetterMethod(Pager *pPager){
   49020   if( pPager->errCode ){
   49021     pPager->xGet = getPageError;
   49022 #if SQLITE_MAX_MMAP_SIZE>0
   49023   }else if( USEFETCH(pPager)
   49024 #ifdef SQLITE_HAS_CODEC
   49025    && pPager->xCodec==0
   49026 #endif
   49027   ){
   49028     pPager->xGet = getPageMMap;
   49029 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   49030   }else{
   49031     pPager->xGet = getPageNormal;
   49032   }
   49033 }
   49034 
   49035 /*
   49036 ** Return true if it is necessary to write page *pPg into the sub-journal.
   49037 ** A page needs to be written into the sub-journal if there exists one
   49038 ** or more open savepoints for which:
   49039 **
   49040 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
   49041 **   * The bit corresponding to the page-number is not set in
   49042 **     PagerSavepoint.pInSavepoint.
   49043 */
   49044 static int subjRequiresPage(PgHdr *pPg){
   49045   Pager *pPager = pPg->pPager;
   49046   PagerSavepoint *p;
   49047   Pgno pgno = pPg->pgno;
   49048   int i;
   49049   for(i=0; i<pPager->nSavepoint; i++){
   49050     p = &pPager->aSavepoint[i];
   49051     if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
   49052       return 1;
   49053     }
   49054   }
   49055   return 0;
   49056 }
   49057 
   49058 #ifdef SQLITE_DEBUG
   49059 /*
   49060 ** Return true if the page is already in the journal file.
   49061 */
   49062 static int pageInJournal(Pager *pPager, PgHdr *pPg){
   49063   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
   49064 }
   49065 #endif
   49066 
   49067 /*
   49068 ** Read a 32-bit integer from the given file descriptor.  Store the integer
   49069 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
   49070 ** error code is something goes wrong.
   49071 **
   49072 ** All values are stored on disk as big-endian.
   49073 */
   49074 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
   49075   unsigned char ac[4];
   49076   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
   49077   if( rc==SQLITE_OK ){
   49078     *pRes = sqlite3Get4byte(ac);
   49079   }
   49080   return rc;
   49081 }
   49082 
   49083 /*
   49084 ** Write a 32-bit integer into a string buffer in big-endian byte order.
   49085 */
   49086 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
   49087 
   49088 
   49089 /*
   49090 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
   49091 ** on success or an error code is something goes wrong.
   49092 */
   49093 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
   49094   char ac[4];
   49095   put32bits(ac, val);
   49096   return sqlite3OsWrite(fd, ac, 4, offset);
   49097 }
   49098 
   49099 /*
   49100 ** Unlock the database file to level eLock, which must be either NO_LOCK
   49101 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
   49102 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
   49103 **
   49104 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   49105 ** called, do not modify it. See the comment above the #define of
   49106 ** UNKNOWN_LOCK for an explanation of this.
   49107 */
   49108 static int pagerUnlockDb(Pager *pPager, int eLock){
   49109   int rc = SQLITE_OK;
   49110 
   49111   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
   49112   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
   49113   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
   49114   if( isOpen(pPager->fd) ){
   49115     assert( pPager->eLock>=eLock );
   49116     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
   49117     if( pPager->eLock!=UNKNOWN_LOCK ){
   49118       pPager->eLock = (u8)eLock;
   49119     }
   49120     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
   49121   }
   49122   return rc;
   49123 }
   49124 
   49125 /*
   49126 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
   49127 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
   49128 ** Pager.eLock variable to the new locking state.
   49129 **
   49130 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   49131 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
   49132 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
   49133 ** of this.
   49134 */
   49135 static int pagerLockDb(Pager *pPager, int eLock){
   49136   int rc = SQLITE_OK;
   49137 
   49138   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
   49139   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
   49140     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
   49141     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
   49142       pPager->eLock = (u8)eLock;
   49143       IOTRACE(("LOCK %p %d\n", pPager, eLock))
   49144     }
   49145   }
   49146   return rc;
   49147 }
   49148 
   49149 /*
   49150 ** This function determines whether or not the atomic-write or
   49151 ** atomic-batch-write optimizations can be used with this pager. The
   49152 ** atomic-write optimization can be used if:
   49153 **
   49154 **  (a) the value returned by OsDeviceCharacteristics() indicates that
   49155 **      a database page may be written atomically, and
   49156 **  (b) the value returned by OsSectorSize() is less than or equal
   49157 **      to the page size.
   49158 **
   49159 ** If it can be used, then the value returned is the size of the journal
   49160 ** file when it contains rollback data for exactly one page.
   49161 **
   49162 ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
   49163 ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
   49164 ** returned in this case.
   49165 **
   49166 ** If neither optimization can be used, 0 is returned.
   49167 */
   49168 static int jrnlBufferSize(Pager *pPager){
   49169   assert( !MEMDB );
   49170 
   49171 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
   49172  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   49173   int dc;                           /* Device characteristics */
   49174 
   49175   assert( isOpen(pPager->fd) );
   49176   dc = sqlite3OsDeviceCharacteristics(pPager->fd);
   49177 #else
   49178   UNUSED_PARAMETER(pPager);
   49179 #endif
   49180 
   49181 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   49182   if( dc&SQLITE_IOCAP_BATCH_ATOMIC ){
   49183     return -1;
   49184   }
   49185 #endif
   49186 
   49187 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   49188   {
   49189     int nSector = pPager->sectorSize;
   49190     int szPage = pPager->pageSize;
   49191 
   49192     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   49193     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   49194     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
   49195       return 0;
   49196     }
   49197   }
   49198 
   49199   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
   49200 #endif
   49201 
   49202   return 0;
   49203 }
   49204 
   49205 /*
   49206 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
   49207 ** on the cache using a hash function.  This is used for testing
   49208 ** and debugging only.
   49209 */
   49210 #ifdef SQLITE_CHECK_PAGES
   49211 /*
   49212 ** Return a 32-bit hash of the page data for pPage.
   49213 */
   49214 static u32 pager_datahash(int nByte, unsigned char *pData){
   49215   u32 hash = 0;
   49216   int i;
   49217   for(i=0; i<nByte; i++){
   49218     hash = (hash*1039) + pData[i];
   49219   }
   49220   return hash;
   49221 }
   49222 static u32 pager_pagehash(PgHdr *pPage){
   49223   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
   49224 }
   49225 static void pager_set_pagehash(PgHdr *pPage){
   49226   pPage->pageHash = pager_pagehash(pPage);
   49227 }
   49228 
   49229 /*
   49230 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
   49231 ** is defined, and NDEBUG is not defined, an assert() statement checks
   49232 ** that the page is either dirty or still matches the calculated page-hash.
   49233 */
   49234 #define CHECK_PAGE(x) checkPage(x)
   49235 static void checkPage(PgHdr *pPg){
   49236   Pager *pPager = pPg->pPager;
   49237   assert( pPager->eState!=PAGER_ERROR );
   49238   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
   49239 }
   49240 
   49241 #else
   49242 #define pager_datahash(X,Y)  0
   49243 #define pager_pagehash(X)  0
   49244 #define pager_set_pagehash(X)
   49245 #define CHECK_PAGE(x)
   49246 #endif  /* SQLITE_CHECK_PAGES */
   49247 
   49248 /*
   49249 ** When this is called the journal file for pager pPager must be open.
   49250 ** This function attempts to read a master journal file name from the
   49251 ** end of the file and, if successful, copies it into memory supplied
   49252 ** by the caller. See comments above writeMasterJournal() for the format
   49253 ** used to store a master journal file name at the end of a journal file.
   49254 **
   49255 ** zMaster must point to a buffer of at least nMaster bytes allocated by
   49256 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
   49257 ** enough space to write the master journal name). If the master journal
   49258 ** name in the journal is longer than nMaster bytes (including a
   49259 ** nul-terminator), then this is handled as if no master journal name
   49260 ** were present in the journal.
   49261 **
   49262 ** If a master journal file name is present at the end of the journal
   49263 ** file, then it is copied into the buffer pointed to by zMaster. A
   49264 ** nul-terminator byte is appended to the buffer following the master
   49265 ** journal file name.
   49266 **
   49267 ** If it is determined that no master journal file name is present
   49268 ** zMaster[0] is set to 0 and SQLITE_OK returned.
   49269 **
   49270 ** If an error occurs while reading from the journal file, an SQLite
   49271 ** error code is returned.
   49272 */
   49273 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
   49274   int rc;                    /* Return code */
   49275   u32 len;                   /* Length in bytes of master journal name */
   49276   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   49277   u32 cksum;                 /* MJ checksum value read from journal */
   49278   u32 u;                     /* Unsigned loop counter */
   49279   unsigned char aMagic[8];   /* A buffer to hold the magic header */
   49280   zMaster[0] = '\0';
   49281 
   49282   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   49283    || szJ<16
   49284    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   49285    || len>=nMaster
   49286    || len>szJ-16
   49287    || len==0
   49288    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   49289    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   49290    || memcmp(aMagic, aJournalMagic, 8)
   49291    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
   49292   ){
   49293     return rc;
   49294   }
   49295 
   49296   /* See if the checksum matches the master journal name */
   49297   for(u=0; u<len; u++){
   49298     cksum -= zMaster[u];
   49299   }
   49300   if( cksum ){
   49301     /* If the checksum doesn't add up, then one or more of the disk sectors
   49302     ** containing the master journal filename is corrupted. This means
   49303     ** definitely roll back, so just return SQLITE_OK and report a (nul)
   49304     ** master-journal filename.
   49305     */
   49306     len = 0;
   49307   }
   49308   zMaster[len] = '\0';
   49309 
   49310   return SQLITE_OK;
   49311 }
   49312 
   49313 /*
   49314 ** Return the offset of the sector boundary at or immediately
   49315 ** following the value in pPager->journalOff, assuming a sector
   49316 ** size of pPager->sectorSize bytes.
   49317 **
   49318 ** i.e for a sector size of 512:
   49319 **
   49320 **   Pager.journalOff          Return value
   49321 **   ---------------------------------------
   49322 **   0                         0
   49323 **   512                       512
   49324 **   100                       512
   49325 **   2000                      2048
   49326 **
   49327 */
   49328 static i64 journalHdrOffset(Pager *pPager){
   49329   i64 offset = 0;
   49330   i64 c = pPager->journalOff;
   49331   if( c ){
   49332     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
   49333   }
   49334   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
   49335   assert( offset>=c );
   49336   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
   49337   return offset;
   49338 }
   49339 
   49340 /*
   49341 ** The journal file must be open when this function is called.
   49342 **
   49343 ** This function is a no-op if the journal file has not been written to
   49344 ** within the current transaction (i.e. if Pager.journalOff==0).
   49345 **
   49346 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
   49347 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
   49348 ** zero the 28-byte header at the start of the journal file. In either case,
   49349 ** if the pager is not in no-sync mode, sync the journal file immediately
   49350 ** after writing or truncating it.
   49351 **
   49352 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
   49353 ** following the truncation or zeroing described above the size of the
   49354 ** journal file in bytes is larger than this value, then truncate the
   49355 ** journal file to Pager.journalSizeLimit bytes. The journal file does
   49356 ** not need to be synced following this operation.
   49357 **
   49358 ** If an IO error occurs, abandon processing and return the IO error code.
   49359 ** Otherwise, return SQLITE_OK.
   49360 */
   49361 static int zeroJournalHdr(Pager *pPager, int doTruncate){
   49362   int rc = SQLITE_OK;                               /* Return code */
   49363   assert( isOpen(pPager->jfd) );
   49364   assert( !sqlite3JournalIsInMemory(pPager->jfd) );
   49365   if( pPager->journalOff ){
   49366     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
   49367 
   49368     IOTRACE(("JZEROHDR %p\n", pPager))
   49369     if( doTruncate || iLimit==0 ){
   49370       rc = sqlite3OsTruncate(pPager->jfd, 0);
   49371     }else{
   49372       static const char zeroHdr[28] = {0};
   49373       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
   49374     }
   49375     if( rc==SQLITE_OK && !pPager->noSync ){
   49376       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
   49377     }
   49378 
   49379     /* At this point the transaction is committed but the write lock
   49380     ** is still held on the file. If there is a size limit configured for
   49381     ** the persistent journal and the journal file currently consumes more
   49382     ** space than that limit allows for, truncate it now. There is no need
   49383     ** to sync the file following this operation.
   49384     */
   49385     if( rc==SQLITE_OK && iLimit>0 ){
   49386       i64 sz;
   49387       rc = sqlite3OsFileSize(pPager->jfd, &sz);
   49388       if( rc==SQLITE_OK && sz>iLimit ){
   49389         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
   49390       }
   49391     }
   49392   }
   49393   return rc;
   49394 }
   49395 
   49396 /*
   49397 ** The journal file must be open when this routine is called. A journal
   49398 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
   49399 ** current location.
   49400 **
   49401 ** The format for the journal header is as follows:
   49402 ** - 8 bytes: Magic identifying journal format.
   49403 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
   49404 ** - 4 bytes: Random number used for page hash.
   49405 ** - 4 bytes: Initial database page count.
   49406 ** - 4 bytes: Sector size used by the process that wrote this journal.
   49407 ** - 4 bytes: Database page size.
   49408 **
   49409 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
   49410 */
   49411 static int writeJournalHdr(Pager *pPager){
   49412   int rc = SQLITE_OK;                 /* Return code */
   49413   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
   49414   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
   49415   u32 nWrite;                         /* Bytes of header sector written */
   49416   int ii;                             /* Loop counter */
   49417 
   49418   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   49419 
   49420   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
   49421     nHeader = JOURNAL_HDR_SZ(pPager);
   49422   }
   49423 
   49424   /* If there are active savepoints and any of them were created
   49425   ** since the most recent journal header was written, update the
   49426   ** PagerSavepoint.iHdrOffset fields now.
   49427   */
   49428   for(ii=0; ii<pPager->nSavepoint; ii++){
   49429     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
   49430       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
   49431     }
   49432   }
   49433 
   49434   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
   49435 
   49436   /*
   49437   ** Write the nRec Field - the number of page records that follow this
   49438   ** journal header. Normally, zero is written to this value at this time.
   49439   ** After the records are added to the journal (and the journal synced,
   49440   ** if in full-sync mode), the zero is overwritten with the true number
   49441   ** of records (see syncJournal()).
   49442   **
   49443   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
   49444   ** reading the journal this value tells SQLite to assume that the
   49445   ** rest of the journal file contains valid page records. This assumption
   49446   ** is dangerous, as if a failure occurred whilst writing to the journal
   49447   ** file it may contain some garbage data. There are two scenarios
   49448   ** where this risk can be ignored:
   49449   **
   49450   **   * When the pager is in no-sync mode. Corruption can follow a
   49451   **     power failure in this case anyway.
   49452   **
   49453   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
   49454   **     that garbage data is never appended to the journal file.
   49455   */
   49456   assert( isOpen(pPager->fd) || pPager->noSync );
   49457   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   49458    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   49459   ){
   49460     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   49461     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
   49462   }else{
   49463     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   49464   }
   49465 
   49466   /* The random check-hash initializer */
   49467   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   49468   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   49469   /* The initial database size */
   49470   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
   49471   /* The assumed sector size for this process */
   49472   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
   49473 
   49474   /* The page size */
   49475   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
   49476 
   49477   /* Initializing the tail of the buffer is not necessary.  Everything
   49478   ** works find if the following memset() is omitted.  But initializing
   49479   ** the memory prevents valgrind from complaining, so we are willing to
   49480   ** take the performance hit.
   49481   */
   49482   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
   49483          nHeader-(sizeof(aJournalMagic)+20));
   49484 
   49485   /* In theory, it is only necessary to write the 28 bytes that the
   49486   ** journal header consumes to the journal file here. Then increment the
   49487   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   49488   ** record is written to the following sector (leaving a gap in the file
   49489   ** that will be implicitly filled in by the OS).
   49490   **
   49491   ** However it has been discovered that on some systems this pattern can
   49492   ** be significantly slower than contiguously writing data to the file,
   49493   ** even if that means explicitly writing data to the block of
   49494   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
   49495   ** is done.
   49496   **
   49497   ** The loop is required here in case the sector-size is larger than the
   49498   ** database page size. Since the zHeader buffer is only Pager.pageSize
   49499   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   49500   ** to populate the entire journal header sector.
   49501   */
   49502   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
   49503     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
   49504     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
   49505     assert( pPager->journalHdr <= pPager->journalOff );
   49506     pPager->journalOff += nHeader;
   49507   }
   49508 
   49509   return rc;
   49510 }
   49511 
   49512 /*
   49513 ** The journal file must be open when this is called. A journal header file
   49514 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
   49515 ** file. The current location in the journal file is given by
   49516 ** pPager->journalOff. See comments above function writeJournalHdr() for
   49517 ** a description of the journal header format.
   49518 **
   49519 ** If the header is read successfully, *pNRec is set to the number of
   49520 ** page records following this header and *pDbSize is set to the size of the
   49521 ** database before the transaction began, in pages. Also, pPager->cksumInit
   49522 ** is set to the value read from the journal header. SQLITE_OK is returned
   49523 ** in this case.
   49524 **
   49525 ** If the journal header file appears to be corrupted, SQLITE_DONE is
   49526 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
   49527 ** cannot be read from the journal file an error code is returned.
   49528 */
   49529 static int readJournalHdr(
   49530   Pager *pPager,               /* Pager object */
   49531   int isHot,
   49532   i64 journalSize,             /* Size of the open journal file in bytes */
   49533   u32 *pNRec,                  /* OUT: Value read from the nRec field */
   49534   u32 *pDbSize                 /* OUT: Value of original database size field */
   49535 ){
   49536   int rc;                      /* Return code */
   49537   unsigned char aMagic[8];     /* A buffer to hold the magic header */
   49538   i64 iHdrOff;                 /* Offset of journal header being read */
   49539 
   49540   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   49541 
   49542   /* Advance Pager.journalOff to the start of the next sector. If the
   49543   ** journal file is too small for there to be a header stored at this
   49544   ** point, return SQLITE_DONE.
   49545   */
   49546   pPager->journalOff = journalHdrOffset(pPager);
   49547   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
   49548     return SQLITE_DONE;
   49549   }
   49550   iHdrOff = pPager->journalOff;
   49551 
   49552   /* Read in the first 8 bytes of the journal header. If they do not match
   49553   ** the  magic string found at the start of each journal header, return
   49554   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
   49555   ** proceed.
   49556   */
   49557   if( isHot || iHdrOff!=pPager->journalHdr ){
   49558     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
   49559     if( rc ){
   49560       return rc;
   49561     }
   49562     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
   49563       return SQLITE_DONE;
   49564     }
   49565   }
   49566 
   49567   /* Read the first three 32-bit fields of the journal header: The nRec
   49568   ** field, the checksum-initializer and the database size at the start
   49569   ** of the transaction. Return an error code if anything goes wrong.
   49570   */
   49571   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   49572    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   49573    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
   49574   ){
   49575     return rc;
   49576   }
   49577 
   49578   if( pPager->journalOff==0 ){
   49579     u32 iPageSize;               /* Page-size field of journal header */
   49580     u32 iSectorSize;             /* Sector-size field of journal header */
   49581 
   49582     /* Read the page-size and sector-size journal header fields. */
   49583     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
   49584      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
   49585     ){
   49586       return rc;
   49587     }
   49588 
   49589     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
   49590     ** journal header to zero. In this case, assume that the Pager.pageSize
   49591     ** variable is already set to the correct page size.
   49592     */
   49593     if( iPageSize==0 ){
   49594       iPageSize = pPager->pageSize;
   49595     }
   49596 
   49597     /* Check that the values read from the page-size and sector-size fields
   49598     ** are within range. To be 'in range', both values need to be a power
   49599     ** of two greater than or equal to 512 or 32, and not greater than their
   49600     ** respective compile time maximum limits.
   49601     */
   49602     if( iPageSize<512                  || iSectorSize<32
   49603      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
   49604      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
   49605     ){
   49606       /* If the either the page-size or sector-size in the journal-header is
   49607       ** invalid, then the process that wrote the journal-header must have
   49608       ** crashed before the header was synced. In this case stop reading
   49609       ** the journal file here.
   49610       */
   49611       return SQLITE_DONE;
   49612     }
   49613 
   49614     /* Update the page-size to match the value read from the journal.
   49615     ** Use a testcase() macro to make sure that malloc failure within
   49616     ** PagerSetPagesize() is tested.
   49617     */
   49618     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
   49619     testcase( rc!=SQLITE_OK );
   49620 
   49621     /* Update the assumed sector-size to match the value used by
   49622     ** the process that created this journal. If this journal was
   49623     ** created by a process other than this one, then this routine
   49624     ** is being called from within pager_playback(). The local value
   49625     ** of Pager.sectorSize is restored at the end of that routine.
   49626     */
   49627     pPager->sectorSize = iSectorSize;
   49628   }
   49629 
   49630   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
   49631   return rc;
   49632 }
   49633 
   49634 
   49635 /*
   49636 ** Write the supplied master journal name into the journal file for pager
   49637 ** pPager at the current location. The master journal name must be the last
   49638 ** thing written to a journal file. If the pager is in full-sync mode, the
   49639 ** journal file descriptor is advanced to the next sector boundary before
   49640 ** anything is written. The format is:
   49641 **
   49642 **   + 4 bytes: PAGER_MJ_PGNO.
   49643 **   + N bytes: Master journal filename in utf-8.
   49644 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
   49645 **   + 4 bytes: Master journal name checksum.
   49646 **   + 8 bytes: aJournalMagic[].
   49647 **
   49648 ** The master journal page checksum is the sum of the bytes in the master
   49649 ** journal name, where each byte is interpreted as a signed 8-bit integer.
   49650 **
   49651 ** If zMaster is a NULL pointer (occurs for a single database transaction),
   49652 ** this call is a no-op.
   49653 */
   49654 static int writeMasterJournal(Pager *pPager, const char *zMaster){
   49655   int rc;                          /* Return code */
   49656   int nMaster;                     /* Length of string zMaster */
   49657   i64 iHdrOff;                     /* Offset of header in journal file */
   49658   i64 jrnlSize;                    /* Size of journal file on disk */
   49659   u32 cksum = 0;                   /* Checksum of string zMaster */
   49660 
   49661   assert( pPager->setMaster==0 );
   49662   assert( !pagerUseWal(pPager) );
   49663 
   49664   if( !zMaster
   49665    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   49666    || !isOpen(pPager->jfd)
   49667   ){
   49668     return SQLITE_OK;
   49669   }
   49670   pPager->setMaster = 1;
   49671   assert( pPager->journalHdr <= pPager->journalOff );
   49672 
   49673   /* Calculate the length in bytes and the checksum of zMaster */
   49674   for(nMaster=0; zMaster[nMaster]; nMaster++){
   49675     cksum += zMaster[nMaster];
   49676   }
   49677 
   49678   /* If in full-sync mode, advance to the next disk sector before writing
   49679   ** the master journal name. This is in case the previous page written to
   49680   ** the journal has already been synced.
   49681   */
   49682   if( pPager->fullSync ){
   49683     pPager->journalOff = journalHdrOffset(pPager);
   49684   }
   49685   iHdrOff = pPager->journalOff;
   49686 
   49687   /* Write the master journal data to the end of the journal file. If
   49688   ** an error occurs, return the error code to the caller.
   49689   */
   49690   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   49691    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   49692    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   49693    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   49694    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
   49695                                  iHdrOff+4+nMaster+8)))
   49696   ){
   49697     return rc;
   49698   }
   49699   pPager->journalOff += (nMaster+20);
   49700 
   49701   /* If the pager is in peristent-journal mode, then the physical
   49702   ** journal-file may extend past the end of the master-journal name
   49703   ** and 8 bytes of magic data just written to the file. This is
   49704   ** dangerous because the code to rollback a hot-journal file
   49705   ** will not be able to find the master-journal name to determine
   49706   ** whether or not the journal is hot.
   49707   **
   49708   ** Easiest thing to do in this scenario is to truncate the journal
   49709   ** file to the required size.
   49710   */
   49711   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   49712    && jrnlSize>pPager->journalOff
   49713   ){
   49714     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
   49715   }
   49716   return rc;
   49717 }
   49718 
   49719 /*
   49720 ** Discard the entire contents of the in-memory page-cache.
   49721 */
   49722 static void pager_reset(Pager *pPager){
   49723   pPager->iDataVersion++;
   49724   sqlite3BackupRestart(pPager->pBackup);
   49725   sqlite3PcacheClear(pPager->pPCache);
   49726 }
   49727 
   49728 /*
   49729 ** Return the pPager->iDataVersion value
   49730 */
   49731 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
   49732   assert( pPager->eState>PAGER_OPEN );
   49733   return pPager->iDataVersion;
   49734 }
   49735 
   49736 /*
   49737 ** Free all structures in the Pager.aSavepoint[] array and set both
   49738 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
   49739 ** if it is open and the pager is not in exclusive mode.
   49740 */
   49741 static void releaseAllSavepoints(Pager *pPager){
   49742   int ii;               /* Iterator for looping through Pager.aSavepoint */
   49743   for(ii=0; ii<pPager->nSavepoint; ii++){
   49744     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   49745   }
   49746   if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
   49747     sqlite3OsClose(pPager->sjfd);
   49748   }
   49749   sqlite3_free(pPager->aSavepoint);
   49750   pPager->aSavepoint = 0;
   49751   pPager->nSavepoint = 0;
   49752   pPager->nSubRec = 0;
   49753 }
   49754 
   49755 /*
   49756 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
   49757 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
   49758 ** or SQLITE_NOMEM if a malloc failure occurs.
   49759 */
   49760 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
   49761   int ii;                   /* Loop counter */
   49762   int rc = SQLITE_OK;       /* Result code */
   49763 
   49764   for(ii=0; ii<pPager->nSavepoint; ii++){
   49765     PagerSavepoint *p = &pPager->aSavepoint[ii];
   49766     if( pgno<=p->nOrig ){
   49767       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
   49768       testcase( rc==SQLITE_NOMEM );
   49769       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   49770     }
   49771   }
   49772   return rc;
   49773 }
   49774 
   49775 /*
   49776 ** This function is a no-op if the pager is in exclusive mode and not
   49777 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
   49778 ** state.
   49779 **
   49780 ** If the pager is not in exclusive-access mode, the database file is
   49781 ** completely unlocked. If the file is unlocked and the file-system does
   49782 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
   49783 ** closed (if it is open).
   49784 **
   49785 ** If the pager is in ERROR state when this function is called, the
   49786 ** contents of the pager cache are discarded before switching back to
   49787 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
   49788 ** or not, any journal file left in the file-system will be treated
   49789 ** as a hot-journal and rolled back the next time a read-transaction
   49790 ** is opened (by this or by any other connection).
   49791 */
   49792 static void pager_unlock(Pager *pPager){
   49793 
   49794   assert( pPager->eState==PAGER_READER
   49795        || pPager->eState==PAGER_OPEN
   49796        || pPager->eState==PAGER_ERROR
   49797   );
   49798 
   49799   sqlite3BitvecDestroy(pPager->pInJournal);
   49800   pPager->pInJournal = 0;
   49801   releaseAllSavepoints(pPager);
   49802 
   49803   if( pagerUseWal(pPager) ){
   49804     assert( !isOpen(pPager->jfd) );
   49805     sqlite3WalEndReadTransaction(pPager->pWal);
   49806     pPager->eState = PAGER_OPEN;
   49807   }else if( !pPager->exclusiveMode ){
   49808     int rc;                       /* Error code returned by pagerUnlockDb() */
   49809     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
   49810 
   49811     /* If the operating system support deletion of open files, then
   49812     ** close the journal file when dropping the database lock.  Otherwise
   49813     ** another connection with journal_mode=delete might delete the file
   49814     ** out from under us.
   49815     */
   49816     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
   49817     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
   49818     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
   49819     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
   49820     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   49821     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
   49822     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
   49823      || 1!=(pPager->journalMode & 5)
   49824     ){
   49825       sqlite3OsClose(pPager->jfd);
   49826     }
   49827 
   49828     /* If the pager is in the ERROR state and the call to unlock the database
   49829     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
   49830     ** above the #define for UNKNOWN_LOCK for an explanation of why this
   49831     ** is necessary.
   49832     */
   49833     rc = pagerUnlockDb(pPager, NO_LOCK);
   49834     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
   49835       pPager->eLock = UNKNOWN_LOCK;
   49836     }
   49837 
   49838     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
   49839     ** without clearing the error code. This is intentional - the error
   49840     ** code is cleared and the cache reset in the block below.
   49841     */
   49842     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
   49843     pPager->changeCountDone = 0;
   49844     pPager->eState = PAGER_OPEN;
   49845   }
   49846 
   49847   /* If Pager.errCode is set, the contents of the pager cache cannot be
   49848   ** trusted. Now that there are no outstanding references to the pager,
   49849   ** it can safely move back to PAGER_OPEN state. This happens in both
   49850   ** normal and exclusive-locking mode.
   49851   */
   49852   assert( pPager->errCode==SQLITE_OK || !MEMDB );
   49853   if( pPager->errCode ){
   49854     if( pPager->tempFile==0 ){
   49855       pager_reset(pPager);
   49856       pPager->changeCountDone = 0;
   49857       pPager->eState = PAGER_OPEN;
   49858     }else{
   49859       pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
   49860     }
   49861     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
   49862     pPager->errCode = SQLITE_OK;
   49863     setGetterMethod(pPager);
   49864   }
   49865 
   49866   pPager->journalOff = 0;
   49867   pPager->journalHdr = 0;
   49868   pPager->setMaster = 0;
   49869 }
   49870 
   49871 /*
   49872 ** This function is called whenever an IOERR or FULL error that requires
   49873 ** the pager to transition into the ERROR state may ahve occurred.
   49874 ** The first argument is a pointer to the pager structure, the second
   49875 ** the error-code about to be returned by a pager API function. The
   49876 ** value returned is a copy of the second argument to this function.
   49877 **
   49878 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
   49879 ** IOERR sub-codes, the pager enters the ERROR state and the error code
   49880 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
   49881 ** all major API calls on the Pager will immediately return Pager.errCode.
   49882 **
   49883 ** The ERROR state indicates that the contents of the pager-cache
   49884 ** cannot be trusted. This state can be cleared by completely discarding
   49885 ** the contents of the pager-cache. If a transaction was active when
   49886 ** the persistent error occurred, then the rollback journal may need
   49887 ** to be replayed to restore the contents of the database file (as if
   49888 ** it were a hot-journal).
   49889 */
   49890 static int pager_error(Pager *pPager, int rc){
   49891   int rc2 = rc & 0xff;
   49892   assert( rc==SQLITE_OK || !MEMDB );
   49893   assert(
   49894        pPager->errCode==SQLITE_FULL ||
   49895        pPager->errCode==SQLITE_OK ||
   49896        (pPager->errCode & 0xff)==SQLITE_IOERR
   49897   );
   49898   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
   49899     pPager->errCode = rc;
   49900     pPager->eState = PAGER_ERROR;
   49901     setGetterMethod(pPager);
   49902   }
   49903   return rc;
   49904 }
   49905 
   49906 static int pager_truncate(Pager *pPager, Pgno nPage);
   49907 
   49908 /*
   49909 ** The write transaction open on pPager is being committed (bCommit==1)
   49910 ** or rolled back (bCommit==0).
   49911 **
   49912 ** Return TRUE if and only if all dirty pages should be flushed to disk.
   49913 **
   49914 ** Rules:
   49915 **
   49916 **   *  For non-TEMP databases, always sync to disk.  This is necessary
   49917 **      for transactions to be durable.
   49918 **
   49919 **   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
   49920 **      file has been created already (via a spill on pagerStress()) and
   49921 **      when the number of dirty pages in memory exceeds 25% of the total
   49922 **      cache size.
   49923 */
   49924 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
   49925   if( pPager->tempFile==0 ) return 1;
   49926   if( !bCommit ) return 0;
   49927   if( !isOpen(pPager->fd) ) return 0;
   49928   return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
   49929 }
   49930 
   49931 /*
   49932 ** This routine ends a transaction. A transaction is usually ended by
   49933 ** either a COMMIT or a ROLLBACK operation. This routine may be called
   49934 ** after rollback of a hot-journal, or if an error occurs while opening
   49935 ** the journal file or writing the very first journal-header of a
   49936 ** database transaction.
   49937 **
   49938 ** This routine is never called in PAGER_ERROR state. If it is called
   49939 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
   49940 ** exclusive than a RESERVED lock, it is a no-op.
   49941 **
   49942 ** Otherwise, any active savepoints are released.
   49943 **
   49944 ** If the journal file is open, then it is "finalized". Once a journal
   49945 ** file has been finalized it is not possible to use it to roll back a
   49946 ** transaction. Nor will it be considered to be a hot-journal by this
   49947 ** or any other database connection. Exactly how a journal is finalized
   49948 ** depends on whether or not the pager is running in exclusive mode and
   49949 ** the current journal-mode (Pager.journalMode value), as follows:
   49950 **
   49951 **   journalMode==MEMORY
   49952 **     Journal file descriptor is simply closed. This destroys an
   49953 **     in-memory journal.
   49954 **
   49955 **   journalMode==TRUNCATE
   49956 **     Journal file is truncated to zero bytes in size.
   49957 **
   49958 **   journalMode==PERSIST
   49959 **     The first 28 bytes of the journal file are zeroed. This invalidates
   49960 **     the first journal header in the file, and hence the entire journal
   49961 **     file. An invalid journal file cannot be rolled back.
   49962 **
   49963 **   journalMode==DELETE
   49964 **     The journal file is closed and deleted using sqlite3OsDelete().
   49965 **
   49966 **     If the pager is running in exclusive mode, this method of finalizing
   49967 **     the journal file is never used. Instead, if the journalMode is
   49968 **     DELETE and the pager is in exclusive mode, the method described under
   49969 **     journalMode==PERSIST is used instead.
   49970 **
   49971 ** After the journal is finalized, the pager moves to PAGER_READER state.
   49972 ** If running in non-exclusive rollback mode, the lock on the file is
   49973 ** downgraded to a SHARED_LOCK.
   49974 **
   49975 ** SQLITE_OK is returned if no error occurs. If an error occurs during
   49976 ** any of the IO operations to finalize the journal file or unlock the
   49977 ** database then the IO error code is returned to the user. If the
   49978 ** operation to finalize the journal file fails, then the code still
   49979 ** tries to unlock the database file if not in exclusive mode. If the
   49980 ** unlock operation fails as well, then the first error code related
   49981 ** to the first error encountered (the journal finalization one) is
   49982 ** returned.
   49983 */
   49984 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
   49985   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   49986   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
   49987 
   49988   /* Do nothing if the pager does not have an open write transaction
   49989   ** or at least a RESERVED lock. This function may be called when there
   49990   ** is no write-transaction active but a RESERVED or greater lock is
   49991   ** held under two circumstances:
   49992   **
   49993   **   1. After a successful hot-journal rollback, it is called with
   49994   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
   49995   **
   49996   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
   49997   **      lock switches back to locking_mode=normal and then executes a
   49998   **      read-transaction, this function is called with eState==PAGER_READER
   49999   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
   50000   */
   50001   assert( assert_pager_state(pPager) );
   50002   assert( pPager->eState!=PAGER_ERROR );
   50003   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
   50004     return SQLITE_OK;
   50005   }
   50006 
   50007   releaseAllSavepoints(pPager);
   50008   assert( isOpen(pPager->jfd) || pPager->pInJournal==0
   50009       || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
   50010   );
   50011   if( isOpen(pPager->jfd) ){
   50012     assert( !pagerUseWal(pPager) );
   50013 
   50014     /* Finalize the journal file. */
   50015     if( sqlite3JournalIsInMemory(pPager->jfd) ){
   50016       /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
   50017       sqlite3OsClose(pPager->jfd);
   50018     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
   50019       if( pPager->journalOff==0 ){
   50020         rc = SQLITE_OK;
   50021       }else{
   50022         rc = sqlite3OsTruncate(pPager->jfd, 0);
   50023         if( rc==SQLITE_OK && pPager->fullSync ){
   50024           /* Make sure the new file size is written into the inode right away.
   50025           ** Otherwise the journal might resurrect following a power loss and
   50026           ** cause the last transaction to roll back.  See
   50027           ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
   50028           */
   50029           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
   50030         }
   50031       }
   50032       pPager->journalOff = 0;
   50033     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   50034       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
   50035     ){
   50036       rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
   50037       pPager->journalOff = 0;
   50038     }else{
   50039       /* This branch may be executed with Pager.journalMode==MEMORY if
   50040       ** a hot-journal was just rolled back. In this case the journal
   50041       ** file should be closed and deleted. If this connection writes to
   50042       ** the database file, it will do so using an in-memory journal.
   50043       */
   50044       int bDelete = !pPager->tempFile;
   50045       assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
   50046       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
   50047            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   50048            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   50049       );
   50050       sqlite3OsClose(pPager->jfd);
   50051       if( bDelete ){
   50052         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
   50053       }
   50054     }
   50055   }
   50056 
   50057 #ifdef SQLITE_CHECK_PAGES
   50058   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
   50059   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
   50060     PgHdr *p = sqlite3PagerLookup(pPager, 1);
   50061     if( p ){
   50062       p->pageHash = 0;
   50063       sqlite3PagerUnrefNotNull(p);
   50064     }
   50065   }
   50066 #endif
   50067 
   50068   sqlite3BitvecDestroy(pPager->pInJournal);
   50069   pPager->pInJournal = 0;
   50070   pPager->nRec = 0;
   50071   if( rc==SQLITE_OK ){
   50072     if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
   50073       sqlite3PcacheCleanAll(pPager->pPCache);
   50074     }else{
   50075       sqlite3PcacheClearWritable(pPager->pPCache);
   50076     }
   50077     sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
   50078   }
   50079 
   50080   if( pagerUseWal(pPager) ){
   50081     /* Drop the WAL write-lock, if any. Also, if the connection was in
   50082     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
   50083     ** lock held on the database file.
   50084     */
   50085     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
   50086     assert( rc2==SQLITE_OK );
   50087   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
   50088     /* This branch is taken when committing a transaction in rollback-journal
   50089     ** mode if the database file on disk is larger than the database image.
   50090     ** At this point the journal has been finalized and the transaction
   50091     ** successfully committed, but the EXCLUSIVE lock is still held on the
   50092     ** file. So it is safe to truncate the database file to its minimum
   50093     ** required size.  */
   50094     assert( pPager->eLock==EXCLUSIVE_LOCK );
   50095     rc = pager_truncate(pPager, pPager->dbSize);
   50096   }
   50097 
   50098   if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
   50099     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
   50100     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   50101   }
   50102 
   50103   if( !pPager->exclusiveMode
   50104    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
   50105   ){
   50106     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
   50107     pPager->changeCountDone = 0;
   50108   }
   50109   pPager->eState = PAGER_READER;
   50110   pPager->setMaster = 0;
   50111 
   50112   return (rc==SQLITE_OK?rc2:rc);
   50113 }
   50114 
   50115 /*
   50116 ** Execute a rollback if a transaction is active and unlock the
   50117 ** database file.
   50118 **
   50119 ** If the pager has already entered the ERROR state, do not attempt
   50120 ** the rollback at this time. Instead, pager_unlock() is called. The
   50121 ** call to pager_unlock() will discard all in-memory pages, unlock
   50122 ** the database file and move the pager back to OPEN state. If this
   50123 ** means that there is a hot-journal left in the file-system, the next
   50124 ** connection to obtain a shared lock on the pager (which may be this one)
   50125 ** will roll it back.
   50126 **
   50127 ** If the pager has not already entered the ERROR state, but an IO or
   50128 ** malloc error occurs during a rollback, then this will itself cause
   50129 ** the pager to enter the ERROR state. Which will be cleared by the
   50130 ** call to pager_unlock(), as described above.
   50131 */
   50132 static void pagerUnlockAndRollback(Pager *pPager){
   50133   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
   50134     assert( assert_pager_state(pPager) );
   50135     if( pPager->eState>=PAGER_WRITER_LOCKED ){
   50136       sqlite3BeginBenignMalloc();
   50137       sqlite3PagerRollback(pPager);
   50138       sqlite3EndBenignMalloc();
   50139     }else if( !pPager->exclusiveMode ){
   50140       assert( pPager->eState==PAGER_READER );
   50141       pager_end_transaction(pPager, 0, 0);
   50142     }
   50143   }
   50144   pager_unlock(pPager);
   50145 }
   50146 
   50147 /*
   50148 ** Parameter aData must point to a buffer of pPager->pageSize bytes
   50149 ** of data. Compute and return a checksum based ont the contents of the
   50150 ** page of data and the current value of pPager->cksumInit.
   50151 **
   50152 ** This is not a real checksum. It is really just the sum of the
   50153 ** random initial value (pPager->cksumInit) and every 200th byte
   50154 ** of the page data, starting with byte offset (pPager->pageSize%200).
   50155 ** Each byte is interpreted as an 8-bit unsigned integer.
   50156 **
   50157 ** Changing the formula used to compute this checksum results in an
   50158 ** incompatible journal file format.
   50159 **
   50160 ** If journal corruption occurs due to a power failure, the most likely
   50161 ** scenario is that one end or the other of the record will be changed.
   50162 ** It is much less likely that the two ends of the journal record will be
   50163 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
   50164 ** though fast and simple, catches the mostly likely kind of corruption.
   50165 */
   50166 static u32 pager_cksum(Pager *pPager, const u8 *aData){
   50167   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
   50168   int i = pPager->pageSize-200;          /* Loop counter */
   50169   while( i>0 ){
   50170     cksum += aData[i];
   50171     i -= 200;
   50172   }
   50173   return cksum;
   50174 }
   50175 
   50176 /*
   50177 ** Report the current page size and number of reserved bytes back
   50178 ** to the codec.
   50179 */
   50180 #ifdef SQLITE_HAS_CODEC
   50181 static void pagerReportSize(Pager *pPager){
   50182   if( pPager->xCodecSizeChng ){
   50183     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
   50184                            (int)pPager->nReserve);
   50185   }
   50186 }
   50187 #else
   50188 # define pagerReportSize(X)     /* No-op if we do not support a codec */
   50189 #endif
   50190 
   50191 #ifdef SQLITE_HAS_CODEC
   50192 /*
   50193 ** Make sure the number of reserved bits is the same in the destination
   50194 ** pager as it is in the source.  This comes up when a VACUUM changes the
   50195 ** number of reserved bits to the "optimal" amount.
   50196 */
   50197 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
   50198   if( pDest->nReserve!=pSrc->nReserve ){
   50199     pDest->nReserve = pSrc->nReserve;
   50200     pagerReportSize(pDest);
   50201   }
   50202 }
   50203 #endif
   50204 
   50205 /*
   50206 ** Read a single page from either the journal file (if isMainJrnl==1) or
   50207 ** from the sub-journal (if isMainJrnl==0) and playback that page.
   50208 ** The page begins at offset *pOffset into the file. The *pOffset
   50209 ** value is increased to the start of the next page in the journal.
   50210 **
   50211 ** The main rollback journal uses checksums - the statement journal does
   50212 ** not.
   50213 **
   50214 ** If the page number of the page record read from the (sub-)journal file
   50215 ** is greater than the current value of Pager.dbSize, then playback is
   50216 ** skipped and SQLITE_OK is returned.
   50217 **
   50218 ** If pDone is not NULL, then it is a record of pages that have already
   50219 ** been played back.  If the page at *pOffset has already been played back
   50220 ** (if the corresponding pDone bit is set) then skip the playback.
   50221 ** Make sure the pDone bit corresponding to the *pOffset page is set
   50222 ** prior to returning.
   50223 **
   50224 ** If the page record is successfully read from the (sub-)journal file
   50225 ** and played back, then SQLITE_OK is returned. If an IO error occurs
   50226 ** while reading the record from the (sub-)journal file or while writing
   50227 ** to the database file, then the IO error code is returned. If data
   50228 ** is successfully read from the (sub-)journal file but appears to be
   50229 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
   50230 ** two circumstances:
   50231 **
   50232 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
   50233 **   * If the record is being rolled back from the main journal file
   50234 **     and the checksum field does not match the record content.
   50235 **
   50236 ** Neither of these two scenarios are possible during a savepoint rollback.
   50237 **
   50238 ** If this is a savepoint rollback, then memory may have to be dynamically
   50239 ** allocated by this function. If this is the case and an allocation fails,
   50240 ** SQLITE_NOMEM is returned.
   50241 */
   50242 static int pager_playback_one_page(
   50243   Pager *pPager,                /* The pager being played back */
   50244   i64 *pOffset,                 /* Offset of record to playback */
   50245   Bitvec *pDone,                /* Bitvec of pages already played back */
   50246   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
   50247   int isSavepnt                 /* True for a savepoint rollback */
   50248 ){
   50249   int rc;
   50250   PgHdr *pPg;                   /* An existing page in the cache */
   50251   Pgno pgno;                    /* The page number of a page in journal */
   50252   u32 cksum;                    /* Checksum used for sanity checking */
   50253   char *aData;                  /* Temporary storage for the page */
   50254   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   50255   int isSynced;                 /* True if journal page is synced */
   50256 #ifdef SQLITE_HAS_CODEC
   50257   /* The jrnlEnc flag is true if Journal pages should be passed through
   50258   ** the codec.  It is false for pure in-memory journals. */
   50259   const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
   50260 #endif
   50261 
   50262   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   50263   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
   50264   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
   50265   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
   50266 
   50267   aData = pPager->pTmpSpace;
   50268   assert( aData );         /* Temp storage must have already been allocated */
   50269   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
   50270 
   50271   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
   50272   ** or savepoint rollback done at the request of the caller) or this is
   50273   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
   50274   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
   50275   ** only reads from the main journal, not the sub-journal.
   50276   */
   50277   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
   50278        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
   50279   );
   50280   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
   50281 
   50282   /* Read the page number and page data from the journal or sub-journal
   50283   ** file. Return an error code to the caller if an IO error occurs.
   50284   */
   50285   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
   50286   rc = read32bits(jfd, *pOffset, &pgno);
   50287   if( rc!=SQLITE_OK ) return rc;
   50288   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
   50289   if( rc!=SQLITE_OK ) return rc;
   50290   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
   50291 
   50292   /* Sanity checking on the page.  This is more important that I originally
   50293   ** thought.  If a power failure occurs while the journal is being written,
   50294   ** it could cause invalid data to be written into the journal.  We need to
   50295   ** detect this invalid data (with high probability) and ignore it.
   50296   */
   50297   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
   50298     assert( !isSavepnt );
   50299     return SQLITE_DONE;
   50300   }
   50301   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
   50302     return SQLITE_OK;
   50303   }
   50304   if( isMainJrnl ){
   50305     rc = read32bits(jfd, (*pOffset)-4, &cksum);
   50306     if( rc ) return rc;
   50307     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
   50308       return SQLITE_DONE;
   50309     }
   50310   }
   50311 
   50312   /* If this page has already been played back before during the current
   50313   ** rollback, then don't bother to play it back again.
   50314   */
   50315   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
   50316     return rc;
   50317   }
   50318 
   50319   /* When playing back page 1, restore the nReserve setting
   50320   */
   50321   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
   50322     pPager->nReserve = ((u8*)aData)[20];
   50323     pagerReportSize(pPager);
   50324   }
   50325 
   50326   /* If the pager is in CACHEMOD state, then there must be a copy of this
   50327   ** page in the pager cache. In this case just update the pager cache,
   50328   ** not the database file. The page is left marked dirty in this case.
   50329   **
   50330   ** An exception to the above rule: If the database is in no-sync mode
   50331   ** and a page is moved during an incremental vacuum then the page may
   50332   ** not be in the pager cache. Later: if a malloc() or IO error occurs
   50333   ** during a Movepage() call, then the page may not be in the cache
   50334   ** either. So the condition described in the above paragraph is not
   50335   ** assert()able.
   50336   **
   50337   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
   50338   ** pager cache if it exists and the main file. The page is then marked
   50339   ** not dirty. Since this code is only executed in PAGER_OPEN state for
   50340   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
   50341   ** if the pager is in OPEN state.
   50342   **
   50343   ** Ticket #1171:  The statement journal might contain page content that is
   50344   ** different from the page content at the start of the transaction.
   50345   ** This occurs when a page is changed prior to the start of a statement
   50346   ** then changed again within the statement.  When rolling back such a
   50347   ** statement we must not write to the original database unless we know
   50348   ** for certain that original page contents are synced into the main rollback
   50349   ** journal.  Otherwise, a power loss might leave modified data in the
   50350   ** database file without an entry in the rollback journal that can
   50351   ** restore the database to its original form.  Two conditions must be
   50352   ** met before writing to the database files. (1) the database must be
   50353   ** locked.  (2) we know that the original page content is fully synced
   50354   ** in the main journal either because the page is not in cache or else
   50355   ** the page is marked as needSync==0.
   50356   **
   50357   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
   50358   ** is possible to fail a statement on a database that does not yet exist.
   50359   ** Do not attempt to write if database file has never been opened.
   50360   */
   50361   if( pagerUseWal(pPager) ){
   50362     pPg = 0;
   50363   }else{
   50364     pPg = sqlite3PagerLookup(pPager, pgno);
   50365   }
   50366   assert( pPg || !MEMDB );
   50367   assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
   50368   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
   50369            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
   50370            (isMainJrnl?"main-journal":"sub-journal")
   50371   ));
   50372   if( isMainJrnl ){
   50373     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
   50374   }else{
   50375     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
   50376   }
   50377   if( isOpen(pPager->fd)
   50378    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   50379    && isSynced
   50380   ){
   50381     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
   50382     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
   50383     assert( !pagerUseWal(pPager) );
   50384 
   50385     /* Write the data read from the journal back into the database file.
   50386     ** This is usually safe even for an encrypted database - as the data
   50387     ** was encrypted before it was written to the journal file. The exception
   50388     ** is if the data was just read from an in-memory sub-journal. In that
   50389     ** case it must be encrypted here before it is copied into the database
   50390     ** file.  */
   50391 #ifdef SQLITE_HAS_CODEC
   50392     if( !jrnlEnc ){
   50393       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
   50394       rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
   50395       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
   50396     }else
   50397 #endif
   50398     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
   50399 
   50400     if( pgno>pPager->dbFileSize ){
   50401       pPager->dbFileSize = pgno;
   50402     }
   50403     if( pPager->pBackup ){
   50404 #ifdef SQLITE_HAS_CODEC
   50405       if( jrnlEnc ){
   50406         CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
   50407         sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   50408         CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
   50409       }else
   50410 #endif
   50411       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   50412     }
   50413   }else if( !isMainJrnl && pPg==0 ){
   50414     /* If this is a rollback of a savepoint and data was not written to
   50415     ** the database and the page is not in-memory, there is a potential
   50416     ** problem. When the page is next fetched by the b-tree layer, it
   50417     ** will be read from the database file, which may or may not be
   50418     ** current.
   50419     **
   50420     ** There are a couple of different ways this can happen. All are quite
   50421     ** obscure. When running in synchronous mode, this can only happen
   50422     ** if the page is on the free-list at the start of the transaction, then
   50423     ** populated, then moved using sqlite3PagerMovepage().
   50424     **
   50425     ** The solution is to add an in-memory page to the cache containing
   50426     ** the data just read from the sub-journal. Mark the page as dirty
   50427     ** and if the pager requires a journal-sync, then mark the page as
   50428     ** requiring a journal-sync before it is written.
   50429     */
   50430     assert( isSavepnt );
   50431     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
   50432     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
   50433     rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
   50434     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
   50435     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
   50436     if( rc!=SQLITE_OK ) return rc;
   50437     sqlite3PcacheMakeDirty(pPg);
   50438   }
   50439   if( pPg ){
   50440     /* No page should ever be explicitly rolled back that is in use, except
   50441     ** for page 1 which is held in use in order to keep the lock on the
   50442     ** database active. However such a page may be rolled back as a result
   50443     ** of an internal error resulting in an automatic call to
   50444     ** sqlite3PagerRollback().
   50445     */
   50446     void *pData;
   50447     pData = pPg->pData;
   50448     memcpy(pData, (u8*)aData, pPager->pageSize);
   50449     pPager->xReiniter(pPg);
   50450     /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
   50451     ** that call was dangerous and had no detectable benefit since the cache
   50452     ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
   50453     ** has been removed. */
   50454     pager_set_pagehash(pPg);
   50455 
   50456     /* If this was page 1, then restore the value of Pager.dbFileVers.
   50457     ** Do this before any decoding. */
   50458     if( pgno==1 ){
   50459       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
   50460     }
   50461 
   50462     /* Decode the page just read from disk */
   50463 #if SQLITE_HAS_CODEC
   50464     if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
   50465 #endif
   50466     sqlite3PcacheRelease(pPg);
   50467   }
   50468   return rc;
   50469 }
   50470 
   50471 /*
   50472 ** Parameter zMaster is the name of a master journal file. A single journal
   50473 ** file that referred to the master journal file has just been rolled back.
   50474 ** This routine checks if it is possible to delete the master journal file,
   50475 ** and does so if it is.
   50476 **
   50477 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
   50478 ** available for use within this function.
   50479 **
   50480 ** When a master journal file is created, it is populated with the names
   50481 ** of all of its child journals, one after another, formatted as utf-8
   50482 ** encoded text. The end of each child journal file is marked with a
   50483 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
   50484 ** file for a transaction involving two databases might be:
   50485 **
   50486 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
   50487 **
   50488 ** A master journal file may only be deleted once all of its child
   50489 ** journals have been rolled back.
   50490 **
   50491 ** This function reads the contents of the master-journal file into
   50492 ** memory and loops through each of the child journal names. For
   50493 ** each child journal, it checks if:
   50494 **
   50495 **   * if the child journal exists, and if so
   50496 **   * if the child journal contains a reference to master journal
   50497 **     file zMaster
   50498 **
   50499 ** If a child journal can be found that matches both of the criteria
   50500 ** above, this function returns without doing anything. Otherwise, if
   50501 ** no such child journal can be found, file zMaster is deleted from
   50502 ** the file-system using sqlite3OsDelete().
   50503 **
   50504 ** If an IO error within this function, an error code is returned. This
   50505 ** function allocates memory by calling sqlite3Malloc(). If an allocation
   50506 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
   50507 ** occur, SQLITE_OK is returned.
   50508 **
   50509 ** TODO: This function allocates a single block of memory to load
   50510 ** the entire contents of the master journal file. This could be
   50511 ** a couple of kilobytes or so - potentially larger than the page
   50512 ** size.
   50513 */
   50514 static int pager_delmaster(Pager *pPager, const char *zMaster){
   50515   sqlite3_vfs *pVfs = pPager->pVfs;
   50516   int rc;                   /* Return code */
   50517   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
   50518   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
   50519   char *zMasterJournal = 0; /* Contents of master journal file */
   50520   i64 nMasterJournal;       /* Size of master journal file */
   50521   char *zJournal;           /* Pointer to one journal within MJ file */
   50522   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
   50523   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
   50524 
   50525   /* Allocate space for both the pJournal and pMaster file descriptors.
   50526   ** If successful, open the master journal file for reading.
   50527   */
   50528   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
   50529   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
   50530   if( !pMaster ){
   50531     rc = SQLITE_NOMEM_BKPT;
   50532   }else{
   50533     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
   50534     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
   50535   }
   50536   if( rc!=SQLITE_OK ) goto delmaster_out;
   50537 
   50538   /* Load the entire master journal file into space obtained from
   50539   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
   50540   ** sufficient space (in zMasterPtr) to hold the names of master
   50541   ** journal files extracted from regular rollback-journals.
   50542   */
   50543   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
   50544   if( rc!=SQLITE_OK ) goto delmaster_out;
   50545   nMasterPtr = pVfs->mxPathname+1;
   50546   zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
   50547   if( !zMasterJournal ){
   50548     rc = SQLITE_NOMEM_BKPT;
   50549     goto delmaster_out;
   50550   }
   50551   zMasterPtr = &zMasterJournal[nMasterJournal+1];
   50552   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
   50553   if( rc!=SQLITE_OK ) goto delmaster_out;
   50554   zMasterJournal[nMasterJournal] = 0;
   50555 
   50556   zJournal = zMasterJournal;
   50557   while( (zJournal-zMasterJournal)<nMasterJournal ){
   50558     int exists;
   50559     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
   50560     if( rc!=SQLITE_OK ){
   50561       goto delmaster_out;
   50562     }
   50563     if( exists ){
   50564       /* One of the journals pointed to by the master journal exists.
   50565       ** Open it and check if it points at the master journal. If
   50566       ** so, return without deleting the master journal file.
   50567       */
   50568       int c;
   50569       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
   50570       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
   50571       if( rc!=SQLITE_OK ){
   50572         goto delmaster_out;
   50573       }
   50574 
   50575       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
   50576       sqlite3OsClose(pJournal);
   50577       if( rc!=SQLITE_OK ){
   50578         goto delmaster_out;
   50579       }
   50580 
   50581       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
   50582       if( c ){
   50583         /* We have a match. Do not delete the master journal file. */
   50584         goto delmaster_out;
   50585       }
   50586     }
   50587     zJournal += (sqlite3Strlen30(zJournal)+1);
   50588   }
   50589 
   50590   sqlite3OsClose(pMaster);
   50591   rc = sqlite3OsDelete(pVfs, zMaster, 0);
   50592 
   50593 delmaster_out:
   50594   sqlite3_free(zMasterJournal);
   50595   if( pMaster ){
   50596     sqlite3OsClose(pMaster);
   50597     assert( !isOpen(pJournal) );
   50598     sqlite3_free(pMaster);
   50599   }
   50600   return rc;
   50601 }
   50602 
   50603 
   50604 /*
   50605 ** This function is used to change the actual size of the database
   50606 ** file in the file-system. This only happens when committing a transaction,
   50607 ** or rolling back a transaction (including rolling back a hot-journal).
   50608 **
   50609 ** If the main database file is not open, or the pager is not in either
   50610 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
   50611 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
   50612 ** If the file on disk is currently larger than nPage pages, then use the VFS
   50613 ** xTruncate() method to truncate it.
   50614 **
   50615 ** Or, it might be the case that the file on disk is smaller than
   50616 ** nPage pages. Some operating system implementations can get confused if
   50617 ** you try to truncate a file to some size that is larger than it
   50618 ** currently is, so detect this case and write a single zero byte to
   50619 ** the end of the new file instead.
   50620 **
   50621 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
   50622 ** the database file, return the error code to the caller.
   50623 */
   50624 static int pager_truncate(Pager *pPager, Pgno nPage){
   50625   int rc = SQLITE_OK;
   50626   assert( pPager->eState!=PAGER_ERROR );
   50627   assert( pPager->eState!=PAGER_READER );
   50628 
   50629   if( isOpen(pPager->fd)
   50630    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   50631   ){
   50632     i64 currentSize, newSize;
   50633     int szPage = pPager->pageSize;
   50634     assert( pPager->eLock==EXCLUSIVE_LOCK );
   50635     /* TODO: Is it safe to use Pager.dbFileSize here? */
   50636     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
   50637     newSize = szPage*(i64)nPage;
   50638     if( rc==SQLITE_OK && currentSize!=newSize ){
   50639       if( currentSize>newSize ){
   50640         rc = sqlite3OsTruncate(pPager->fd, newSize);
   50641       }else if( (currentSize+szPage)<=newSize ){
   50642         char *pTmp = pPager->pTmpSpace;
   50643         memset(pTmp, 0, szPage);
   50644         testcase( (newSize-szPage) == currentSize );
   50645         testcase( (newSize-szPage) >  currentSize );
   50646         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
   50647       }
   50648       if( rc==SQLITE_OK ){
   50649         pPager->dbFileSize = nPage;
   50650       }
   50651     }
   50652   }
   50653   return rc;
   50654 }
   50655 
   50656 /*
   50657 ** Return a sanitized version of the sector-size of OS file pFile. The
   50658 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
   50659 */
   50660 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
   50661   int iRet = sqlite3OsSectorSize(pFile);
   50662   if( iRet<32 ){
   50663     iRet = 512;
   50664   }else if( iRet>MAX_SECTOR_SIZE ){
   50665     assert( MAX_SECTOR_SIZE>=512 );
   50666     iRet = MAX_SECTOR_SIZE;
   50667   }
   50668   return iRet;
   50669 }
   50670 
   50671 /*
   50672 ** Set the value of the Pager.sectorSize variable for the given
   50673 ** pager based on the value returned by the xSectorSize method
   50674 ** of the open database file. The sector size will be used
   50675 ** to determine the size and alignment of journal header and
   50676 ** master journal pointers within created journal files.
   50677 **
   50678 ** For temporary files the effective sector size is always 512 bytes.
   50679 **
   50680 ** Otherwise, for non-temporary files, the effective sector size is
   50681 ** the value returned by the xSectorSize() method rounded up to 32 if
   50682 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
   50683 ** is greater than MAX_SECTOR_SIZE.
   50684 **
   50685 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
   50686 ** the effective sector size to its minimum value (512).  The purpose of
   50687 ** pPager->sectorSize is to define the "blast radius" of bytes that
   50688 ** might change if a crash occurs while writing to a single byte in
   50689 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
   50690 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
   50691 ** size.  For backwards compatibility of the rollback journal file format,
   50692 ** we cannot reduce the effective sector size below 512.
   50693 */
   50694 static void setSectorSize(Pager *pPager){
   50695   assert( isOpen(pPager->fd) || pPager->tempFile );
   50696 
   50697   if( pPager->tempFile
   50698    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
   50699               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
   50700   ){
   50701     /* Sector size doesn't matter for temporary files. Also, the file
   50702     ** may not have been opened yet, in which case the OsSectorSize()
   50703     ** call will segfault. */
   50704     pPager->sectorSize = 512;
   50705   }else{
   50706     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
   50707   }
   50708 }
   50709 
   50710 /*
   50711 ** Playback the journal and thus restore the database file to
   50712 ** the state it was in before we started making changes.
   50713 **
   50714 ** The journal file format is as follows:
   50715 **
   50716 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
   50717 **  (2)  4 byte big-endian integer which is the number of valid page records
   50718 **       in the journal.  If this value is 0xffffffff, then compute the
   50719 **       number of page records from the journal size.
   50720 **  (3)  4 byte big-endian integer which is the initial value for the
   50721 **       sanity checksum.
   50722 **  (4)  4 byte integer which is the number of pages to truncate the
   50723 **       database to during a rollback.
   50724 **  (5)  4 byte big-endian integer which is the sector size.  The header
   50725 **       is this many bytes in size.
   50726 **  (6)  4 byte big-endian integer which is the page size.
   50727 **  (7)  zero padding out to the next sector size.
   50728 **  (8)  Zero or more pages instances, each as follows:
   50729 **        +  4 byte page number.
   50730 **        +  pPager->pageSize bytes of data.
   50731 **        +  4 byte checksum
   50732 **
   50733 ** When we speak of the journal header, we mean the first 7 items above.
   50734 ** Each entry in the journal is an instance of the 8th item.
   50735 **
   50736 ** Call the value from the second bullet "nRec".  nRec is the number of
   50737 ** valid page entries in the journal.  In most cases, you can compute the
   50738 ** value of nRec from the size of the journal file.  But if a power
   50739 ** failure occurred while the journal was being written, it could be the
   50740 ** case that the size of the journal file had already been increased but
   50741 ** the extra entries had not yet made it safely to disk.  In such a case,
   50742 ** the value of nRec computed from the file size would be too large.  For
   50743 ** that reason, we always use the nRec value in the header.
   50744 **
   50745 ** If the nRec value is 0xffffffff it means that nRec should be computed
   50746 ** from the file size.  This value is used when the user selects the
   50747 ** no-sync option for the journal.  A power failure could lead to corruption
   50748 ** in this case.  But for things like temporary table (which will be
   50749 ** deleted when the power is restored) we don't care.
   50750 **
   50751 ** If the file opened as the journal file is not a well-formed
   50752 ** journal file then all pages up to the first corrupted page are rolled
   50753 ** back (or no pages if the journal header is corrupted). The journal file
   50754 ** is then deleted and SQLITE_OK returned, just as if no corruption had
   50755 ** been encountered.
   50756 **
   50757 ** If an I/O or malloc() error occurs, the journal-file is not deleted
   50758 ** and an error code is returned.
   50759 **
   50760 ** The isHot parameter indicates that we are trying to rollback a journal
   50761 ** that might be a hot journal.  Or, it could be that the journal is
   50762 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
   50763 ** If the journal really is hot, reset the pager cache prior rolling
   50764 ** back any content.  If the journal is merely persistent, no reset is
   50765 ** needed.
   50766 */
   50767 static int pager_playback(Pager *pPager, int isHot){
   50768   sqlite3_vfs *pVfs = pPager->pVfs;
   50769   i64 szJ;                 /* Size of the journal file in bytes */
   50770   u32 nRec;                /* Number of Records in the journal */
   50771   u32 u;                   /* Unsigned loop counter */
   50772   Pgno mxPg = 0;           /* Size of the original file in pages */
   50773   int rc;                  /* Result code of a subroutine */
   50774   int res = 1;             /* Value returned by sqlite3OsAccess() */
   50775   char *zMaster = 0;       /* Name of master journal file if any */
   50776   int needPagerReset;      /* True to reset page prior to first page rollback */
   50777   int nPlayback = 0;       /* Total number of pages restored from journal */
   50778   u32 savedPageSize = pPager->pageSize;
   50779 
   50780   /* Figure out how many records are in the journal.  Abort early if
   50781   ** the journal is empty.
   50782   */
   50783   assert( isOpen(pPager->jfd) );
   50784   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
   50785   if( rc!=SQLITE_OK ){
   50786     goto end_playback;
   50787   }
   50788 
   50789   /* Read the master journal name from the journal, if it is present.
   50790   ** If a master journal file name is specified, but the file is not
   50791   ** present on disk, then the journal is not hot and does not need to be
   50792   ** played back.
   50793   **
   50794   ** TODO: Technically the following is an error because it assumes that
   50795   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
   50796   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
   50797   ** mxPathname is 512, which is the same as the minimum allowable value
   50798   ** for pageSize.
   50799   */
   50800   zMaster = pPager->pTmpSpace;
   50801   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   50802   if( rc==SQLITE_OK && zMaster[0] ){
   50803     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   50804   }
   50805   zMaster = 0;
   50806   if( rc!=SQLITE_OK || !res ){
   50807     goto end_playback;
   50808   }
   50809   pPager->journalOff = 0;
   50810   needPagerReset = isHot;
   50811 
   50812   /* This loop terminates either when a readJournalHdr() or
   50813   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
   50814   ** occurs.
   50815   */
   50816   while( 1 ){
   50817     /* Read the next journal header from the journal file.  If there are
   50818     ** not enough bytes left in the journal file for a complete header, or
   50819     ** it is corrupted, then a process must have failed while writing it.
   50820     ** This indicates nothing more needs to be rolled back.
   50821     */
   50822     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
   50823     if( rc!=SQLITE_OK ){
   50824       if( rc==SQLITE_DONE ){
   50825         rc = SQLITE_OK;
   50826       }
   50827       goto end_playback;
   50828     }
   50829 
   50830     /* If nRec is 0xffffffff, then this journal was created by a process
   50831     ** working in no-sync mode. This means that the rest of the journal
   50832     ** file consists of pages, there are no more journal headers. Compute
   50833     ** the value of nRec based on this assumption.
   50834     */
   50835     if( nRec==0xffffffff ){
   50836       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   50837       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
   50838     }
   50839 
   50840     /* If nRec is 0 and this rollback is of a transaction created by this
   50841     ** process and if this is the final header in the journal, then it means
   50842     ** that this part of the journal was being filled but has not yet been
   50843     ** synced to disk.  Compute the number of pages based on the remaining
   50844     ** size of the file.
   50845     **
   50846     ** The third term of the test was added to fix ticket #2565.
   50847     ** When rolling back a hot journal, nRec==0 always means that the next
   50848     ** chunk of the journal contains zero pages to be rolled back.  But
   50849     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
   50850     ** the journal, it means that the journal might contain additional
   50851     ** pages that need to be rolled back and that the number of pages
   50852     ** should be computed based on the journal file size.
   50853     */
   50854     if( nRec==0 && !isHot &&
   50855         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
   50856       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
   50857     }
   50858 
   50859     /* If this is the first header read from the journal, truncate the
   50860     ** database file back to its original size.
   50861     */
   50862     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
   50863       rc = pager_truncate(pPager, mxPg);
   50864       if( rc!=SQLITE_OK ){
   50865         goto end_playback;
   50866       }
   50867       pPager->dbSize = mxPg;
   50868     }
   50869 
   50870     /* Copy original pages out of the journal and back into the
   50871     ** database file and/or page cache.
   50872     */
   50873     for(u=0; u<nRec; u++){
   50874       if( needPagerReset ){
   50875         pager_reset(pPager);
   50876         needPagerReset = 0;
   50877       }
   50878       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
   50879       if( rc==SQLITE_OK ){
   50880         nPlayback++;
   50881       }else{
   50882         if( rc==SQLITE_DONE ){
   50883           pPager->journalOff = szJ;
   50884           break;
   50885         }else if( rc==SQLITE_IOERR_SHORT_READ ){
   50886           /* If the journal has been truncated, simply stop reading and
   50887           ** processing the journal. This might happen if the journal was
   50888           ** not completely written and synced prior to a crash.  In that
   50889           ** case, the database should have never been written in the
   50890           ** first place so it is OK to simply abandon the rollback. */
   50891           rc = SQLITE_OK;
   50892           goto end_playback;
   50893         }else{
   50894           /* If we are unable to rollback, quit and return the error
   50895           ** code.  This will cause the pager to enter the error state
   50896           ** so that no further harm will be done.  Perhaps the next
   50897           ** process to come along will be able to rollback the database.
   50898           */
   50899           goto end_playback;
   50900         }
   50901       }
   50902     }
   50903   }
   50904   /*NOTREACHED*/
   50905   assert( 0 );
   50906 
   50907 end_playback:
   50908   if( rc==SQLITE_OK ){
   50909     rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
   50910   }
   50911   /* Following a rollback, the database file should be back in its original
   50912   ** state prior to the start of the transaction, so invoke the
   50913   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
   50914   ** assertion that the transaction counter was modified.
   50915   */
   50916 #ifdef SQLITE_DEBUG
   50917   if( pPager->fd->pMethods ){
   50918     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
   50919   }
   50920 #endif
   50921 
   50922   /* If this playback is happening automatically as a result of an IO or
   50923   ** malloc error that occurred after the change-counter was updated but
   50924   ** before the transaction was committed, then the change-counter
   50925   ** modification may just have been reverted. If this happens in exclusive
   50926   ** mode, then subsequent transactions performed by the connection will not
   50927   ** update the change-counter at all. This may lead to cache inconsistency
   50928   ** problems for other processes at some point in the future. So, just
   50929   ** in case this has happened, clear the changeCountDone flag now.
   50930   */
   50931   pPager->changeCountDone = pPager->tempFile;
   50932 
   50933   if( rc==SQLITE_OK ){
   50934     zMaster = pPager->pTmpSpace;
   50935     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   50936     testcase( rc!=SQLITE_OK );
   50937   }
   50938   if( rc==SQLITE_OK
   50939    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   50940   ){
   50941     rc = sqlite3PagerSync(pPager, 0);
   50942   }
   50943   if( rc==SQLITE_OK ){
   50944     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
   50945     testcase( rc!=SQLITE_OK );
   50946   }
   50947   if( rc==SQLITE_OK && zMaster[0] && res ){
   50948     /* If there was a master journal and this routine will return success,
   50949     ** see if it is possible to delete the master journal.
   50950     */
   50951     rc = pager_delmaster(pPager, zMaster);
   50952     testcase( rc!=SQLITE_OK );
   50953   }
   50954   if( isHot && nPlayback ){
   50955     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
   50956                 nPlayback, pPager->zJournal);
   50957   }
   50958 
   50959   /* The Pager.sectorSize variable may have been updated while rolling
   50960   ** back a journal created by a process with a different sector size
   50961   ** value. Reset it to the correct value for this process.
   50962   */
   50963   setSectorSize(pPager);
   50964   return rc;
   50965 }
   50966 
   50967 
   50968 /*
   50969 ** Read the content for page pPg out of the database file (or out of
   50970 ** the WAL if that is where the most recent copy if found) into
   50971 ** pPg->pData. A shared lock or greater must be held on the database
   50972 ** file before this function is called.
   50973 **
   50974 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
   50975 ** the value read from the database file.
   50976 **
   50977 ** If an IO error occurs, then the IO error is returned to the caller.
   50978 ** Otherwise, SQLITE_OK is returned.
   50979 */
   50980 static int readDbPage(PgHdr *pPg){
   50981   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
   50982   int rc = SQLITE_OK;          /* Return code */
   50983 
   50984 #ifndef SQLITE_OMIT_WAL
   50985   u32 iFrame = 0;              /* Frame of WAL containing pgno */
   50986 
   50987   assert( pPager->eState>=PAGER_READER && !MEMDB );
   50988   assert( isOpen(pPager->fd) );
   50989 
   50990   if( pagerUseWal(pPager) ){
   50991     rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
   50992     if( rc ) return rc;
   50993   }
   50994   if( iFrame ){
   50995     rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
   50996   }else
   50997 #endif
   50998   {
   50999     i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
   51000     rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
   51001     if( rc==SQLITE_IOERR_SHORT_READ ){
   51002       rc = SQLITE_OK;
   51003     }
   51004   }
   51005 
   51006   if( pPg->pgno==1 ){
   51007     if( rc ){
   51008       /* If the read is unsuccessful, set the dbFileVers[] to something
   51009       ** that will never be a valid file version.  dbFileVers[] is a copy
   51010       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
   51011       ** zero or the size of the database in page. Bytes 32..35 and 35..39
   51012       ** should be page numbers which are never 0xffffffff.  So filling
   51013       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
   51014       **
   51015       ** For an encrypted database, the situation is more complex:  bytes
   51016       ** 24..39 of the database are white noise.  But the probability of
   51017       ** white noise equaling 16 bytes of 0xff is vanishingly small so
   51018       ** we should still be ok.
   51019       */
   51020       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
   51021     }else{
   51022       u8 *dbFileVers = &((u8*)pPg->pData)[24];
   51023       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
   51024     }
   51025   }
   51026   CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
   51027 
   51028   PAGER_INCR(sqlite3_pager_readdb_count);
   51029   PAGER_INCR(pPager->nRead);
   51030   IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
   51031   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
   51032                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
   51033 
   51034   return rc;
   51035 }
   51036 
   51037 /*
   51038 ** Update the value of the change-counter at offsets 24 and 92 in
   51039 ** the header and the sqlite version number at offset 96.
   51040 **
   51041 ** This is an unconditional update.  See also the pager_incr_changecounter()
   51042 ** routine which only updates the change-counter if the update is actually
   51043 ** needed, as determined by the pPager->changeCountDone state variable.
   51044 */
   51045 static void pager_write_changecounter(PgHdr *pPg){
   51046   u32 change_counter;
   51047 
   51048   /* Increment the value just read and write it back to byte 24. */
   51049   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
   51050   put32bits(((char*)pPg->pData)+24, change_counter);
   51051 
   51052   /* Also store the SQLite version number in bytes 96..99 and in
   51053   ** bytes 92..95 store the change counter for which the version number
   51054   ** is valid. */
   51055   put32bits(((char*)pPg->pData)+92, change_counter);
   51056   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
   51057 }
   51058 
   51059 #ifndef SQLITE_OMIT_WAL
   51060 /*
   51061 ** This function is invoked once for each page that has already been
   51062 ** written into the log file when a WAL transaction is rolled back.
   51063 ** Parameter iPg is the page number of said page. The pCtx argument
   51064 ** is actually a pointer to the Pager structure.
   51065 **
   51066 ** If page iPg is present in the cache, and has no outstanding references,
   51067 ** it is discarded. Otherwise, if there are one or more outstanding
   51068 ** references, the page content is reloaded from the database. If the
   51069 ** attempt to reload content from the database is required and fails,
   51070 ** return an SQLite error code. Otherwise, SQLITE_OK.
   51071 */
   51072 static int pagerUndoCallback(void *pCtx, Pgno iPg){
   51073   int rc = SQLITE_OK;
   51074   Pager *pPager = (Pager *)pCtx;
   51075   PgHdr *pPg;
   51076 
   51077   assert( pagerUseWal(pPager) );
   51078   pPg = sqlite3PagerLookup(pPager, iPg);
   51079   if( pPg ){
   51080     if( sqlite3PcachePageRefcount(pPg)==1 ){
   51081       sqlite3PcacheDrop(pPg);
   51082     }else{
   51083       rc = readDbPage(pPg);
   51084       if( rc==SQLITE_OK ){
   51085         pPager->xReiniter(pPg);
   51086       }
   51087       sqlite3PagerUnrefNotNull(pPg);
   51088     }
   51089   }
   51090 
   51091   /* Normally, if a transaction is rolled back, any backup processes are
   51092   ** updated as data is copied out of the rollback journal and into the
   51093   ** database. This is not generally possible with a WAL database, as
   51094   ** rollback involves simply truncating the log file. Therefore, if one
   51095   ** or more frames have already been written to the log (and therefore
   51096   ** also copied into the backup databases) as part of this transaction,
   51097   ** the backups must be restarted.
   51098   */
   51099   sqlite3BackupRestart(pPager->pBackup);
   51100 
   51101   return rc;
   51102 }
   51103 
   51104 /*
   51105 ** This function is called to rollback a transaction on a WAL database.
   51106 */
   51107 static int pagerRollbackWal(Pager *pPager){
   51108   int rc;                         /* Return Code */
   51109   PgHdr *pList;                   /* List of dirty pages to revert */
   51110 
   51111   /* For all pages in the cache that are currently dirty or have already
   51112   ** been written (but not committed) to the log file, do one of the
   51113   ** following:
   51114   **
   51115   **   + Discard the cached page (if refcount==0), or
   51116   **   + Reload page content from the database (if refcount>0).
   51117   */
   51118   pPager->dbSize = pPager->dbOrigSize;
   51119   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
   51120   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   51121   while( pList && rc==SQLITE_OK ){
   51122     PgHdr *pNext = pList->pDirty;
   51123     rc = pagerUndoCallback((void *)pPager, pList->pgno);
   51124     pList = pNext;
   51125   }
   51126 
   51127   return rc;
   51128 }
   51129 
   51130 /*
   51131 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
   51132 ** the contents of the list of pages headed by pList (connected by pDirty),
   51133 ** this function notifies any active backup processes that the pages have
   51134 ** changed.
   51135 **
   51136 ** The list of pages passed into this routine is always sorted by page number.
   51137 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
   51138 */
   51139 static int pagerWalFrames(
   51140   Pager *pPager,                  /* Pager object */
   51141   PgHdr *pList,                   /* List of frames to log */
   51142   Pgno nTruncate,                 /* Database size after this commit */
   51143   int isCommit                    /* True if this is a commit */
   51144 ){
   51145   int rc;                         /* Return code */
   51146   int nList;                      /* Number of pages in pList */
   51147   PgHdr *p;                       /* For looping over pages */
   51148 
   51149   assert( pPager->pWal );
   51150   assert( pList );
   51151 #ifdef SQLITE_DEBUG
   51152   /* Verify that the page list is in accending order */
   51153   for(p=pList; p && p->pDirty; p=p->pDirty){
   51154     assert( p->pgno < p->pDirty->pgno );
   51155   }
   51156 #endif
   51157 
   51158   assert( pList->pDirty==0 || isCommit );
   51159   if( isCommit ){
   51160     /* If a WAL transaction is being committed, there is no point in writing
   51161     ** any pages with page numbers greater than nTruncate into the WAL file.
   51162     ** They will never be read by any client. So remove them from the pDirty
   51163     ** list here. */
   51164     PgHdr **ppNext = &pList;
   51165     nList = 0;
   51166     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
   51167       if( p->pgno<=nTruncate ){
   51168         ppNext = &p->pDirty;
   51169         nList++;
   51170       }
   51171     }
   51172     assert( pList );
   51173   }else{
   51174     nList = 1;
   51175   }
   51176   pPager->aStat[PAGER_STAT_WRITE] += nList;
   51177 
   51178   if( pList->pgno==1 ) pager_write_changecounter(pList);
   51179   rc = sqlite3WalFrames(pPager->pWal,
   51180       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
   51181   );
   51182   if( rc==SQLITE_OK && pPager->pBackup ){
   51183     for(p=pList; p; p=p->pDirty){
   51184       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
   51185     }
   51186   }
   51187 
   51188 #ifdef SQLITE_CHECK_PAGES
   51189   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   51190   for(p=pList; p; p=p->pDirty){
   51191     pager_set_pagehash(p);
   51192   }
   51193 #endif
   51194 
   51195   return rc;
   51196 }
   51197 
   51198 /*
   51199 ** Begin a read transaction on the WAL.
   51200 **
   51201 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
   51202 ** makes a snapshot of the database at the current point in time and preserves
   51203 ** that snapshot for use by the reader in spite of concurrently changes by
   51204 ** other writers or checkpointers.
   51205 */
   51206 static int pagerBeginReadTransaction(Pager *pPager){
   51207   int rc;                         /* Return code */
   51208   int changed = 0;                /* True if cache must be reset */
   51209 
   51210   assert( pagerUseWal(pPager) );
   51211   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   51212 
   51213   /* sqlite3WalEndReadTransaction() was not called for the previous
   51214   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
   51215   ** are in locking_mode=NORMAL and EndRead() was previously called,
   51216   ** the duplicate call is harmless.
   51217   */
   51218   sqlite3WalEndReadTransaction(pPager->pWal);
   51219 
   51220   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
   51221   if( rc!=SQLITE_OK || changed ){
   51222     pager_reset(pPager);
   51223     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
   51224   }
   51225 
   51226   return rc;
   51227 }
   51228 #endif
   51229 
   51230 /*
   51231 ** This function is called as part of the transition from PAGER_OPEN
   51232 ** to PAGER_READER state to determine the size of the database file
   51233 ** in pages (assuming the page size currently stored in Pager.pageSize).
   51234 **
   51235 ** If no error occurs, SQLITE_OK is returned and the size of the database
   51236 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
   51237 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
   51238 */
   51239 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
   51240   Pgno nPage;                     /* Value to return via *pnPage */
   51241 
   51242   /* Query the WAL sub-system for the database size. The WalDbsize()
   51243   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
   51244   ** if the database size is not available. The database size is not
   51245   ** available from the WAL sub-system if the log file is empty or
   51246   ** contains no valid committed transactions.
   51247   */
   51248   assert( pPager->eState==PAGER_OPEN );
   51249   assert( pPager->eLock>=SHARED_LOCK );
   51250   assert( isOpen(pPager->fd) );
   51251   assert( pPager->tempFile==0 );
   51252   nPage = sqlite3WalDbsize(pPager->pWal);
   51253 
   51254   /* If the number of pages in the database is not available from the
   51255   ** WAL sub-system, determine the page count based on the size of
   51256   ** the database file.  If the size of the database file is not an
   51257   ** integer multiple of the page-size, round up the result.
   51258   */
   51259   if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
   51260     i64 n = 0;                    /* Size of db file in bytes */
   51261     int rc = sqlite3OsFileSize(pPager->fd, &n);
   51262     if( rc!=SQLITE_OK ){
   51263       return rc;
   51264     }
   51265     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
   51266   }
   51267 
   51268   /* If the current number of pages in the file is greater than the
   51269   ** configured maximum pager number, increase the allowed limit so
   51270   ** that the file can be read.
   51271   */
   51272   if( nPage>pPager->mxPgno ){
   51273     pPager->mxPgno = (Pgno)nPage;
   51274   }
   51275 
   51276   *pnPage = nPage;
   51277   return SQLITE_OK;
   51278 }
   51279 
   51280 #ifndef SQLITE_OMIT_WAL
   51281 /*
   51282 ** Check if the *-wal file that corresponds to the database opened by pPager
   51283 ** exists if the database is not empy, or verify that the *-wal file does
   51284 ** not exist (by deleting it) if the database file is empty.
   51285 **
   51286 ** If the database is not empty and the *-wal file exists, open the pager
   51287 ** in WAL mode.  If the database is empty or if no *-wal file exists and
   51288 ** if no error occurs, make sure Pager.journalMode is not set to
   51289 ** PAGER_JOURNALMODE_WAL.
   51290 **
   51291 ** Return SQLITE_OK or an error code.
   51292 **
   51293 ** The caller must hold a SHARED lock on the database file to call this
   51294 ** function. Because an EXCLUSIVE lock on the db file is required to delete
   51295 ** a WAL on a none-empty database, this ensures there is no race condition
   51296 ** between the xAccess() below and an xDelete() being executed by some
   51297 ** other connection.
   51298 */
   51299 static int pagerOpenWalIfPresent(Pager *pPager){
   51300   int rc = SQLITE_OK;
   51301   assert( pPager->eState==PAGER_OPEN );
   51302   assert( pPager->eLock>=SHARED_LOCK );
   51303 
   51304   if( !pPager->tempFile ){
   51305     int isWal;                    /* True if WAL file exists */
   51306     rc = sqlite3OsAccess(
   51307         pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
   51308     );
   51309     if( rc==SQLITE_OK ){
   51310       if( isWal ){
   51311         Pgno nPage;                   /* Size of the database file */
   51312 
   51313         rc = pagerPagecount(pPager, &nPage);
   51314         if( rc ) return rc;
   51315         if( nPage==0 ){
   51316           rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
   51317         }else{
   51318           testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
   51319           rc = sqlite3PagerOpenWal(pPager, 0);
   51320         }
   51321       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
   51322         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
   51323       }
   51324     }
   51325   }
   51326   return rc;
   51327 }
   51328 #endif
   51329 
   51330 /*
   51331 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
   51332 ** the entire master journal file. The case pSavepoint==NULL occurs when
   51333 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
   51334 ** savepoint.
   51335 **
   51336 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
   51337 ** being rolled back), then the rollback consists of up to three stages,
   51338 ** performed in the order specified:
   51339 **
   51340 **   * Pages are played back from the main journal starting at byte
   51341 **     offset PagerSavepoint.iOffset and continuing to
   51342 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
   51343 **     file if PagerSavepoint.iHdrOffset is zero.
   51344 **
   51345 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
   51346 **     back starting from the journal header immediately following
   51347 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
   51348 **
   51349 **   * Pages are then played back from the sub-journal file, starting
   51350 **     with the PagerSavepoint.iSubRec and continuing to the end of
   51351 **     the journal file.
   51352 **
   51353 ** Throughout the rollback process, each time a page is rolled back, the
   51354 ** corresponding bit is set in a bitvec structure (variable pDone in the
   51355 ** implementation below). This is used to ensure that a page is only
   51356 ** rolled back the first time it is encountered in either journal.
   51357 **
   51358 ** If pSavepoint is NULL, then pages are only played back from the main
   51359 ** journal file. There is no need for a bitvec in this case.
   51360 **
   51361 ** In either case, before playback commences the Pager.dbSize variable
   51362 ** is reset to the value that it held at the start of the savepoint
   51363 ** (or transaction). No page with a page-number greater than this value
   51364 ** is played back. If one is encountered it is simply skipped.
   51365 */
   51366 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   51367   i64 szJ;                 /* Effective size of the main journal */
   51368   i64 iHdrOff;             /* End of first segment of main-journal records */
   51369   int rc = SQLITE_OK;      /* Return code */
   51370   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
   51371 
   51372   assert( pPager->eState!=PAGER_ERROR );
   51373   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   51374 
   51375   /* Allocate a bitvec to use to store the set of pages rolled back */
   51376   if( pSavepoint ){
   51377     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
   51378     if( !pDone ){
   51379       return SQLITE_NOMEM_BKPT;
   51380     }
   51381   }
   51382 
   51383   /* Set the database size back to the value it was before the savepoint
   51384   ** being reverted was opened.
   51385   */
   51386   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
   51387   pPager->changeCountDone = pPager->tempFile;
   51388 
   51389   if( !pSavepoint && pagerUseWal(pPager) ){
   51390     return pagerRollbackWal(pPager);
   51391   }
   51392 
   51393   /* Use pPager->journalOff as the effective size of the main rollback
   51394   ** journal.  The actual file might be larger than this in
   51395   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
   51396   ** past pPager->journalOff is off-limits to us.
   51397   */
   51398   szJ = pPager->journalOff;
   51399   assert( pagerUseWal(pPager)==0 || szJ==0 );
   51400 
   51401   /* Begin by rolling back records from the main journal starting at
   51402   ** PagerSavepoint.iOffset and continuing to the next journal header.
   51403   ** There might be records in the main journal that have a page number
   51404   ** greater than the current database size (pPager->dbSize) but those
   51405   ** will be skipped automatically.  Pages are added to pDone as they
   51406   ** are played back.
   51407   */
   51408   if( pSavepoint && !pagerUseWal(pPager) ){
   51409     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
   51410     pPager->journalOff = pSavepoint->iOffset;
   51411     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
   51412       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   51413     }
   51414     assert( rc!=SQLITE_DONE );
   51415   }else{
   51416     pPager->journalOff = 0;
   51417   }
   51418 
   51419   /* Continue rolling back records out of the main journal starting at
   51420   ** the first journal header seen and continuing until the effective end
   51421   ** of the main journal file.  Continue to skip out-of-range pages and
   51422   ** continue adding pages rolled back to pDone.
   51423   */
   51424   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
   51425     u32 ii;            /* Loop counter */
   51426     u32 nJRec = 0;     /* Number of Journal Records */
   51427     u32 dummy;
   51428     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
   51429     assert( rc!=SQLITE_DONE );
   51430 
   51431     /*
   51432     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
   51433     ** test is related to ticket #2565.  See the discussion in the
   51434     ** pager_playback() function for additional information.
   51435     */
   51436     if( nJRec==0
   51437      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
   51438     ){
   51439       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
   51440     }
   51441     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
   51442       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   51443     }
   51444     assert( rc!=SQLITE_DONE );
   51445   }
   51446   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
   51447 
   51448   /* Finally,  rollback pages from the sub-journal.  Page that were
   51449   ** previously rolled back out of the main journal (and are hence in pDone)
   51450   ** will be skipped.  Out-of-range pages are also skipped.
   51451   */
   51452   if( pSavepoint ){
   51453     u32 ii;            /* Loop counter */
   51454     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
   51455 
   51456     if( pagerUseWal(pPager) ){
   51457       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
   51458     }
   51459     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
   51460       assert( offset==(i64)ii*(4+pPager->pageSize) );
   51461       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
   51462     }
   51463     assert( rc!=SQLITE_DONE );
   51464   }
   51465 
   51466   sqlite3BitvecDestroy(pDone);
   51467   if( rc==SQLITE_OK ){
   51468     pPager->journalOff = szJ;
   51469   }
   51470 
   51471   return rc;
   51472 }
   51473 
   51474 /*
   51475 ** Change the maximum number of in-memory pages that are allowed
   51476 ** before attempting to recycle clean and unused pages.
   51477 */
   51478 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
   51479   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
   51480 }
   51481 
   51482 /*
   51483 ** Change the maximum number of in-memory pages that are allowed
   51484 ** before attempting to spill pages to journal.
   51485 */
   51486 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
   51487   return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
   51488 }
   51489 
   51490 /*
   51491 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
   51492 */
   51493 static void pagerFixMaplimit(Pager *pPager){
   51494 #if SQLITE_MAX_MMAP_SIZE>0
   51495   sqlite3_file *fd = pPager->fd;
   51496   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
   51497     sqlite3_int64 sz;
   51498     sz = pPager->szMmap;
   51499     pPager->bUseFetch = (sz>0);
   51500     setGetterMethod(pPager);
   51501     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
   51502   }
   51503 #endif
   51504 }
   51505 
   51506 /*
   51507 ** Change the maximum size of any memory mapping made of the database file.
   51508 */
   51509 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
   51510   pPager->szMmap = szMmap;
   51511   pagerFixMaplimit(pPager);
   51512 }
   51513 
   51514 /*
   51515 ** Free as much memory as possible from the pager.
   51516 */
   51517 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
   51518   sqlite3PcacheShrink(pPager->pPCache);
   51519 }
   51520 
   51521 /*
   51522 ** Adjust settings of the pager to those specified in the pgFlags parameter.
   51523 **
   51524 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
   51525 ** of the database to damage due to OS crashes or power failures by
   51526 ** changing the number of syncs()s when writing the journals.
   51527 ** There are four levels:
   51528 **
   51529 **    OFF       sqlite3OsSync() is never called.  This is the default
   51530 **              for temporary and transient files.
   51531 **
   51532 **    NORMAL    The journal is synced once before writes begin on the
   51533 **              database.  This is normally adequate protection, but
   51534 **              it is theoretically possible, though very unlikely,
   51535 **              that an inopertune power failure could leave the journal
   51536 **              in a state which would cause damage to the database
   51537 **              when it is rolled back.
   51538 **
   51539 **    FULL      The journal is synced twice before writes begin on the
   51540 **              database (with some additional information - the nRec field
   51541 **              of the journal header - being written in between the two
   51542 **              syncs).  If we assume that writing a
   51543 **              single disk sector is atomic, then this mode provides
   51544 **              assurance that the journal will not be corrupted to the
   51545 **              point of causing damage to the database during rollback.
   51546 **
   51547 **    EXTRA     This is like FULL except that is also syncs the directory
   51548 **              that contains the rollback journal after the rollback
   51549 **              journal is unlinked.
   51550 **
   51551 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
   51552 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
   51553 ** prior to the start of checkpoint and that the database file is synced
   51554 ** at the conclusion of the checkpoint if the entire content of the WAL
   51555 ** was written back into the database.  But no sync operations occur for
   51556 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
   51557 ** file is synced following each commit operation, in addition to the
   51558 ** syncs associated with NORMAL.  There is no difference between FULL
   51559 ** and EXTRA for WAL mode.
   51560 **
   51561 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
   51562 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
   51563 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
   51564 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
   51565 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
   51566 ** synchronous=FULL versus synchronous=NORMAL setting determines when
   51567 ** the xSync primitive is called and is relevant to all platforms.
   51568 **
   51569 ** Numeric values associated with these states are OFF==1, NORMAL=2,
   51570 ** and FULL=3.
   51571 */
   51572 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   51573 SQLITE_PRIVATE void sqlite3PagerSetFlags(
   51574   Pager *pPager,        /* The pager to set safety level for */
   51575   unsigned pgFlags      /* Various flags */
   51576 ){
   51577   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
   51578   if( pPager->tempFile ){
   51579     pPager->noSync = 1;
   51580     pPager->fullSync = 0;
   51581     pPager->extraSync = 0;
   51582   }else{
   51583     pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
   51584     pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
   51585     pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
   51586   }
   51587   if( pPager->noSync ){
   51588     pPager->syncFlags = 0;
   51589   }else if( pgFlags & PAGER_FULLFSYNC ){
   51590     pPager->syncFlags = SQLITE_SYNC_FULL;
   51591   }else{
   51592     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   51593   }
   51594   pPager->walSyncFlags = (pPager->syncFlags<<2);
   51595   if( pPager->fullSync ){
   51596     pPager->walSyncFlags |= pPager->syncFlags;
   51597   }
   51598   if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
   51599     pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
   51600   }
   51601   if( pgFlags & PAGER_CACHESPILL ){
   51602     pPager->doNotSpill &= ~SPILLFLAG_OFF;
   51603   }else{
   51604     pPager->doNotSpill |= SPILLFLAG_OFF;
   51605   }
   51606 }
   51607 #endif
   51608 
   51609 /*
   51610 ** The following global variable is incremented whenever the library
   51611 ** attempts to open a temporary file.  This information is used for
   51612 ** testing and analysis only.
   51613 */
   51614 #ifdef SQLITE_TEST
   51615 SQLITE_API int sqlite3_opentemp_count = 0;
   51616 #endif
   51617 
   51618 /*
   51619 ** Open a temporary file.
   51620 **
   51621 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
   51622 ** or some other error code if we fail. The OS will automatically
   51623 ** delete the temporary file when it is closed.
   51624 **
   51625 ** The flags passed to the VFS layer xOpen() call are those specified
   51626 ** by parameter vfsFlags ORed with the following:
   51627 **
   51628 **     SQLITE_OPEN_READWRITE
   51629 **     SQLITE_OPEN_CREATE
   51630 **     SQLITE_OPEN_EXCLUSIVE
   51631 **     SQLITE_OPEN_DELETEONCLOSE
   51632 */
   51633 static int pagerOpentemp(
   51634   Pager *pPager,        /* The pager object */
   51635   sqlite3_file *pFile,  /* Write the file descriptor here */
   51636   int vfsFlags          /* Flags passed through to the VFS */
   51637 ){
   51638   int rc;               /* Return code */
   51639 
   51640 #ifdef SQLITE_TEST
   51641   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
   51642 #endif
   51643 
   51644   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   51645             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   51646   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
   51647   assert( rc!=SQLITE_OK || isOpen(pFile) );
   51648   return rc;
   51649 }
   51650 
   51651 /*
   51652 ** Set the busy handler function.
   51653 **
   51654 ** The pager invokes the busy-handler if sqlite3OsLock() returns
   51655 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
   51656 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
   51657 ** lock. It does *not* invoke the busy handler when upgrading from
   51658 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
   51659 ** (which occurs during hot-journal rollback). Summary:
   51660 **
   51661 **   Transition                        | Invokes xBusyHandler
   51662 **   --------------------------------------------------------
   51663 **   NO_LOCK       -> SHARED_LOCK      | Yes
   51664 **   SHARED_LOCK   -> RESERVED_LOCK    | No
   51665 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
   51666 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
   51667 **
   51668 ** If the busy-handler callback returns non-zero, the lock is
   51669 ** retried. If it returns zero, then the SQLITE_BUSY error is
   51670 ** returned to the caller of the pager API function.
   51671 */
   51672 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
   51673   Pager *pPager,                       /* Pager object */
   51674   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
   51675   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
   51676 ){
   51677   pPager->xBusyHandler = xBusyHandler;
   51678   pPager->pBusyHandlerArg = pBusyHandlerArg;
   51679 
   51680   if( isOpen(pPager->fd) ){
   51681     void **ap = (void **)&pPager->xBusyHandler;
   51682     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
   51683     assert( ap[1]==pBusyHandlerArg );
   51684     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
   51685   }
   51686 }
   51687 
   51688 /*
   51689 ** Change the page size used by the Pager object. The new page size
   51690 ** is passed in *pPageSize.
   51691 **
   51692 ** If the pager is in the error state when this function is called, it
   51693 ** is a no-op. The value returned is the error state error code (i.e.
   51694 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
   51695 **
   51696 ** Otherwise, if all of the following are true:
   51697 **
   51698 **   * the new page size (value of *pPageSize) is valid (a power
   51699 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
   51700 **
   51701 **   * there are no outstanding page references, and
   51702 **
   51703 **   * the database is either not an in-memory database or it is
   51704 **     an in-memory database that currently consists of zero pages.
   51705 **
   51706 ** then the pager object page size is set to *pPageSize.
   51707 **
   51708 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
   51709 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
   51710 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
   51711 ** In all other cases, SQLITE_OK is returned.
   51712 **
   51713 ** If the page size is not changed, either because one of the enumerated
   51714 ** conditions above is not true, the pager was in error state when this
   51715 ** function was called, or because the memory allocation attempt failed,
   51716 ** then *pPageSize is set to the old, retained page size before returning.
   51717 */
   51718 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
   51719   int rc = SQLITE_OK;
   51720 
   51721   /* It is not possible to do a full assert_pager_state() here, as this
   51722   ** function may be called from within PagerOpen(), before the state
   51723   ** of the Pager object is internally consistent.
   51724   **
   51725   ** At one point this function returned an error if the pager was in
   51726   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
   51727   ** there is at least one outstanding page reference, this function
   51728   ** is a no-op for that case anyhow.
   51729   */
   51730 
   51731   u32 pageSize = *pPageSize;
   51732   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   51733   if( (pPager->memDb==0 || pPager->dbSize==0)
   51734    && sqlite3PcacheRefCount(pPager->pPCache)==0
   51735    && pageSize && pageSize!=(u32)pPager->pageSize
   51736   ){
   51737     char *pNew = NULL;             /* New temp space */
   51738     i64 nByte = 0;
   51739 
   51740     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
   51741       rc = sqlite3OsFileSize(pPager->fd, &nByte);
   51742     }
   51743     if( rc==SQLITE_OK ){
   51744       pNew = (char *)sqlite3PageMalloc(pageSize);
   51745       if( !pNew ) rc = SQLITE_NOMEM_BKPT;
   51746     }
   51747 
   51748     if( rc==SQLITE_OK ){
   51749       pager_reset(pPager);
   51750       rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
   51751     }
   51752     if( rc==SQLITE_OK ){
   51753       sqlite3PageFree(pPager->pTmpSpace);
   51754       pPager->pTmpSpace = pNew;
   51755       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
   51756       pPager->pageSize = pageSize;
   51757     }else{
   51758       sqlite3PageFree(pNew);
   51759     }
   51760   }
   51761 
   51762   *pPageSize = pPager->pageSize;
   51763   if( rc==SQLITE_OK ){
   51764     if( nReserve<0 ) nReserve = pPager->nReserve;
   51765     assert( nReserve>=0 && nReserve<1000 );
   51766     pPager->nReserve = (i16)nReserve;
   51767     pagerReportSize(pPager);
   51768     pagerFixMaplimit(pPager);
   51769   }
   51770   return rc;
   51771 }
   51772 
   51773 /*
   51774 ** Return a pointer to the "temporary page" buffer held internally
   51775 ** by the pager.  This is a buffer that is big enough to hold the
   51776 ** entire content of a database page.  This buffer is used internally
   51777 ** during rollback and will be overwritten whenever a rollback
   51778 ** occurs.  But other modules are free to use it too, as long as
   51779 ** no rollbacks are happening.
   51780 */
   51781 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
   51782   return pPager->pTmpSpace;
   51783 }
   51784 
   51785 /*
   51786 ** Attempt to set the maximum database page count if mxPage is positive.
   51787 ** Make no changes if mxPage is zero or negative.  And never reduce the
   51788 ** maximum page count below the current size of the database.
   51789 **
   51790 ** Regardless of mxPage, return the current maximum page count.
   51791 */
   51792 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
   51793   if( mxPage>0 ){
   51794     pPager->mxPgno = mxPage;
   51795   }
   51796   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
   51797   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
   51798   return pPager->mxPgno;
   51799 }
   51800 
   51801 /*
   51802 ** The following set of routines are used to disable the simulated
   51803 ** I/O error mechanism.  These routines are used to avoid simulated
   51804 ** errors in places where we do not care about errors.
   51805 **
   51806 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
   51807 ** and generate no code.
   51808 */
   51809 #ifdef SQLITE_TEST
   51810 SQLITE_API extern int sqlite3_io_error_pending;
   51811 SQLITE_API extern int sqlite3_io_error_hit;
   51812 static int saved_cnt;
   51813 void disable_simulated_io_errors(void){
   51814   saved_cnt = sqlite3_io_error_pending;
   51815   sqlite3_io_error_pending = -1;
   51816 }
   51817 void enable_simulated_io_errors(void){
   51818   sqlite3_io_error_pending = saved_cnt;
   51819 }
   51820 #else
   51821 # define disable_simulated_io_errors()
   51822 # define enable_simulated_io_errors()
   51823 #endif
   51824 
   51825 /*
   51826 ** Read the first N bytes from the beginning of the file into memory
   51827 ** that pDest points to.
   51828 **
   51829 ** If the pager was opened on a transient file (zFilename==""), or
   51830 ** opened on a file less than N bytes in size, the output buffer is
   51831 ** zeroed and SQLITE_OK returned. The rationale for this is that this
   51832 ** function is used to read database headers, and a new transient or
   51833 ** zero sized database has a header than consists entirely of zeroes.
   51834 **
   51835 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
   51836 ** the error code is returned to the caller and the contents of the
   51837 ** output buffer undefined.
   51838 */
   51839 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
   51840   int rc = SQLITE_OK;
   51841   memset(pDest, 0, N);
   51842   assert( isOpen(pPager->fd) || pPager->tempFile );
   51843 
   51844   /* This routine is only called by btree immediately after creating
   51845   ** the Pager object.  There has not been an opportunity to transition
   51846   ** to WAL mode yet.
   51847   */
   51848   assert( !pagerUseWal(pPager) );
   51849 
   51850   if( isOpen(pPager->fd) ){
   51851     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
   51852     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
   51853     if( rc==SQLITE_IOERR_SHORT_READ ){
   51854       rc = SQLITE_OK;
   51855     }
   51856   }
   51857   return rc;
   51858 }
   51859 
   51860 /*
   51861 ** This function may only be called when a read-transaction is open on
   51862 ** the pager. It returns the total number of pages in the database.
   51863 **
   51864 ** However, if the file is between 1 and <page-size> bytes in size, then
   51865 ** this is considered a 1 page file.
   51866 */
   51867 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
   51868   assert( pPager->eState>=PAGER_READER );
   51869   assert( pPager->eState!=PAGER_WRITER_FINISHED );
   51870   *pnPage = (int)pPager->dbSize;
   51871 }
   51872 
   51873 
   51874 /*
   51875 ** Try to obtain a lock of type locktype on the database file. If
   51876 ** a similar or greater lock is already held, this function is a no-op
   51877 ** (returning SQLITE_OK immediately).
   51878 **
   51879 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
   51880 ** the busy callback if the lock is currently not available. Repeat
   51881 ** until the busy callback returns false or until the attempt to
   51882 ** obtain the lock succeeds.
   51883 **
   51884 ** Return SQLITE_OK on success and an error code if we cannot obtain
   51885 ** the lock. If the lock is obtained successfully, set the Pager.state
   51886 ** variable to locktype before returning.
   51887 */
   51888 static int pager_wait_on_lock(Pager *pPager, int locktype){
   51889   int rc;                              /* Return code */
   51890 
   51891   /* Check that this is either a no-op (because the requested lock is
   51892   ** already held), or one of the transitions that the busy-handler
   51893   ** may be invoked during, according to the comment above
   51894   ** sqlite3PagerSetBusyhandler().
   51895   */
   51896   assert( (pPager->eLock>=locktype)
   51897        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
   51898        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
   51899   );
   51900 
   51901   do {
   51902     rc = pagerLockDb(pPager, locktype);
   51903   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
   51904   return rc;
   51905 }
   51906 
   51907 /*
   51908 ** Function assertTruncateConstraint(pPager) checks that one of the
   51909 ** following is true for all dirty pages currently in the page-cache:
   51910 **
   51911 **   a) The page number is less than or equal to the size of the
   51912 **      current database image, in pages, OR
   51913 **
   51914 **   b) if the page content were written at this time, it would not
   51915 **      be necessary to write the current content out to the sub-journal
   51916 **      (as determined by function subjRequiresPage()).
   51917 **
   51918 ** If the condition asserted by this function were not true, and the
   51919 ** dirty page were to be discarded from the cache via the pagerStress()
   51920 ** routine, pagerStress() would not write the current page content to
   51921 ** the database file. If a savepoint transaction were rolled back after
   51922 ** this happened, the correct behavior would be to restore the current
   51923 ** content of the page. However, since this content is not present in either
   51924 ** the database file or the portion of the rollback journal and
   51925 ** sub-journal rolled back the content could not be restored and the
   51926 ** database image would become corrupt. It is therefore fortunate that
   51927 ** this circumstance cannot arise.
   51928 */
   51929 #if defined(SQLITE_DEBUG)
   51930 static void assertTruncateConstraintCb(PgHdr *pPg){
   51931   assert( pPg->flags&PGHDR_DIRTY );
   51932   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
   51933 }
   51934 static void assertTruncateConstraint(Pager *pPager){
   51935   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
   51936 }
   51937 #else
   51938 # define assertTruncateConstraint(pPager)
   51939 #endif
   51940 
   51941 /*
   51942 ** Truncate the in-memory database file image to nPage pages. This
   51943 ** function does not actually modify the database file on disk. It
   51944 ** just sets the internal state of the pager object so that the
   51945 ** truncation will be done when the current transaction is committed.
   51946 **
   51947 ** This function is only called right before committing a transaction.
   51948 ** Once this function has been called, the transaction must either be
   51949 ** rolled back or committed. It is not safe to call this function and
   51950 ** then continue writing to the database.
   51951 */
   51952 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
   51953   assert( pPager->dbSize>=nPage );
   51954   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   51955   pPager->dbSize = nPage;
   51956 
   51957   /* At one point the code here called assertTruncateConstraint() to
   51958   ** ensure that all pages being truncated away by this operation are,
   51959   ** if one or more savepoints are open, present in the savepoint
   51960   ** journal so that they can be restored if the savepoint is rolled
   51961   ** back. This is no longer necessary as this function is now only
   51962   ** called right before committing a transaction. So although the
   51963   ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
   51964   ** they cannot be rolled back. So the assertTruncateConstraint() call
   51965   ** is no longer correct. */
   51966 }
   51967 
   51968 
   51969 /*
   51970 ** This function is called before attempting a hot-journal rollback. It
   51971 ** syncs the journal file to disk, then sets pPager->journalHdr to the
   51972 ** size of the journal file so that the pager_playback() routine knows
   51973 ** that the entire journal file has been synced.
   51974 **
   51975 ** Syncing a hot-journal to disk before attempting to roll it back ensures
   51976 ** that if a power-failure occurs during the rollback, the process that
   51977 ** attempts rollback following system recovery sees the same journal
   51978 ** content as this process.
   51979 **
   51980 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
   51981 ** an SQLite error code.
   51982 */
   51983 static int pagerSyncHotJournal(Pager *pPager){
   51984   int rc = SQLITE_OK;
   51985   if( !pPager->noSync ){
   51986     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
   51987   }
   51988   if( rc==SQLITE_OK ){
   51989     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
   51990   }
   51991   return rc;
   51992 }
   51993 
   51994 #if SQLITE_MAX_MMAP_SIZE>0
   51995 /*
   51996 ** Obtain a reference to a memory mapped page object for page number pgno.
   51997 ** The new object will use the pointer pData, obtained from xFetch().
   51998 ** If successful, set *ppPage to point to the new page reference
   51999 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
   52000 ** *ppPage to zero.
   52001 **
   52002 ** Page references obtained by calling this function should be released
   52003 ** by calling pagerReleaseMapPage().
   52004 */
   52005 static int pagerAcquireMapPage(
   52006   Pager *pPager,                  /* Pager object */
   52007   Pgno pgno,                      /* Page number */
   52008   void *pData,                    /* xFetch()'d data for this page */
   52009   PgHdr **ppPage                  /* OUT: Acquired page object */
   52010 ){
   52011   PgHdr *p;                       /* Memory mapped page to return */
   52012 
   52013   if( pPager->pMmapFreelist ){
   52014     *ppPage = p = pPager->pMmapFreelist;
   52015     pPager->pMmapFreelist = p->pDirty;
   52016     p->pDirty = 0;
   52017     assert( pPager->nExtra>=8 );
   52018     memset(p->pExtra, 0, 8);
   52019   }else{
   52020     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
   52021     if( p==0 ){
   52022       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
   52023       return SQLITE_NOMEM_BKPT;
   52024     }
   52025     p->pExtra = (void *)&p[1];
   52026     p->flags = PGHDR_MMAP;
   52027     p->nRef = 1;
   52028     p->pPager = pPager;
   52029   }
   52030 
   52031   assert( p->pExtra==(void *)&p[1] );
   52032   assert( p->pPage==0 );
   52033   assert( p->flags==PGHDR_MMAP );
   52034   assert( p->pPager==pPager );
   52035   assert( p->nRef==1 );
   52036 
   52037   p->pgno = pgno;
   52038   p->pData = pData;
   52039   pPager->nMmapOut++;
   52040 
   52041   return SQLITE_OK;
   52042 }
   52043 #endif
   52044 
   52045 /*
   52046 ** Release a reference to page pPg. pPg must have been returned by an
   52047 ** earlier call to pagerAcquireMapPage().
   52048 */
   52049 static void pagerReleaseMapPage(PgHdr *pPg){
   52050   Pager *pPager = pPg->pPager;
   52051   pPager->nMmapOut--;
   52052   pPg->pDirty = pPager->pMmapFreelist;
   52053   pPager->pMmapFreelist = pPg;
   52054 
   52055   assert( pPager->fd->pMethods->iVersion>=3 );
   52056   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
   52057 }
   52058 
   52059 /*
   52060 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
   52061 */
   52062 static void pagerFreeMapHdrs(Pager *pPager){
   52063   PgHdr *p;
   52064   PgHdr *pNext;
   52065   for(p=pPager->pMmapFreelist; p; p=pNext){
   52066     pNext = p->pDirty;
   52067     sqlite3_free(p);
   52068   }
   52069 }
   52070 
   52071 
   52072 /*
   52073 ** Shutdown the page cache.  Free all memory and close all files.
   52074 **
   52075 ** If a transaction was in progress when this routine is called, that
   52076 ** transaction is rolled back.  All outstanding pages are invalidated
   52077 ** and their memory is freed.  Any attempt to use a page associated
   52078 ** with this page cache after this function returns will likely
   52079 ** result in a coredump.
   52080 **
   52081 ** This function always succeeds. If a transaction is active an attempt
   52082 ** is made to roll it back. If an error occurs during the rollback
   52083 ** a hot journal may be left in the filesystem but no error is returned
   52084 ** to the caller.
   52085 */
   52086 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
   52087   u8 *pTmp = (u8 *)pPager->pTmpSpace;
   52088 
   52089   assert( db || pagerUseWal(pPager)==0 );
   52090   assert( assert_pager_state(pPager) );
   52091   disable_simulated_io_errors();
   52092   sqlite3BeginBenignMalloc();
   52093   pagerFreeMapHdrs(pPager);
   52094   /* pPager->errCode = 0; */
   52095   pPager->exclusiveMode = 0;
   52096 #ifndef SQLITE_OMIT_WAL
   52097   assert( db || pPager->pWal==0 );
   52098   sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,
   52099       (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
   52100   );
   52101   pPager->pWal = 0;
   52102 #endif
   52103   pager_reset(pPager);
   52104   if( MEMDB ){
   52105     pager_unlock(pPager);
   52106   }else{
   52107     /* If it is open, sync the journal file before calling UnlockAndRollback.
   52108     ** If this is not done, then an unsynced portion of the open journal
   52109     ** file may be played back into the database. If a power failure occurs
   52110     ** while this is happening, the database could become corrupt.
   52111     **
   52112     ** If an error occurs while trying to sync the journal, shift the pager
   52113     ** into the ERROR state. This causes UnlockAndRollback to unlock the
   52114     ** database and close the journal file without attempting to roll it
   52115     ** back or finalize it. The next database user will have to do hot-journal
   52116     ** rollback before accessing the database file.
   52117     */
   52118     if( isOpen(pPager->jfd) ){
   52119       pager_error(pPager, pagerSyncHotJournal(pPager));
   52120     }
   52121     pagerUnlockAndRollback(pPager);
   52122   }
   52123   sqlite3EndBenignMalloc();
   52124   enable_simulated_io_errors();
   52125   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
   52126   IOTRACE(("CLOSE %p\n", pPager))
   52127   sqlite3OsClose(pPager->jfd);
   52128   sqlite3OsClose(pPager->fd);
   52129   sqlite3PageFree(pTmp);
   52130   sqlite3PcacheClose(pPager->pPCache);
   52131 
   52132 #ifdef SQLITE_HAS_CODEC
   52133   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   52134 #endif
   52135 
   52136   assert( !pPager->aSavepoint && !pPager->pInJournal );
   52137   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
   52138 
   52139   sqlite3_free(pPager);
   52140   return SQLITE_OK;
   52141 }
   52142 
   52143 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   52144 /*
   52145 ** Return the page number for page pPg.
   52146 */
   52147 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
   52148   return pPg->pgno;
   52149 }
   52150 #endif
   52151 
   52152 /*
   52153 ** Increment the reference count for page pPg.
   52154 */
   52155 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
   52156   sqlite3PcacheRef(pPg);
   52157 }
   52158 
   52159 /*
   52160 ** Sync the journal. In other words, make sure all the pages that have
   52161 ** been written to the journal have actually reached the surface of the
   52162 ** disk and can be restored in the event of a hot-journal rollback.
   52163 **
   52164 ** If the Pager.noSync flag is set, then this function is a no-op.
   52165 ** Otherwise, the actions required depend on the journal-mode and the
   52166 ** device characteristics of the file-system, as follows:
   52167 **
   52168 **   * If the journal file is an in-memory journal file, no action need
   52169 **     be taken.
   52170 **
   52171 **   * Otherwise, if the device does not support the SAFE_APPEND property,
   52172 **     then the nRec field of the most recently written journal header
   52173 **     is updated to contain the number of journal records that have
   52174 **     been written following it. If the pager is operating in full-sync
   52175 **     mode, then the journal file is synced before this field is updated.
   52176 **
   52177 **   * If the device does not support the SEQUENTIAL property, then
   52178 **     journal file is synced.
   52179 **
   52180 ** Or, in pseudo-code:
   52181 **
   52182 **   if( NOT <in-memory journal> ){
   52183 **     if( NOT SAFE_APPEND ){
   52184 **       if( <full-sync mode> ) xSync(<journal file>);
   52185 **       <update nRec field>
   52186 **     }
   52187 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
   52188 **   }
   52189 **
   52190 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
   52191 ** page currently held in memory before returning SQLITE_OK. If an IO
   52192 ** error is encountered, then the IO error code is returned to the caller.
   52193 */
   52194 static int syncJournal(Pager *pPager, int newHdr){
   52195   int rc;                         /* Return code */
   52196 
   52197   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   52198        || pPager->eState==PAGER_WRITER_DBMOD
   52199   );
   52200   assert( assert_pager_state(pPager) );
   52201   assert( !pagerUseWal(pPager) );
   52202 
   52203   rc = sqlite3PagerExclusiveLock(pPager);
   52204   if( rc!=SQLITE_OK ) return rc;
   52205 
   52206   if( !pPager->noSync ){
   52207     assert( !pPager->tempFile );
   52208     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
   52209       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   52210       assert( isOpen(pPager->jfd) );
   52211 
   52212       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   52213         /* This block deals with an obscure problem. If the last connection
   52214         ** that wrote to this database was operating in persistent-journal
   52215         ** mode, then the journal file may at this point actually be larger
   52216         ** than Pager.journalOff bytes. If the next thing in the journal
   52217         ** file happens to be a journal-header (written as part of the
   52218         ** previous connection's transaction), and a crash or power-failure
   52219         ** occurs after nRec is updated but before this connection writes
   52220         ** anything else to the journal file (or commits/rolls back its
   52221         ** transaction), then SQLite may become confused when doing the
   52222         ** hot-journal rollback following recovery. It may roll back all
   52223         ** of this connections data, then proceed to rolling back the old,
   52224         ** out-of-date data that follows it. Database corruption.
   52225         **
   52226         ** To work around this, if the journal file does appear to contain
   52227         ** a valid header following Pager.journalOff, then write a 0x00
   52228         ** byte to the start of it to prevent it from being recognized.
   52229         **
   52230         ** Variable iNextHdrOffset is set to the offset at which this
   52231         ** problematic header will occur, if it exists. aMagic is used
   52232         ** as a temporary buffer to inspect the first couple of bytes of
   52233         ** the potential journal header.
   52234         */
   52235         i64 iNextHdrOffset;
   52236         u8 aMagic[8];
   52237         u8 zHeader[sizeof(aJournalMagic)+4];
   52238 
   52239         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   52240         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
   52241 
   52242         iNextHdrOffset = journalHdrOffset(pPager);
   52243         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
   52244         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
   52245           static const u8 zerobyte = 0;
   52246           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
   52247         }
   52248         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   52249           return rc;
   52250         }
   52251 
   52252         /* Write the nRec value into the journal file header. If in
   52253         ** full-synchronous mode, sync the journal first. This ensures that
   52254         ** all data has really hit the disk before nRec is updated to mark
   52255         ** it as a candidate for rollback.
   52256         **
   52257         ** This is not required if the persistent media supports the
   52258         ** SAFE_APPEND property. Because in this case it is not possible
   52259         ** for garbage data to be appended to the file, the nRec field
   52260         ** is populated with 0xFFFFFFFF when the journal header is written
   52261         ** and never needs to be updated.
   52262         */
   52263         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   52264           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   52265           IOTRACE(("JSYNC %p\n", pPager))
   52266           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
   52267           if( rc!=SQLITE_OK ) return rc;
   52268         }
   52269         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
   52270         rc = sqlite3OsWrite(
   52271             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
   52272         );
   52273         if( rc!=SQLITE_OK ) return rc;
   52274       }
   52275       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   52276         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   52277         IOTRACE(("JSYNC %p\n", pPager))
   52278         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
   52279           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
   52280         );
   52281         if( rc!=SQLITE_OK ) return rc;
   52282       }
   52283 
   52284       pPager->journalHdr = pPager->journalOff;
   52285       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   52286         pPager->nRec = 0;
   52287         rc = writeJournalHdr(pPager);
   52288         if( rc!=SQLITE_OK ) return rc;
   52289       }
   52290     }else{
   52291       pPager->journalHdr = pPager->journalOff;
   52292     }
   52293   }
   52294 
   52295   /* Unless the pager is in noSync mode, the journal file was just
   52296   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
   52297   ** all pages.
   52298   */
   52299   sqlite3PcacheClearSyncFlags(pPager->pPCache);
   52300   pPager->eState = PAGER_WRITER_DBMOD;
   52301   assert( assert_pager_state(pPager) );
   52302   return SQLITE_OK;
   52303 }
   52304 
   52305 /*
   52306 ** The argument is the first in a linked list of dirty pages connected
   52307 ** by the PgHdr.pDirty pointer. This function writes each one of the
   52308 ** in-memory pages in the list to the database file. The argument may
   52309 ** be NULL, representing an empty list. In this case this function is
   52310 ** a no-op.
   52311 **
   52312 ** The pager must hold at least a RESERVED lock when this function
   52313 ** is called. Before writing anything to the database file, this lock
   52314 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
   52315 ** SQLITE_BUSY is returned and no data is written to the database file.
   52316 **
   52317 ** If the pager is a temp-file pager and the actual file-system file
   52318 ** is not yet open, it is created and opened before any data is
   52319 ** written out.
   52320 **
   52321 ** Once the lock has been upgraded and, if necessary, the file opened,
   52322 ** the pages are written out to the database file in list order. Writing
   52323 ** a page is skipped if it meets either of the following criteria:
   52324 **
   52325 **   * The page number is greater than Pager.dbSize, or
   52326 **   * The PGHDR_DONT_WRITE flag is set on the page.
   52327 **
   52328 ** If writing out a page causes the database file to grow, Pager.dbFileSize
   52329 ** is updated accordingly. If page 1 is written out, then the value cached
   52330 ** in Pager.dbFileVers[] is updated to match the new value stored in
   52331 ** the database file.
   52332 **
   52333 ** If everything is successful, SQLITE_OK is returned. If an IO error
   52334 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
   52335 ** be obtained, SQLITE_BUSY is returned.
   52336 */
   52337 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
   52338   int rc = SQLITE_OK;                  /* Return code */
   52339 
   52340   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
   52341   assert( !pagerUseWal(pPager) );
   52342   assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
   52343   assert( pPager->eLock==EXCLUSIVE_LOCK );
   52344   assert( isOpen(pPager->fd) || pList->pDirty==0 );
   52345 
   52346   /* If the file is a temp-file has not yet been opened, open it now. It
   52347   ** is not possible for rc to be other than SQLITE_OK if this branch
   52348   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
   52349   */
   52350   if( !isOpen(pPager->fd) ){
   52351     assert( pPager->tempFile && rc==SQLITE_OK );
   52352     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
   52353   }
   52354 
   52355   /* Before the first write, give the VFS a hint of what the final
   52356   ** file size will be.
   52357   */
   52358   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
   52359   if( rc==SQLITE_OK
   52360    && pPager->dbHintSize<pPager->dbSize
   52361    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
   52362   ){
   52363     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
   52364     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
   52365     pPager->dbHintSize = pPager->dbSize;
   52366   }
   52367 
   52368   while( rc==SQLITE_OK && pList ){
   52369     Pgno pgno = pList->pgno;
   52370 
   52371     /* If there are dirty pages in the page cache with page numbers greater
   52372     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
   52373     ** make the file smaller (presumably by auto-vacuum code). Do not write
   52374     ** any such pages to the file.
   52375     **
   52376     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
   52377     ** set (set by sqlite3PagerDontWrite()).
   52378     */
   52379     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
   52380       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
   52381       char *pData;                                   /* Data to write */
   52382 
   52383       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
   52384       if( pList->pgno==1 ) pager_write_changecounter(pList);
   52385 
   52386       /* Encode the database */
   52387       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
   52388 
   52389       /* Write out the page data. */
   52390       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
   52391 
   52392       /* If page 1 was just written, update Pager.dbFileVers to match
   52393       ** the value now stored in the database file. If writing this
   52394       ** page caused the database file to grow, update dbFileSize.
   52395       */
   52396       if( pgno==1 ){
   52397         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
   52398       }
   52399       if( pgno>pPager->dbFileSize ){
   52400         pPager->dbFileSize = pgno;
   52401       }
   52402       pPager->aStat[PAGER_STAT_WRITE]++;
   52403 
   52404       /* Update any backup objects copying the contents of this pager. */
   52405       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
   52406 
   52407       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
   52408                    PAGERID(pPager), pgno, pager_pagehash(pList)));
   52409       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
   52410       PAGER_INCR(sqlite3_pager_writedb_count);
   52411     }else{
   52412       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
   52413     }
   52414     pager_set_pagehash(pList);
   52415     pList = pList->pDirty;
   52416   }
   52417 
   52418   return rc;
   52419 }
   52420 
   52421 /*
   52422 ** Ensure that the sub-journal file is open. If it is already open, this
   52423 ** function is a no-op.
   52424 **
   52425 ** SQLITE_OK is returned if everything goes according to plan. An
   52426 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
   52427 ** fails.
   52428 */
   52429 static int openSubJournal(Pager *pPager){
   52430   int rc = SQLITE_OK;
   52431   if( !isOpen(pPager->sjfd) ){
   52432     const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
   52433       | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
   52434       | SQLITE_OPEN_DELETEONCLOSE;
   52435     int nStmtSpill = sqlite3Config.nStmtSpill;
   52436     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
   52437       nStmtSpill = -1;
   52438     }
   52439     rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
   52440   }
   52441   return rc;
   52442 }
   52443 
   52444 /*
   52445 ** Append a record of the current state of page pPg to the sub-journal.
   52446 **
   52447 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
   52448 ** for all open savepoints before returning.
   52449 **
   52450 ** This function returns SQLITE_OK if everything is successful, an IO
   52451 ** error code if the attempt to write to the sub-journal fails, or
   52452 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
   52453 ** bitvec.
   52454 */
   52455 static int subjournalPage(PgHdr *pPg){
   52456   int rc = SQLITE_OK;
   52457   Pager *pPager = pPg->pPager;
   52458   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   52459 
   52460     /* Open the sub-journal, if it has not already been opened */
   52461     assert( pPager->useJournal );
   52462     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
   52463     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
   52464     assert( pagerUseWal(pPager)
   52465          || pageInJournal(pPager, pPg)
   52466          || pPg->pgno>pPager->dbOrigSize
   52467     );
   52468     rc = openSubJournal(pPager);
   52469 
   52470     /* If the sub-journal was opened successfully (or was already open),
   52471     ** write the journal record into the file.  */
   52472     if( rc==SQLITE_OK ){
   52473       void *pData = pPg->pData;
   52474       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
   52475       char *pData2;
   52476 
   52477 #if SQLITE_HAS_CODEC
   52478       if( !pPager->subjInMemory ){
   52479         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
   52480       }else
   52481 #endif
   52482       pData2 = pData;
   52483       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
   52484       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
   52485       if( rc==SQLITE_OK ){
   52486         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
   52487       }
   52488     }
   52489   }
   52490   if( rc==SQLITE_OK ){
   52491     pPager->nSubRec++;
   52492     assert( pPager->nSavepoint>0 );
   52493     rc = addToSavepointBitvecs(pPager, pPg->pgno);
   52494   }
   52495   return rc;
   52496 }
   52497 static int subjournalPageIfRequired(PgHdr *pPg){
   52498   if( subjRequiresPage(pPg) ){
   52499     return subjournalPage(pPg);
   52500   }else{
   52501     return SQLITE_OK;
   52502   }
   52503 }
   52504 
   52505 /*
   52506 ** This function is called by the pcache layer when it has reached some
   52507 ** soft memory limit. The first argument is a pointer to a Pager object
   52508 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
   52509 ** database). The second argument is a reference to a page that is
   52510 ** currently dirty but has no outstanding references. The page
   52511 ** is always associated with the Pager object passed as the first
   52512 ** argument.
   52513 **
   52514 ** The job of this function is to make pPg clean by writing its contents
   52515 ** out to the database file, if possible. This may involve syncing the
   52516 ** journal file.
   52517 **
   52518 ** If successful, sqlite3PcacheMakeClean() is called on the page and
   52519 ** SQLITE_OK returned. If an IO error occurs while trying to make the
   52520 ** page clean, the IO error code is returned. If the page cannot be
   52521 ** made clean for some other reason, but no error occurs, then SQLITE_OK
   52522 ** is returned by sqlite3PcacheMakeClean() is not called.
   52523 */
   52524 static int pagerStress(void *p, PgHdr *pPg){
   52525   Pager *pPager = (Pager *)p;
   52526   int rc = SQLITE_OK;
   52527 
   52528   assert( pPg->pPager==pPager );
   52529   assert( pPg->flags&PGHDR_DIRTY );
   52530 
   52531   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
   52532   ** journal (and adding a new header) is not allowed.  This occurs
   52533   ** during calls to sqlite3PagerWrite() while trying to journal multiple
   52534   ** pages belonging to the same sector.
   52535   **
   52536   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
   52537   ** regardless of whether or not a sync is required.  This is set during
   52538   ** a rollback or by user request, respectively.
   52539   **
   52540   ** Spilling is also prohibited when in an error state since that could
   52541   ** lead to database corruption.   In the current implementation it
   52542   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
   52543   ** while in the error state, hence it is impossible for this routine to
   52544   ** be called in the error state.  Nevertheless, we include a NEVER()
   52545   ** test for the error state as a safeguard against future changes.
   52546   */
   52547   if( NEVER(pPager->errCode) ) return SQLITE_OK;
   52548   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
   52549   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
   52550   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
   52551   if( pPager->doNotSpill
   52552    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
   52553       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
   52554   ){
   52555     return SQLITE_OK;
   52556   }
   52557 
   52558   pPg->pDirty = 0;
   52559   if( pagerUseWal(pPager) ){
   52560     /* Write a single frame for this page to the log. */
   52561     rc = subjournalPageIfRequired(pPg);
   52562     if( rc==SQLITE_OK ){
   52563       rc = pagerWalFrames(pPager, pPg, 0, 0);
   52564     }
   52565   }else{
   52566 
   52567 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   52568     if( pPager->tempFile==0 ){
   52569       rc = sqlite3JournalCreate(pPager->jfd);
   52570       if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
   52571     }
   52572 #endif
   52573 
   52574     /* Sync the journal file if required. */
   52575     if( pPg->flags&PGHDR_NEED_SYNC
   52576      || pPager->eState==PAGER_WRITER_CACHEMOD
   52577     ){
   52578       rc = syncJournal(pPager, 1);
   52579     }
   52580 
   52581     /* Write the contents of the page out to the database file. */
   52582     if( rc==SQLITE_OK ){
   52583       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
   52584       rc = pager_write_pagelist(pPager, pPg);
   52585     }
   52586   }
   52587 
   52588   /* Mark the page as clean. */
   52589   if( rc==SQLITE_OK ){
   52590     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
   52591     sqlite3PcacheMakeClean(pPg);
   52592   }
   52593 
   52594   return pager_error(pPager, rc);
   52595 }
   52596 
   52597 /*
   52598 ** Flush all unreferenced dirty pages to disk.
   52599 */
   52600 SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
   52601   int rc = pPager->errCode;
   52602   if( !MEMDB ){
   52603     PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
   52604     assert( assert_pager_state(pPager) );
   52605     while( rc==SQLITE_OK && pList ){
   52606       PgHdr *pNext = pList->pDirty;
   52607       if( pList->nRef==0 ){
   52608         rc = pagerStress((void*)pPager, pList);
   52609       }
   52610       pList = pNext;
   52611     }
   52612   }
   52613 
   52614   return rc;
   52615 }
   52616 
   52617 /*
   52618 ** Allocate and initialize a new Pager object and put a pointer to it
   52619 ** in *ppPager. The pager should eventually be freed by passing it
   52620 ** to sqlite3PagerClose().
   52621 **
   52622 ** The zFilename argument is the path to the database file to open.
   52623 ** If zFilename is NULL then a randomly-named temporary file is created
   52624 ** and used as the file to be cached. Temporary files are be deleted
   52625 ** automatically when they are closed. If zFilename is ":memory:" then
   52626 ** all information is held in cache. It is never written to disk.
   52627 ** This can be used to implement an in-memory database.
   52628 **
   52629 ** The nExtra parameter specifies the number of bytes of space allocated
   52630 ** along with each page reference. This space is available to the user
   52631 ** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the
   52632 ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
   52633 ** (The extra space is used by btree as the MemPage object.)
   52634 **
   52635 ** The flags argument is used to specify properties that affect the
   52636 ** operation of the pager. It should be passed some bitwise combination
   52637 ** of the PAGER_* flags.
   52638 **
   52639 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
   52640 ** of the xOpen() method of the supplied VFS when opening files.
   52641 **
   52642 ** If the pager object is allocated and the specified file opened
   52643 ** successfully, SQLITE_OK is returned and *ppPager set to point to
   52644 ** the new pager object. If an error occurs, *ppPager is set to NULL
   52645 ** and error code returned. This function may return SQLITE_NOMEM
   52646 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
   52647 ** various SQLITE_IO_XXX errors.
   52648 */
   52649 SQLITE_PRIVATE int sqlite3PagerOpen(
   52650   sqlite3_vfs *pVfs,       /* The virtual file system to use */
   52651   Pager **ppPager,         /* OUT: Return the Pager structure here */
   52652   const char *zFilename,   /* Name of the database file to open */
   52653   int nExtra,              /* Extra bytes append to each in-memory page */
   52654   int flags,               /* flags controlling this file */
   52655   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
   52656   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
   52657 ){
   52658   u8 *pPtr;
   52659   Pager *pPager = 0;       /* Pager object to allocate and return */
   52660   int rc = SQLITE_OK;      /* Return code */
   52661   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   52662   int memDb = 0;           /* True if this is an in-memory file */
   52663   int readOnly = 0;        /* True if this is a read-only file */
   52664   int journalFileSize;     /* Bytes to allocate for each journal fd */
   52665   char *zPathname = 0;     /* Full path to database file */
   52666   int nPathname = 0;       /* Number of bytes in zPathname */
   52667   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
   52668   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   52669   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   52670   const char *zUri = 0;    /* URI args to copy */
   52671   int nUri = 0;            /* Number of bytes of URI args at *zUri */
   52672 
   52673   /* Figure out how much space is required for each journal file-handle
   52674   ** (there are two of them, the main journal and the sub-journal).  */
   52675   journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
   52676 
   52677   /* Set the output variable to NULL in case an error occurs. */
   52678   *ppPager = 0;
   52679 
   52680 #ifndef SQLITE_OMIT_MEMORYDB
   52681   if( flags & PAGER_MEMORY ){
   52682     memDb = 1;
   52683     if( zFilename && zFilename[0] ){
   52684       zPathname = sqlite3DbStrDup(0, zFilename);
   52685       if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
   52686       nPathname = sqlite3Strlen30(zPathname);
   52687       zFilename = 0;
   52688     }
   52689   }
   52690 #endif
   52691 
   52692   /* Compute and store the full pathname in an allocated buffer pointed
   52693   ** to by zPathname, length nPathname. Or, if this is a temporary file,
   52694   ** leave both nPathname and zPathname set to 0.
   52695   */
   52696   if( zFilename && zFilename[0] ){
   52697     const char *z;
   52698     nPathname = pVfs->mxPathname+1;
   52699     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
   52700     if( zPathname==0 ){
   52701       return SQLITE_NOMEM_BKPT;
   52702     }
   52703     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
   52704     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
   52705     nPathname = sqlite3Strlen30(zPathname);
   52706     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
   52707     while( *z ){
   52708       z += sqlite3Strlen30(z)+1;
   52709       z += sqlite3Strlen30(z)+1;
   52710     }
   52711     nUri = (int)(&z[1] - zUri);
   52712     assert( nUri>=0 );
   52713     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
   52714       /* This branch is taken when the journal path required by
   52715       ** the database being opened will be more than pVfs->mxPathname
   52716       ** bytes in length. This means the database cannot be opened,
   52717       ** as it will not be possible to open the journal file or even
   52718       ** check for a hot-journal before reading.
   52719       */
   52720       rc = SQLITE_CANTOPEN_BKPT;
   52721     }
   52722     if( rc!=SQLITE_OK ){
   52723       sqlite3DbFree(0, zPathname);
   52724       return rc;
   52725     }
   52726   }
   52727 
   52728   /* Allocate memory for the Pager structure, PCache object, the
   52729   ** three file descriptors, the database file name and the journal
   52730   ** file name. The layout in memory is as follows:
   52731   **
   52732   **     Pager object                    (sizeof(Pager) bytes)
   52733   **     PCache object                   (sqlite3PcacheSize() bytes)
   52734   **     Database file handle            (pVfs->szOsFile bytes)
   52735   **     Sub-journal file handle         (journalFileSize bytes)
   52736   **     Main journal file handle        (journalFileSize bytes)
   52737   **     Database file name              (nPathname+1 bytes)
   52738   **     Journal file name               (nPathname+8+1 bytes)
   52739   */
   52740   pPtr = (u8 *)sqlite3MallocZero(
   52741     ROUND8(sizeof(*pPager)) +      /* Pager structure */
   52742     ROUND8(pcacheSize) +           /* PCache object */
   52743     ROUND8(pVfs->szOsFile) +       /* The main db file */
   52744     journalFileSize * 2 +          /* The two journal files */
   52745     nPathname + 1 + nUri +         /* zFilename */
   52746     nPathname + 8 + 2              /* zJournal */
   52747 #ifndef SQLITE_OMIT_WAL
   52748     + nPathname + 4 + 2            /* zWal */
   52749 #endif
   52750   );
   52751   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   52752   if( !pPtr ){
   52753     sqlite3DbFree(0, zPathname);
   52754     return SQLITE_NOMEM_BKPT;
   52755   }
   52756   pPager =              (Pager*)(pPtr);
   52757   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
   52758   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
   52759   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
   52760   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
   52761   pPager->zFilename =    (char*)(pPtr += journalFileSize);
   52762   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
   52763 
   52764   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
   52765   if( zPathname ){
   52766     assert( nPathname>0 );
   52767     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
   52768     memcpy(pPager->zFilename, zPathname, nPathname);
   52769     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
   52770     memcpy(pPager->zJournal, zPathname, nPathname);
   52771     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
   52772     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
   52773 #ifndef SQLITE_OMIT_WAL
   52774     pPager->zWal = &pPager->zJournal[nPathname+8+1];
   52775     memcpy(pPager->zWal, zPathname, nPathname);
   52776     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
   52777     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
   52778 #endif
   52779     sqlite3DbFree(0, zPathname);
   52780   }
   52781   pPager->pVfs = pVfs;
   52782   pPager->vfsFlags = vfsFlags;
   52783 
   52784   /* Open the pager file.
   52785   */
   52786   if( zFilename && zFilename[0] ){
   52787     int fout = 0;                    /* VFS flags returned by xOpen() */
   52788     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
   52789     assert( !memDb );
   52790     readOnly = (fout&SQLITE_OPEN_READONLY);
   52791 
   52792     /* If the file was successfully opened for read/write access,
   52793     ** choose a default page size in case we have to create the
   52794     ** database file. The default page size is the maximum of:
   52795     **
   52796     **    + SQLITE_DEFAULT_PAGE_SIZE,
   52797     **    + The value returned by sqlite3OsSectorSize()
   52798     **    + The largest page size that can be written atomically.
   52799     */
   52800     if( rc==SQLITE_OK ){
   52801       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   52802       if( !readOnly ){
   52803         setSectorSize(pPager);
   52804         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
   52805         if( szPageDflt<pPager->sectorSize ){
   52806           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
   52807             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
   52808           }else{
   52809             szPageDflt = (u32)pPager->sectorSize;
   52810           }
   52811         }
   52812 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   52813         {
   52814           int ii;
   52815           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   52816           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   52817           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
   52818           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
   52819             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
   52820               szPageDflt = ii;
   52821             }
   52822           }
   52823         }
   52824 #endif
   52825       }
   52826       pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
   52827       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
   52828        || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
   52829           vfsFlags |= SQLITE_OPEN_READONLY;
   52830           goto act_like_temp_file;
   52831       }
   52832     }
   52833   }else{
   52834     /* If a temporary file is requested, it is not opened immediately.
   52835     ** In this case we accept the default page size and delay actually
   52836     ** opening the file until the first call to OsWrite().
   52837     **
   52838     ** This branch is also run for an in-memory database. An in-memory
   52839     ** database is the same as a temp-file that is never written out to
   52840     ** disk and uses an in-memory rollback journal.
   52841     **
   52842     ** This branch also runs for files marked as immutable.
   52843     */
   52844 act_like_temp_file:
   52845     tempFile = 1;
   52846     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
   52847     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
   52848     pPager->noLock = 1;                /* Do no locking */
   52849     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   52850   }
   52851 
   52852   /* The following call to PagerSetPagesize() serves to set the value of
   52853   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   52854   */
   52855   if( rc==SQLITE_OK ){
   52856     assert( pPager->memDb==0 );
   52857     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
   52858     testcase( rc!=SQLITE_OK );
   52859   }
   52860 
   52861   /* Initialize the PCache object. */
   52862   if( rc==SQLITE_OK ){
   52863     nExtra = ROUND8(nExtra);
   52864     assert( nExtra>=8 && nExtra<1000 );
   52865     rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
   52866                        !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
   52867   }
   52868 
   52869   /* If an error occurred above, free the  Pager structure and close the file.
   52870   */
   52871   if( rc!=SQLITE_OK ){
   52872     sqlite3OsClose(pPager->fd);
   52873     sqlite3PageFree(pPager->pTmpSpace);
   52874     sqlite3_free(pPager);
   52875     return rc;
   52876   }
   52877 
   52878   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
   52879   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
   52880 
   52881   pPager->useJournal = (u8)useJournal;
   52882   /* pPager->stmtOpen = 0; */
   52883   /* pPager->stmtInUse = 0; */
   52884   /* pPager->nRef = 0; */
   52885   /* pPager->stmtSize = 0; */
   52886   /* pPager->stmtJSize = 0; */
   52887   /* pPager->nPage = 0; */
   52888   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
   52889   /* pPager->state = PAGER_UNLOCK; */
   52890   /* pPager->errMask = 0; */
   52891   pPager->tempFile = (u8)tempFile;
   52892   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
   52893           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   52894   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
   52895   pPager->exclusiveMode = (u8)tempFile;
   52896   pPager->changeCountDone = pPager->tempFile;
   52897   pPager->memDb = (u8)memDb;
   52898   pPager->readOnly = (u8)readOnly;
   52899   assert( useJournal || pPager->tempFile );
   52900   pPager->noSync = pPager->tempFile;
   52901   if( pPager->noSync ){
   52902     assert( pPager->fullSync==0 );
   52903     assert( pPager->extraSync==0 );
   52904     assert( pPager->syncFlags==0 );
   52905     assert( pPager->walSyncFlags==0 );
   52906   }else{
   52907     pPager->fullSync = 1;
   52908     pPager->extraSync = 0;
   52909     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   52910     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
   52911   }
   52912   /* pPager->pFirst = 0; */
   52913   /* pPager->pFirstSynced = 0; */
   52914   /* pPager->pLast = 0; */
   52915   pPager->nExtra = (u16)nExtra;
   52916   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
   52917   assert( isOpen(pPager->fd) || tempFile );
   52918   setSectorSize(pPager);
   52919   if( !useJournal ){
   52920     pPager->journalMode = PAGER_JOURNALMODE_OFF;
   52921   }else if( memDb ){
   52922     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
   52923   }
   52924   /* pPager->xBusyHandler = 0; */
   52925   /* pPager->pBusyHandlerArg = 0; */
   52926   pPager->xReiniter = xReinit;
   52927   setGetterMethod(pPager);
   52928   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
   52929   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
   52930 
   52931   *ppPager = pPager;
   52932   return SQLITE_OK;
   52933 }
   52934 
   52935 
   52936 /* Verify that the database file has not be deleted or renamed out from
   52937 ** under the pager.  Return SQLITE_OK if the database is still were it ought
   52938 ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
   52939 ** code from sqlite3OsAccess()) if the database has gone missing.
   52940 */
   52941 static int databaseIsUnmoved(Pager *pPager){
   52942   int bHasMoved = 0;
   52943   int rc;
   52944 
   52945   if( pPager->tempFile ) return SQLITE_OK;
   52946   if( pPager->dbSize==0 ) return SQLITE_OK;
   52947   assert( pPager->zFilename && pPager->zFilename[0] );
   52948   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
   52949   if( rc==SQLITE_NOTFOUND ){
   52950     /* If the HAS_MOVED file-control is unimplemented, assume that the file
   52951     ** has not been moved.  That is the historical behavior of SQLite: prior to
   52952     ** version 3.8.3, it never checked */
   52953     rc = SQLITE_OK;
   52954   }else if( rc==SQLITE_OK && bHasMoved ){
   52955     rc = SQLITE_READONLY_DBMOVED;
   52956   }
   52957   return rc;
   52958 }
   52959 
   52960 
   52961 /*
   52962 ** This function is called after transitioning from PAGER_UNLOCK to
   52963 ** PAGER_SHARED state. It tests if there is a hot journal present in
   52964 ** the file-system for the given pager. A hot journal is one that
   52965 ** needs to be played back. According to this function, a hot-journal
   52966 ** file exists if the following criteria are met:
   52967 **
   52968 **   * The journal file exists in the file system, and
   52969 **   * No process holds a RESERVED or greater lock on the database file, and
   52970 **   * The database file itself is greater than 0 bytes in size, and
   52971 **   * The first byte of the journal file exists and is not 0x00.
   52972 **
   52973 ** If the current size of the database file is 0 but a journal file
   52974 ** exists, that is probably an old journal left over from a prior
   52975 ** database with the same name. In this case the journal file is
   52976 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
   52977 ** is returned.
   52978 **
   52979 ** This routine does not check if there is a master journal filename
   52980 ** at the end of the file. If there is, and that master journal file
   52981 ** does not exist, then the journal file is not really hot. In this
   52982 ** case this routine will return a false-positive. The pager_playback()
   52983 ** routine will discover that the journal file is not really hot and
   52984 ** will not roll it back.
   52985 **
   52986 ** If a hot-journal file is found to exist, *pExists is set to 1 and
   52987 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
   52988 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
   52989 ** to determine whether or not a hot-journal file exists, the IO error
   52990 ** code is returned and the value of *pExists is undefined.
   52991 */
   52992 static int hasHotJournal(Pager *pPager, int *pExists){
   52993   sqlite3_vfs * const pVfs = pPager->pVfs;
   52994   int rc = SQLITE_OK;           /* Return code */
   52995   int exists = 1;               /* True if a journal file is present */
   52996   int jrnlOpen = !!isOpen(pPager->jfd);
   52997 
   52998   assert( pPager->useJournal );
   52999   assert( isOpen(pPager->fd) );
   53000   assert( pPager->eState==PAGER_OPEN );
   53001 
   53002   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
   53003     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   53004   ));
   53005 
   53006   *pExists = 0;
   53007   if( !jrnlOpen ){
   53008     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
   53009   }
   53010   if( rc==SQLITE_OK && exists ){
   53011     int locked = 0;             /* True if some process holds a RESERVED lock */
   53012 
   53013     /* Race condition here:  Another process might have been holding the
   53014     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
   53015     ** call above, but then delete the journal and drop the lock before
   53016     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
   53017     ** is the case, this routine might think there is a hot journal when
   53018     ** in fact there is none.  This results in a false-positive which will
   53019     ** be dealt with by the playback routine.  Ticket #3883.
   53020     */
   53021     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
   53022     if( rc==SQLITE_OK && !locked ){
   53023       Pgno nPage;                 /* Number of pages in database file */
   53024 
   53025       assert( pPager->tempFile==0 );
   53026       rc = pagerPagecount(pPager, &nPage);
   53027       if( rc==SQLITE_OK ){
   53028         /* If the database is zero pages in size, that means that either (1) the
   53029         ** journal is a remnant from a prior database with the same name where
   53030         ** the database file but not the journal was deleted, or (2) the initial
   53031         ** transaction that populates a new database is being rolled back.
   53032         ** In either case, the journal file can be deleted.  However, take care
   53033         ** not to delete the journal file if it is already open due to
   53034         ** journal_mode=PERSIST.
   53035         */
   53036         if( nPage==0 && !jrnlOpen ){
   53037           sqlite3BeginBenignMalloc();
   53038           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
   53039             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
   53040             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
   53041           }
   53042           sqlite3EndBenignMalloc();
   53043         }else{
   53044           /* The journal file exists and no other connection has a reserved
   53045           ** or greater lock on the database file. Now check that there is
   53046           ** at least one non-zero bytes at the start of the journal file.
   53047           ** If there is, then we consider this journal to be hot. If not,
   53048           ** it can be ignored.
   53049           */
   53050           if( !jrnlOpen ){
   53051             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
   53052             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
   53053           }
   53054           if( rc==SQLITE_OK ){
   53055             u8 first = 0;
   53056             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
   53057             if( rc==SQLITE_IOERR_SHORT_READ ){
   53058               rc = SQLITE_OK;
   53059             }
   53060             if( !jrnlOpen ){
   53061               sqlite3OsClose(pPager->jfd);
   53062             }
   53063             *pExists = (first!=0);
   53064           }else if( rc==SQLITE_CANTOPEN ){
   53065             /* If we cannot open the rollback journal file in order to see if
   53066             ** it has a zero header, that might be due to an I/O error, or
   53067             ** it might be due to the race condition described above and in
   53068             ** ticket #3883.  Either way, assume that the journal is hot.
   53069             ** This might be a false positive.  But if it is, then the
   53070             ** automatic journal playback and recovery mechanism will deal
   53071             ** with it under an EXCLUSIVE lock where we do not need to
   53072             ** worry so much with race conditions.
   53073             */
   53074             *pExists = 1;
   53075             rc = SQLITE_OK;
   53076           }
   53077         }
   53078       }
   53079     }
   53080   }
   53081 
   53082   return rc;
   53083 }
   53084 
   53085 /*
   53086 ** This function is called to obtain a shared lock on the database file.
   53087 ** It is illegal to call sqlite3PagerGet() until after this function
   53088 ** has been successfully called. If a shared-lock is already held when
   53089 ** this function is called, it is a no-op.
   53090 **
   53091 ** The following operations are also performed by this function.
   53092 **
   53093 **   1) If the pager is currently in PAGER_OPEN state (no lock held
   53094 **      on the database file), then an attempt is made to obtain a
   53095 **      SHARED lock on the database file. Immediately after obtaining
   53096 **      the SHARED lock, the file-system is checked for a hot-journal,
   53097 **      which is played back if present. Following any hot-journal
   53098 **      rollback, the contents of the cache are validated by checking
   53099 **      the 'change-counter' field of the database file header and
   53100 **      discarded if they are found to be invalid.
   53101 **
   53102 **   2) If the pager is running in exclusive-mode, and there are currently
   53103 **      no outstanding references to any pages, and is in the error state,
   53104 **      then an attempt is made to clear the error state by discarding
   53105 **      the contents of the page cache and rolling back any open journal
   53106 **      file.
   53107 **
   53108 ** If everything is successful, SQLITE_OK is returned. If an IO error
   53109 ** occurs while locking the database, checking for a hot-journal file or
   53110 ** rolling back a journal file, the IO error code is returned.
   53111 */
   53112 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
   53113   int rc = SQLITE_OK;                /* Return code */
   53114 
   53115   /* This routine is only called from b-tree and only when there are no
   53116   ** outstanding pages. This implies that the pager state should either
   53117   ** be OPEN or READER. READER is only possible if the pager is or was in
   53118   ** exclusive access mode.  */
   53119   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   53120   assert( assert_pager_state(pPager) );
   53121   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   53122   assert( pPager->errCode==SQLITE_OK );
   53123 
   53124   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
   53125     int bHotJournal = 1;          /* True if there exists a hot journal-file */
   53126 
   53127     assert( !MEMDB );
   53128     assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
   53129 
   53130     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
   53131     if( rc!=SQLITE_OK ){
   53132       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
   53133       goto failed;
   53134     }
   53135 
   53136     /* If a journal file exists, and there is no RESERVED lock on the
   53137     ** database file, then it either needs to be played back or deleted.
   53138     */
   53139     if( pPager->eLock<=SHARED_LOCK ){
   53140       rc = hasHotJournal(pPager, &bHotJournal);
   53141     }
   53142     if( rc!=SQLITE_OK ){
   53143       goto failed;
   53144     }
   53145     if( bHotJournal ){
   53146       if( pPager->readOnly ){
   53147         rc = SQLITE_READONLY_ROLLBACK;
   53148         goto failed;
   53149       }
   53150 
   53151       /* Get an EXCLUSIVE lock on the database file. At this point it is
   53152       ** important that a RESERVED lock is not obtained on the way to the
   53153       ** EXCLUSIVE lock. If it were, another process might open the
   53154       ** database file, detect the RESERVED lock, and conclude that the
   53155       ** database is safe to read while this process is still rolling the
   53156       ** hot-journal back.
   53157       **
   53158       ** Because the intermediate RESERVED lock is not requested, any
   53159       ** other process attempting to access the database file will get to
   53160       ** this point in the code and fail to obtain its own EXCLUSIVE lock
   53161       ** on the database file.
   53162       **
   53163       ** Unless the pager is in locking_mode=exclusive mode, the lock is
   53164       ** downgraded to SHARED_LOCK before this function returns.
   53165       */
   53166       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   53167       if( rc!=SQLITE_OK ){
   53168         goto failed;
   53169       }
   53170 
   53171       /* If it is not already open and the file exists on disk, open the
   53172       ** journal for read/write access. Write access is required because
   53173       ** in exclusive-access mode the file descriptor will be kept open
   53174       ** and possibly used for a transaction later on. Also, write-access
   53175       ** is usually required to finalize the journal in journal_mode=persist
   53176       ** mode (and also for journal_mode=truncate on some systems).
   53177       **
   53178       ** If the journal does not exist, it usually means that some
   53179       ** other connection managed to get in and roll it back before
   53180       ** this connection obtained the exclusive lock above. Or, it
   53181       ** may mean that the pager was in the error-state when this
   53182       ** function was called and the journal file does not exist.
   53183       */
   53184       if( !isOpen(pPager->jfd) ){
   53185         sqlite3_vfs * const pVfs = pPager->pVfs;
   53186         int bExists;              /* True if journal file exists */
   53187         rc = sqlite3OsAccess(
   53188             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
   53189         if( rc==SQLITE_OK && bExists ){
   53190           int fout = 0;
   53191           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
   53192           assert( !pPager->tempFile );
   53193           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
   53194           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   53195           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
   53196             rc = SQLITE_CANTOPEN_BKPT;
   53197             sqlite3OsClose(pPager->jfd);
   53198           }
   53199         }
   53200       }
   53201 
   53202       /* Playback and delete the journal.  Drop the database write
   53203       ** lock and reacquire the read lock. Purge the cache before
   53204       ** playing back the hot-journal so that we don't end up with
   53205       ** an inconsistent cache.  Sync the hot journal before playing
   53206       ** it back since the process that crashed and left the hot journal
   53207       ** probably did not sync it and we are required to always sync
   53208       ** the journal before playing it back.
   53209       */
   53210       if( isOpen(pPager->jfd) ){
   53211         assert( rc==SQLITE_OK );
   53212         rc = pagerSyncHotJournal(pPager);
   53213         if( rc==SQLITE_OK ){
   53214           rc = pager_playback(pPager, !pPager->tempFile);
   53215           pPager->eState = PAGER_OPEN;
   53216         }
   53217       }else if( !pPager->exclusiveMode ){
   53218         pagerUnlockDb(pPager, SHARED_LOCK);
   53219       }
   53220 
   53221       if( rc!=SQLITE_OK ){
   53222         /* This branch is taken if an error occurs while trying to open
   53223         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
   53224         ** pager_unlock() routine will be called before returning to unlock
   53225         ** the file. If the unlock attempt fails, then Pager.eLock must be
   53226         ** set to UNKNOWN_LOCK (see the comment above the #define for
   53227         ** UNKNOWN_LOCK above for an explanation).
   53228         **
   53229         ** In order to get pager_unlock() to do this, set Pager.eState to
   53230         ** PAGER_ERROR now. This is not actually counted as a transition
   53231         ** to ERROR state in the state diagram at the top of this file,
   53232         ** since we know that the same call to pager_unlock() will very
   53233         ** shortly transition the pager object to the OPEN state. Calling
   53234         ** assert_pager_state() would fail now, as it should not be possible
   53235         ** to be in ERROR state when there are zero outstanding page
   53236         ** references.
   53237         */
   53238         pager_error(pPager, rc);
   53239         goto failed;
   53240       }
   53241 
   53242       assert( pPager->eState==PAGER_OPEN );
   53243       assert( (pPager->eLock==SHARED_LOCK)
   53244            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
   53245       );
   53246     }
   53247 
   53248     if( !pPager->tempFile && pPager->hasHeldSharedLock ){
   53249       /* The shared-lock has just been acquired then check to
   53250       ** see if the database has been modified.  If the database has changed,
   53251       ** flush the cache.  The hasHeldSharedLock flag prevents this from
   53252       ** occurring on the very first access to a file, in order to save a
   53253       ** single unnecessary sqlite3OsRead() call at the start-up.
   53254       **
   53255       ** Database changes are detected by looking at 15 bytes beginning
   53256       ** at offset 24 into the file.  The first 4 of these 16 bytes are
   53257       ** a 32-bit counter that is incremented with each change.  The
   53258       ** other bytes change randomly with each file change when
   53259       ** a codec is in use.
   53260       **
   53261       ** There is a vanishingly small chance that a change will not be
   53262       ** detected.  The chance of an undetected change is so small that
   53263       ** it can be neglected.
   53264       */
   53265       char dbFileVers[sizeof(pPager->dbFileVers)];
   53266 
   53267       IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
   53268       rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
   53269       if( rc!=SQLITE_OK ){
   53270         if( rc!=SQLITE_IOERR_SHORT_READ ){
   53271           goto failed;
   53272         }
   53273         memset(dbFileVers, 0, sizeof(dbFileVers));
   53274       }
   53275 
   53276       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
   53277         pager_reset(pPager);
   53278 
   53279         /* Unmap the database file. It is possible that external processes
   53280         ** may have truncated the database file and then extended it back
   53281         ** to its original size while this process was not holding a lock.
   53282         ** In this case there may exist a Pager.pMap mapping that appears
   53283         ** to be the right size but is not actually valid. Avoid this
   53284         ** possibility by unmapping the db here. */
   53285         if( USEFETCH(pPager) ){
   53286           sqlite3OsUnfetch(pPager->fd, 0, 0);
   53287         }
   53288       }
   53289     }
   53290 
   53291     /* If there is a WAL file in the file-system, open this database in WAL
   53292     ** mode. Otherwise, the following function call is a no-op.
   53293     */
   53294     rc = pagerOpenWalIfPresent(pPager);
   53295 #ifndef SQLITE_OMIT_WAL
   53296     assert( pPager->pWal==0 || rc==SQLITE_OK );
   53297 #endif
   53298   }
   53299 
   53300   if( pagerUseWal(pPager) ){
   53301     assert( rc==SQLITE_OK );
   53302     rc = pagerBeginReadTransaction(pPager);
   53303   }
   53304 
   53305   if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
   53306     rc = pagerPagecount(pPager, &pPager->dbSize);
   53307   }
   53308 
   53309  failed:
   53310   if( rc!=SQLITE_OK ){
   53311     assert( !MEMDB );
   53312     pager_unlock(pPager);
   53313     assert( pPager->eState==PAGER_OPEN );
   53314   }else{
   53315     pPager->eState = PAGER_READER;
   53316     pPager->hasHeldSharedLock = 1;
   53317   }
   53318   return rc;
   53319 }
   53320 
   53321 /*
   53322 ** If the reference count has reached zero, rollback any active
   53323 ** transaction and unlock the pager.
   53324 **
   53325 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
   53326 ** the rollback journal, the unlock is not performed and there is
   53327 ** nothing to rollback, so this routine is a no-op.
   53328 */
   53329 static void pagerUnlockIfUnused(Pager *pPager){
   53330   if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
   53331     assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
   53332     pagerUnlockAndRollback(pPager);
   53333   }
   53334 }
   53335 
   53336 /*
   53337 ** The page getter methods each try to acquire a reference to a
   53338 ** page with page number pgno. If the requested reference is
   53339 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
   53340 **
   53341 ** There are different implementations of the getter method depending
   53342 ** on the current state of the pager.
   53343 **
   53344 **     getPageNormal()         --  The normal getter
   53345 **     getPageError()          --  Used if the pager is in an error state
   53346 **     getPageMmap()           --  Used if memory-mapped I/O is enabled
   53347 **
   53348 ** If the requested page is already in the cache, it is returned.
   53349 ** Otherwise, a new page object is allocated and populated with data
   53350 ** read from the database file. In some cases, the pcache module may
   53351 ** choose not to allocate a new page object and may reuse an existing
   53352 ** object with no outstanding references.
   53353 **
   53354 ** The extra data appended to a page is always initialized to zeros the
   53355 ** first time a page is loaded into memory. If the page requested is
   53356 ** already in the cache when this function is called, then the extra
   53357 ** data is left as it was when the page object was last used.
   53358 **
   53359 ** If the database image is smaller than the requested page or if
   53360 ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
   53361 ** requested page is not already stored in the cache, then no
   53362 ** actual disk read occurs. In this case the memory image of the
   53363 ** page is initialized to all zeros.
   53364 **
   53365 ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
   53366 ** the contents of the page. This occurs in two scenarios:
   53367 **
   53368 **   a) When reading a free-list leaf page from the database, and
   53369 **
   53370 **   b) When a savepoint is being rolled back and we need to load
   53371 **      a new page into the cache to be filled with the data read
   53372 **      from the savepoint journal.
   53373 **
   53374 ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
   53375 ** of being read from the database. Additionally, the bits corresponding
   53376 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
   53377 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
   53378 ** savepoints are set. This means if the page is made writable at any
   53379 ** point in the future, using a call to sqlite3PagerWrite(), its contents
   53380 ** will not be journaled. This saves IO.
   53381 **
   53382 ** The acquisition might fail for several reasons.  In all cases,
   53383 ** an appropriate error code is returned and *ppPage is set to NULL.
   53384 **
   53385 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
   53386 ** to find a page in the in-memory cache first.  If the page is not already
   53387 ** in memory, this routine goes to disk to read it in whereas Lookup()
   53388 ** just returns 0.  This routine acquires a read-lock the first time it
   53389 ** has to go to disk, and could also playback an old journal if necessary.
   53390 ** Since Lookup() never goes to disk, it never has to deal with locks
   53391 ** or journal files.
   53392 */
   53393 static int getPageNormal(
   53394   Pager *pPager,      /* The pager open on the database file */
   53395   Pgno pgno,          /* Page number to fetch */
   53396   DbPage **ppPage,    /* Write a pointer to the page here */
   53397   int flags           /* PAGER_GET_XXX flags */
   53398 ){
   53399   int rc = SQLITE_OK;
   53400   PgHdr *pPg;
   53401   u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */
   53402   sqlite3_pcache_page *pBase;
   53403 
   53404   assert( pPager->errCode==SQLITE_OK );
   53405   assert( pPager->eState>=PAGER_READER );
   53406   assert( assert_pager_state(pPager) );
   53407   assert( pPager->hasHeldSharedLock==1 );
   53408 
   53409   if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
   53410   pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
   53411   if( pBase==0 ){
   53412     pPg = 0;
   53413     rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
   53414     if( rc!=SQLITE_OK ) goto pager_acquire_err;
   53415     if( pBase==0 ){
   53416       rc = SQLITE_NOMEM_BKPT;
   53417       goto pager_acquire_err;
   53418     }
   53419   }
   53420   pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
   53421   assert( pPg==(*ppPage) );
   53422   assert( pPg->pgno==pgno );
   53423   assert( pPg->pPager==pPager || pPg->pPager==0 );
   53424 
   53425   noContent = (flags & PAGER_GET_NOCONTENT)!=0;
   53426   if( pPg->pPager && !noContent ){
   53427     /* In this case the pcache already contains an initialized copy of
   53428     ** the page. Return without further ado.  */
   53429     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
   53430     pPager->aStat[PAGER_STAT_HIT]++;
   53431     return SQLITE_OK;
   53432 
   53433   }else{
   53434     /* The pager cache has created a new page. Its content needs to
   53435     ** be initialized. But first some error checks:
   53436     **
   53437     ** (1) The maximum page number is 2^31
   53438     ** (2) Never try to fetch the locking page
   53439     */
   53440     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
   53441       rc = SQLITE_CORRUPT_BKPT;
   53442       goto pager_acquire_err;
   53443     }
   53444 
   53445     pPg->pPager = pPager;
   53446 
   53447     assert( !isOpen(pPager->fd) || !MEMDB );
   53448     if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
   53449       if( pgno>pPager->mxPgno ){
   53450         rc = SQLITE_FULL;
   53451         goto pager_acquire_err;
   53452       }
   53453       if( noContent ){
   53454         /* Failure to set the bits in the InJournal bit-vectors is benign.
   53455         ** It merely means that we might do some extra work to journal a
   53456         ** page that does not need to be journaled.  Nevertheless, be sure
   53457         ** to test the case where a malloc error occurs while trying to set
   53458         ** a bit in a bit vector.
   53459         */
   53460         sqlite3BeginBenignMalloc();
   53461         if( pgno<=pPager->dbOrigSize ){
   53462           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
   53463           testcase( rc==SQLITE_NOMEM );
   53464         }
   53465         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
   53466         testcase( rc==SQLITE_NOMEM );
   53467         sqlite3EndBenignMalloc();
   53468       }
   53469       memset(pPg->pData, 0, pPager->pageSize);
   53470       IOTRACE(("ZERO %p %d\n", pPager, pgno));
   53471     }else{
   53472       assert( pPg->pPager==pPager );
   53473       pPager->aStat[PAGER_STAT_MISS]++;
   53474       rc = readDbPage(pPg);
   53475       if( rc!=SQLITE_OK ){
   53476         goto pager_acquire_err;
   53477       }
   53478     }
   53479     pager_set_pagehash(pPg);
   53480   }
   53481   return SQLITE_OK;
   53482 
   53483 pager_acquire_err:
   53484   assert( rc!=SQLITE_OK );
   53485   if( pPg ){
   53486     sqlite3PcacheDrop(pPg);
   53487   }
   53488   pagerUnlockIfUnused(pPager);
   53489   *ppPage = 0;
   53490   return rc;
   53491 }
   53492 
   53493 #if SQLITE_MAX_MMAP_SIZE>0
   53494 /* The page getter for when memory-mapped I/O is enabled */
   53495 static int getPageMMap(
   53496   Pager *pPager,      /* The pager open on the database file */
   53497   Pgno pgno,          /* Page number to fetch */
   53498   DbPage **ppPage,    /* Write a pointer to the page here */
   53499   int flags           /* PAGER_GET_XXX flags */
   53500 ){
   53501   int rc = SQLITE_OK;
   53502   PgHdr *pPg = 0;
   53503   u32 iFrame = 0;                 /* Frame to read from WAL file */
   53504 
   53505   /* It is acceptable to use a read-only (mmap) page for any page except
   53506   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
   53507   ** flag was specified by the caller. And so long as the db is not a
   53508   ** temporary or in-memory database.  */
   53509   const int bMmapOk = (pgno>1
   53510    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
   53511   );
   53512 
   53513   assert( USEFETCH(pPager) );
   53514 #ifdef SQLITE_HAS_CODEC
   53515   assert( pPager->xCodec==0 );
   53516 #endif
   53517 
   53518   /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
   53519   ** allows the compiler optimizer to reuse the results of the "pgno>1"
   53520   ** test in the previous statement, and avoid testing pgno==0 in the
   53521   ** common case where pgno is large. */
   53522   if( pgno<=1 && pgno==0 ){
   53523     return SQLITE_CORRUPT_BKPT;
   53524   }
   53525   assert( pPager->eState>=PAGER_READER );
   53526   assert( assert_pager_state(pPager) );
   53527   assert( pPager->hasHeldSharedLock==1 );
   53528   assert( pPager->errCode==SQLITE_OK );
   53529 
   53530   if( bMmapOk && pagerUseWal(pPager) ){
   53531     rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
   53532     if( rc!=SQLITE_OK ){
   53533       *ppPage = 0;
   53534       return rc;
   53535     }
   53536   }
   53537   if( bMmapOk && iFrame==0 ){
   53538     void *pData = 0;
   53539     rc = sqlite3OsFetch(pPager->fd,
   53540         (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
   53541     );
   53542     if( rc==SQLITE_OK && pData ){
   53543       if( pPager->eState>PAGER_READER || pPager->tempFile ){
   53544         pPg = sqlite3PagerLookup(pPager, pgno);
   53545       }
   53546       if( pPg==0 ){
   53547         rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
   53548       }else{
   53549         sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
   53550       }
   53551       if( pPg ){
   53552         assert( rc==SQLITE_OK );
   53553         *ppPage = pPg;
   53554         return SQLITE_OK;
   53555       }
   53556     }
   53557     if( rc!=SQLITE_OK ){
   53558       *ppPage = 0;
   53559       return rc;
   53560     }
   53561   }
   53562   return getPageNormal(pPager, pgno, ppPage, flags);
   53563 }
   53564 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   53565 
   53566 /* The page getter method for when the pager is an error state */
   53567 static int getPageError(
   53568   Pager *pPager,      /* The pager open on the database file */
   53569   Pgno pgno,          /* Page number to fetch */
   53570   DbPage **ppPage,    /* Write a pointer to the page here */
   53571   int flags           /* PAGER_GET_XXX flags */
   53572 ){
   53573   UNUSED_PARAMETER(pgno);
   53574   UNUSED_PARAMETER(flags);
   53575   assert( pPager->errCode!=SQLITE_OK );
   53576   *ppPage = 0;
   53577   return pPager->errCode;
   53578 }
   53579 
   53580 
   53581 /* Dispatch all page fetch requests to the appropriate getter method.
   53582 */
   53583 SQLITE_PRIVATE int sqlite3PagerGet(
   53584   Pager *pPager,      /* The pager open on the database file */
   53585   Pgno pgno,          /* Page number to fetch */
   53586   DbPage **ppPage,    /* Write a pointer to the page here */
   53587   int flags           /* PAGER_GET_XXX flags */
   53588 ){
   53589   return pPager->xGet(pPager, pgno, ppPage, flags);
   53590 }
   53591 
   53592 /*
   53593 ** Acquire a page if it is already in the in-memory cache.  Do
   53594 ** not read the page from disk.  Return a pointer to the page,
   53595 ** or 0 if the page is not in cache.
   53596 **
   53597 ** See also sqlite3PagerGet().  The difference between this routine
   53598 ** and sqlite3PagerGet() is that _get() will go to the disk and read
   53599 ** in the page if the page is not already in cache.  This routine
   53600 ** returns NULL if the page is not in cache or if a disk I/O error
   53601 ** has ever happened.
   53602 */
   53603 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
   53604   sqlite3_pcache_page *pPage;
   53605   assert( pPager!=0 );
   53606   assert( pgno!=0 );
   53607   assert( pPager->pPCache!=0 );
   53608   pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
   53609   assert( pPage==0 || pPager->hasHeldSharedLock );
   53610   if( pPage==0 ) return 0;
   53611   return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
   53612 }
   53613 
   53614 /*
   53615 ** Release a page reference.
   53616 **
   53617 ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
   53618 ** used if we know that the page being released is not the last page.
   53619 ** The btree layer always holds page1 open until the end, so these first
   53620 ** to routines can be used to release any page other than BtShared.pPage1.
   53621 **
   53622 ** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine
   53623 ** checks the total number of outstanding pages and if the number of
   53624 ** pages reaches zero it drops the database lock.
   53625 */
   53626 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
   53627   TESTONLY( Pager *pPager = pPg->pPager; )
   53628   assert( pPg!=0 );
   53629   if( pPg->flags & PGHDR_MMAP ){
   53630     assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */
   53631     pagerReleaseMapPage(pPg);
   53632   }else{
   53633     sqlite3PcacheRelease(pPg);
   53634   }
   53635   /* Do not use this routine to release the last reference to page1 */
   53636   assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
   53637 }
   53638 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
   53639   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
   53640 }
   53641 SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
   53642   Pager *pPager;
   53643   assert( pPg!=0 );
   53644   assert( pPg->pgno==1 );
   53645   assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
   53646   pPager = pPg->pPager;
   53647   sqlite3PcacheRelease(pPg);
   53648   pagerUnlockIfUnused(pPager);
   53649 }
   53650 
   53651 /*
   53652 ** This function is called at the start of every write transaction.
   53653 ** There must already be a RESERVED or EXCLUSIVE lock on the database
   53654 ** file when this routine is called.
   53655 **
   53656 ** Open the journal file for pager pPager and write a journal header
   53657 ** to the start of it. If there are active savepoints, open the sub-journal
   53658 ** as well. This function is only used when the journal file is being
   53659 ** opened to write a rollback log for a transaction. It is not used
   53660 ** when opening a hot journal file to roll it back.
   53661 **
   53662 ** If the journal file is already open (as it may be in exclusive mode),
   53663 ** then this function just writes a journal header to the start of the
   53664 ** already open file.
   53665 **
   53666 ** Whether or not the journal file is opened by this function, the
   53667 ** Pager.pInJournal bitvec structure is allocated.
   53668 **
   53669 ** Return SQLITE_OK if everything is successful. Otherwise, return
   53670 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
   53671 ** an IO error code if opening or writing the journal file fails.
   53672 */
   53673 static int pager_open_journal(Pager *pPager){
   53674   int rc = SQLITE_OK;                        /* Return code */
   53675   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
   53676 
   53677   assert( pPager->eState==PAGER_WRITER_LOCKED );
   53678   assert( assert_pager_state(pPager) );
   53679   assert( pPager->pInJournal==0 );
   53680 
   53681   /* If already in the error state, this function is a no-op.  But on
   53682   ** the other hand, this routine is never called if we are already in
   53683   ** an error state. */
   53684   if( NEVER(pPager->errCode) ) return pPager->errCode;
   53685 
   53686   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   53687     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
   53688     if( pPager->pInJournal==0 ){
   53689       return SQLITE_NOMEM_BKPT;
   53690     }
   53691 
   53692     /* Open the journal file if it is not already open. */
   53693     if( !isOpen(pPager->jfd) ){
   53694       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
   53695         sqlite3MemJournalOpen(pPager->jfd);
   53696       }else{
   53697         int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
   53698         int nSpill;
   53699 
   53700         if( pPager->tempFile ){
   53701           flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
   53702           nSpill = sqlite3Config.nStmtSpill;
   53703         }else{
   53704           flags |= SQLITE_OPEN_MAIN_JOURNAL;
   53705           nSpill = jrnlBufferSize(pPager);
   53706         }
   53707 
   53708         /* Verify that the database still has the same name as it did when
   53709         ** it was originally opened. */
   53710         rc = databaseIsUnmoved(pPager);
   53711         if( rc==SQLITE_OK ){
   53712           rc = sqlite3JournalOpen (
   53713               pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
   53714           );
   53715         }
   53716       }
   53717       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   53718     }
   53719 
   53720 
   53721     /* Write the first journal header to the journal file and open
   53722     ** the sub-journal if necessary.
   53723     */
   53724     if( rc==SQLITE_OK ){
   53725       /* TODO: Check if all of these are really required. */
   53726       pPager->nRec = 0;
   53727       pPager->journalOff = 0;
   53728       pPager->setMaster = 0;
   53729       pPager->journalHdr = 0;
   53730       rc = writeJournalHdr(pPager);
   53731     }
   53732   }
   53733 
   53734   if( rc!=SQLITE_OK ){
   53735     sqlite3BitvecDestroy(pPager->pInJournal);
   53736     pPager->pInJournal = 0;
   53737   }else{
   53738     assert( pPager->eState==PAGER_WRITER_LOCKED );
   53739     pPager->eState = PAGER_WRITER_CACHEMOD;
   53740   }
   53741 
   53742   return rc;
   53743 }
   53744 
   53745 /*
   53746 ** Begin a write-transaction on the specified pager object. If a
   53747 ** write-transaction has already been opened, this function is a no-op.
   53748 **
   53749 ** If the exFlag argument is false, then acquire at least a RESERVED
   53750 ** lock on the database file. If exFlag is true, then acquire at least
   53751 ** an EXCLUSIVE lock. If such a lock is already held, no locking
   53752 ** functions need be called.
   53753 **
   53754 ** If the subjInMemory argument is non-zero, then any sub-journal opened
   53755 ** within this transaction will be opened as an in-memory file. This
   53756 ** has no effect if the sub-journal is already opened (as it may be when
   53757 ** running in exclusive mode) or if the transaction does not require a
   53758 ** sub-journal. If the subjInMemory argument is zero, then any required
   53759 ** sub-journal is implemented in-memory if pPager is an in-memory database,
   53760 ** or using a temporary file otherwise.
   53761 */
   53762 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
   53763   int rc = SQLITE_OK;
   53764 
   53765   if( pPager->errCode ) return pPager->errCode;
   53766   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
   53767   pPager->subjInMemory = (u8)subjInMemory;
   53768 
   53769   if( ALWAYS(pPager->eState==PAGER_READER) ){
   53770     assert( pPager->pInJournal==0 );
   53771 
   53772     if( pagerUseWal(pPager) ){
   53773       /* If the pager is configured to use locking_mode=exclusive, and an
   53774       ** exclusive lock on the database is not already held, obtain it now.
   53775       */
   53776       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
   53777         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   53778         if( rc!=SQLITE_OK ){
   53779           return rc;
   53780         }
   53781         (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
   53782       }
   53783 
   53784       /* Grab the write lock on the log file. If successful, upgrade to
   53785       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
   53786       ** The busy-handler is not invoked if another connection already
   53787       ** holds the write-lock. If possible, the upper layer will call it.
   53788       */
   53789       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
   53790     }else{
   53791       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
   53792       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
   53793       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
   53794       ** lock, but not when obtaining the RESERVED lock.
   53795       */
   53796       rc = pagerLockDb(pPager, RESERVED_LOCK);
   53797       if( rc==SQLITE_OK && exFlag ){
   53798         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   53799       }
   53800     }
   53801 
   53802     if( rc==SQLITE_OK ){
   53803       /* Change to WRITER_LOCKED state.
   53804       **
   53805       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
   53806       ** when it has an open transaction, but never to DBMOD or FINISHED.
   53807       ** This is because in those states the code to roll back savepoint
   53808       ** transactions may copy data from the sub-journal into the database
   53809       ** file as well as into the page cache. Which would be incorrect in
   53810       ** WAL mode.
   53811       */
   53812       pPager->eState = PAGER_WRITER_LOCKED;
   53813       pPager->dbHintSize = pPager->dbSize;
   53814       pPager->dbFileSize = pPager->dbSize;
   53815       pPager->dbOrigSize = pPager->dbSize;
   53816       pPager->journalOff = 0;
   53817     }
   53818 
   53819     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
   53820     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
   53821     assert( assert_pager_state(pPager) );
   53822   }
   53823 
   53824   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
   53825   return rc;
   53826 }
   53827 
   53828 /*
   53829 ** Write page pPg onto the end of the rollback journal.
   53830 */
   53831 static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
   53832   Pager *pPager = pPg->pPager;
   53833   int rc;
   53834   u32 cksum;
   53835   char *pData2;
   53836   i64 iOff = pPager->journalOff;
   53837 
   53838   /* We should never write to the journal file the page that
   53839   ** contains the database locks.  The following assert verifies
   53840   ** that we do not. */
   53841   assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
   53842 
   53843   assert( pPager->journalHdr<=pPager->journalOff );
   53844   CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
   53845   cksum = pager_cksum(pPager, (u8*)pData2);
   53846 
   53847   /* Even if an IO or diskfull error occurs while journalling the
   53848   ** page in the block above, set the need-sync flag for the page.
   53849   ** Otherwise, when the transaction is rolled back, the logic in
   53850   ** playback_one_page() will think that the page needs to be restored
   53851   ** in the database file. And if an IO error occurs while doing so,
   53852   ** then corruption may follow.
   53853   */
   53854   pPg->flags |= PGHDR_NEED_SYNC;
   53855 
   53856   rc = write32bits(pPager->jfd, iOff, pPg->pgno);
   53857   if( rc!=SQLITE_OK ) return rc;
   53858   rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
   53859   if( rc!=SQLITE_OK ) return rc;
   53860   rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
   53861   if( rc!=SQLITE_OK ) return rc;
   53862 
   53863   IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
   53864            pPager->journalOff, pPager->pageSize));
   53865   PAGER_INCR(sqlite3_pager_writej_count);
   53866   PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
   53867        PAGERID(pPager), pPg->pgno,
   53868        ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
   53869 
   53870   pPager->journalOff += 8 + pPager->pageSize;
   53871   pPager->nRec++;
   53872   assert( pPager->pInJournal!=0 );
   53873   rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
   53874   testcase( rc==SQLITE_NOMEM );
   53875   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   53876   rc |= addToSavepointBitvecs(pPager, pPg->pgno);
   53877   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   53878   return rc;
   53879 }
   53880 
   53881 /*
   53882 ** Mark a single data page as writeable. The page is written into the
   53883 ** main journal or sub-journal as required. If the page is written into
   53884 ** one of the journals, the corresponding bit is set in the
   53885 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
   53886 ** of any open savepoints as appropriate.
   53887 */
   53888 static int pager_write(PgHdr *pPg){
   53889   Pager *pPager = pPg->pPager;
   53890   int rc = SQLITE_OK;
   53891 
   53892   /* This routine is not called unless a write-transaction has already
   53893   ** been started. The journal file may or may not be open at this point.
   53894   ** It is never called in the ERROR state.
   53895   */
   53896   assert( pPager->eState==PAGER_WRITER_LOCKED
   53897        || pPager->eState==PAGER_WRITER_CACHEMOD
   53898        || pPager->eState==PAGER_WRITER_DBMOD
   53899   );
   53900   assert( assert_pager_state(pPager) );
   53901   assert( pPager->errCode==0 );
   53902   assert( pPager->readOnly==0 );
   53903   CHECK_PAGE(pPg);
   53904 
   53905   /* The journal file needs to be opened. Higher level routines have already
   53906   ** obtained the necessary locks to begin the write-transaction, but the
   53907   ** rollback journal might not yet be open. Open it now if this is the case.
   53908   **
   53909   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
   53910   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
   53911   ** an error might occur and the pager would end up in WRITER_LOCKED state
   53912   ** with pages marked as dirty in the cache.
   53913   */
   53914   if( pPager->eState==PAGER_WRITER_LOCKED ){
   53915     rc = pager_open_journal(pPager);
   53916     if( rc!=SQLITE_OK ) return rc;
   53917   }
   53918   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   53919   assert( assert_pager_state(pPager) );
   53920 
   53921   /* Mark the page that is about to be modified as dirty. */
   53922   sqlite3PcacheMakeDirty(pPg);
   53923 
   53924   /* If a rollback journal is in use, them make sure the page that is about
   53925   ** to change is in the rollback journal, or if the page is a new page off
   53926   ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
   53927   */
   53928   assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
   53929   if( pPager->pInJournal!=0
   53930    && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
   53931   ){
   53932     assert( pagerUseWal(pPager)==0 );
   53933     if( pPg->pgno<=pPager->dbOrigSize ){
   53934       rc = pagerAddPageToRollbackJournal(pPg);
   53935       if( rc!=SQLITE_OK ){
   53936         return rc;
   53937       }
   53938     }else{
   53939       if( pPager->eState!=PAGER_WRITER_DBMOD ){
   53940         pPg->flags |= PGHDR_NEED_SYNC;
   53941       }
   53942       PAGERTRACE(("APPEND %d page %d needSync=%d\n",
   53943               PAGERID(pPager), pPg->pgno,
   53944              ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
   53945     }
   53946   }
   53947 
   53948   /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
   53949   ** and before writing the page into the rollback journal.  Wait until now,
   53950   ** after the page has been successfully journalled, before setting the
   53951   ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
   53952   */
   53953   pPg->flags |= PGHDR_WRITEABLE;
   53954 
   53955   /* If the statement journal is open and the page is not in it,
   53956   ** then write the page into the statement journal.
   53957   */
   53958   if( pPager->nSavepoint>0 ){
   53959     rc = subjournalPageIfRequired(pPg);
   53960   }
   53961 
   53962   /* Update the database size and return. */
   53963   if( pPager->dbSize<pPg->pgno ){
   53964     pPager->dbSize = pPg->pgno;
   53965   }
   53966   return rc;
   53967 }
   53968 
   53969 /*
   53970 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
   53971 ** is larger than the page size.  SQLite makes the (reasonable) assumption that
   53972 ** all bytes of a sector are written together by hardware.  Hence, all bytes of
   53973 ** a sector need to be journalled in case of a power loss in the middle of
   53974 ** a write.
   53975 **
   53976 ** Usually, the sector size is less than or equal to the page size, in which
   53977 ** case pages can be individually written.  This routine only runs in the
   53978 ** exceptional case where the page size is smaller than the sector size.
   53979 */
   53980 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
   53981   int rc = SQLITE_OK;          /* Return code */
   53982   Pgno nPageCount;             /* Total number of pages in database file */
   53983   Pgno pg1;                    /* First page of the sector pPg is located on. */
   53984   int nPage = 0;               /* Number of pages starting at pg1 to journal */
   53985   int ii;                      /* Loop counter */
   53986   int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
   53987   Pager *pPager = pPg->pPager; /* The pager that owns pPg */
   53988   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
   53989 
   53990   /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
   53991   ** a journal header to be written between the pages journaled by
   53992   ** this function.
   53993   */
   53994   assert( !MEMDB );
   53995   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
   53996   pPager->doNotSpill |= SPILLFLAG_NOSYNC;
   53997 
   53998   /* This trick assumes that both the page-size and sector-size are
   53999   ** an integer power of 2. It sets variable pg1 to the identifier
   54000   ** of the first page of the sector pPg is located on.
   54001   */
   54002   pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
   54003 
   54004   nPageCount = pPager->dbSize;
   54005   if( pPg->pgno>nPageCount ){
   54006     nPage = (pPg->pgno - pg1)+1;
   54007   }else if( (pg1+nPagePerSector-1)>nPageCount ){
   54008     nPage = nPageCount+1-pg1;
   54009   }else{
   54010     nPage = nPagePerSector;
   54011   }
   54012   assert(nPage>0);
   54013   assert(pg1<=pPg->pgno);
   54014   assert((pg1+nPage)>pPg->pgno);
   54015 
   54016   for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
   54017     Pgno pg = pg1+ii;
   54018     PgHdr *pPage;
   54019     if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
   54020       if( pg!=PAGER_MJ_PGNO(pPager) ){
   54021         rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
   54022         if( rc==SQLITE_OK ){
   54023           rc = pager_write(pPage);
   54024           if( pPage->flags&PGHDR_NEED_SYNC ){
   54025             needSync = 1;
   54026           }
   54027           sqlite3PagerUnrefNotNull(pPage);
   54028         }
   54029       }
   54030     }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
   54031       if( pPage->flags&PGHDR_NEED_SYNC ){
   54032         needSync = 1;
   54033       }
   54034       sqlite3PagerUnrefNotNull(pPage);
   54035     }
   54036   }
   54037 
   54038   /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   54039   ** starting at pg1, then it needs to be set for all of them. Because
   54040   ** writing to any of these nPage pages may damage the others, the
   54041   ** journal file must contain sync()ed copies of all of them
   54042   ** before any of them can be written out to the database file.
   54043   */
   54044   if( rc==SQLITE_OK && needSync ){
   54045     assert( !MEMDB );
   54046     for(ii=0; ii<nPage; ii++){
   54047       PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
   54048       if( pPage ){
   54049         pPage->flags |= PGHDR_NEED_SYNC;
   54050         sqlite3PagerUnrefNotNull(pPage);
   54051       }
   54052     }
   54053   }
   54054 
   54055   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
   54056   pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
   54057   return rc;
   54058 }
   54059 
   54060 /*
   54061 ** Mark a data page as writeable. This routine must be called before
   54062 ** making changes to a page. The caller must check the return value
   54063 ** of this function and be careful not to change any page data unless
   54064 ** this routine returns SQLITE_OK.
   54065 **
   54066 ** The difference between this function and pager_write() is that this
   54067 ** function also deals with the special case where 2 or more pages
   54068 ** fit on a single disk sector. In this case all co-resident pages
   54069 ** must have been written to the journal file before returning.
   54070 **
   54071 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
   54072 ** as appropriate. Otherwise, SQLITE_OK.
   54073 */
   54074 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
   54075   Pager *pPager = pPg->pPager;
   54076   assert( (pPg->flags & PGHDR_MMAP)==0 );
   54077   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   54078   assert( assert_pager_state(pPager) );
   54079   if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
   54080     if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
   54081     return SQLITE_OK;
   54082   }else if( pPager->errCode ){
   54083     return pPager->errCode;
   54084   }else if( pPager->sectorSize > (u32)pPager->pageSize ){
   54085     assert( pPager->tempFile==0 );
   54086     return pagerWriteLargeSector(pPg);
   54087   }else{
   54088     return pager_write(pPg);
   54089   }
   54090 }
   54091 
   54092 /*
   54093 ** Return TRUE if the page given in the argument was previously passed
   54094 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
   54095 ** to change the content of the page.
   54096 */
   54097 #ifndef NDEBUG
   54098 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
   54099   return pPg->flags & PGHDR_WRITEABLE;
   54100 }
   54101 #endif
   54102 
   54103 /*
   54104 ** A call to this routine tells the pager that it is not necessary to
   54105 ** write the information on page pPg back to the disk, even though
   54106 ** that page might be marked as dirty.  This happens, for example, when
   54107 ** the page has been added as a leaf of the freelist and so its
   54108 ** content no longer matters.
   54109 **
   54110 ** The overlying software layer calls this routine when all of the data
   54111 ** on the given page is unused. The pager marks the page as clean so
   54112 ** that it does not get written to disk.
   54113 **
   54114 ** Tests show that this optimization can quadruple the speed of large
   54115 ** DELETE operations.
   54116 **
   54117 ** This optimization cannot be used with a temp-file, as the page may
   54118 ** have been dirty at the start of the transaction. In that case, if
   54119 ** memory pressure forces page pPg out of the cache, the data does need
   54120 ** to be written out to disk so that it may be read back in if the
   54121 ** current transaction is rolled back.
   54122 */
   54123 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
   54124   Pager *pPager = pPg->pPager;
   54125   if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
   54126     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
   54127     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
   54128     pPg->flags |= PGHDR_DONT_WRITE;
   54129     pPg->flags &= ~PGHDR_WRITEABLE;
   54130     testcase( pPg->flags & PGHDR_NEED_SYNC );
   54131     pager_set_pagehash(pPg);
   54132   }
   54133 }
   54134 
   54135 /*
   54136 ** This routine is called to increment the value of the database file
   54137 ** change-counter, stored as a 4-byte big-endian integer starting at
   54138 ** byte offset 24 of the pager file.  The secondary change counter at
   54139 ** 92 is also updated, as is the SQLite version number at offset 96.
   54140 **
   54141 ** But this only happens if the pPager->changeCountDone flag is false.
   54142 ** To avoid excess churning of page 1, the update only happens once.
   54143 ** See also the pager_write_changecounter() routine that does an
   54144 ** unconditional update of the change counters.
   54145 **
   54146 ** If the isDirectMode flag is zero, then this is done by calling
   54147 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
   54148 ** page data. In this case the file will be updated when the current
   54149 ** transaction is committed.
   54150 **
   54151 ** The isDirectMode flag may only be non-zero if the library was compiled
   54152 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
   54153 ** if isDirect is non-zero, then the database file is updated directly
   54154 ** by writing an updated version of page 1 using a call to the
   54155 ** sqlite3OsWrite() function.
   54156 */
   54157 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
   54158   int rc = SQLITE_OK;
   54159 
   54160   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   54161        || pPager->eState==PAGER_WRITER_DBMOD
   54162   );
   54163   assert( assert_pager_state(pPager) );
   54164 
   54165   /* Declare and initialize constant integer 'isDirect'. If the
   54166   ** atomic-write optimization is enabled in this build, then isDirect
   54167   ** is initialized to the value passed as the isDirectMode parameter
   54168   ** to this function. Otherwise, it is always set to zero.
   54169   **
   54170   ** The idea is that if the atomic-write optimization is not
   54171   ** enabled at compile time, the compiler can omit the tests of
   54172   ** 'isDirect' below, as well as the block enclosed in the
   54173   ** "if( isDirect )" condition.
   54174   */
   54175 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
   54176 # define DIRECT_MODE 0
   54177   assert( isDirectMode==0 );
   54178   UNUSED_PARAMETER(isDirectMode);
   54179 #else
   54180 # define DIRECT_MODE isDirectMode
   54181 #endif
   54182 
   54183   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
   54184     PgHdr *pPgHdr;                /* Reference to page 1 */
   54185 
   54186     assert( !pPager->tempFile && isOpen(pPager->fd) );
   54187 
   54188     /* Open page 1 of the file for writing. */
   54189     rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
   54190     assert( pPgHdr==0 || rc==SQLITE_OK );
   54191 
   54192     /* If page one was fetched successfully, and this function is not
   54193     ** operating in direct-mode, make page 1 writable.  When not in
   54194     ** direct mode, page 1 is always held in cache and hence the PagerGet()
   54195     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
   54196     */
   54197     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
   54198       rc = sqlite3PagerWrite(pPgHdr);
   54199     }
   54200 
   54201     if( rc==SQLITE_OK ){
   54202       /* Actually do the update of the change counter */
   54203       pager_write_changecounter(pPgHdr);
   54204 
   54205       /* If running in direct mode, write the contents of page 1 to the file. */
   54206       if( DIRECT_MODE ){
   54207         const void *zBuf;
   54208         assert( pPager->dbFileSize>0 );
   54209         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
   54210         if( rc==SQLITE_OK ){
   54211           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
   54212           pPager->aStat[PAGER_STAT_WRITE]++;
   54213         }
   54214         if( rc==SQLITE_OK ){
   54215           /* Update the pager's copy of the change-counter. Otherwise, the
   54216           ** next time a read transaction is opened the cache will be
   54217           ** flushed (as the change-counter values will not match).  */
   54218           const void *pCopy = (const void *)&((const char *)zBuf)[24];
   54219           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
   54220           pPager->changeCountDone = 1;
   54221         }
   54222       }else{
   54223         pPager->changeCountDone = 1;
   54224       }
   54225     }
   54226 
   54227     /* Release the page reference. */
   54228     sqlite3PagerUnref(pPgHdr);
   54229   }
   54230   return rc;
   54231 }
   54232 
   54233 /*
   54234 ** Sync the database file to disk. This is a no-op for in-memory databases
   54235 ** or pages with the Pager.noSync flag set.
   54236 **
   54237 ** If successful, or if called on a pager for which it is a no-op, this
   54238 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
   54239 */
   54240 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
   54241   int rc = SQLITE_OK;
   54242 
   54243   if( isOpen(pPager->fd) ){
   54244     void *pArg = (void*)zMaster;
   54245     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
   54246     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   54247   }
   54248   if( rc==SQLITE_OK && !pPager->noSync ){
   54249     assert( !MEMDB );
   54250     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   54251   }
   54252   return rc;
   54253 }
   54254 
   54255 /*
   54256 ** This function may only be called while a write-transaction is active in
   54257 ** rollback. If the connection is in WAL mode, this call is a no-op.
   54258 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
   54259 ** the database file, an attempt is made to obtain one.
   54260 **
   54261 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
   54262 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
   54263 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
   54264 ** returned.
   54265 */
   54266 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
   54267   int rc = pPager->errCode;
   54268   assert( assert_pager_state(pPager) );
   54269   if( rc==SQLITE_OK ){
   54270     assert( pPager->eState==PAGER_WRITER_CACHEMOD
   54271          || pPager->eState==PAGER_WRITER_DBMOD
   54272          || pPager->eState==PAGER_WRITER_LOCKED
   54273     );
   54274     assert( assert_pager_state(pPager) );
   54275     if( 0==pagerUseWal(pPager) ){
   54276       rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   54277     }
   54278   }
   54279   return rc;
   54280 }
   54281 
   54282 /*
   54283 ** Sync the database file for the pager pPager. zMaster points to the name
   54284 ** of a master journal file that should be written into the individual
   54285 ** journal file. zMaster may be NULL, which is interpreted as no master
   54286 ** journal (a single database transaction).
   54287 **
   54288 ** This routine ensures that:
   54289 **
   54290 **   * The database file change-counter is updated,
   54291 **   * the journal is synced (unless the atomic-write optimization is used),
   54292 **   * all dirty pages are written to the database file,
   54293 **   * the database file is truncated (if required), and
   54294 **   * the database file synced.
   54295 **
   54296 ** The only thing that remains to commit the transaction is to finalize
   54297 ** (delete, truncate or zero the first part of) the journal file (or
   54298 ** delete the master journal file if specified).
   54299 **
   54300 ** Note that if zMaster==NULL, this does not overwrite a previous value
   54301 ** passed to an sqlite3PagerCommitPhaseOne() call.
   54302 **
   54303 ** If the final parameter - noSync - is true, then the database file itself
   54304 ** is not synced. The caller must call sqlite3PagerSync() directly to
   54305 ** sync the database file before calling CommitPhaseTwo() to delete the
   54306 ** journal file in this case.
   54307 */
   54308 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   54309   Pager *pPager,                  /* Pager object */
   54310   const char *zMaster,            /* If not NULL, the master journal name */
   54311   int noSync                      /* True to omit the xSync on the db file */
   54312 ){
   54313   int rc = SQLITE_OK;             /* Return code */
   54314 
   54315   assert( pPager->eState==PAGER_WRITER_LOCKED
   54316        || pPager->eState==PAGER_WRITER_CACHEMOD
   54317        || pPager->eState==PAGER_WRITER_DBMOD
   54318        || pPager->eState==PAGER_ERROR
   54319   );
   54320   assert( assert_pager_state(pPager) );
   54321 
   54322   /* If a prior error occurred, report that error again. */
   54323   if( NEVER(pPager->errCode) ) return pPager->errCode;
   54324 
   54325   /* Provide the ability to easily simulate an I/O error during testing */
   54326   if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
   54327 
   54328   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
   54329       pPager->zFilename, zMaster, pPager->dbSize));
   54330 
   54331   /* If no database changes have been made, return early. */
   54332   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
   54333 
   54334   assert( MEMDB==0 || pPager->tempFile );
   54335   assert( isOpen(pPager->fd) || pPager->tempFile );
   54336   if( 0==pagerFlushOnCommit(pPager, 1) ){
   54337     /* If this is an in-memory db, or no pages have been written to, or this
   54338     ** function has already been called, it is mostly a no-op.  However, any
   54339     ** backup in progress needs to be restarted.  */
   54340     sqlite3BackupRestart(pPager->pBackup);
   54341   }else{
   54342     if( pagerUseWal(pPager) ){
   54343       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
   54344       PgHdr *pPageOne = 0;
   54345       if( pList==0 ){
   54346         /* Must have at least one page for the WAL commit flag.
   54347         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
   54348         rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
   54349         pList = pPageOne;
   54350         pList->pDirty = 0;
   54351       }
   54352       assert( rc==SQLITE_OK );
   54353       if( ALWAYS(pList) ){
   54354         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
   54355       }
   54356       sqlite3PagerUnref(pPageOne);
   54357       if( rc==SQLITE_OK ){
   54358         sqlite3PcacheCleanAll(pPager->pPCache);
   54359       }
   54360     }else{
   54361       /* The bBatch boolean is true if the batch-atomic-write commit method
   54362       ** should be used.  No rollback journal is created if batch-atomic-write
   54363       ** is enabled.
   54364       */
   54365       sqlite3_file *fd = pPager->fd;
   54366 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   54367       const int bBatch = zMaster==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
   54368         && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
   54369         && !pPager->noSync
   54370         && sqlite3JournalIsInMemory(pPager->jfd);
   54371 #else
   54372 # define bBatch 0
   54373 #endif
   54374 
   54375 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   54376       /* The following block updates the change-counter. Exactly how it
   54377       ** does this depends on whether or not the atomic-update optimization
   54378       ** was enabled at compile time, and if this transaction meets the
   54379       ** runtime criteria to use the operation:
   54380       **
   54381       **    * The file-system supports the atomic-write property for
   54382       **      blocks of size page-size, and
   54383       **    * This commit is not part of a multi-file transaction, and
   54384       **    * Exactly one page has been modified and store in the journal file.
   54385       **
   54386       ** If the optimization was not enabled at compile time, then the
   54387       ** pager_incr_changecounter() function is called to update the change
   54388       ** counter in 'indirect-mode'. If the optimization is compiled in but
   54389       ** is not applicable to this transaction, call sqlite3JournalCreate()
   54390       ** to make sure the journal file has actually been created, then call
   54391       ** pager_incr_changecounter() to update the change-counter in indirect
   54392       ** mode.
   54393       **
   54394       ** Otherwise, if the optimization is both enabled and applicable,
   54395       ** then call pager_incr_changecounter() to update the change-counter
   54396       ** in 'direct' mode. In this case the journal file will never be
   54397       ** created for this transaction.
   54398       */
   54399       if( bBatch==0 ){
   54400         PgHdr *pPg;
   54401         assert( isOpen(pPager->jfd)
   54402             || pPager->journalMode==PAGER_JOURNALMODE_OFF
   54403             || pPager->journalMode==PAGER_JOURNALMODE_WAL
   54404             );
   54405         if( !zMaster && isOpen(pPager->jfd)
   54406          && pPager->journalOff==jrnlBufferSize(pPager)
   54407          && pPager->dbSize>=pPager->dbOrigSize
   54408          && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
   54409         ){
   54410           /* Update the db file change counter via the direct-write method. The
   54411           ** following call will modify the in-memory representation of page 1
   54412           ** to include the updated change counter and then write page 1
   54413           ** directly to the database file. Because of the atomic-write
   54414           ** property of the host file-system, this is safe.
   54415           */
   54416           rc = pager_incr_changecounter(pPager, 1);
   54417         }else{
   54418           rc = sqlite3JournalCreate(pPager->jfd);
   54419           if( rc==SQLITE_OK ){
   54420             rc = pager_incr_changecounter(pPager, 0);
   54421           }
   54422         }
   54423       }
   54424 #else
   54425 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   54426       if( zMaster ){
   54427         rc = sqlite3JournalCreate(pPager->jfd);
   54428         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   54429       }
   54430 #endif
   54431       rc = pager_incr_changecounter(pPager, 0);
   54432 #endif
   54433       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   54434 
   54435       /* Write the master journal name into the journal file. If a master
   54436       ** journal file name has already been written to the journal file,
   54437       ** or if zMaster is NULL (no master journal), then this call is a no-op.
   54438       */
   54439       rc = writeMasterJournal(pPager, zMaster);
   54440       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   54441 
   54442       /* Sync the journal file and write all dirty pages to the database.
   54443       ** If the atomic-update optimization is being used, this sync will not
   54444       ** create the journal file or perform any real IO.
   54445       **
   54446       ** Because the change-counter page was just modified, unless the
   54447       ** atomic-update optimization is used it is almost certain that the
   54448       ** journal requires a sync here. However, in locking_mode=exclusive
   54449       ** on a system under memory pressure it is just possible that this is
   54450       ** not the case. In this case it is likely enough that the redundant
   54451       ** xSync() call will be changed to a no-op by the OS anyhow.
   54452       */
   54453       rc = syncJournal(pPager, 0);
   54454       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   54455 
   54456       if( bBatch ){
   54457         /* The pager is now in DBMOD state. But regardless of what happens
   54458         ** next, attempting to play the journal back into the database would
   54459         ** be unsafe. Close it now to make sure that does not happen.  */
   54460         sqlite3OsClose(pPager->jfd);
   54461         rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
   54462         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   54463       }
   54464       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
   54465       if( bBatch ){
   54466         if( rc==SQLITE_OK ){
   54467           rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
   54468         }else{
   54469           sqlite3OsFileControl(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
   54470         }
   54471       }
   54472 
   54473       if( rc!=SQLITE_OK ){
   54474         assert( rc!=SQLITE_IOERR_BLOCKED );
   54475         goto commit_phase_one_exit;
   54476       }
   54477       sqlite3PcacheCleanAll(pPager->pPCache);
   54478 
   54479       /* If the file on disk is smaller than the database image, use
   54480       ** pager_truncate to grow the file here. This can happen if the database
   54481       ** image was extended as part of the current transaction and then the
   54482       ** last page in the db image moved to the free-list. In this case the
   54483       ** last page is never written out to disk, leaving the database file
   54484       ** undersized. Fix this now if it is the case.  */
   54485       if( pPager->dbSize>pPager->dbFileSize ){
   54486         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
   54487         assert( pPager->eState==PAGER_WRITER_DBMOD );
   54488         rc = pager_truncate(pPager, nNew);
   54489         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   54490       }
   54491 
   54492       /* Finally, sync the database file. */
   54493       if( !noSync ){
   54494         rc = sqlite3PagerSync(pPager, zMaster);
   54495       }
   54496       IOTRACE(("DBSYNC %p\n", pPager))
   54497     }
   54498   }
   54499 
   54500 commit_phase_one_exit:
   54501   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
   54502     pPager->eState = PAGER_WRITER_FINISHED;
   54503   }
   54504   return rc;
   54505 }
   54506 
   54507 
   54508 /*
   54509 ** When this function is called, the database file has been completely
   54510 ** updated to reflect the changes made by the current transaction and
   54511 ** synced to disk. The journal file still exists in the file-system
   54512 ** though, and if a failure occurs at this point it will eventually
   54513 ** be used as a hot-journal and the current transaction rolled back.
   54514 **
   54515 ** This function finalizes the journal file, either by deleting,
   54516 ** truncating or partially zeroing it, so that it cannot be used
   54517 ** for hot-journal rollback. Once this is done the transaction is
   54518 ** irrevocably committed.
   54519 **
   54520 ** If an error occurs, an IO error code is returned and the pager
   54521 ** moves into the error state. Otherwise, SQLITE_OK is returned.
   54522 */
   54523 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   54524   int rc = SQLITE_OK;                  /* Return code */
   54525 
   54526   /* This routine should not be called if a prior error has occurred.
   54527   ** But if (due to a coding error elsewhere in the system) it does get
   54528   ** called, just return the same error code without doing anything. */
   54529   if( NEVER(pPager->errCode) ) return pPager->errCode;
   54530 
   54531   assert( pPager->eState==PAGER_WRITER_LOCKED
   54532        || pPager->eState==PAGER_WRITER_FINISHED
   54533        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
   54534   );
   54535   assert( assert_pager_state(pPager) );
   54536 
   54537   /* An optimization. If the database was not actually modified during
   54538   ** this transaction, the pager is running in exclusive-mode and is
   54539   ** using persistent journals, then this function is a no-op.
   54540   **
   54541   ** The start of the journal file currently contains a single journal
   54542   ** header with the nRec field set to 0. If such a journal is used as
   54543   ** a hot-journal during hot-journal rollback, 0 changes will be made
   54544   ** to the database file. So there is no need to zero the journal
   54545   ** header. Since the pager is in exclusive mode, there is no need
   54546   ** to drop any locks either.
   54547   */
   54548   if( pPager->eState==PAGER_WRITER_LOCKED
   54549    && pPager->exclusiveMode
   54550    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   54551   ){
   54552     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
   54553     pPager->eState = PAGER_READER;
   54554     return SQLITE_OK;
   54555   }
   54556 
   54557   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
   54558   pPager->iDataVersion++;
   54559   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
   54560   return pager_error(pPager, rc);
   54561 }
   54562 
   54563 /*
   54564 ** If a write transaction is open, then all changes made within the
   54565 ** transaction are reverted and the current write-transaction is closed.
   54566 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
   54567 ** state if an error occurs.
   54568 **
   54569 ** If the pager is already in PAGER_ERROR state when this function is called,
   54570 ** it returns Pager.errCode immediately. No work is performed in this case.
   54571 **
   54572 ** Otherwise, in rollback mode, this function performs two functions:
   54573 **
   54574 **   1) It rolls back the journal file, restoring all database file and
   54575 **      in-memory cache pages to the state they were in when the transaction
   54576 **      was opened, and
   54577 **
   54578 **   2) It finalizes the journal file, so that it is not used for hot
   54579 **      rollback at any point in the future.
   54580 **
   54581 ** Finalization of the journal file (task 2) is only performed if the
   54582 ** rollback is successful.
   54583 **
   54584 ** In WAL mode, all cache-entries containing data modified within the
   54585 ** current transaction are either expelled from the cache or reverted to
   54586 ** their pre-transaction state by re-reading data from the database or
   54587 ** WAL files. The WAL transaction is then closed.
   54588 */
   54589 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   54590   int rc = SQLITE_OK;                  /* Return code */
   54591   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
   54592 
   54593   /* PagerRollback() is a no-op if called in READER or OPEN state. If
   54594   ** the pager is already in the ERROR state, the rollback is not
   54595   ** attempted here. Instead, the error code is returned to the caller.
   54596   */
   54597   assert( assert_pager_state(pPager) );
   54598   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
   54599   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
   54600 
   54601   if( pagerUseWal(pPager) ){
   54602     int rc2;
   54603     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
   54604     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
   54605     if( rc==SQLITE_OK ) rc = rc2;
   54606   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
   54607     int eState = pPager->eState;
   54608     rc = pager_end_transaction(pPager, 0, 0);
   54609     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
   54610       /* This can happen using journal_mode=off. Move the pager to the error
   54611       ** state to indicate that the contents of the cache may not be trusted.
   54612       ** Any active readers will get SQLITE_ABORT.
   54613       */
   54614       pPager->errCode = SQLITE_ABORT;
   54615       pPager->eState = PAGER_ERROR;
   54616       setGetterMethod(pPager);
   54617       return rc;
   54618     }
   54619   }else{
   54620     rc = pager_playback(pPager, 0);
   54621   }
   54622 
   54623   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
   54624   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
   54625           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
   54626           || rc==SQLITE_CANTOPEN
   54627   );
   54628 
   54629   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
   54630   ** cache. So call pager_error() on the way out to make any error persistent.
   54631   */
   54632   return pager_error(pPager, rc);
   54633 }
   54634 
   54635 /*
   54636 ** Return TRUE if the database file is opened read-only.  Return FALSE
   54637 ** if the database is (in theory) writable.
   54638 */
   54639 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
   54640   return pPager->readOnly;
   54641 }
   54642 
   54643 #ifdef SQLITE_DEBUG
   54644 /*
   54645 ** Return the sum of the reference counts for all pages held by pPager.
   54646 */
   54647 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
   54648   return sqlite3PcacheRefCount(pPager->pPCache);
   54649 }
   54650 #endif
   54651 
   54652 /*
   54653 ** Return the approximate number of bytes of memory currently
   54654 ** used by the pager and its associated cache.
   54655 */
   54656 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
   54657   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
   54658                                      + 5*sizeof(void*);
   54659   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
   54660            + sqlite3MallocSize(pPager)
   54661            + pPager->pageSize;
   54662 }
   54663 
   54664 /*
   54665 ** Return the number of references to the specified page.
   54666 */
   54667 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
   54668   return sqlite3PcachePageRefcount(pPage);
   54669 }
   54670 
   54671 #ifdef SQLITE_TEST
   54672 /*
   54673 ** This routine is used for testing and analysis only.
   54674 */
   54675 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
   54676   static int a[11];
   54677   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
   54678   a[1] = sqlite3PcachePagecount(pPager->pPCache);
   54679   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
   54680   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
   54681   a[4] = pPager->eState;
   54682   a[5] = pPager->errCode;
   54683   a[6] = pPager->aStat[PAGER_STAT_HIT];
   54684   a[7] = pPager->aStat[PAGER_STAT_MISS];
   54685   a[8] = 0;  /* Used to be pPager->nOvfl */
   54686   a[9] = pPager->nRead;
   54687   a[10] = pPager->aStat[PAGER_STAT_WRITE];
   54688   return a;
   54689 }
   54690 #endif
   54691 
   54692 /*
   54693 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
   54694 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
   54695 ** current cache hit or miss count, according to the value of eStat. If the
   54696 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
   54697 ** returning.
   54698 */
   54699 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
   54700 
   54701   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
   54702        || eStat==SQLITE_DBSTATUS_CACHE_MISS
   54703        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
   54704   );
   54705 
   54706   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
   54707   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
   54708   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
   54709 
   54710   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
   54711   if( reset ){
   54712     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
   54713   }
   54714 }
   54715 
   54716 /*
   54717 ** Return true if this is an in-memory or temp-file backed pager.
   54718 */
   54719 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
   54720   return pPager->tempFile;
   54721 }
   54722 
   54723 /*
   54724 ** Check that there are at least nSavepoint savepoints open. If there are
   54725 ** currently less than nSavepoints open, then open one or more savepoints
   54726 ** to make up the difference. If the number of savepoints is already
   54727 ** equal to nSavepoint, then this function is a no-op.
   54728 **
   54729 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
   54730 ** occurs while opening the sub-journal file, then an IO error code is
   54731 ** returned. Otherwise, SQLITE_OK.
   54732 */
   54733 static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
   54734   int rc = SQLITE_OK;                       /* Return code */
   54735   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
   54736   int ii;                                   /* Iterator variable */
   54737   PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
   54738 
   54739   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   54740   assert( assert_pager_state(pPager) );
   54741   assert( nSavepoint>nCurrent && pPager->useJournal );
   54742 
   54743   /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
   54744   ** if the allocation fails. Otherwise, zero the new portion in case a
   54745   ** malloc failure occurs while populating it in the for(...) loop below.
   54746   */
   54747   aNew = (PagerSavepoint *)sqlite3Realloc(
   54748       pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
   54749   );
   54750   if( !aNew ){
   54751     return SQLITE_NOMEM_BKPT;
   54752   }
   54753   memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
   54754   pPager->aSavepoint = aNew;
   54755 
   54756   /* Populate the PagerSavepoint structures just allocated. */
   54757   for(ii=nCurrent; ii<nSavepoint; ii++){
   54758     aNew[ii].nOrig = pPager->dbSize;
   54759     if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
   54760       aNew[ii].iOffset = pPager->journalOff;
   54761     }else{
   54762       aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
   54763     }
   54764     aNew[ii].iSubRec = pPager->nSubRec;
   54765     aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
   54766     if( !aNew[ii].pInSavepoint ){
   54767       return SQLITE_NOMEM_BKPT;
   54768     }
   54769     if( pagerUseWal(pPager) ){
   54770       sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
   54771     }
   54772     pPager->nSavepoint = ii+1;
   54773   }
   54774   assert( pPager->nSavepoint==nSavepoint );
   54775   assertTruncateConstraint(pPager);
   54776   return rc;
   54777 }
   54778 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
   54779   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   54780   assert( assert_pager_state(pPager) );
   54781 
   54782   if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
   54783     return pagerOpenSavepoint(pPager, nSavepoint);
   54784   }else{
   54785     return SQLITE_OK;
   54786   }
   54787 }
   54788 
   54789 
   54790 /*
   54791 ** This function is called to rollback or release (commit) a savepoint.
   54792 ** The savepoint to release or rollback need not be the most recently
   54793 ** created savepoint.
   54794 **
   54795 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
   54796 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
   54797 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
   54798 ** that have occurred since the specified savepoint was created.
   54799 **
   54800 ** The savepoint to rollback or release is identified by parameter
   54801 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
   54802 ** (the first created). A value of (Pager.nSavepoint-1) means operate
   54803 ** on the most recently created savepoint. If iSavepoint is greater than
   54804 ** (Pager.nSavepoint-1), then this function is a no-op.
   54805 **
   54806 ** If a negative value is passed to this function, then the current
   54807 ** transaction is rolled back. This is different to calling
   54808 ** sqlite3PagerRollback() because this function does not terminate
   54809 ** the transaction or unlock the database, it just restores the
   54810 ** contents of the database to its original state.
   54811 **
   54812 ** In any case, all savepoints with an index greater than iSavepoint
   54813 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
   54814 ** then savepoint iSavepoint is also destroyed.
   54815 **
   54816 ** This function may return SQLITE_NOMEM if a memory allocation fails,
   54817 ** or an IO error code if an IO error occurs while rolling back a
   54818 ** savepoint. If no errors occur, SQLITE_OK is returned.
   54819 */
   54820 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   54821   int rc = pPager->errCode;
   54822 
   54823 #ifdef SQLITE_ENABLE_ZIPVFS
   54824   if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
   54825 #endif
   54826 
   54827   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   54828   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
   54829 
   54830   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
   54831     int ii;            /* Iterator variable */
   54832     int nNew;          /* Number of remaining savepoints after this op. */
   54833 
   54834     /* Figure out how many savepoints will still be active after this
   54835     ** operation. Store this value in nNew. Then free resources associated
   54836     ** with any savepoints that are destroyed by this operation.
   54837     */
   54838     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
   54839     for(ii=nNew; ii<pPager->nSavepoint; ii++){
   54840       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   54841     }
   54842     pPager->nSavepoint = nNew;
   54843 
   54844     /* If this is a release of the outermost savepoint, truncate
   54845     ** the sub-journal to zero bytes in size. */
   54846     if( op==SAVEPOINT_RELEASE ){
   54847       if( nNew==0 && isOpen(pPager->sjfd) ){
   54848         /* Only truncate if it is an in-memory sub-journal. */
   54849         if( sqlite3JournalIsInMemory(pPager->sjfd) ){
   54850           rc = sqlite3OsTruncate(pPager->sjfd, 0);
   54851           assert( rc==SQLITE_OK );
   54852         }
   54853         pPager->nSubRec = 0;
   54854       }
   54855     }
   54856     /* Else this is a rollback operation, playback the specified savepoint.
   54857     ** If this is a temp-file, it is possible that the journal file has
   54858     ** not yet been opened. In this case there have been no changes to
   54859     ** the database file, so the playback operation can be skipped.
   54860     */
   54861     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
   54862       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
   54863       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
   54864       assert(rc!=SQLITE_DONE);
   54865     }
   54866 
   54867 #ifdef SQLITE_ENABLE_ZIPVFS
   54868     /* If the cache has been modified but the savepoint cannot be rolled
   54869     ** back journal_mode=off, put the pager in the error state. This way,
   54870     ** if the VFS used by this pager includes ZipVFS, the entire transaction
   54871     ** can be rolled back at the ZipVFS level.  */
   54872     else if(
   54873         pPager->journalMode==PAGER_JOURNALMODE_OFF
   54874      && pPager->eState>=PAGER_WRITER_CACHEMOD
   54875     ){
   54876       pPager->errCode = SQLITE_ABORT;
   54877       pPager->eState = PAGER_ERROR;
   54878       setGetterMethod(pPager);
   54879     }
   54880 #endif
   54881   }
   54882 
   54883   return rc;
   54884 }
   54885 
   54886 /*
   54887 ** Return the full pathname of the database file.
   54888 **
   54889 ** Except, if the pager is in-memory only, then return an empty string if
   54890 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
   54891 ** used to report the filename to the user, for compatibility with legacy
   54892 ** behavior.  But when the Btree needs to know the filename for matching to
   54893 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
   54894 ** participate in shared-cache.
   54895 */
   54896 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
   54897   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
   54898 }
   54899 
   54900 /*
   54901 ** Return the VFS structure for the pager.
   54902 */
   54903 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
   54904   return pPager->pVfs;
   54905 }
   54906 
   54907 /*
   54908 ** Return the file handle for the database file associated
   54909 ** with the pager.  This might return NULL if the file has
   54910 ** not yet been opened.
   54911 */
   54912 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   54913   return pPager->fd;
   54914 }
   54915 
   54916 /*
   54917 ** Return the file handle for the journal file (if it exists).
   54918 ** This will be either the rollback journal or the WAL file.
   54919 */
   54920 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
   54921 #if SQLITE_OMIT_WAL
   54922   return pPager->jfd;
   54923 #else
   54924   return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
   54925 #endif
   54926 }
   54927 
   54928 /*
   54929 ** Return the full pathname of the journal file.
   54930 */
   54931 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   54932   return pPager->zJournal;
   54933 }
   54934 
   54935 #ifdef SQLITE_HAS_CODEC
   54936 /*
   54937 ** Set or retrieve the codec for this pager
   54938 */
   54939 SQLITE_PRIVATE void sqlite3PagerSetCodec(
   54940   Pager *pPager,
   54941   void *(*xCodec)(void*,void*,Pgno,int),
   54942   void (*xCodecSizeChng)(void*,int,int),
   54943   void (*xCodecFree)(void*),
   54944   void *pCodec
   54945 ){
   54946   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   54947   pPager->xCodec = pPager->memDb ? 0 : xCodec;
   54948   pPager->xCodecSizeChng = xCodecSizeChng;
   54949   pPager->xCodecFree = xCodecFree;
   54950   pPager->pCodec = pCodec;
   54951   setGetterMethod(pPager);
   54952   pagerReportSize(pPager);
   54953 }
   54954 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
   54955   return pPager->pCodec;
   54956 }
   54957 
   54958 /*
   54959 ** This function is called by the wal module when writing page content
   54960 ** into the log file.
   54961 **
   54962 ** This function returns a pointer to a buffer containing the encrypted
   54963 ** page content. If a malloc fails, this function may return NULL.
   54964 */
   54965 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
   54966   void *aData = 0;
   54967   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
   54968   return aData;
   54969 }
   54970 
   54971 /*
   54972 ** Return the current pager state
   54973 */
   54974 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
   54975   return pPager->eState;
   54976 }
   54977 #endif /* SQLITE_HAS_CODEC */
   54978 
   54979 #ifndef SQLITE_OMIT_AUTOVACUUM
   54980 /*
   54981 ** Move the page pPg to location pgno in the file.
   54982 **
   54983 ** There must be no references to the page previously located at
   54984 ** pgno (which we call pPgOld) though that page is allowed to be
   54985 ** in cache.  If the page previously located at pgno is not already
   54986 ** in the rollback journal, it is not put there by by this routine.
   54987 **
   54988 ** References to the page pPg remain valid. Updating any
   54989 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
   54990 ** allocated along with the page) is the responsibility of the caller.
   54991 **
   54992 ** A transaction must be active when this routine is called. It used to be
   54993 ** required that a statement transaction was not active, but this restriction
   54994 ** has been removed (CREATE INDEX needs to move a page when a statement
   54995 ** transaction is active).
   54996 **
   54997 ** If the fourth argument, isCommit, is non-zero, then this page is being
   54998 ** moved as part of a database reorganization just before the transaction
   54999 ** is being committed. In this case, it is guaranteed that the database page
   55000 ** pPg refers to will not be written to again within this transaction.
   55001 **
   55002 ** This function may return SQLITE_NOMEM or an IO error code if an error
   55003 ** occurs. Otherwise, it returns SQLITE_OK.
   55004 */
   55005 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
   55006   PgHdr *pPgOld;               /* The page being overwritten. */
   55007   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
   55008   int rc;                      /* Return code */
   55009   Pgno origPgno;               /* The original page number */
   55010 
   55011   assert( pPg->nRef>0 );
   55012   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   55013        || pPager->eState==PAGER_WRITER_DBMOD
   55014   );
   55015   assert( assert_pager_state(pPager) );
   55016 
   55017   /* In order to be able to rollback, an in-memory database must journal
   55018   ** the page we are moving from.
   55019   */
   55020   assert( pPager->tempFile || !MEMDB );
   55021   if( pPager->tempFile ){
   55022     rc = sqlite3PagerWrite(pPg);
   55023     if( rc ) return rc;
   55024   }
   55025 
   55026   /* If the page being moved is dirty and has not been saved by the latest
   55027   ** savepoint, then save the current contents of the page into the
   55028   ** sub-journal now. This is required to handle the following scenario:
   55029   **
   55030   **   BEGIN;
   55031   **     <journal page X, then modify it in memory>
   55032   **     SAVEPOINT one;
   55033   **       <Move page X to location Y>
   55034   **     ROLLBACK TO one;
   55035   **
   55036   ** If page X were not written to the sub-journal here, it would not
   55037   ** be possible to restore its contents when the "ROLLBACK TO one"
   55038   ** statement were is processed.
   55039   **
   55040   ** subjournalPage() may need to allocate space to store pPg->pgno into
   55041   ** one or more savepoint bitvecs. This is the reason this function
   55042   ** may return SQLITE_NOMEM.
   55043   */
   55044   if( (pPg->flags & PGHDR_DIRTY)!=0
   55045    && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
   55046   ){
   55047     return rc;
   55048   }
   55049 
   55050   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
   55051       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   55052   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
   55053 
   55054   /* If the journal needs to be sync()ed before page pPg->pgno can
   55055   ** be written to, store pPg->pgno in local variable needSyncPgno.
   55056   **
   55057   ** If the isCommit flag is set, there is no need to remember that
   55058   ** the journal needs to be sync()ed before database page pPg->pgno
   55059   ** can be written to. The caller has already promised not to write to it.
   55060   */
   55061   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
   55062     needSyncPgno = pPg->pgno;
   55063     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
   55064             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
   55065     assert( pPg->flags&PGHDR_DIRTY );
   55066   }
   55067 
   55068   /* If the cache contains a page with page-number pgno, remove it
   55069   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
   55070   ** page pgno before the 'move' operation, it needs to be retained
   55071   ** for the page moved there.
   55072   */
   55073   pPg->flags &= ~PGHDR_NEED_SYNC;
   55074   pPgOld = sqlite3PagerLookup(pPager, pgno);
   55075   assert( !pPgOld || pPgOld->nRef==1 );
   55076   if( pPgOld ){
   55077     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
   55078     if( pPager->tempFile ){
   55079       /* Do not discard pages from an in-memory database since we might
   55080       ** need to rollback later.  Just move the page out of the way. */
   55081       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
   55082     }else{
   55083       sqlite3PcacheDrop(pPgOld);
   55084     }
   55085   }
   55086 
   55087   origPgno = pPg->pgno;
   55088   sqlite3PcacheMove(pPg, pgno);
   55089   sqlite3PcacheMakeDirty(pPg);
   55090 
   55091   /* For an in-memory database, make sure the original page continues
   55092   ** to exist, in case the transaction needs to roll back.  Use pPgOld
   55093   ** as the original page since it has already been allocated.
   55094   */
   55095   if( pPager->tempFile && pPgOld ){
   55096     sqlite3PcacheMove(pPgOld, origPgno);
   55097     sqlite3PagerUnrefNotNull(pPgOld);
   55098   }
   55099 
   55100   if( needSyncPgno ){
   55101     /* If needSyncPgno is non-zero, then the journal file needs to be
   55102     ** sync()ed before any data is written to database file page needSyncPgno.
   55103     ** Currently, no such page exists in the page-cache and the
   55104     ** "is journaled" bitvec flag has been set. This needs to be remedied by
   55105     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
   55106     ** flag.
   55107     **
   55108     ** If the attempt to load the page into the page-cache fails, (due
   55109     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
   55110     ** array. Otherwise, if the page is loaded and written again in
   55111     ** this transaction, it may be written to the database file before
   55112     ** it is synced into the journal file. This way, it may end up in
   55113     ** the journal file twice, but that is not a problem.
   55114     */
   55115     PgHdr *pPgHdr;
   55116     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
   55117     if( rc!=SQLITE_OK ){
   55118       if( needSyncPgno<=pPager->dbOrigSize ){
   55119         assert( pPager->pTmpSpace!=0 );
   55120         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
   55121       }
   55122       return rc;
   55123     }
   55124     pPgHdr->flags |= PGHDR_NEED_SYNC;
   55125     sqlite3PcacheMakeDirty(pPgHdr);
   55126     sqlite3PagerUnrefNotNull(pPgHdr);
   55127   }
   55128 
   55129   return SQLITE_OK;
   55130 }
   55131 #endif
   55132 
   55133 /*
   55134 ** The page handle passed as the first argument refers to a dirty page
   55135 ** with a page number other than iNew. This function changes the page's
   55136 ** page number to iNew and sets the value of the PgHdr.flags field to
   55137 ** the value passed as the third parameter.
   55138 */
   55139 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
   55140   assert( pPg->pgno!=iNew );
   55141   pPg->flags = flags;
   55142   sqlite3PcacheMove(pPg, iNew);
   55143 }
   55144 
   55145 /*
   55146 ** Return a pointer to the data for the specified page.
   55147 */
   55148 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
   55149   assert( pPg->nRef>0 || pPg->pPager->memDb );
   55150   return pPg->pData;
   55151 }
   55152 
   55153 /*
   55154 ** Return a pointer to the Pager.nExtra bytes of "extra" space
   55155 ** allocated along with the specified page.
   55156 */
   55157 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
   55158   return pPg->pExtra;
   55159 }
   55160 
   55161 /*
   55162 ** Get/set the locking-mode for this pager. Parameter eMode must be one
   55163 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
   55164 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
   55165 ** the locking-mode is set to the value specified.
   55166 **
   55167 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
   55168 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
   55169 ** locking-mode.
   55170 */
   55171 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
   55172   assert( eMode==PAGER_LOCKINGMODE_QUERY
   55173             || eMode==PAGER_LOCKINGMODE_NORMAL
   55174             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   55175   assert( PAGER_LOCKINGMODE_QUERY<0 );
   55176   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
   55177   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
   55178   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
   55179     pPager->exclusiveMode = (u8)eMode;
   55180   }
   55181   return (int)pPager->exclusiveMode;
   55182 }
   55183 
   55184 /*
   55185 ** Set the journal-mode for this pager. Parameter eMode must be one of:
   55186 **
   55187 **    PAGER_JOURNALMODE_DELETE
   55188 **    PAGER_JOURNALMODE_TRUNCATE
   55189 **    PAGER_JOURNALMODE_PERSIST
   55190 **    PAGER_JOURNALMODE_OFF
   55191 **    PAGER_JOURNALMODE_MEMORY
   55192 **    PAGER_JOURNALMODE_WAL
   55193 **
   55194 ** The journalmode is set to the value specified if the change is allowed.
   55195 ** The change may be disallowed for the following reasons:
   55196 **
   55197 **   *  An in-memory database can only have its journal_mode set to _OFF
   55198 **      or _MEMORY.
   55199 **
   55200 **   *  Temporary databases cannot have _WAL journalmode.
   55201 **
   55202 ** The returned indicate the current (possibly updated) journal-mode.
   55203 */
   55204 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   55205   u8 eOld = pPager->journalMode;    /* Prior journalmode */
   55206 
   55207 #ifdef SQLITE_DEBUG
   55208   /* The print_pager_state() routine is intended to be used by the debugger
   55209   ** only.  We invoke it once here to suppress a compiler warning. */
   55210   print_pager_state(pPager);
   55211 #endif
   55212 
   55213 
   55214   /* The eMode parameter is always valid */
   55215   assert(      eMode==PAGER_JOURNALMODE_DELETE
   55216             || eMode==PAGER_JOURNALMODE_TRUNCATE
   55217             || eMode==PAGER_JOURNALMODE_PERSIST
   55218             || eMode==PAGER_JOURNALMODE_OFF
   55219             || eMode==PAGER_JOURNALMODE_WAL
   55220             || eMode==PAGER_JOURNALMODE_MEMORY );
   55221 
   55222   /* This routine is only called from the OP_JournalMode opcode, and
   55223   ** the logic there will never allow a temporary file to be changed
   55224   ** to WAL mode.
   55225   */
   55226   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
   55227 
   55228   /* Do allow the journalmode of an in-memory database to be set to
   55229   ** anything other than MEMORY or OFF
   55230   */
   55231   if( MEMDB ){
   55232     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
   55233     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
   55234       eMode = eOld;
   55235     }
   55236   }
   55237 
   55238   if( eMode!=eOld ){
   55239 
   55240     /* Change the journal mode. */
   55241     assert( pPager->eState!=PAGER_ERROR );
   55242     pPager->journalMode = (u8)eMode;
   55243 
   55244     /* When transistioning from TRUNCATE or PERSIST to any other journal
   55245     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
   55246     ** delete the journal file.
   55247     */
   55248     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   55249     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
   55250     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
   55251     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
   55252     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
   55253     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
   55254 
   55255     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
   55256     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
   55257 
   55258       /* In this case we would like to delete the journal file. If it is
   55259       ** not possible, then that is not a problem. Deleting the journal file
   55260       ** here is an optimization only.
   55261       **
   55262       ** Before deleting the journal file, obtain a RESERVED lock on the
   55263       ** database file. This ensures that the journal file is not deleted
   55264       ** while it is in use by some other client.
   55265       */
   55266       sqlite3OsClose(pPager->jfd);
   55267       if( pPager->eLock>=RESERVED_LOCK ){
   55268         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   55269       }else{
   55270         int rc = SQLITE_OK;
   55271         int state = pPager->eState;
   55272         assert( state==PAGER_OPEN || state==PAGER_READER );
   55273         if( state==PAGER_OPEN ){
   55274           rc = sqlite3PagerSharedLock(pPager);
   55275         }
   55276         if( pPager->eState==PAGER_READER ){
   55277           assert( rc==SQLITE_OK );
   55278           rc = pagerLockDb(pPager, RESERVED_LOCK);
   55279         }
   55280         if( rc==SQLITE_OK ){
   55281           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   55282         }
   55283         if( rc==SQLITE_OK && state==PAGER_READER ){
   55284           pagerUnlockDb(pPager, SHARED_LOCK);
   55285         }else if( state==PAGER_OPEN ){
   55286           pager_unlock(pPager);
   55287         }
   55288         assert( state==pPager->eState );
   55289       }
   55290     }else if( eMode==PAGER_JOURNALMODE_OFF ){
   55291       sqlite3OsClose(pPager->jfd);
   55292     }
   55293   }
   55294 
   55295   /* Return the new journal mode */
   55296   return (int)pPager->journalMode;
   55297 }
   55298 
   55299 /*
   55300 ** Return the current journal mode.
   55301 */
   55302 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
   55303   return (int)pPager->journalMode;
   55304 }
   55305 
   55306 /*
   55307 ** Return TRUE if the pager is in a state where it is OK to change the
   55308 ** journalmode.  Journalmode changes can only happen when the database
   55309 ** is unmodified.
   55310 */
   55311 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
   55312   assert( assert_pager_state(pPager) );
   55313   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
   55314   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
   55315   return 1;
   55316 }
   55317 
   55318 /*
   55319 ** Get/set the size-limit used for persistent journal files.
   55320 **
   55321 ** Setting the size limit to -1 means no limit is enforced.
   55322 ** An attempt to set a limit smaller than -1 is a no-op.
   55323 */
   55324 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
   55325   if( iLimit>=-1 ){
   55326     pPager->journalSizeLimit = iLimit;
   55327     sqlite3WalLimit(pPager->pWal, iLimit);
   55328   }
   55329   return pPager->journalSizeLimit;
   55330 }
   55331 
   55332 /*
   55333 ** Return a pointer to the pPager->pBackup variable. The backup module
   55334 ** in backup.c maintains the content of this variable. This module
   55335 ** uses it opaquely as an argument to sqlite3BackupRestart() and
   55336 ** sqlite3BackupUpdate() only.
   55337 */
   55338 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
   55339   return &pPager->pBackup;
   55340 }
   55341 
   55342 #ifndef SQLITE_OMIT_VACUUM
   55343 /*
   55344 ** Unless this is an in-memory or temporary database, clear the pager cache.
   55345 */
   55346 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
   55347   assert( MEMDB==0 || pPager->tempFile );
   55348   if( pPager->tempFile==0 ) pager_reset(pPager);
   55349 }
   55350 #endif
   55351 
   55352 
   55353 #ifndef SQLITE_OMIT_WAL
   55354 /*
   55355 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
   55356 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
   55357 ** or wal_blocking_checkpoint() API functions.
   55358 **
   55359 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   55360 */
   55361 SQLITE_PRIVATE int sqlite3PagerCheckpoint(
   55362   Pager *pPager,                  /* Checkpoint on this pager */
   55363   sqlite3 *db,                    /* Db handle used to check for interrupts */
   55364   int eMode,                      /* Type of checkpoint */
   55365   int *pnLog,                     /* OUT: Final number of frames in log */
   55366   int *pnCkpt                     /* OUT: Final number of checkpointed frames */
   55367 ){
   55368   int rc = SQLITE_OK;
   55369   if( pPager->pWal ){
   55370     rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
   55371         (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
   55372         pPager->pBusyHandlerArg,
   55373         pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
   55374         pnLog, pnCkpt
   55375     );
   55376   }
   55377   return rc;
   55378 }
   55379 
   55380 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
   55381   return sqlite3WalCallback(pPager->pWal);
   55382 }
   55383 
   55384 /*
   55385 ** Return true if the underlying VFS for the given pager supports the
   55386 ** primitives necessary for write-ahead logging.
   55387 */
   55388 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
   55389   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
   55390   if( pPager->noLock ) return 0;
   55391   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
   55392 }
   55393 
   55394 /*
   55395 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
   55396 ** is obtained instead, immediately release it.
   55397 */
   55398 static int pagerExclusiveLock(Pager *pPager){
   55399   int rc;                         /* Return code */
   55400 
   55401   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   55402   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   55403   if( rc!=SQLITE_OK ){
   55404     /* If the attempt to grab the exclusive lock failed, release the
   55405     ** pending lock that may have been obtained instead.  */
   55406     pagerUnlockDb(pPager, SHARED_LOCK);
   55407   }
   55408 
   55409   return rc;
   55410 }
   55411 
   55412 /*
   55413 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
   55414 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
   55415 ** lock on the database file and use heap-memory to store the wal-index
   55416 ** in. Otherwise, use the normal shared-memory.
   55417 */
   55418 static int pagerOpenWal(Pager *pPager){
   55419   int rc = SQLITE_OK;
   55420 
   55421   assert( pPager->pWal==0 && pPager->tempFile==0 );
   55422   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   55423 
   55424   /* If the pager is already in exclusive-mode, the WAL module will use
   55425   ** heap-memory for the wal-index instead of the VFS shared-memory
   55426   ** implementation. Take the exclusive lock now, before opening the WAL
   55427   ** file, to make sure this is safe.
   55428   */
   55429   if( pPager->exclusiveMode ){
   55430     rc = pagerExclusiveLock(pPager);
   55431   }
   55432 
   55433   /* Open the connection to the log file. If this operation fails,
   55434   ** (e.g. due to malloc() failure), return an error code.
   55435   */
   55436   if( rc==SQLITE_OK ){
   55437     rc = sqlite3WalOpen(pPager->pVfs,
   55438         pPager->fd, pPager->zWal, pPager->exclusiveMode,
   55439         pPager->journalSizeLimit, &pPager->pWal
   55440     );
   55441   }
   55442   pagerFixMaplimit(pPager);
   55443 
   55444   return rc;
   55445 }
   55446 
   55447 
   55448 /*
   55449 ** The caller must be holding a SHARED lock on the database file to call
   55450 ** this function.
   55451 **
   55452 ** If the pager passed as the first argument is open on a real database
   55453 ** file (not a temp file or an in-memory database), and the WAL file
   55454 ** is not already open, make an attempt to open it now. If successful,
   55455 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
   55456 ** not support the xShmXXX() methods, return an error code. *pbOpen is
   55457 ** not modified in either case.
   55458 **
   55459 ** If the pager is open on a temp-file (or in-memory database), or if
   55460 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
   55461 ** without doing anything.
   55462 */
   55463 SQLITE_PRIVATE int sqlite3PagerOpenWal(
   55464   Pager *pPager,                  /* Pager object */
   55465   int *pbOpen                     /* OUT: Set to true if call is a no-op */
   55466 ){
   55467   int rc = SQLITE_OK;             /* Return code */
   55468 
   55469   assert( assert_pager_state(pPager) );
   55470   assert( pPager->eState==PAGER_OPEN   || pbOpen );
   55471   assert( pPager->eState==PAGER_READER || !pbOpen );
   55472   assert( pbOpen==0 || *pbOpen==0 );
   55473   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
   55474 
   55475   if( !pPager->tempFile && !pPager->pWal ){
   55476     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
   55477 
   55478     /* Close any rollback journal previously open */
   55479     sqlite3OsClose(pPager->jfd);
   55480 
   55481     rc = pagerOpenWal(pPager);
   55482     if( rc==SQLITE_OK ){
   55483       pPager->journalMode = PAGER_JOURNALMODE_WAL;
   55484       pPager->eState = PAGER_OPEN;
   55485     }
   55486   }else{
   55487     *pbOpen = 1;
   55488   }
   55489 
   55490   return rc;
   55491 }
   55492 
   55493 /*
   55494 ** This function is called to close the connection to the log file prior
   55495 ** to switching from WAL to rollback mode.
   55496 **
   55497 ** Before closing the log file, this function attempts to take an
   55498 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
   55499 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
   55500 ** If successful, the EXCLUSIVE lock is not released before returning.
   55501 */
   55502 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
   55503   int rc = SQLITE_OK;
   55504 
   55505   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
   55506 
   55507   /* If the log file is not already open, but does exist in the file-system,
   55508   ** it may need to be checkpointed before the connection can switch to
   55509   ** rollback mode. Open it now so this can happen.
   55510   */
   55511   if( !pPager->pWal ){
   55512     int logexists = 0;
   55513     rc = pagerLockDb(pPager, SHARED_LOCK);
   55514     if( rc==SQLITE_OK ){
   55515       rc = sqlite3OsAccess(
   55516           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
   55517       );
   55518     }
   55519     if( rc==SQLITE_OK && logexists ){
   55520       rc = pagerOpenWal(pPager);
   55521     }
   55522   }
   55523 
   55524   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
   55525   ** the database file, the log and log-summary files will be deleted.
   55526   */
   55527   if( rc==SQLITE_OK && pPager->pWal ){
   55528     rc = pagerExclusiveLock(pPager);
   55529     if( rc==SQLITE_OK ){
   55530       rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
   55531                            pPager->pageSize, (u8*)pPager->pTmpSpace);
   55532       pPager->pWal = 0;
   55533       pagerFixMaplimit(pPager);
   55534       if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
   55535     }
   55536   }
   55537   return rc;
   55538 }
   55539 
   55540 #ifdef SQLITE_ENABLE_SNAPSHOT
   55541 /*
   55542 ** If this is a WAL database, obtain a snapshot handle for the snapshot
   55543 ** currently open. Otherwise, return an error.
   55544 */
   55545 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
   55546   int rc = SQLITE_ERROR;
   55547   if( pPager->pWal ){
   55548     rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
   55549   }
   55550   return rc;
   55551 }
   55552 
   55553 /*
   55554 ** If this is a WAL database, store a pointer to pSnapshot. Next time a
   55555 ** read transaction is opened, attempt to read from the snapshot it
   55556 ** identifies. If this is not a WAL database, return an error.
   55557 */
   55558 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
   55559   int rc = SQLITE_OK;
   55560   if( pPager->pWal ){
   55561     sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
   55562   }else{
   55563     rc = SQLITE_ERROR;
   55564   }
   55565   return rc;
   55566 }
   55567 
   55568 /*
   55569 ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
   55570 ** is not a WAL database, return an error.
   55571 */
   55572 SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
   55573   int rc;
   55574   if( pPager->pWal ){
   55575     rc = sqlite3WalSnapshotRecover(pPager->pWal);
   55576   }else{
   55577     rc = SQLITE_ERROR;
   55578   }
   55579   return rc;
   55580 }
   55581 #endif /* SQLITE_ENABLE_SNAPSHOT */
   55582 #endif /* !SQLITE_OMIT_WAL */
   55583 
   55584 #ifdef SQLITE_ENABLE_ZIPVFS
   55585 /*
   55586 ** A read-lock must be held on the pager when this function is called. If
   55587 ** the pager is in WAL mode and the WAL file currently contains one or more
   55588 ** frames, return the size in bytes of the page images stored within the
   55589 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
   55590 ** is empty, return 0.
   55591 */
   55592 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
   55593   assert( pPager->eState>=PAGER_READER );
   55594   return sqlite3WalFramesize(pPager->pWal);
   55595 }
   55596 #endif
   55597 
   55598 #endif /* SQLITE_OMIT_DISKIO */
   55599 
   55600 /************** End of pager.c ***********************************************/
   55601 /************** Begin file wal.c *********************************************/
   55602 /*
   55603 ** 2010 February 1
   55604 **
   55605 ** The author disclaims copyright to this source code.  In place of
   55606 ** a legal notice, here is a blessing:
   55607 **
   55608 **    May you do good and not evil.
   55609 **    May you find forgiveness for yourself and forgive others.
   55610 **    May you share freely, never taking more than you give.
   55611 **
   55612 *************************************************************************
   55613 **
   55614 ** This file contains the implementation of a write-ahead log (WAL) used in
   55615 ** "journal_mode=WAL" mode.
   55616 **
   55617 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
   55618 **
   55619 ** A WAL file consists of a header followed by zero or more "frames".
   55620 ** Each frame records the revised content of a single page from the
   55621 ** database file.  All changes to the database are recorded by writing
   55622 ** frames into the WAL.  Transactions commit when a frame is written that
   55623 ** contains a commit marker.  A single WAL can and usually does record
   55624 ** multiple transactions.  Periodically, the content of the WAL is
   55625 ** transferred back into the database file in an operation called a
   55626 ** "checkpoint".
   55627 **
   55628 ** A single WAL file can be used multiple times.  In other words, the
   55629 ** WAL can fill up with frames and then be checkpointed and then new
   55630 ** frames can overwrite the old ones.  A WAL always grows from beginning
   55631 ** toward the end.  Checksums and counters attached to each frame are
   55632 ** used to determine which frames within the WAL are valid and which
   55633 ** are leftovers from prior checkpoints.
   55634 **
   55635 ** The WAL header is 32 bytes in size and consists of the following eight
   55636 ** big-endian 32-bit unsigned integer values:
   55637 **
   55638 **     0: Magic number.  0x377f0682 or 0x377f0683
   55639 **     4: File format version.  Currently 3007000
   55640 **     8: Database page size.  Example: 1024
   55641 **    12: Checkpoint sequence number
   55642 **    16: Salt-1, random integer incremented with each checkpoint
   55643 **    20: Salt-2, a different random integer changing with each ckpt
   55644 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
   55645 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
   55646 **
   55647 ** Immediately following the wal-header are zero or more frames. Each
   55648 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
   55649 ** of page data. The frame-header is six big-endian 32-bit unsigned
   55650 ** integer values, as follows:
   55651 **
   55652 **     0: Page number.
   55653 **     4: For commit records, the size of the database image in pages
   55654 **        after the commit. For all other records, zero.
   55655 **     8: Salt-1 (copied from the header)
   55656 **    12: Salt-2 (copied from the header)
   55657 **    16: Checksum-1.
   55658 **    20: Checksum-2.
   55659 **
   55660 ** A frame is considered valid if and only if the following conditions are
   55661 ** true:
   55662 **
   55663 **    (1) The salt-1 and salt-2 values in the frame-header match
   55664 **        salt values in the wal-header
   55665 **
   55666 **    (2) The checksum values in the final 8 bytes of the frame-header
   55667 **        exactly match the checksum computed consecutively on the
   55668 **        WAL header and the first 8 bytes and the content of all frames
   55669 **        up to and including the current frame.
   55670 **
   55671 ** The checksum is computed using 32-bit big-endian integers if the
   55672 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
   55673 ** is computed using little-endian if the magic number is 0x377f0682.
   55674 ** The checksum values are always stored in the frame header in a
   55675 ** big-endian format regardless of which byte order is used to compute
   55676 ** the checksum.  The checksum is computed by interpreting the input as
   55677 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
   55678 ** algorithm used for the checksum is as follows:
   55679 **
   55680 **   for i from 0 to n-1 step 2:
   55681 **     s0 += x[i] + s1;
   55682 **     s1 += x[i+1] + s0;
   55683 **   endfor
   55684 **
   55685 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
   55686 ** in reverse order (the largest fibonacci weight occurs on the first element
   55687 ** of the sequence being summed.)  The s1 value spans all 32-bit
   55688 ** terms of the sequence whereas s0 omits the final term.
   55689 **
   55690 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
   55691 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
   55692 ** The VFS.xSync operations serve as write barriers - all writes launched
   55693 ** before the xSync must complete before any write that launches after the
   55694 ** xSync begins.
   55695 **
   55696 ** After each checkpoint, the salt-1 value is incremented and the salt-2
   55697 ** value is randomized.  This prevents old and new frames in the WAL from
   55698 ** being considered valid at the same time and being checkpointing together
   55699 ** following a crash.
   55700 **
   55701 ** READER ALGORITHM
   55702 **
   55703 ** To read a page from the database (call it page number P), a reader
   55704 ** first checks the WAL to see if it contains page P.  If so, then the
   55705 ** last valid instance of page P that is a followed by a commit frame
   55706 ** or is a commit frame itself becomes the value read.  If the WAL
   55707 ** contains no copies of page P that are valid and which are a commit
   55708 ** frame or are followed by a commit frame, then page P is read from
   55709 ** the database file.
   55710 **
   55711 ** To start a read transaction, the reader records the index of the last
   55712 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
   55713 ** for all subsequent read operations.  New transactions can be appended
   55714 ** to the WAL, but as long as the reader uses its original mxFrame value
   55715 ** and ignores the newly appended content, it will see a consistent snapshot
   55716 ** of the database from a single point in time.  This technique allows
   55717 ** multiple concurrent readers to view different versions of the database
   55718 ** content simultaneously.
   55719 **
   55720 ** The reader algorithm in the previous paragraphs works correctly, but
   55721 ** because frames for page P can appear anywhere within the WAL, the
   55722 ** reader has to scan the entire WAL looking for page P frames.  If the
   55723 ** WAL is large (multiple megabytes is typical) that scan can be slow,
   55724 ** and read performance suffers.  To overcome this problem, a separate
   55725 ** data structure called the wal-index is maintained to expedite the
   55726 ** search for frames of a particular page.
   55727 **
   55728 ** WAL-INDEX FORMAT
   55729 **
   55730 ** Conceptually, the wal-index is shared memory, though VFS implementations
   55731 ** might choose to implement the wal-index using a mmapped file.  Because
   55732 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
   55733 ** on a network filesystem.  All users of the database must be able to
   55734 ** share memory.
   55735 **
   55736 ** In the default unix and windows implementation, the wal-index is a mmapped
   55737 ** file whose name is the database name with a "-shm" suffix added.  For that
   55738 ** reason, the wal-index is sometimes called the "shm" file.
   55739 **
   55740 ** The wal-index is transient.  After a crash, the wal-index can (and should
   55741 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
   55742 ** to either truncate or zero the header of the wal-index when the last
   55743 ** connection to it closes.  Because the wal-index is transient, it can
   55744 ** use an architecture-specific format; it does not have to be cross-platform.
   55745 ** Hence, unlike the database and WAL file formats which store all values
   55746 ** as big endian, the wal-index can store multi-byte values in the native
   55747 ** byte order of the host computer.
   55748 **
   55749 ** The purpose of the wal-index is to answer this question quickly:  Given
   55750 ** a page number P and a maximum frame index M, return the index of the
   55751 ** last frame in the wal before frame M for page P in the WAL, or return
   55752 ** NULL if there are no frames for page P in the WAL prior to M.
   55753 **
   55754 ** The wal-index consists of a header region, followed by an one or
   55755 ** more index blocks.
   55756 **
   55757 ** The wal-index header contains the total number of frames within the WAL
   55758 ** in the mxFrame field.
   55759 **
   55760 ** Each index block except for the first contains information on
   55761 ** HASHTABLE_NPAGE frames. The first index block contains information on
   55762 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
   55763 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
   55764 ** first index block are the same size as all other index blocks in the
   55765 ** wal-index.
   55766 **
   55767 ** Each index block contains two sections, a page-mapping that contains the
   55768 ** database page number associated with each wal frame, and a hash-table
   55769 ** that allows readers to query an index block for a specific page number.
   55770 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
   55771 ** for the first index block) 32-bit page numbers. The first entry in the
   55772 ** first index-block contains the database page number corresponding to the
   55773 ** first frame in the WAL file. The first entry in the second index block
   55774 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
   55775 ** the log, and so on.
   55776 **
   55777 ** The last index block in a wal-index usually contains less than the full
   55778 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
   55779 ** depending on the contents of the WAL file. This does not change the
   55780 ** allocated size of the page-mapping array - the page-mapping array merely
   55781 ** contains unused entries.
   55782 **
   55783 ** Even without using the hash table, the last frame for page P
   55784 ** can be found by scanning the page-mapping sections of each index block
   55785 ** starting with the last index block and moving toward the first, and
   55786 ** within each index block, starting at the end and moving toward the
   55787 ** beginning.  The first entry that equals P corresponds to the frame
   55788 ** holding the content for that page.
   55789 **
   55790 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
   55791 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
   55792 ** hash table for each page number in the mapping section, so the hash
   55793 ** table is never more than half full.  The expected number of collisions
   55794 ** prior to finding a match is 1.  Each entry of the hash table is an
   55795 ** 1-based index of an entry in the mapping section of the same
   55796 ** index block.   Let K be the 1-based index of the largest entry in
   55797 ** the mapping section.  (For index blocks other than the last, K will
   55798 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
   55799 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
   55800 ** contain a value of 0.
   55801 **
   55802 ** To look for page P in the hash table, first compute a hash iKey on
   55803 ** P as follows:
   55804 **
   55805 **      iKey = (P * 383) % HASHTABLE_NSLOT
   55806 **
   55807 ** Then start scanning entries of the hash table, starting with iKey
   55808 ** (wrapping around to the beginning when the end of the hash table is
   55809 ** reached) until an unused hash slot is found. Let the first unused slot
   55810 ** be at index iUnused.  (iUnused might be less than iKey if there was
   55811 ** wrap-around.) Because the hash table is never more than half full,
   55812 ** the search is guaranteed to eventually hit an unused entry.  Let
   55813 ** iMax be the value between iKey and iUnused, closest to iUnused,
   55814 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
   55815 ** no hash slot such that aHash[i]==p) then page P is not in the
   55816 ** current index block.  Otherwise the iMax-th mapping entry of the
   55817 ** current index block corresponds to the last entry that references
   55818 ** page P.
   55819 **
   55820 ** A hash search begins with the last index block and moves toward the
   55821 ** first index block, looking for entries corresponding to page P.  On
   55822 ** average, only two or three slots in each index block need to be
   55823 ** examined in order to either find the last entry for page P, or to
   55824 ** establish that no such entry exists in the block.  Each index block
   55825 ** holds over 4000 entries.  So two or three index blocks are sufficient
   55826 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
   55827 ** comparisons (on average) suffice to either locate a frame in the
   55828 ** WAL or to establish that the frame does not exist in the WAL.  This
   55829 ** is much faster than scanning the entire 10MB WAL.
   55830 **
   55831 ** Note that entries are added in order of increasing K.  Hence, one
   55832 ** reader might be using some value K0 and a second reader that started
   55833 ** at a later time (after additional transactions were added to the WAL
   55834 ** and to the wal-index) might be using a different value K1, where K1>K0.
   55835 ** Both readers can use the same hash table and mapping section to get
   55836 ** the correct result.  There may be entries in the hash table with
   55837 ** K>K0 but to the first reader, those entries will appear to be unused
   55838 ** slots in the hash table and so the first reader will get an answer as
   55839 ** if no values greater than K0 had ever been inserted into the hash table
   55840 ** in the first place - which is what reader one wants.  Meanwhile, the
   55841 ** second reader using K1 will see additional values that were inserted
   55842 ** later, which is exactly what reader two wants.
   55843 **
   55844 ** When a rollback occurs, the value of K is decreased. Hash table entries
   55845 ** that correspond to frames greater than the new K value are removed
   55846 ** from the hash table at this point.
   55847 */
   55848 #ifndef SQLITE_OMIT_WAL
   55849 
   55850 /* #include "wal.h" */
   55851 
   55852 /*
   55853 ** Trace output macros
   55854 */
   55855 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   55856 SQLITE_PRIVATE int sqlite3WalTrace = 0;
   55857 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
   55858 #else
   55859 # define WALTRACE(X)
   55860 #endif
   55861 
   55862 /*
   55863 ** The maximum (and only) versions of the wal and wal-index formats
   55864 ** that may be interpreted by this version of SQLite.
   55865 **
   55866 ** If a client begins recovering a WAL file and finds that (a) the checksum
   55867 ** values in the wal-header are correct and (b) the version field is not
   55868 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
   55869 **
   55870 ** Similarly, if a client successfully reads a wal-index header (i.e. the
   55871 ** checksum test is successful) and finds that the version field is not
   55872 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
   55873 ** returns SQLITE_CANTOPEN.
   55874 */
   55875 #define WAL_MAX_VERSION      3007000
   55876 #define WALINDEX_MAX_VERSION 3007000
   55877 
   55878 /*
   55879 ** Index numbers for various locking bytes.   WAL_NREADER is the number
   55880 ** of available reader locks and should be at least 3.  The default
   55881 ** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
   55882 **
   55883 ** Technically, the various VFSes are free to implement these locks however
   55884 ** they see fit.  However, compatibility is encouraged so that VFSes can
   55885 ** interoperate.  The standard implemention used on both unix and windows
   55886 ** is for the index number to indicate a byte offset into the
   55887 ** WalCkptInfo.aLock[] array in the wal-index header.  In other words, all
   55888 ** locks are on the shm file.  The WALINDEX_LOCK_OFFSET constant (which
   55889 ** should be 120) is the location in the shm file for the first locking
   55890 ** byte.
   55891 */
   55892 #define WAL_WRITE_LOCK         0
   55893 #define WAL_ALL_BUT_WRITE      1
   55894 #define WAL_CKPT_LOCK          1
   55895 #define WAL_RECOVER_LOCK       2
   55896 #define WAL_READ_LOCK(I)       (3+(I))
   55897 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
   55898 
   55899 
   55900 /* Object declarations */
   55901 typedef struct WalIndexHdr WalIndexHdr;
   55902 typedef struct WalIterator WalIterator;
   55903 typedef struct WalCkptInfo WalCkptInfo;
   55904 
   55905 
   55906 /*
   55907 ** The following object holds a copy of the wal-index header content.
   55908 **
   55909 ** The actual header in the wal-index consists of two copies of this
   55910 ** object followed by one instance of the WalCkptInfo object.
   55911 ** For all versions of SQLite through 3.10.0 and probably beyond,
   55912 ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
   55913 ** the total header size is 136 bytes.
   55914 **
   55915 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
   55916 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
   55917 ** added in 3.7.1 when support for 64K pages was added.
   55918 */
   55919 struct WalIndexHdr {
   55920   u32 iVersion;                   /* Wal-index version */
   55921   u32 unused;                     /* Unused (padding) field */
   55922   u32 iChange;                    /* Counter incremented each transaction */
   55923   u8 isInit;                      /* 1 when initialized */
   55924   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
   55925   u16 szPage;                     /* Database page size in bytes. 1==64K */
   55926   u32 mxFrame;                    /* Index of last valid frame in the WAL */
   55927   u32 nPage;                      /* Size of database in pages */
   55928   u32 aFrameCksum[2];             /* Checksum of last frame in log */
   55929   u32 aSalt[2];                   /* Two salt values copied from WAL header */
   55930   u32 aCksum[2];                  /* Checksum over all prior fields */
   55931 };
   55932 
   55933 /*
   55934 ** A copy of the following object occurs in the wal-index immediately
   55935 ** following the second copy of the WalIndexHdr.  This object stores
   55936 ** information used by checkpoint.
   55937 **
   55938 ** nBackfill is the number of frames in the WAL that have been written
   55939 ** back into the database. (We call the act of moving content from WAL to
   55940 ** database "backfilling".)  The nBackfill number is never greater than
   55941 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
   55942 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
   55943 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
   55944 ** mxFrame back to zero when the WAL is reset.
   55945 **
   55946 ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
   55947 ** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
   55948 ** the nBackfillAttempted is set before any backfilling is done and the
   55949 ** nBackfill is only set after all backfilling completes.  So if a checkpoint
   55950 ** crashes, nBackfillAttempted might be larger than nBackfill.  The
   55951 ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
   55952 **
   55953 ** The aLock[] field is a set of bytes used for locking.  These bytes should
   55954 ** never be read or written.
   55955 **
   55956 ** There is one entry in aReadMark[] for each reader lock.  If a reader
   55957 ** holds read-lock K, then the value in aReadMark[K] is no greater than
   55958 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
   55959 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
   55960 ** a special case; its value is never used and it exists as a place-holder
   55961 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
   55962 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
   55963 ** directly from the database.
   55964 **
   55965 ** The value of aReadMark[K] may only be changed by a thread that
   55966 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
   55967 ** aReadMark[K] cannot changed while there is a reader is using that mark
   55968 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
   55969 **
   55970 ** The checkpointer may only transfer frames from WAL to database where
   55971 ** the frame numbers are less than or equal to every aReadMark[] that is
   55972 ** in use (that is, every aReadMark[j] for which there is a corresponding
   55973 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
   55974 ** largest value and will increase an unused aReadMark[] to mxFrame if there
   55975 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
   55976 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
   55977 ** in the WAL has been backfilled into the database) then new readers
   55978 ** will choose aReadMark[0] which has value 0 and hence such reader will
   55979 ** get all their all content directly from the database file and ignore
   55980 ** the WAL.
   55981 **
   55982 ** Writers normally append new frames to the end of the WAL.  However,
   55983 ** if nBackfill equals mxFrame (meaning that all WAL content has been
   55984 ** written back into the database) and if no readers are using the WAL
   55985 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
   55986 ** the writer will first "reset" the WAL back to the beginning and start
   55987 ** writing new content beginning at frame 1.
   55988 **
   55989 ** We assume that 32-bit loads are atomic and so no locks are needed in
   55990 ** order to read from any aReadMark[] entries.
   55991 */
   55992 struct WalCkptInfo {
   55993   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
   55994   u32 aReadMark[WAL_NREADER];     /* Reader marks */
   55995   u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
   55996   u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
   55997   u32 notUsed0;                   /* Available for future enhancements */
   55998 };
   55999 #define READMARK_NOT_USED  0xffffffff
   56000 
   56001 
   56002 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
   56003 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
   56004 ** only support mandatory file-locks, we do not read or write data
   56005 ** from the region of the file on which locks are applied.
   56006 */
   56007 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
   56008 #define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
   56009 
   56010 /* Size of header before each frame in wal */
   56011 #define WAL_FRAME_HDRSIZE 24
   56012 
   56013 /* Size of write ahead log header, including checksum. */
   56014 #define WAL_HDRSIZE 32
   56015 
   56016 /* WAL magic value. Either this value, or the same value with the least
   56017 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
   56018 ** big-endian format in the first 4 bytes of a WAL file.
   56019 **
   56020 ** If the LSB is set, then the checksums for each frame within the WAL
   56021 ** file are calculated by treating all data as an array of 32-bit
   56022 ** big-endian words. Otherwise, they are calculated by interpreting
   56023 ** all data as 32-bit little-endian words.
   56024 */
   56025 #define WAL_MAGIC 0x377f0682
   56026 
   56027 /*
   56028 ** Return the offset of frame iFrame in the write-ahead log file,
   56029 ** assuming a database page size of szPage bytes. The offset returned
   56030 ** is to the start of the write-ahead log frame-header.
   56031 */
   56032 #define walFrameOffset(iFrame, szPage) (                               \
   56033   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
   56034 )
   56035 
   56036 /*
   56037 ** An open write-ahead log file is represented by an instance of the
   56038 ** following object.
   56039 */
   56040 struct Wal {
   56041   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
   56042   sqlite3_file *pDbFd;       /* File handle for the database file */
   56043   sqlite3_file *pWalFd;      /* File handle for WAL file */
   56044   u32 iCallback;             /* Value to pass to log callback (or 0) */
   56045   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
   56046   int nWiData;               /* Size of array apWiData */
   56047   int szFirstBlock;          /* Size of first block written to WAL file */
   56048   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
   56049   u32 szPage;                /* Database page size */
   56050   i16 readLock;              /* Which read lock is being held.  -1 for none */
   56051   u8 syncFlags;              /* Flags to use to sync header writes */
   56052   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
   56053   u8 writeLock;              /* True if in a write transaction */
   56054   u8 ckptLock;               /* True if holding a checkpoint lock */
   56055   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
   56056   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
   56057   u8 syncHeader;             /* Fsync the WAL header if true */
   56058   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
   56059   u8 bShmUnreliable;         /* SHM content is read-only and unreliable */
   56060   WalIndexHdr hdr;           /* Wal-index header for current transaction */
   56061   u32 minFrame;              /* Ignore wal frames before this one */
   56062   u32 iReCksum;              /* On commit, recalculate checksums from here */
   56063   const char *zWalName;      /* Name of WAL file */
   56064   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
   56065 #ifdef SQLITE_DEBUG
   56066   u8 lockError;              /* True if a locking error has occurred */
   56067 #endif
   56068 #ifdef SQLITE_ENABLE_SNAPSHOT
   56069   WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
   56070 #endif
   56071 };
   56072 
   56073 /*
   56074 ** Candidate values for Wal.exclusiveMode.
   56075 */
   56076 #define WAL_NORMAL_MODE     0
   56077 #define WAL_EXCLUSIVE_MODE  1
   56078 #define WAL_HEAPMEMORY_MODE 2
   56079 
   56080 /*
   56081 ** Possible values for WAL.readOnly
   56082 */
   56083 #define WAL_RDWR        0    /* Normal read/write connection */
   56084 #define WAL_RDONLY      1    /* The WAL file is readonly */
   56085 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
   56086 
   56087 /*
   56088 ** Each page of the wal-index mapping contains a hash-table made up of
   56089 ** an array of HASHTABLE_NSLOT elements of the following type.
   56090 */
   56091 typedef u16 ht_slot;
   56092 
   56093 /*
   56094 ** This structure is used to implement an iterator that loops through
   56095 ** all frames in the WAL in database page order. Where two or more frames
   56096 ** correspond to the same database page, the iterator visits only the
   56097 ** frame most recently written to the WAL (in other words, the frame with
   56098 ** the largest index).
   56099 **
   56100 ** The internals of this structure are only accessed by:
   56101 **
   56102 **   walIteratorInit() - Create a new iterator,
   56103 **   walIteratorNext() - Step an iterator,
   56104 **   walIteratorFree() - Free an iterator.
   56105 **
   56106 ** This functionality is used by the checkpoint code (see walCheckpoint()).
   56107 */
   56108 struct WalIterator {
   56109   int iPrior;                     /* Last result returned from the iterator */
   56110   int nSegment;                   /* Number of entries in aSegment[] */
   56111   struct WalSegment {
   56112     int iNext;                    /* Next slot in aIndex[] not yet returned */
   56113     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
   56114     u32 *aPgno;                   /* Array of page numbers. */
   56115     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
   56116     int iZero;                    /* Frame number associated with aPgno[0] */
   56117   } aSegment[1];                  /* One for every 32KB page in the wal-index */
   56118 };
   56119 
   56120 /*
   56121 ** Define the parameters of the hash tables in the wal-index file. There
   56122 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
   56123 ** wal-index.
   56124 **
   56125 ** Changing any of these constants will alter the wal-index format and
   56126 ** create incompatibilities.
   56127 */
   56128 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
   56129 #define HASHTABLE_HASH_1     383                  /* Should be prime */
   56130 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
   56131 
   56132 /*
   56133 ** The block of page numbers associated with the first hash-table in a
   56134 ** wal-index is smaller than usual. This is so that there is a complete
   56135 ** hash-table on each aligned 32KB page of the wal-index.
   56136 */
   56137 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
   56138 
   56139 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
   56140 #define WALINDEX_PGSZ   (                                         \
   56141     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
   56142 )
   56143 
   56144 /*
   56145 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
   56146 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
   56147 ** numbered from zero.
   56148 **
   56149 ** If the wal-index is currently smaller the iPage pages then the size
   56150 ** of the wal-index might be increased, but only if it is safe to do
   56151 ** so.  It is safe to enlarge the wal-index if pWal->writeLock is true
   56152 ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
   56153 **
   56154 ** If this call is successful, *ppPage is set to point to the wal-index
   56155 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
   56156 ** then an SQLite error code is returned and *ppPage is set to 0.
   56157 */
   56158 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
   56159   int rc = SQLITE_OK;
   56160 
   56161   /* Enlarge the pWal->apWiData[] array if required */
   56162   if( pWal->nWiData<=iPage ){
   56163     int nByte = sizeof(u32*)*(iPage+1);
   56164     volatile u32 **apNew;
   56165     apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
   56166     if( !apNew ){
   56167       *ppPage = 0;
   56168       return SQLITE_NOMEM_BKPT;
   56169     }
   56170     memset((void*)&apNew[pWal->nWiData], 0,
   56171            sizeof(u32*)*(iPage+1-pWal->nWiData));
   56172     pWal->apWiData = apNew;
   56173     pWal->nWiData = iPage+1;
   56174   }
   56175 
   56176   /* Request a pointer to the required page from the VFS */
   56177   if( pWal->apWiData[iPage]==0 ){
   56178     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   56179       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
   56180       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
   56181     }else{
   56182       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
   56183           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
   56184       );
   56185       assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
   56186       testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
   56187       if( (rc&0xff)==SQLITE_READONLY ){
   56188         pWal->readOnly |= WAL_SHM_RDONLY;
   56189         if( rc==SQLITE_READONLY ){
   56190           rc = SQLITE_OK;
   56191         }
   56192       }
   56193     }
   56194   }
   56195 
   56196   *ppPage = pWal->apWiData[iPage];
   56197   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
   56198   return rc;
   56199 }
   56200 
   56201 /*
   56202 ** Return a pointer to the WalCkptInfo structure in the wal-index.
   56203 */
   56204 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
   56205   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   56206   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
   56207 }
   56208 
   56209 /*
   56210 ** Return a pointer to the WalIndexHdr structure in the wal-index.
   56211 */
   56212 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
   56213   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   56214   return (volatile WalIndexHdr*)pWal->apWiData[0];
   56215 }
   56216 
   56217 /*
   56218 ** The argument to this macro must be of type u32. On a little-endian
   56219 ** architecture, it returns the u32 value that results from interpreting
   56220 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
   56221 ** returns the value that would be produced by interpreting the 4 bytes
   56222 ** of the input value as a little-endian integer.
   56223 */
   56224 #define BYTESWAP32(x) ( \
   56225     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
   56226   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
   56227 )
   56228 
   56229 /*
   56230 ** Generate or extend an 8 byte checksum based on the data in
   56231 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
   56232 ** initial values of 0 and 0 if aIn==NULL).
   56233 **
   56234 ** The checksum is written back into aOut[] before returning.
   56235 **
   56236 ** nByte must be a positive multiple of 8.
   56237 */
   56238 static void walChecksumBytes(
   56239   int nativeCksum, /* True for native byte-order, false for non-native */
   56240   u8 *a,           /* Content to be checksummed */
   56241   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
   56242   const u32 *aIn,  /* Initial checksum value input */
   56243   u32 *aOut        /* OUT: Final checksum value output */
   56244 ){
   56245   u32 s1, s2;
   56246   u32 *aData = (u32 *)a;
   56247   u32 *aEnd = (u32 *)&a[nByte];
   56248 
   56249   if( aIn ){
   56250     s1 = aIn[0];
   56251     s2 = aIn[1];
   56252   }else{
   56253     s1 = s2 = 0;
   56254   }
   56255 
   56256   assert( nByte>=8 );
   56257   assert( (nByte&0x00000007)==0 );
   56258 
   56259   if( nativeCksum ){
   56260     do {
   56261       s1 += *aData++ + s2;
   56262       s2 += *aData++ + s1;
   56263     }while( aData<aEnd );
   56264   }else{
   56265     do {
   56266       s1 += BYTESWAP32(aData[0]) + s2;
   56267       s2 += BYTESWAP32(aData[1]) + s1;
   56268       aData += 2;
   56269     }while( aData<aEnd );
   56270   }
   56271 
   56272   aOut[0] = s1;
   56273   aOut[1] = s2;
   56274 }
   56275 
   56276 static void walShmBarrier(Wal *pWal){
   56277   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
   56278     sqlite3OsShmBarrier(pWal->pDbFd);
   56279   }
   56280 }
   56281 
   56282 /*
   56283 ** Write the header information in pWal->hdr into the wal-index.
   56284 **
   56285 ** The checksum on pWal->hdr is updated before it is written.
   56286 */
   56287 static void walIndexWriteHdr(Wal *pWal){
   56288   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
   56289   const int nCksum = offsetof(WalIndexHdr, aCksum);
   56290 
   56291   assert( pWal->writeLock );
   56292   pWal->hdr.isInit = 1;
   56293   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
   56294   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
   56295   memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
   56296   walShmBarrier(pWal);
   56297   memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
   56298 }
   56299 
   56300 /*
   56301 ** This function encodes a single frame header and writes it to a buffer
   56302 ** supplied by the caller. A frame-header is made up of a series of
   56303 ** 4-byte big-endian integers, as follows:
   56304 **
   56305 **     0: Page number.
   56306 **     4: For commit records, the size of the database image in pages
   56307 **        after the commit. For all other records, zero.
   56308 **     8: Salt-1 (copied from the wal-header)
   56309 **    12: Salt-2 (copied from the wal-header)
   56310 **    16: Checksum-1.
   56311 **    20: Checksum-2.
   56312 */
   56313 static void walEncodeFrame(
   56314   Wal *pWal,                      /* The write-ahead log */
   56315   u32 iPage,                      /* Database page number for frame */
   56316   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
   56317   u8 *aData,                      /* Pointer to page data */
   56318   u8 *aFrame                      /* OUT: Write encoded frame here */
   56319 ){
   56320   int nativeCksum;                /* True for native byte-order checksums */
   56321   u32 *aCksum = pWal->hdr.aFrameCksum;
   56322   assert( WAL_FRAME_HDRSIZE==24 );
   56323   sqlite3Put4byte(&aFrame[0], iPage);
   56324   sqlite3Put4byte(&aFrame[4], nTruncate);
   56325   if( pWal->iReCksum==0 ){
   56326     memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
   56327 
   56328     nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   56329     walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   56330     walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   56331 
   56332     sqlite3Put4byte(&aFrame[16], aCksum[0]);
   56333     sqlite3Put4byte(&aFrame[20], aCksum[1]);
   56334   }else{
   56335     memset(&aFrame[8], 0, 16);
   56336   }
   56337 }
   56338 
   56339 /*
   56340 ** Check to see if the frame with header in aFrame[] and content
   56341 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
   56342 ** *pnTruncate and return true.  Return if the frame is not valid.
   56343 */
   56344 static int walDecodeFrame(
   56345   Wal *pWal,                      /* The write-ahead log */
   56346   u32 *piPage,                    /* OUT: Database page number for frame */
   56347   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
   56348   u8 *aData,                      /* Pointer to page data (for checksum) */
   56349   u8 *aFrame                      /* Frame data */
   56350 ){
   56351   int nativeCksum;                /* True for native byte-order checksums */
   56352   u32 *aCksum = pWal->hdr.aFrameCksum;
   56353   u32 pgno;                       /* Page number of the frame */
   56354   assert( WAL_FRAME_HDRSIZE==24 );
   56355 
   56356   /* A frame is only valid if the salt values in the frame-header
   56357   ** match the salt values in the wal-header.
   56358   */
   56359   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
   56360     return 0;
   56361   }
   56362 
   56363   /* A frame is only valid if the page number is creater than zero.
   56364   */
   56365   pgno = sqlite3Get4byte(&aFrame[0]);
   56366   if( pgno==0 ){
   56367     return 0;
   56368   }
   56369 
   56370   /* A frame is only valid if a checksum of the WAL header,
   56371   ** all prior frams, the first 16 bytes of this frame-header,
   56372   ** and the frame-data matches the checksum in the last 8
   56373   ** bytes of this frame-header.
   56374   */
   56375   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   56376   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   56377   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   56378   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
   56379    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
   56380   ){
   56381     /* Checksum failed. */
   56382     return 0;
   56383   }
   56384 
   56385   /* If we reach this point, the frame is valid.  Return the page number
   56386   ** and the new database size.
   56387   */
   56388   *piPage = pgno;
   56389   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
   56390   return 1;
   56391 }
   56392 
   56393 
   56394 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   56395 /*
   56396 ** Names of locks.  This routine is used to provide debugging output and is not
   56397 ** a part of an ordinary build.
   56398 */
   56399 static const char *walLockName(int lockIdx){
   56400   if( lockIdx==WAL_WRITE_LOCK ){
   56401     return "WRITE-LOCK";
   56402   }else if( lockIdx==WAL_CKPT_LOCK ){
   56403     return "CKPT-LOCK";
   56404   }else if( lockIdx==WAL_RECOVER_LOCK ){
   56405     return "RECOVER-LOCK";
   56406   }else{
   56407     static char zName[15];
   56408     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
   56409                      lockIdx-WAL_READ_LOCK(0));
   56410     return zName;
   56411   }
   56412 }
   56413 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   56414 
   56415 
   56416 /*
   56417 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
   56418 ** A lock cannot be moved directly between shared and exclusive - it must go
   56419 ** through the unlocked state first.
   56420 **
   56421 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
   56422 */
   56423 static int walLockShared(Wal *pWal, int lockIdx){
   56424   int rc;
   56425   if( pWal->exclusiveMode ) return SQLITE_OK;
   56426   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   56427                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
   56428   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
   56429             walLockName(lockIdx), rc ? "failed" : "ok"));
   56430   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   56431   return rc;
   56432 }
   56433 static void walUnlockShared(Wal *pWal, int lockIdx){
   56434   if( pWal->exclusiveMode ) return;
   56435   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   56436                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
   56437   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
   56438 }
   56439 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
   56440   int rc;
   56441   if( pWal->exclusiveMode ) return SQLITE_OK;
   56442   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   56443                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
   56444   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
   56445             walLockName(lockIdx), n, rc ? "failed" : "ok"));
   56446   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   56447   return rc;
   56448 }
   56449 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
   56450   if( pWal->exclusiveMode ) return;
   56451   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   56452                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
   56453   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
   56454              walLockName(lockIdx), n));
   56455 }
   56456 
   56457 /*
   56458 ** Compute a hash on a page number.  The resulting hash value must land
   56459 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
   56460 ** the hash to the next value in the event of a collision.
   56461 */
   56462 static int walHash(u32 iPage){
   56463   assert( iPage>0 );
   56464   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
   56465   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
   56466 }
   56467 static int walNextHash(int iPriorHash){
   56468   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
   56469 }
   56470 
   56471 /*
   56472 ** Return pointers to the hash table and page number array stored on
   56473 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
   56474 ** numbered starting from 0.
   56475 **
   56476 ** Set output variable *paHash to point to the start of the hash table
   56477 ** in the wal-index file. Set *piZero to one less than the frame
   56478 ** number of the first frame indexed by this hash table. If a
   56479 ** slot in the hash table is set to N, it refers to frame number
   56480 ** (*piZero+N) in the log.
   56481 **
   56482 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
   56483 ** first frame indexed by the hash table, frame (*piZero+1).
   56484 */
   56485 static int walHashGet(
   56486   Wal *pWal,                      /* WAL handle */
   56487   int iHash,                      /* Find the iHash'th table */
   56488   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
   56489   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
   56490   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
   56491 ){
   56492   int rc;                         /* Return code */
   56493   volatile u32 *aPgno;
   56494 
   56495   rc = walIndexPage(pWal, iHash, &aPgno);
   56496   assert( rc==SQLITE_OK || iHash>0 );
   56497 
   56498   if( rc==SQLITE_OK ){
   56499     u32 iZero;
   56500     volatile ht_slot *aHash;
   56501 
   56502     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
   56503     if( iHash==0 ){
   56504       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
   56505       iZero = 0;
   56506     }else{
   56507       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
   56508     }
   56509 
   56510     *paPgno = &aPgno[-1];
   56511     *paHash = aHash;
   56512     *piZero = iZero;
   56513   }
   56514   return rc;
   56515 }
   56516 
   56517 /*
   56518 ** Return the number of the wal-index page that contains the hash-table
   56519 ** and page-number array that contain entries corresponding to WAL frame
   56520 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
   56521 ** are numbered starting from 0.
   56522 */
   56523 static int walFramePage(u32 iFrame){
   56524   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
   56525   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
   56526        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
   56527        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
   56528        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
   56529        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
   56530   );
   56531   return iHash;
   56532 }
   56533 
   56534 /*
   56535 ** Return the page number associated with frame iFrame in this WAL.
   56536 */
   56537 static u32 walFramePgno(Wal *pWal, u32 iFrame){
   56538   int iHash = walFramePage(iFrame);
   56539   if( iHash==0 ){
   56540     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
   56541   }
   56542   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
   56543 }
   56544 
   56545 /*
   56546 ** Remove entries from the hash table that point to WAL slots greater
   56547 ** than pWal->hdr.mxFrame.
   56548 **
   56549 ** This function is called whenever pWal->hdr.mxFrame is decreased due
   56550 ** to a rollback or savepoint.
   56551 **
   56552 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
   56553 ** updated.  Any later hash tables will be automatically cleared when
   56554 ** pWal->hdr.mxFrame advances to the point where those hash tables are
   56555 ** actually needed.
   56556 */
   56557 static void walCleanupHash(Wal *pWal){
   56558   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
   56559   volatile u32 *aPgno = 0;        /* Page number array for hash table */
   56560   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
   56561   int iLimit = 0;                 /* Zero values greater than this */
   56562   int nByte;                      /* Number of bytes to zero in aPgno[] */
   56563   int i;                          /* Used to iterate through aHash[] */
   56564 
   56565   assert( pWal->writeLock );
   56566   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
   56567   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
   56568   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
   56569 
   56570   if( pWal->hdr.mxFrame==0 ) return;
   56571 
   56572   /* Obtain pointers to the hash-table and page-number array containing
   56573   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
   56574   ** that the page said hash-table and array reside on is already mapped.
   56575   */
   56576   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
   56577   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
   56578   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
   56579 
   56580   /* Zero all hash-table entries that correspond to frame numbers greater
   56581   ** than pWal->hdr.mxFrame.
   56582   */
   56583   iLimit = pWal->hdr.mxFrame - iZero;
   56584   assert( iLimit>0 );
   56585   for(i=0; i<HASHTABLE_NSLOT; i++){
   56586     if( aHash[i]>iLimit ){
   56587       aHash[i] = 0;
   56588     }
   56589   }
   56590 
   56591   /* Zero the entries in the aPgno array that correspond to frames with
   56592   ** frame numbers greater than pWal->hdr.mxFrame.
   56593   */
   56594   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
   56595   memset((void *)&aPgno[iLimit+1], 0, nByte);
   56596 
   56597 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   56598   /* Verify that the every entry in the mapping region is still reachable
   56599   ** via the hash table even after the cleanup.
   56600   */
   56601   if( iLimit ){
   56602     int j;           /* Loop counter */
   56603     int iKey;        /* Hash key */
   56604     for(j=1; j<=iLimit; j++){
   56605       for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
   56606         if( aHash[iKey]==j ) break;
   56607       }
   56608       assert( aHash[iKey]==j );
   56609     }
   56610   }
   56611 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   56612 }
   56613 
   56614 
   56615 /*
   56616 ** Set an entry in the wal-index that will map database page number
   56617 ** pPage into WAL frame iFrame.
   56618 */
   56619 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
   56620   int rc;                         /* Return code */
   56621   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
   56622   volatile u32 *aPgno = 0;        /* Page number array */
   56623   volatile ht_slot *aHash = 0;    /* Hash table */
   56624 
   56625   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
   56626 
   56627   /* Assuming the wal-index file was successfully mapped, populate the
   56628   ** page number array and hash table entry.
   56629   */
   56630   if( rc==SQLITE_OK ){
   56631     int iKey;                     /* Hash table key */
   56632     int idx;                      /* Value to write to hash-table slot */
   56633     int nCollide;                 /* Number of hash collisions */
   56634 
   56635     idx = iFrame - iZero;
   56636     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
   56637 
   56638     /* If this is the first entry to be added to this hash-table, zero the
   56639     ** entire hash table and aPgno[] array before proceeding.
   56640     */
   56641     if( idx==1 ){
   56642       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
   56643       memset((void*)&aPgno[1], 0, nByte);
   56644     }
   56645 
   56646     /* If the entry in aPgno[] is already set, then the previous writer
   56647     ** must have exited unexpectedly in the middle of a transaction (after
   56648     ** writing one or more dirty pages to the WAL to free up memory).
   56649     ** Remove the remnants of that writers uncommitted transaction from
   56650     ** the hash-table before writing any new entries.
   56651     */
   56652     if( aPgno[idx] ){
   56653       walCleanupHash(pWal);
   56654       assert( !aPgno[idx] );
   56655     }
   56656 
   56657     /* Write the aPgno[] array entry and the hash-table slot. */
   56658     nCollide = idx;
   56659     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
   56660       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
   56661     }
   56662     aPgno[idx] = iPage;
   56663     aHash[iKey] = (ht_slot)idx;
   56664 
   56665 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   56666     /* Verify that the number of entries in the hash table exactly equals
   56667     ** the number of entries in the mapping region.
   56668     */
   56669     {
   56670       int i;           /* Loop counter */
   56671       int nEntry = 0;  /* Number of entries in the hash table */
   56672       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
   56673       assert( nEntry==idx );
   56674     }
   56675 
   56676     /* Verify that the every entry in the mapping region is reachable
   56677     ** via the hash table.  This turns out to be a really, really expensive
   56678     ** thing to check, so only do this occasionally - not on every
   56679     ** iteration.
   56680     */
   56681     if( (idx&0x3ff)==0 ){
   56682       int i;           /* Loop counter */
   56683       for(i=1; i<=idx; i++){
   56684         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   56685           if( aHash[iKey]==i ) break;
   56686         }
   56687         assert( aHash[iKey]==i );
   56688       }
   56689     }
   56690 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   56691   }
   56692 
   56693 
   56694   return rc;
   56695 }
   56696 
   56697 
   56698 /*
   56699 ** Recover the wal-index by reading the write-ahead log file.
   56700 **
   56701 ** This routine first tries to establish an exclusive lock on the
   56702 ** wal-index to prevent other threads/processes from doing anything
   56703 ** with the WAL or wal-index while recovery is running.  The
   56704 ** WAL_RECOVER_LOCK is also held so that other threads will know
   56705 ** that this thread is running recovery.  If unable to establish
   56706 ** the necessary locks, this routine returns SQLITE_BUSY.
   56707 */
   56708 static int walIndexRecover(Wal *pWal){
   56709   int rc;                         /* Return Code */
   56710   i64 nSize;                      /* Size of log file */
   56711   u32 aFrameCksum[2] = {0, 0};
   56712   int iLock;                      /* Lock offset to lock for checkpoint */
   56713 
   56714   /* Obtain an exclusive lock on all byte in the locking range not already
   56715   ** locked by the caller. The caller is guaranteed to have locked the
   56716   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
   56717   ** If successful, the same bytes that are locked here are unlocked before
   56718   ** this function returns.
   56719   */
   56720   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
   56721   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
   56722   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
   56723   assert( pWal->writeLock );
   56724   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
   56725   rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
   56726   if( rc==SQLITE_OK ){
   56727     rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   56728     if( rc!=SQLITE_OK ){
   56729       walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
   56730     }
   56731   }
   56732   if( rc ){
   56733     return rc;
   56734   }
   56735 
   56736   WALTRACE(("WAL%p: recovery begin...\n", pWal));
   56737 
   56738   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   56739 
   56740   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
   56741   if( rc!=SQLITE_OK ){
   56742     goto recovery_error;
   56743   }
   56744 
   56745   if( nSize>WAL_HDRSIZE ){
   56746     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
   56747     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
   56748     int szFrame;                  /* Number of bytes in buffer aFrame[] */
   56749     u8 *aData;                    /* Pointer to data part of aFrame buffer */
   56750     int iFrame;                   /* Index of last frame read */
   56751     i64 iOffset;                  /* Next offset to read from log file */
   56752     int szPage;                   /* Page size according to the log */
   56753     u32 magic;                    /* Magic value read from WAL header */
   56754     u32 version;                  /* Magic value read from WAL header */
   56755     int isValid;                  /* True if this frame is valid */
   56756 
   56757     /* Read in the WAL header. */
   56758     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
   56759     if( rc!=SQLITE_OK ){
   56760       goto recovery_error;
   56761     }
   56762 
   56763     /* If the database page size is not a power of two, or is greater than
   56764     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
   56765     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
   56766     ** WAL file.
   56767     */
   56768     magic = sqlite3Get4byte(&aBuf[0]);
   56769     szPage = sqlite3Get4byte(&aBuf[8]);
   56770     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
   56771      || szPage&(szPage-1)
   56772      || szPage>SQLITE_MAX_PAGE_SIZE
   56773      || szPage<512
   56774     ){
   56775       goto finished;
   56776     }
   56777     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
   56778     pWal->szPage = szPage;
   56779     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
   56780     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
   56781 
   56782     /* Verify that the WAL header checksum is correct */
   56783     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
   56784         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
   56785     );
   56786     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
   56787      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
   56788     ){
   56789       goto finished;
   56790     }
   56791 
   56792     /* Verify that the version number on the WAL format is one that
   56793     ** are able to understand */
   56794     version = sqlite3Get4byte(&aBuf[4]);
   56795     if( version!=WAL_MAX_VERSION ){
   56796       rc = SQLITE_CANTOPEN_BKPT;
   56797       goto finished;
   56798     }
   56799 
   56800     /* Malloc a buffer to read frames into. */
   56801     szFrame = szPage + WAL_FRAME_HDRSIZE;
   56802     aFrame = (u8 *)sqlite3_malloc64(szFrame);
   56803     if( !aFrame ){
   56804       rc = SQLITE_NOMEM_BKPT;
   56805       goto recovery_error;
   56806     }
   56807     aData = &aFrame[WAL_FRAME_HDRSIZE];
   56808 
   56809     /* Read all frames from the log file. */
   56810     iFrame = 0;
   56811     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
   56812       u32 pgno;                   /* Database page number for frame */
   56813       u32 nTruncate;              /* dbsize field from frame header */
   56814 
   56815       /* Read and decode the next log frame. */
   56816       iFrame++;
   56817       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
   56818       if( rc!=SQLITE_OK ) break;
   56819       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
   56820       if( !isValid ) break;
   56821       rc = walIndexAppend(pWal, iFrame, pgno);
   56822       if( rc!=SQLITE_OK ) break;
   56823 
   56824       /* If nTruncate is non-zero, this is a commit record. */
   56825       if( nTruncate ){
   56826         pWal->hdr.mxFrame = iFrame;
   56827         pWal->hdr.nPage = nTruncate;
   56828         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   56829         testcase( szPage<=32768 );
   56830         testcase( szPage>=65536 );
   56831         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
   56832         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
   56833       }
   56834     }
   56835 
   56836     sqlite3_free(aFrame);
   56837   }
   56838 
   56839 finished:
   56840   if( rc==SQLITE_OK ){
   56841     volatile WalCkptInfo *pInfo;
   56842     int i;
   56843     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
   56844     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
   56845     walIndexWriteHdr(pWal);
   56846 
   56847     /* Reset the checkpoint-header. This is safe because this thread is
   56848     ** currently holding locks that exclude all other readers, writers and
   56849     ** checkpointers.
   56850     */
   56851     pInfo = walCkptInfo(pWal);
   56852     pInfo->nBackfill = 0;
   56853     pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
   56854     pInfo->aReadMark[0] = 0;
   56855     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   56856     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
   56857 
   56858     /* If more than one frame was recovered from the log file, report an
   56859     ** event via sqlite3_log(). This is to help with identifying performance
   56860     ** problems caused by applications routinely shutting down without
   56861     ** checkpointing the log file.
   56862     */
   56863     if( pWal->hdr.nPage ){
   56864       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
   56865           "recovered %d frames from WAL file %s",
   56866           pWal->hdr.mxFrame, pWal->zWalName
   56867       );
   56868     }
   56869   }
   56870 
   56871 recovery_error:
   56872   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
   56873   walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
   56874   walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   56875   return rc;
   56876 }
   56877 
   56878 /*
   56879 ** Close an open wal-index.
   56880 */
   56881 static void walIndexClose(Wal *pWal, int isDelete){
   56882   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
   56883     int i;
   56884     for(i=0; i<pWal->nWiData; i++){
   56885       sqlite3_free((void *)pWal->apWiData[i]);
   56886       pWal->apWiData[i] = 0;
   56887     }
   56888   }
   56889   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
   56890     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
   56891   }
   56892 }
   56893 
   56894 /*
   56895 ** Open a connection to the WAL file zWalName. The database file must
   56896 ** already be opened on connection pDbFd. The buffer that zWalName points
   56897 ** to must remain valid for the lifetime of the returned Wal* handle.
   56898 **
   56899 ** A SHARED lock should be held on the database file when this function
   56900 ** is called. The purpose of this SHARED lock is to prevent any other
   56901 ** client from unlinking the WAL or wal-index file. If another process
   56902 ** were to do this just after this client opened one of these files, the
   56903 ** system would be badly broken.
   56904 **
   56905 ** If the log file is successfully opened, SQLITE_OK is returned and
   56906 ** *ppWal is set to point to a new WAL handle. If an error occurs,
   56907 ** an SQLite error code is returned and *ppWal is left unmodified.
   56908 */
   56909 SQLITE_PRIVATE int sqlite3WalOpen(
   56910   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
   56911   sqlite3_file *pDbFd,            /* The open database file */
   56912   const char *zWalName,           /* Name of the WAL file */
   56913   int bNoShm,                     /* True to run in heap-memory mode */
   56914   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
   56915   Wal **ppWal                     /* OUT: Allocated Wal handle */
   56916 ){
   56917   int rc;                         /* Return Code */
   56918   Wal *pRet;                      /* Object to allocate and return */
   56919   int flags;                      /* Flags passed to OsOpen() */
   56920 
   56921   assert( zWalName && zWalName[0] );
   56922   assert( pDbFd );
   56923 
   56924   /* In the amalgamation, the os_unix.c and os_win.c source files come before
   56925   ** this source file.  Verify that the #defines of the locking byte offsets
   56926   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
   56927   ** For that matter, if the lock offset ever changes from its initial design
   56928   ** value of 120, we need to know that so there is an assert() to check it.
   56929   */
   56930   assert( 120==WALINDEX_LOCK_OFFSET );
   56931   assert( 136==WALINDEX_HDR_SIZE );
   56932 #ifdef WIN_SHM_BASE
   56933   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
   56934 #endif
   56935 #ifdef UNIX_SHM_BASE
   56936   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
   56937 #endif
   56938 
   56939 
   56940   /* Allocate an instance of struct Wal to return. */
   56941   *ppWal = 0;
   56942   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
   56943   if( !pRet ){
   56944     return SQLITE_NOMEM_BKPT;
   56945   }
   56946 
   56947   pRet->pVfs = pVfs;
   56948   pRet->pWalFd = (sqlite3_file *)&pRet[1];
   56949   pRet->pDbFd = pDbFd;
   56950   pRet->readLock = -1;
   56951   pRet->mxWalSize = mxWalSize;
   56952   pRet->zWalName = zWalName;
   56953   pRet->syncHeader = 1;
   56954   pRet->padToSectorBoundary = 1;
   56955   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
   56956 
   56957   /* Open file handle on the write-ahead log file. */
   56958   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
   56959   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
   56960   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
   56961     pRet->readOnly = WAL_RDONLY;
   56962   }
   56963 
   56964   if( rc!=SQLITE_OK ){
   56965     walIndexClose(pRet, 0);
   56966     sqlite3OsClose(pRet->pWalFd);
   56967     sqlite3_free(pRet);
   56968   }else{
   56969     int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
   56970     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
   56971     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
   56972       pRet->padToSectorBoundary = 0;
   56973     }
   56974     *ppWal = pRet;
   56975     WALTRACE(("WAL%d: opened\n", pRet));
   56976   }
   56977   return rc;
   56978 }
   56979 
   56980 /*
   56981 ** Change the size to which the WAL file is trucated on each reset.
   56982 */
   56983 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
   56984   if( pWal ) pWal->mxWalSize = iLimit;
   56985 }
   56986 
   56987 /*
   56988 ** Find the smallest page number out of all pages held in the WAL that
   56989 ** has not been returned by any prior invocation of this method on the
   56990 ** same WalIterator object.   Write into *piFrame the frame index where
   56991 ** that page was last written into the WAL.  Write into *piPage the page
   56992 ** number.
   56993 **
   56994 ** Return 0 on success.  If there are no pages in the WAL with a page
   56995 ** number larger than *piPage, then return 1.
   56996 */
   56997 static int walIteratorNext(
   56998   WalIterator *p,               /* Iterator */
   56999   u32 *piPage,                  /* OUT: The page number of the next page */
   57000   u32 *piFrame                  /* OUT: Wal frame index of next page */
   57001 ){
   57002   u32 iMin;                     /* Result pgno must be greater than iMin */
   57003   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
   57004   int i;                        /* For looping through segments */
   57005 
   57006   iMin = p->iPrior;
   57007   assert( iMin<0xffffffff );
   57008   for(i=p->nSegment-1; i>=0; i--){
   57009     struct WalSegment *pSegment = &p->aSegment[i];
   57010     while( pSegment->iNext<pSegment->nEntry ){
   57011       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
   57012       if( iPg>iMin ){
   57013         if( iPg<iRet ){
   57014           iRet = iPg;
   57015           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
   57016         }
   57017         break;
   57018       }
   57019       pSegment->iNext++;
   57020     }
   57021   }
   57022 
   57023   *piPage = p->iPrior = iRet;
   57024   return (iRet==0xFFFFFFFF);
   57025 }
   57026 
   57027 /*
   57028 ** This function merges two sorted lists into a single sorted list.
   57029 **
   57030 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
   57031 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
   57032 ** is guaranteed for all J<K:
   57033 **
   57034 **        aContent[aLeft[J]] < aContent[aLeft[K]]
   57035 **        aContent[aRight[J]] < aContent[aRight[K]]
   57036 **
   57037 ** This routine overwrites aRight[] with a new (probably longer) sequence
   57038 ** of indices such that the aRight[] contains every index that appears in
   57039 ** either aLeft[] or the old aRight[] and such that the second condition
   57040 ** above is still met.
   57041 **
   57042 ** The aContent[aLeft[X]] values will be unique for all X.  And the
   57043 ** aContent[aRight[X]] values will be unique too.  But there might be
   57044 ** one or more combinations of X and Y such that
   57045 **
   57046 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
   57047 **
   57048 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
   57049 */
   57050 static void walMerge(
   57051   const u32 *aContent,            /* Pages in wal - keys for the sort */
   57052   ht_slot *aLeft,                 /* IN: Left hand input list */
   57053   int nLeft,                      /* IN: Elements in array *paLeft */
   57054   ht_slot **paRight,              /* IN/OUT: Right hand input list */
   57055   int *pnRight,                   /* IN/OUT: Elements in *paRight */
   57056   ht_slot *aTmp                   /* Temporary buffer */
   57057 ){
   57058   int iLeft = 0;                  /* Current index in aLeft */
   57059   int iRight = 0;                 /* Current index in aRight */
   57060   int iOut = 0;                   /* Current index in output buffer */
   57061   int nRight = *pnRight;
   57062   ht_slot *aRight = *paRight;
   57063 
   57064   assert( nLeft>0 && nRight>0 );
   57065   while( iRight<nRight || iLeft<nLeft ){
   57066     ht_slot logpage;
   57067     Pgno dbpage;
   57068 
   57069     if( (iLeft<nLeft)
   57070      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
   57071     ){
   57072       logpage = aLeft[iLeft++];
   57073     }else{
   57074       logpage = aRight[iRight++];
   57075     }
   57076     dbpage = aContent[logpage];
   57077 
   57078     aTmp[iOut++] = logpage;
   57079     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
   57080 
   57081     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
   57082     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
   57083   }
   57084 
   57085   *paRight = aLeft;
   57086   *pnRight = iOut;
   57087   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
   57088 }
   57089 
   57090 /*
   57091 ** Sort the elements in list aList using aContent[] as the sort key.
   57092 ** Remove elements with duplicate keys, preferring to keep the
   57093 ** larger aList[] values.
   57094 **
   57095 ** The aList[] entries are indices into aContent[].  The values in
   57096 ** aList[] are to be sorted so that for all J<K:
   57097 **
   57098 **      aContent[aList[J]] < aContent[aList[K]]
   57099 **
   57100 ** For any X and Y such that
   57101 **
   57102 **      aContent[aList[X]] == aContent[aList[Y]]
   57103 **
   57104 ** Keep the larger of the two values aList[X] and aList[Y] and discard
   57105 ** the smaller.
   57106 */
   57107 static void walMergesort(
   57108   const u32 *aContent,            /* Pages in wal */
   57109   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
   57110   ht_slot *aList,                 /* IN/OUT: List to sort */
   57111   int *pnList                     /* IN/OUT: Number of elements in aList[] */
   57112 ){
   57113   struct Sublist {
   57114     int nList;                    /* Number of elements in aList */
   57115     ht_slot *aList;               /* Pointer to sub-list content */
   57116   };
   57117 
   57118   const int nList = *pnList;      /* Size of input list */
   57119   int nMerge = 0;                 /* Number of elements in list aMerge */
   57120   ht_slot *aMerge = 0;            /* List to be merged */
   57121   int iList;                      /* Index into input list */
   57122   u32 iSub = 0;                   /* Index into aSub array */
   57123   struct Sublist aSub[13];        /* Array of sub-lists */
   57124 
   57125   memset(aSub, 0, sizeof(aSub));
   57126   assert( nList<=HASHTABLE_NPAGE && nList>0 );
   57127   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
   57128 
   57129   for(iList=0; iList<nList; iList++){
   57130     nMerge = 1;
   57131     aMerge = &aList[iList];
   57132     for(iSub=0; iList & (1<<iSub); iSub++){
   57133       struct Sublist *p;
   57134       assert( iSub<ArraySize(aSub) );
   57135       p = &aSub[iSub];
   57136       assert( p->aList && p->nList<=(1<<iSub) );
   57137       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
   57138       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   57139     }
   57140     aSub[iSub].aList = aMerge;
   57141     aSub[iSub].nList = nMerge;
   57142   }
   57143 
   57144   for(iSub++; iSub<ArraySize(aSub); iSub++){
   57145     if( nList & (1<<iSub) ){
   57146       struct Sublist *p;
   57147       assert( iSub<ArraySize(aSub) );
   57148       p = &aSub[iSub];
   57149       assert( p->nList<=(1<<iSub) );
   57150       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
   57151       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   57152     }
   57153   }
   57154   assert( aMerge==aList );
   57155   *pnList = nMerge;
   57156 
   57157 #ifdef SQLITE_DEBUG
   57158   {
   57159     int i;
   57160     for(i=1; i<*pnList; i++){
   57161       assert( aContent[aList[i]] > aContent[aList[i-1]] );
   57162     }
   57163   }
   57164 #endif
   57165 }
   57166 
   57167 /*
   57168 ** Free an iterator allocated by walIteratorInit().
   57169 */
   57170 static void walIteratorFree(WalIterator *p){
   57171   sqlite3_free(p);
   57172 }
   57173 
   57174 /*
   57175 ** Construct a WalInterator object that can be used to loop over all
   57176 ** pages in the WAL in ascending order. The caller must hold the checkpoint
   57177 ** lock.
   57178 **
   57179 ** On success, make *pp point to the newly allocated WalInterator object
   57180 ** return SQLITE_OK. Otherwise, return an error code. If this routine
   57181 ** returns an error, the value of *pp is undefined.
   57182 **
   57183 ** The calling routine should invoke walIteratorFree() to destroy the
   57184 ** WalIterator object when it has finished with it.
   57185 */
   57186 static int walIteratorInit(Wal *pWal, WalIterator **pp){
   57187   WalIterator *p;                 /* Return value */
   57188   int nSegment;                   /* Number of segments to merge */
   57189   u32 iLast;                      /* Last frame in log */
   57190   int nByte;                      /* Number of bytes to allocate */
   57191   int i;                          /* Iterator variable */
   57192   ht_slot *aTmp;                  /* Temp space used by merge-sort */
   57193   int rc = SQLITE_OK;             /* Return Code */
   57194 
   57195   /* This routine only runs while holding the checkpoint lock. And
   57196   ** it only runs if there is actually content in the log (mxFrame>0).
   57197   */
   57198   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
   57199   iLast = pWal->hdr.mxFrame;
   57200 
   57201   /* Allocate space for the WalIterator object. */
   57202   nSegment = walFramePage(iLast) + 1;
   57203   nByte = sizeof(WalIterator)
   57204         + (nSegment-1)*sizeof(struct WalSegment)
   57205         + iLast*sizeof(ht_slot);
   57206   p = (WalIterator *)sqlite3_malloc64(nByte);
   57207   if( !p ){
   57208     return SQLITE_NOMEM_BKPT;
   57209   }
   57210   memset(p, 0, nByte);
   57211   p->nSegment = nSegment;
   57212 
   57213   /* Allocate temporary space used by the merge-sort routine. This block
   57214   ** of memory will be freed before this function returns.
   57215   */
   57216   aTmp = (ht_slot *)sqlite3_malloc64(
   57217       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
   57218   );
   57219   if( !aTmp ){
   57220     rc = SQLITE_NOMEM_BKPT;
   57221   }
   57222 
   57223   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
   57224     volatile ht_slot *aHash;
   57225     u32 iZero;
   57226     volatile u32 *aPgno;
   57227 
   57228     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
   57229     if( rc==SQLITE_OK ){
   57230       int j;                      /* Counter variable */
   57231       int nEntry;                 /* Number of entries in this segment */
   57232       ht_slot *aIndex;            /* Sorted index for this segment */
   57233 
   57234       aPgno++;
   57235       if( (i+1)==nSegment ){
   57236         nEntry = (int)(iLast - iZero);
   57237       }else{
   57238         nEntry = (int)((u32*)aHash - (u32*)aPgno);
   57239       }
   57240       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
   57241       iZero++;
   57242 
   57243       for(j=0; j<nEntry; j++){
   57244         aIndex[j] = (ht_slot)j;
   57245       }
   57246       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
   57247       p->aSegment[i].iZero = iZero;
   57248       p->aSegment[i].nEntry = nEntry;
   57249       p->aSegment[i].aIndex = aIndex;
   57250       p->aSegment[i].aPgno = (u32 *)aPgno;
   57251     }
   57252   }
   57253   sqlite3_free(aTmp);
   57254 
   57255   if( rc!=SQLITE_OK ){
   57256     walIteratorFree(p);
   57257   }
   57258   *pp = p;
   57259   return rc;
   57260 }
   57261 
   57262 /*
   57263 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
   57264 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
   57265 ** busy-handler function. Invoke it and retry the lock until either the
   57266 ** lock is successfully obtained or the busy-handler returns 0.
   57267 */
   57268 static int walBusyLock(
   57269   Wal *pWal,                      /* WAL connection */
   57270   int (*xBusy)(void*),            /* Function to call when busy */
   57271   void *pBusyArg,                 /* Context argument for xBusyHandler */
   57272   int lockIdx,                    /* Offset of first byte to lock */
   57273   int n                           /* Number of bytes to lock */
   57274 ){
   57275   int rc;
   57276   do {
   57277     rc = walLockExclusive(pWal, lockIdx, n);
   57278   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
   57279   return rc;
   57280 }
   57281 
   57282 /*
   57283 ** The cache of the wal-index header must be valid to call this function.
   57284 ** Return the page-size in bytes used by the database.
   57285 */
   57286 static int walPagesize(Wal *pWal){
   57287   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   57288 }
   57289 
   57290 /*
   57291 ** The following is guaranteed when this function is called:
   57292 **
   57293 **   a) the WRITER lock is held,
   57294 **   b) the entire log file has been checkpointed, and
   57295 **   c) any existing readers are reading exclusively from the database
   57296 **      file - there are no readers that may attempt to read a frame from
   57297 **      the log file.
   57298 **
   57299 ** This function updates the shared-memory structures so that the next
   57300 ** client to write to the database (which may be this one) does so by
   57301 ** writing frames into the start of the log file.
   57302 **
   57303 ** The value of parameter salt1 is used as the aSalt[1] value in the
   57304 ** new wal-index header. It should be passed a pseudo-random value (i.e.
   57305 ** one obtained from sqlite3_randomness()).
   57306 */
   57307 static void walRestartHdr(Wal *pWal, u32 salt1){
   57308   volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   57309   int i;                          /* Loop counter */
   57310   u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
   57311   pWal->nCkpt++;
   57312   pWal->hdr.mxFrame = 0;
   57313   sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
   57314   memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
   57315   walIndexWriteHdr(pWal);
   57316   pInfo->nBackfill = 0;
   57317   pInfo->nBackfillAttempted = 0;
   57318   pInfo->aReadMark[1] = 0;
   57319   for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   57320   assert( pInfo->aReadMark[0]==0 );
   57321 }
   57322 
   57323 /*
   57324 ** Copy as much content as we can from the WAL back into the database file
   57325 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
   57326 **
   57327 ** The amount of information copies from WAL to database might be limited
   57328 ** by active readers.  This routine will never overwrite a database page
   57329 ** that a concurrent reader might be using.
   57330 **
   57331 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
   57332 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
   57333 ** checkpoints are always run by a background thread or background
   57334 ** process, foreground threads will never block on a lengthy fsync call.
   57335 **
   57336 ** Fsync is called on the WAL before writing content out of the WAL and
   57337 ** into the database.  This ensures that if the new content is persistent
   57338 ** in the WAL and can be recovered following a power-loss or hard reset.
   57339 **
   57340 ** Fsync is also called on the database file if (and only if) the entire
   57341 ** WAL content is copied into the database file.  This second fsync makes
   57342 ** it safe to delete the WAL since the new content will persist in the
   57343 ** database file.
   57344 **
   57345 ** This routine uses and updates the nBackfill field of the wal-index header.
   57346 ** This is the only routine that will increase the value of nBackfill.
   57347 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
   57348 ** its value.)
   57349 **
   57350 ** The caller must be holding sufficient locks to ensure that no other
   57351 ** checkpoint is running (in any other thread or process) at the same
   57352 ** time.
   57353 */
   57354 static int walCheckpoint(
   57355   Wal *pWal,                      /* Wal connection */
   57356   sqlite3 *db,                    /* Check for interrupts on this handle */
   57357   int eMode,                      /* One of PASSIVE, FULL or RESTART */
   57358   int (*xBusy)(void*),            /* Function to call when busy */
   57359   void *pBusyArg,                 /* Context argument for xBusyHandler */
   57360   int sync_flags,                 /* Flags for OsSync() (or 0) */
   57361   u8 *zBuf                        /* Temporary buffer to use */
   57362 ){
   57363   int rc = SQLITE_OK;             /* Return code */
   57364   int szPage;                     /* Database page-size */
   57365   WalIterator *pIter = 0;         /* Wal iterator context */
   57366   u32 iDbpage = 0;                /* Next database page to write */
   57367   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
   57368   u32 mxSafeFrame;                /* Max frame that can be backfilled */
   57369   u32 mxPage;                     /* Max database page to write */
   57370   int i;                          /* Loop counter */
   57371   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
   57372 
   57373   szPage = walPagesize(pWal);
   57374   testcase( szPage<=32768 );
   57375   testcase( szPage>=65536 );
   57376   pInfo = walCkptInfo(pWal);
   57377   if( pInfo->nBackfill<pWal->hdr.mxFrame ){
   57378 
   57379     /* Allocate the iterator */
   57380     rc = walIteratorInit(pWal, &pIter);
   57381     if( rc!=SQLITE_OK ){
   57382       return rc;
   57383     }
   57384     assert( pIter );
   57385 
   57386     /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
   57387     ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
   57388     assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
   57389 
   57390     /* Compute in mxSafeFrame the index of the last frame of the WAL that is
   57391     ** safe to write into the database.  Frames beyond mxSafeFrame might
   57392     ** overwrite database pages that are in use by active readers and thus
   57393     ** cannot be backfilled from the WAL.
   57394     */
   57395     mxSafeFrame = pWal->hdr.mxFrame;
   57396     mxPage = pWal->hdr.nPage;
   57397     for(i=1; i<WAL_NREADER; i++){
   57398       /* Thread-sanitizer reports that the following is an unsafe read,
   57399       ** as some other thread may be in the process of updating the value
   57400       ** of the aReadMark[] slot. The assumption here is that if that is
   57401       ** happening, the other client may only be increasing the value,
   57402       ** not decreasing it. So assuming either that either the "old" or
   57403       ** "new" version of the value is read, and not some arbitrary value
   57404       ** that would never be written by a real client, things are still
   57405       ** safe.  */
   57406       u32 y = pInfo->aReadMark[i];
   57407       if( mxSafeFrame>y ){
   57408         assert( y<=pWal->hdr.mxFrame );
   57409         rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
   57410         if( rc==SQLITE_OK ){
   57411           pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
   57412           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   57413         }else if( rc==SQLITE_BUSY ){
   57414           mxSafeFrame = y;
   57415           xBusy = 0;
   57416         }else{
   57417           goto walcheckpoint_out;
   57418         }
   57419       }
   57420     }
   57421 
   57422     if( pInfo->nBackfill<mxSafeFrame
   57423      && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
   57424     ){
   57425       i64 nSize;                    /* Current size of database file */
   57426       u32 nBackfill = pInfo->nBackfill;
   57427 
   57428       pInfo->nBackfillAttempted = mxSafeFrame;
   57429 
   57430       /* Sync the WAL to disk */
   57431       rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
   57432 
   57433       /* If the database may grow as a result of this checkpoint, hint
   57434       ** about the eventual size of the db file to the VFS layer.
   57435       */
   57436       if( rc==SQLITE_OK ){
   57437         i64 nReq = ((i64)mxPage * szPage);
   57438         rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
   57439         if( rc==SQLITE_OK && nSize<nReq ){
   57440           sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
   57441         }
   57442       }
   57443 
   57444 
   57445       /* Iterate through the contents of the WAL, copying data to the db file */
   57446       while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
   57447         i64 iOffset;
   57448         assert( walFramePgno(pWal, iFrame)==iDbpage );
   57449         if( db->u1.isInterrupted ){
   57450           rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
   57451           break;
   57452         }
   57453         if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
   57454           continue;
   57455         }
   57456         iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
   57457         /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
   57458         rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
   57459         if( rc!=SQLITE_OK ) break;
   57460         iOffset = (iDbpage-1)*(i64)szPage;
   57461         testcase( IS_BIG_INT(iOffset) );
   57462         rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
   57463         if( rc!=SQLITE_OK ) break;
   57464       }
   57465 
   57466       /* If work was actually accomplished... */
   57467       if( rc==SQLITE_OK ){
   57468         if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
   57469           i64 szDb = pWal->hdr.nPage*(i64)szPage;
   57470           testcase( IS_BIG_INT(szDb) );
   57471           rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
   57472           if( rc==SQLITE_OK ){
   57473             rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
   57474           }
   57475         }
   57476         if( rc==SQLITE_OK ){
   57477           pInfo->nBackfill = mxSafeFrame;
   57478         }
   57479       }
   57480 
   57481       /* Release the reader lock held while backfilling */
   57482       walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
   57483     }
   57484 
   57485     if( rc==SQLITE_BUSY ){
   57486       /* Reset the return code so as not to report a checkpoint failure
   57487       ** just because there are active readers.  */
   57488       rc = SQLITE_OK;
   57489     }
   57490   }
   57491 
   57492   /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
   57493   ** entire wal file has been copied into the database file, then block
   57494   ** until all readers have finished using the wal file. This ensures that
   57495   ** the next process to write to the database restarts the wal file.
   57496   */
   57497   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   57498     assert( pWal->writeLock );
   57499     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
   57500       rc = SQLITE_BUSY;
   57501     }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
   57502       u32 salt1;
   57503       sqlite3_randomness(4, &salt1);
   57504       assert( pInfo->nBackfill==pWal->hdr.mxFrame );
   57505       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
   57506       if( rc==SQLITE_OK ){
   57507         if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
   57508           /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
   57509           ** SQLITE_CHECKPOINT_RESTART with the addition that it also
   57510           ** truncates the log file to zero bytes just prior to a
   57511           ** successful return.
   57512           **
   57513           ** In theory, it might be safe to do this without updating the
   57514           ** wal-index header in shared memory, as all subsequent reader or
   57515           ** writer clients should see that the entire log file has been
   57516           ** checkpointed and behave accordingly. This seems unsafe though,
   57517           ** as it would leave the system in a state where the contents of
   57518           ** the wal-index header do not match the contents of the
   57519           ** file-system. To avoid this, update the wal-index header to
   57520           ** indicate that the log file contains zero valid frames.  */
   57521           walRestartHdr(pWal, salt1);
   57522           rc = sqlite3OsTruncate(pWal->pWalFd, 0);
   57523         }
   57524         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   57525       }
   57526     }
   57527   }
   57528 
   57529  walcheckpoint_out:
   57530   walIteratorFree(pIter);
   57531   return rc;
   57532 }
   57533 
   57534 /*
   57535 ** If the WAL file is currently larger than nMax bytes in size, truncate
   57536 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
   57537 */
   57538 static void walLimitSize(Wal *pWal, i64 nMax){
   57539   i64 sz;
   57540   int rx;
   57541   sqlite3BeginBenignMalloc();
   57542   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
   57543   if( rx==SQLITE_OK && (sz > nMax ) ){
   57544     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
   57545   }
   57546   sqlite3EndBenignMalloc();
   57547   if( rx ){
   57548     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
   57549   }
   57550 }
   57551 
   57552 /*
   57553 ** Close a connection to a log file.
   57554 */
   57555 SQLITE_PRIVATE int sqlite3WalClose(
   57556   Wal *pWal,                      /* Wal to close */
   57557   sqlite3 *db,                    /* For interrupt flag */
   57558   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
   57559   int nBuf,
   57560   u8 *zBuf                        /* Buffer of at least nBuf bytes */
   57561 ){
   57562   int rc = SQLITE_OK;
   57563   if( pWal ){
   57564     int isDelete = 0;             /* True to unlink wal and wal-index files */
   57565 
   57566     /* If an EXCLUSIVE lock can be obtained on the database file (using the
   57567     ** ordinary, rollback-mode locking methods, this guarantees that the
   57568     ** connection associated with this log file is the only connection to
   57569     ** the database. In this case checkpoint the database and unlink both
   57570     ** the wal and wal-index files.
   57571     **
   57572     ** The EXCLUSIVE lock is not released before returning.
   57573     */
   57574     if( zBuf!=0
   57575      && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
   57576     ){
   57577       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
   57578         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   57579       }
   57580       rc = sqlite3WalCheckpoint(pWal, db,
   57581           SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
   57582       );
   57583       if( rc==SQLITE_OK ){
   57584         int bPersist = -1;
   57585         sqlite3OsFileControlHint(
   57586             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
   57587         );
   57588         if( bPersist!=1 ){
   57589           /* Try to delete the WAL file if the checkpoint completed and
   57590           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
   57591           ** mode (!bPersist) */
   57592           isDelete = 1;
   57593         }else if( pWal->mxWalSize>=0 ){
   57594           /* Try to truncate the WAL file to zero bytes if the checkpoint
   57595           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
   57596           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
   57597           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
   57598           ** to zero bytes as truncating to the journal_size_limit might
   57599           ** leave a corrupt WAL file on disk. */
   57600           walLimitSize(pWal, 0);
   57601         }
   57602       }
   57603     }
   57604 
   57605     walIndexClose(pWal, isDelete);
   57606     sqlite3OsClose(pWal->pWalFd);
   57607     if( isDelete ){
   57608       sqlite3BeginBenignMalloc();
   57609       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
   57610       sqlite3EndBenignMalloc();
   57611     }
   57612     WALTRACE(("WAL%p: closed\n", pWal));
   57613     sqlite3_free((void *)pWal->apWiData);
   57614     sqlite3_free(pWal);
   57615   }
   57616   return rc;
   57617 }
   57618 
   57619 /*
   57620 ** Try to read the wal-index header.  Return 0 on success and 1 if
   57621 ** there is a problem.
   57622 **
   57623 ** The wal-index is in shared memory.  Another thread or process might
   57624 ** be writing the header at the same time this procedure is trying to
   57625 ** read it, which might result in inconsistency.  A dirty read is detected
   57626 ** by verifying that both copies of the header are the same and also by
   57627 ** a checksum on the header.
   57628 **
   57629 ** If and only if the read is consistent and the header is different from
   57630 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
   57631 ** and *pChanged is set to 1.
   57632 **
   57633 ** If the checksum cannot be verified return non-zero. If the header
   57634 ** is read successfully and the checksum verified, return zero.
   57635 */
   57636 static int walIndexTryHdr(Wal *pWal, int *pChanged){
   57637   u32 aCksum[2];                  /* Checksum on the header content */
   57638   WalIndexHdr h1, h2;             /* Two copies of the header content */
   57639   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
   57640 
   57641   /* The first page of the wal-index must be mapped at this point. */
   57642   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   57643 
   57644   /* Read the header. This might happen concurrently with a write to the
   57645   ** same area of shared memory on a different CPU in a SMP,
   57646   ** meaning it is possible that an inconsistent snapshot is read
   57647   ** from the file. If this happens, return non-zero.
   57648   **
   57649   ** There are two copies of the header at the beginning of the wal-index.
   57650   ** When reading, read [0] first then [1].  Writes are in the reverse order.
   57651   ** Memory barriers are used to prevent the compiler or the hardware from
   57652   ** reordering the reads and writes.
   57653   */
   57654   aHdr = walIndexHdr(pWal);
   57655   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
   57656   walShmBarrier(pWal);
   57657   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
   57658 
   57659   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
   57660     return 1;   /* Dirty read */
   57661   }
   57662   if( h1.isInit==0 ){
   57663     return 1;   /* Malformed header - probably all zeros */
   57664   }
   57665   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
   57666   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
   57667     return 1;   /* Checksum does not match */
   57668   }
   57669 
   57670   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
   57671     *pChanged = 1;
   57672     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
   57673     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   57674     testcase( pWal->szPage<=32768 );
   57675     testcase( pWal->szPage>=65536 );
   57676   }
   57677 
   57678   /* The header was successfully read. Return zero. */
   57679   return 0;
   57680 }
   57681 
   57682 /*
   57683 ** This is the value that walTryBeginRead returns when it needs to
   57684 ** be retried.
   57685 */
   57686 #define WAL_RETRY  (-1)
   57687 
   57688 /*
   57689 ** Read the wal-index header from the wal-index and into pWal->hdr.
   57690 ** If the wal-header appears to be corrupt, try to reconstruct the
   57691 ** wal-index from the WAL before returning.
   57692 **
   57693 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
   57694 ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
   57695 ** to 0.
   57696 **
   57697 ** If the wal-index header is successfully read, return SQLITE_OK.
   57698 ** Otherwise an SQLite error code.
   57699 */
   57700 static int walIndexReadHdr(Wal *pWal, int *pChanged){
   57701   int rc;                         /* Return code */
   57702   int badHdr;                     /* True if a header read failed */
   57703   volatile u32 *page0;            /* Chunk of wal-index containing header */
   57704 
   57705   /* Ensure that page 0 of the wal-index (the page that contains the
   57706   ** wal-index header) is mapped. Return early if an error occurs here.
   57707   */
   57708   assert( pChanged );
   57709   rc = walIndexPage(pWal, 0, &page0);
   57710   if( rc!=SQLITE_OK ){
   57711     assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
   57712     if( rc==SQLITE_READONLY_CANTINIT ){
   57713       /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
   57714       ** was openable but is not writable, and this thread is unable to
   57715       ** confirm that another write-capable connection has the shared-memory
   57716       ** open, and hence the content of the shared-memory is unreliable,
   57717       ** since the shared-memory might be inconsistent with the WAL file
   57718       ** and there is no writer on hand to fix it. */
   57719       assert( page0==0 );
   57720       assert( pWal->writeLock==0 );
   57721       assert( pWal->readOnly & WAL_SHM_RDONLY );
   57722       pWal->bShmUnreliable = 1;
   57723       pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
   57724       *pChanged = 1;
   57725     }else{
   57726       return rc; /* Any other non-OK return is just an error */
   57727     }
   57728   }else{
   57729     /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
   57730     ** is zero, which prevents the SHM from growing */
   57731     testcase( page0!=0 );
   57732   }
   57733   assert( page0!=0 || pWal->writeLock==0 );
   57734 
   57735   /* If the first page of the wal-index has been mapped, try to read the
   57736   ** wal-index header immediately, without holding any lock. This usually
   57737   ** works, but may fail if the wal-index header is corrupt or currently
   57738   ** being modified by another thread or process.
   57739   */
   57740   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
   57741 
   57742   /* If the first attempt failed, it might have been due to a race
   57743   ** with a writer.  So get a WRITE lock and try again.
   57744   */
   57745   assert( badHdr==0 || pWal->writeLock==0 );
   57746   if( badHdr ){
   57747     if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
   57748       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
   57749         walUnlockShared(pWal, WAL_WRITE_LOCK);
   57750         rc = SQLITE_READONLY_RECOVERY;
   57751       }
   57752     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
   57753       pWal->writeLock = 1;
   57754       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
   57755         badHdr = walIndexTryHdr(pWal, pChanged);
   57756         if( badHdr ){
   57757           /* If the wal-index header is still malformed even while holding
   57758           ** a WRITE lock, it can only mean that the header is corrupted and
   57759           ** needs to be reconstructed.  So run recovery to do exactly that.
   57760           */
   57761           rc = walIndexRecover(pWal);
   57762           *pChanged = 1;
   57763         }
   57764       }
   57765       pWal->writeLock = 0;
   57766       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   57767     }
   57768   }
   57769 
   57770   /* If the header is read successfully, check the version number to make
   57771   ** sure the wal-index was not constructed with some future format that
   57772   ** this version of SQLite cannot understand.
   57773   */
   57774   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
   57775     rc = SQLITE_CANTOPEN_BKPT;
   57776   }
   57777   if( pWal->bShmUnreliable ){
   57778     if( rc!=SQLITE_OK ){
   57779       walIndexClose(pWal, 0);
   57780       pWal->bShmUnreliable = 0;
   57781       assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
   57782       /* walIndexRecover() might have returned SHORT_READ if a concurrent
   57783       ** writer truncated the WAL out from under it.  If that happens, it
   57784       ** indicates that a writer has fixed the SHM file for us, so retry */
   57785       if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
   57786     }
   57787     pWal->exclusiveMode = WAL_NORMAL_MODE;
   57788   }
   57789 
   57790   return rc;
   57791 }
   57792 
   57793 /*
   57794 ** Open a transaction in a connection where the shared-memory is read-only
   57795 ** and where we cannot verify that there is a separate write-capable connection
   57796 ** on hand to keep the shared-memory up-to-date with the WAL file.
   57797 **
   57798 ** This can happen, for example, when the shared-memory is implemented by
   57799 ** memory-mapping a *-shm file, where a prior writer has shut down and
   57800 ** left the *-shm file on disk, and now the present connection is trying
   57801 ** to use that database but lacks write permission on the *-shm file.
   57802 ** Other scenarios are also possible, depending on the VFS implementation.
   57803 **
   57804 ** Precondition:
   57805 **
   57806 **    The *-wal file has been read and an appropriate wal-index has been
   57807 **    constructed in pWal->apWiData[] using heap memory instead of shared
   57808 **    memory.
   57809 **
   57810 ** If this function returns SQLITE_OK, then the read transaction has
   57811 ** been successfully opened. In this case output variable (*pChanged)
   57812 ** is set to true before returning if the caller should discard the
   57813 ** contents of the page cache before proceeding. Or, if it returns
   57814 ** WAL_RETRY, then the heap memory wal-index has been discarded and
   57815 ** the caller should retry opening the read transaction from the
   57816 ** beginning (including attempting to map the *-shm file).
   57817 **
   57818 ** If an error occurs, an SQLite error code is returned.
   57819 */
   57820 static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
   57821   i64 szWal;                      /* Size of wal file on disk in bytes */
   57822   i64 iOffset;                    /* Current offset when reading wal file */
   57823   u8 aBuf[WAL_HDRSIZE];           /* Buffer to load WAL header into */
   57824   u8 *aFrame = 0;                 /* Malloc'd buffer to load entire frame */
   57825   int szFrame;                    /* Number of bytes in buffer aFrame[] */
   57826   u8 *aData;                      /* Pointer to data part of aFrame buffer */
   57827   volatile void *pDummy;          /* Dummy argument for xShmMap */
   57828   int rc;                         /* Return code */
   57829   u32 aSaveCksum[2];              /* Saved copy of pWal->hdr.aFrameCksum */
   57830 
   57831   assert( pWal->bShmUnreliable );
   57832   assert( pWal->readOnly & WAL_SHM_RDONLY );
   57833   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   57834 
   57835   /* Take WAL_READ_LOCK(0). This has the effect of preventing any
   57836   ** writers from running a checkpoint, but does not stop them
   57837   ** from running recovery.  */
   57838   rc = walLockShared(pWal, WAL_READ_LOCK(0));
   57839   if( rc!=SQLITE_OK ){
   57840     if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
   57841     goto begin_unreliable_shm_out;
   57842   }
   57843   pWal->readLock = 0;
   57844 
   57845   /* Check to see if a separate writer has attached to the shared-memory area,
   57846   ** thus making the shared-memory "reliable" again.  Do this by invoking
   57847   ** the xShmMap() routine of the VFS and looking to see if the return
   57848   ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
   57849   **
   57850   ** If the shared-memory is now "reliable" return WAL_RETRY, which will
   57851   ** cause the heap-memory WAL-index to be discarded and the actual
   57852   ** shared memory to be used in its place.
   57853   **
   57854   ** This step is important because, even though this connection is holding
   57855   ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
   57856   ** have already checkpointed the WAL file and, while the current
   57857   ** is active, wrap the WAL and start overwriting frames that this
   57858   ** process wants to use.
   57859   **
   57860   ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
   57861   ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
   57862   ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
   57863   ** even if some external agent does a "chmod" to make the shared-memory
   57864   ** writable by us, until sqlite3OsShmUnmap() has been called.
   57865   ** This is a requirement on the VFS implementation.
   57866    */
   57867   rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
   57868   assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
   57869   if( rc!=SQLITE_READONLY_CANTINIT ){
   57870     rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
   57871     goto begin_unreliable_shm_out;
   57872   }
   57873 
   57874   /* We reach this point only if the real shared-memory is still unreliable.
   57875   ** Assume the in-memory WAL-index substitute is correct and load it
   57876   ** into pWal->hdr.
   57877   */
   57878   memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
   57879 
   57880   /* Make sure some writer hasn't come in and changed the WAL file out
   57881   ** from under us, then disconnected, while we were not looking.
   57882   */
   57883   rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
   57884   if( rc!=SQLITE_OK ){
   57885     goto begin_unreliable_shm_out;
   57886   }
   57887   if( szWal<WAL_HDRSIZE ){
   57888     /* If the wal file is too small to contain a wal-header and the
   57889     ** wal-index header has mxFrame==0, then it must be safe to proceed
   57890     ** reading the database file only. However, the page cache cannot
   57891     ** be trusted, as a read/write connection may have connected, written
   57892     ** the db, run a checkpoint, truncated the wal file and disconnected
   57893     ** since this client's last read transaction.  */
   57894     *pChanged = 1;
   57895     rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
   57896     goto begin_unreliable_shm_out;
   57897   }
   57898 
   57899   /* Check the salt keys at the start of the wal file still match. */
   57900   rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
   57901   if( rc!=SQLITE_OK ){
   57902     goto begin_unreliable_shm_out;
   57903   }
   57904   if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
   57905     /* Some writer has wrapped the WAL file while we were not looking.
   57906     ** Return WAL_RETRY which will cause the in-memory WAL-index to be
   57907     ** rebuilt. */
   57908     rc = WAL_RETRY;
   57909     goto begin_unreliable_shm_out;
   57910   }
   57911 
   57912   /* Allocate a buffer to read frames into */
   57913   szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
   57914   aFrame = (u8 *)sqlite3_malloc64(szFrame);
   57915   if( aFrame==0 ){
   57916     rc = SQLITE_NOMEM_BKPT;
   57917     goto begin_unreliable_shm_out;
   57918   }
   57919   aData = &aFrame[WAL_FRAME_HDRSIZE];
   57920 
   57921   /* Check to see if a complete transaction has been appended to the
   57922   ** wal file since the heap-memory wal-index was created. If so, the
   57923   ** heap-memory wal-index is discarded and WAL_RETRY returned to
   57924   ** the caller.  */
   57925   aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
   57926   aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
   57927   for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
   57928       iOffset+szFrame<=szWal;
   57929       iOffset+=szFrame
   57930   ){
   57931     u32 pgno;                   /* Database page number for frame */
   57932     u32 nTruncate;              /* dbsize field from frame header */
   57933 
   57934     /* Read and decode the next log frame. */
   57935     rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
   57936     if( rc!=SQLITE_OK ) break;
   57937     if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
   57938 
   57939     /* If nTruncate is non-zero, then a complete transaction has been
   57940     ** appended to this wal file. Set rc to WAL_RETRY and break out of
   57941     ** the loop.  */
   57942     if( nTruncate ){
   57943       rc = WAL_RETRY;
   57944       break;
   57945     }
   57946   }
   57947   pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
   57948   pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
   57949 
   57950  begin_unreliable_shm_out:
   57951   sqlite3_free(aFrame);
   57952   if( rc!=SQLITE_OK ){
   57953     int i;
   57954     for(i=0; i<pWal->nWiData; i++){
   57955       sqlite3_free((void*)pWal->apWiData[i]);
   57956       pWal->apWiData[i] = 0;
   57957     }
   57958     pWal->bShmUnreliable = 0;
   57959     sqlite3WalEndReadTransaction(pWal);
   57960     *pChanged = 1;
   57961   }
   57962   return rc;
   57963 }
   57964 
   57965 /*
   57966 ** Attempt to start a read transaction.  This might fail due to a race or
   57967 ** other transient condition.  When that happens, it returns WAL_RETRY to
   57968 ** indicate to the caller that it is safe to retry immediately.
   57969 **
   57970 ** On success return SQLITE_OK.  On a permanent failure (such an
   57971 ** I/O error or an SQLITE_BUSY because another process is running
   57972 ** recovery) return a positive error code.
   57973 **
   57974 ** The useWal parameter is true to force the use of the WAL and disable
   57975 ** the case where the WAL is bypassed because it has been completely
   57976 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
   57977 ** to make a copy of the wal-index header into pWal->hdr.  If the
   57978 ** wal-index header has changed, *pChanged is set to 1 (as an indication
   57979 ** to the caller that the local page cache is obsolete and needs to be
   57980 ** flushed.)  When useWal==1, the wal-index header is assumed to already
   57981 ** be loaded and the pChanged parameter is unused.
   57982 **
   57983 ** The caller must set the cnt parameter to the number of prior calls to
   57984 ** this routine during the current read attempt that returned WAL_RETRY.
   57985 ** This routine will start taking more aggressive measures to clear the
   57986 ** race conditions after multiple WAL_RETRY returns, and after an excessive
   57987 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
   57988 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
   57989 ** and is not honoring the locking protocol.  There is a vanishingly small
   57990 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
   57991 ** bad luck when there is lots of contention for the wal-index, but that
   57992 ** possibility is so small that it can be safely neglected, we believe.
   57993 **
   57994 ** On success, this routine obtains a read lock on
   57995 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
   57996 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
   57997 ** that means the Wal does not hold any read lock.  The reader must not
   57998 ** access any database page that is modified by a WAL frame up to and
   57999 ** including frame number aReadMark[pWal->readLock].  The reader will
   58000 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
   58001 ** Or if pWal->readLock==0, then the reader will ignore the WAL
   58002 ** completely and get all content directly from the database file.
   58003 ** If the useWal parameter is 1 then the WAL will never be ignored and
   58004 ** this routine will always set pWal->readLock>0 on success.
   58005 ** When the read transaction is completed, the caller must release the
   58006 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
   58007 **
   58008 ** This routine uses the nBackfill and aReadMark[] fields of the header
   58009 ** to select a particular WAL_READ_LOCK() that strives to let the
   58010 ** checkpoint process do as much work as possible.  This routine might
   58011 ** update values of the aReadMark[] array in the header, but if it does
   58012 ** so it takes care to hold an exclusive lock on the corresponding
   58013 ** WAL_READ_LOCK() while changing values.
   58014 */
   58015 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   58016   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
   58017   u32 mxReadMark;                 /* Largest aReadMark[] value */
   58018   int mxI;                        /* Index of largest aReadMark[] value */
   58019   int i;                          /* Loop counter */
   58020   int rc = SQLITE_OK;             /* Return code  */
   58021   u32 mxFrame;                    /* Wal frame to lock to */
   58022 
   58023   assert( pWal->readLock<0 );     /* Not currently locked */
   58024 
   58025   /* useWal may only be set for read/write connections */
   58026   assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
   58027 
   58028   /* Take steps to avoid spinning forever if there is a protocol error.
   58029   **
   58030   ** Circumstances that cause a RETRY should only last for the briefest
   58031   ** instances of time.  No I/O or other system calls are done while the
   58032   ** locks are held, so the locks should not be held for very long. But
   58033   ** if we are unlucky, another process that is holding a lock might get
   58034   ** paged out or take a page-fault that is time-consuming to resolve,
   58035   ** during the few nanoseconds that it is holding the lock.  In that case,
   58036   ** it might take longer than normal for the lock to free.
   58037   **
   58038   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
   58039   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
   58040   ** is more of a scheduler yield than an actual delay.  But on the 10th
   58041   ** an subsequent retries, the delays start becoming longer and longer,
   58042   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
   58043   ** The total delay time before giving up is less than 10 seconds.
   58044   */
   58045   if( cnt>5 ){
   58046     int nDelay = 1;                      /* Pause time in microseconds */
   58047     if( cnt>100 ){
   58048       VVA_ONLY( pWal->lockError = 1; )
   58049       return SQLITE_PROTOCOL;
   58050     }
   58051     if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
   58052     sqlite3OsSleep(pWal->pVfs, nDelay);
   58053   }
   58054 
   58055   if( !useWal ){
   58056     assert( rc==SQLITE_OK );
   58057     if( pWal->bShmUnreliable==0 ){
   58058       rc = walIndexReadHdr(pWal, pChanged);
   58059     }
   58060     if( rc==SQLITE_BUSY ){
   58061       /* If there is not a recovery running in another thread or process
   58062       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
   58063       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
   58064       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
   58065       ** would be technically correct.  But the race is benign since with
   58066       ** WAL_RETRY this routine will be called again and will probably be
   58067       ** right on the second iteration.
   58068       */
   58069       if( pWal->apWiData[0]==0 ){
   58070         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
   58071         ** We assume this is a transient condition, so return WAL_RETRY. The
   58072         ** xShmMap() implementation used by the default unix and win32 VFS
   58073         ** modules may return SQLITE_BUSY due to a race condition in the
   58074         ** code that determines whether or not the shared-memory region
   58075         ** must be zeroed before the requested page is returned.
   58076         */
   58077         rc = WAL_RETRY;
   58078       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
   58079         walUnlockShared(pWal, WAL_RECOVER_LOCK);
   58080         rc = WAL_RETRY;
   58081       }else if( rc==SQLITE_BUSY ){
   58082         rc = SQLITE_BUSY_RECOVERY;
   58083       }
   58084     }
   58085     if( rc!=SQLITE_OK ){
   58086       return rc;
   58087     }
   58088     else if( pWal->bShmUnreliable ){
   58089       return walBeginShmUnreliable(pWal, pChanged);
   58090     }
   58091   }
   58092 
   58093   assert( pWal->nWiData>0 );
   58094   assert( pWal->apWiData[0]!=0 );
   58095   pInfo = walCkptInfo(pWal);
   58096   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
   58097 #ifdef SQLITE_ENABLE_SNAPSHOT
   58098    && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
   58099 #endif
   58100   ){
   58101     /* The WAL has been completely backfilled (or it is empty).
   58102     ** and can be safely ignored.
   58103     */
   58104     rc = walLockShared(pWal, WAL_READ_LOCK(0));
   58105     walShmBarrier(pWal);
   58106     if( rc==SQLITE_OK ){
   58107       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
   58108         /* It is not safe to allow the reader to continue here if frames
   58109         ** may have been appended to the log before READ_LOCK(0) was obtained.
   58110         ** When holding READ_LOCK(0), the reader ignores the entire log file,
   58111         ** which implies that the database file contains a trustworthy
   58112         ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
   58113         ** happening, this is usually correct.
   58114         **
   58115         ** However, if frames have been appended to the log (or if the log
   58116         ** is wrapped and written for that matter) before the READ_LOCK(0)
   58117         ** is obtained, that is not necessarily true. A checkpointer may
   58118         ** have started to backfill the appended frames but crashed before
   58119         ** it finished. Leaving a corrupt image in the database file.
   58120         */
   58121         walUnlockShared(pWal, WAL_READ_LOCK(0));
   58122         return WAL_RETRY;
   58123       }
   58124       pWal->readLock = 0;
   58125       return SQLITE_OK;
   58126     }else if( rc!=SQLITE_BUSY ){
   58127       return rc;
   58128     }
   58129   }
   58130 
   58131   /* If we get this far, it means that the reader will want to use
   58132   ** the WAL to get at content from recent commits.  The job now is
   58133   ** to select one of the aReadMark[] entries that is closest to
   58134   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
   58135   */
   58136   mxReadMark = 0;
   58137   mxI = 0;
   58138   mxFrame = pWal->hdr.mxFrame;
   58139 #ifdef SQLITE_ENABLE_SNAPSHOT
   58140   if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
   58141     mxFrame = pWal->pSnapshot->mxFrame;
   58142   }
   58143 #endif
   58144   for(i=1; i<WAL_NREADER; i++){
   58145     u32 thisMark = pInfo->aReadMark[i];
   58146     if( mxReadMark<=thisMark && thisMark<=mxFrame ){
   58147       assert( thisMark!=READMARK_NOT_USED );
   58148       mxReadMark = thisMark;
   58149       mxI = i;
   58150     }
   58151   }
   58152   if( (pWal->readOnly & WAL_SHM_RDONLY)==0
   58153    && (mxReadMark<mxFrame || mxI==0)
   58154   ){
   58155     for(i=1; i<WAL_NREADER; i++){
   58156       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
   58157       if( rc==SQLITE_OK ){
   58158         mxReadMark = pInfo->aReadMark[i] = mxFrame;
   58159         mxI = i;
   58160         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   58161         break;
   58162       }else if( rc!=SQLITE_BUSY ){
   58163         return rc;
   58164       }
   58165     }
   58166   }
   58167   if( mxI==0 ){
   58168     assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
   58169     return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
   58170   }
   58171 
   58172   rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
   58173   if( rc ){
   58174     return rc==SQLITE_BUSY ? WAL_RETRY : rc;
   58175   }
   58176   /* Now that the read-lock has been obtained, check that neither the
   58177   ** value in the aReadMark[] array or the contents of the wal-index
   58178   ** header have changed.
   58179   **
   58180   ** It is necessary to check that the wal-index header did not change
   58181   ** between the time it was read and when the shared-lock was obtained
   58182   ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
   58183   ** that the log file may have been wrapped by a writer, or that frames
   58184   ** that occur later in the log than pWal->hdr.mxFrame may have been
   58185   ** copied into the database by a checkpointer. If either of these things
   58186   ** happened, then reading the database with the current value of
   58187   ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
   58188   ** instead.
   58189   **
   58190   ** Before checking that the live wal-index header has not changed
   58191   ** since it was read, set Wal.minFrame to the first frame in the wal
   58192   ** file that has not yet been checkpointed. This client will not need
   58193   ** to read any frames earlier than minFrame from the wal file - they
   58194   ** can be safely read directly from the database file.
   58195   **
   58196   ** Because a ShmBarrier() call is made between taking the copy of
   58197   ** nBackfill and checking that the wal-header in shared-memory still
   58198   ** matches the one cached in pWal->hdr, it is guaranteed that the
   58199   ** checkpointer that set nBackfill was not working with a wal-index
   58200   ** header newer than that cached in pWal->hdr. If it were, that could
   58201   ** cause a problem. The checkpointer could omit to checkpoint
   58202   ** a version of page X that lies before pWal->minFrame (call that version
   58203   ** A) on the basis that there is a newer version (version B) of the same
   58204   ** page later in the wal file. But if version B happens to like past
   58205   ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
   58206   ** that it can read version A from the database file. However, since
   58207   ** we can guarantee that the checkpointer that set nBackfill could not
   58208   ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
   58209   */
   58210   pWal->minFrame = pInfo->nBackfill+1;
   58211   walShmBarrier(pWal);
   58212   if( pInfo->aReadMark[mxI]!=mxReadMark
   58213    || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
   58214   ){
   58215     walUnlockShared(pWal, WAL_READ_LOCK(mxI));
   58216     return WAL_RETRY;
   58217   }else{
   58218     assert( mxReadMark<=pWal->hdr.mxFrame );
   58219     pWal->readLock = (i16)mxI;
   58220   }
   58221   return rc;
   58222 }
   58223 
   58224 #ifdef SQLITE_ENABLE_SNAPSHOT
   58225 /*
   58226 ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
   58227 ** variable so that older snapshots can be accessed. To do this, loop
   58228 ** through all wal frames from nBackfillAttempted to (nBackfill+1),
   58229 ** comparing their content to the corresponding page with the database
   58230 ** file, if any. Set nBackfillAttempted to the frame number of the
   58231 ** first frame for which the wal file content matches the db file.
   58232 **
   58233 ** This is only really safe if the file-system is such that any page
   58234 ** writes made by earlier checkpointers were atomic operations, which
   58235 ** is not always true. It is also possible that nBackfillAttempted
   58236 ** may be left set to a value larger than expected, if a wal frame
   58237 ** contains content that duplicate of an earlier version of the same
   58238 ** page.
   58239 **
   58240 ** SQLITE_OK is returned if successful, or an SQLite error code if an
   58241 ** error occurs. It is not an error if nBackfillAttempted cannot be
   58242 ** decreased at all.
   58243 */
   58244 SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
   58245   int rc;
   58246 
   58247   assert( pWal->readLock>=0 );
   58248   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
   58249   if( rc==SQLITE_OK ){
   58250     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   58251     int szPage = (int)pWal->szPage;
   58252     i64 szDb;                   /* Size of db file in bytes */
   58253 
   58254     rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
   58255     if( rc==SQLITE_OK ){
   58256       void *pBuf1 = sqlite3_malloc(szPage);
   58257       void *pBuf2 = sqlite3_malloc(szPage);
   58258       if( pBuf1==0 || pBuf2==0 ){
   58259         rc = SQLITE_NOMEM;
   58260       }else{
   58261         u32 i = pInfo->nBackfillAttempted;
   58262         for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
   58263           volatile ht_slot *dummy;
   58264           volatile u32 *aPgno;      /* Array of page numbers */
   58265           u32 iZero;                /* Frame corresponding to aPgno[0] */
   58266           u32 pgno;                 /* Page number in db file */
   58267           i64 iDbOff;               /* Offset of db file entry */
   58268           i64 iWalOff;              /* Offset of wal file entry */
   58269 
   58270           rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
   58271           if( rc!=SQLITE_OK ) break;
   58272           pgno = aPgno[i-iZero];
   58273           iDbOff = (i64)(pgno-1) * szPage;
   58274 
   58275           if( iDbOff+szPage<=szDb ){
   58276             iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
   58277             rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
   58278 
   58279             if( rc==SQLITE_OK ){
   58280               rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
   58281             }
   58282 
   58283             if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
   58284               break;
   58285             }
   58286           }
   58287 
   58288           pInfo->nBackfillAttempted = i-1;
   58289         }
   58290       }
   58291 
   58292       sqlite3_free(pBuf1);
   58293       sqlite3_free(pBuf2);
   58294     }
   58295     walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
   58296   }
   58297 
   58298   return rc;
   58299 }
   58300 #endif /* SQLITE_ENABLE_SNAPSHOT */
   58301 
   58302 /*
   58303 ** Begin a read transaction on the database.
   58304 **
   58305 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
   58306 ** it takes a snapshot of the state of the WAL and wal-index for the current
   58307 ** instant in time.  The current thread will continue to use this snapshot.
   58308 ** Other threads might append new content to the WAL and wal-index but
   58309 ** that extra content is ignored by the current thread.
   58310 **
   58311 ** If the database contents have changes since the previous read
   58312 ** transaction, then *pChanged is set to 1 before returning.  The
   58313 ** Pager layer will use this to know that is cache is stale and
   58314 ** needs to be flushed.
   58315 */
   58316 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
   58317   int rc;                         /* Return code */
   58318   int cnt = 0;                    /* Number of TryBeginRead attempts */
   58319 
   58320 #ifdef SQLITE_ENABLE_SNAPSHOT
   58321   int bChanged = 0;
   58322   WalIndexHdr *pSnapshot = pWal->pSnapshot;
   58323   if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
   58324     bChanged = 1;
   58325   }
   58326 #endif
   58327 
   58328   do{
   58329     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
   58330   }while( rc==WAL_RETRY );
   58331   testcase( (rc&0xff)==SQLITE_BUSY );
   58332   testcase( (rc&0xff)==SQLITE_IOERR );
   58333   testcase( rc==SQLITE_PROTOCOL );
   58334   testcase( rc==SQLITE_OK );
   58335 
   58336 #ifdef SQLITE_ENABLE_SNAPSHOT
   58337   if( rc==SQLITE_OK ){
   58338     if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
   58339       /* At this point the client has a lock on an aReadMark[] slot holding
   58340       ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
   58341       ** is populated with the wal-index header corresponding to the head
   58342       ** of the wal file. Verify that pSnapshot is still valid before
   58343       ** continuing.  Reasons why pSnapshot might no longer be valid:
   58344       **
   58345       **    (1)  The WAL file has been reset since the snapshot was taken.
   58346       **         In this case, the salt will have changed.
   58347       **
   58348       **    (2)  A checkpoint as been attempted that wrote frames past
   58349       **         pSnapshot->mxFrame into the database file.  Note that the
   58350       **         checkpoint need not have completed for this to cause problems.
   58351       */
   58352       volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   58353 
   58354       assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
   58355       assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
   58356 
   58357       /* It is possible that there is a checkpointer thread running
   58358       ** concurrent with this code. If this is the case, it may be that the
   58359       ** checkpointer has already determined that it will checkpoint
   58360       ** snapshot X, where X is later in the wal file than pSnapshot, but
   58361       ** has not yet set the pInfo->nBackfillAttempted variable to indicate
   58362       ** its intent. To avoid the race condition this leads to, ensure that
   58363       ** there is no checkpointer process by taking a shared CKPT lock
   58364       ** before checking pInfo->nBackfillAttempted.
   58365       **
   58366       ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
   58367       **       this already?
   58368       */
   58369       rc = walLockShared(pWal, WAL_CKPT_LOCK);
   58370 
   58371       if( rc==SQLITE_OK ){
   58372         /* Check that the wal file has not been wrapped. Assuming that it has
   58373         ** not, also check that no checkpointer has attempted to checkpoint any
   58374         ** frames beyond pSnapshot->mxFrame. If either of these conditions are
   58375         ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
   58376         ** with *pSnapshot and set *pChanged as appropriate for opening the
   58377         ** snapshot.  */
   58378         if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
   58379          && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
   58380         ){
   58381           assert( pWal->readLock>0 );
   58382           memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
   58383           *pChanged = bChanged;
   58384         }else{
   58385           rc = SQLITE_BUSY_SNAPSHOT;
   58386         }
   58387 
   58388         /* Release the shared CKPT lock obtained above. */
   58389         walUnlockShared(pWal, WAL_CKPT_LOCK);
   58390       }
   58391 
   58392 
   58393       if( rc!=SQLITE_OK ){
   58394         sqlite3WalEndReadTransaction(pWal);
   58395       }
   58396     }
   58397   }
   58398 #endif
   58399   return rc;
   58400 }
   58401 
   58402 /*
   58403 ** Finish with a read transaction.  All this does is release the
   58404 ** read-lock.
   58405 */
   58406 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
   58407   sqlite3WalEndWriteTransaction(pWal);
   58408   if( pWal->readLock>=0 ){
   58409     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   58410     pWal->readLock = -1;
   58411   }
   58412 }
   58413 
   58414 /*
   58415 ** Search the wal file for page pgno. If found, set *piRead to the frame that
   58416 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
   58417 ** to zero.
   58418 **
   58419 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
   58420 ** error does occur, the final value of *piRead is undefined.
   58421 */
   58422 SQLITE_PRIVATE int sqlite3WalFindFrame(
   58423   Wal *pWal,                      /* WAL handle */
   58424   Pgno pgno,                      /* Database page number to read data for */
   58425   u32 *piRead                     /* OUT: Frame number (or zero) */
   58426 ){
   58427   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
   58428   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
   58429   int iHash;                      /* Used to loop through N hash tables */
   58430   int iMinHash;
   58431 
   58432   /* This routine is only be called from within a read transaction. */
   58433   assert( pWal->readLock>=0 || pWal->lockError );
   58434 
   58435   /* If the "last page" field of the wal-index header snapshot is 0, then
   58436   ** no data will be read from the wal under any circumstances. Return early
   58437   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
   58438   ** then the WAL is ignored by the reader so return early, as if the
   58439   ** WAL were empty.
   58440   */
   58441   if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
   58442     *piRead = 0;
   58443     return SQLITE_OK;
   58444   }
   58445 
   58446   /* Search the hash table or tables for an entry matching page number
   58447   ** pgno. Each iteration of the following for() loop searches one
   58448   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
   58449   **
   58450   ** This code might run concurrently to the code in walIndexAppend()
   58451   ** that adds entries to the wal-index (and possibly to this hash
   58452   ** table). This means the value just read from the hash
   58453   ** slot (aHash[iKey]) may have been added before or after the
   58454   ** current read transaction was opened. Values added after the
   58455   ** read transaction was opened may have been written incorrectly -
   58456   ** i.e. these slots may contain garbage data. However, we assume
   58457   ** that any slots written before the current read transaction was
   58458   ** opened remain unmodified.
   58459   **
   58460   ** For the reasons above, the if(...) condition featured in the inner
   58461   ** loop of the following block is more stringent that would be required
   58462   ** if we had exclusive access to the hash-table:
   58463   **
   58464   **   (aPgno[iFrame]==pgno):
   58465   **     This condition filters out normal hash-table collisions.
   58466   **
   58467   **   (iFrame<=iLast):
   58468   **     This condition filters out entries that were added to the hash
   58469   **     table after the current read-transaction had started.
   58470   */
   58471   iMinHash = walFramePage(pWal->minFrame);
   58472   for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
   58473     volatile ht_slot *aHash;      /* Pointer to hash table */
   58474     volatile u32 *aPgno;          /* Pointer to array of page numbers */
   58475     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
   58476     int iKey;                     /* Hash slot index */
   58477     int nCollide;                 /* Number of hash collisions remaining */
   58478     int rc;                       /* Error code */
   58479 
   58480     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
   58481     if( rc!=SQLITE_OK ){
   58482       return rc;
   58483     }
   58484     nCollide = HASHTABLE_NSLOT;
   58485     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
   58486       u32 iFrame = aHash[iKey] + iZero;
   58487       if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
   58488         assert( iFrame>iRead || CORRUPT_DB );
   58489         iRead = iFrame;
   58490       }
   58491       if( (nCollide--)==0 ){
   58492         return SQLITE_CORRUPT_BKPT;
   58493       }
   58494     }
   58495   }
   58496 
   58497 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   58498   /* If expensive assert() statements are available, do a linear search
   58499   ** of the wal-index file content. Make sure the results agree with the
   58500   ** result obtained using the hash indexes above.  */
   58501   {
   58502     u32 iRead2 = 0;
   58503     u32 iTest;
   58504     assert( pWal->bShmUnreliable || pWal->minFrame>0 );
   58505     for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
   58506       if( walFramePgno(pWal, iTest)==pgno ){
   58507         iRead2 = iTest;
   58508         break;
   58509       }
   58510     }
   58511     assert( iRead==iRead2 );
   58512   }
   58513 #endif
   58514 
   58515   *piRead = iRead;
   58516   return SQLITE_OK;
   58517 }
   58518 
   58519 /*
   58520 ** Read the contents of frame iRead from the wal file into buffer pOut
   58521 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
   58522 ** error code otherwise.
   58523 */
   58524 SQLITE_PRIVATE int sqlite3WalReadFrame(
   58525   Wal *pWal,                      /* WAL handle */
   58526   u32 iRead,                      /* Frame to read */
   58527   int nOut,                       /* Size of buffer pOut in bytes */
   58528   u8 *pOut                        /* Buffer to write page data to */
   58529 ){
   58530   int sz;
   58531   i64 iOffset;
   58532   sz = pWal->hdr.szPage;
   58533   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
   58534   testcase( sz<=32768 );
   58535   testcase( sz>=65536 );
   58536   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
   58537   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   58538   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
   58539 }
   58540 
   58541 /*
   58542 ** Return the size of the database in pages (or zero, if unknown).
   58543 */
   58544 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
   58545   if( pWal && ALWAYS(pWal->readLock>=0) ){
   58546     return pWal->hdr.nPage;
   58547   }
   58548   return 0;
   58549 }
   58550 
   58551 
   58552 /*
   58553 ** This function starts a write transaction on the WAL.
   58554 **
   58555 ** A read transaction must have already been started by a prior call
   58556 ** to sqlite3WalBeginReadTransaction().
   58557 **
   58558 ** If another thread or process has written into the database since
   58559 ** the read transaction was started, then it is not possible for this
   58560 ** thread to write as doing so would cause a fork.  So this routine
   58561 ** returns SQLITE_BUSY in that case and no write transaction is started.
   58562 **
   58563 ** There can only be a single writer active at a time.
   58564 */
   58565 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
   58566   int rc;
   58567 
   58568   /* Cannot start a write transaction without first holding a read
   58569   ** transaction. */
   58570   assert( pWal->readLock>=0 );
   58571   assert( pWal->writeLock==0 && pWal->iReCksum==0 );
   58572 
   58573   if( pWal->readOnly ){
   58574     return SQLITE_READONLY;
   58575   }
   58576 
   58577   /* Only one writer allowed at a time.  Get the write lock.  Return
   58578   ** SQLITE_BUSY if unable.
   58579   */
   58580   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
   58581   if( rc ){
   58582     return rc;
   58583   }
   58584   pWal->writeLock = 1;
   58585 
   58586   /* If another connection has written to the database file since the
   58587   ** time the read transaction on this connection was started, then
   58588   ** the write is disallowed.
   58589   */
   58590   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
   58591     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   58592     pWal->writeLock = 0;
   58593     rc = SQLITE_BUSY_SNAPSHOT;
   58594   }
   58595 
   58596   return rc;
   58597 }
   58598 
   58599 /*
   58600 ** End a write transaction.  The commit has already been done.  This
   58601 ** routine merely releases the lock.
   58602 */
   58603 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
   58604   if( pWal->writeLock ){
   58605     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   58606     pWal->writeLock = 0;
   58607     pWal->iReCksum = 0;
   58608     pWal->truncateOnCommit = 0;
   58609   }
   58610   return SQLITE_OK;
   58611 }
   58612 
   58613 /*
   58614 ** If any data has been written (but not committed) to the log file, this
   58615 ** function moves the write-pointer back to the start of the transaction.
   58616 **
   58617 ** Additionally, the callback function is invoked for each frame written
   58618 ** to the WAL since the start of the transaction. If the callback returns
   58619 ** other than SQLITE_OK, it is not invoked again and the error code is
   58620 ** returned to the caller.
   58621 **
   58622 ** Otherwise, if the callback function does not return an error, this
   58623 ** function returns SQLITE_OK.
   58624 */
   58625 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
   58626   int rc = SQLITE_OK;
   58627   if( ALWAYS(pWal->writeLock) ){
   58628     Pgno iMax = pWal->hdr.mxFrame;
   58629     Pgno iFrame;
   58630 
   58631     /* Restore the clients cache of the wal-index header to the state it
   58632     ** was in before the client began writing to the database.
   58633     */
   58634     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
   58635 
   58636     for(iFrame=pWal->hdr.mxFrame+1;
   58637         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
   58638         iFrame++
   58639     ){
   58640       /* This call cannot fail. Unless the page for which the page number
   58641       ** is passed as the second argument is (a) in the cache and
   58642       ** (b) has an outstanding reference, then xUndo is either a no-op
   58643       ** (if (a) is false) or simply expels the page from the cache (if (b)
   58644       ** is false).
   58645       **
   58646       ** If the upper layer is doing a rollback, it is guaranteed that there
   58647       ** are no outstanding references to any page other than page 1. And
   58648       ** page 1 is never written to the log until the transaction is
   58649       ** committed. As a result, the call to xUndo may not fail.
   58650       */
   58651       assert( walFramePgno(pWal, iFrame)!=1 );
   58652       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
   58653     }
   58654     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
   58655   }
   58656   return rc;
   58657 }
   58658 
   58659 /*
   58660 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
   58661 ** values. This function populates the array with values required to
   58662 ** "rollback" the write position of the WAL handle back to the current
   58663 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
   58664 */
   58665 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
   58666   assert( pWal->writeLock );
   58667   aWalData[0] = pWal->hdr.mxFrame;
   58668   aWalData[1] = pWal->hdr.aFrameCksum[0];
   58669   aWalData[2] = pWal->hdr.aFrameCksum[1];
   58670   aWalData[3] = pWal->nCkpt;
   58671 }
   58672 
   58673 /*
   58674 ** Move the write position of the WAL back to the point identified by
   58675 ** the values in the aWalData[] array. aWalData must point to an array
   58676 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
   58677 ** by a call to WalSavepoint().
   58678 */
   58679 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
   58680   int rc = SQLITE_OK;
   58681 
   58682   assert( pWal->writeLock );
   58683   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
   58684 
   58685   if( aWalData[3]!=pWal->nCkpt ){
   58686     /* This savepoint was opened immediately after the write-transaction
   58687     ** was started. Right after that, the writer decided to wrap around
   58688     ** to the start of the log. Update the savepoint values to match.
   58689     */
   58690     aWalData[0] = 0;
   58691     aWalData[3] = pWal->nCkpt;
   58692   }
   58693 
   58694   if( aWalData[0]<pWal->hdr.mxFrame ){
   58695     pWal->hdr.mxFrame = aWalData[0];
   58696     pWal->hdr.aFrameCksum[0] = aWalData[1];
   58697     pWal->hdr.aFrameCksum[1] = aWalData[2];
   58698     walCleanupHash(pWal);
   58699   }
   58700 
   58701   return rc;
   58702 }
   58703 
   58704 /*
   58705 ** This function is called just before writing a set of frames to the log
   58706 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
   58707 ** to the current log file, it is possible to overwrite the start of the
   58708 ** existing log file with the new frames (i.e. "reset" the log). If so,
   58709 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
   58710 ** unchanged.
   58711 **
   58712 ** SQLITE_OK is returned if no error is encountered (regardless of whether
   58713 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
   58714 ** if an error occurs.
   58715 */
   58716 static int walRestartLog(Wal *pWal){
   58717   int rc = SQLITE_OK;
   58718   int cnt;
   58719 
   58720   if( pWal->readLock==0 ){
   58721     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   58722     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
   58723     if( pInfo->nBackfill>0 ){
   58724       u32 salt1;
   58725       sqlite3_randomness(4, &salt1);
   58726       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   58727       if( rc==SQLITE_OK ){
   58728         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
   58729         ** readers are currently using the WAL), then the transactions
   58730         ** frames will overwrite the start of the existing log. Update the
   58731         ** wal-index header to reflect this.
   58732         **
   58733         ** In theory it would be Ok to update the cache of the header only
   58734         ** at this point. But updating the actual wal-index header is also
   58735         ** safe and means there is no special case for sqlite3WalUndo()
   58736         ** to handle if this transaction is rolled back.  */
   58737         walRestartHdr(pWal, salt1);
   58738         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   58739       }else if( rc!=SQLITE_BUSY ){
   58740         return rc;
   58741       }
   58742     }
   58743     walUnlockShared(pWal, WAL_READ_LOCK(0));
   58744     pWal->readLock = -1;
   58745     cnt = 0;
   58746     do{
   58747       int notUsed;
   58748       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
   58749     }while( rc==WAL_RETRY );
   58750     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
   58751     testcase( (rc&0xff)==SQLITE_IOERR );
   58752     testcase( rc==SQLITE_PROTOCOL );
   58753     testcase( rc==SQLITE_OK );
   58754   }
   58755   return rc;
   58756 }
   58757 
   58758 /*
   58759 ** Information about the current state of the WAL file and where
   58760 ** the next fsync should occur - passed from sqlite3WalFrames() into
   58761 ** walWriteToLog().
   58762 */
   58763 typedef struct WalWriter {
   58764   Wal *pWal;                   /* The complete WAL information */
   58765   sqlite3_file *pFd;           /* The WAL file to which we write */
   58766   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
   58767   int syncFlags;               /* Flags for the fsync */
   58768   int szPage;                  /* Size of one page */
   58769 } WalWriter;
   58770 
   58771 /*
   58772 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
   58773 ** Do a sync when crossing the p->iSyncPoint boundary.
   58774 **
   58775 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
   58776 ** first write the part before iSyncPoint, then sync, then write the
   58777 ** rest.
   58778 */
   58779 static int walWriteToLog(
   58780   WalWriter *p,              /* WAL to write to */
   58781   void *pContent,            /* Content to be written */
   58782   int iAmt,                  /* Number of bytes to write */
   58783   sqlite3_int64 iOffset      /* Start writing at this offset */
   58784 ){
   58785   int rc;
   58786   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
   58787     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
   58788     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
   58789     if( rc ) return rc;
   58790     iOffset += iFirstAmt;
   58791     iAmt -= iFirstAmt;
   58792     pContent = (void*)(iFirstAmt + (char*)pContent);
   58793     assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
   58794     rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
   58795     if( iAmt==0 || rc ) return rc;
   58796   }
   58797   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
   58798   return rc;
   58799 }
   58800 
   58801 /*
   58802 ** Write out a single frame of the WAL
   58803 */
   58804 static int walWriteOneFrame(
   58805   WalWriter *p,               /* Where to write the frame */
   58806   PgHdr *pPage,               /* The page of the frame to be written */
   58807   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
   58808   sqlite3_int64 iOffset       /* Byte offset at which to write */
   58809 ){
   58810   int rc;                         /* Result code from subfunctions */
   58811   void *pData;                    /* Data actually written */
   58812   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
   58813 #if defined(SQLITE_HAS_CODEC)
   58814   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
   58815 #else
   58816   pData = pPage->pData;
   58817 #endif
   58818   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
   58819   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
   58820   if( rc ) return rc;
   58821   /* Write the page data */
   58822   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
   58823   return rc;
   58824 }
   58825 
   58826 /*
   58827 ** This function is called as part of committing a transaction within which
   58828 ** one or more frames have been overwritten. It updates the checksums for
   58829 ** all frames written to the wal file by the current transaction starting
   58830 ** with the earliest to have been overwritten.
   58831 **
   58832 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
   58833 */
   58834 static int walRewriteChecksums(Wal *pWal, u32 iLast){
   58835   const int szPage = pWal->szPage;/* Database page size */
   58836   int rc = SQLITE_OK;             /* Return code */
   58837   u8 *aBuf;                       /* Buffer to load data from wal file into */
   58838   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
   58839   u32 iRead;                      /* Next frame to read from wal file */
   58840   i64 iCksumOff;
   58841 
   58842   aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
   58843   if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
   58844 
   58845   /* Find the checksum values to use as input for the recalculating the
   58846   ** first checksum. If the first frame is frame 1 (implying that the current
   58847   ** transaction restarted the wal file), these values must be read from the
   58848   ** wal-file header. Otherwise, read them from the frame header of the
   58849   ** previous frame.  */
   58850   assert( pWal->iReCksum>0 );
   58851   if( pWal->iReCksum==1 ){
   58852     iCksumOff = 24;
   58853   }else{
   58854     iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
   58855   }
   58856   rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
   58857   pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
   58858   pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
   58859 
   58860   iRead = pWal->iReCksum;
   58861   pWal->iReCksum = 0;
   58862   for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
   58863     i64 iOff = walFrameOffset(iRead, szPage);
   58864     rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
   58865     if( rc==SQLITE_OK ){
   58866       u32 iPgno, nDbSize;
   58867       iPgno = sqlite3Get4byte(aBuf);
   58868       nDbSize = sqlite3Get4byte(&aBuf[4]);
   58869 
   58870       walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
   58871       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
   58872     }
   58873   }
   58874 
   58875   sqlite3_free(aBuf);
   58876   return rc;
   58877 }
   58878 
   58879 /*
   58880 ** Write a set of frames to the log. The caller must hold the write-lock
   58881 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
   58882 */
   58883 SQLITE_PRIVATE int sqlite3WalFrames(
   58884   Wal *pWal,                      /* Wal handle to write to */
   58885   int szPage,                     /* Database page-size in bytes */
   58886   PgHdr *pList,                   /* List of dirty pages to write */
   58887   Pgno nTruncate,                 /* Database size after this commit */
   58888   int isCommit,                   /* True if this is a commit */
   58889   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
   58890 ){
   58891   int rc;                         /* Used to catch return codes */
   58892   u32 iFrame;                     /* Next frame address */
   58893   PgHdr *p;                       /* Iterator to run through pList with. */
   58894   PgHdr *pLast = 0;               /* Last frame in list */
   58895   int nExtra = 0;                 /* Number of extra copies of last page */
   58896   int szFrame;                    /* The size of a single frame */
   58897   i64 iOffset;                    /* Next byte to write in WAL file */
   58898   WalWriter w;                    /* The writer */
   58899   u32 iFirst = 0;                 /* First frame that may be overwritten */
   58900   WalIndexHdr *pLive;             /* Pointer to shared header */
   58901 
   58902   assert( pList );
   58903   assert( pWal->writeLock );
   58904 
   58905   /* If this frame set completes a transaction, then nTruncate>0.  If
   58906   ** nTruncate==0 then this frame set does not complete the transaction. */
   58907   assert( (isCommit!=0)==(nTruncate!=0) );
   58908 
   58909 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   58910   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
   58911     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
   58912               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
   58913   }
   58914 #endif
   58915 
   58916   pLive = (WalIndexHdr*)walIndexHdr(pWal);
   58917   if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
   58918     iFirst = pLive->mxFrame+1;
   58919   }
   58920 
   58921   /* See if it is possible to write these frames into the start of the
   58922   ** log file, instead of appending to it at pWal->hdr.mxFrame.
   58923   */
   58924   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
   58925     return rc;
   58926   }
   58927 
   58928   /* If this is the first frame written into the log, write the WAL
   58929   ** header to the start of the WAL file. See comments at the top of
   58930   ** this source file for a description of the WAL header format.
   58931   */
   58932   iFrame = pWal->hdr.mxFrame;
   58933   if( iFrame==0 ){
   58934     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
   58935     u32 aCksum[2];                /* Checksum for wal-header */
   58936 
   58937     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
   58938     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
   58939     sqlite3Put4byte(&aWalHdr[8], szPage);
   58940     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
   58941     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
   58942     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
   58943     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
   58944     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
   58945     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
   58946 
   58947     pWal->szPage = szPage;
   58948     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
   58949     pWal->hdr.aFrameCksum[0] = aCksum[0];
   58950     pWal->hdr.aFrameCksum[1] = aCksum[1];
   58951     pWal->truncateOnCommit = 1;
   58952 
   58953     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
   58954     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
   58955     if( rc!=SQLITE_OK ){
   58956       return rc;
   58957     }
   58958 
   58959     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
   58960     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
   58961     ** an out-of-order write following a WAL restart could result in
   58962     ** database corruption.  See the ticket:
   58963     **
   58964     **     https://sqlite.org/src/info/ff5be73dee
   58965     */
   58966     if( pWal->syncHeader ){
   58967       rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
   58968       if( rc ) return rc;
   58969     }
   58970   }
   58971   assert( (int)pWal->szPage==szPage );
   58972 
   58973   /* Setup information needed to write frames into the WAL */
   58974   w.pWal = pWal;
   58975   w.pFd = pWal->pWalFd;
   58976   w.iSyncPoint = 0;
   58977   w.syncFlags = sync_flags;
   58978   w.szPage = szPage;
   58979   iOffset = walFrameOffset(iFrame+1, szPage);
   58980   szFrame = szPage + WAL_FRAME_HDRSIZE;
   58981 
   58982   /* Write all frames into the log file exactly once */
   58983   for(p=pList; p; p=p->pDirty){
   58984     int nDbSize;   /* 0 normally.  Positive == commit flag */
   58985 
   58986     /* Check if this page has already been written into the wal file by
   58987     ** the current transaction. If so, overwrite the existing frame and
   58988     ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
   58989     ** checksums must be recomputed when the transaction is committed.  */
   58990     if( iFirst && (p->pDirty || isCommit==0) ){
   58991       u32 iWrite = 0;
   58992       VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
   58993       assert( rc==SQLITE_OK || iWrite==0 );
   58994       if( iWrite>=iFirst ){
   58995         i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
   58996         void *pData;
   58997         if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
   58998           pWal->iReCksum = iWrite;
   58999         }
   59000 #if defined(SQLITE_HAS_CODEC)
   59001         if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
   59002 #else
   59003         pData = p->pData;
   59004 #endif
   59005         rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
   59006         if( rc ) return rc;
   59007         p->flags &= ~PGHDR_WAL_APPEND;
   59008         continue;
   59009       }
   59010     }
   59011 
   59012     iFrame++;
   59013     assert( iOffset==walFrameOffset(iFrame, szPage) );
   59014     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
   59015     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
   59016     if( rc ) return rc;
   59017     pLast = p;
   59018     iOffset += szFrame;
   59019     p->flags |= PGHDR_WAL_APPEND;
   59020   }
   59021 
   59022   /* Recalculate checksums within the wal file if required. */
   59023   if( isCommit && pWal->iReCksum ){
   59024     rc = walRewriteChecksums(pWal, iFrame);
   59025     if( rc ) return rc;
   59026   }
   59027 
   59028   /* If this is the end of a transaction, then we might need to pad
   59029   ** the transaction and/or sync the WAL file.
   59030   **
   59031   ** Padding and syncing only occur if this set of frames complete a
   59032   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
   59033   ** or synchronous==OFF, then no padding or syncing are needed.
   59034   **
   59035   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
   59036   ** needed and only the sync is done.  If padding is needed, then the
   59037   ** final frame is repeated (with its commit mark) until the next sector
   59038   ** boundary is crossed.  Only the part of the WAL prior to the last
   59039   ** sector boundary is synced; the part of the last frame that extends
   59040   ** past the sector boundary is written after the sync.
   59041   */
   59042   if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
   59043     int bSync = 1;
   59044     if( pWal->padToSectorBoundary ){
   59045       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
   59046       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
   59047       bSync = (w.iSyncPoint==iOffset);
   59048       testcase( bSync );
   59049       while( iOffset<w.iSyncPoint ){
   59050         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
   59051         if( rc ) return rc;
   59052         iOffset += szFrame;
   59053         nExtra++;
   59054       }
   59055     }
   59056     if( bSync ){
   59057       assert( rc==SQLITE_OK );
   59058       rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
   59059     }
   59060   }
   59061 
   59062   /* If this frame set completes the first transaction in the WAL and
   59063   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
   59064   ** journal size limit, if possible.
   59065   */
   59066   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
   59067     i64 sz = pWal->mxWalSize;
   59068     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
   59069       sz = walFrameOffset(iFrame+nExtra+1, szPage);
   59070     }
   59071     walLimitSize(pWal, sz);
   59072     pWal->truncateOnCommit = 0;
   59073   }
   59074 
   59075   /* Append data to the wal-index. It is not necessary to lock the
   59076   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
   59077   ** guarantees that there are no other writers, and no data that may
   59078   ** be in use by existing readers is being overwritten.
   59079   */
   59080   iFrame = pWal->hdr.mxFrame;
   59081   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
   59082     if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
   59083     iFrame++;
   59084     rc = walIndexAppend(pWal, iFrame, p->pgno);
   59085   }
   59086   while( rc==SQLITE_OK && nExtra>0 ){
   59087     iFrame++;
   59088     nExtra--;
   59089     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
   59090   }
   59091 
   59092   if( rc==SQLITE_OK ){
   59093     /* Update the private copy of the header. */
   59094     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   59095     testcase( szPage<=32768 );
   59096     testcase( szPage>=65536 );
   59097     pWal->hdr.mxFrame = iFrame;
   59098     if( isCommit ){
   59099       pWal->hdr.iChange++;
   59100       pWal->hdr.nPage = nTruncate;
   59101     }
   59102     /* If this is a commit, update the wal-index header too. */
   59103     if( isCommit ){
   59104       walIndexWriteHdr(pWal);
   59105       pWal->iCallback = iFrame;
   59106     }
   59107   }
   59108 
   59109   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
   59110   return rc;
   59111 }
   59112 
   59113 /*
   59114 ** This routine is called to implement sqlite3_wal_checkpoint() and
   59115 ** related interfaces.
   59116 **
   59117 ** Obtain a CHECKPOINT lock and then backfill as much information as
   59118 ** we can from WAL into the database.
   59119 **
   59120 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
   59121 ** callback. In this case this function runs a blocking checkpoint.
   59122 */
   59123 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   59124   Wal *pWal,                      /* Wal connection */
   59125   sqlite3 *db,                    /* Check this handle's interrupt flag */
   59126   int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
   59127   int (*xBusy)(void*),            /* Function to call when busy */
   59128   void *pBusyArg,                 /* Context argument for xBusyHandler */
   59129   int sync_flags,                 /* Flags to sync db file with (or 0) */
   59130   int nBuf,                       /* Size of temporary buffer */
   59131   u8 *zBuf,                       /* Temporary buffer to use */
   59132   int *pnLog,                     /* OUT: Number of frames in WAL */
   59133   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   59134 ){
   59135   int rc;                         /* Return code */
   59136   int isChanged = 0;              /* True if a new wal-index header is loaded */
   59137   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
   59138   int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
   59139 
   59140   assert( pWal->ckptLock==0 );
   59141   assert( pWal->writeLock==0 );
   59142 
   59143   /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
   59144   ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
   59145   assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
   59146 
   59147   if( pWal->readOnly ) return SQLITE_READONLY;
   59148   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
   59149 
   59150   /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
   59151   ** "checkpoint" lock on the database file. */
   59152   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
   59153   if( rc ){
   59154     /* EVIDENCE-OF: R-10421-19736 If any other process is running a
   59155     ** checkpoint operation at the same time, the lock cannot be obtained and
   59156     ** SQLITE_BUSY is returned.
   59157     ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
   59158     ** it will not be invoked in this case.
   59159     */
   59160     testcase( rc==SQLITE_BUSY );
   59161     testcase( xBusy!=0 );
   59162     return rc;
   59163   }
   59164   pWal->ckptLock = 1;
   59165 
   59166   /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
   59167   ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
   59168   ** file.
   59169   **
   59170   ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
   59171   ** immediately, and a busy-handler is configured, it is invoked and the
   59172   ** writer lock retried until either the busy-handler returns 0 or the
   59173   ** lock is successfully obtained.
   59174   */
   59175   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   59176     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
   59177     if( rc==SQLITE_OK ){
   59178       pWal->writeLock = 1;
   59179     }else if( rc==SQLITE_BUSY ){
   59180       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
   59181       xBusy2 = 0;
   59182       rc = SQLITE_OK;
   59183     }
   59184   }
   59185 
   59186   /* Read the wal-index header. */
   59187   if( rc==SQLITE_OK ){
   59188     rc = walIndexReadHdr(pWal, &isChanged);
   59189     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
   59190       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
   59191     }
   59192   }
   59193 
   59194   /* Copy data from the log to the database file. */
   59195   if( rc==SQLITE_OK ){
   59196 
   59197     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
   59198       rc = SQLITE_CORRUPT_BKPT;
   59199     }else{
   59200       rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
   59201     }
   59202 
   59203     /* If no error occurred, set the output variables. */
   59204     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
   59205       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
   59206       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
   59207     }
   59208   }
   59209 
   59210   if( isChanged ){
   59211     /* If a new wal-index header was loaded before the checkpoint was
   59212     ** performed, then the pager-cache associated with pWal is now
   59213     ** out of date. So zero the cached wal-index header to ensure that
   59214     ** next time the pager opens a snapshot on this database it knows that
   59215     ** the cache needs to be reset.
   59216     */
   59217     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   59218   }
   59219 
   59220   /* Release the locks. */
   59221   sqlite3WalEndWriteTransaction(pWal);
   59222   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
   59223   pWal->ckptLock = 0;
   59224   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
   59225   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
   59226 }
   59227 
   59228 /* Return the value to pass to a sqlite3_wal_hook callback, the
   59229 ** number of frames in the WAL at the point of the last commit since
   59230 ** sqlite3WalCallback() was called.  If no commits have occurred since
   59231 ** the last call, then return 0.
   59232 */
   59233 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
   59234   u32 ret = 0;
   59235   if( pWal ){
   59236     ret = pWal->iCallback;
   59237     pWal->iCallback = 0;
   59238   }
   59239   return (int)ret;
   59240 }
   59241 
   59242 /*
   59243 ** This function is called to change the WAL subsystem into or out
   59244 ** of locking_mode=EXCLUSIVE.
   59245 **
   59246 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
   59247 ** into locking_mode=NORMAL.  This means that we must acquire a lock
   59248 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
   59249 ** or if the acquisition of the lock fails, then return 0.  If the
   59250 ** transition out of exclusive-mode is successful, return 1.  This
   59251 ** operation must occur while the pager is still holding the exclusive
   59252 ** lock on the main database file.
   59253 **
   59254 ** If op is one, then change from locking_mode=NORMAL into
   59255 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
   59256 ** be released.  Return 1 if the transition is made and 0 if the
   59257 ** WAL is already in exclusive-locking mode - meaning that this
   59258 ** routine is a no-op.  The pager must already hold the exclusive lock
   59259 ** on the main database file before invoking this operation.
   59260 **
   59261 ** If op is negative, then do a dry-run of the op==1 case but do
   59262 ** not actually change anything. The pager uses this to see if it
   59263 ** should acquire the database exclusive lock prior to invoking
   59264 ** the op==1 case.
   59265 */
   59266 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   59267   int rc;
   59268   assert( pWal->writeLock==0 );
   59269   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
   59270 
   59271   /* pWal->readLock is usually set, but might be -1 if there was a
   59272   ** prior error while attempting to acquire are read-lock. This cannot
   59273   ** happen if the connection is actually in exclusive mode (as no xShmLock
   59274   ** locks are taken in this case). Nor should the pager attempt to
   59275   ** upgrade to exclusive-mode following such an error.
   59276   */
   59277   assert( pWal->readLock>=0 || pWal->lockError );
   59278   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
   59279 
   59280   if( op==0 ){
   59281     if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
   59282       pWal->exclusiveMode = WAL_NORMAL_MODE;
   59283       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
   59284         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   59285       }
   59286       rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
   59287     }else{
   59288       /* Already in locking_mode=NORMAL */
   59289       rc = 0;
   59290     }
   59291   }else if( op>0 ){
   59292     assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
   59293     assert( pWal->readLock>=0 );
   59294     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   59295     pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   59296     rc = 1;
   59297   }else{
   59298     rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
   59299   }
   59300   return rc;
   59301 }
   59302 
   59303 /*
   59304 ** Return true if the argument is non-NULL and the WAL module is using
   59305 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   59306 ** WAL module is using shared-memory, return false.
   59307 */
   59308 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
   59309   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
   59310 }
   59311 
   59312 #ifdef SQLITE_ENABLE_SNAPSHOT
   59313 /* Create a snapshot object.  The content of a snapshot is opaque to
   59314 ** every other subsystem, so the WAL module can put whatever it needs
   59315 ** in the object.
   59316 */
   59317 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
   59318   int rc = SQLITE_OK;
   59319   WalIndexHdr *pRet;
   59320   static const u32 aZero[4] = { 0, 0, 0, 0 };
   59321 
   59322   assert( pWal->readLock>=0 && pWal->writeLock==0 );
   59323 
   59324   if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
   59325     *ppSnapshot = 0;
   59326     return SQLITE_ERROR;
   59327   }
   59328   pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
   59329   if( pRet==0 ){
   59330     rc = SQLITE_NOMEM_BKPT;
   59331   }else{
   59332     memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
   59333     *ppSnapshot = (sqlite3_snapshot*)pRet;
   59334   }
   59335 
   59336   return rc;
   59337 }
   59338 
   59339 /* Try to open on pSnapshot when the next read-transaction starts
   59340 */
   59341 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
   59342   pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
   59343 }
   59344 
   59345 /*
   59346 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
   59347 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
   59348 */
   59349 SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
   59350   WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
   59351   WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
   59352 
   59353   /* aSalt[0] is a copy of the value stored in the wal file header. It
   59354   ** is incremented each time the wal file is restarted.  */
   59355   if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
   59356   if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
   59357   if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
   59358   if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
   59359   return 0;
   59360 }
   59361 #endif /* SQLITE_ENABLE_SNAPSHOT */
   59362 
   59363 #ifdef SQLITE_ENABLE_ZIPVFS
   59364 /*
   59365 ** If the argument is not NULL, it points to a Wal object that holds a
   59366 ** read-lock. This function returns the database page-size if it is known,
   59367 ** or zero if it is not (or if pWal is NULL).
   59368 */
   59369 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
   59370   assert( pWal==0 || pWal->readLock>=0 );
   59371   return (pWal ? pWal->szPage : 0);
   59372 }
   59373 #endif
   59374 
   59375 /* Return the sqlite3_file object for the WAL file
   59376 */
   59377 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
   59378   return pWal->pWalFd;
   59379 }
   59380 
   59381 #endif /* #ifndef SQLITE_OMIT_WAL */
   59382 
   59383 /************** End of wal.c *************************************************/
   59384 /************** Begin file btmutex.c *****************************************/
   59385 /*
   59386 ** 2007 August 27
   59387 **
   59388 ** The author disclaims copyright to this source code.  In place of
   59389 ** a legal notice, here is a blessing:
   59390 **
   59391 **    May you do good and not evil.
   59392 **    May you find forgiveness for yourself and forgive others.
   59393 **    May you share freely, never taking more than you give.
   59394 **
   59395 *************************************************************************
   59396 **
   59397 ** This file contains code used to implement mutexes on Btree objects.
   59398 ** This code really belongs in btree.c.  But btree.c is getting too
   59399 ** big and we want to break it down some.  This packaged seemed like
   59400 ** a good breakout.
   59401 */
   59402 /************** Include btreeInt.h in the middle of btmutex.c ****************/
   59403 /************** Begin file btreeInt.h ****************************************/
   59404 /*
   59405 ** 2004 April 6
   59406 **
   59407 ** The author disclaims copyright to this source code.  In place of
   59408 ** a legal notice, here is a blessing:
   59409 **
   59410 **    May you do good and not evil.
   59411 **    May you find forgiveness for yourself and forgive others.
   59412 **    May you share freely, never taking more than you give.
   59413 **
   59414 *************************************************************************
   59415 ** This file implements an external (disk-based) database using BTrees.
   59416 ** For a detailed discussion of BTrees, refer to
   59417 **
   59418 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
   59419 **     "Sorting And Searching", pages 473-480. Addison-Wesley
   59420 **     Publishing Company, Reading, Massachusetts.
   59421 **
   59422 ** The basic idea is that each page of the file contains N database
   59423 ** entries and N+1 pointers to subpages.
   59424 **
   59425 **   ----------------------------------------------------------------
   59426 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
   59427 **   ----------------------------------------------------------------
   59428 **
   59429 ** All of the keys on the page that Ptr(0) points to have values less
   59430 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
   59431 ** values greater than Key(0) and less than Key(1).  All of the keys
   59432 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
   59433 ** so forth.
   59434 **
   59435 ** Finding a particular key requires reading O(log(M)) pages from the
   59436 ** disk where M is the number of entries in the tree.
   59437 **
   59438 ** In this implementation, a single file can hold one or more separate
   59439 ** BTrees.  Each BTree is identified by the index of its root page.  The
   59440 ** key and data for any entry are combined to form the "payload".  A
   59441 ** fixed amount of payload can be carried directly on the database
   59442 ** page.  If the payload is larger than the preset amount then surplus
   59443 ** bytes are stored on overflow pages.  The payload for an entry
   59444 ** and the preceding pointer are combined to form a "Cell".  Each
   59445 ** page has a small header which contains the Ptr(N) pointer and other
   59446 ** information such as the size of key and data.
   59447 **
   59448 ** FORMAT DETAILS
   59449 **
   59450 ** The file is divided into pages.  The first page is called page 1,
   59451 ** the second is page 2, and so forth.  A page number of zero indicates
   59452 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
   59453 ** Each page can be either a btree page, a freelist page, an overflow
   59454 ** page, or a pointer-map page.
   59455 **
   59456 ** The first page is always a btree page.  The first 100 bytes of the first
   59457 ** page contain a special header (the "file header") that describes the file.
   59458 ** The format of the file header is as follows:
   59459 **
   59460 **   OFFSET   SIZE    DESCRIPTION
   59461 **      0      16     Header string: "SQLite format 3\000"
   59462 **     16       2     Page size in bytes.  (1 means 65536)
   59463 **     18       1     File format write version
   59464 **     19       1     File format read version
   59465 **     20       1     Bytes of unused space at the end of each page
   59466 **     21       1     Max embedded payload fraction (must be 64)
   59467 **     22       1     Min embedded payload fraction (must be 32)
   59468 **     23       1     Min leaf payload fraction (must be 32)
   59469 **     24       4     File change counter
   59470 **     28       4     Reserved for future use
   59471 **     32       4     First freelist page
   59472 **     36       4     Number of freelist pages in the file
   59473 **     40      60     15 4-byte meta values passed to higher layers
   59474 **
   59475 **     40       4     Schema cookie
   59476 **     44       4     File format of schema layer
   59477 **     48       4     Size of page cache
   59478 **     52       4     Largest root-page (auto/incr_vacuum)
   59479 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
   59480 **     60       4     User version
   59481 **     64       4     Incremental vacuum mode
   59482 **     68       4     Application-ID
   59483 **     72      20     unused
   59484 **     92       4     The version-valid-for number
   59485 **     96       4     SQLITE_VERSION_NUMBER
   59486 **
   59487 ** All of the integer values are big-endian (most significant byte first).
   59488 **
   59489 ** The file change counter is incremented when the database is changed
   59490 ** This counter allows other processes to know when the file has changed
   59491 ** and thus when they need to flush their cache.
   59492 **
   59493 ** The max embedded payload fraction is the amount of the total usable
   59494 ** space in a page that can be consumed by a single cell for standard
   59495 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
   59496 ** is to limit the maximum cell size so that at least 4 cells will fit
   59497 ** on one page.  Thus the default max embedded payload fraction is 64.
   59498 **
   59499 ** If the payload for a cell is larger than the max payload, then extra
   59500 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
   59501 ** as many bytes as possible are moved into the overflow pages without letting
   59502 ** the cell size drop below the min embedded payload fraction.
   59503 **
   59504 ** The min leaf payload fraction is like the min embedded payload fraction
   59505 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
   59506 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
   59507 ** not specified in the header.
   59508 **
   59509 ** Each btree pages is divided into three sections:  The header, the
   59510 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
   59511 ** file header that occurs before the page header.
   59512 **
   59513 **      |----------------|
   59514 **      | file header    |   100 bytes.  Page 1 only.
   59515 **      |----------------|
   59516 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
   59517 **      |----------------|
   59518 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
   59519 **      | array          |   |  Grows downward
   59520 **      |                |   v
   59521 **      |----------------|
   59522 **      | unallocated    |
   59523 **      | space          |
   59524 **      |----------------|   ^  Grows upwards
   59525 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
   59526 **      | area           |   |  and free space fragments.
   59527 **      |----------------|
   59528 **
   59529 ** The page headers looks like this:
   59530 **
   59531 **   OFFSET   SIZE     DESCRIPTION
   59532 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
   59533 **      1       2      byte offset to the first freeblock
   59534 **      3       2      number of cells on this page
   59535 **      5       2      first byte of the cell content area
   59536 **      7       1      number of fragmented free bytes
   59537 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
   59538 **
   59539 ** The flags define the format of this btree page.  The leaf flag means that
   59540 ** this page has no children.  The zerodata flag means that this page carries
   59541 ** only keys and no data.  The intkey flag means that the key is an integer
   59542 ** which is stored in the key size entry of the cell header rather than in
   59543 ** the payload area.
   59544 **
   59545 ** The cell pointer array begins on the first byte after the page header.
   59546 ** The cell pointer array contains zero or more 2-byte numbers which are
   59547 ** offsets from the beginning of the page to the cell content in the cell
   59548 ** content area.  The cell pointers occur in sorted order.  The system strives
   59549 ** to keep free space after the last cell pointer so that new cells can
   59550 ** be easily added without having to defragment the page.
   59551 **
   59552 ** Cell content is stored at the very end of the page and grows toward the
   59553 ** beginning of the page.
   59554 **
   59555 ** Unused space within the cell content area is collected into a linked list of
   59556 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
   59557 ** to the first freeblock is given in the header.  Freeblocks occur in
   59558 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
   59559 ** any group of 3 or fewer unused bytes in the cell content area cannot
   59560 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
   59561 ** a fragment.  The total number of bytes in all fragments is recorded.
   59562 ** in the page header at offset 7.
   59563 **
   59564 **    SIZE    DESCRIPTION
   59565 **      2     Byte offset of the next freeblock
   59566 **      2     Bytes in this freeblock
   59567 **
   59568 ** Cells are of variable length.  Cells are stored in the cell content area at
   59569 ** the end of the page.  Pointers to the cells are in the cell pointer array
   59570 ** that immediately follows the page header.  Cells is not necessarily
   59571 ** contiguous or in order, but cell pointers are contiguous and in order.
   59572 **
   59573 ** Cell content makes use of variable length integers.  A variable
   59574 ** length integer is 1 to 9 bytes where the lower 7 bits of each
   59575 ** byte are used.  The integer consists of all bytes that have bit 8 set and
   59576 ** the first byte with bit 8 clear.  The most significant byte of the integer
   59577 ** appears first.  A variable-length integer may not be more than 9 bytes long.
   59578 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
   59579 ** allows a 64-bit integer to be encoded in 9 bytes.
   59580 **
   59581 **    0x00                      becomes  0x00000000
   59582 **    0x7f                      becomes  0x0000007f
   59583 **    0x81 0x00                 becomes  0x00000080
   59584 **    0x82 0x00                 becomes  0x00000100
   59585 **    0x80 0x7f                 becomes  0x0000007f
   59586 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
   59587 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
   59588 **
   59589 ** Variable length integers are used for rowids and to hold the number of
   59590 ** bytes of key and data in a btree cell.
   59591 **
   59592 ** The content of a cell looks like this:
   59593 **
   59594 **    SIZE    DESCRIPTION
   59595 **      4     Page number of the left child. Omitted if leaf flag is set.
   59596 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
   59597 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
   59598 **      *     Payload
   59599 **      4     First page of the overflow chain.  Omitted if no overflow
   59600 **
   59601 ** Overflow pages form a linked list.  Each page except the last is completely
   59602 ** filled with data (pagesize - 4 bytes).  The last page can have as little
   59603 ** as 1 byte of data.
   59604 **
   59605 **    SIZE    DESCRIPTION
   59606 **      4     Page number of next overflow page
   59607 **      *     Data
   59608 **
   59609 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
   59610 ** file header points to the first in a linked list of trunk page.  Each trunk
   59611 ** page points to multiple leaf pages.  The content of a leaf page is
   59612 ** unspecified.  A trunk page looks like this:
   59613 **
   59614 **    SIZE    DESCRIPTION
   59615 **      4     Page number of next trunk page
   59616 **      4     Number of leaf pointers on this page
   59617 **      *     zero or more pages numbers of leaves
   59618 */
   59619 /* #include "sqliteInt.h" */
   59620 
   59621 
   59622 /* The following value is the maximum cell size assuming a maximum page
   59623 ** size give above.
   59624 */
   59625 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
   59626 
   59627 /* The maximum number of cells on a single page of the database.  This
   59628 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
   59629 ** plus 2 bytes for the index to the cell in the page header).  Such
   59630 ** small cells will be rare, but they are possible.
   59631 */
   59632 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
   59633 
   59634 /* Forward declarations */
   59635 typedef struct MemPage MemPage;
   59636 typedef struct BtLock BtLock;
   59637 typedef struct CellInfo CellInfo;
   59638 
   59639 /*
   59640 ** This is a magic string that appears at the beginning of every
   59641 ** SQLite database in order to identify the file as a real database.
   59642 **
   59643 ** You can change this value at compile-time by specifying a
   59644 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
   59645 ** header must be exactly 16 bytes including the zero-terminator so
   59646 ** the string itself should be 15 characters long.  If you change
   59647 ** the header, then your custom library will not be able to read
   59648 ** databases generated by the standard tools and the standard tools
   59649 ** will not be able to read databases created by your custom library.
   59650 */
   59651 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
   59652 #  define SQLITE_FILE_HEADER "SQLite format 3"
   59653 #endif
   59654 
   59655 /*
   59656 ** Page type flags.  An ORed combination of these flags appear as the
   59657 ** first byte of on-disk image of every BTree page.
   59658 */
   59659 #define PTF_INTKEY    0x01
   59660 #define PTF_ZERODATA  0x02
   59661 #define PTF_LEAFDATA  0x04
   59662 #define PTF_LEAF      0x08
   59663 
   59664 /*
   59665 ** An instance of this object stores information about each a single database
   59666 ** page that has been loaded into memory.  The information in this object
   59667 ** is derived from the raw on-disk page content.
   59668 **
   59669 ** As each database page is loaded into memory, the pager allocats an
   59670 ** instance of this object and zeros the first 8 bytes.  (This is the
   59671 ** "extra" information associated with each page of the pager.)
   59672 **
   59673 ** Access to all fields of this structure is controlled by the mutex
   59674 ** stored in MemPage.pBt->mutex.
   59675 */
   59676 struct MemPage {
   59677   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   59678   u8 bBusy;            /* Prevent endless loops on corrupt database files */
   59679   u8 intKey;           /* True if table b-trees.  False for index b-trees */
   59680   u8 intKeyLeaf;       /* True if the leaf of an intKey table */
   59681   Pgno pgno;           /* Page number for this page */
   59682   /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
   59683   ** is allocated. All fields that follow must be initialized before use */
   59684   u8 leaf;             /* True if a leaf page */
   59685   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   59686   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   59687   u8 max1bytePayload;  /* min(maxLocal,127) */
   59688   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   59689   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   59690   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   59691   u16 cellOffset;      /* Index in aData of first cell pointer */
   59692   u16 nFree;           /* Number of free bytes on the page */
   59693   u16 nCell;           /* Number of cells on this page, local and ovfl */
   59694   u16 maskPage;        /* Mask for page offset */
   59695   u16 aiOvfl[4];       /* Insert the i-th overflow cell before the aiOvfl-th
   59696                        ** non-overflow cell */
   59697   u8 *apOvfl[4];       /* Pointers to the body of overflow cells */
   59698   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   59699   u8 *aData;           /* Pointer to disk image of the page data */
   59700   u8 *aDataEnd;        /* One byte past the end of usable data */
   59701   u8 *aCellIdx;        /* The cell index area */
   59702   u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
   59703   DbPage *pDbPage;     /* Pager page handle */
   59704   u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
   59705   void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
   59706 };
   59707 
   59708 /*
   59709 ** A linked list of the following structures is stored at BtShared.pLock.
   59710 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
   59711 ** is opened on the table with root page BtShared.iTable. Locks are removed
   59712 ** from this list when a transaction is committed or rolled back, or when
   59713 ** a btree handle is closed.
   59714 */
   59715 struct BtLock {
   59716   Btree *pBtree;        /* Btree handle holding this lock */
   59717   Pgno iTable;          /* Root page of table */
   59718   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
   59719   BtLock *pNext;        /* Next in BtShared.pLock list */
   59720 };
   59721 
   59722 /* Candidate values for BtLock.eLock */
   59723 #define READ_LOCK     1
   59724 #define WRITE_LOCK    2
   59725 
   59726 /* A Btree handle
   59727 **
   59728 ** A database connection contains a pointer to an instance of
   59729 ** this object for every database file that it has open.  This structure
   59730 ** is opaque to the database connection.  The database connection cannot
   59731 ** see the internals of this structure and only deals with pointers to
   59732 ** this structure.
   59733 **
   59734 ** For some database files, the same underlying database cache might be
   59735 ** shared between multiple connections.  In that case, each connection
   59736 ** has it own instance of this object.  But each instance of this object
   59737 ** points to the same BtShared object.  The database cache and the
   59738 ** schema associated with the database file are all contained within
   59739 ** the BtShared object.
   59740 **
   59741 ** All fields in this structure are accessed under sqlite3.mutex.
   59742 ** The pBt pointer itself may not be changed while there exists cursors
   59743 ** in the referenced BtShared that point back to this Btree since those
   59744 ** cursors have to go through this Btree to find their BtShared and
   59745 ** they often do so without holding sqlite3.mutex.
   59746 */
   59747 struct Btree {
   59748   sqlite3 *db;       /* The database connection holding this btree */
   59749   BtShared *pBt;     /* Sharable content of this btree */
   59750   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
   59751   u8 sharable;       /* True if we can share pBt with another db */
   59752   u8 locked;         /* True if db currently has pBt locked */
   59753   u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
   59754   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   59755   int nBackup;       /* Number of backup operations reading this btree */
   59756   u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
   59757   Btree *pNext;      /* List of other sharable Btrees from the same db */
   59758   Btree *pPrev;      /* Back pointer of the same list */
   59759 #ifndef SQLITE_OMIT_SHARED_CACHE
   59760   BtLock lock;       /* Object used to lock page 1 */
   59761 #endif
   59762 };
   59763 
   59764 /*
   59765 ** Btree.inTrans may take one of the following values.
   59766 **
   59767 ** If the shared-data extension is enabled, there may be multiple users
   59768 ** of the Btree structure. At most one of these may open a write transaction,
   59769 ** but any number may have active read transactions.
   59770 */
   59771 #define TRANS_NONE  0
   59772 #define TRANS_READ  1
   59773 #define TRANS_WRITE 2
   59774 
   59775 /*
   59776 ** An instance of this object represents a single database file.
   59777 **
   59778 ** A single database file can be in use at the same time by two
   59779 ** or more database connections.  When two or more connections are
   59780 ** sharing the same database file, each connection has it own
   59781 ** private Btree object for the file and each of those Btrees points
   59782 ** to this one BtShared object.  BtShared.nRef is the number of
   59783 ** connections currently sharing this database file.
   59784 **
   59785 ** Fields in this structure are accessed under the BtShared.mutex
   59786 ** mutex, except for nRef and pNext which are accessed under the
   59787 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
   59788 ** may not be modified once it is initially set as long as nRef>0.
   59789 ** The pSchema field may be set once under BtShared.mutex and
   59790 ** thereafter is unchanged as long as nRef>0.
   59791 **
   59792 ** isPending:
   59793 **
   59794 **   If a BtShared client fails to obtain a write-lock on a database
   59795 **   table (because there exists one or more read-locks on the table),
   59796 **   the shared-cache enters 'pending-lock' state and isPending is
   59797 **   set to true.
   59798 **
   59799 **   The shared-cache leaves the 'pending lock' state when either of
   59800 **   the following occur:
   59801 **
   59802 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
   59803 **     2) The number of locks held by other connections drops to zero.
   59804 **
   59805 **   while in the 'pending-lock' state, no connection may start a new
   59806 **   transaction.
   59807 **
   59808 **   This feature is included to help prevent writer-starvation.
   59809 */
   59810 struct BtShared {
   59811   Pager *pPager;        /* The page cache */
   59812   sqlite3 *db;          /* Database connection currently using this Btree */
   59813   BtCursor *pCursor;    /* A list of all open cursors */
   59814   MemPage *pPage1;      /* First page of the database */
   59815   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
   59816 #ifndef SQLITE_OMIT_AUTOVACUUM
   59817   u8 autoVacuum;        /* True if auto-vacuum is enabled */
   59818   u8 incrVacuum;        /* True if incr-vacuum is enabled */
   59819   u8 bDoTruncate;       /* True to truncate db on commit */
   59820 #endif
   59821   u8 inTransaction;     /* Transaction state */
   59822   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
   59823 #ifdef SQLITE_HAS_CODEC
   59824   u8 optimalReserve;    /* Desired amount of reserved space per page */
   59825 #endif
   59826   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
   59827   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   59828   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   59829   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   59830   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
   59831   u32 pageSize;         /* Total number of bytes on a page */
   59832   u32 usableSize;       /* Number of usable bytes on each page */
   59833   int nTransaction;     /* Number of open transactions (read + write) */
   59834   u32 nPage;            /* Number of pages in the database */
   59835   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
   59836   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
   59837   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
   59838   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
   59839 #ifndef SQLITE_OMIT_SHARED_CACHE
   59840   int nRef;             /* Number of references to this structure */
   59841   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
   59842   BtLock *pLock;        /* List of locks held on this shared-btree struct */
   59843   Btree *pWriter;       /* Btree with currently open write transaction */
   59844 #endif
   59845   u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
   59846 };
   59847 
   59848 /*
   59849 ** Allowed values for BtShared.btsFlags
   59850 */
   59851 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
   59852 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
   59853 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
   59854 #define BTS_OVERWRITE        0x0008   /* Overwrite deleted content with zeros */
   59855 #define BTS_FAST_SECURE      0x000c   /* Combination of the previous two */
   59856 #define BTS_INITIALLY_EMPTY  0x0010   /* Database was empty at trans start */
   59857 #define BTS_NO_WAL           0x0020   /* Do not open write-ahead-log files */
   59858 #define BTS_EXCLUSIVE        0x0040   /* pWriter has an exclusive lock */
   59859 #define BTS_PENDING          0x0080   /* Waiting for read-locks to clear */
   59860 
   59861 /*
   59862 ** An instance of the following structure is used to hold information
   59863 ** about a cell.  The parseCellPtr() function fills in this structure
   59864 ** based on information extract from the raw disk page.
   59865 */
   59866 struct CellInfo {
   59867   i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
   59868   u8 *pPayload;  /* Pointer to the start of payload */
   59869   u32 nPayload;  /* Bytes of payload */
   59870   u16 nLocal;    /* Amount of payload held locally, not on overflow */
   59871   u16 nSize;     /* Size of the cell content on the main b-tree page */
   59872 };
   59873 
   59874 /*
   59875 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   59876 ** this will be declared corrupt. This value is calculated based on a
   59877 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
   59878 ** root-node and 3 for all other internal nodes.
   59879 **
   59880 ** If a tree that appears to be taller than this is encountered, it is
   59881 ** assumed that the database is corrupt.
   59882 */
   59883 #define BTCURSOR_MAX_DEPTH 20
   59884 
   59885 /*
   59886 ** A cursor is a pointer to a particular entry within a particular
   59887 ** b-tree within a database file.
   59888 **
   59889 ** The entry is identified by its MemPage and the index in
   59890 ** MemPage.aCell[] of the entry.
   59891 **
   59892 ** A single database file can be shared by two more database connections,
   59893 ** but cursors cannot be shared.  Each cursor is associated with a
   59894 ** particular database connection identified BtCursor.pBtree.db.
   59895 **
   59896 ** Fields in this structure are accessed under the BtShared.mutex
   59897 ** found at self->pBt->mutex.
   59898 **
   59899 ** skipNext meaning:
   59900 **    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
   59901 **    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
   59902 **    eState==FAULT:                   Cursor fault with skipNext as error code.
   59903 */
   59904 struct BtCursor {
   59905   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
   59906   u8 curFlags;              /* zero or more BTCF_* flags defined below */
   59907   u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
   59908   u8 hints;                 /* As configured by CursorSetHints() */
   59909   int nOvflAlloc;           /* Allocated size of aOverflow[] array */
   59910   Btree *pBtree;            /* The Btree to which this cursor belongs */
   59911   BtShared *pBt;            /* The BtShared this cursor points to */
   59912   BtCursor *pNext;          /* Forms a linked list of all cursors */
   59913   Pgno *aOverflow;          /* Cache of overflow page locations */
   59914   CellInfo info;            /* A parse of the cell we are pointing at */
   59915   i64 nKey;                 /* Size of pKey, or last integer key */
   59916   void *pKey;               /* Saved key that was cursor last known position */
   59917   Pgno pgnoRoot;            /* The root page of this tree */
   59918   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
   59919                    ** Error code if eState==CURSOR_FAULT */
   59920   /* All fields above are zeroed when the cursor is allocated.  See
   59921   ** sqlite3BtreeCursorZero().  Fields that follow must be manually
   59922   ** initialized. */
   59923   i8 iPage;                 /* Index of current page in apPage */
   59924   u8 curIntKey;             /* Value of apPage[0]->intKey */
   59925   u16 ix;                   /* Current index for apPage[iPage] */
   59926   u16 aiIdx[BTCURSOR_MAX_DEPTH-1];     /* Current index in apPage[i] */
   59927   struct KeyInfo *pKeyInfo;            /* Arg passed to comparison function */
   59928   MemPage *pPage;                        /* Current page */
   59929   MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
   59930 };
   59931 
   59932 /*
   59933 ** Legal values for BtCursor.curFlags
   59934 */
   59935 #define BTCF_WriteFlag    0x01   /* True if a write cursor */
   59936 #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
   59937 #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
   59938 #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
   59939 #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
   59940 #define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
   59941 
   59942 /*
   59943 ** Potential values for BtCursor.eState.
   59944 **
   59945 ** CURSOR_INVALID:
   59946 **   Cursor does not point to a valid entry. This can happen (for example)
   59947 **   because the table is empty or because BtreeCursorFirst() has not been
   59948 **   called.
   59949 **
   59950 ** CURSOR_VALID:
   59951 **   Cursor points to a valid entry. getPayload() etc. may be called.
   59952 **
   59953 ** CURSOR_SKIPNEXT:
   59954 **   Cursor is valid except that the Cursor.skipNext field is non-zero
   59955 **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
   59956 **   operation should be a no-op.
   59957 **
   59958 ** CURSOR_REQUIRESEEK:
   59959 **   The table that this cursor was opened on still exists, but has been
   59960 **   modified since the cursor was last used. The cursor position is saved
   59961 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
   59962 **   this state, restoreCursorPosition() can be called to attempt to
   59963 **   seek the cursor to the saved position.
   59964 **
   59965 ** CURSOR_FAULT:
   59966 **   An unrecoverable error (an I/O error or a malloc failure) has occurred
   59967 **   on a different connection that shares the BtShared cache with this
   59968 **   cursor.  The error has left the cache in an inconsistent state.
   59969 **   Do nothing else with this cursor.  Any attempt to use the cursor
   59970 **   should return the error code stored in BtCursor.skipNext
   59971 */
   59972 #define CURSOR_INVALID           0
   59973 #define CURSOR_VALID             1
   59974 #define CURSOR_SKIPNEXT          2
   59975 #define CURSOR_REQUIRESEEK       3
   59976 #define CURSOR_FAULT             4
   59977 
   59978 /*
   59979 ** The database page the PENDING_BYTE occupies. This page is never used.
   59980 */
   59981 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
   59982 
   59983 /*
   59984 ** These macros define the location of the pointer-map entry for a
   59985 ** database page. The first argument to each is the number of usable
   59986 ** bytes on each page of the database (often 1024). The second is the
   59987 ** page number to look up in the pointer map.
   59988 **
   59989 ** PTRMAP_PAGENO returns the database page number of the pointer-map
   59990 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
   59991 ** the offset of the requested map entry.
   59992 **
   59993 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
   59994 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
   59995 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
   59996 ** this test.
   59997 */
   59998 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
   59999 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
   60000 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
   60001 
   60002 /*
   60003 ** The pointer map is a lookup table that identifies the parent page for
   60004 ** each child page in the database file.  The parent page is the page that
   60005 ** contains a pointer to the child.  Every page in the database contains
   60006 ** 0 or 1 parent pages.  (In this context 'database page' refers
   60007 ** to any page that is not part of the pointer map itself.)  Each pointer map
   60008 ** entry consists of a single byte 'type' and a 4 byte parent page number.
   60009 ** The PTRMAP_XXX identifiers below are the valid types.
   60010 **
   60011 ** The purpose of the pointer map is to facility moving pages from one
   60012 ** position in the file to another as part of autovacuum.  When a page
   60013 ** is moved, the pointer in its parent must be updated to point to the
   60014 ** new location.  The pointer map is used to locate the parent page quickly.
   60015 **
   60016 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
   60017 **                  used in this case.
   60018 **
   60019 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
   60020 **                  is not used in this case.
   60021 **
   60022 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
   60023 **                   overflow pages. The page number identifies the page that
   60024 **                   contains the cell with a pointer to this overflow page.
   60025 **
   60026 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
   60027 **                   overflow pages. The page-number identifies the previous
   60028 **                   page in the overflow page list.
   60029 **
   60030 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
   60031 **               identifies the parent page in the btree.
   60032 */
   60033 #define PTRMAP_ROOTPAGE 1
   60034 #define PTRMAP_FREEPAGE 2
   60035 #define PTRMAP_OVERFLOW1 3
   60036 #define PTRMAP_OVERFLOW2 4
   60037 #define PTRMAP_BTREE 5
   60038 
   60039 /* A bunch of assert() statements to check the transaction state variables
   60040 ** of handle p (type Btree*) are internally consistent.
   60041 */
   60042 #define btreeIntegrity(p) \
   60043   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
   60044   assert( p->pBt->inTransaction>=p->inTrans );
   60045 
   60046 
   60047 /*
   60048 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
   60049 ** if the database supports auto-vacuum or not. Because it is used
   60050 ** within an expression that is an argument to another macro
   60051 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
   60052 ** So, this macro is defined instead.
   60053 */
   60054 #ifndef SQLITE_OMIT_AUTOVACUUM
   60055 #define ISAUTOVACUUM (pBt->autoVacuum)
   60056 #else
   60057 #define ISAUTOVACUUM 0
   60058 #endif
   60059 
   60060 
   60061 /*
   60062 ** This structure is passed around through all the sanity checking routines
   60063 ** in order to keep track of some global state information.
   60064 **
   60065 ** The aRef[] array is allocated so that there is 1 bit for each page in
   60066 ** the database. As the integrity-check proceeds, for each page used in
   60067 ** the database the corresponding bit is set. This allows integrity-check to
   60068 ** detect pages that are used twice and orphaned pages (both of which
   60069 ** indicate corruption).
   60070 */
   60071 typedef struct IntegrityCk IntegrityCk;
   60072 struct IntegrityCk {
   60073   BtShared *pBt;    /* The tree being checked out */
   60074   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   60075   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
   60076   Pgno nPage;       /* Number of pages in the database */
   60077   int mxErr;        /* Stop accumulating errors when this reaches zero */
   60078   int nErr;         /* Number of messages written to zErrMsg so far */
   60079   int mallocFailed; /* A memory allocation error has occurred */
   60080   const char *zPfx; /* Error message prefix */
   60081   int v1, v2;       /* Values for up to two %d fields in zPfx */
   60082   StrAccum errMsg;  /* Accumulate the error message text here */
   60083   u32 *heap;        /* Min-heap used for analyzing cell coverage */
   60084 };
   60085 
   60086 /*
   60087 ** Routines to read or write a two- and four-byte big-endian integer values.
   60088 */
   60089 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   60090 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   60091 #define get4byte sqlite3Get4byte
   60092 #define put4byte sqlite3Put4byte
   60093 
   60094 /*
   60095 ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
   60096 ** two-byte aligned address.  get2bytea() is only used for accessing the
   60097 ** cell addresses in a btree header.
   60098 */
   60099 #if SQLITE_BYTEORDER==4321
   60100 # define get2byteAligned(x)  (*(u16*)(x))
   60101 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
   60102 # define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
   60103 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   60104 # define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
   60105 #else
   60106 # define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
   60107 #endif
   60108 
   60109 /************** End of btreeInt.h ********************************************/
   60110 /************** Continuing where we left off in btmutex.c ********************/
   60111 #ifndef SQLITE_OMIT_SHARED_CACHE
   60112 #if SQLITE_THREADSAFE
   60113 
   60114 /*
   60115 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
   60116 ** set BtShared.db to the database handle associated with p and the
   60117 ** p->locked boolean to true.
   60118 */
   60119 static void lockBtreeMutex(Btree *p){
   60120   assert( p->locked==0 );
   60121   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
   60122   assert( sqlite3_mutex_held(p->db->mutex) );
   60123 
   60124   sqlite3_mutex_enter(p->pBt->mutex);
   60125   p->pBt->db = p->db;
   60126   p->locked = 1;
   60127 }
   60128 
   60129 /*
   60130 ** Release the BtShared mutex associated with B-Tree handle p and
   60131 ** clear the p->locked boolean.
   60132 */
   60133 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
   60134   BtShared *pBt = p->pBt;
   60135   assert( p->locked==1 );
   60136   assert( sqlite3_mutex_held(pBt->mutex) );
   60137   assert( sqlite3_mutex_held(p->db->mutex) );
   60138   assert( p->db==pBt->db );
   60139 
   60140   sqlite3_mutex_leave(pBt->mutex);
   60141   p->locked = 0;
   60142 }
   60143 
   60144 /* Forward reference */
   60145 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
   60146 
   60147 /*
   60148 ** Enter a mutex on the given BTree object.
   60149 **
   60150 ** If the object is not sharable, then no mutex is ever required
   60151 ** and this routine is a no-op.  The underlying mutex is non-recursive.
   60152 ** But we keep a reference count in Btree.wantToLock so the behavior
   60153 ** of this interface is recursive.
   60154 **
   60155 ** To avoid deadlocks, multiple Btrees are locked in the same order
   60156 ** by all database connections.  The p->pNext is a list of other
   60157 ** Btrees belonging to the same database connection as the p Btree
   60158 ** which need to be locked after p.  If we cannot get a lock on
   60159 ** p, then first unlock all of the others on p->pNext, then wait
   60160 ** for the lock to become available on p, then relock all of the
   60161 ** subsequent Btrees that desire a lock.
   60162 */
   60163 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   60164   /* Some basic sanity checking on the Btree.  The list of Btrees
   60165   ** connected by pNext and pPrev should be in sorted order by
   60166   ** Btree.pBt value. All elements of the list should belong to
   60167   ** the same connection. Only shared Btrees are on the list. */
   60168   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
   60169   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
   60170   assert( p->pNext==0 || p->pNext->db==p->db );
   60171   assert( p->pPrev==0 || p->pPrev->db==p->db );
   60172   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
   60173 
   60174   /* Check for locking consistency */
   60175   assert( !p->locked || p->wantToLock>0 );
   60176   assert( p->sharable || p->wantToLock==0 );
   60177 
   60178   /* We should already hold a lock on the database connection */
   60179   assert( sqlite3_mutex_held(p->db->mutex) );
   60180 
   60181   /* Unless the database is sharable and unlocked, then BtShared.db
   60182   ** should already be set correctly. */
   60183   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   60184 
   60185   if( !p->sharable ) return;
   60186   p->wantToLock++;
   60187   if( p->locked ) return;
   60188   btreeLockCarefully(p);
   60189 }
   60190 
   60191 /* This is a helper function for sqlite3BtreeLock(). By moving
   60192 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
   60193 ** into this routine, we avoid unnecessary stack pointer changes
   60194 ** and thus help the sqlite3BtreeLock() routine to run much faster
   60195 ** in the common case.
   60196 */
   60197 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
   60198   Btree *pLater;
   60199 
   60200   /* In most cases, we should be able to acquire the lock we
   60201   ** want without having to go through the ascending lock
   60202   ** procedure that follows.  Just be sure not to block.
   60203   */
   60204   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
   60205     p->pBt->db = p->db;
   60206     p->locked = 1;
   60207     return;
   60208   }
   60209 
   60210   /* To avoid deadlock, first release all locks with a larger
   60211   ** BtShared address.  Then acquire our lock.  Then reacquire
   60212   ** the other BtShared locks that we used to hold in ascending
   60213   ** order.
   60214   */
   60215   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   60216     assert( pLater->sharable );
   60217     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
   60218     assert( !pLater->locked || pLater->wantToLock>0 );
   60219     if( pLater->locked ){
   60220       unlockBtreeMutex(pLater);
   60221     }
   60222   }
   60223   lockBtreeMutex(p);
   60224   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   60225     if( pLater->wantToLock ){
   60226       lockBtreeMutex(pLater);
   60227     }
   60228   }
   60229 }
   60230 
   60231 
   60232 /*
   60233 ** Exit the recursive mutex on a Btree.
   60234 */
   60235 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
   60236   assert( sqlite3_mutex_held(p->db->mutex) );
   60237   if( p->sharable ){
   60238     assert( p->wantToLock>0 );
   60239     p->wantToLock--;
   60240     if( p->wantToLock==0 ){
   60241       unlockBtreeMutex(p);
   60242     }
   60243   }
   60244 }
   60245 
   60246 #ifndef NDEBUG
   60247 /*
   60248 ** Return true if the BtShared mutex is held on the btree, or if the
   60249 ** B-Tree is not marked as sharable.
   60250 **
   60251 ** This routine is used only from within assert() statements.
   60252 */
   60253 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
   60254   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
   60255   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
   60256   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
   60257   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
   60258 
   60259   return (p->sharable==0 || p->locked);
   60260 }
   60261 #endif
   60262 
   60263 
   60264 /*
   60265 ** Enter the mutex on every Btree associated with a database
   60266 ** connection.  This is needed (for example) prior to parsing
   60267 ** a statement since we will be comparing table and column names
   60268 ** against all schemas and we do not want those schemas being
   60269 ** reset out from under us.
   60270 **
   60271 ** There is a corresponding leave-all procedures.
   60272 **
   60273 ** Enter the mutexes in accending order by BtShared pointer address
   60274 ** to avoid the possibility of deadlock when two threads with
   60275 ** two or more btrees in common both try to lock all their btrees
   60276 ** at the same instant.
   60277 */
   60278 static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
   60279   int i;
   60280   int skipOk = 1;
   60281   Btree *p;
   60282   assert( sqlite3_mutex_held(db->mutex) );
   60283   for(i=0; i<db->nDb; i++){
   60284     p = db->aDb[i].pBt;
   60285     if( p && p->sharable ){
   60286       sqlite3BtreeEnter(p);
   60287       skipOk = 0;
   60288     }
   60289   }
   60290   db->skipBtreeMutex = skipOk;
   60291 }
   60292 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   60293   if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
   60294 }
   60295 static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
   60296   int i;
   60297   Btree *p;
   60298   assert( sqlite3_mutex_held(db->mutex) );
   60299   for(i=0; i<db->nDb; i++){
   60300     p = db->aDb[i].pBt;
   60301     if( p ) sqlite3BtreeLeave(p);
   60302   }
   60303 }
   60304 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
   60305   if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
   60306 }
   60307 
   60308 #ifndef NDEBUG
   60309 /*
   60310 ** Return true if the current thread holds the database connection
   60311 ** mutex and all required BtShared mutexes.
   60312 **
   60313 ** This routine is used inside assert() statements only.
   60314 */
   60315 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
   60316   int i;
   60317   if( !sqlite3_mutex_held(db->mutex) ){
   60318     return 0;
   60319   }
   60320   for(i=0; i<db->nDb; i++){
   60321     Btree *p;
   60322     p = db->aDb[i].pBt;
   60323     if( p && p->sharable &&
   60324          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
   60325       return 0;
   60326     }
   60327   }
   60328   return 1;
   60329 }
   60330 #endif /* NDEBUG */
   60331 
   60332 #ifndef NDEBUG
   60333 /*
   60334 ** Return true if the correct mutexes are held for accessing the
   60335 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
   60336 ** access are:
   60337 **
   60338 **   (1) The mutex on db
   60339 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
   60340 **
   60341 ** If pSchema is not NULL, then iDb is computed from pSchema and
   60342 ** db using sqlite3SchemaToIndex().
   60343 */
   60344 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
   60345   Btree *p;
   60346   assert( db!=0 );
   60347   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
   60348   assert( iDb>=0 && iDb<db->nDb );
   60349   if( !sqlite3_mutex_held(db->mutex) ) return 0;
   60350   if( iDb==1 ) return 1;
   60351   p = db->aDb[iDb].pBt;
   60352   assert( p!=0 );
   60353   return p->sharable==0 || p->locked==1;
   60354 }
   60355 #endif /* NDEBUG */
   60356 
   60357 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
   60358 /*
   60359 ** The following are special cases for mutex enter routines for use
   60360 ** in single threaded applications that use shared cache.  Except for
   60361 ** these two routines, all mutex operations are no-ops in that case and
   60362 ** are null #defines in btree.h.
   60363 **
   60364 ** If shared cache is disabled, then all btree mutex routines, including
   60365 ** the ones below, are no-ops and are null #defines in btree.h.
   60366 */
   60367 
   60368 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   60369   p->pBt->db = p->db;
   60370 }
   60371 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   60372   int i;
   60373   for(i=0; i<db->nDb; i++){
   60374     Btree *p = db->aDb[i].pBt;
   60375     if( p ){
   60376       p->pBt->db = p->db;
   60377     }
   60378   }
   60379 }
   60380 #endif /* if SQLITE_THREADSAFE */
   60381 
   60382 #ifndef SQLITE_OMIT_INCRBLOB
   60383 /*
   60384 ** Enter a mutex on a Btree given a cursor owned by that Btree.
   60385 **
   60386 ** These entry points are used by incremental I/O only. Enter() is required
   60387 ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
   60388 ** the build is threadsafe. Leave() is only required by threadsafe builds.
   60389 */
   60390 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
   60391   sqlite3BtreeEnter(pCur->pBtree);
   60392 }
   60393 # if SQLITE_THREADSAFE
   60394 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
   60395   sqlite3BtreeLeave(pCur->pBtree);
   60396 }
   60397 # endif
   60398 #endif /* ifndef SQLITE_OMIT_INCRBLOB */
   60399 
   60400 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
   60401 
   60402 /************** End of btmutex.c *********************************************/
   60403 /************** Begin file btree.c *******************************************/
   60404 /*
   60405 ** 2004 April 6
   60406 **
   60407 ** The author disclaims copyright to this source code.  In place of
   60408 ** a legal notice, here is a blessing:
   60409 **
   60410 **    May you do good and not evil.
   60411 **    May you find forgiveness for yourself and forgive others.
   60412 **    May you share freely, never taking more than you give.
   60413 **
   60414 *************************************************************************
   60415 ** This file implements an external (disk-based) database using BTrees.
   60416 ** See the header comment on "btreeInt.h" for additional information.
   60417 ** Including a description of file format and an overview of operation.
   60418 */
   60419 /* #include "btreeInt.h" */
   60420 
   60421 /*
   60422 ** The header string that appears at the beginning of every
   60423 ** SQLite database.
   60424 */
   60425 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
   60426 
   60427 /*
   60428 ** Set this global variable to 1 to enable tracing using the TRACE
   60429 ** macro.
   60430 */
   60431 #if 0
   60432 int sqlite3BtreeTrace=1;  /* True to enable tracing */
   60433 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
   60434 #else
   60435 # define TRACE(X)
   60436 #endif
   60437 
   60438 /*
   60439 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
   60440 ** But if the value is zero, make it 65536.
   60441 **
   60442 ** This routine is used to extract the "offset to cell content area" value
   60443 ** from the header of a btree page.  If the page size is 65536 and the page
   60444 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
   60445 ** This routine makes the necessary adjustment to 65536.
   60446 */
   60447 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
   60448 
   60449 /*
   60450 ** Values passed as the 5th argument to allocateBtreePage()
   60451 */
   60452 #define BTALLOC_ANY   0           /* Allocate any page */
   60453 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
   60454 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
   60455 
   60456 /*
   60457 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
   60458 ** defined, or 0 if it is. For example:
   60459 **
   60460 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
   60461 */
   60462 #ifndef SQLITE_OMIT_AUTOVACUUM
   60463 #define IfNotOmitAV(expr) (expr)
   60464 #else
   60465 #define IfNotOmitAV(expr) 0
   60466 #endif
   60467 
   60468 #ifndef SQLITE_OMIT_SHARED_CACHE
   60469 /*
   60470 ** A list of BtShared objects that are eligible for participation
   60471 ** in shared cache.  This variable has file scope during normal builds,
   60472 ** but the test harness needs to access it so we make it global for
   60473 ** test builds.
   60474 **
   60475 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
   60476 */
   60477 #ifdef SQLITE_TEST
   60478 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   60479 #else
   60480 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   60481 #endif
   60482 #endif /* SQLITE_OMIT_SHARED_CACHE */
   60483 
   60484 #ifndef SQLITE_OMIT_SHARED_CACHE
   60485 /*
   60486 ** Enable or disable the shared pager and schema features.
   60487 **
   60488 ** This routine has no effect on existing database connections.
   60489 ** The shared cache setting effects only future calls to
   60490 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
   60491 */
   60492 SQLITE_API int sqlite3_enable_shared_cache(int enable){
   60493   sqlite3GlobalConfig.sharedCacheEnabled = enable;
   60494   return SQLITE_OK;
   60495 }
   60496 #endif
   60497 
   60498 
   60499 
   60500 #ifdef SQLITE_OMIT_SHARED_CACHE
   60501   /*
   60502   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
   60503   ** and clearAllSharedCacheTableLocks()
   60504   ** manipulate entries in the BtShared.pLock linked list used to store
   60505   ** shared-cache table level locks. If the library is compiled with the
   60506   ** shared-cache feature disabled, then there is only ever one user
   60507   ** of each BtShared structure and so this locking is not necessary.
   60508   ** So define the lock related functions as no-ops.
   60509   */
   60510   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
   60511   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
   60512   #define clearAllSharedCacheTableLocks(a)
   60513   #define downgradeAllSharedCacheTableLocks(a)
   60514   #define hasSharedCacheTableLock(a,b,c,d) 1
   60515   #define hasReadConflicts(a, b) 0
   60516 #endif
   60517 
   60518 /*
   60519 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
   60520 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
   60521 **
   60522 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
   60523 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
   60524 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
   60525 ** with the page number and filename associated with the (MemPage*).
   60526 */
   60527 #ifdef SQLITE_DEBUG
   60528 int corruptPageError(int lineno, MemPage *p){
   60529   char *zMsg;
   60530   sqlite3BeginBenignMalloc();
   60531   zMsg = sqlite3_mprintf("database corruption page %d of %s",
   60532       (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
   60533   );
   60534   sqlite3EndBenignMalloc();
   60535   if( zMsg ){
   60536     sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
   60537   }
   60538   sqlite3_free(zMsg);
   60539   return SQLITE_CORRUPT_BKPT;
   60540 }
   60541 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
   60542 #else
   60543 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
   60544 #endif
   60545 
   60546 #ifndef SQLITE_OMIT_SHARED_CACHE
   60547 
   60548 #ifdef SQLITE_DEBUG
   60549 /*
   60550 **** This function is only used as part of an assert() statement. ***
   60551 **
   60552 ** Check to see if pBtree holds the required locks to read or write to the
   60553 ** table with root page iRoot.   Return 1 if it does and 0 if not.
   60554 **
   60555 ** For example, when writing to a table with root-page iRoot via
   60556 ** Btree connection pBtree:
   60557 **
   60558 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
   60559 **
   60560 ** When writing to an index that resides in a sharable database, the
   60561 ** caller should have first obtained a lock specifying the root page of
   60562 ** the corresponding table. This makes things a bit more complicated,
   60563 ** as this module treats each table as a separate structure. To determine
   60564 ** the table corresponding to the index being written, this
   60565 ** function has to search through the database schema.
   60566 **
   60567 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
   60568 ** hold a write-lock on the schema table (root page 1). This is also
   60569 ** acceptable.
   60570 */
   60571 static int hasSharedCacheTableLock(
   60572   Btree *pBtree,         /* Handle that must hold lock */
   60573   Pgno iRoot,            /* Root page of b-tree */
   60574   int isIndex,           /* True if iRoot is the root of an index b-tree */
   60575   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
   60576 ){
   60577   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
   60578   Pgno iTab = 0;
   60579   BtLock *pLock;
   60580 
   60581   /* If this database is not shareable, or if the client is reading
   60582   ** and has the read-uncommitted flag set, then no lock is required.
   60583   ** Return true immediately.
   60584   */
   60585   if( (pBtree->sharable==0)
   60586    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
   60587   ){
   60588     return 1;
   60589   }
   60590 
   60591   /* If the client is reading  or writing an index and the schema is
   60592   ** not loaded, then it is too difficult to actually check to see if
   60593   ** the correct locks are held.  So do not bother - just return true.
   60594   ** This case does not come up very often anyhow.
   60595   */
   60596   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
   60597     return 1;
   60598   }
   60599 
   60600   /* Figure out the root-page that the lock should be held on. For table
   60601   ** b-trees, this is just the root page of the b-tree being read or
   60602   ** written. For index b-trees, it is the root page of the associated
   60603   ** table.  */
   60604   if( isIndex ){
   60605     HashElem *p;
   60606     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
   60607       Index *pIdx = (Index *)sqliteHashData(p);
   60608       if( pIdx->tnum==(int)iRoot ){
   60609         if( iTab ){
   60610           /* Two or more indexes share the same root page.  There must
   60611           ** be imposter tables.  So just return true.  The assert is not
   60612           ** useful in that case. */
   60613           return 1;
   60614         }
   60615         iTab = pIdx->pTable->tnum;
   60616       }
   60617     }
   60618   }else{
   60619     iTab = iRoot;
   60620   }
   60621 
   60622   /* Search for the required lock. Either a write-lock on root-page iTab, a
   60623   ** write-lock on the schema table, or (if the client is reading) a
   60624   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   60625   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
   60626     if( pLock->pBtree==pBtree
   60627      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
   60628      && pLock->eLock>=eLockType
   60629     ){
   60630       return 1;
   60631     }
   60632   }
   60633 
   60634   /* Failed to find the required lock. */
   60635   return 0;
   60636 }
   60637 #endif /* SQLITE_DEBUG */
   60638 
   60639 #ifdef SQLITE_DEBUG
   60640 /*
   60641 **** This function may be used as part of assert() statements only. ****
   60642 **
   60643 ** Return true if it would be illegal for pBtree to write into the
   60644 ** table or index rooted at iRoot because other shared connections are
   60645 ** simultaneously reading that same table or index.
   60646 **
   60647 ** It is illegal for pBtree to write if some other Btree object that
   60648 ** shares the same BtShared object is currently reading or writing
   60649 ** the iRoot table.  Except, if the other Btree object has the
   60650 ** read-uncommitted flag set, then it is OK for the other object to
   60651 ** have a read cursor.
   60652 **
   60653 ** For example, before writing to any part of the table or index
   60654 ** rooted at page iRoot, one should call:
   60655 **
   60656 **    assert( !hasReadConflicts(pBtree, iRoot) );
   60657 */
   60658 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   60659   BtCursor *p;
   60660   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   60661     if( p->pgnoRoot==iRoot
   60662      && p->pBtree!=pBtree
   60663      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
   60664     ){
   60665       return 1;
   60666     }
   60667   }
   60668   return 0;
   60669 }
   60670 #endif    /* #ifdef SQLITE_DEBUG */
   60671 
   60672 /*
   60673 ** Query to see if Btree handle p may obtain a lock of type eLock
   60674 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
   60675 ** SQLITE_OK if the lock may be obtained (by calling
   60676 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
   60677 */
   60678 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   60679   BtShared *pBt = p->pBt;
   60680   BtLock *pIter;
   60681 
   60682   assert( sqlite3BtreeHoldsMutex(p) );
   60683   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   60684   assert( p->db!=0 );
   60685   assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
   60686 
   60687   /* If requesting a write-lock, then the Btree must have an open write
   60688   ** transaction on this file. And, obviously, for this to be so there
   60689   ** must be an open write transaction on the file itself.
   60690   */
   60691   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   60692   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
   60693 
   60694   /* This routine is a no-op if the shared-cache is not enabled */
   60695   if( !p->sharable ){
   60696     return SQLITE_OK;
   60697   }
   60698 
   60699   /* If some other connection is holding an exclusive lock, the
   60700   ** requested lock may not be obtained.
   60701   */
   60702   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
   60703     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
   60704     return SQLITE_LOCKED_SHAREDCACHE;
   60705   }
   60706 
   60707   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   60708     /* The condition (pIter->eLock!=eLock) in the following if(...)
   60709     ** statement is a simplification of:
   60710     **
   60711     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
   60712     **
   60713     ** since we know that if eLock==WRITE_LOCK, then no other connection
   60714     ** may hold a WRITE_LOCK on any table in this file (since there can
   60715     ** only be a single writer).
   60716     */
   60717     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
   60718     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
   60719     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
   60720       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
   60721       if( eLock==WRITE_LOCK ){
   60722         assert( p==pBt->pWriter );
   60723         pBt->btsFlags |= BTS_PENDING;
   60724       }
   60725       return SQLITE_LOCKED_SHAREDCACHE;
   60726     }
   60727   }
   60728   return SQLITE_OK;
   60729 }
   60730 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   60731 
   60732 #ifndef SQLITE_OMIT_SHARED_CACHE
   60733 /*
   60734 ** Add a lock on the table with root-page iTable to the shared-btree used
   60735 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
   60736 ** WRITE_LOCK.
   60737 **
   60738 ** This function assumes the following:
   60739 **
   60740 **   (a) The specified Btree object p is connected to a sharable
   60741 **       database (one with the BtShared.sharable flag set), and
   60742 **
   60743 **   (b) No other Btree objects hold a lock that conflicts
   60744 **       with the requested lock (i.e. querySharedCacheTableLock() has
   60745 **       already been called and returned SQLITE_OK).
   60746 **
   60747 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
   60748 ** is returned if a malloc attempt fails.
   60749 */
   60750 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
   60751   BtShared *pBt = p->pBt;
   60752   BtLock *pLock = 0;
   60753   BtLock *pIter;
   60754 
   60755   assert( sqlite3BtreeHoldsMutex(p) );
   60756   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   60757   assert( p->db!=0 );
   60758 
   60759   /* A connection with the read-uncommitted flag set will never try to
   60760   ** obtain a read-lock using this function. The only read-lock obtained
   60761   ** by a connection in read-uncommitted mode is on the sqlite_master
   60762   ** table, and that lock is obtained in BtreeBeginTrans().  */
   60763   assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
   60764 
   60765   /* This function should only be called on a sharable b-tree after it
   60766   ** has been determined that no other b-tree holds a conflicting lock.  */
   60767   assert( p->sharable );
   60768   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
   60769 
   60770   /* First search the list for an existing lock on this table. */
   60771   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   60772     if( pIter->iTable==iTable && pIter->pBtree==p ){
   60773       pLock = pIter;
   60774       break;
   60775     }
   60776   }
   60777 
   60778   /* If the above search did not find a BtLock struct associating Btree p
   60779   ** with table iTable, allocate one and link it into the list.
   60780   */
   60781   if( !pLock ){
   60782     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
   60783     if( !pLock ){
   60784       return SQLITE_NOMEM_BKPT;
   60785     }
   60786     pLock->iTable = iTable;
   60787     pLock->pBtree = p;
   60788     pLock->pNext = pBt->pLock;
   60789     pBt->pLock = pLock;
   60790   }
   60791 
   60792   /* Set the BtLock.eLock variable to the maximum of the current lock
   60793   ** and the requested lock. This means if a write-lock was already held
   60794   ** and a read-lock requested, we don't incorrectly downgrade the lock.
   60795   */
   60796   assert( WRITE_LOCK>READ_LOCK );
   60797   if( eLock>pLock->eLock ){
   60798     pLock->eLock = eLock;
   60799   }
   60800 
   60801   return SQLITE_OK;
   60802 }
   60803 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   60804 
   60805 #ifndef SQLITE_OMIT_SHARED_CACHE
   60806 /*
   60807 ** Release all the table locks (locks obtained via calls to
   60808 ** the setSharedCacheTableLock() procedure) held by Btree object p.
   60809 **
   60810 ** This function assumes that Btree p has an open read or write
   60811 ** transaction. If it does not, then the BTS_PENDING flag
   60812 ** may be incorrectly cleared.
   60813 */
   60814 static void clearAllSharedCacheTableLocks(Btree *p){
   60815   BtShared *pBt = p->pBt;
   60816   BtLock **ppIter = &pBt->pLock;
   60817 
   60818   assert( sqlite3BtreeHoldsMutex(p) );
   60819   assert( p->sharable || 0==*ppIter );
   60820   assert( p->inTrans>0 );
   60821 
   60822   while( *ppIter ){
   60823     BtLock *pLock = *ppIter;
   60824     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
   60825     assert( pLock->pBtree->inTrans>=pLock->eLock );
   60826     if( pLock->pBtree==p ){
   60827       *ppIter = pLock->pNext;
   60828       assert( pLock->iTable!=1 || pLock==&p->lock );
   60829       if( pLock->iTable!=1 ){
   60830         sqlite3_free(pLock);
   60831       }
   60832     }else{
   60833       ppIter = &pLock->pNext;
   60834     }
   60835   }
   60836 
   60837   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
   60838   if( pBt->pWriter==p ){
   60839     pBt->pWriter = 0;
   60840     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   60841   }else if( pBt->nTransaction==2 ){
   60842     /* This function is called when Btree p is concluding its
   60843     ** transaction. If there currently exists a writer, and p is not
   60844     ** that writer, then the number of locks held by connections other
   60845     ** than the writer must be about to drop to zero. In this case
   60846     ** set the BTS_PENDING flag to 0.
   60847     **
   60848     ** If there is not currently a writer, then BTS_PENDING must
   60849     ** be zero already. So this next line is harmless in that case.
   60850     */
   60851     pBt->btsFlags &= ~BTS_PENDING;
   60852   }
   60853 }
   60854 
   60855 /*
   60856 ** This function changes all write-locks held by Btree p into read-locks.
   60857 */
   60858 static void downgradeAllSharedCacheTableLocks(Btree *p){
   60859   BtShared *pBt = p->pBt;
   60860   if( pBt->pWriter==p ){
   60861     BtLock *pLock;
   60862     pBt->pWriter = 0;
   60863     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   60864     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
   60865       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
   60866       pLock->eLock = READ_LOCK;
   60867     }
   60868   }
   60869 }
   60870 
   60871 #endif /* SQLITE_OMIT_SHARED_CACHE */
   60872 
   60873 static void releasePage(MemPage *pPage);         /* Forward reference */
   60874 static void releasePageOne(MemPage *pPage);      /* Forward reference */
   60875 static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
   60876 
   60877 /*
   60878 ***** This routine is used inside of assert() only ****
   60879 **
   60880 ** Verify that the cursor holds the mutex on its BtShared
   60881 */
   60882 #ifdef SQLITE_DEBUG
   60883 static int cursorHoldsMutex(BtCursor *p){
   60884   return sqlite3_mutex_held(p->pBt->mutex);
   60885 }
   60886 
   60887 /* Verify that the cursor and the BtShared agree about what is the current
   60888 ** database connetion. This is important in shared-cache mode. If the database
   60889 ** connection pointers get out-of-sync, it is possible for routines like
   60890 ** btreeInitPage() to reference an stale connection pointer that references a
   60891 ** a connection that has already closed.  This routine is used inside assert()
   60892 ** statements only and for the purpose of double-checking that the btree code
   60893 ** does keep the database connection pointers up-to-date.
   60894 */
   60895 static int cursorOwnsBtShared(BtCursor *p){
   60896   assert( cursorHoldsMutex(p) );
   60897   return (p->pBtree->db==p->pBt->db);
   60898 }
   60899 #endif
   60900 
   60901 /*
   60902 ** Invalidate the overflow cache of the cursor passed as the first argument.
   60903 ** on the shared btree structure pBt.
   60904 */
   60905 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
   60906 
   60907 /*
   60908 ** Invalidate the overflow page-list cache for all cursors opened
   60909 ** on the shared btree structure pBt.
   60910 */
   60911 static void invalidateAllOverflowCache(BtShared *pBt){
   60912   BtCursor *p;
   60913   assert( sqlite3_mutex_held(pBt->mutex) );
   60914   for(p=pBt->pCursor; p; p=p->pNext){
   60915     invalidateOverflowCache(p);
   60916   }
   60917 }
   60918 
   60919 #ifndef SQLITE_OMIT_INCRBLOB
   60920 /*
   60921 ** This function is called before modifying the contents of a table
   60922 ** to invalidate any incrblob cursors that are open on the
   60923 ** row or one of the rows being modified.
   60924 **
   60925 ** If argument isClearTable is true, then the entire contents of the
   60926 ** table is about to be deleted. In this case invalidate all incrblob
   60927 ** cursors open on any row within the table with root-page pgnoRoot.
   60928 **
   60929 ** Otherwise, if argument isClearTable is false, then the row with
   60930 ** rowid iRow is being replaced or deleted. In this case invalidate
   60931 ** only those incrblob cursors open on that specific row.
   60932 */
   60933 static void invalidateIncrblobCursors(
   60934   Btree *pBtree,          /* The database file to check */
   60935   Pgno pgnoRoot,          /* The table that might be changing */
   60936   i64 iRow,               /* The rowid that might be changing */
   60937   int isClearTable        /* True if all rows are being deleted */
   60938 ){
   60939   BtCursor *p;
   60940   if( pBtree->hasIncrblobCur==0 ) return;
   60941   assert( sqlite3BtreeHoldsMutex(pBtree) );
   60942   pBtree->hasIncrblobCur = 0;
   60943   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   60944     if( (p->curFlags & BTCF_Incrblob)!=0 ){
   60945       pBtree->hasIncrblobCur = 1;
   60946       if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
   60947         p->eState = CURSOR_INVALID;
   60948       }
   60949     }
   60950   }
   60951 }
   60952 
   60953 #else
   60954   /* Stub function when INCRBLOB is omitted */
   60955   #define invalidateIncrblobCursors(w,x,y,z)
   60956 #endif /* SQLITE_OMIT_INCRBLOB */
   60957 
   60958 /*
   60959 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
   60960 ** when a page that previously contained data becomes a free-list leaf
   60961 ** page.
   60962 **
   60963 ** The BtShared.pHasContent bitvec exists to work around an obscure
   60964 ** bug caused by the interaction of two useful IO optimizations surrounding
   60965 ** free-list leaf pages:
   60966 **
   60967 **   1) When all data is deleted from a page and the page becomes
   60968 **      a free-list leaf page, the page is not written to the database
   60969 **      (as free-list leaf pages contain no meaningful data). Sometimes
   60970 **      such a page is not even journalled (as it will not be modified,
   60971 **      why bother journalling it?).
   60972 **
   60973 **   2) When a free-list leaf page is reused, its content is not read
   60974 **      from the database or written to the journal file (why should it
   60975 **      be, if it is not at all meaningful?).
   60976 **
   60977 ** By themselves, these optimizations work fine and provide a handy
   60978 ** performance boost to bulk delete or insert operations. However, if
   60979 ** a page is moved to the free-list and then reused within the same
   60980 ** transaction, a problem comes up. If the page is not journalled when
   60981 ** it is moved to the free-list and it is also not journalled when it
   60982 ** is extracted from the free-list and reused, then the original data
   60983 ** may be lost. In the event of a rollback, it may not be possible
   60984 ** to restore the database to its original configuration.
   60985 **
   60986 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
   60987 ** moved to become a free-list leaf page, the corresponding bit is
   60988 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
   60989 ** optimization 2 above is omitted if the corresponding bit is already
   60990 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
   60991 ** at the end of every transaction.
   60992 */
   60993 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
   60994   int rc = SQLITE_OK;
   60995   if( !pBt->pHasContent ){
   60996     assert( pgno<=pBt->nPage );
   60997     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
   60998     if( !pBt->pHasContent ){
   60999       rc = SQLITE_NOMEM_BKPT;
   61000     }
   61001   }
   61002   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
   61003     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
   61004   }
   61005   return rc;
   61006 }
   61007 
   61008 /*
   61009 ** Query the BtShared.pHasContent vector.
   61010 **
   61011 ** This function is called when a free-list leaf page is removed from the
   61012 ** free-list for reuse. It returns false if it is safe to retrieve the
   61013 ** page from the pager layer with the 'no-content' flag set. True otherwise.
   61014 */
   61015 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   61016   Bitvec *p = pBt->pHasContent;
   61017   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
   61018 }
   61019 
   61020 /*
   61021 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
   61022 ** invoked at the conclusion of each write-transaction.
   61023 */
   61024 static void btreeClearHasContent(BtShared *pBt){
   61025   sqlite3BitvecDestroy(pBt->pHasContent);
   61026   pBt->pHasContent = 0;
   61027 }
   61028 
   61029 /*
   61030 ** Release all of the apPage[] pages for a cursor.
   61031 */
   61032 static void btreeReleaseAllCursorPages(BtCursor *pCur){
   61033   int i;
   61034   if( pCur->iPage>=0 ){
   61035     for(i=0; i<pCur->iPage; i++){
   61036       releasePageNotNull(pCur->apPage[i]);
   61037     }
   61038     releasePageNotNull(pCur->pPage);
   61039     pCur->iPage = -1;
   61040   }
   61041 }
   61042 
   61043 /*
   61044 ** The cursor passed as the only argument must point to a valid entry
   61045 ** when this function is called (i.e. have eState==CURSOR_VALID). This
   61046 ** function saves the current cursor key in variables pCur->nKey and
   61047 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
   61048 ** code otherwise.
   61049 **
   61050 ** If the cursor is open on an intkey table, then the integer key
   61051 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
   61052 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
   61053 ** set to point to a malloced buffer pCur->nKey bytes in size containing
   61054 ** the key.
   61055 */
   61056 static int saveCursorKey(BtCursor *pCur){
   61057   int rc = SQLITE_OK;
   61058   assert( CURSOR_VALID==pCur->eState );
   61059   assert( 0==pCur->pKey );
   61060   assert( cursorHoldsMutex(pCur) );
   61061 
   61062   if( pCur->curIntKey ){
   61063     /* Only the rowid is required for a table btree */
   61064     pCur->nKey = sqlite3BtreeIntegerKey(pCur);
   61065   }else{
   61066     /* For an index btree, save the complete key content */
   61067     void *pKey;
   61068     pCur->nKey = sqlite3BtreePayloadSize(pCur);
   61069     pKey = sqlite3Malloc( pCur->nKey );
   61070     if( pKey ){
   61071       rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
   61072       if( rc==SQLITE_OK ){
   61073         pCur->pKey = pKey;
   61074       }else{
   61075         sqlite3_free(pKey);
   61076       }
   61077     }else{
   61078       rc = SQLITE_NOMEM_BKPT;
   61079     }
   61080   }
   61081   assert( !pCur->curIntKey || !pCur->pKey );
   61082   return rc;
   61083 }
   61084 
   61085 /*
   61086 ** Save the current cursor position in the variables BtCursor.nKey
   61087 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
   61088 **
   61089 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
   61090 ** prior to calling this routine.
   61091 */
   61092 static int saveCursorPosition(BtCursor *pCur){
   61093   int rc;
   61094 
   61095   assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
   61096   assert( 0==pCur->pKey );
   61097   assert( cursorHoldsMutex(pCur) );
   61098 
   61099   if( pCur->eState==CURSOR_SKIPNEXT ){
   61100     pCur->eState = CURSOR_VALID;
   61101   }else{
   61102     pCur->skipNext = 0;
   61103   }
   61104 
   61105   rc = saveCursorKey(pCur);
   61106   if( rc==SQLITE_OK ){
   61107     btreeReleaseAllCursorPages(pCur);
   61108     pCur->eState = CURSOR_REQUIRESEEK;
   61109   }
   61110 
   61111   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
   61112   return rc;
   61113 }
   61114 
   61115 /* Forward reference */
   61116 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
   61117 
   61118 /*
   61119 ** Save the positions of all cursors (except pExcept) that are open on
   61120 ** the table with root-page iRoot.  "Saving the cursor position" means that
   61121 ** the location in the btree is remembered in such a way that it can be
   61122 ** moved back to the same spot after the btree has been modified.  This
   61123 ** routine is called just before cursor pExcept is used to modify the
   61124 ** table, for example in BtreeDelete() or BtreeInsert().
   61125 **
   61126 ** If there are two or more cursors on the same btree, then all such
   61127 ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
   61128 ** routine enforces that rule.  This routine only needs to be called in
   61129 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
   61130 **
   61131 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
   61132 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
   61133 ** pointless call to this routine.
   61134 **
   61135 ** Implementation note:  This routine merely checks to see if any cursors
   61136 ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
   61137 ** event that cursors are in need to being saved.
   61138 */
   61139 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
   61140   BtCursor *p;
   61141   assert( sqlite3_mutex_held(pBt->mutex) );
   61142   assert( pExcept==0 || pExcept->pBt==pBt );
   61143   for(p=pBt->pCursor; p; p=p->pNext){
   61144     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
   61145   }
   61146   if( p ) return saveCursorsOnList(p, iRoot, pExcept);
   61147   if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
   61148   return SQLITE_OK;
   61149 }
   61150 
   61151 /* This helper routine to saveAllCursors does the actual work of saving
   61152 ** the cursors if and when a cursor is found that actually requires saving.
   61153 ** The common case is that no cursors need to be saved, so this routine is
   61154 ** broken out from its caller to avoid unnecessary stack pointer movement.
   61155 */
   61156 static int SQLITE_NOINLINE saveCursorsOnList(
   61157   BtCursor *p,         /* The first cursor that needs saving */
   61158   Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
   61159   BtCursor *pExcept    /* Do not save this cursor */
   61160 ){
   61161   do{
   61162     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
   61163       if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
   61164         int rc = saveCursorPosition(p);
   61165         if( SQLITE_OK!=rc ){
   61166           return rc;
   61167         }
   61168       }else{
   61169         testcase( p->iPage>=0 );
   61170         btreeReleaseAllCursorPages(p);
   61171       }
   61172     }
   61173     p = p->pNext;
   61174   }while( p );
   61175   return SQLITE_OK;
   61176 }
   61177 
   61178 /*
   61179 ** Clear the current cursor position.
   61180 */
   61181 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
   61182   assert( cursorHoldsMutex(pCur) );
   61183   sqlite3_free(pCur->pKey);
   61184   pCur->pKey = 0;
   61185   pCur->eState = CURSOR_INVALID;
   61186 }
   61187 
   61188 /*
   61189 ** In this version of BtreeMoveto, pKey is a packed index record
   61190 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
   61191 ** record and then call BtreeMovetoUnpacked() to do the work.
   61192 */
   61193 static int btreeMoveto(
   61194   BtCursor *pCur,     /* Cursor open on the btree to be searched */
   61195   const void *pKey,   /* Packed key if the btree is an index */
   61196   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
   61197   int bias,           /* Bias search to the high end */
   61198   int *pRes           /* Write search results here */
   61199 ){
   61200   int rc;                    /* Status code */
   61201   UnpackedRecord *pIdxKey;   /* Unpacked index key */
   61202 
   61203   if( pKey ){
   61204     assert( nKey==(i64)(int)nKey );
   61205     pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
   61206     if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
   61207     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
   61208     if( pIdxKey->nField==0 ){
   61209       rc = SQLITE_CORRUPT_BKPT;
   61210       goto moveto_done;
   61211     }
   61212   }else{
   61213     pIdxKey = 0;
   61214   }
   61215   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
   61216 moveto_done:
   61217   if( pIdxKey ){
   61218     sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
   61219   }
   61220   return rc;
   61221 }
   61222 
   61223 /*
   61224 ** Restore the cursor to the position it was in (or as close to as possible)
   61225 ** when saveCursorPosition() was called. Note that this call deletes the
   61226 ** saved position info stored by saveCursorPosition(), so there can be
   61227 ** at most one effective restoreCursorPosition() call after each
   61228 ** saveCursorPosition().
   61229 */
   61230 static int btreeRestoreCursorPosition(BtCursor *pCur){
   61231   int rc;
   61232   int skipNext;
   61233   assert( cursorOwnsBtShared(pCur) );
   61234   assert( pCur->eState>=CURSOR_REQUIRESEEK );
   61235   if( pCur->eState==CURSOR_FAULT ){
   61236     return pCur->skipNext;
   61237   }
   61238   pCur->eState = CURSOR_INVALID;
   61239   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
   61240   if( rc==SQLITE_OK ){
   61241     sqlite3_free(pCur->pKey);
   61242     pCur->pKey = 0;
   61243     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
   61244     pCur->skipNext |= skipNext;
   61245     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
   61246       pCur->eState = CURSOR_SKIPNEXT;
   61247     }
   61248   }
   61249   return rc;
   61250 }
   61251 
   61252 #define restoreCursorPosition(p) \
   61253   (p->eState>=CURSOR_REQUIRESEEK ? \
   61254          btreeRestoreCursorPosition(p) : \
   61255          SQLITE_OK)
   61256 
   61257 /*
   61258 ** Determine whether or not a cursor has moved from the position where
   61259 ** it was last placed, or has been invalidated for any other reason.
   61260 ** Cursors can move when the row they are pointing at is deleted out
   61261 ** from under them, for example.  Cursor might also move if a btree
   61262 ** is rebalanced.
   61263 **
   61264 ** Calling this routine with a NULL cursor pointer returns false.
   61265 **
   61266 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
   61267 ** back to where it ought to be if this routine returns true.
   61268 */
   61269 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
   61270   return pCur->eState!=CURSOR_VALID;
   61271 }
   61272 
   61273 /*
   61274 ** Return a pointer to a fake BtCursor object that will always answer
   61275 ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
   61276 ** cursor returned must not be used with any other Btree interface.
   61277 */
   61278 SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
   61279   static u8 fakeCursor = CURSOR_VALID;
   61280   assert( offsetof(BtCursor, eState)==0 );
   61281   return (BtCursor*)&fakeCursor;
   61282 }
   61283 
   61284 /*
   61285 ** This routine restores a cursor back to its original position after it
   61286 ** has been moved by some outside activity (such as a btree rebalance or
   61287 ** a row having been deleted out from under the cursor).
   61288 **
   61289 ** On success, the *pDifferentRow parameter is false if the cursor is left
   61290 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
   61291 ** was pointing to has been deleted, forcing the cursor to point to some
   61292 ** nearby row.
   61293 **
   61294 ** This routine should only be called for a cursor that just returned
   61295 ** TRUE from sqlite3BtreeCursorHasMoved().
   61296 */
   61297 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
   61298   int rc;
   61299 
   61300   assert( pCur!=0 );
   61301   assert( pCur->eState!=CURSOR_VALID );
   61302   rc = restoreCursorPosition(pCur);
   61303   if( rc ){
   61304     *pDifferentRow = 1;
   61305     return rc;
   61306   }
   61307   if( pCur->eState!=CURSOR_VALID ){
   61308     *pDifferentRow = 1;
   61309   }else{
   61310     assert( pCur->skipNext==0 );
   61311     *pDifferentRow = 0;
   61312   }
   61313   return SQLITE_OK;
   61314 }
   61315 
   61316 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   61317 /*
   61318 ** Provide hints to the cursor.  The particular hint given (and the type
   61319 ** and number of the varargs parameters) is determined by the eHintType
   61320 ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
   61321 */
   61322 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
   61323   /* Used only by system that substitute their own storage engine */
   61324 }
   61325 #endif
   61326 
   61327 /*
   61328 ** Provide flag hints to the cursor.
   61329 */
   61330 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
   61331   assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
   61332   pCur->hints = x;
   61333 }
   61334 
   61335 
   61336 #ifndef SQLITE_OMIT_AUTOVACUUM
   61337 /*
   61338 ** Given a page number of a regular database page, return the page
   61339 ** number for the pointer-map page that contains the entry for the
   61340 ** input page number.
   61341 **
   61342 ** Return 0 (not a valid page) for pgno==1 since there is
   61343 ** no pointer map associated with page 1.  The integrity_check logic
   61344 ** requires that ptrmapPageno(*,1)!=1.
   61345 */
   61346 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   61347   int nPagesPerMapPage;
   61348   Pgno iPtrMap, ret;
   61349   assert( sqlite3_mutex_held(pBt->mutex) );
   61350   if( pgno<2 ) return 0;
   61351   nPagesPerMapPage = (pBt->usableSize/5)+1;
   61352   iPtrMap = (pgno-2)/nPagesPerMapPage;
   61353   ret = (iPtrMap*nPagesPerMapPage) + 2;
   61354   if( ret==PENDING_BYTE_PAGE(pBt) ){
   61355     ret++;
   61356   }
   61357   return ret;
   61358 }
   61359 
   61360 /*
   61361 ** Write an entry into the pointer map.
   61362 **
   61363 ** This routine updates the pointer map entry for page number 'key'
   61364 ** so that it maps to type 'eType' and parent page number 'pgno'.
   61365 **
   61366 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
   61367 ** a no-op.  If an error occurs, the appropriate error code is written
   61368 ** into *pRC.
   61369 */
   61370 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   61371   DbPage *pDbPage;  /* The pointer map page */
   61372   u8 *pPtrmap;      /* The pointer map data */
   61373   Pgno iPtrmap;     /* The pointer map page number */
   61374   int offset;       /* Offset in pointer map page */
   61375   int rc;           /* Return code from subfunctions */
   61376 
   61377   if( *pRC ) return;
   61378 
   61379   assert( sqlite3_mutex_held(pBt->mutex) );
   61380   /* The master-journal page number must never be used as a pointer map page */
   61381   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
   61382 
   61383   assert( pBt->autoVacuum );
   61384   if( key==0 ){
   61385     *pRC = SQLITE_CORRUPT_BKPT;
   61386     return;
   61387   }
   61388   iPtrmap = PTRMAP_PAGENO(pBt, key);
   61389   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
   61390   if( rc!=SQLITE_OK ){
   61391     *pRC = rc;
   61392     return;
   61393   }
   61394   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   61395   if( offset<0 ){
   61396     *pRC = SQLITE_CORRUPT_BKPT;
   61397     goto ptrmap_exit;
   61398   }
   61399   assert( offset <= (int)pBt->usableSize-5 );
   61400   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   61401 
   61402   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
   61403     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
   61404     *pRC= rc = sqlite3PagerWrite(pDbPage);
   61405     if( rc==SQLITE_OK ){
   61406       pPtrmap[offset] = eType;
   61407       put4byte(&pPtrmap[offset+1], parent);
   61408     }
   61409   }
   61410 
   61411 ptrmap_exit:
   61412   sqlite3PagerUnref(pDbPage);
   61413 }
   61414 
   61415 /*
   61416 ** Read an entry from the pointer map.
   61417 **
   61418 ** This routine retrieves the pointer map entry for page 'key', writing
   61419 ** the type and parent page number to *pEType and *pPgno respectively.
   61420 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   61421 */
   61422 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   61423   DbPage *pDbPage;   /* The pointer map page */
   61424   int iPtrmap;       /* Pointer map page index */
   61425   u8 *pPtrmap;       /* Pointer map page data */
   61426   int offset;        /* Offset of entry in pointer map */
   61427   int rc;
   61428 
   61429   assert( sqlite3_mutex_held(pBt->mutex) );
   61430 
   61431   iPtrmap = PTRMAP_PAGENO(pBt, key);
   61432   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
   61433   if( rc!=0 ){
   61434     return rc;
   61435   }
   61436   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   61437 
   61438   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   61439   if( offset<0 ){
   61440     sqlite3PagerUnref(pDbPage);
   61441     return SQLITE_CORRUPT_BKPT;
   61442   }
   61443   assert( offset <= (int)pBt->usableSize-5 );
   61444   assert( pEType!=0 );
   61445   *pEType = pPtrmap[offset];
   61446   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
   61447 
   61448   sqlite3PagerUnref(pDbPage);
   61449   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
   61450   return SQLITE_OK;
   61451 }
   61452 
   61453 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
   61454   #define ptrmapPut(w,x,y,z,rc)
   61455   #define ptrmapGet(w,x,y,z) SQLITE_OK
   61456   #define ptrmapPutOvflPtr(x, y, rc)
   61457 #endif
   61458 
   61459 /*
   61460 ** Given a btree page and a cell index (0 means the first cell on
   61461 ** the page, 1 means the second cell, and so forth) return a pointer
   61462 ** to the cell content.
   61463 **
   61464 ** findCellPastPtr() does the same except it skips past the initial
   61465 ** 4-byte child pointer found on interior pages, if there is one.
   61466 **
   61467 ** This routine works only for pages that do not contain overflow cells.
   61468 */
   61469 #define findCell(P,I) \
   61470   ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
   61471 #define findCellPastPtr(P,I) \
   61472   ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
   61473 
   61474 
   61475 /*
   61476 ** This is common tail processing for btreeParseCellPtr() and
   61477 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
   61478 ** on a single B-tree page.  Make necessary adjustments to the CellInfo
   61479 ** structure.
   61480 */
   61481 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
   61482   MemPage *pPage,         /* Page containing the cell */
   61483   u8 *pCell,              /* Pointer to the cell text. */
   61484   CellInfo *pInfo         /* Fill in this structure */
   61485 ){
   61486   /* If the payload will not fit completely on the local page, we have
   61487   ** to decide how much to store locally and how much to spill onto
   61488   ** overflow pages.  The strategy is to minimize the amount of unused
   61489   ** space on overflow pages while keeping the amount of local storage
   61490   ** in between minLocal and maxLocal.
   61491   **
   61492   ** Warning:  changing the way overflow payload is distributed in any
   61493   ** way will result in an incompatible file format.
   61494   */
   61495   int minLocal;  /* Minimum amount of payload held locally */
   61496   int maxLocal;  /* Maximum amount of payload held locally */
   61497   int surplus;   /* Overflow payload available for local storage */
   61498 
   61499   minLocal = pPage->minLocal;
   61500   maxLocal = pPage->maxLocal;
   61501   surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
   61502   testcase( surplus==maxLocal );
   61503   testcase( surplus==maxLocal+1 );
   61504   if( surplus <= maxLocal ){
   61505     pInfo->nLocal = (u16)surplus;
   61506   }else{
   61507     pInfo->nLocal = (u16)minLocal;
   61508   }
   61509   pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
   61510 }
   61511 
   61512 /*
   61513 ** The following routines are implementations of the MemPage.xParseCell()
   61514 ** method.
   61515 **
   61516 ** Parse a cell content block and fill in the CellInfo structure.
   61517 **
   61518 ** btreeParseCellPtr()        =>   table btree leaf nodes
   61519 ** btreeParseCellNoPayload()  =>   table btree internal nodes
   61520 ** btreeParseCellPtrIndex()   =>   index btree nodes
   61521 **
   61522 ** There is also a wrapper function btreeParseCell() that works for
   61523 ** all MemPage types and that references the cell by index rather than
   61524 ** by pointer.
   61525 */
   61526 static void btreeParseCellPtrNoPayload(
   61527   MemPage *pPage,         /* Page containing the cell */
   61528   u8 *pCell,              /* Pointer to the cell text. */
   61529   CellInfo *pInfo         /* Fill in this structure */
   61530 ){
   61531   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   61532   assert( pPage->leaf==0 );
   61533   assert( pPage->childPtrSize==4 );
   61534 #ifndef SQLITE_DEBUG
   61535   UNUSED_PARAMETER(pPage);
   61536 #endif
   61537   pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
   61538   pInfo->nPayload = 0;
   61539   pInfo->nLocal = 0;
   61540   pInfo->pPayload = 0;
   61541   return;
   61542 }
   61543 static void btreeParseCellPtr(
   61544   MemPage *pPage,         /* Page containing the cell */
   61545   u8 *pCell,              /* Pointer to the cell text. */
   61546   CellInfo *pInfo         /* Fill in this structure */
   61547 ){
   61548   u8 *pIter;              /* For scanning through pCell */
   61549   u32 nPayload;           /* Number of bytes of cell payload */
   61550   u64 iKey;               /* Extracted Key value */
   61551 
   61552   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   61553   assert( pPage->leaf==0 || pPage->leaf==1 );
   61554   assert( pPage->intKeyLeaf );
   61555   assert( pPage->childPtrSize==0 );
   61556   pIter = pCell;
   61557 
   61558   /* The next block of code is equivalent to:
   61559   **
   61560   **     pIter += getVarint32(pIter, nPayload);
   61561   **
   61562   ** The code is inlined to avoid a function call.
   61563   */
   61564   nPayload = *pIter;
   61565   if( nPayload>=0x80 ){
   61566     u8 *pEnd = &pIter[8];
   61567     nPayload &= 0x7f;
   61568     do{
   61569       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
   61570     }while( (*pIter)>=0x80 && pIter<pEnd );
   61571   }
   61572   pIter++;
   61573 
   61574   /* The next block of code is equivalent to:
   61575   **
   61576   **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
   61577   **
   61578   ** The code is inlined to avoid a function call.
   61579   */
   61580   iKey = *pIter;
   61581   if( iKey>=0x80 ){
   61582     u8 *pEnd = &pIter[7];
   61583     iKey &= 0x7f;
   61584     while(1){
   61585       iKey = (iKey<<7) | (*++pIter & 0x7f);
   61586       if( (*pIter)<0x80 ) break;
   61587       if( pIter>=pEnd ){
   61588         iKey = (iKey<<8) | *++pIter;
   61589         break;
   61590       }
   61591     }
   61592   }
   61593   pIter++;
   61594 
   61595   pInfo->nKey = *(i64*)&iKey;
   61596   pInfo->nPayload = nPayload;
   61597   pInfo->pPayload = pIter;
   61598   testcase( nPayload==pPage->maxLocal );
   61599   testcase( nPayload==pPage->maxLocal+1 );
   61600   if( nPayload<=pPage->maxLocal ){
   61601     /* This is the (easy) common case where the entire payload fits
   61602     ** on the local page.  No overflow is required.
   61603     */
   61604     pInfo->nSize = nPayload + (u16)(pIter - pCell);
   61605     if( pInfo->nSize<4 ) pInfo->nSize = 4;
   61606     pInfo->nLocal = (u16)nPayload;
   61607   }else{
   61608     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
   61609   }
   61610 }
   61611 static void btreeParseCellPtrIndex(
   61612   MemPage *pPage,         /* Page containing the cell */
   61613   u8 *pCell,              /* Pointer to the cell text. */
   61614   CellInfo *pInfo         /* Fill in this structure */
   61615 ){
   61616   u8 *pIter;              /* For scanning through pCell */
   61617   u32 nPayload;           /* Number of bytes of cell payload */
   61618 
   61619   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   61620   assert( pPage->leaf==0 || pPage->leaf==1 );
   61621   assert( pPage->intKeyLeaf==0 );
   61622   pIter = pCell + pPage->childPtrSize;
   61623   nPayload = *pIter;
   61624   if( nPayload>=0x80 ){
   61625     u8 *pEnd = &pIter[8];
   61626     nPayload &= 0x7f;
   61627     do{
   61628       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
   61629     }while( *(pIter)>=0x80 && pIter<pEnd );
   61630   }
   61631   pIter++;
   61632   pInfo->nKey = nPayload;
   61633   pInfo->nPayload = nPayload;
   61634   pInfo->pPayload = pIter;
   61635   testcase( nPayload==pPage->maxLocal );
   61636   testcase( nPayload==pPage->maxLocal+1 );
   61637   if( nPayload<=pPage->maxLocal ){
   61638     /* This is the (easy) common case where the entire payload fits
   61639     ** on the local page.  No overflow is required.
   61640     */
   61641     pInfo->nSize = nPayload + (u16)(pIter - pCell);
   61642     if( pInfo->nSize<4 ) pInfo->nSize = 4;
   61643     pInfo->nLocal = (u16)nPayload;
   61644   }else{
   61645     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
   61646   }
   61647 }
   61648 static void btreeParseCell(
   61649   MemPage *pPage,         /* Page containing the cell */
   61650   int iCell,              /* The cell index.  First cell is 0 */
   61651   CellInfo *pInfo         /* Fill in this structure */
   61652 ){
   61653   pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
   61654 }
   61655 
   61656 /*
   61657 ** The following routines are implementations of the MemPage.xCellSize
   61658 ** method.
   61659 **
   61660 ** Compute the total number of bytes that a Cell needs in the cell
   61661 ** data area of the btree-page.  The return number includes the cell
   61662 ** data header and the local payload, but not any overflow page or
   61663 ** the space used by the cell pointer.
   61664 **
   61665 ** cellSizePtrNoPayload()    =>   table internal nodes
   61666 ** cellSizePtr()             =>   all index nodes & table leaf nodes
   61667 */
   61668 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   61669   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
   61670   u8 *pEnd;                                /* End mark for a varint */
   61671   u32 nSize;                               /* Size value to return */
   61672 
   61673 #ifdef SQLITE_DEBUG
   61674   /* The value returned by this function should always be the same as
   61675   ** the (CellInfo.nSize) value found by doing a full parse of the
   61676   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   61677   ** this function verifies that this invariant is not violated. */
   61678   CellInfo debuginfo;
   61679   pPage->xParseCell(pPage, pCell, &debuginfo);
   61680 #endif
   61681 
   61682   nSize = *pIter;
   61683   if( nSize>=0x80 ){
   61684     pEnd = &pIter[8];
   61685     nSize &= 0x7f;
   61686     do{
   61687       nSize = (nSize<<7) | (*++pIter & 0x7f);
   61688     }while( *(pIter)>=0x80 && pIter<pEnd );
   61689   }
   61690   pIter++;
   61691   if( pPage->intKey ){
   61692     /* pIter now points at the 64-bit integer key value, a variable length
   61693     ** integer. The following block moves pIter to point at the first byte
   61694     ** past the end of the key value. */
   61695     pEnd = &pIter[9];
   61696     while( (*pIter++)&0x80 && pIter<pEnd );
   61697   }
   61698   testcase( nSize==pPage->maxLocal );
   61699   testcase( nSize==pPage->maxLocal+1 );
   61700   if( nSize<=pPage->maxLocal ){
   61701     nSize += (u32)(pIter - pCell);
   61702     if( nSize<4 ) nSize = 4;
   61703   }else{
   61704     int minLocal = pPage->minLocal;
   61705     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
   61706     testcase( nSize==pPage->maxLocal );
   61707     testcase( nSize==pPage->maxLocal+1 );
   61708     if( nSize>pPage->maxLocal ){
   61709       nSize = minLocal;
   61710     }
   61711     nSize += 4 + (u16)(pIter - pCell);
   61712   }
   61713   assert( nSize==debuginfo.nSize || CORRUPT_DB );
   61714   return (u16)nSize;
   61715 }
   61716 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
   61717   u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
   61718   u8 *pEnd;              /* End mark for a varint */
   61719 
   61720 #ifdef SQLITE_DEBUG
   61721   /* The value returned by this function should always be the same as
   61722   ** the (CellInfo.nSize) value found by doing a full parse of the
   61723   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   61724   ** this function verifies that this invariant is not violated. */
   61725   CellInfo debuginfo;
   61726   pPage->xParseCell(pPage, pCell, &debuginfo);
   61727 #else
   61728   UNUSED_PARAMETER(pPage);
   61729 #endif
   61730 
   61731   assert( pPage->childPtrSize==4 );
   61732   pEnd = pIter + 9;
   61733   while( (*pIter++)&0x80 && pIter<pEnd );
   61734   assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
   61735   return (u16)(pIter - pCell);
   61736 }
   61737 
   61738 
   61739 #ifdef SQLITE_DEBUG
   61740 /* This variation on cellSizePtr() is used inside of assert() statements
   61741 ** only. */
   61742 static u16 cellSize(MemPage *pPage, int iCell){
   61743   return pPage->xCellSize(pPage, findCell(pPage, iCell));
   61744 }
   61745 #endif
   61746 
   61747 #ifndef SQLITE_OMIT_AUTOVACUUM
   61748 /*
   61749 ** If the cell pCell, part of page pPage contains a pointer
   61750 ** to an overflow page, insert an entry into the pointer-map
   61751 ** for the overflow page.
   61752 */
   61753 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
   61754   CellInfo info;
   61755   if( *pRC ) return;
   61756   assert( pCell!=0 );
   61757   pPage->xParseCell(pPage, pCell, &info);
   61758   if( info.nLocal<info.nPayload ){
   61759     Pgno ovfl = get4byte(&pCell[info.nSize-4]);
   61760     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
   61761   }
   61762 }
   61763 #endif
   61764 
   61765 
   61766 /*
   61767 ** Defragment the page given. This routine reorganizes cells within the
   61768 ** page so that there are no free-blocks on the free-block list.
   61769 **
   61770 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
   61771 ** present in the page after this routine returns.
   61772 **
   61773 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
   61774 ** b-tree page so that there are no freeblocks or fragment bytes, all
   61775 ** unused bytes are contained in the unallocated space region, and all
   61776 ** cells are packed tightly at the end of the page.
   61777 */
   61778 static int defragmentPage(MemPage *pPage, int nMaxFrag){
   61779   int i;                     /* Loop counter */
   61780   int pc;                    /* Address of the i-th cell */
   61781   int hdr;                   /* Offset to the page header */
   61782   int size;                  /* Size of a cell */
   61783   int usableSize;            /* Number of usable bytes on a page */
   61784   int cellOffset;            /* Offset to the cell pointer array */
   61785   int cbrk;                  /* Offset to the cell content area */
   61786   int nCell;                 /* Number of cells on the page */
   61787   unsigned char *data;       /* The page data */
   61788   unsigned char *temp;       /* Temp area for cell content */
   61789   unsigned char *src;        /* Source of content */
   61790   int iCellFirst;            /* First allowable cell index */
   61791   int iCellLast;             /* Last possible cell index */
   61792 
   61793   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   61794   assert( pPage->pBt!=0 );
   61795   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
   61796   assert( pPage->nOverflow==0 );
   61797   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   61798   temp = 0;
   61799   src = data = pPage->aData;
   61800   hdr = pPage->hdrOffset;
   61801   cellOffset = pPage->cellOffset;
   61802   nCell = pPage->nCell;
   61803   assert( nCell==get2byte(&data[hdr+3]) );
   61804   iCellFirst = cellOffset + 2*nCell;
   61805   usableSize = pPage->pBt->usableSize;
   61806 
   61807   /* This block handles pages with two or fewer free blocks and nMaxFrag
   61808   ** or fewer fragmented bytes. In this case it is faster to move the
   61809   ** two (or one) blocks of cells using memmove() and add the required
   61810   ** offsets to each pointer in the cell-pointer array than it is to
   61811   ** reconstruct the entire page.  */
   61812   if( (int)data[hdr+7]<=nMaxFrag ){
   61813     int iFree = get2byte(&data[hdr+1]);
   61814     if( iFree ){
   61815       int iFree2 = get2byte(&data[iFree]);
   61816 
   61817       /* pageFindSlot() has already verified that free blocks are sorted
   61818       ** in order of offset within the page, and that no block extends
   61819       ** past the end of the page. Provided the two free slots do not
   61820       ** overlap, this guarantees that the memmove() calls below will not
   61821       ** overwrite the usableSize byte buffer, even if the database page
   61822       ** is corrupt.  */
   61823       assert( iFree2==0 || iFree2>iFree );
   61824       assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
   61825       assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
   61826 
   61827       if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
   61828         u8 *pEnd = &data[cellOffset + nCell*2];
   61829         u8 *pAddr;
   61830         int sz2 = 0;
   61831         int sz = get2byte(&data[iFree+2]);
   61832         int top = get2byte(&data[hdr+5]);
   61833         if( top>=iFree ){
   61834           return SQLITE_CORRUPT_PAGE(pPage);
   61835         }
   61836         if( iFree2 ){
   61837           assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
   61838           sz2 = get2byte(&data[iFree2+2]);
   61839           assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
   61840           memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
   61841           sz += sz2;
   61842         }
   61843         cbrk = top+sz;
   61844         assert( cbrk+(iFree-top) <= usableSize );
   61845         memmove(&data[cbrk], &data[top], iFree-top);
   61846         for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
   61847           pc = get2byte(pAddr);
   61848           if( pc<iFree ){ put2byte(pAddr, pc+sz); }
   61849           else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
   61850         }
   61851         goto defragment_out;
   61852       }
   61853     }
   61854   }
   61855 
   61856   cbrk = usableSize;
   61857   iCellLast = usableSize - 4;
   61858   for(i=0; i<nCell; i++){
   61859     u8 *pAddr;     /* The i-th cell pointer */
   61860     pAddr = &data[cellOffset + i*2];
   61861     pc = get2byte(pAddr);
   61862     testcase( pc==iCellFirst );
   61863     testcase( pc==iCellLast );
   61864     /* These conditions have already been verified in btreeInitPage()
   61865     ** if PRAGMA cell_size_check=ON.
   61866     */
   61867     if( pc<iCellFirst || pc>iCellLast ){
   61868       return SQLITE_CORRUPT_PAGE(pPage);
   61869     }
   61870     assert( pc>=iCellFirst && pc<=iCellLast );
   61871     size = pPage->xCellSize(pPage, &src[pc]);
   61872     cbrk -= size;
   61873     if( cbrk<iCellFirst || pc+size>usableSize ){
   61874       return SQLITE_CORRUPT_PAGE(pPage);
   61875     }
   61876     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
   61877     testcase( cbrk+size==usableSize );
   61878     testcase( pc+size==usableSize );
   61879     put2byte(pAddr, cbrk);
   61880     if( temp==0 ){
   61881       int x;
   61882       if( cbrk==pc ) continue;
   61883       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
   61884       x = get2byte(&data[hdr+5]);
   61885       memcpy(&temp[x], &data[x], (cbrk+size) - x);
   61886       src = temp;
   61887     }
   61888     memcpy(&data[cbrk], &src[pc], size);
   61889   }
   61890   data[hdr+7] = 0;
   61891 
   61892  defragment_out:
   61893   if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
   61894     return SQLITE_CORRUPT_PAGE(pPage);
   61895   }
   61896   assert( cbrk>=iCellFirst );
   61897   put2byte(&data[hdr+5], cbrk);
   61898   data[hdr+1] = 0;
   61899   data[hdr+2] = 0;
   61900   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
   61901   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   61902   return SQLITE_OK;
   61903 }
   61904 
   61905 /*
   61906 ** Search the free-list on page pPg for space to store a cell nByte bytes in
   61907 ** size. If one can be found, return a pointer to the space and remove it
   61908 ** from the free-list.
   61909 **
   61910 ** If no suitable space can be found on the free-list, return NULL.
   61911 **
   61912 ** This function may detect corruption within pPg.  If corruption is
   61913 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
   61914 **
   61915 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
   61916 ** will be ignored if adding the extra space to the fragmentation count
   61917 ** causes the fragmentation count to exceed 60.
   61918 */
   61919 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
   61920   const int hdr = pPg->hdrOffset;
   61921   u8 * const aData = pPg->aData;
   61922   int iAddr = hdr + 1;
   61923   int pc = get2byte(&aData[iAddr]);
   61924   int x;
   61925   int usableSize = pPg->pBt->usableSize;
   61926   int size;            /* Size of the free slot */
   61927 
   61928   assert( pc>0 );
   61929   while( pc<=usableSize-4 ){
   61930     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
   61931     ** freeblock form a big-endian integer which is the size of the freeblock
   61932     ** in bytes, including the 4-byte header. */
   61933     size = get2byte(&aData[pc+2]);
   61934     if( (x = size - nByte)>=0 ){
   61935       testcase( x==4 );
   61936       testcase( x==3 );
   61937       if( size+pc > usableSize ){
   61938         *pRc = SQLITE_CORRUPT_PAGE(pPg);
   61939         return 0;
   61940       }else if( x<4 ){
   61941         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
   61942         ** number of bytes in fragments may not exceed 60. */
   61943         if( aData[hdr+7]>57 ) return 0;
   61944 
   61945         /* Remove the slot from the free-list. Update the number of
   61946         ** fragmented bytes within the page. */
   61947         memcpy(&aData[iAddr], &aData[pc], 2);
   61948         aData[hdr+7] += (u8)x;
   61949       }else{
   61950         /* The slot remains on the free-list. Reduce its size to account
   61951          ** for the portion used by the new allocation. */
   61952         put2byte(&aData[pc+2], x);
   61953       }
   61954       return &aData[pc + x];
   61955     }
   61956     iAddr = pc;
   61957     pc = get2byte(&aData[pc]);
   61958     if( pc<iAddr+size ) break;
   61959   }
   61960   if( pc ){
   61961     *pRc = SQLITE_CORRUPT_PAGE(pPg);
   61962   }
   61963 
   61964   return 0;
   61965 }
   61966 
   61967 /*
   61968 ** Allocate nByte bytes of space from within the B-Tree page passed
   61969 ** as the first argument. Write into *pIdx the index into pPage->aData[]
   61970 ** of the first byte of allocated space. Return either SQLITE_OK or
   61971 ** an error code (usually SQLITE_CORRUPT).
   61972 **
   61973 ** The caller guarantees that there is sufficient space to make the
   61974 ** allocation.  This routine might need to defragment in order to bring
   61975 ** all the space together, however.  This routine will avoid using
   61976 ** the first two bytes past the cell pointer area since presumably this
   61977 ** allocation is being made in order to insert a new cell, so we will
   61978 ** also end up needing a new cell pointer.
   61979 */
   61980 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   61981   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
   61982   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
   61983   int top;                             /* First byte of cell content area */
   61984   int rc = SQLITE_OK;                  /* Integer return code */
   61985   int gap;        /* First byte of gap between cell pointers and cell content */
   61986 
   61987   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   61988   assert( pPage->pBt );
   61989   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   61990   assert( nByte>=0 );  /* Minimum cell size is 4 */
   61991   assert( pPage->nFree>=nByte );
   61992   assert( pPage->nOverflow==0 );
   61993   assert( nByte < (int)(pPage->pBt->usableSize-8) );
   61994 
   61995   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
   61996   gap = pPage->cellOffset + 2*pPage->nCell;
   61997   assert( gap<=65536 );
   61998   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
   61999   ** and the reserved space is zero (the usual value for reserved space)
   62000   ** then the cell content offset of an empty page wants to be 65536.
   62001   ** However, that integer is too large to be stored in a 2-byte unsigned
   62002   ** integer, so a value of 0 is used in its place. */
   62003   top = get2byte(&data[hdr+5]);
   62004   assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
   62005   if( gap>top ){
   62006     if( top==0 && pPage->pBt->usableSize==65536 ){
   62007       top = 65536;
   62008     }else{
   62009       return SQLITE_CORRUPT_PAGE(pPage);
   62010     }
   62011   }
   62012 
   62013   /* If there is enough space between gap and top for one more cell pointer
   62014   ** array entry offset, and if the freelist is not empty, then search the
   62015   ** freelist looking for a free slot big enough to satisfy the request.
   62016   */
   62017   testcase( gap+2==top );
   62018   testcase( gap+1==top );
   62019   testcase( gap==top );
   62020   if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
   62021     u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
   62022     if( pSpace ){
   62023       assert( pSpace>=data && (pSpace - data)<65536 );
   62024       *pIdx = (int)(pSpace - data);
   62025       return SQLITE_OK;
   62026     }else if( rc ){
   62027       return rc;
   62028     }
   62029   }
   62030 
   62031   /* The request could not be fulfilled using a freelist slot.  Check
   62032   ** to see if defragmentation is necessary.
   62033   */
   62034   testcase( gap+2+nByte==top );
   62035   if( gap+2+nByte>top ){
   62036     assert( pPage->nCell>0 || CORRUPT_DB );
   62037     rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
   62038     if( rc ) return rc;
   62039     top = get2byteNotZero(&data[hdr+5]);
   62040     assert( gap+2+nByte<=top );
   62041   }
   62042 
   62043 
   62044   /* Allocate memory from the gap in between the cell pointer array
   62045   ** and the cell content area.  The btreeInitPage() call has already
   62046   ** validated the freelist.  Given that the freelist is valid, there
   62047   ** is no way that the allocation can extend off the end of the page.
   62048   ** The assert() below verifies the previous sentence.
   62049   */
   62050   top -= nByte;
   62051   put2byte(&data[hdr+5], top);
   62052   assert( top+nByte <= (int)pPage->pBt->usableSize );
   62053   *pIdx = top;
   62054   return SQLITE_OK;
   62055 }
   62056 
   62057 /*
   62058 ** Return a section of the pPage->aData to the freelist.
   62059 ** The first byte of the new free block is pPage->aData[iStart]
   62060 ** and the size of the block is iSize bytes.
   62061 **
   62062 ** Adjacent freeblocks are coalesced.
   62063 **
   62064 ** Note that even though the freeblock list was checked by btreeInitPage(),
   62065 ** that routine will not detect overlap between cells or freeblocks.  Nor
   62066 ** does it detect cells or freeblocks that encrouch into the reserved bytes
   62067 ** at the end of the page.  So do additional corruption checks inside this
   62068 ** routine and return SQLITE_CORRUPT if any problems are found.
   62069 */
   62070 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
   62071   u16 iPtr;                             /* Address of ptr to next freeblock */
   62072   u16 iFreeBlk;                         /* Address of the next freeblock */
   62073   u8 hdr;                               /* Page header size.  0 or 100 */
   62074   u8 nFrag = 0;                         /* Reduction in fragmentation */
   62075   u16 iOrigSize = iSize;                /* Original value of iSize */
   62076   u16 x;                                /* Offset to cell content area */
   62077   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
   62078   unsigned char *data = pPage->aData;   /* Page content */
   62079 
   62080   assert( pPage->pBt!=0 );
   62081   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   62082   assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
   62083   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
   62084   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   62085   assert( iSize>=4 );   /* Minimum cell size is 4 */
   62086   assert( iStart<=pPage->pBt->usableSize-4 );
   62087 
   62088   /* The list of freeblocks must be in ascending order.  Find the
   62089   ** spot on the list where iStart should be inserted.
   62090   */
   62091   hdr = pPage->hdrOffset;
   62092   iPtr = hdr + 1;
   62093   if( data[iPtr+1]==0 && data[iPtr]==0 ){
   62094     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
   62095   }else{
   62096     while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
   62097       if( iFreeBlk<iPtr+4 ){
   62098         if( iFreeBlk==0 ) break;
   62099         return SQLITE_CORRUPT_PAGE(pPage);
   62100       }
   62101       iPtr = iFreeBlk;
   62102     }
   62103     if( iFreeBlk>pPage->pBt->usableSize-4 ){
   62104       return SQLITE_CORRUPT_PAGE(pPage);
   62105     }
   62106     assert( iFreeBlk>iPtr || iFreeBlk==0 );
   62107 
   62108     /* At this point:
   62109     **    iFreeBlk:   First freeblock after iStart, or zero if none
   62110     **    iPtr:       The address of a pointer to iFreeBlk
   62111     **
   62112     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
   62113     */
   62114     if( iFreeBlk && iEnd+3>=iFreeBlk ){
   62115       nFrag = iFreeBlk - iEnd;
   62116       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
   62117       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
   62118       if( iEnd > pPage->pBt->usableSize ){
   62119         return SQLITE_CORRUPT_PAGE(pPage);
   62120       }
   62121       iSize = iEnd - iStart;
   62122       iFreeBlk = get2byte(&data[iFreeBlk]);
   62123     }
   62124 
   62125     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
   62126     ** pointer in the page header) then check to see if iStart should be
   62127     ** coalesced onto the end of iPtr.
   62128     */
   62129     if( iPtr>hdr+1 ){
   62130       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
   62131       if( iPtrEnd+3>=iStart ){
   62132         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
   62133         nFrag += iStart - iPtrEnd;
   62134         iSize = iEnd - iPtr;
   62135         iStart = iPtr;
   62136       }
   62137     }
   62138     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
   62139     data[hdr+7] -= nFrag;
   62140   }
   62141   x = get2byte(&data[hdr+5]);
   62142   if( iStart<=x ){
   62143     /* The new freeblock is at the beginning of the cell content area,
   62144     ** so just extend the cell content area rather than create another
   62145     ** freelist entry */
   62146     if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
   62147     put2byte(&data[hdr+1], iFreeBlk);
   62148     put2byte(&data[hdr+5], iEnd);
   62149   }else{
   62150     /* Insert the new freeblock into the freelist */
   62151     put2byte(&data[iPtr], iStart);
   62152   }
   62153   if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
   62154     /* Overwrite deleted information with zeros when the secure_delete
   62155     ** option is enabled */
   62156     memset(&data[iStart], 0, iSize);
   62157   }
   62158   put2byte(&data[iStart], iFreeBlk);
   62159   put2byte(&data[iStart+2], iSize);
   62160   pPage->nFree += iOrigSize;
   62161   return SQLITE_OK;
   62162 }
   62163 
   62164 /*
   62165 ** Decode the flags byte (the first byte of the header) for a page
   62166 ** and initialize fields of the MemPage structure accordingly.
   62167 **
   62168 ** Only the following combinations are supported.  Anything different
   62169 ** indicates a corrupt database files:
   62170 **
   62171 **         PTF_ZERODATA
   62172 **         PTF_ZERODATA | PTF_LEAF
   62173 **         PTF_LEAFDATA | PTF_INTKEY
   62174 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
   62175 */
   62176 static int decodeFlags(MemPage *pPage, int flagByte){
   62177   BtShared *pBt;     /* A copy of pPage->pBt */
   62178 
   62179   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   62180   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   62181   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
   62182   flagByte &= ~PTF_LEAF;
   62183   pPage->childPtrSize = 4-4*pPage->leaf;
   62184   pPage->xCellSize = cellSizePtr;
   62185   pBt = pPage->pBt;
   62186   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
   62187     /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
   62188     ** interior table b-tree page. */
   62189     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
   62190     /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
   62191     ** leaf table b-tree page. */
   62192     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
   62193     pPage->intKey = 1;
   62194     if( pPage->leaf ){
   62195       pPage->intKeyLeaf = 1;
   62196       pPage->xParseCell = btreeParseCellPtr;
   62197     }else{
   62198       pPage->intKeyLeaf = 0;
   62199       pPage->xCellSize = cellSizePtrNoPayload;
   62200       pPage->xParseCell = btreeParseCellPtrNoPayload;
   62201     }
   62202     pPage->maxLocal = pBt->maxLeaf;
   62203     pPage->minLocal = pBt->minLeaf;
   62204   }else if( flagByte==PTF_ZERODATA ){
   62205     /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
   62206     ** interior index b-tree page. */
   62207     assert( (PTF_ZERODATA)==2 );
   62208     /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
   62209     ** leaf index b-tree page. */
   62210     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
   62211     pPage->intKey = 0;
   62212     pPage->intKeyLeaf = 0;
   62213     pPage->xParseCell = btreeParseCellPtrIndex;
   62214     pPage->maxLocal = pBt->maxLocal;
   62215     pPage->minLocal = pBt->minLocal;
   62216   }else{
   62217     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
   62218     ** an error. */
   62219     return SQLITE_CORRUPT_PAGE(pPage);
   62220   }
   62221   pPage->max1bytePayload = pBt->max1bytePayload;
   62222   return SQLITE_OK;
   62223 }
   62224 
   62225 /*
   62226 ** Initialize the auxiliary information for a disk block.
   62227 **
   62228 ** Return SQLITE_OK on success.  If we see that the page does
   62229 ** not contain a well-formed database page, then return
   62230 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
   62231 ** guarantee that the page is well-formed.  It only shows that
   62232 ** we failed to detect any corruption.
   62233 */
   62234 static int btreeInitPage(MemPage *pPage){
   62235   int pc;            /* Address of a freeblock within pPage->aData[] */
   62236   u8 hdr;            /* Offset to beginning of page header */
   62237   u8 *data;          /* Equal to pPage->aData */
   62238   BtShared *pBt;        /* The main btree structure */
   62239   int usableSize;    /* Amount of usable space on each page */
   62240   u16 cellOffset;    /* Offset from start of page to first cell pointer */
   62241   int nFree;         /* Number of unused bytes on the page */
   62242   int top;           /* First byte of the cell content area */
   62243   int iCellFirst;    /* First allowable cell or freeblock offset */
   62244   int iCellLast;     /* Last possible cell or freeblock offset */
   62245 
   62246   assert( pPage->pBt!=0 );
   62247   assert( pPage->pBt->db!=0 );
   62248   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   62249   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
   62250   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
   62251   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
   62252   assert( pPage->isInit==0 );
   62253 
   62254   pBt = pPage->pBt;
   62255   hdr = pPage->hdrOffset;
   62256   data = pPage->aData;
   62257   /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
   62258   ** the b-tree page type. */
   62259   if( decodeFlags(pPage, data[hdr]) ){
   62260     return SQLITE_CORRUPT_PAGE(pPage);
   62261   }
   62262   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   62263   pPage->maskPage = (u16)(pBt->pageSize - 1);
   62264   pPage->nOverflow = 0;
   62265   usableSize = pBt->usableSize;
   62266   pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
   62267   pPage->aDataEnd = &data[usableSize];
   62268   pPage->aCellIdx = &data[cellOffset];
   62269   pPage->aDataOfst = &data[pPage->childPtrSize];
   62270   /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
   62271   ** the start of the cell content area. A zero value for this integer is
   62272   ** interpreted as 65536. */
   62273   top = get2byteNotZero(&data[hdr+5]);
   62274   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
   62275   ** number of cells on the page. */
   62276   pPage->nCell = get2byte(&data[hdr+3]);
   62277   if( pPage->nCell>MX_CELL(pBt) ){
   62278     /* To many cells for a single page.  The page must be corrupt */
   62279     return SQLITE_CORRUPT_PAGE(pPage);
   62280   }
   62281   testcase( pPage->nCell==MX_CELL(pBt) );
   62282   /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
   62283   ** possible for a root page of a table that contains no rows) then the
   62284   ** offset to the cell content area will equal the page size minus the
   62285   ** bytes of reserved space. */
   62286   assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
   62287 
   62288   /* A malformed database page might cause us to read past the end
   62289   ** of page when parsing a cell.
   62290   **
   62291   ** The following block of code checks early to see if a cell extends
   62292   ** past the end of a page boundary and causes SQLITE_CORRUPT to be
   62293   ** returned if it does.
   62294   */
   62295   iCellFirst = cellOffset + 2*pPage->nCell;
   62296   iCellLast = usableSize - 4;
   62297   if( pBt->db->flags & SQLITE_CellSizeCk ){
   62298     int i;            /* Index into the cell pointer array */
   62299     int sz;           /* Size of a cell */
   62300 
   62301     if( !pPage->leaf ) iCellLast--;
   62302     for(i=0; i<pPage->nCell; i++){
   62303       pc = get2byteAligned(&data[cellOffset+i*2]);
   62304       testcase( pc==iCellFirst );
   62305       testcase( pc==iCellLast );
   62306       if( pc<iCellFirst || pc>iCellLast ){
   62307         return SQLITE_CORRUPT_PAGE(pPage);
   62308       }
   62309       sz = pPage->xCellSize(pPage, &data[pc]);
   62310       testcase( pc+sz==usableSize );
   62311       if( pc+sz>usableSize ){
   62312         return SQLITE_CORRUPT_PAGE(pPage);
   62313       }
   62314     }
   62315     if( !pPage->leaf ) iCellLast++;
   62316   }
   62317 
   62318   /* Compute the total free space on the page
   62319   ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
   62320   ** start of the first freeblock on the page, or is zero if there are no
   62321   ** freeblocks. */
   62322   pc = get2byte(&data[hdr+1]);
   62323   nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
   62324   if( pc>0 ){
   62325     u32 next, size;
   62326     if( pc<iCellFirst ){
   62327       /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
   62328       ** always be at least one cell before the first freeblock.
   62329       */
   62330       return SQLITE_CORRUPT_PAGE(pPage);
   62331     }
   62332     while( 1 ){
   62333       if( pc>iCellLast ){
   62334         /* Freeblock off the end of the page */
   62335         return SQLITE_CORRUPT_PAGE(pPage);
   62336       }
   62337       next = get2byte(&data[pc]);
   62338       size = get2byte(&data[pc+2]);
   62339       nFree = nFree + size;
   62340       if( next<=pc+size+3 ) break;
   62341       pc = next;
   62342     }
   62343     if( next>0 ){
   62344       /* Freeblock not in ascending order */
   62345       return SQLITE_CORRUPT_PAGE(pPage);
   62346     }
   62347     if( pc+size>(unsigned int)usableSize ){
   62348       /* Last freeblock extends past page end */
   62349       return SQLITE_CORRUPT_PAGE(pPage);
   62350     }
   62351   }
   62352 
   62353   /* At this point, nFree contains the sum of the offset to the start
   62354   ** of the cell-content area plus the number of free bytes within
   62355   ** the cell-content area. If this is greater than the usable-size
   62356   ** of the page, then the page must be corrupted. This check also
   62357   ** serves to verify that the offset to the start of the cell-content
   62358   ** area, according to the page header, lies within the page.
   62359   */
   62360   if( nFree>usableSize ){
   62361     return SQLITE_CORRUPT_PAGE(pPage);
   62362   }
   62363   pPage->nFree = (u16)(nFree - iCellFirst);
   62364   pPage->isInit = 1;
   62365   return SQLITE_OK;
   62366 }
   62367 
   62368 /*
   62369 ** Set up a raw page so that it looks like a database page holding
   62370 ** no entries.
   62371 */
   62372 static void zeroPage(MemPage *pPage, int flags){
   62373   unsigned char *data = pPage->aData;
   62374   BtShared *pBt = pPage->pBt;
   62375   u8 hdr = pPage->hdrOffset;
   62376   u16 first;
   62377 
   62378   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
   62379   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   62380   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   62381   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   62382   assert( sqlite3_mutex_held(pBt->mutex) );
   62383   if( pBt->btsFlags & BTS_FAST_SECURE ){
   62384     memset(&data[hdr], 0, pBt->usableSize - hdr);
   62385   }
   62386   data[hdr] = (char)flags;
   62387   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
   62388   memset(&data[hdr+1], 0, 4);
   62389   data[hdr+7] = 0;
   62390   put2byte(&data[hdr+5], pBt->usableSize);
   62391   pPage->nFree = (u16)(pBt->usableSize - first);
   62392   decodeFlags(pPage, flags);
   62393   pPage->cellOffset = first;
   62394   pPage->aDataEnd = &data[pBt->usableSize];
   62395   pPage->aCellIdx = &data[first];
   62396   pPage->aDataOfst = &data[pPage->childPtrSize];
   62397   pPage->nOverflow = 0;
   62398   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   62399   pPage->maskPage = (u16)(pBt->pageSize - 1);
   62400   pPage->nCell = 0;
   62401   pPage->isInit = 1;
   62402 }
   62403 
   62404 
   62405 /*
   62406 ** Convert a DbPage obtained from the pager into a MemPage used by
   62407 ** the btree layer.
   62408 */
   62409 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
   62410   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   62411   if( pgno!=pPage->pgno ){
   62412     pPage->aData = sqlite3PagerGetData(pDbPage);
   62413     pPage->pDbPage = pDbPage;
   62414     pPage->pBt = pBt;
   62415     pPage->pgno = pgno;
   62416     pPage->hdrOffset = pgno==1 ? 100 : 0;
   62417   }
   62418   assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
   62419   return pPage;
   62420 }
   62421 
   62422 /*
   62423 ** Get a page from the pager.  Initialize the MemPage.pBt and
   62424 ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
   62425 **
   62426 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
   62427 ** about the content of the page at this time.  So do not go to the disk
   62428 ** to fetch the content.  Just fill in the content with zeros for now.
   62429 ** If in the future we call sqlite3PagerWrite() on this page, that
   62430 ** means we have started to be concerned about content and the disk
   62431 ** read should occur at that point.
   62432 */
   62433 static int btreeGetPage(
   62434   BtShared *pBt,       /* The btree */
   62435   Pgno pgno,           /* Number of the page to fetch */
   62436   MemPage **ppPage,    /* Return the page in this parameter */
   62437   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
   62438 ){
   62439   int rc;
   62440   DbPage *pDbPage;
   62441 
   62442   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
   62443   assert( sqlite3_mutex_held(pBt->mutex) );
   62444   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
   62445   if( rc ) return rc;
   62446   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
   62447   return SQLITE_OK;
   62448 }
   62449 
   62450 /*
   62451 ** Retrieve a page from the pager cache. If the requested page is not
   62452 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
   62453 ** MemPage.aData elements if needed.
   62454 */
   62455 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
   62456   DbPage *pDbPage;
   62457   assert( sqlite3_mutex_held(pBt->mutex) );
   62458   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
   62459   if( pDbPage ){
   62460     return btreePageFromDbPage(pDbPage, pgno, pBt);
   62461   }
   62462   return 0;
   62463 }
   62464 
   62465 /*
   62466 ** Return the size of the database file in pages. If there is any kind of
   62467 ** error, return ((unsigned int)-1).
   62468 */
   62469 static Pgno btreePagecount(BtShared *pBt){
   62470   return pBt->nPage;
   62471 }
   62472 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
   62473   assert( sqlite3BtreeHoldsMutex(p) );
   62474   assert( ((p->pBt->nPage)&0x80000000)==0 );
   62475   return btreePagecount(p->pBt);
   62476 }
   62477 
   62478 /*
   62479 ** Get a page from the pager and initialize it.
   62480 **
   62481 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
   62482 ** call.  Do additional sanity checking on the page in this case.
   62483 ** And if the fetch fails, this routine must decrement pCur->iPage.
   62484 **
   62485 ** The page is fetched as read-write unless pCur is not NULL and is
   62486 ** a read-only cursor.
   62487 **
   62488 ** If an error occurs, then *ppPage is undefined. It
   62489 ** may remain unchanged, or it may be set to an invalid value.
   62490 */
   62491 static int getAndInitPage(
   62492   BtShared *pBt,                  /* The database file */
   62493   Pgno pgno,                      /* Number of the page to get */
   62494   MemPage **ppPage,               /* Write the page pointer here */
   62495   BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
   62496   int bReadOnly                   /* True for a read-only page */
   62497 ){
   62498   int rc;
   62499   DbPage *pDbPage;
   62500   assert( sqlite3_mutex_held(pBt->mutex) );
   62501   assert( pCur==0 || ppPage==&pCur->pPage );
   62502   assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
   62503   assert( pCur==0 || pCur->iPage>0 );
   62504 
   62505   if( pgno>btreePagecount(pBt) ){
   62506     rc = SQLITE_CORRUPT_BKPT;
   62507     goto getAndInitPage_error;
   62508   }
   62509   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
   62510   if( rc ){
   62511     goto getAndInitPage_error;
   62512   }
   62513   *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   62514   if( (*ppPage)->isInit==0 ){
   62515     btreePageFromDbPage(pDbPage, pgno, pBt);
   62516     rc = btreeInitPage(*ppPage);
   62517     if( rc!=SQLITE_OK ){
   62518       releasePage(*ppPage);
   62519       goto getAndInitPage_error;
   62520     }
   62521   }
   62522   assert( (*ppPage)->pgno==pgno );
   62523   assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
   62524 
   62525   /* If obtaining a child page for a cursor, we must verify that the page is
   62526   ** compatible with the root page. */
   62527   if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
   62528     rc = SQLITE_CORRUPT_PGNO(pgno);
   62529     releasePage(*ppPage);
   62530     goto getAndInitPage_error;
   62531   }
   62532   return SQLITE_OK;
   62533 
   62534 getAndInitPage_error:
   62535   if( pCur ){
   62536     pCur->iPage--;
   62537     pCur->pPage = pCur->apPage[pCur->iPage];
   62538   }
   62539   testcase( pgno==0 );
   62540   assert( pgno!=0 || rc==SQLITE_CORRUPT );
   62541   return rc;
   62542 }
   62543 
   62544 /*
   62545 ** Release a MemPage.  This should be called once for each prior
   62546 ** call to btreeGetPage.
   62547 **
   62548 ** Page1 is a special case and must be released using releasePageOne().
   62549 */
   62550 static void releasePageNotNull(MemPage *pPage){
   62551   assert( pPage->aData );
   62552   assert( pPage->pBt );
   62553   assert( pPage->pDbPage!=0 );
   62554   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   62555   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   62556   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   62557   sqlite3PagerUnrefNotNull(pPage->pDbPage);
   62558 }
   62559 static void releasePage(MemPage *pPage){
   62560   if( pPage ) releasePageNotNull(pPage);
   62561 }
   62562 static void releasePageOne(MemPage *pPage){
   62563   assert( pPage!=0 );
   62564   assert( pPage->aData );
   62565   assert( pPage->pBt );
   62566   assert( pPage->pDbPage!=0 );
   62567   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   62568   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   62569   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   62570   sqlite3PagerUnrefPageOne(pPage->pDbPage);
   62571 }
   62572 
   62573 /*
   62574 ** Get an unused page.
   62575 **
   62576 ** This works just like btreeGetPage() with the addition:
   62577 **
   62578 **   *  If the page is already in use for some other purpose, immediately
   62579 **      release it and return an SQLITE_CURRUPT error.
   62580 **   *  Make sure the isInit flag is clear
   62581 */
   62582 static int btreeGetUnusedPage(
   62583   BtShared *pBt,       /* The btree */
   62584   Pgno pgno,           /* Number of the page to fetch */
   62585   MemPage **ppPage,    /* Return the page in this parameter */
   62586   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
   62587 ){
   62588   int rc = btreeGetPage(pBt, pgno, ppPage, flags);
   62589   if( rc==SQLITE_OK ){
   62590     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
   62591       releasePage(*ppPage);
   62592       *ppPage = 0;
   62593       return SQLITE_CORRUPT_BKPT;
   62594     }
   62595     (*ppPage)->isInit = 0;
   62596   }else{
   62597     *ppPage = 0;
   62598   }
   62599   return rc;
   62600 }
   62601 
   62602 
   62603 /*
   62604 ** During a rollback, when the pager reloads information into the cache
   62605 ** so that the cache is restored to its original state at the start of
   62606 ** the transaction, for each page restored this routine is called.
   62607 **
   62608 ** This routine needs to reset the extra data section at the end of the
   62609 ** page to agree with the restored data.
   62610 */
   62611 static void pageReinit(DbPage *pData){
   62612   MemPage *pPage;
   62613   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
   62614   assert( sqlite3PagerPageRefcount(pData)>0 );
   62615   if( pPage->isInit ){
   62616     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   62617     pPage->isInit = 0;
   62618     if( sqlite3PagerPageRefcount(pData)>1 ){
   62619       /* pPage might not be a btree page;  it might be an overflow page
   62620       ** or ptrmap page or a free page.  In those cases, the following
   62621       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
   62622       ** But no harm is done by this.  And it is very important that
   62623       ** btreeInitPage() be called on every btree page so we make
   62624       ** the call for every page that comes in for re-initing. */
   62625       btreeInitPage(pPage);
   62626     }
   62627   }
   62628 }
   62629 
   62630 /*
   62631 ** Invoke the busy handler for a btree.
   62632 */
   62633 static int btreeInvokeBusyHandler(void *pArg){
   62634   BtShared *pBt = (BtShared*)pArg;
   62635   assert( pBt->db );
   62636   assert( sqlite3_mutex_held(pBt->db->mutex) );
   62637   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
   62638 }
   62639 
   62640 /*
   62641 ** Open a database file.
   62642 **
   62643 ** zFilename is the name of the database file.  If zFilename is NULL
   62644 ** then an ephemeral database is created.  The ephemeral database might
   62645 ** be exclusively in memory, or it might use a disk-based memory cache.
   62646 ** Either way, the ephemeral database will be automatically deleted
   62647 ** when sqlite3BtreeClose() is called.
   62648 **
   62649 ** If zFilename is ":memory:" then an in-memory database is created
   62650 ** that is automatically destroyed when it is closed.
   62651 **
   62652 ** The "flags" parameter is a bitmask that might contain bits like
   62653 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
   62654 **
   62655 ** If the database is already opened in the same database connection
   62656 ** and we are in shared cache mode, then the open will fail with an
   62657 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
   62658 ** objects in the same database connection since doing so will lead
   62659 ** to problems with locking.
   62660 */
   62661 SQLITE_PRIVATE int sqlite3BtreeOpen(
   62662   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
   62663   const char *zFilename,  /* Name of the file containing the BTree database */
   62664   sqlite3 *db,            /* Associated database handle */
   62665   Btree **ppBtree,        /* Pointer to new Btree object written here */
   62666   int flags,              /* Options */
   62667   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
   62668 ){
   62669   BtShared *pBt = 0;             /* Shared part of btree structure */
   62670   Btree *p;                      /* Handle to return */
   62671   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
   62672   int rc = SQLITE_OK;            /* Result code from this function */
   62673   u8 nReserve;                   /* Byte of unused space on each page */
   62674   unsigned char zDbHeader[100];  /* Database header content */
   62675 
   62676   /* True if opening an ephemeral, temporary database */
   62677   const int isTempDb = zFilename==0 || zFilename[0]==0;
   62678 
   62679   /* Set the variable isMemdb to true for an in-memory database, or
   62680   ** false for a file-based database.
   62681   */
   62682 #ifdef SQLITE_OMIT_MEMORYDB
   62683   const int isMemdb = 0;
   62684 #else
   62685   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
   62686                        || (isTempDb && sqlite3TempInMemory(db))
   62687                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
   62688 #endif
   62689 
   62690   assert( db!=0 );
   62691   assert( pVfs!=0 );
   62692   assert( sqlite3_mutex_held(db->mutex) );
   62693   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
   62694 
   62695   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
   62696   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
   62697 
   62698   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
   62699   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
   62700 
   62701   if( isMemdb ){
   62702     flags |= BTREE_MEMORY;
   62703   }
   62704   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
   62705     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
   62706   }
   62707   p = sqlite3MallocZero(sizeof(Btree));
   62708   if( !p ){
   62709     return SQLITE_NOMEM_BKPT;
   62710   }
   62711   p->inTrans = TRANS_NONE;
   62712   p->db = db;
   62713 #ifndef SQLITE_OMIT_SHARED_CACHE
   62714   p->lock.pBtree = p;
   62715   p->lock.iTable = 1;
   62716 #endif
   62717 
   62718 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   62719   /*
   62720   ** If this Btree is a candidate for shared cache, try to find an
   62721   ** existing BtShared object that we can share with
   62722   */
   62723   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
   62724     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
   62725       int nFilename = sqlite3Strlen30(zFilename)+1;
   62726       int nFullPathname = pVfs->mxPathname+1;
   62727       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
   62728       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   62729 
   62730       p->sharable = 1;
   62731       if( !zFullPathname ){
   62732         sqlite3_free(p);
   62733         return SQLITE_NOMEM_BKPT;
   62734       }
   62735       if( isMemdb ){
   62736         memcpy(zFullPathname, zFilename, nFilename);
   62737       }else{
   62738         rc = sqlite3OsFullPathname(pVfs, zFilename,
   62739                                    nFullPathname, zFullPathname);
   62740         if( rc ){
   62741           sqlite3_free(zFullPathname);
   62742           sqlite3_free(p);
   62743           return rc;
   62744         }
   62745       }
   62746 #if SQLITE_THREADSAFE
   62747       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
   62748       sqlite3_mutex_enter(mutexOpen);
   62749       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   62750       sqlite3_mutex_enter(mutexShared);
   62751 #endif
   62752       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
   62753         assert( pBt->nRef>0 );
   62754         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
   62755                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
   62756           int iDb;
   62757           for(iDb=db->nDb-1; iDb>=0; iDb--){
   62758             Btree *pExisting = db->aDb[iDb].pBt;
   62759             if( pExisting && pExisting->pBt==pBt ){
   62760               sqlite3_mutex_leave(mutexShared);
   62761               sqlite3_mutex_leave(mutexOpen);
   62762               sqlite3_free(zFullPathname);
   62763               sqlite3_free(p);
   62764               return SQLITE_CONSTRAINT;
   62765             }
   62766           }
   62767           p->pBt = pBt;
   62768           pBt->nRef++;
   62769           break;
   62770         }
   62771       }
   62772       sqlite3_mutex_leave(mutexShared);
   62773       sqlite3_free(zFullPathname);
   62774     }
   62775 #ifdef SQLITE_DEBUG
   62776     else{
   62777       /* In debug mode, we mark all persistent databases as sharable
   62778       ** even when they are not.  This exercises the locking code and
   62779       ** gives more opportunity for asserts(sqlite3_mutex_held())
   62780       ** statements to find locking problems.
   62781       */
   62782       p->sharable = 1;
   62783     }
   62784 #endif
   62785   }
   62786 #endif
   62787   if( pBt==0 ){
   62788     /*
   62789     ** The following asserts make sure that structures used by the btree are
   62790     ** the right size.  This is to guard against size changes that result
   62791     ** when compiling on a different architecture.
   62792     */
   62793     assert( sizeof(i64)==8 );
   62794     assert( sizeof(u64)==8 );
   62795     assert( sizeof(u32)==4 );
   62796     assert( sizeof(u16)==2 );
   62797     assert( sizeof(Pgno)==4 );
   62798 
   62799     pBt = sqlite3MallocZero( sizeof(*pBt) );
   62800     if( pBt==0 ){
   62801       rc = SQLITE_NOMEM_BKPT;
   62802       goto btree_open_out;
   62803     }
   62804     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
   62805                           sizeof(MemPage), flags, vfsFlags, pageReinit);
   62806     if( rc==SQLITE_OK ){
   62807       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
   62808       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
   62809     }
   62810     if( rc!=SQLITE_OK ){
   62811       goto btree_open_out;
   62812     }
   62813     pBt->openFlags = (u8)flags;
   62814     pBt->db = db;
   62815     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
   62816     p->pBt = pBt;
   62817 
   62818     pBt->pCursor = 0;
   62819     pBt->pPage1 = 0;
   62820     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
   62821 #if defined(SQLITE_SECURE_DELETE)
   62822     pBt->btsFlags |= BTS_SECURE_DELETE;
   62823 #elif defined(SQLITE_FAST_SECURE_DELETE)
   62824     pBt->btsFlags |= BTS_OVERWRITE;
   62825 #endif
   62826     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
   62827     ** determined by the 2-byte integer located at an offset of 16 bytes from
   62828     ** the beginning of the database file. */
   62829     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
   62830     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
   62831          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
   62832       pBt->pageSize = 0;
   62833 #ifndef SQLITE_OMIT_AUTOVACUUM
   62834       /* If the magic name ":memory:" will create an in-memory database, then
   62835       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
   62836       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
   62837       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
   62838       ** regular file-name. In this case the auto-vacuum applies as per normal.
   62839       */
   62840       if( zFilename && !isMemdb ){
   62841         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
   62842         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
   62843       }
   62844 #endif
   62845       nReserve = 0;
   62846     }else{
   62847       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
   62848       ** determined by the one-byte unsigned integer found at an offset of 20
   62849       ** into the database file header. */
   62850       nReserve = zDbHeader[20];
   62851       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   62852 #ifndef SQLITE_OMIT_AUTOVACUUM
   62853       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
   62854       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
   62855 #endif
   62856     }
   62857     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   62858     if( rc ) goto btree_open_out;
   62859     pBt->usableSize = pBt->pageSize - nReserve;
   62860     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   62861 
   62862 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   62863     /* Add the new BtShared object to the linked list sharable BtShareds.
   62864     */
   62865     pBt->nRef = 1;
   62866     if( p->sharable ){
   62867       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   62868       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
   62869       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
   62870         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
   62871         if( pBt->mutex==0 ){
   62872           rc = SQLITE_NOMEM_BKPT;
   62873           goto btree_open_out;
   62874         }
   62875       }
   62876       sqlite3_mutex_enter(mutexShared);
   62877       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
   62878       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
   62879       sqlite3_mutex_leave(mutexShared);
   62880     }
   62881 #endif
   62882   }
   62883 
   62884 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   62885   /* If the new Btree uses a sharable pBtShared, then link the new
   62886   ** Btree into the list of all sharable Btrees for the same connection.
   62887   ** The list is kept in ascending order by pBt address.
   62888   */
   62889   if( p->sharable ){
   62890     int i;
   62891     Btree *pSib;
   62892     for(i=0; i<db->nDb; i++){
   62893       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
   62894         while( pSib->pPrev ){ pSib = pSib->pPrev; }
   62895         if( (uptr)p->pBt<(uptr)pSib->pBt ){
   62896           p->pNext = pSib;
   62897           p->pPrev = 0;
   62898           pSib->pPrev = p;
   62899         }else{
   62900           while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
   62901             pSib = pSib->pNext;
   62902           }
   62903           p->pNext = pSib->pNext;
   62904           p->pPrev = pSib;
   62905           if( p->pNext ){
   62906             p->pNext->pPrev = p;
   62907           }
   62908           pSib->pNext = p;
   62909         }
   62910         break;
   62911       }
   62912     }
   62913   }
   62914 #endif
   62915   *ppBtree = p;
   62916 
   62917 btree_open_out:
   62918   if( rc!=SQLITE_OK ){
   62919     if( pBt && pBt->pPager ){
   62920       sqlite3PagerClose(pBt->pPager, 0);
   62921     }
   62922     sqlite3_free(pBt);
   62923     sqlite3_free(p);
   62924     *ppBtree = 0;
   62925   }else{
   62926     sqlite3_file *pFile;
   62927 
   62928     /* If the B-Tree was successfully opened, set the pager-cache size to the
   62929     ** default value. Except, when opening on an existing shared pager-cache,
   62930     ** do not change the pager-cache size.
   62931     */
   62932     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
   62933       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
   62934     }
   62935 
   62936     pFile = sqlite3PagerFile(pBt->pPager);
   62937     if( pFile->pMethods ){
   62938       sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
   62939     }
   62940   }
   62941   if( mutexOpen ){
   62942     assert( sqlite3_mutex_held(mutexOpen) );
   62943     sqlite3_mutex_leave(mutexOpen);
   62944   }
   62945   assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
   62946   return rc;
   62947 }
   62948 
   62949 /*
   62950 ** Decrement the BtShared.nRef counter.  When it reaches zero,
   62951 ** remove the BtShared structure from the sharing list.  Return
   62952 ** true if the BtShared.nRef counter reaches zero and return
   62953 ** false if it is still positive.
   62954 */
   62955 static int removeFromSharingList(BtShared *pBt){
   62956 #ifndef SQLITE_OMIT_SHARED_CACHE
   62957   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
   62958   BtShared *pList;
   62959   int removed = 0;
   62960 
   62961   assert( sqlite3_mutex_notheld(pBt->mutex) );
   62962   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   62963   sqlite3_mutex_enter(pMaster);
   62964   pBt->nRef--;
   62965   if( pBt->nRef<=0 ){
   62966     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
   62967       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
   62968     }else{
   62969       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
   62970       while( ALWAYS(pList) && pList->pNext!=pBt ){
   62971         pList=pList->pNext;
   62972       }
   62973       if( ALWAYS(pList) ){
   62974         pList->pNext = pBt->pNext;
   62975       }
   62976     }
   62977     if( SQLITE_THREADSAFE ){
   62978       sqlite3_mutex_free(pBt->mutex);
   62979     }
   62980     removed = 1;
   62981   }
   62982   sqlite3_mutex_leave(pMaster);
   62983   return removed;
   62984 #else
   62985   return 1;
   62986 #endif
   62987 }
   62988 
   62989 /*
   62990 ** Make sure pBt->pTmpSpace points to an allocation of
   62991 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
   62992 ** pointer.
   62993 */
   62994 static void allocateTempSpace(BtShared *pBt){
   62995   if( !pBt->pTmpSpace ){
   62996     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
   62997 
   62998     /* One of the uses of pBt->pTmpSpace is to format cells before
   62999     ** inserting them into a leaf page (function fillInCell()). If
   63000     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
   63001     ** by the various routines that manipulate binary cells. Which
   63002     ** can mean that fillInCell() only initializes the first 2 or 3
   63003     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
   63004     ** it into a database page. This is not actually a problem, but it
   63005     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
   63006     ** data is passed to system call write(). So to avoid this error,
   63007     ** zero the first 4 bytes of temp space here.
   63008     **
   63009     ** Also:  Provide four bytes of initialized space before the
   63010     ** beginning of pTmpSpace as an area available to prepend the
   63011     ** left-child pointer to the beginning of a cell.
   63012     */
   63013     if( pBt->pTmpSpace ){
   63014       memset(pBt->pTmpSpace, 0, 8);
   63015       pBt->pTmpSpace += 4;
   63016     }
   63017   }
   63018 }
   63019 
   63020 /*
   63021 ** Free the pBt->pTmpSpace allocation
   63022 */
   63023 static void freeTempSpace(BtShared *pBt){
   63024   if( pBt->pTmpSpace ){
   63025     pBt->pTmpSpace -= 4;
   63026     sqlite3PageFree(pBt->pTmpSpace);
   63027     pBt->pTmpSpace = 0;
   63028   }
   63029 }
   63030 
   63031 /*
   63032 ** Close an open database and invalidate all cursors.
   63033 */
   63034 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   63035   BtShared *pBt = p->pBt;
   63036   BtCursor *pCur;
   63037 
   63038   /* Close all cursors opened via this handle.  */
   63039   assert( sqlite3_mutex_held(p->db->mutex) );
   63040   sqlite3BtreeEnter(p);
   63041   pCur = pBt->pCursor;
   63042   while( pCur ){
   63043     BtCursor *pTmp = pCur;
   63044     pCur = pCur->pNext;
   63045     if( pTmp->pBtree==p ){
   63046       sqlite3BtreeCloseCursor(pTmp);
   63047     }
   63048   }
   63049 
   63050   /* Rollback any active transaction and free the handle structure.
   63051   ** The call to sqlite3BtreeRollback() drops any table-locks held by
   63052   ** this handle.
   63053   */
   63054   sqlite3BtreeRollback(p, SQLITE_OK, 0);
   63055   sqlite3BtreeLeave(p);
   63056 
   63057   /* If there are still other outstanding references to the shared-btree
   63058   ** structure, return now. The remainder of this procedure cleans
   63059   ** up the shared-btree.
   63060   */
   63061   assert( p->wantToLock==0 && p->locked==0 );
   63062   if( !p->sharable || removeFromSharingList(pBt) ){
   63063     /* The pBt is no longer on the sharing list, so we can access
   63064     ** it without having to hold the mutex.
   63065     **
   63066     ** Clean out and delete the BtShared object.
   63067     */
   63068     assert( !pBt->pCursor );
   63069     sqlite3PagerClose(pBt->pPager, p->db);
   63070     if( pBt->xFreeSchema && pBt->pSchema ){
   63071       pBt->xFreeSchema(pBt->pSchema);
   63072     }
   63073     sqlite3DbFree(0, pBt->pSchema);
   63074     freeTempSpace(pBt);
   63075     sqlite3_free(pBt);
   63076   }
   63077 
   63078 #ifndef SQLITE_OMIT_SHARED_CACHE
   63079   assert( p->wantToLock==0 );
   63080   assert( p->locked==0 );
   63081   if( p->pPrev ) p->pPrev->pNext = p->pNext;
   63082   if( p->pNext ) p->pNext->pPrev = p->pPrev;
   63083 #endif
   63084 
   63085   sqlite3_free(p);
   63086   return SQLITE_OK;
   63087 }
   63088 
   63089 /*
   63090 ** Change the "soft" limit on the number of pages in the cache.
   63091 ** Unused and unmodified pages will be recycled when the number of
   63092 ** pages in the cache exceeds this soft limit.  But the size of the
   63093 ** cache is allowed to grow larger than this limit if it contains
   63094 ** dirty pages or pages still in active use.
   63095 */
   63096 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
   63097   BtShared *pBt = p->pBt;
   63098   assert( sqlite3_mutex_held(p->db->mutex) );
   63099   sqlite3BtreeEnter(p);
   63100   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
   63101   sqlite3BtreeLeave(p);
   63102   return SQLITE_OK;
   63103 }
   63104 
   63105 /*
   63106 ** Change the "spill" limit on the number of pages in the cache.
   63107 ** If the number of pages exceeds this limit during a write transaction,
   63108 ** the pager might attempt to "spill" pages to the journal early in
   63109 ** order to free up memory.
   63110 **
   63111 ** The value returned is the current spill size.  If zero is passed
   63112 ** as an argument, no changes are made to the spill size setting, so
   63113 ** using mxPage of 0 is a way to query the current spill size.
   63114 */
   63115 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
   63116   BtShared *pBt = p->pBt;
   63117   int res;
   63118   assert( sqlite3_mutex_held(p->db->mutex) );
   63119   sqlite3BtreeEnter(p);
   63120   res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
   63121   sqlite3BtreeLeave(p);
   63122   return res;
   63123 }
   63124 
   63125 #if SQLITE_MAX_MMAP_SIZE>0
   63126 /*
   63127 ** Change the limit on the amount of the database file that may be
   63128 ** memory mapped.
   63129 */
   63130 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
   63131   BtShared *pBt = p->pBt;
   63132   assert( sqlite3_mutex_held(p->db->mutex) );
   63133   sqlite3BtreeEnter(p);
   63134   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
   63135   sqlite3BtreeLeave(p);
   63136   return SQLITE_OK;
   63137 }
   63138 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   63139 
   63140 /*
   63141 ** Change the way data is synced to disk in order to increase or decrease
   63142 ** how well the database resists damage due to OS crashes and power
   63143 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
   63144 ** there is a high probability of damage)  Level 2 is the default.  There
   63145 ** is a very low but non-zero probability of damage.  Level 3 reduces the
   63146 ** probability of damage to near zero but with a write performance reduction.
   63147 */
   63148 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   63149 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
   63150   Btree *p,              /* The btree to set the safety level on */
   63151   unsigned pgFlags       /* Various PAGER_* flags */
   63152 ){
   63153   BtShared *pBt = p->pBt;
   63154   assert( sqlite3_mutex_held(p->db->mutex) );
   63155   sqlite3BtreeEnter(p);
   63156   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
   63157   sqlite3BtreeLeave(p);
   63158   return SQLITE_OK;
   63159 }
   63160 #endif
   63161 
   63162 /*
   63163 ** Change the default pages size and the number of reserved bytes per page.
   63164 ** Or, if the page size has already been fixed, return SQLITE_READONLY
   63165 ** without changing anything.
   63166 **
   63167 ** The page size must be a power of 2 between 512 and 65536.  If the page
   63168 ** size supplied does not meet this constraint then the page size is not
   63169 ** changed.
   63170 **
   63171 ** Page sizes are constrained to be a power of two so that the region
   63172 ** of the database file used for locking (beginning at PENDING_BYTE,
   63173 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
   63174 ** at the beginning of a page.
   63175 **
   63176 ** If parameter nReserve is less than zero, then the number of reserved
   63177 ** bytes per page is left unchanged.
   63178 **
   63179 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
   63180 ** and autovacuum mode can no longer be changed.
   63181 */
   63182 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   63183   int rc = SQLITE_OK;
   63184   BtShared *pBt = p->pBt;
   63185   assert( nReserve>=-1 && nReserve<=255 );
   63186   sqlite3BtreeEnter(p);
   63187 #if SQLITE_HAS_CODEC
   63188   if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
   63189 #endif
   63190   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
   63191     sqlite3BtreeLeave(p);
   63192     return SQLITE_READONLY;
   63193   }
   63194   if( nReserve<0 ){
   63195     nReserve = pBt->pageSize - pBt->usableSize;
   63196   }
   63197   assert( nReserve>=0 && nReserve<=255 );
   63198   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
   63199         ((pageSize-1)&pageSize)==0 ){
   63200     assert( (pageSize & 7)==0 );
   63201     assert( !pBt->pCursor );
   63202     pBt->pageSize = (u32)pageSize;
   63203     freeTempSpace(pBt);
   63204   }
   63205   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   63206   pBt->usableSize = pBt->pageSize - (u16)nReserve;
   63207   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   63208   sqlite3BtreeLeave(p);
   63209   return rc;
   63210 }
   63211 
   63212 /*
   63213 ** Return the currently defined page size
   63214 */
   63215 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
   63216   return p->pBt->pageSize;
   63217 }
   63218 
   63219 /*
   63220 ** This function is similar to sqlite3BtreeGetReserve(), except that it
   63221 ** may only be called if it is guaranteed that the b-tree mutex is already
   63222 ** held.
   63223 **
   63224 ** This is useful in one special case in the backup API code where it is
   63225 ** known that the shared b-tree mutex is held, but the mutex on the
   63226 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
   63227 ** were to be called, it might collide with some other operation on the
   63228 ** database handle that owns *p, causing undefined behavior.
   63229 */
   63230 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
   63231   int n;
   63232   assert( sqlite3_mutex_held(p->pBt->mutex) );
   63233   n = p->pBt->pageSize - p->pBt->usableSize;
   63234   return n;
   63235 }
   63236 
   63237 /*
   63238 ** Return the number of bytes of space at the end of every page that
   63239 ** are intentually left unused.  This is the "reserved" space that is
   63240 ** sometimes used by extensions.
   63241 **
   63242 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
   63243 ** greater of the current reserved space and the maximum requested
   63244 ** reserve space.
   63245 */
   63246 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
   63247   int n;
   63248   sqlite3BtreeEnter(p);
   63249   n = sqlite3BtreeGetReserveNoMutex(p);
   63250 #ifdef SQLITE_HAS_CODEC
   63251   if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
   63252 #endif
   63253   sqlite3BtreeLeave(p);
   63254   return n;
   63255 }
   63256 
   63257 
   63258 /*
   63259 ** Set the maximum page count for a database if mxPage is positive.
   63260 ** No changes are made if mxPage is 0 or negative.
   63261 ** Regardless of the value of mxPage, return the maximum page count.
   63262 */
   63263 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
   63264   int n;
   63265   sqlite3BtreeEnter(p);
   63266   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   63267   sqlite3BtreeLeave(p);
   63268   return n;
   63269 }
   63270 
   63271 /*
   63272 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
   63273 **
   63274 **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
   63275 **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
   63276 **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
   63277 **    newFlag==(-1)    No changes
   63278 **
   63279 ** This routine acts as a query if newFlag is less than zero
   63280 **
   63281 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
   63282 ** freelist leaf pages are not written back to the database.  Thus in-page
   63283 ** deleted content is cleared, but freelist deleted content is not.
   63284 **
   63285 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
   63286 ** that freelist leaf pages are written back into the database, increasing
   63287 ** the amount of disk I/O.
   63288 */
   63289 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
   63290   int b;
   63291   if( p==0 ) return 0;
   63292   sqlite3BtreeEnter(p);
   63293   assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
   63294   assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
   63295   if( newFlag>=0 ){
   63296     p->pBt->btsFlags &= ~BTS_FAST_SECURE;
   63297     p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
   63298   }
   63299   b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
   63300   sqlite3BtreeLeave(p);
   63301   return b;
   63302 }
   63303 
   63304 /*
   63305 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
   63306 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
   63307 ** is disabled. The default value for the auto-vacuum property is
   63308 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
   63309 */
   63310 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
   63311 #ifdef SQLITE_OMIT_AUTOVACUUM
   63312   return SQLITE_READONLY;
   63313 #else
   63314   BtShared *pBt = p->pBt;
   63315   int rc = SQLITE_OK;
   63316   u8 av = (u8)autoVacuum;
   63317 
   63318   sqlite3BtreeEnter(p);
   63319   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
   63320     rc = SQLITE_READONLY;
   63321   }else{
   63322     pBt->autoVacuum = av ?1:0;
   63323     pBt->incrVacuum = av==2 ?1:0;
   63324   }
   63325   sqlite3BtreeLeave(p);
   63326   return rc;
   63327 #endif
   63328 }
   63329 
   63330 /*
   63331 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
   63332 ** enabled 1 is returned. Otherwise 0.
   63333 */
   63334 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
   63335 #ifdef SQLITE_OMIT_AUTOVACUUM
   63336   return BTREE_AUTOVACUUM_NONE;
   63337 #else
   63338   int rc;
   63339   sqlite3BtreeEnter(p);
   63340   rc = (
   63341     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
   63342     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
   63343     BTREE_AUTOVACUUM_INCR
   63344   );
   63345   sqlite3BtreeLeave(p);
   63346   return rc;
   63347 #endif
   63348 }
   63349 
   63350 /*
   63351 ** If the user has not set the safety-level for this database connection
   63352 ** using "PRAGMA synchronous", and if the safety-level is not already
   63353 ** set to the value passed to this function as the second parameter,
   63354 ** set it so.
   63355 */
   63356 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
   63357     && !defined(SQLITE_OMIT_WAL)
   63358 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
   63359   sqlite3 *db;
   63360   Db *pDb;
   63361   if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
   63362     while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
   63363     if( pDb->bSyncSet==0
   63364      && pDb->safety_level!=safety_level
   63365      && pDb!=&db->aDb[1]
   63366     ){
   63367       pDb->safety_level = safety_level;
   63368       sqlite3PagerSetFlags(pBt->pPager,
   63369           pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
   63370     }
   63371   }
   63372 }
   63373 #else
   63374 # define setDefaultSyncFlag(pBt,safety_level)
   63375 #endif
   63376 
   63377 /*
   63378 ** Get a reference to pPage1 of the database file.  This will
   63379 ** also acquire a readlock on that file.
   63380 **
   63381 ** SQLITE_OK is returned on success.  If the file is not a
   63382 ** well-formed database file, then SQLITE_CORRUPT is returned.
   63383 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
   63384 ** is returned if we run out of memory.
   63385 */
   63386 static int lockBtree(BtShared *pBt){
   63387   int rc;              /* Result code from subfunctions */
   63388   MemPage *pPage1;     /* Page 1 of the database file */
   63389   int nPage;           /* Number of pages in the database */
   63390   int nPageFile = 0;   /* Number of pages in the database file */
   63391   int nPageHeader;     /* Number of pages in the database according to hdr */
   63392 
   63393   assert( sqlite3_mutex_held(pBt->mutex) );
   63394   assert( pBt->pPage1==0 );
   63395   rc = sqlite3PagerSharedLock(pBt->pPager);
   63396   if( rc!=SQLITE_OK ) return rc;
   63397   rc = btreeGetPage(pBt, 1, &pPage1, 0);
   63398   if( rc!=SQLITE_OK ) return rc;
   63399 
   63400   /* Do some checking to help insure the file we opened really is
   63401   ** a valid database file.
   63402   */
   63403   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
   63404   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
   63405   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
   63406     nPage = nPageFile;
   63407   }
   63408   if( nPage>0 ){
   63409     u32 pageSize;
   63410     u32 usableSize;
   63411     u8 *page1 = pPage1->aData;
   63412     rc = SQLITE_NOTADB;
   63413     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
   63414     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
   63415     ** 61 74 20 33 00. */
   63416     if( memcmp(page1, zMagicHeader, 16)!=0 ){
   63417       goto page1_init_failed;
   63418     }
   63419 
   63420 #ifdef SQLITE_OMIT_WAL
   63421     if( page1[18]>1 ){
   63422       pBt->btsFlags |= BTS_READ_ONLY;
   63423     }
   63424     if( page1[19]>1 ){
   63425       goto page1_init_failed;
   63426     }
   63427 #else
   63428     if( page1[18]>2 ){
   63429       pBt->btsFlags |= BTS_READ_ONLY;
   63430     }
   63431     if( page1[19]>2 ){
   63432       goto page1_init_failed;
   63433     }
   63434 
   63435     /* If the write version is set to 2, this database should be accessed
   63436     ** in WAL mode. If the log is not already open, open it now. Then
   63437     ** return SQLITE_OK and return without populating BtShared.pPage1.
   63438     ** The caller detects this and calls this function again. This is
   63439     ** required as the version of page 1 currently in the page1 buffer
   63440     ** may not be the latest version - there may be a newer one in the log
   63441     ** file.
   63442     */
   63443     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
   63444       int isOpen = 0;
   63445       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
   63446       if( rc!=SQLITE_OK ){
   63447         goto page1_init_failed;
   63448       }else{
   63449         setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
   63450         if( isOpen==0 ){
   63451           releasePageOne(pPage1);
   63452           return SQLITE_OK;
   63453         }
   63454       }
   63455       rc = SQLITE_NOTADB;
   63456     }else{
   63457       setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
   63458     }
   63459 #endif
   63460 
   63461     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
   63462     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
   63463     **
   63464     ** The original design allowed these amounts to vary, but as of
   63465     ** version 3.6.0, we require them to be fixed.
   63466     */
   63467     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
   63468       goto page1_init_failed;
   63469     }
   63470     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
   63471     ** determined by the 2-byte integer located at an offset of 16 bytes from
   63472     ** the beginning of the database file. */
   63473     pageSize = (page1[16]<<8) | (page1[17]<<16);
   63474     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
   63475     ** between 512 and 65536 inclusive. */
   63476     if( ((pageSize-1)&pageSize)!=0
   63477      || pageSize>SQLITE_MAX_PAGE_SIZE
   63478      || pageSize<=256
   63479     ){
   63480       goto page1_init_failed;
   63481     }
   63482     assert( (pageSize & 7)==0 );
   63483     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
   63484     ** integer at offset 20 is the number of bytes of space at the end of
   63485     ** each page to reserve for extensions.
   63486     **
   63487     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
   63488     ** determined by the one-byte unsigned integer found at an offset of 20
   63489     ** into the database file header. */
   63490     usableSize = pageSize - page1[20];
   63491     if( (u32)pageSize!=pBt->pageSize ){
   63492       /* After reading the first page of the database assuming a page size
   63493       ** of BtShared.pageSize, we have discovered that the page-size is
   63494       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
   63495       ** zero and return SQLITE_OK. The caller will call this function
   63496       ** again with the correct page-size.
   63497       */
   63498       releasePageOne(pPage1);
   63499       pBt->usableSize = usableSize;
   63500       pBt->pageSize = pageSize;
   63501       freeTempSpace(pBt);
   63502       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
   63503                                    pageSize-usableSize);
   63504       return rc;
   63505     }
   63506     if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
   63507       rc = SQLITE_CORRUPT_BKPT;
   63508       goto page1_init_failed;
   63509     }
   63510     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
   63511     ** be less than 480. In other words, if the page size is 512, then the
   63512     ** reserved space size cannot exceed 32. */
   63513     if( usableSize<480 ){
   63514       goto page1_init_failed;
   63515     }
   63516     pBt->pageSize = pageSize;
   63517     pBt->usableSize = usableSize;
   63518 #ifndef SQLITE_OMIT_AUTOVACUUM
   63519     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
   63520     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
   63521 #endif
   63522   }
   63523 
   63524   /* maxLocal is the maximum amount of payload to store locally for
   63525   ** a cell.  Make sure it is small enough so that at least minFanout
   63526   ** cells can will fit on one page.  We assume a 10-byte page header.
   63527   ** Besides the payload, the cell must store:
   63528   **     2-byte pointer to the cell
   63529   **     4-byte child pointer
   63530   **     9-byte nKey value
   63531   **     4-byte nData value
   63532   **     4-byte overflow page pointer
   63533   ** So a cell consists of a 2-byte pointer, a header which is as much as
   63534   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
   63535   ** page pointer.
   63536   */
   63537   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
   63538   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
   63539   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
   63540   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
   63541   if( pBt->maxLocal>127 ){
   63542     pBt->max1bytePayload = 127;
   63543   }else{
   63544     pBt->max1bytePayload = (u8)pBt->maxLocal;
   63545   }
   63546   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
   63547   pBt->pPage1 = pPage1;
   63548   pBt->nPage = nPage;
   63549   return SQLITE_OK;
   63550 
   63551 page1_init_failed:
   63552   releasePageOne(pPage1);
   63553   pBt->pPage1 = 0;
   63554   return rc;
   63555 }
   63556 
   63557 #ifndef NDEBUG
   63558 /*
   63559 ** Return the number of cursors open on pBt. This is for use
   63560 ** in assert() expressions, so it is only compiled if NDEBUG is not
   63561 ** defined.
   63562 **
   63563 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
   63564 ** false then all cursors are counted.
   63565 **
   63566 ** For the purposes of this routine, a cursor is any cursor that
   63567 ** is capable of reading or writing to the database.  Cursors that
   63568 ** have been tripped into the CURSOR_FAULT state are not counted.
   63569 */
   63570 static int countValidCursors(BtShared *pBt, int wrOnly){
   63571   BtCursor *pCur;
   63572   int r = 0;
   63573   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
   63574     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
   63575      && pCur->eState!=CURSOR_FAULT ) r++;
   63576   }
   63577   return r;
   63578 }
   63579 #endif
   63580 
   63581 /*
   63582 ** If there are no outstanding cursors and we are not in the middle
   63583 ** of a transaction but there is a read lock on the database, then
   63584 ** this routine unrefs the first page of the database file which
   63585 ** has the effect of releasing the read lock.
   63586 **
   63587 ** If there is a transaction in progress, this routine is a no-op.
   63588 */
   63589 static void unlockBtreeIfUnused(BtShared *pBt){
   63590   assert( sqlite3_mutex_held(pBt->mutex) );
   63591   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
   63592   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
   63593     MemPage *pPage1 = pBt->pPage1;
   63594     assert( pPage1->aData );
   63595     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
   63596     pBt->pPage1 = 0;
   63597     releasePageOne(pPage1);
   63598   }
   63599 }
   63600 
   63601 /*
   63602 ** If pBt points to an empty file then convert that empty file
   63603 ** into a new empty database by initializing the first page of
   63604 ** the database.
   63605 */
   63606 static int newDatabase(BtShared *pBt){
   63607   MemPage *pP1;
   63608   unsigned char *data;
   63609   int rc;
   63610 
   63611   assert( sqlite3_mutex_held(pBt->mutex) );
   63612   if( pBt->nPage>0 ){
   63613     return SQLITE_OK;
   63614   }
   63615   pP1 = pBt->pPage1;
   63616   assert( pP1!=0 );
   63617   data = pP1->aData;
   63618   rc = sqlite3PagerWrite(pP1->pDbPage);
   63619   if( rc ) return rc;
   63620   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
   63621   assert( sizeof(zMagicHeader)==16 );
   63622   data[16] = (u8)((pBt->pageSize>>8)&0xff);
   63623   data[17] = (u8)((pBt->pageSize>>16)&0xff);
   63624   data[18] = 1;
   63625   data[19] = 1;
   63626   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
   63627   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
   63628   data[21] = 64;
   63629   data[22] = 32;
   63630   data[23] = 32;
   63631   memset(&data[24], 0, 100-24);
   63632   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
   63633   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   63634 #ifndef SQLITE_OMIT_AUTOVACUUM
   63635   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
   63636   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
   63637   put4byte(&data[36 + 4*4], pBt->autoVacuum);
   63638   put4byte(&data[36 + 7*4], pBt->incrVacuum);
   63639 #endif
   63640   pBt->nPage = 1;
   63641   data[31] = 1;
   63642   return SQLITE_OK;
   63643 }
   63644 
   63645 /*
   63646 ** Initialize the first page of the database file (creating a database
   63647 ** consisting of a single page and no schema objects). Return SQLITE_OK
   63648 ** if successful, or an SQLite error code otherwise.
   63649 */
   63650 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
   63651   int rc;
   63652   sqlite3BtreeEnter(p);
   63653   p->pBt->nPage = 0;
   63654   rc = newDatabase(p->pBt);
   63655   sqlite3BtreeLeave(p);
   63656   return rc;
   63657 }
   63658 
   63659 /*
   63660 ** Attempt to start a new transaction. A write-transaction
   63661 ** is started if the second argument is nonzero, otherwise a read-
   63662 ** transaction.  If the second argument is 2 or more and exclusive
   63663 ** transaction is started, meaning that no other process is allowed
   63664 ** to access the database.  A preexisting transaction may not be
   63665 ** upgraded to exclusive by calling this routine a second time - the
   63666 ** exclusivity flag only works for a new transaction.
   63667 **
   63668 ** A write-transaction must be started before attempting any
   63669 ** changes to the database.  None of the following routines
   63670 ** will work unless a transaction is started first:
   63671 **
   63672 **      sqlite3BtreeCreateTable()
   63673 **      sqlite3BtreeCreateIndex()
   63674 **      sqlite3BtreeClearTable()
   63675 **      sqlite3BtreeDropTable()
   63676 **      sqlite3BtreeInsert()
   63677 **      sqlite3BtreeDelete()
   63678 **      sqlite3BtreeUpdateMeta()
   63679 **
   63680 ** If an initial attempt to acquire the lock fails because of lock contention
   63681 ** and the database was previously unlocked, then invoke the busy handler
   63682 ** if there is one.  But if there was previously a read-lock, do not
   63683 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
   63684 ** returned when there is already a read-lock in order to avoid a deadlock.
   63685 **
   63686 ** Suppose there are two processes A and B.  A has a read lock and B has
   63687 ** a reserved lock.  B tries to promote to exclusive but is blocked because
   63688 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
   63689 ** One or the other of the two processes must give way or there can be
   63690 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
   63691 ** when A already has a read lock, we encourage A to give up and let B
   63692 ** proceed.
   63693 */
   63694 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
   63695   BtShared *pBt = p->pBt;
   63696   int rc = SQLITE_OK;
   63697 
   63698   sqlite3BtreeEnter(p);
   63699   btreeIntegrity(p);
   63700 
   63701   /* If the btree is already in a write-transaction, or it
   63702   ** is already in a read-transaction and a read-transaction
   63703   ** is requested, this is a no-op.
   63704   */
   63705   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
   63706     goto trans_begun;
   63707   }
   63708   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
   63709 
   63710   /* Write transactions are not possible on a read-only database */
   63711   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
   63712     rc = SQLITE_READONLY;
   63713     goto trans_begun;
   63714   }
   63715 
   63716 #ifndef SQLITE_OMIT_SHARED_CACHE
   63717   {
   63718     sqlite3 *pBlock = 0;
   63719     /* If another database handle has already opened a write transaction
   63720     ** on this shared-btree structure and a second write transaction is
   63721     ** requested, return SQLITE_LOCKED.
   63722     */
   63723     if( (wrflag && pBt->inTransaction==TRANS_WRITE)
   63724      || (pBt->btsFlags & BTS_PENDING)!=0
   63725     ){
   63726       pBlock = pBt->pWriter->db;
   63727     }else if( wrflag>1 ){
   63728       BtLock *pIter;
   63729       for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   63730         if( pIter->pBtree!=p ){
   63731           pBlock = pIter->pBtree->db;
   63732           break;
   63733         }
   63734       }
   63735     }
   63736     if( pBlock ){
   63737       sqlite3ConnectionBlocked(p->db, pBlock);
   63738       rc = SQLITE_LOCKED_SHAREDCACHE;
   63739       goto trans_begun;
   63740     }
   63741   }
   63742 #endif
   63743 
   63744   /* Any read-only or read-write transaction implies a read-lock on
   63745   ** page 1. So if some other shared-cache client already has a write-lock
   63746   ** on page 1, the transaction cannot be opened. */
   63747   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   63748   if( SQLITE_OK!=rc ) goto trans_begun;
   63749 
   63750   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
   63751   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
   63752   do {
   63753     /* Call lockBtree() until either pBt->pPage1 is populated or
   63754     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
   63755     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
   63756     ** reading page 1 it discovers that the page-size of the database
   63757     ** file is not pBt->pageSize. In this case lockBtree() will update
   63758     ** pBt->pageSize to the page-size of the file on disk.
   63759     */
   63760     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
   63761 
   63762     if( rc==SQLITE_OK && wrflag ){
   63763       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
   63764         rc = SQLITE_READONLY;
   63765       }else{
   63766         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
   63767         if( rc==SQLITE_OK ){
   63768           rc = newDatabase(pBt);
   63769         }
   63770       }
   63771     }
   63772 
   63773     if( rc!=SQLITE_OK ){
   63774       unlockBtreeIfUnused(pBt);
   63775     }
   63776   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
   63777           btreeInvokeBusyHandler(pBt) );
   63778 
   63779   if( rc==SQLITE_OK ){
   63780     if( p->inTrans==TRANS_NONE ){
   63781       pBt->nTransaction++;
   63782 #ifndef SQLITE_OMIT_SHARED_CACHE
   63783       if( p->sharable ){
   63784         assert( p->lock.pBtree==p && p->lock.iTable==1 );
   63785         p->lock.eLock = READ_LOCK;
   63786         p->lock.pNext = pBt->pLock;
   63787         pBt->pLock = &p->lock;
   63788       }
   63789 #endif
   63790     }
   63791     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
   63792     if( p->inTrans>pBt->inTransaction ){
   63793       pBt->inTransaction = p->inTrans;
   63794     }
   63795     if( wrflag ){
   63796       MemPage *pPage1 = pBt->pPage1;
   63797 #ifndef SQLITE_OMIT_SHARED_CACHE
   63798       assert( !pBt->pWriter );
   63799       pBt->pWriter = p;
   63800       pBt->btsFlags &= ~BTS_EXCLUSIVE;
   63801       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
   63802 #endif
   63803 
   63804       /* If the db-size header field is incorrect (as it may be if an old
   63805       ** client has been writing the database file), update it now. Doing
   63806       ** this sooner rather than later means the database size can safely
   63807       ** re-read the database size from page 1 if a savepoint or transaction
   63808       ** rollback occurs within the transaction.
   63809       */
   63810       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
   63811         rc = sqlite3PagerWrite(pPage1->pDbPage);
   63812         if( rc==SQLITE_OK ){
   63813           put4byte(&pPage1->aData[28], pBt->nPage);
   63814         }
   63815       }
   63816     }
   63817   }
   63818 
   63819 
   63820 trans_begun:
   63821   if( rc==SQLITE_OK && wrflag ){
   63822     /* This call makes sure that the pager has the correct number of
   63823     ** open savepoints. If the second parameter is greater than 0 and
   63824     ** the sub-journal is not already open, then it will be opened here.
   63825     */
   63826     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
   63827   }
   63828 
   63829   btreeIntegrity(p);
   63830   sqlite3BtreeLeave(p);
   63831   return rc;
   63832 }
   63833 
   63834 #ifndef SQLITE_OMIT_AUTOVACUUM
   63835 
   63836 /*
   63837 ** Set the pointer-map entries for all children of page pPage. Also, if
   63838 ** pPage contains cells that point to overflow pages, set the pointer
   63839 ** map entries for the overflow pages as well.
   63840 */
   63841 static int setChildPtrmaps(MemPage *pPage){
   63842   int i;                             /* Counter variable */
   63843   int nCell;                         /* Number of cells in page pPage */
   63844   int rc;                            /* Return code */
   63845   BtShared *pBt = pPage->pBt;
   63846   Pgno pgno = pPage->pgno;
   63847 
   63848   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   63849   rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
   63850   if( rc!=SQLITE_OK ) return rc;
   63851   nCell = pPage->nCell;
   63852 
   63853   for(i=0; i<nCell; i++){
   63854     u8 *pCell = findCell(pPage, i);
   63855 
   63856     ptrmapPutOvflPtr(pPage, pCell, &rc);
   63857 
   63858     if( !pPage->leaf ){
   63859       Pgno childPgno = get4byte(pCell);
   63860       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   63861     }
   63862   }
   63863 
   63864   if( !pPage->leaf ){
   63865     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   63866     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   63867   }
   63868 
   63869   return rc;
   63870 }
   63871 
   63872 /*
   63873 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
   63874 ** that it points to iTo. Parameter eType describes the type of pointer to
   63875 ** be modified, as  follows:
   63876 **
   63877 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
   63878 **                   page of pPage.
   63879 **
   63880 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
   63881 **                   page pointed to by one of the cells on pPage.
   63882 **
   63883 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
   63884 **                   overflow page in the list.
   63885 */
   63886 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
   63887   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   63888   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   63889   if( eType==PTRMAP_OVERFLOW2 ){
   63890     /* The pointer is always the first 4 bytes of the page in this case.  */
   63891     if( get4byte(pPage->aData)!=iFrom ){
   63892       return SQLITE_CORRUPT_PAGE(pPage);
   63893     }
   63894     put4byte(pPage->aData, iTo);
   63895   }else{
   63896     int i;
   63897     int nCell;
   63898     int rc;
   63899 
   63900     rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
   63901     if( rc ) return rc;
   63902     nCell = pPage->nCell;
   63903 
   63904     for(i=0; i<nCell; i++){
   63905       u8 *pCell = findCell(pPage, i);
   63906       if( eType==PTRMAP_OVERFLOW1 ){
   63907         CellInfo info;
   63908         pPage->xParseCell(pPage, pCell, &info);
   63909         if( info.nLocal<info.nPayload ){
   63910           if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
   63911             return SQLITE_CORRUPT_PAGE(pPage);
   63912           }
   63913           if( iFrom==get4byte(pCell+info.nSize-4) ){
   63914             put4byte(pCell+info.nSize-4, iTo);
   63915             break;
   63916           }
   63917         }
   63918       }else{
   63919         if( get4byte(pCell)==iFrom ){
   63920           put4byte(pCell, iTo);
   63921           break;
   63922         }
   63923       }
   63924     }
   63925 
   63926     if( i==nCell ){
   63927       if( eType!=PTRMAP_BTREE ||
   63928           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
   63929         return SQLITE_CORRUPT_PAGE(pPage);
   63930       }
   63931       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
   63932     }
   63933   }
   63934   return SQLITE_OK;
   63935 }
   63936 
   63937 
   63938 /*
   63939 ** Move the open database page pDbPage to location iFreePage in the
   63940 ** database. The pDbPage reference remains valid.
   63941 **
   63942 ** The isCommit flag indicates that there is no need to remember that
   63943 ** the journal needs to be sync()ed before database page pDbPage->pgno
   63944 ** can be written to. The caller has already promised not to write to that
   63945 ** page.
   63946 */
   63947 static int relocatePage(
   63948   BtShared *pBt,           /* Btree */
   63949   MemPage *pDbPage,        /* Open page to move */
   63950   u8 eType,                /* Pointer map 'type' entry for pDbPage */
   63951   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
   63952   Pgno iFreePage,          /* The location to move pDbPage to */
   63953   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
   63954 ){
   63955   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
   63956   Pgno iDbPage = pDbPage->pgno;
   63957   Pager *pPager = pBt->pPager;
   63958   int rc;
   63959 
   63960   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
   63961       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   63962   assert( sqlite3_mutex_held(pBt->mutex) );
   63963   assert( pDbPage->pBt==pBt );
   63964 
   63965   /* Move page iDbPage from its current location to page number iFreePage */
   63966   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
   63967       iDbPage, iFreePage, iPtrPage, eType));
   63968   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   63969   if( rc!=SQLITE_OK ){
   63970     return rc;
   63971   }
   63972   pDbPage->pgno = iFreePage;
   63973 
   63974   /* If pDbPage was a btree-page, then it may have child pages and/or cells
   63975   ** that point to overflow pages. The pointer map entries for all these
   63976   ** pages need to be changed.
   63977   **
   63978   ** If pDbPage is an overflow page, then the first 4 bytes may store a
   63979   ** pointer to a subsequent overflow page. If this is the case, then
   63980   ** the pointer map needs to be updated for the subsequent overflow page.
   63981   */
   63982   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
   63983     rc = setChildPtrmaps(pDbPage);
   63984     if( rc!=SQLITE_OK ){
   63985       return rc;
   63986     }
   63987   }else{
   63988     Pgno nextOvfl = get4byte(pDbPage->aData);
   63989     if( nextOvfl!=0 ){
   63990       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
   63991       if( rc!=SQLITE_OK ){
   63992         return rc;
   63993       }
   63994     }
   63995   }
   63996 
   63997   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
   63998   ** that it points at iFreePage. Also fix the pointer map entry for
   63999   ** iPtrPage.
   64000   */
   64001   if( eType!=PTRMAP_ROOTPAGE ){
   64002     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
   64003     if( rc!=SQLITE_OK ){
   64004       return rc;
   64005     }
   64006     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
   64007     if( rc!=SQLITE_OK ){
   64008       releasePage(pPtrPage);
   64009       return rc;
   64010     }
   64011     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
   64012     releasePage(pPtrPage);
   64013     if( rc==SQLITE_OK ){
   64014       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
   64015     }
   64016   }
   64017   return rc;
   64018 }
   64019 
   64020 /* Forward declaration required by incrVacuumStep(). */
   64021 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
   64022 
   64023 /*
   64024 ** Perform a single step of an incremental-vacuum. If successful, return
   64025 ** SQLITE_OK. If there is no work to do (and therefore no point in
   64026 ** calling this function again), return SQLITE_DONE. Or, if an error
   64027 ** occurs, return some other error code.
   64028 **
   64029 ** More specifically, this function attempts to re-organize the database so
   64030 ** that the last page of the file currently in use is no longer in use.
   64031 **
   64032 ** Parameter nFin is the number of pages that this database would contain
   64033 ** were this function called until it returns SQLITE_DONE.
   64034 **
   64035 ** If the bCommit parameter is non-zero, this function assumes that the
   64036 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
   64037 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
   64038 ** operation, or false for an incremental vacuum.
   64039 */
   64040 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
   64041   Pgno nFreeList;           /* Number of pages still on the free-list */
   64042   int rc;
   64043 
   64044   assert( sqlite3_mutex_held(pBt->mutex) );
   64045   assert( iLastPg>nFin );
   64046 
   64047   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
   64048     u8 eType;
   64049     Pgno iPtrPage;
   64050 
   64051     nFreeList = get4byte(&pBt->pPage1->aData[36]);
   64052     if( nFreeList==0 ){
   64053       return SQLITE_DONE;
   64054     }
   64055 
   64056     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
   64057     if( rc!=SQLITE_OK ){
   64058       return rc;
   64059     }
   64060     if( eType==PTRMAP_ROOTPAGE ){
   64061       return SQLITE_CORRUPT_BKPT;
   64062     }
   64063 
   64064     if( eType==PTRMAP_FREEPAGE ){
   64065       if( bCommit==0 ){
   64066         /* Remove the page from the files free-list. This is not required
   64067         ** if bCommit is non-zero. In that case, the free-list will be
   64068         ** truncated to zero after this function returns, so it doesn't
   64069         ** matter if it still contains some garbage entries.
   64070         */
   64071         Pgno iFreePg;
   64072         MemPage *pFreePg;
   64073         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
   64074         if( rc!=SQLITE_OK ){
   64075           return rc;
   64076         }
   64077         assert( iFreePg==iLastPg );
   64078         releasePage(pFreePg);
   64079       }
   64080     } else {
   64081       Pgno iFreePg;             /* Index of free page to move pLastPg to */
   64082       MemPage *pLastPg;
   64083       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
   64084       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
   64085 
   64086       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
   64087       if( rc!=SQLITE_OK ){
   64088         return rc;
   64089       }
   64090 
   64091       /* If bCommit is zero, this loop runs exactly once and page pLastPg
   64092       ** is swapped with the first free page pulled off the free list.
   64093       **
   64094       ** On the other hand, if bCommit is greater than zero, then keep
   64095       ** looping until a free-page located within the first nFin pages
   64096       ** of the file is found.
   64097       */
   64098       if( bCommit==0 ){
   64099         eMode = BTALLOC_LE;
   64100         iNear = nFin;
   64101       }
   64102       do {
   64103         MemPage *pFreePg;
   64104         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
   64105         if( rc!=SQLITE_OK ){
   64106           releasePage(pLastPg);
   64107           return rc;
   64108         }
   64109         releasePage(pFreePg);
   64110       }while( bCommit && iFreePg>nFin );
   64111       assert( iFreePg<iLastPg );
   64112 
   64113       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
   64114       releasePage(pLastPg);
   64115       if( rc!=SQLITE_OK ){
   64116         return rc;
   64117       }
   64118     }
   64119   }
   64120 
   64121   if( bCommit==0 ){
   64122     do {
   64123       iLastPg--;
   64124     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
   64125     pBt->bDoTruncate = 1;
   64126     pBt->nPage = iLastPg;
   64127   }
   64128   return SQLITE_OK;
   64129 }
   64130 
   64131 /*
   64132 ** The database opened by the first argument is an auto-vacuum database
   64133 ** nOrig pages in size containing nFree free pages. Return the expected
   64134 ** size of the database in pages following an auto-vacuum operation.
   64135 */
   64136 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
   64137   int nEntry;                     /* Number of entries on one ptrmap page */
   64138   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
   64139   Pgno nFin;                      /* Return value */
   64140 
   64141   nEntry = pBt->usableSize/5;
   64142   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
   64143   nFin = nOrig - nFree - nPtrmap;
   64144   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
   64145     nFin--;
   64146   }
   64147   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
   64148     nFin--;
   64149   }
   64150 
   64151   return nFin;
   64152 }
   64153 
   64154 /*
   64155 ** A write-transaction must be opened before calling this function.
   64156 ** It performs a single unit of work towards an incremental vacuum.
   64157 **
   64158 ** If the incremental vacuum is finished after this function has run,
   64159 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
   64160 ** SQLITE_OK is returned. Otherwise an SQLite error code.
   64161 */
   64162 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   64163   int rc;
   64164   BtShared *pBt = p->pBt;
   64165 
   64166   sqlite3BtreeEnter(p);
   64167   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
   64168   if( !pBt->autoVacuum ){
   64169     rc = SQLITE_DONE;
   64170   }else{
   64171     Pgno nOrig = btreePagecount(pBt);
   64172     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
   64173     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
   64174 
   64175     if( nOrig<nFin ){
   64176       rc = SQLITE_CORRUPT_BKPT;
   64177     }else if( nFree>0 ){
   64178       rc = saveAllCursors(pBt, 0, 0);
   64179       if( rc==SQLITE_OK ){
   64180         invalidateAllOverflowCache(pBt);
   64181         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
   64182       }
   64183       if( rc==SQLITE_OK ){
   64184         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   64185         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
   64186       }
   64187     }else{
   64188       rc = SQLITE_DONE;
   64189     }
   64190   }
   64191   sqlite3BtreeLeave(p);
   64192   return rc;
   64193 }
   64194 
   64195 /*
   64196 ** This routine is called prior to sqlite3PagerCommit when a transaction
   64197 ** is committed for an auto-vacuum database.
   64198 **
   64199 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
   64200 ** the database file should be truncated to during the commit process.
   64201 ** i.e. the database has been reorganized so that only the first *pnTrunc
   64202 ** pages are in use.
   64203 */
   64204 static int autoVacuumCommit(BtShared *pBt){
   64205   int rc = SQLITE_OK;
   64206   Pager *pPager = pBt->pPager;
   64207   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
   64208 
   64209   assert( sqlite3_mutex_held(pBt->mutex) );
   64210   invalidateAllOverflowCache(pBt);
   64211   assert(pBt->autoVacuum);
   64212   if( !pBt->incrVacuum ){
   64213     Pgno nFin;         /* Number of pages in database after autovacuuming */
   64214     Pgno nFree;        /* Number of pages on the freelist initially */
   64215     Pgno iFree;        /* The next page to be freed */
   64216     Pgno nOrig;        /* Database size before freeing */
   64217 
   64218     nOrig = btreePagecount(pBt);
   64219     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
   64220       /* It is not possible to create a database for which the final page
   64221       ** is either a pointer-map page or the pending-byte page. If one
   64222       ** is encountered, this indicates corruption.
   64223       */
   64224       return SQLITE_CORRUPT_BKPT;
   64225     }
   64226 
   64227     nFree = get4byte(&pBt->pPage1->aData[36]);
   64228     nFin = finalDbSize(pBt, nOrig, nFree);
   64229     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
   64230     if( nFin<nOrig ){
   64231       rc = saveAllCursors(pBt, 0, 0);
   64232     }
   64233     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
   64234       rc = incrVacuumStep(pBt, nFin, iFree, 1);
   64235     }
   64236     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
   64237       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   64238       put4byte(&pBt->pPage1->aData[32], 0);
   64239       put4byte(&pBt->pPage1->aData[36], 0);
   64240       put4byte(&pBt->pPage1->aData[28], nFin);
   64241       pBt->bDoTruncate = 1;
   64242       pBt->nPage = nFin;
   64243     }
   64244     if( rc!=SQLITE_OK ){
   64245       sqlite3PagerRollback(pPager);
   64246     }
   64247   }
   64248 
   64249   assert( nRef>=sqlite3PagerRefcount(pPager) );
   64250   return rc;
   64251 }
   64252 
   64253 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
   64254 # define setChildPtrmaps(x) SQLITE_OK
   64255 #endif
   64256 
   64257 /*
   64258 ** This routine does the first phase of a two-phase commit.  This routine
   64259 ** causes a rollback journal to be created (if it does not already exist)
   64260 ** and populated with enough information so that if a power loss occurs
   64261 ** the database can be restored to its original state by playing back
   64262 ** the journal.  Then the contents of the journal are flushed out to
   64263 ** the disk.  After the journal is safely on oxide, the changes to the
   64264 ** database are written into the database file and flushed to oxide.
   64265 ** At the end of this call, the rollback journal still exists on the
   64266 ** disk and we are still holding all locks, so the transaction has not
   64267 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
   64268 ** commit process.
   64269 **
   64270 ** This call is a no-op if no write-transaction is currently active on pBt.
   64271 **
   64272 ** Otherwise, sync the database file for the btree pBt. zMaster points to
   64273 ** the name of a master journal file that should be written into the
   64274 ** individual journal file, or is NULL, indicating no master journal file
   64275 ** (single database transaction).
   64276 **
   64277 ** When this is called, the master journal should already have been
   64278 ** created, populated with this journal pointer and synced to disk.
   64279 **
   64280 ** Once this is routine has returned, the only thing required to commit
   64281 ** the write-transaction for this database file is to delete the journal.
   64282 */
   64283 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
   64284   int rc = SQLITE_OK;
   64285   if( p->inTrans==TRANS_WRITE ){
   64286     BtShared *pBt = p->pBt;
   64287     sqlite3BtreeEnter(p);
   64288 #ifndef SQLITE_OMIT_AUTOVACUUM
   64289     if( pBt->autoVacuum ){
   64290       rc = autoVacuumCommit(pBt);
   64291       if( rc!=SQLITE_OK ){
   64292         sqlite3BtreeLeave(p);
   64293         return rc;
   64294       }
   64295     }
   64296     if( pBt->bDoTruncate ){
   64297       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
   64298     }
   64299 #endif
   64300     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
   64301     sqlite3BtreeLeave(p);
   64302   }
   64303   return rc;
   64304 }
   64305 
   64306 /*
   64307 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
   64308 ** at the conclusion of a transaction.
   64309 */
   64310 static void btreeEndTransaction(Btree *p){
   64311   BtShared *pBt = p->pBt;
   64312   sqlite3 *db = p->db;
   64313   assert( sqlite3BtreeHoldsMutex(p) );
   64314 
   64315 #ifndef SQLITE_OMIT_AUTOVACUUM
   64316   pBt->bDoTruncate = 0;
   64317 #endif
   64318   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
   64319     /* If there are other active statements that belong to this database
   64320     ** handle, downgrade to a read-only transaction. The other statements
   64321     ** may still be reading from the database.  */
   64322     downgradeAllSharedCacheTableLocks(p);
   64323     p->inTrans = TRANS_READ;
   64324   }else{
   64325     /* If the handle had any kind of transaction open, decrement the
   64326     ** transaction count of the shared btree. If the transaction count
   64327     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
   64328     ** call below will unlock the pager.  */
   64329     if( p->inTrans!=TRANS_NONE ){
   64330       clearAllSharedCacheTableLocks(p);
   64331       pBt->nTransaction--;
   64332       if( 0==pBt->nTransaction ){
   64333         pBt->inTransaction = TRANS_NONE;
   64334       }
   64335     }
   64336 
   64337     /* Set the current transaction state to TRANS_NONE and unlock the
   64338     ** pager if this call closed the only read or write transaction.  */
   64339     p->inTrans = TRANS_NONE;
   64340     unlockBtreeIfUnused(pBt);
   64341   }
   64342 
   64343   btreeIntegrity(p);
   64344 }
   64345 
   64346 /*
   64347 ** Commit the transaction currently in progress.
   64348 **
   64349 ** This routine implements the second phase of a 2-phase commit.  The
   64350 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
   64351 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
   64352 ** routine did all the work of writing information out to disk and flushing the
   64353 ** contents so that they are written onto the disk platter.  All this
   64354 ** routine has to do is delete or truncate or zero the header in the
   64355 ** the rollback journal (which causes the transaction to commit) and
   64356 ** drop locks.
   64357 **
   64358 ** Normally, if an error occurs while the pager layer is attempting to
   64359 ** finalize the underlying journal file, this function returns an error and
   64360 ** the upper layer will attempt a rollback. However, if the second argument
   64361 ** is non-zero then this b-tree transaction is part of a multi-file
   64362 ** transaction. In this case, the transaction has already been committed
   64363 ** (by deleting a master journal file) and the caller will ignore this
   64364 ** functions return code. So, even if an error occurs in the pager layer,
   64365 ** reset the b-tree objects internal state to indicate that the write
   64366 ** transaction has been closed. This is quite safe, as the pager will have
   64367 ** transitioned to the error state.
   64368 **
   64369 ** This will release the write lock on the database file.  If there
   64370 ** are no active cursors, it also releases the read lock.
   64371 */
   64372 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
   64373 
   64374   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
   64375   sqlite3BtreeEnter(p);
   64376   btreeIntegrity(p);
   64377 
   64378   /* If the handle has a write-transaction open, commit the shared-btrees
   64379   ** transaction and set the shared state to TRANS_READ.
   64380   */
   64381   if( p->inTrans==TRANS_WRITE ){
   64382     int rc;
   64383     BtShared *pBt = p->pBt;
   64384     assert( pBt->inTransaction==TRANS_WRITE );
   64385     assert( pBt->nTransaction>0 );
   64386     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
   64387     if( rc!=SQLITE_OK && bCleanup==0 ){
   64388       sqlite3BtreeLeave(p);
   64389       return rc;
   64390     }
   64391     p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
   64392     pBt->inTransaction = TRANS_READ;
   64393     btreeClearHasContent(pBt);
   64394   }
   64395 
   64396   btreeEndTransaction(p);
   64397   sqlite3BtreeLeave(p);
   64398   return SQLITE_OK;
   64399 }
   64400 
   64401 /*
   64402 ** Do both phases of a commit.
   64403 */
   64404 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
   64405   int rc;
   64406   sqlite3BtreeEnter(p);
   64407   rc = sqlite3BtreeCommitPhaseOne(p, 0);
   64408   if( rc==SQLITE_OK ){
   64409     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
   64410   }
   64411   sqlite3BtreeLeave(p);
   64412   return rc;
   64413 }
   64414 
   64415 /*
   64416 ** This routine sets the state to CURSOR_FAULT and the error
   64417 ** code to errCode for every cursor on any BtShared that pBtree
   64418 ** references.  Or if the writeOnly flag is set to 1, then only
   64419 ** trip write cursors and leave read cursors unchanged.
   64420 **
   64421 ** Every cursor is a candidate to be tripped, including cursors
   64422 ** that belong to other database connections that happen to be
   64423 ** sharing the cache with pBtree.
   64424 **
   64425 ** This routine gets called when a rollback occurs. If the writeOnly
   64426 ** flag is true, then only write-cursors need be tripped - read-only
   64427 ** cursors save their current positions so that they may continue
   64428 ** following the rollback. Or, if writeOnly is false, all cursors are
   64429 ** tripped. In general, writeOnly is false if the transaction being
   64430 ** rolled back modified the database schema. In this case b-tree root
   64431 ** pages may be moved or deleted from the database altogether, making
   64432 ** it unsafe for read cursors to continue.
   64433 **
   64434 ** If the writeOnly flag is true and an error is encountered while
   64435 ** saving the current position of a read-only cursor, all cursors,
   64436 ** including all read-cursors are tripped.
   64437 **
   64438 ** SQLITE_OK is returned if successful, or if an error occurs while
   64439 ** saving a cursor position, an SQLite error code.
   64440 */
   64441 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
   64442   BtCursor *p;
   64443   int rc = SQLITE_OK;
   64444 
   64445   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
   64446   if( pBtree ){
   64447     sqlite3BtreeEnter(pBtree);
   64448     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   64449       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
   64450         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
   64451           rc = saveCursorPosition(p);
   64452           if( rc!=SQLITE_OK ){
   64453             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
   64454             break;
   64455           }
   64456         }
   64457       }else{
   64458         sqlite3BtreeClearCursor(p);
   64459         p->eState = CURSOR_FAULT;
   64460         p->skipNext = errCode;
   64461       }
   64462       btreeReleaseAllCursorPages(p);
   64463     }
   64464     sqlite3BtreeLeave(pBtree);
   64465   }
   64466   return rc;
   64467 }
   64468 
   64469 /*
   64470 ** Rollback the transaction in progress.
   64471 **
   64472 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
   64473 ** Only write cursors are tripped if writeOnly is true but all cursors are
   64474 ** tripped if writeOnly is false.  Any attempt to use
   64475 ** a tripped cursor will result in an error.
   64476 **
   64477 ** This will release the write lock on the database file.  If there
   64478 ** are no active cursors, it also releases the read lock.
   64479 */
   64480 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
   64481   int rc;
   64482   BtShared *pBt = p->pBt;
   64483   MemPage *pPage1;
   64484 
   64485   assert( writeOnly==1 || writeOnly==0 );
   64486   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
   64487   sqlite3BtreeEnter(p);
   64488   if( tripCode==SQLITE_OK ){
   64489     rc = tripCode = saveAllCursors(pBt, 0, 0);
   64490     if( rc ) writeOnly = 0;
   64491   }else{
   64492     rc = SQLITE_OK;
   64493   }
   64494   if( tripCode ){
   64495     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
   64496     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
   64497     if( rc2!=SQLITE_OK ) rc = rc2;
   64498   }
   64499   btreeIntegrity(p);
   64500 
   64501   if( p->inTrans==TRANS_WRITE ){
   64502     int rc2;
   64503 
   64504     assert( TRANS_WRITE==pBt->inTransaction );
   64505     rc2 = sqlite3PagerRollback(pBt->pPager);
   64506     if( rc2!=SQLITE_OK ){
   64507       rc = rc2;
   64508     }
   64509 
   64510     /* The rollback may have destroyed the pPage1->aData value.  So
   64511     ** call btreeGetPage() on page 1 again to make
   64512     ** sure pPage1->aData is set correctly. */
   64513     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
   64514       int nPage = get4byte(28+(u8*)pPage1->aData);
   64515       testcase( nPage==0 );
   64516       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
   64517       testcase( pBt->nPage!=nPage );
   64518       pBt->nPage = nPage;
   64519       releasePageOne(pPage1);
   64520     }
   64521     assert( countValidCursors(pBt, 1)==0 );
   64522     pBt->inTransaction = TRANS_READ;
   64523     btreeClearHasContent(pBt);
   64524   }
   64525 
   64526   btreeEndTransaction(p);
   64527   sqlite3BtreeLeave(p);
   64528   return rc;
   64529 }
   64530 
   64531 /*
   64532 ** Start a statement subtransaction. The subtransaction can be rolled
   64533 ** back independently of the main transaction. You must start a transaction
   64534 ** before starting a subtransaction. The subtransaction is ended automatically
   64535 ** if the main transaction commits or rolls back.
   64536 **
   64537 ** Statement subtransactions are used around individual SQL statements
   64538 ** that are contained within a BEGIN...COMMIT block.  If a constraint
   64539 ** error occurs within the statement, the effect of that one statement
   64540 ** can be rolled back without having to rollback the entire transaction.
   64541 **
   64542 ** A statement sub-transaction is implemented as an anonymous savepoint. The
   64543 ** value passed as the second parameter is the total number of savepoints,
   64544 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
   64545 ** are no active savepoints and no other statement-transactions open,
   64546 ** iStatement is 1. This anonymous savepoint can be released or rolled back
   64547 ** using the sqlite3BtreeSavepoint() function.
   64548 */
   64549 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
   64550   int rc;
   64551   BtShared *pBt = p->pBt;
   64552   sqlite3BtreeEnter(p);
   64553   assert( p->inTrans==TRANS_WRITE );
   64554   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   64555   assert( iStatement>0 );
   64556   assert( iStatement>p->db->nSavepoint );
   64557   assert( pBt->inTransaction==TRANS_WRITE );
   64558   /* At the pager level, a statement transaction is a savepoint with
   64559   ** an index greater than all savepoints created explicitly using
   64560   ** SQL statements. It is illegal to open, release or rollback any
   64561   ** such savepoints while the statement transaction savepoint is active.
   64562   */
   64563   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
   64564   sqlite3BtreeLeave(p);
   64565   return rc;
   64566 }
   64567 
   64568 /*
   64569 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
   64570 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
   64571 ** savepoint identified by parameter iSavepoint, depending on the value
   64572 ** of op.
   64573 **
   64574 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
   64575 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
   64576 ** contents of the entire transaction are rolled back. This is different
   64577 ** from a normal transaction rollback, as no locks are released and the
   64578 ** transaction remains open.
   64579 */
   64580 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
   64581   int rc = SQLITE_OK;
   64582   if( p && p->inTrans==TRANS_WRITE ){
   64583     BtShared *pBt = p->pBt;
   64584     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   64585     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
   64586     sqlite3BtreeEnter(p);
   64587     if( op==SAVEPOINT_ROLLBACK ){
   64588       rc = saveAllCursors(pBt, 0, 0);
   64589     }
   64590     if( rc==SQLITE_OK ){
   64591       rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
   64592     }
   64593     if( rc==SQLITE_OK ){
   64594       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
   64595         pBt->nPage = 0;
   64596       }
   64597       rc = newDatabase(pBt);
   64598       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
   64599 
   64600       /* The database size was written into the offset 28 of the header
   64601       ** when the transaction started, so we know that the value at offset
   64602       ** 28 is nonzero. */
   64603       assert( pBt->nPage>0 );
   64604     }
   64605     sqlite3BtreeLeave(p);
   64606   }
   64607   return rc;
   64608 }
   64609 
   64610 /*
   64611 ** Create a new cursor for the BTree whose root is on the page
   64612 ** iTable. If a read-only cursor is requested, it is assumed that
   64613 ** the caller already has at least a read-only transaction open
   64614 ** on the database already. If a write-cursor is requested, then
   64615 ** the caller is assumed to have an open write transaction.
   64616 **
   64617 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
   64618 ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
   64619 ** can be used for reading or for writing if other conditions for writing
   64620 ** are also met.  These are the conditions that must be met in order
   64621 ** for writing to be allowed:
   64622 **
   64623 ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
   64624 **
   64625 ** 2:  Other database connections that share the same pager cache
   64626 **     but which are not in the READ_UNCOMMITTED state may not have
   64627 **     cursors open with wrFlag==0 on the same table.  Otherwise
   64628 **     the changes made by this write cursor would be visible to
   64629 **     the read cursors in the other database connection.
   64630 **
   64631 ** 3:  The database must be writable (not on read-only media)
   64632 **
   64633 ** 4:  There must be an active transaction.
   64634 **
   64635 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
   64636 ** is set.  If FORDELETE is set, that is a hint to the implementation that
   64637 ** this cursor will only be used to seek to and delete entries of an index
   64638 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
   64639 ** this implementation.  But in a hypothetical alternative storage engine
   64640 ** in which index entries are automatically deleted when corresponding table
   64641 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
   64642 ** operations on this cursor can be no-ops and all READ operations can
   64643 ** return a null row (2-bytes: 0x01 0x00).
   64644 **
   64645 ** No checking is done to make sure that page iTable really is the
   64646 ** root page of a b-tree.  If it is not, then the cursor acquired
   64647 ** will not work correctly.
   64648 **
   64649 ** It is assumed that the sqlite3BtreeCursorZero() has been called
   64650 ** on pCur to initialize the memory space prior to invoking this routine.
   64651 */
   64652 static int btreeCursor(
   64653   Btree *p,                              /* The btree */
   64654   int iTable,                            /* Root page of table to open */
   64655   int wrFlag,                            /* 1 to write. 0 read-only */
   64656   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   64657   BtCursor *pCur                         /* Space for new cursor */
   64658 ){
   64659   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
   64660   BtCursor *pX;                          /* Looping over other all cursors */
   64661 
   64662   assert( sqlite3BtreeHoldsMutex(p) );
   64663   assert( wrFlag==0
   64664        || wrFlag==BTREE_WRCSR
   64665        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
   64666   );
   64667 
   64668   /* The following assert statements verify that if this is a sharable
   64669   ** b-tree database, the connection is holding the required table locks,
   64670   ** and that no other connection has any open cursor that conflicts with
   64671   ** this lock.  */
   64672   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
   64673   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
   64674 
   64675   /* Assert that the caller has opened the required transaction. */
   64676   assert( p->inTrans>TRANS_NONE );
   64677   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
   64678   assert( pBt->pPage1 && pBt->pPage1->aData );
   64679   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
   64680 
   64681   if( wrFlag ){
   64682     allocateTempSpace(pBt);
   64683     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
   64684   }
   64685   if( iTable==1 && btreePagecount(pBt)==0 ){
   64686     assert( wrFlag==0 );
   64687     iTable = 0;
   64688   }
   64689 
   64690   /* Now that no other errors can occur, finish filling in the BtCursor
   64691   ** variables and link the cursor into the BtShared list.  */
   64692   pCur->pgnoRoot = (Pgno)iTable;
   64693   pCur->iPage = -1;
   64694   pCur->pKeyInfo = pKeyInfo;
   64695   pCur->pBtree = p;
   64696   pCur->pBt = pBt;
   64697   pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
   64698   pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
   64699   /* If there are two or more cursors on the same btree, then all such
   64700   ** cursors *must* have the BTCF_Multiple flag set. */
   64701   for(pX=pBt->pCursor; pX; pX=pX->pNext){
   64702     if( pX->pgnoRoot==(Pgno)iTable ){
   64703       pX->curFlags |= BTCF_Multiple;
   64704       pCur->curFlags |= BTCF_Multiple;
   64705     }
   64706   }
   64707   pCur->pNext = pBt->pCursor;
   64708   pBt->pCursor = pCur;
   64709   pCur->eState = CURSOR_INVALID;
   64710   return SQLITE_OK;
   64711 }
   64712 SQLITE_PRIVATE int sqlite3BtreeCursor(
   64713   Btree *p,                                   /* The btree */
   64714   int iTable,                                 /* Root page of table to open */
   64715   int wrFlag,                                 /* 1 to write. 0 read-only */
   64716   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   64717   BtCursor *pCur                              /* Write new cursor here */
   64718 ){
   64719   int rc;
   64720   if( iTable<1 ){
   64721     rc = SQLITE_CORRUPT_BKPT;
   64722   }else{
   64723     sqlite3BtreeEnter(p);
   64724     rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   64725     sqlite3BtreeLeave(p);
   64726   }
   64727   return rc;
   64728 }
   64729 
   64730 /*
   64731 ** Return the size of a BtCursor object in bytes.
   64732 **
   64733 ** This interfaces is needed so that users of cursors can preallocate
   64734 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
   64735 ** to users so they cannot do the sizeof() themselves - they must call
   64736 ** this routine.
   64737 */
   64738 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
   64739   return ROUND8(sizeof(BtCursor));
   64740 }
   64741 
   64742 /*
   64743 ** Initialize memory that will be converted into a BtCursor object.
   64744 **
   64745 ** The simple approach here would be to memset() the entire object
   64746 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
   64747 ** do not need to be zeroed and they are large, so we can save a lot
   64748 ** of run-time by skipping the initialization of those elements.
   64749 */
   64750 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
   64751   memset(p, 0, offsetof(BtCursor, iPage));
   64752 }
   64753 
   64754 /*
   64755 ** Close a cursor.  The read lock on the database file is released
   64756 ** when the last cursor is closed.
   64757 */
   64758 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
   64759   Btree *pBtree = pCur->pBtree;
   64760   if( pBtree ){
   64761     BtShared *pBt = pCur->pBt;
   64762     sqlite3BtreeEnter(pBtree);
   64763     assert( pBt->pCursor!=0 );
   64764     if( pBt->pCursor==pCur ){
   64765       pBt->pCursor = pCur->pNext;
   64766     }else{
   64767       BtCursor *pPrev = pBt->pCursor;
   64768       do{
   64769         if( pPrev->pNext==pCur ){
   64770           pPrev->pNext = pCur->pNext;
   64771           break;
   64772         }
   64773         pPrev = pPrev->pNext;
   64774       }while( ALWAYS(pPrev) );
   64775     }
   64776     btreeReleaseAllCursorPages(pCur);
   64777     unlockBtreeIfUnused(pBt);
   64778     sqlite3_free(pCur->aOverflow);
   64779     sqlite3_free(pCur->pKey);
   64780     sqlite3BtreeLeave(pBtree);
   64781   }
   64782   return SQLITE_OK;
   64783 }
   64784 
   64785 /*
   64786 ** Make sure the BtCursor* given in the argument has a valid
   64787 ** BtCursor.info structure.  If it is not already valid, call
   64788 ** btreeParseCell() to fill it in.
   64789 **
   64790 ** BtCursor.info is a cache of the information in the current cell.
   64791 ** Using this cache reduces the number of calls to btreeParseCell().
   64792 */
   64793 #ifndef NDEBUG
   64794   static void assertCellInfo(BtCursor *pCur){
   64795     CellInfo info;
   64796     memset(&info, 0, sizeof(info));
   64797     btreeParseCell(pCur->pPage, pCur->ix, &info);
   64798     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
   64799   }
   64800 #else
   64801   #define assertCellInfo(x)
   64802 #endif
   64803 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
   64804   if( pCur->info.nSize==0 ){
   64805     pCur->curFlags |= BTCF_ValidNKey;
   64806     btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
   64807   }else{
   64808     assertCellInfo(pCur);
   64809   }
   64810 }
   64811 
   64812 #ifndef NDEBUG  /* The next routine used only within assert() statements */
   64813 /*
   64814 ** Return true if the given BtCursor is valid.  A valid cursor is one
   64815 ** that is currently pointing to a row in a (non-empty) table.
   64816 ** This is a verification routine is used only within assert() statements.
   64817 */
   64818 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
   64819   return pCur && pCur->eState==CURSOR_VALID;
   64820 }
   64821 #endif /* NDEBUG */
   64822 SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
   64823   assert( pCur!=0 );
   64824   return pCur->eState==CURSOR_VALID;
   64825 }
   64826 
   64827 /*
   64828 ** Return the value of the integer key or "rowid" for a table btree.
   64829 ** This routine is only valid for a cursor that is pointing into a
   64830 ** ordinary table btree.  If the cursor points to an index btree or
   64831 ** is invalid, the result of this routine is undefined.
   64832 */
   64833 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
   64834   assert( cursorHoldsMutex(pCur) );
   64835   assert( pCur->eState==CURSOR_VALID );
   64836   assert( pCur->curIntKey );
   64837   getCellInfo(pCur);
   64838   return pCur->info.nKey;
   64839 }
   64840 
   64841 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
   64842 /*
   64843 ** Return the offset into the database file for the start of the
   64844 ** payload to which the cursor is pointing.
   64845 */
   64846 SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
   64847   assert( cursorHoldsMutex(pCur) );
   64848   assert( pCur->eState==CURSOR_VALID );
   64849   getCellInfo(pCur);
   64850   return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
   64851          (i64)(pCur->info.pPayload - pCur->pPage->aData);
   64852 }
   64853 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
   64854 
   64855 /*
   64856 ** Return the number of bytes of payload for the entry that pCur is
   64857 ** currently pointing to.  For table btrees, this will be the amount
   64858 ** of data.  For index btrees, this will be the size of the key.
   64859 **
   64860 ** The caller must guarantee that the cursor is pointing to a non-NULL
   64861 ** valid entry.  In other words, the calling procedure must guarantee
   64862 ** that the cursor has Cursor.eState==CURSOR_VALID.
   64863 */
   64864 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
   64865   assert( cursorHoldsMutex(pCur) );
   64866   assert( pCur->eState==CURSOR_VALID );
   64867   getCellInfo(pCur);
   64868   return pCur->info.nPayload;
   64869 }
   64870 
   64871 /*
   64872 ** Given the page number of an overflow page in the database (parameter
   64873 ** ovfl), this function finds the page number of the next page in the
   64874 ** linked list of overflow pages. If possible, it uses the auto-vacuum
   64875 ** pointer-map data instead of reading the content of page ovfl to do so.
   64876 **
   64877 ** If an error occurs an SQLite error code is returned. Otherwise:
   64878 **
   64879 ** The page number of the next overflow page in the linked list is
   64880 ** written to *pPgnoNext. If page ovfl is the last page in its linked
   64881 ** list, *pPgnoNext is set to zero.
   64882 **
   64883 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
   64884 ** to page number pOvfl was obtained, then *ppPage is set to point to that
   64885 ** reference. It is the responsibility of the caller to call releasePage()
   64886 ** on *ppPage to free the reference. In no reference was obtained (because
   64887 ** the pointer-map was used to obtain the value for *pPgnoNext), then
   64888 ** *ppPage is set to zero.
   64889 */
   64890 static int getOverflowPage(
   64891   BtShared *pBt,               /* The database file */
   64892   Pgno ovfl,                   /* Current overflow page number */
   64893   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
   64894   Pgno *pPgnoNext              /* OUT: Next overflow page number */
   64895 ){
   64896   Pgno next = 0;
   64897   MemPage *pPage = 0;
   64898   int rc = SQLITE_OK;
   64899 
   64900   assert( sqlite3_mutex_held(pBt->mutex) );
   64901   assert(pPgnoNext);
   64902 
   64903 #ifndef SQLITE_OMIT_AUTOVACUUM
   64904   /* Try to find the next page in the overflow list using the
   64905   ** autovacuum pointer-map pages. Guess that the next page in
   64906   ** the overflow list is page number (ovfl+1). If that guess turns
   64907   ** out to be wrong, fall back to loading the data of page
   64908   ** number ovfl to determine the next page number.
   64909   */
   64910   if( pBt->autoVacuum ){
   64911     Pgno pgno;
   64912     Pgno iGuess = ovfl+1;
   64913     u8 eType;
   64914 
   64915     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
   64916       iGuess++;
   64917     }
   64918 
   64919     if( iGuess<=btreePagecount(pBt) ){
   64920       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
   64921       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
   64922         next = iGuess;
   64923         rc = SQLITE_DONE;
   64924       }
   64925     }
   64926   }
   64927 #endif
   64928 
   64929   assert( next==0 || rc==SQLITE_DONE );
   64930   if( rc==SQLITE_OK ){
   64931     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
   64932     assert( rc==SQLITE_OK || pPage==0 );
   64933     if( rc==SQLITE_OK ){
   64934       next = get4byte(pPage->aData);
   64935     }
   64936   }
   64937 
   64938   *pPgnoNext = next;
   64939   if( ppPage ){
   64940     *ppPage = pPage;
   64941   }else{
   64942     releasePage(pPage);
   64943   }
   64944   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   64945 }
   64946 
   64947 /*
   64948 ** Copy data from a buffer to a page, or from a page to a buffer.
   64949 **
   64950 ** pPayload is a pointer to data stored on database page pDbPage.
   64951 ** If argument eOp is false, then nByte bytes of data are copied
   64952 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
   64953 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
   64954 ** of data are copied from the buffer pBuf to pPayload.
   64955 **
   64956 ** SQLITE_OK is returned on success, otherwise an error code.
   64957 */
   64958 static int copyPayload(
   64959   void *pPayload,           /* Pointer to page data */
   64960   void *pBuf,               /* Pointer to buffer */
   64961   int nByte,                /* Number of bytes to copy */
   64962   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
   64963   DbPage *pDbPage           /* Page containing pPayload */
   64964 ){
   64965   if( eOp ){
   64966     /* Copy data from buffer to page (a write operation) */
   64967     int rc = sqlite3PagerWrite(pDbPage);
   64968     if( rc!=SQLITE_OK ){
   64969       return rc;
   64970     }
   64971     memcpy(pPayload, pBuf, nByte);
   64972   }else{
   64973     /* Copy data from page to buffer (a read operation) */
   64974     memcpy(pBuf, pPayload, nByte);
   64975   }
   64976   return SQLITE_OK;
   64977 }
   64978 
   64979 /*
   64980 ** This function is used to read or overwrite payload information
   64981 ** for the entry that the pCur cursor is pointing to. The eOp
   64982 ** argument is interpreted as follows:
   64983 **
   64984 **   0: The operation is a read. Populate the overflow cache.
   64985 **   1: The operation is a write. Populate the overflow cache.
   64986 **
   64987 ** A total of "amt" bytes are read or written beginning at "offset".
   64988 ** Data is read to or from the buffer pBuf.
   64989 **
   64990 ** The content being read or written might appear on the main page
   64991 ** or be scattered out on multiple overflow pages.
   64992 **
   64993 ** If the current cursor entry uses one or more overflow pages
   64994 ** this function may allocate space for and lazily populate
   64995 ** the overflow page-list cache array (BtCursor.aOverflow).
   64996 ** Subsequent calls use this cache to make seeking to the supplied offset
   64997 ** more efficient.
   64998 **
   64999 ** Once an overflow page-list cache has been allocated, it must be
   65000 ** invalidated if some other cursor writes to the same table, or if
   65001 ** the cursor is moved to a different row. Additionally, in auto-vacuum
   65002 ** mode, the following events may invalidate an overflow page-list cache.
   65003 **
   65004 **   * An incremental vacuum,
   65005 **   * A commit in auto_vacuum="full" mode,
   65006 **   * Creating a table (may require moving an overflow page).
   65007 */
   65008 static int accessPayload(
   65009   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   65010   u32 offset,          /* Begin reading this far into payload */
   65011   u32 amt,             /* Read this many bytes */
   65012   unsigned char *pBuf, /* Write the bytes into this buffer */
   65013   int eOp              /* zero to read. non-zero to write. */
   65014 ){
   65015   unsigned char *aPayload;
   65016   int rc = SQLITE_OK;
   65017   int iIdx = 0;
   65018   MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
   65019   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
   65020 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   65021   unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
   65022 #endif
   65023 
   65024   assert( pPage );
   65025   assert( eOp==0 || eOp==1 );
   65026   assert( pCur->eState==CURSOR_VALID );
   65027   assert( pCur->ix<pPage->nCell );
   65028   assert( cursorHoldsMutex(pCur) );
   65029 
   65030   getCellInfo(pCur);
   65031   aPayload = pCur->info.pPayload;
   65032   assert( offset+amt <= pCur->info.nPayload );
   65033 
   65034   assert( aPayload > pPage->aData );
   65035   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
   65036     /* Trying to read or write past the end of the data is an error.  The
   65037     ** conditional above is really:
   65038     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
   65039     ** but is recast into its current form to avoid integer overflow problems
   65040     */
   65041     return SQLITE_CORRUPT_PAGE(pPage);
   65042   }
   65043 
   65044   /* Check if data must be read/written to/from the btree page itself. */
   65045   if( offset<pCur->info.nLocal ){
   65046     int a = amt;
   65047     if( a+offset>pCur->info.nLocal ){
   65048       a = pCur->info.nLocal - offset;
   65049     }
   65050     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
   65051     offset = 0;
   65052     pBuf += a;
   65053     amt -= a;
   65054   }else{
   65055     offset -= pCur->info.nLocal;
   65056   }
   65057 
   65058 
   65059   if( rc==SQLITE_OK && amt>0 ){
   65060     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
   65061     Pgno nextPage;
   65062 
   65063     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
   65064 
   65065     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
   65066     **
   65067     ** The aOverflow[] array is sized at one entry for each overflow page
   65068     ** in the overflow chain. The page number of the first overflow page is
   65069     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
   65070     ** means "not yet known" (the cache is lazily populated).
   65071     */
   65072     if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
   65073       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
   65074       if( nOvfl>pCur->nOvflAlloc ){
   65075         Pgno *aNew = (Pgno*)sqlite3Realloc(
   65076             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
   65077         );
   65078         if( aNew==0 ){
   65079           return SQLITE_NOMEM_BKPT;
   65080         }else{
   65081           pCur->nOvflAlloc = nOvfl*2;
   65082           pCur->aOverflow = aNew;
   65083         }
   65084       }
   65085       memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
   65086       pCur->curFlags |= BTCF_ValidOvfl;
   65087     }else{
   65088       /* If the overflow page-list cache has been allocated and the
   65089       ** entry for the first required overflow page is valid, skip
   65090       ** directly to it.
   65091       */
   65092       if( pCur->aOverflow[offset/ovflSize] ){
   65093         iIdx = (offset/ovflSize);
   65094         nextPage = pCur->aOverflow[iIdx];
   65095         offset = (offset%ovflSize);
   65096       }
   65097     }
   65098 
   65099     assert( rc==SQLITE_OK && amt>0 );
   65100     while( nextPage ){
   65101       /* If required, populate the overflow page-list cache. */
   65102       assert( pCur->aOverflow[iIdx]==0
   65103               || pCur->aOverflow[iIdx]==nextPage
   65104               || CORRUPT_DB );
   65105       pCur->aOverflow[iIdx] = nextPage;
   65106 
   65107       if( offset>=ovflSize ){
   65108         /* The only reason to read this page is to obtain the page
   65109         ** number for the next page in the overflow chain. The page
   65110         ** data is not required. So first try to lookup the overflow
   65111         ** page-list cache, if any, then fall back to the getOverflowPage()
   65112         ** function.
   65113         */
   65114         assert( pCur->curFlags & BTCF_ValidOvfl );
   65115         assert( pCur->pBtree->db==pBt->db );
   65116         if( pCur->aOverflow[iIdx+1] ){
   65117           nextPage = pCur->aOverflow[iIdx+1];
   65118         }else{
   65119           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
   65120         }
   65121         offset -= ovflSize;
   65122       }else{
   65123         /* Need to read this page properly. It contains some of the
   65124         ** range of data that is being read (eOp==0) or written (eOp!=0).
   65125         */
   65126 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   65127         sqlite3_file *fd;      /* File from which to do direct overflow read */
   65128 #endif
   65129         int a = amt;
   65130         if( a + offset > ovflSize ){
   65131           a = ovflSize - offset;
   65132         }
   65133 
   65134 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   65135         /* If all the following are true:
   65136         **
   65137         **   1) this is a read operation, and
   65138         **   2) data is required from the start of this overflow page, and
   65139         **   3) there is no open write-transaction, and
   65140         **   4) the database is file-backed, and
   65141         **   5) the page is not in the WAL file
   65142         **   6) at least 4 bytes have already been read into the output buffer
   65143         **
   65144         ** then data can be read directly from the database file into the
   65145         ** output buffer, bypassing the page-cache altogether. This speeds
   65146         ** up loading large records that span many overflow pages.
   65147         */
   65148         if( eOp==0                                             /* (1) */
   65149          && offset==0                                          /* (2) */
   65150          && pBt->inTransaction==TRANS_READ                     /* (3) */
   65151          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
   65152          && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
   65153          && &pBuf[-4]>=pBufStart                               /* (6) */
   65154         ){
   65155           u8 aSave[4];
   65156           u8 *aWrite = &pBuf[-4];
   65157           assert( aWrite>=pBufStart );                         /* due to (6) */
   65158           memcpy(aSave, aWrite, 4);
   65159           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
   65160           nextPage = get4byte(aWrite);
   65161           memcpy(aWrite, aSave, 4);
   65162         }else
   65163 #endif
   65164 
   65165         {
   65166           DbPage *pDbPage;
   65167           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
   65168               (eOp==0 ? PAGER_GET_READONLY : 0)
   65169           );
   65170           if( rc==SQLITE_OK ){
   65171             aPayload = sqlite3PagerGetData(pDbPage);
   65172             nextPage = get4byte(aPayload);
   65173             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
   65174             sqlite3PagerUnref(pDbPage);
   65175             offset = 0;
   65176           }
   65177         }
   65178         amt -= a;
   65179         if( amt==0 ) return rc;
   65180         pBuf += a;
   65181       }
   65182       if( rc ) break;
   65183       iIdx++;
   65184     }
   65185   }
   65186 
   65187   if( rc==SQLITE_OK && amt>0 ){
   65188     /* Overflow chain ends prematurely */
   65189     return SQLITE_CORRUPT_PAGE(pPage);
   65190   }
   65191   return rc;
   65192 }
   65193 
   65194 /*
   65195 ** Read part of the payload for the row at which that cursor pCur is currently
   65196 ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
   65197 ** begins at "offset".
   65198 **
   65199 ** pCur can be pointing to either a table or an index b-tree.
   65200 ** If pointing to a table btree, then the content section is read.  If
   65201 ** pCur is pointing to an index b-tree then the key section is read.
   65202 **
   65203 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
   65204 ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
   65205 ** cursor might be invalid or might need to be restored before being read.
   65206 **
   65207 ** Return SQLITE_OK on success or an error code if anything goes
   65208 ** wrong.  An error is returned if "offset+amt" is larger than
   65209 ** the available payload.
   65210 */
   65211 SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   65212   assert( cursorHoldsMutex(pCur) );
   65213   assert( pCur->eState==CURSOR_VALID );
   65214   assert( pCur->iPage>=0 && pCur->pPage );
   65215   assert( pCur->ix<pCur->pPage->nCell );
   65216   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
   65217 }
   65218 
   65219 /*
   65220 ** This variant of sqlite3BtreePayload() works even if the cursor has not
   65221 ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
   65222 ** interface.
   65223 */
   65224 #ifndef SQLITE_OMIT_INCRBLOB
   65225 static SQLITE_NOINLINE int accessPayloadChecked(
   65226   BtCursor *pCur,
   65227   u32 offset,
   65228   u32 amt,
   65229   void *pBuf
   65230 ){
   65231   int rc;
   65232   if ( pCur->eState==CURSOR_INVALID ){
   65233     return SQLITE_ABORT;
   65234   }
   65235   assert( cursorOwnsBtShared(pCur) );
   65236   rc = btreeRestoreCursorPosition(pCur);
   65237   return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
   65238 }
   65239 SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   65240   if( pCur->eState==CURSOR_VALID ){
   65241     assert( cursorOwnsBtShared(pCur) );
   65242     return accessPayload(pCur, offset, amt, pBuf, 0);
   65243   }else{
   65244     return accessPayloadChecked(pCur, offset, amt, pBuf);
   65245   }
   65246 }
   65247 #endif /* SQLITE_OMIT_INCRBLOB */
   65248 
   65249 /*
   65250 ** Return a pointer to payload information from the entry that the
   65251 ** pCur cursor is pointing to.  The pointer is to the beginning of
   65252 ** the key if index btrees (pPage->intKey==0) and is the data for
   65253 ** table btrees (pPage->intKey==1). The number of bytes of available
   65254 ** key/data is written into *pAmt.  If *pAmt==0, then the value
   65255 ** returned will not be a valid pointer.
   65256 **
   65257 ** This routine is an optimization.  It is common for the entire key
   65258 ** and data to fit on the local page and for there to be no overflow
   65259 ** pages.  When that is so, this routine can be used to access the
   65260 ** key and data without making a copy.  If the key and/or data spills
   65261 ** onto overflow pages, then accessPayload() must be used to reassemble
   65262 ** the key/data and copy it into a preallocated buffer.
   65263 **
   65264 ** The pointer returned by this routine looks directly into the cached
   65265 ** page of the database.  The data might change or move the next time
   65266 ** any btree routine is called.
   65267 */
   65268 static const void *fetchPayload(
   65269   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   65270   u32 *pAmt            /* Write the number of available bytes here */
   65271 ){
   65272   int amt;
   65273   assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
   65274   assert( pCur->eState==CURSOR_VALID );
   65275   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   65276   assert( cursorOwnsBtShared(pCur) );
   65277   assert( pCur->ix<pCur->pPage->nCell );
   65278   assert( pCur->info.nSize>0 );
   65279   assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
   65280   assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
   65281   amt = pCur->info.nLocal;
   65282   if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
   65283     /* There is too little space on the page for the expected amount
   65284     ** of local content. Database must be corrupt. */
   65285     assert( CORRUPT_DB );
   65286     amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
   65287   }
   65288   *pAmt = (u32)amt;
   65289   return (void*)pCur->info.pPayload;
   65290 }
   65291 
   65292 
   65293 /*
   65294 ** For the entry that cursor pCur is point to, return as
   65295 ** many bytes of the key or data as are available on the local
   65296 ** b-tree page.  Write the number of available bytes into *pAmt.
   65297 **
   65298 ** The pointer returned is ephemeral.  The key/data may move
   65299 ** or be destroyed on the next call to any Btree routine,
   65300 ** including calls from other threads against the same cache.
   65301 ** Hence, a mutex on the BtShared should be held prior to calling
   65302 ** this routine.
   65303 **
   65304 ** These routines is used to get quick access to key and data
   65305 ** in the common case where no overflow pages are used.
   65306 */
   65307 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
   65308   return fetchPayload(pCur, pAmt);
   65309 }
   65310 
   65311 
   65312 /*
   65313 ** Move the cursor down to a new child page.  The newPgno argument is the
   65314 ** page number of the child page to move to.
   65315 **
   65316 ** This function returns SQLITE_CORRUPT if the page-header flags field of
   65317 ** the new child page does not match the flags field of the parent (i.e.
   65318 ** if an intkey page appears to be the parent of a non-intkey page, or
   65319 ** vice-versa).
   65320 */
   65321 static int moveToChild(BtCursor *pCur, u32 newPgno){
   65322   BtShared *pBt = pCur->pBt;
   65323 
   65324   assert( cursorOwnsBtShared(pCur) );
   65325   assert( pCur->eState==CURSOR_VALID );
   65326   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
   65327   assert( pCur->iPage>=0 );
   65328   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
   65329     return SQLITE_CORRUPT_BKPT;
   65330   }
   65331   pCur->info.nSize = 0;
   65332   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   65333   pCur->aiIdx[pCur->iPage] = pCur->ix;
   65334   pCur->apPage[pCur->iPage] = pCur->pPage;
   65335   pCur->ix = 0;
   65336   pCur->iPage++;
   65337   return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
   65338 }
   65339 
   65340 #ifdef SQLITE_DEBUG
   65341 /*
   65342 ** Page pParent is an internal (non-leaf) tree page. This function
   65343 ** asserts that page number iChild is the left-child if the iIdx'th
   65344 ** cell in page pParent. Or, if iIdx is equal to the total number of
   65345 ** cells in pParent, that page number iChild is the right-child of
   65346 ** the page.
   65347 */
   65348 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   65349   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
   65350                             ** in a corrupt database */
   65351   assert( iIdx<=pParent->nCell );
   65352   if( iIdx==pParent->nCell ){
   65353     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
   65354   }else{
   65355     assert( get4byte(findCell(pParent, iIdx))==iChild );
   65356   }
   65357 }
   65358 #else
   65359 #  define assertParentIndex(x,y,z)
   65360 #endif
   65361 
   65362 /*
   65363 ** Move the cursor up to the parent page.
   65364 **
   65365 ** pCur->idx is set to the cell index that contains the pointer
   65366 ** to the page we are coming from.  If we are coming from the
   65367 ** right-most child page then pCur->idx is set to one more than
   65368 ** the largest cell index.
   65369 */
   65370 static void moveToParent(BtCursor *pCur){
   65371   MemPage *pLeaf;
   65372   assert( cursorOwnsBtShared(pCur) );
   65373   assert( pCur->eState==CURSOR_VALID );
   65374   assert( pCur->iPage>0 );
   65375   assert( pCur->pPage );
   65376   assertParentIndex(
   65377     pCur->apPage[pCur->iPage-1],
   65378     pCur->aiIdx[pCur->iPage-1],
   65379     pCur->pPage->pgno
   65380   );
   65381   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
   65382   pCur->info.nSize = 0;
   65383   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   65384   pCur->ix = pCur->aiIdx[pCur->iPage-1];
   65385   pLeaf = pCur->pPage;
   65386   pCur->pPage = pCur->apPage[--pCur->iPage];
   65387   releasePageNotNull(pLeaf);
   65388 }
   65389 
   65390 /*
   65391 ** Move the cursor to point to the root page of its b-tree structure.
   65392 **
   65393 ** If the table has a virtual root page, then the cursor is moved to point
   65394 ** to the virtual root page instead of the actual root page. A table has a
   65395 ** virtual root page when the actual root page contains no cells and a
   65396 ** single child page. This can only happen with the table rooted at page 1.
   65397 **
   65398 ** If the b-tree structure is empty, the cursor state is set to
   65399 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
   65400 ** the cursor is set to point to the first cell located on the root
   65401 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
   65402 **
   65403 ** If this function returns successfully, it may be assumed that the
   65404 ** page-header flags indicate that the [virtual] root-page is the expected
   65405 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
   65406 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
   65407 ** indicating a table b-tree, or if the caller did specify a KeyInfo
   65408 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
   65409 ** b-tree).
   65410 */
   65411 static int moveToRoot(BtCursor *pCur){
   65412   MemPage *pRoot;
   65413   int rc = SQLITE_OK;
   65414 
   65415   assert( cursorOwnsBtShared(pCur) );
   65416   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
   65417   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
   65418   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
   65419   assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
   65420   assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
   65421 
   65422   if( pCur->iPage>=0 ){
   65423     if( pCur->iPage ){
   65424       releasePageNotNull(pCur->pPage);
   65425       while( --pCur->iPage ){
   65426         releasePageNotNull(pCur->apPage[pCur->iPage]);
   65427       }
   65428       pCur->pPage = pCur->apPage[0];
   65429       goto skip_init;
   65430     }
   65431   }else if( pCur->pgnoRoot==0 ){
   65432     pCur->eState = CURSOR_INVALID;
   65433     return SQLITE_EMPTY;
   65434   }else{
   65435     assert( pCur->iPage==(-1) );
   65436     if( pCur->eState>=CURSOR_REQUIRESEEK ){
   65437       if( pCur->eState==CURSOR_FAULT ){
   65438         assert( pCur->skipNext!=SQLITE_OK );
   65439         return pCur->skipNext;
   65440       }
   65441       sqlite3BtreeClearCursor(pCur);
   65442     }
   65443     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
   65444                         0, pCur->curPagerFlags);
   65445     if( rc!=SQLITE_OK ){
   65446       pCur->eState = CURSOR_INVALID;
   65447       return rc;
   65448     }
   65449     pCur->iPage = 0;
   65450     pCur->curIntKey = pCur->pPage->intKey;
   65451   }
   65452   pRoot = pCur->pPage;
   65453   assert( pRoot->pgno==pCur->pgnoRoot );
   65454 
   65455   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   65456   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   65457   ** NULL, the caller expects a table b-tree. If this is not the case,
   65458   ** return an SQLITE_CORRUPT error.
   65459   **
   65460   ** Earlier versions of SQLite assumed that this test could not fail
   65461   ** if the root page was already loaded when this function was called (i.e.
   65462   ** if pCur->iPage>=0). But this is not so if the database is corrupted
   65463   ** in such a way that page pRoot is linked into a second b-tree table
   65464   ** (or the freelist).  */
   65465   assert( pRoot->intKey==1 || pRoot->intKey==0 );
   65466   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
   65467     return SQLITE_CORRUPT_PAGE(pCur->pPage);
   65468   }
   65469 
   65470 skip_init:
   65471   pCur->ix = 0;
   65472   pCur->info.nSize = 0;
   65473   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
   65474 
   65475   pRoot = pCur->pPage;
   65476   if( pRoot->nCell>0 ){
   65477     pCur->eState = CURSOR_VALID;
   65478   }else if( !pRoot->leaf ){
   65479     Pgno subpage;
   65480     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
   65481     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
   65482     pCur->eState = CURSOR_VALID;
   65483     rc = moveToChild(pCur, subpage);
   65484   }else{
   65485     pCur->eState = CURSOR_INVALID;
   65486     rc = SQLITE_EMPTY;
   65487   }
   65488   return rc;
   65489 }
   65490 
   65491 /*
   65492 ** Move the cursor down to the left-most leaf entry beneath the
   65493 ** entry to which it is currently pointing.
   65494 **
   65495 ** The left-most leaf is the one with the smallest key - the first
   65496 ** in ascending order.
   65497 */
   65498 static int moveToLeftmost(BtCursor *pCur){
   65499   Pgno pgno;
   65500   int rc = SQLITE_OK;
   65501   MemPage *pPage;
   65502 
   65503   assert( cursorOwnsBtShared(pCur) );
   65504   assert( pCur->eState==CURSOR_VALID );
   65505   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
   65506     assert( pCur->ix<pPage->nCell );
   65507     pgno = get4byte(findCell(pPage, pCur->ix));
   65508     rc = moveToChild(pCur, pgno);
   65509   }
   65510   return rc;
   65511 }
   65512 
   65513 /*
   65514 ** Move the cursor down to the right-most leaf entry beneath the
   65515 ** page to which it is currently pointing.  Notice the difference
   65516 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
   65517 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
   65518 ** finds the right-most entry beneath the *page*.
   65519 **
   65520 ** The right-most entry is the one with the largest key - the last
   65521 ** key in ascending order.
   65522 */
   65523 static int moveToRightmost(BtCursor *pCur){
   65524   Pgno pgno;
   65525   int rc = SQLITE_OK;
   65526   MemPage *pPage = 0;
   65527 
   65528   assert( cursorOwnsBtShared(pCur) );
   65529   assert( pCur->eState==CURSOR_VALID );
   65530   while( !(pPage = pCur->pPage)->leaf ){
   65531     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   65532     pCur->ix = pPage->nCell;
   65533     rc = moveToChild(pCur, pgno);
   65534     if( rc ) return rc;
   65535   }
   65536   pCur->ix = pPage->nCell-1;
   65537   assert( pCur->info.nSize==0 );
   65538   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
   65539   return SQLITE_OK;
   65540 }
   65541 
   65542 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
   65543 ** on success.  Set *pRes to 0 if the cursor actually points to something
   65544 ** or set *pRes to 1 if the table is empty.
   65545 */
   65546 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
   65547   int rc;
   65548 
   65549   assert( cursorOwnsBtShared(pCur) );
   65550   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   65551   rc = moveToRoot(pCur);
   65552   if( rc==SQLITE_OK ){
   65553     assert( pCur->pPage->nCell>0 );
   65554     *pRes = 0;
   65555     rc = moveToLeftmost(pCur);
   65556   }else if( rc==SQLITE_EMPTY ){
   65557     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
   65558     *pRes = 1;
   65559     rc = SQLITE_OK;
   65560   }
   65561   return rc;
   65562 }
   65563 
   65564 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
   65565 ** on success.  Set *pRes to 0 if the cursor actually points to something
   65566 ** or set *pRes to 1 if the table is empty.
   65567 */
   65568 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   65569   int rc;
   65570 
   65571   assert( cursorOwnsBtShared(pCur) );
   65572   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   65573 
   65574   /* If the cursor already points to the last entry, this is a no-op. */
   65575   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
   65576 #ifdef SQLITE_DEBUG
   65577     /* This block serves to assert() that the cursor really does point
   65578     ** to the last entry in the b-tree. */
   65579     int ii;
   65580     for(ii=0; ii<pCur->iPage; ii++){
   65581       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
   65582     }
   65583     assert( pCur->ix==pCur->pPage->nCell-1 );
   65584     assert( pCur->pPage->leaf );
   65585 #endif
   65586     return SQLITE_OK;
   65587   }
   65588 
   65589   rc = moveToRoot(pCur);
   65590   if( rc==SQLITE_OK ){
   65591     assert( pCur->eState==CURSOR_VALID );
   65592     *pRes = 0;
   65593     rc = moveToRightmost(pCur);
   65594     if( rc==SQLITE_OK ){
   65595       pCur->curFlags |= BTCF_AtLast;
   65596     }else{
   65597       pCur->curFlags &= ~BTCF_AtLast;
   65598     }
   65599   }else if( rc==SQLITE_EMPTY ){
   65600     assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
   65601     *pRes = 1;
   65602     rc = SQLITE_OK;
   65603   }
   65604   return rc;
   65605 }
   65606 
   65607 /* Move the cursor so that it points to an entry near the key
   65608 ** specified by pIdxKey or intKey.   Return a success code.
   65609 **
   65610 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
   65611 ** must be NULL.  For index tables, pIdxKey is used and intKey
   65612 ** is ignored.
   65613 **
   65614 ** If an exact match is not found, then the cursor is always
   65615 ** left pointing at a leaf page which would hold the entry if it
   65616 ** were present.  The cursor might point to an entry that comes
   65617 ** before or after the key.
   65618 **
   65619 ** An integer is written into *pRes which is the result of
   65620 ** comparing the key with the entry to which the cursor is
   65621 ** pointing.  The meaning of the integer written into
   65622 ** *pRes is as follows:
   65623 **
   65624 **     *pRes<0      The cursor is left pointing at an entry that
   65625 **                  is smaller than intKey/pIdxKey or if the table is empty
   65626 **                  and the cursor is therefore left point to nothing.
   65627 **
   65628 **     *pRes==0     The cursor is left pointing at an entry that
   65629 **                  exactly matches intKey/pIdxKey.
   65630 **
   65631 **     *pRes>0      The cursor is left pointing at an entry that
   65632 **                  is larger than intKey/pIdxKey.
   65633 **
   65634 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
   65635 ** exists an entry in the table that exactly matches pIdxKey.
   65636 */
   65637 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   65638   BtCursor *pCur,          /* The cursor to be moved */
   65639   UnpackedRecord *pIdxKey, /* Unpacked index key */
   65640   i64 intKey,              /* The table key */
   65641   int biasRight,           /* If true, bias the search to the high end */
   65642   int *pRes                /* Write search results here */
   65643 ){
   65644   int rc;
   65645   RecordCompare xRecordCompare;
   65646 
   65647   assert( cursorOwnsBtShared(pCur) );
   65648   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   65649   assert( pRes );
   65650   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
   65651   assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
   65652 
   65653   /* If the cursor is already positioned at the point we are trying
   65654   ** to move to, then just return without doing any work */
   65655   if( pIdxKey==0
   65656    && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
   65657   ){
   65658     if( pCur->info.nKey==intKey ){
   65659       *pRes = 0;
   65660       return SQLITE_OK;
   65661     }
   65662     if( pCur->info.nKey<intKey ){
   65663       if( (pCur->curFlags & BTCF_AtLast)!=0 ){
   65664         *pRes = -1;
   65665         return SQLITE_OK;
   65666       }
   65667       /* If the requested key is one more than the previous key, then
   65668       ** try to get there using sqlite3BtreeNext() rather than a full
   65669       ** binary search.  This is an optimization only.  The correct answer
   65670       ** is still obtained without this case, only a little more slowely */
   65671       if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
   65672         *pRes = 0;
   65673         rc = sqlite3BtreeNext(pCur, 0);
   65674         if( rc==SQLITE_OK ){
   65675           getCellInfo(pCur);
   65676           if( pCur->info.nKey==intKey ){
   65677             return SQLITE_OK;
   65678           }
   65679         }else if( rc==SQLITE_DONE ){
   65680           rc = SQLITE_OK;
   65681         }else{
   65682           return rc;
   65683         }
   65684       }
   65685     }
   65686   }
   65687 
   65688   if( pIdxKey ){
   65689     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
   65690     pIdxKey->errCode = 0;
   65691     assert( pIdxKey->default_rc==1
   65692          || pIdxKey->default_rc==0
   65693          || pIdxKey->default_rc==-1
   65694     );
   65695   }else{
   65696     xRecordCompare = 0; /* All keys are integers */
   65697   }
   65698 
   65699   rc = moveToRoot(pCur);
   65700   if( rc ){
   65701     if( rc==SQLITE_EMPTY ){
   65702       assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
   65703       *pRes = -1;
   65704       return SQLITE_OK;
   65705     }
   65706     return rc;
   65707   }
   65708   assert( pCur->pPage );
   65709   assert( pCur->pPage->isInit );
   65710   assert( pCur->eState==CURSOR_VALID );
   65711   assert( pCur->pPage->nCell > 0 );
   65712   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
   65713   assert( pCur->curIntKey || pIdxKey );
   65714   for(;;){
   65715     int lwr, upr, idx, c;
   65716     Pgno chldPg;
   65717     MemPage *pPage = pCur->pPage;
   65718     u8 *pCell;                          /* Pointer to current cell in pPage */
   65719 
   65720     /* pPage->nCell must be greater than zero. If this is the root-page
   65721     ** the cursor would have been INVALID above and this for(;;) loop
   65722     ** not run. If this is not the root-page, then the moveToChild() routine
   65723     ** would have already detected db corruption. Similarly, pPage must
   65724     ** be the right kind (index or table) of b-tree page. Otherwise
   65725     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
   65726     assert( pPage->nCell>0 );
   65727     assert( pPage->intKey==(pIdxKey==0) );
   65728     lwr = 0;
   65729     upr = pPage->nCell-1;
   65730     assert( biasRight==0 || biasRight==1 );
   65731     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
   65732     pCur->ix = (u16)idx;
   65733     if( xRecordCompare==0 ){
   65734       for(;;){
   65735         i64 nCellKey;
   65736         pCell = findCellPastPtr(pPage, idx);
   65737         if( pPage->intKeyLeaf ){
   65738           while( 0x80 <= *(pCell++) ){
   65739             if( pCell>=pPage->aDataEnd ){
   65740               return SQLITE_CORRUPT_PAGE(pPage);
   65741             }
   65742           }
   65743         }
   65744         getVarint(pCell, (u64*)&nCellKey);
   65745         if( nCellKey<intKey ){
   65746           lwr = idx+1;
   65747           if( lwr>upr ){ c = -1; break; }
   65748         }else if( nCellKey>intKey ){
   65749           upr = idx-1;
   65750           if( lwr>upr ){ c = +1; break; }
   65751         }else{
   65752           assert( nCellKey==intKey );
   65753           pCur->ix = (u16)idx;
   65754           if( !pPage->leaf ){
   65755             lwr = idx;
   65756             goto moveto_next_layer;
   65757           }else{
   65758             pCur->curFlags |= BTCF_ValidNKey;
   65759             pCur->info.nKey = nCellKey;
   65760             pCur->info.nSize = 0;
   65761             *pRes = 0;
   65762             return SQLITE_OK;
   65763           }
   65764         }
   65765         assert( lwr+upr>=0 );
   65766         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
   65767       }
   65768     }else{
   65769       for(;;){
   65770         int nCell;  /* Size of the pCell cell in bytes */
   65771         pCell = findCellPastPtr(pPage, idx);
   65772 
   65773         /* The maximum supported page-size is 65536 bytes. This means that
   65774         ** the maximum number of record bytes stored on an index B-Tree
   65775         ** page is less than 16384 bytes and may be stored as a 2-byte
   65776         ** varint. This information is used to attempt to avoid parsing
   65777         ** the entire cell by checking for the cases where the record is
   65778         ** stored entirely within the b-tree page by inspecting the first
   65779         ** 2 bytes of the cell.
   65780         */
   65781         nCell = pCell[0];
   65782         if( nCell<=pPage->max1bytePayload ){
   65783           /* This branch runs if the record-size field of the cell is a
   65784           ** single byte varint and the record fits entirely on the main
   65785           ** b-tree page.  */
   65786           testcase( pCell+nCell+1==pPage->aDataEnd );
   65787           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
   65788         }else if( !(pCell[1] & 0x80)
   65789           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
   65790         ){
   65791           /* The record-size field is a 2 byte varint and the record
   65792           ** fits entirely on the main b-tree page.  */
   65793           testcase( pCell+nCell+2==pPage->aDataEnd );
   65794           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
   65795         }else{
   65796           /* The record flows over onto one or more overflow pages. In
   65797           ** this case the whole cell needs to be parsed, a buffer allocated
   65798           ** and accessPayload() used to retrieve the record into the
   65799           ** buffer before VdbeRecordCompare() can be called.
   65800           **
   65801           ** If the record is corrupt, the xRecordCompare routine may read
   65802           ** up to two varints past the end of the buffer. An extra 18
   65803           ** bytes of padding is allocated at the end of the buffer in
   65804           ** case this happens.  */
   65805           void *pCellKey;
   65806           u8 * const pCellBody = pCell - pPage->childPtrSize;
   65807           pPage->xParseCell(pPage, pCellBody, &pCur->info);
   65808           nCell = (int)pCur->info.nKey;
   65809           testcase( nCell<0 );   /* True if key size is 2^32 or more */
   65810           testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
   65811           testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
   65812           testcase( nCell==2 );  /* Minimum legal index key size */
   65813           if( nCell<2 ){
   65814             rc = SQLITE_CORRUPT_PAGE(pPage);
   65815             goto moveto_finish;
   65816           }
   65817           pCellKey = sqlite3Malloc( nCell+18 );
   65818           if( pCellKey==0 ){
   65819             rc = SQLITE_NOMEM_BKPT;
   65820             goto moveto_finish;
   65821           }
   65822           pCur->ix = (u16)idx;
   65823           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
   65824           pCur->curFlags &= ~BTCF_ValidOvfl;
   65825           if( rc ){
   65826             sqlite3_free(pCellKey);
   65827             goto moveto_finish;
   65828           }
   65829           c = xRecordCompare(nCell, pCellKey, pIdxKey);
   65830           sqlite3_free(pCellKey);
   65831         }
   65832         assert(
   65833             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
   65834          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
   65835         );
   65836         if( c<0 ){
   65837           lwr = idx+1;
   65838         }else if( c>0 ){
   65839           upr = idx-1;
   65840         }else{
   65841           assert( c==0 );
   65842           *pRes = 0;
   65843           rc = SQLITE_OK;
   65844           pCur->ix = (u16)idx;
   65845           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
   65846           goto moveto_finish;
   65847         }
   65848         if( lwr>upr ) break;
   65849         assert( lwr+upr>=0 );
   65850         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
   65851       }
   65852     }
   65853     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
   65854     assert( pPage->isInit );
   65855     if( pPage->leaf ){
   65856       assert( pCur->ix<pCur->pPage->nCell );
   65857       pCur->ix = (u16)idx;
   65858       *pRes = c;
   65859       rc = SQLITE_OK;
   65860       goto moveto_finish;
   65861     }
   65862 moveto_next_layer:
   65863     if( lwr>=pPage->nCell ){
   65864       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   65865     }else{
   65866       chldPg = get4byte(findCell(pPage, lwr));
   65867     }
   65868     pCur->ix = (u16)lwr;
   65869     rc = moveToChild(pCur, chldPg);
   65870     if( rc ) break;
   65871   }
   65872 moveto_finish:
   65873   pCur->info.nSize = 0;
   65874   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
   65875   return rc;
   65876 }
   65877 
   65878 
   65879 /*
   65880 ** Return TRUE if the cursor is not pointing at an entry of the table.
   65881 **
   65882 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
   65883 ** past the last entry in the table or sqlite3BtreePrev() moves past
   65884 ** the first entry.  TRUE is also returned if the table is empty.
   65885 */
   65886 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
   65887   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
   65888   ** have been deleted? This API will need to change to return an error code
   65889   ** as well as the boolean result value.
   65890   */
   65891   return (CURSOR_VALID!=pCur->eState);
   65892 }
   65893 
   65894 /*
   65895 ** Return an estimate for the number of rows in the table that pCur is
   65896 ** pointing to.  Return a negative number if no estimate is currently
   65897 ** available.
   65898 */
   65899 SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
   65900   i64 n;
   65901   u8 i;
   65902 
   65903   assert( cursorOwnsBtShared(pCur) );
   65904   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   65905 
   65906   /* Currently this interface is only called by the OP_IfSmaller
   65907   ** opcode, and it that case the cursor will always be valid and
   65908   ** will always point to a leaf node. */
   65909   if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
   65910   if( NEVER(pCur->pPage->leaf==0) ) return -1;
   65911 
   65912   n = pCur->pPage->nCell;
   65913   for(i=0; i<pCur->iPage; i++){
   65914     n *= pCur->apPage[i]->nCell;
   65915   }
   65916   return n;
   65917 }
   65918 
   65919 /*
   65920 ** Advance the cursor to the next entry in the database.
   65921 ** Return value:
   65922 **
   65923 **    SQLITE_OK        success
   65924 **    SQLITE_DONE      cursor is already pointing at the last element
   65925 **    otherwise        some kind of error occurred
   65926 **
   65927 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
   65928 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
   65929 ** to the next cell on the current page.  The (slower) btreeNext() helper
   65930 ** routine is called when it is necessary to move to a different page or
   65931 ** to restore the cursor.
   65932 **
   65933 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
   65934 ** cursor corresponds to an SQL index and this routine could have been
   65935 ** skipped if the SQL index had been a unique index.  The F argument
   65936 ** is a hint to the implement.  SQLite btree implementation does not use
   65937 ** this hint, but COMDB2 does.
   65938 */
   65939 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
   65940   int rc;
   65941   int idx;
   65942   MemPage *pPage;
   65943 
   65944   assert( cursorOwnsBtShared(pCur) );
   65945   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   65946   if( pCur->eState!=CURSOR_VALID ){
   65947     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
   65948     rc = restoreCursorPosition(pCur);
   65949     if( rc!=SQLITE_OK ){
   65950       return rc;
   65951     }
   65952     if( CURSOR_INVALID==pCur->eState ){
   65953       return SQLITE_DONE;
   65954     }
   65955     if( pCur->skipNext ){
   65956       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
   65957       pCur->eState = CURSOR_VALID;
   65958       if( pCur->skipNext>0 ){
   65959         pCur->skipNext = 0;
   65960         return SQLITE_OK;
   65961       }
   65962       pCur->skipNext = 0;
   65963     }
   65964   }
   65965 
   65966   pPage = pCur->pPage;
   65967   idx = ++pCur->ix;
   65968   assert( pPage->isInit );
   65969 
   65970   /* If the database file is corrupt, it is possible for the value of idx
   65971   ** to be invalid here. This can only occur if a second cursor modifies
   65972   ** the page while cursor pCur is holding a reference to it. Which can
   65973   ** only happen if the database is corrupt in such a way as to link the
   65974   ** page into more than one b-tree structure. */
   65975   testcase( idx>pPage->nCell );
   65976 
   65977   if( idx>=pPage->nCell ){
   65978     if( !pPage->leaf ){
   65979       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   65980       if( rc ) return rc;
   65981       return moveToLeftmost(pCur);
   65982     }
   65983     do{
   65984       if( pCur->iPage==0 ){
   65985         pCur->eState = CURSOR_INVALID;
   65986         return SQLITE_DONE;
   65987       }
   65988       moveToParent(pCur);
   65989       pPage = pCur->pPage;
   65990     }while( pCur->ix>=pPage->nCell );
   65991     if( pPage->intKey ){
   65992       return sqlite3BtreeNext(pCur, 0);
   65993     }else{
   65994       return SQLITE_OK;
   65995     }
   65996   }
   65997   if( pPage->leaf ){
   65998     return SQLITE_OK;
   65999   }else{
   66000     return moveToLeftmost(pCur);
   66001   }
   66002 }
   66003 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
   66004   MemPage *pPage;
   66005   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
   66006   assert( cursorOwnsBtShared(pCur) );
   66007   assert( flags==0 || flags==1 );
   66008   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   66009   pCur->info.nSize = 0;
   66010   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
   66011   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
   66012   pPage = pCur->pPage;
   66013   if( (++pCur->ix)>=pPage->nCell ){
   66014     pCur->ix--;
   66015     return btreeNext(pCur);
   66016   }
   66017   if( pPage->leaf ){
   66018     return SQLITE_OK;
   66019   }else{
   66020     return moveToLeftmost(pCur);
   66021   }
   66022 }
   66023 
   66024 /*
   66025 ** Step the cursor to the back to the previous entry in the database.
   66026 ** Return values:
   66027 **
   66028 **     SQLITE_OK     success
   66029 **     SQLITE_DONE   the cursor is already on the first element of the table
   66030 **     otherwise     some kind of error occurred
   66031 **
   66032 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
   66033 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
   66034 ** to the previous cell on the current page.  The (slower) btreePrevious()
   66035 ** helper routine is called when it is necessary to move to a different page
   66036 ** or to restore the cursor.
   66037 **
   66038 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
   66039 ** the cursor corresponds to an SQL index and this routine could have been
   66040 ** skipped if the SQL index had been a unique index.  The F argument is a
   66041 ** hint to the implement.  The native SQLite btree implementation does not
   66042 ** use this hint, but COMDB2 does.
   66043 */
   66044 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
   66045   int rc;
   66046   MemPage *pPage;
   66047 
   66048   assert( cursorOwnsBtShared(pCur) );
   66049   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   66050   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
   66051   assert( pCur->info.nSize==0 );
   66052   if( pCur->eState!=CURSOR_VALID ){
   66053     rc = restoreCursorPosition(pCur);
   66054     if( rc!=SQLITE_OK ){
   66055       return rc;
   66056     }
   66057     if( CURSOR_INVALID==pCur->eState ){
   66058       return SQLITE_DONE;
   66059     }
   66060     if( pCur->skipNext ){
   66061       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
   66062       pCur->eState = CURSOR_VALID;
   66063       if( pCur->skipNext<0 ){
   66064         pCur->skipNext = 0;
   66065         return SQLITE_OK;
   66066       }
   66067       pCur->skipNext = 0;
   66068     }
   66069   }
   66070 
   66071   pPage = pCur->pPage;
   66072   assert( pPage->isInit );
   66073   if( !pPage->leaf ){
   66074     int idx = pCur->ix;
   66075     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
   66076     if( rc ) return rc;
   66077     rc = moveToRightmost(pCur);
   66078   }else{
   66079     while( pCur->ix==0 ){
   66080       if( pCur->iPage==0 ){
   66081         pCur->eState = CURSOR_INVALID;
   66082         return SQLITE_DONE;
   66083       }
   66084       moveToParent(pCur);
   66085     }
   66086     assert( pCur->info.nSize==0 );
   66087     assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
   66088 
   66089     pCur->ix--;
   66090     pPage = pCur->pPage;
   66091     if( pPage->intKey && !pPage->leaf ){
   66092       rc = sqlite3BtreePrevious(pCur, 0);
   66093     }else{
   66094       rc = SQLITE_OK;
   66095     }
   66096   }
   66097   return rc;
   66098 }
   66099 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
   66100   assert( cursorOwnsBtShared(pCur) );
   66101   assert( flags==0 || flags==1 );
   66102   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
   66103   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
   66104   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
   66105   pCur->info.nSize = 0;
   66106   if( pCur->eState!=CURSOR_VALID
   66107    || pCur->ix==0
   66108    || pCur->pPage->leaf==0
   66109   ){
   66110     return btreePrevious(pCur);
   66111   }
   66112   pCur->ix--;
   66113   return SQLITE_OK;
   66114 }
   66115 
   66116 /*
   66117 ** Allocate a new page from the database file.
   66118 **
   66119 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
   66120 ** has already been called on the new page.)  The new page has also
   66121 ** been referenced and the calling routine is responsible for calling
   66122 ** sqlite3PagerUnref() on the new page when it is done.
   66123 **
   66124 ** SQLITE_OK is returned on success.  Any other return value indicates
   66125 ** an error.  *ppPage is set to NULL in the event of an error.
   66126 **
   66127 ** If the "nearby" parameter is not 0, then an effort is made to
   66128 ** locate a page close to the page number "nearby".  This can be used in an
   66129 ** attempt to keep related pages close to each other in the database file,
   66130 ** which in turn can make database access faster.
   66131 **
   66132 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
   66133 ** anywhere on the free-list, then it is guaranteed to be returned.  If
   66134 ** eMode is BTALLOC_LT then the page returned will be less than or equal
   66135 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
   66136 ** are no restrictions on which page is returned.
   66137 */
   66138 static int allocateBtreePage(
   66139   BtShared *pBt,         /* The btree */
   66140   MemPage **ppPage,      /* Store pointer to the allocated page here */
   66141   Pgno *pPgno,           /* Store the page number here */
   66142   Pgno nearby,           /* Search for a page near this one */
   66143   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
   66144 ){
   66145   MemPage *pPage1;
   66146   int rc;
   66147   u32 n;     /* Number of pages on the freelist */
   66148   u32 k;     /* Number of leaves on the trunk of the freelist */
   66149   MemPage *pTrunk = 0;
   66150   MemPage *pPrevTrunk = 0;
   66151   Pgno mxPage;     /* Total size of the database file */
   66152 
   66153   assert( sqlite3_mutex_held(pBt->mutex) );
   66154   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
   66155   pPage1 = pBt->pPage1;
   66156   mxPage = btreePagecount(pBt);
   66157   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
   66158   ** stores stores the total number of pages on the freelist. */
   66159   n = get4byte(&pPage1->aData[36]);
   66160   testcase( n==mxPage-1 );
   66161   if( n>=mxPage ){
   66162     return SQLITE_CORRUPT_BKPT;
   66163   }
   66164   if( n>0 ){
   66165     /* There are pages on the freelist.  Reuse one of those pages. */
   66166     Pgno iTrunk;
   66167     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
   66168     u32 nSearch = 0;   /* Count of the number of search attempts */
   66169 
   66170     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
   66171     ** shows that the page 'nearby' is somewhere on the free-list, then
   66172     ** the entire-list will be searched for that page.
   66173     */
   66174 #ifndef SQLITE_OMIT_AUTOVACUUM
   66175     if( eMode==BTALLOC_EXACT ){
   66176       if( nearby<=mxPage ){
   66177         u8 eType;
   66178         assert( nearby>0 );
   66179         assert( pBt->autoVacuum );
   66180         rc = ptrmapGet(pBt, nearby, &eType, 0);
   66181         if( rc ) return rc;
   66182         if( eType==PTRMAP_FREEPAGE ){
   66183           searchList = 1;
   66184         }
   66185       }
   66186     }else if( eMode==BTALLOC_LE ){
   66187       searchList = 1;
   66188     }
   66189 #endif
   66190 
   66191     /* Decrement the free-list count by 1. Set iTrunk to the index of the
   66192     ** first free-list trunk page. iPrevTrunk is initially 1.
   66193     */
   66194     rc = sqlite3PagerWrite(pPage1->pDbPage);
   66195     if( rc ) return rc;
   66196     put4byte(&pPage1->aData[36], n-1);
   66197 
   66198     /* The code within this loop is run only once if the 'searchList' variable
   66199     ** is not true. Otherwise, it runs once for each trunk-page on the
   66200     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
   66201     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
   66202     */
   66203     do {
   66204       pPrevTrunk = pTrunk;
   66205       if( pPrevTrunk ){
   66206         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
   66207         ** is the page number of the next freelist trunk page in the list or
   66208         ** zero if this is the last freelist trunk page. */
   66209         iTrunk = get4byte(&pPrevTrunk->aData[0]);
   66210       }else{
   66211         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
   66212         ** stores the page number of the first page of the freelist, or zero if
   66213         ** the freelist is empty. */
   66214         iTrunk = get4byte(&pPage1->aData[32]);
   66215       }
   66216       testcase( iTrunk==mxPage );
   66217       if( iTrunk>mxPage || nSearch++ > n ){
   66218         rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
   66219       }else{
   66220         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
   66221       }
   66222       if( rc ){
   66223         pTrunk = 0;
   66224         goto end_allocate_page;
   66225       }
   66226       assert( pTrunk!=0 );
   66227       assert( pTrunk->aData!=0 );
   66228       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
   66229       ** is the number of leaf page pointers to follow. */
   66230       k = get4byte(&pTrunk->aData[4]);
   66231       if( k==0 && !searchList ){
   66232         /* The trunk has no leaves and the list is not being searched.
   66233         ** So extract the trunk page itself and use it as the newly
   66234         ** allocated page */
   66235         assert( pPrevTrunk==0 );
   66236         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   66237         if( rc ){
   66238           goto end_allocate_page;
   66239         }
   66240         *pPgno = iTrunk;
   66241         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   66242         *ppPage = pTrunk;
   66243         pTrunk = 0;
   66244         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   66245       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
   66246         /* Value of k is out of range.  Database corruption */
   66247         rc = SQLITE_CORRUPT_PGNO(iTrunk);
   66248         goto end_allocate_page;
   66249 #ifndef SQLITE_OMIT_AUTOVACUUM
   66250       }else if( searchList
   66251             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
   66252       ){
   66253         /* The list is being searched and this trunk page is the page
   66254         ** to allocate, regardless of whether it has leaves.
   66255         */
   66256         *pPgno = iTrunk;
   66257         *ppPage = pTrunk;
   66258         searchList = 0;
   66259         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   66260         if( rc ){
   66261           goto end_allocate_page;
   66262         }
   66263         if( k==0 ){
   66264           if( !pPrevTrunk ){
   66265             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   66266           }else{
   66267             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   66268             if( rc!=SQLITE_OK ){
   66269               goto end_allocate_page;
   66270             }
   66271             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
   66272           }
   66273         }else{
   66274           /* The trunk page is required by the caller but it contains
   66275           ** pointers to free-list leaves. The first leaf becomes a trunk
   66276           ** page in this case.
   66277           */
   66278           MemPage *pNewTrunk;
   66279           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
   66280           if( iNewTrunk>mxPage ){
   66281             rc = SQLITE_CORRUPT_PGNO(iTrunk);
   66282             goto end_allocate_page;
   66283           }
   66284           testcase( iNewTrunk==mxPage );
   66285           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
   66286           if( rc!=SQLITE_OK ){
   66287             goto end_allocate_page;
   66288           }
   66289           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
   66290           if( rc!=SQLITE_OK ){
   66291             releasePage(pNewTrunk);
   66292             goto end_allocate_page;
   66293           }
   66294           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
   66295           put4byte(&pNewTrunk->aData[4], k-1);
   66296           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
   66297           releasePage(pNewTrunk);
   66298           if( !pPrevTrunk ){
   66299             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
   66300             put4byte(&pPage1->aData[32], iNewTrunk);
   66301           }else{
   66302             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   66303             if( rc ){
   66304               goto end_allocate_page;
   66305             }
   66306             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
   66307           }
   66308         }
   66309         pTrunk = 0;
   66310         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   66311 #endif
   66312       }else if( k>0 ){
   66313         /* Extract a leaf from the trunk */
   66314         u32 closest;
   66315         Pgno iPage;
   66316         unsigned char *aData = pTrunk->aData;
   66317         if( nearby>0 ){
   66318           u32 i;
   66319           closest = 0;
   66320           if( eMode==BTALLOC_LE ){
   66321             for(i=0; i<k; i++){
   66322               iPage = get4byte(&aData[8+i*4]);
   66323               if( iPage<=nearby ){
   66324                 closest = i;
   66325                 break;
   66326               }
   66327             }
   66328           }else{
   66329             int dist;
   66330             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
   66331             for(i=1; i<k; i++){
   66332               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
   66333               if( d2<dist ){
   66334                 closest = i;
   66335                 dist = d2;
   66336               }
   66337             }
   66338           }
   66339         }else{
   66340           closest = 0;
   66341         }
   66342 
   66343         iPage = get4byte(&aData[8+closest*4]);
   66344         testcase( iPage==mxPage );
   66345         if( iPage>mxPage ){
   66346           rc = SQLITE_CORRUPT_PGNO(iTrunk);
   66347           goto end_allocate_page;
   66348         }
   66349         testcase( iPage==mxPage );
   66350         if( !searchList
   66351          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
   66352         ){
   66353           int noContent;
   66354           *pPgno = iPage;
   66355           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
   66356                  ": %d more free pages\n",
   66357                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
   66358           rc = sqlite3PagerWrite(pTrunk->pDbPage);
   66359           if( rc ) goto end_allocate_page;
   66360           if( closest<k-1 ){
   66361             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
   66362           }
   66363           put4byte(&aData[4], k-1);
   66364           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
   66365           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
   66366           if( rc==SQLITE_OK ){
   66367             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   66368             if( rc!=SQLITE_OK ){
   66369               releasePage(*ppPage);
   66370               *ppPage = 0;
   66371             }
   66372           }
   66373           searchList = 0;
   66374         }
   66375       }
   66376       releasePage(pPrevTrunk);
   66377       pPrevTrunk = 0;
   66378     }while( searchList );
   66379   }else{
   66380     /* There are no pages on the freelist, so append a new page to the
   66381     ** database image.
   66382     **
   66383     ** Normally, new pages allocated by this block can be requested from the
   66384     ** pager layer with the 'no-content' flag set. This prevents the pager
   66385     ** from trying to read the pages content from disk. However, if the
   66386     ** current transaction has already run one or more incremental-vacuum
   66387     ** steps, then the page we are about to allocate may contain content
   66388     ** that is required in the event of a rollback. In this case, do
   66389     ** not set the no-content flag. This causes the pager to load and journal
   66390     ** the current page content before overwriting it.
   66391     **
   66392     ** Note that the pager will not actually attempt to load or journal
   66393     ** content for any page that really does lie past the end of the database
   66394     ** file on disk. So the effects of disabling the no-content optimization
   66395     ** here are confined to those pages that lie between the end of the
   66396     ** database image and the end of the database file.
   66397     */
   66398     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
   66399 
   66400     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   66401     if( rc ) return rc;
   66402     pBt->nPage++;
   66403     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
   66404 
   66405 #ifndef SQLITE_OMIT_AUTOVACUUM
   66406     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
   66407       /* If *pPgno refers to a pointer-map page, allocate two new pages
   66408       ** at the end of the file instead of one. The first allocated page
   66409       ** becomes a new pointer-map page, the second is used by the caller.
   66410       */
   66411       MemPage *pPg = 0;
   66412       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
   66413       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
   66414       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
   66415       if( rc==SQLITE_OK ){
   66416         rc = sqlite3PagerWrite(pPg->pDbPage);
   66417         releasePage(pPg);
   66418       }
   66419       if( rc ) return rc;
   66420       pBt->nPage++;
   66421       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
   66422     }
   66423 #endif
   66424     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
   66425     *pPgno = pBt->nPage;
   66426 
   66427     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   66428     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
   66429     if( rc ) return rc;
   66430     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   66431     if( rc!=SQLITE_OK ){
   66432       releasePage(*ppPage);
   66433       *ppPage = 0;
   66434     }
   66435     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
   66436   }
   66437 
   66438   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   66439 
   66440 end_allocate_page:
   66441   releasePage(pTrunk);
   66442   releasePage(pPrevTrunk);
   66443   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
   66444   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
   66445   return rc;
   66446 }
   66447 
   66448 /*
   66449 ** This function is used to add page iPage to the database file free-list.
   66450 ** It is assumed that the page is not already a part of the free-list.
   66451 **
   66452 ** The value passed as the second argument to this function is optional.
   66453 ** If the caller happens to have a pointer to the MemPage object
   66454 ** corresponding to page iPage handy, it may pass it as the second value.
   66455 ** Otherwise, it may pass NULL.
   66456 **
   66457 ** If a pointer to a MemPage object is passed as the second argument,
   66458 ** its reference count is not altered by this function.
   66459 */
   66460 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   66461   MemPage *pTrunk = 0;                /* Free-list trunk page */
   66462   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   66463   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   66464   MemPage *pPage;                     /* Page being freed. May be NULL. */
   66465   int rc;                             /* Return Code */
   66466   int nFree;                          /* Initial number of pages on free-list */
   66467 
   66468   assert( sqlite3_mutex_held(pBt->mutex) );
   66469   assert( CORRUPT_DB || iPage>1 );
   66470   assert( !pMemPage || pMemPage->pgno==iPage );
   66471 
   66472   if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
   66473   if( pMemPage ){
   66474     pPage = pMemPage;
   66475     sqlite3PagerRef(pPage->pDbPage);
   66476   }else{
   66477     pPage = btreePageLookup(pBt, iPage);
   66478   }
   66479 
   66480   /* Increment the free page count on pPage1 */
   66481   rc = sqlite3PagerWrite(pPage1->pDbPage);
   66482   if( rc ) goto freepage_out;
   66483   nFree = get4byte(&pPage1->aData[36]);
   66484   put4byte(&pPage1->aData[36], nFree+1);
   66485 
   66486   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   66487     /* If the secure_delete option is enabled, then
   66488     ** always fully overwrite deleted information with zeros.
   66489     */
   66490     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
   66491      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
   66492     ){
   66493       goto freepage_out;
   66494     }
   66495     memset(pPage->aData, 0, pPage->pBt->pageSize);
   66496   }
   66497 
   66498   /* If the database supports auto-vacuum, write an entry in the pointer-map
   66499   ** to indicate that the page is free.
   66500   */
   66501   if( ISAUTOVACUUM ){
   66502     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
   66503     if( rc ) goto freepage_out;
   66504   }
   66505 
   66506   /* Now manipulate the actual database free-list structure. There are two
   66507   ** possibilities. If the free-list is currently empty, or if the first
   66508   ** trunk page in the free-list is full, then this page will become a
   66509   ** new free-list trunk page. Otherwise, it will become a leaf of the
   66510   ** first trunk page in the current free-list. This block tests if it
   66511   ** is possible to add the page as a new free-list leaf.
   66512   */
   66513   if( nFree!=0 ){
   66514     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
   66515 
   66516     iTrunk = get4byte(&pPage1->aData[32]);
   66517     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   66518     if( rc!=SQLITE_OK ){
   66519       goto freepage_out;
   66520     }
   66521 
   66522     nLeaf = get4byte(&pTrunk->aData[4]);
   66523     assert( pBt->usableSize>32 );
   66524     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
   66525       rc = SQLITE_CORRUPT_BKPT;
   66526       goto freepage_out;
   66527     }
   66528     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
   66529       /* In this case there is room on the trunk page to insert the page
   66530       ** being freed as a new leaf.
   66531       **
   66532       ** Note that the trunk page is not really full until it contains
   66533       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
   66534       ** coded.  But due to a coding error in versions of SQLite prior to
   66535       ** 3.6.0, databases with freelist trunk pages holding more than
   66536       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
   66537       ** to maintain backwards compatibility with older versions of SQLite,
   66538       ** we will continue to restrict the number of entries to usableSize/4 - 8
   66539       ** for now.  At some point in the future (once everyone has upgraded
   66540       ** to 3.6.0 or later) we should consider fixing the conditional above
   66541       ** to read "usableSize/4-2" instead of "usableSize/4-8".
   66542       **
   66543       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
   66544       ** avoid using the last six entries in the freelist trunk page array in
   66545       ** order that database files created by newer versions of SQLite can be
   66546       ** read by older versions of SQLite.
   66547       */
   66548       rc = sqlite3PagerWrite(pTrunk->pDbPage);
   66549       if( rc==SQLITE_OK ){
   66550         put4byte(&pTrunk->aData[4], nLeaf+1);
   66551         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
   66552         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
   66553           sqlite3PagerDontWrite(pPage->pDbPage);
   66554         }
   66555         rc = btreeSetHasContent(pBt, iPage);
   66556       }
   66557       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
   66558       goto freepage_out;
   66559     }
   66560   }
   66561 
   66562   /* If control flows to this point, then it was not possible to add the
   66563   ** the page being freed as a leaf page of the first trunk in the free-list.
   66564   ** Possibly because the free-list is empty, or possibly because the
   66565   ** first trunk in the free-list is full. Either way, the page being freed
   66566   ** will become the new first trunk page in the free-list.
   66567   */
   66568   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
   66569     goto freepage_out;
   66570   }
   66571   rc = sqlite3PagerWrite(pPage->pDbPage);
   66572   if( rc!=SQLITE_OK ){
   66573     goto freepage_out;
   66574   }
   66575   put4byte(pPage->aData, iTrunk);
   66576   put4byte(&pPage->aData[4], 0);
   66577   put4byte(&pPage1->aData[32], iPage);
   66578   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
   66579 
   66580 freepage_out:
   66581   if( pPage ){
   66582     pPage->isInit = 0;
   66583   }
   66584   releasePage(pPage);
   66585   releasePage(pTrunk);
   66586   return rc;
   66587 }
   66588 static void freePage(MemPage *pPage, int *pRC){
   66589   if( (*pRC)==SQLITE_OK ){
   66590     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
   66591   }
   66592 }
   66593 
   66594 /*
   66595 ** Free any overflow pages associated with the given Cell.  Write the
   66596 ** local Cell size (the number of bytes on the original page, omitting
   66597 ** overflow) into *pnSize.
   66598 */
   66599 static int clearCell(
   66600   MemPage *pPage,          /* The page that contains the Cell */
   66601   unsigned char *pCell,    /* First byte of the Cell */
   66602   CellInfo *pInfo          /* Size information about the cell */
   66603 ){
   66604   BtShared *pBt;
   66605   Pgno ovflPgno;
   66606   int rc;
   66607   int nOvfl;
   66608   u32 ovflPageSize;
   66609 
   66610   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   66611   pPage->xParseCell(pPage, pCell, pInfo);
   66612   if( pInfo->nLocal==pInfo->nPayload ){
   66613     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
   66614   }
   66615   if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
   66616     /* Cell extends past end of page */
   66617     return SQLITE_CORRUPT_PAGE(pPage);
   66618   }
   66619   ovflPgno = get4byte(pCell + pInfo->nSize - 4);
   66620   pBt = pPage->pBt;
   66621   assert( pBt->usableSize > 4 );
   66622   ovflPageSize = pBt->usableSize - 4;
   66623   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
   66624   assert( nOvfl>0 ||
   66625     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
   66626   );
   66627   while( nOvfl-- ){
   66628     Pgno iNext = 0;
   66629     MemPage *pOvfl = 0;
   66630     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
   66631       /* 0 is not a legal page number and page 1 cannot be an
   66632       ** overflow page. Therefore if ovflPgno<2 or past the end of the
   66633       ** file the database must be corrupt. */
   66634       return SQLITE_CORRUPT_BKPT;
   66635     }
   66636     if( nOvfl ){
   66637       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
   66638       if( rc ) return rc;
   66639     }
   66640 
   66641     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
   66642      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
   66643     ){
   66644       /* There is no reason any cursor should have an outstanding reference
   66645       ** to an overflow page belonging to a cell that is being deleted/updated.
   66646       ** So if there exists more than one reference to this page, then it
   66647       ** must not really be an overflow page and the database must be corrupt.
   66648       ** It is helpful to detect this before calling freePage2(), as
   66649       ** freePage2() may zero the page contents if secure-delete mode is
   66650       ** enabled. If this 'overflow' page happens to be a page that the
   66651       ** caller is iterating through or using in some other way, this
   66652       ** can be problematic.
   66653       */
   66654       rc = SQLITE_CORRUPT_BKPT;
   66655     }else{
   66656       rc = freePage2(pBt, pOvfl, ovflPgno);
   66657     }
   66658 
   66659     if( pOvfl ){
   66660       sqlite3PagerUnref(pOvfl->pDbPage);
   66661     }
   66662     if( rc ) return rc;
   66663     ovflPgno = iNext;
   66664   }
   66665   return SQLITE_OK;
   66666 }
   66667 
   66668 /*
   66669 ** Create the byte sequence used to represent a cell on page pPage
   66670 ** and write that byte sequence into pCell[].  Overflow pages are
   66671 ** allocated and filled in as necessary.  The calling procedure
   66672 ** is responsible for making sure sufficient space has been allocated
   66673 ** for pCell[].
   66674 **
   66675 ** Note that pCell does not necessary need to point to the pPage->aData
   66676 ** area.  pCell might point to some temporary storage.  The cell will
   66677 ** be constructed in this temporary area then copied into pPage->aData
   66678 ** later.
   66679 */
   66680 static int fillInCell(
   66681   MemPage *pPage,                /* The page that contains the cell */
   66682   unsigned char *pCell,          /* Complete text of the cell */
   66683   const BtreePayload *pX,        /* Payload with which to construct the cell */
   66684   int *pnSize                    /* Write cell size here */
   66685 ){
   66686   int nPayload;
   66687   const u8 *pSrc;
   66688   int nSrc, n, rc, mn;
   66689   int spaceLeft;
   66690   MemPage *pToRelease;
   66691   unsigned char *pPrior;
   66692   unsigned char *pPayload;
   66693   BtShared *pBt;
   66694   Pgno pgnoOvfl;
   66695   int nHeader;
   66696 
   66697   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   66698 
   66699   /* pPage is not necessarily writeable since pCell might be auxiliary
   66700   ** buffer space that is separate from the pPage buffer area */
   66701   assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
   66702             || sqlite3PagerIswriteable(pPage->pDbPage) );
   66703 
   66704   /* Fill in the header. */
   66705   nHeader = pPage->childPtrSize;
   66706   if( pPage->intKey ){
   66707     nPayload = pX->nData + pX->nZero;
   66708     pSrc = pX->pData;
   66709     nSrc = pX->nData;
   66710     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
   66711     nHeader += putVarint32(&pCell[nHeader], nPayload);
   66712     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
   66713   }else{
   66714     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
   66715     nSrc = nPayload = (int)pX->nKey;
   66716     pSrc = pX->pKey;
   66717     nHeader += putVarint32(&pCell[nHeader], nPayload);
   66718   }
   66719 
   66720   /* Fill in the payload */
   66721   pPayload = &pCell[nHeader];
   66722   if( nPayload<=pPage->maxLocal ){
   66723     /* This is the common case where everything fits on the btree page
   66724     ** and no overflow pages are required. */
   66725     n = nHeader + nPayload;
   66726     testcase( n==3 );
   66727     testcase( n==4 );
   66728     if( n<4 ) n = 4;
   66729     *pnSize = n;
   66730     assert( nSrc<=nPayload );
   66731     testcase( nSrc<nPayload );
   66732     memcpy(pPayload, pSrc, nSrc);
   66733     memset(pPayload+nSrc, 0, nPayload-nSrc);
   66734     return SQLITE_OK;
   66735   }
   66736 
   66737   /* If we reach this point, it means that some of the content will need
   66738   ** to spill onto overflow pages.
   66739   */
   66740   mn = pPage->minLocal;
   66741   n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
   66742   testcase( n==pPage->maxLocal );
   66743   testcase( n==pPage->maxLocal+1 );
   66744   if( n > pPage->maxLocal ) n = mn;
   66745   spaceLeft = n;
   66746   *pnSize = n + nHeader + 4;
   66747   pPrior = &pCell[nHeader+n];
   66748   pToRelease = 0;
   66749   pgnoOvfl = 0;
   66750   pBt = pPage->pBt;
   66751 
   66752   /* At this point variables should be set as follows:
   66753   **
   66754   **   nPayload           Total payload size in bytes
   66755   **   pPayload           Begin writing payload here
   66756   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
   66757   **                      that means content must spill into overflow pages.
   66758   **   *pnSize            Size of the local cell (not counting overflow pages)
   66759   **   pPrior             Where to write the pgno of the first overflow page
   66760   **
   66761   ** Use a call to btreeParseCellPtr() to verify that the values above
   66762   ** were computed correctly.
   66763   */
   66764 #ifdef SQLITE_DEBUG
   66765   {
   66766     CellInfo info;
   66767     pPage->xParseCell(pPage, pCell, &info);
   66768     assert( nHeader==(int)(info.pPayload - pCell) );
   66769     assert( info.nKey==pX->nKey );
   66770     assert( *pnSize == info.nSize );
   66771     assert( spaceLeft == info.nLocal );
   66772   }
   66773 #endif
   66774 
   66775   /* Write the payload into the local Cell and any extra into overflow pages */
   66776   while( 1 ){
   66777     n = nPayload;
   66778     if( n>spaceLeft ) n = spaceLeft;
   66779 
   66780     /* If pToRelease is not zero than pPayload points into the data area
   66781     ** of pToRelease.  Make sure pToRelease is still writeable. */
   66782     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   66783 
   66784     /* If pPayload is part of the data area of pPage, then make sure pPage
   66785     ** is still writeable */
   66786     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
   66787             || sqlite3PagerIswriteable(pPage->pDbPage) );
   66788 
   66789     if( nSrc>=n ){
   66790       memcpy(pPayload, pSrc, n);
   66791     }else if( nSrc>0 ){
   66792       n = nSrc;
   66793       memcpy(pPayload, pSrc, n);
   66794     }else{
   66795       memset(pPayload, 0, n);
   66796     }
   66797     nPayload -= n;
   66798     if( nPayload<=0 ) break;
   66799     pPayload += n;
   66800     pSrc += n;
   66801     nSrc -= n;
   66802     spaceLeft -= n;
   66803     if( spaceLeft==0 ){
   66804       MemPage *pOvfl = 0;
   66805 #ifndef SQLITE_OMIT_AUTOVACUUM
   66806       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
   66807       if( pBt->autoVacuum ){
   66808         do{
   66809           pgnoOvfl++;
   66810         } while(
   66811           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
   66812         );
   66813       }
   66814 #endif
   66815       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
   66816 #ifndef SQLITE_OMIT_AUTOVACUUM
   66817       /* If the database supports auto-vacuum, and the second or subsequent
   66818       ** overflow page is being allocated, add an entry to the pointer-map
   66819       ** for that page now.
   66820       **
   66821       ** If this is the first overflow page, then write a partial entry
   66822       ** to the pointer-map. If we write nothing to this pointer-map slot,
   66823       ** then the optimistic overflow chain processing in clearCell()
   66824       ** may misinterpret the uninitialized values and delete the
   66825       ** wrong pages from the database.
   66826       */
   66827       if( pBt->autoVacuum && rc==SQLITE_OK ){
   66828         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
   66829         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
   66830         if( rc ){
   66831           releasePage(pOvfl);
   66832         }
   66833       }
   66834 #endif
   66835       if( rc ){
   66836         releasePage(pToRelease);
   66837         return rc;
   66838       }
   66839 
   66840       /* If pToRelease is not zero than pPrior points into the data area
   66841       ** of pToRelease.  Make sure pToRelease is still writeable. */
   66842       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   66843 
   66844       /* If pPrior is part of the data area of pPage, then make sure pPage
   66845       ** is still writeable */
   66846       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
   66847             || sqlite3PagerIswriteable(pPage->pDbPage) );
   66848 
   66849       put4byte(pPrior, pgnoOvfl);
   66850       releasePage(pToRelease);
   66851       pToRelease = pOvfl;
   66852       pPrior = pOvfl->aData;
   66853       put4byte(pPrior, 0);
   66854       pPayload = &pOvfl->aData[4];
   66855       spaceLeft = pBt->usableSize - 4;
   66856     }
   66857   }
   66858   releasePage(pToRelease);
   66859   return SQLITE_OK;
   66860 }
   66861 
   66862 /*
   66863 ** Remove the i-th cell from pPage.  This routine effects pPage only.
   66864 ** The cell content is not freed or deallocated.  It is assumed that
   66865 ** the cell content has been copied someplace else.  This routine just
   66866 ** removes the reference to the cell from pPage.
   66867 **
   66868 ** "sz" must be the number of bytes in the cell.
   66869 */
   66870 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   66871   u32 pc;         /* Offset to cell content of cell being deleted */
   66872   u8 *data;       /* pPage->aData */
   66873   u8 *ptr;        /* Used to move bytes around within data[] */
   66874   int rc;         /* The return code */
   66875   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
   66876 
   66877   if( *pRC ) return;
   66878   assert( idx>=0 && idx<pPage->nCell );
   66879   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
   66880   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   66881   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   66882   data = pPage->aData;
   66883   ptr = &pPage->aCellIdx[2*idx];
   66884   pc = get2byte(ptr);
   66885   hdr = pPage->hdrOffset;
   66886   testcase( pc==get2byte(&data[hdr+5]) );
   66887   testcase( pc+sz==pPage->pBt->usableSize );
   66888   if( pc+sz > pPage->pBt->usableSize ){
   66889     *pRC = SQLITE_CORRUPT_BKPT;
   66890     return;
   66891   }
   66892   rc = freeSpace(pPage, pc, sz);
   66893   if( rc ){
   66894     *pRC = rc;
   66895     return;
   66896   }
   66897   pPage->nCell--;
   66898   if( pPage->nCell==0 ){
   66899     memset(&data[hdr+1], 0, 4);
   66900     data[hdr+7] = 0;
   66901     put2byte(&data[hdr+5], pPage->pBt->usableSize);
   66902     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
   66903                        - pPage->childPtrSize - 8;
   66904   }else{
   66905     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
   66906     put2byte(&data[hdr+3], pPage->nCell);
   66907     pPage->nFree += 2;
   66908   }
   66909 }
   66910 
   66911 /*
   66912 ** Insert a new cell on pPage at cell index "i".  pCell points to the
   66913 ** content of the cell.
   66914 **
   66915 ** If the cell content will fit on the page, then put it there.  If it
   66916 ** will not fit, then make a copy of the cell content into pTemp if
   66917 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
   66918 ** in pPage->apOvfl[] and make it point to the cell content (either
   66919 ** in pTemp or the original pCell) and also record its index.
   66920 ** Allocating a new entry in pPage->aCell[] implies that
   66921 ** pPage->nOverflow is incremented.
   66922 **
   66923 ** *pRC must be SQLITE_OK when this routine is called.
   66924 */
   66925 static void insertCell(
   66926   MemPage *pPage,   /* Page into which we are copying */
   66927   int i,            /* New cell becomes the i-th cell of the page */
   66928   u8 *pCell,        /* Content of the new cell */
   66929   int sz,           /* Bytes of content in pCell */
   66930   u8 *pTemp,        /* Temp storage space for pCell, if needed */
   66931   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
   66932   int *pRC          /* Read and write return code from here */
   66933 ){
   66934   int idx = 0;      /* Where to write new cell content in data[] */
   66935   int j;            /* Loop counter */
   66936   u8 *data;         /* The content of the whole page */
   66937   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
   66938 
   66939   assert( *pRC==SQLITE_OK );
   66940   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
   66941   assert( MX_CELL(pPage->pBt)<=10921 );
   66942   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
   66943   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
   66944   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
   66945   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   66946   /* The cell should normally be sized correctly.  However, when moving a
   66947   ** malformed cell from a leaf page to an interior page, if the cell size
   66948   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
   66949   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
   66950   ** the term after the || in the following assert(). */
   66951   assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
   66952   if( pPage->nOverflow || sz+2>pPage->nFree ){
   66953     if( pTemp ){
   66954       memcpy(pTemp, pCell, sz);
   66955       pCell = pTemp;
   66956     }
   66957     if( iChild ){
   66958       put4byte(pCell, iChild);
   66959     }
   66960     j = pPage->nOverflow++;
   66961     /* Comparison against ArraySize-1 since we hold back one extra slot
   66962     ** as a contingency.  In other words, never need more than 3 overflow
   66963     ** slots but 4 are allocated, just to be safe. */
   66964     assert( j < ArraySize(pPage->apOvfl)-1 );
   66965     pPage->apOvfl[j] = pCell;
   66966     pPage->aiOvfl[j] = (u16)i;
   66967 
   66968     /* When multiple overflows occur, they are always sequential and in
   66969     ** sorted order.  This invariants arise because multiple overflows can
   66970     ** only occur when inserting divider cells into the parent page during
   66971     ** balancing, and the dividers are adjacent and sorted.
   66972     */
   66973     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
   66974     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
   66975   }else{
   66976     int rc = sqlite3PagerWrite(pPage->pDbPage);
   66977     if( rc!=SQLITE_OK ){
   66978       *pRC = rc;
   66979       return;
   66980     }
   66981     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   66982     data = pPage->aData;
   66983     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
   66984     rc = allocateSpace(pPage, sz, &idx);
   66985     if( rc ){ *pRC = rc; return; }
   66986     /* The allocateSpace() routine guarantees the following properties
   66987     ** if it returns successfully */
   66988     assert( idx >= 0 );
   66989     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
   66990     assert( idx+sz <= (int)pPage->pBt->usableSize );
   66991     pPage->nFree -= (u16)(2 + sz);
   66992     memcpy(&data[idx], pCell, sz);
   66993     if( iChild ){
   66994       put4byte(&data[idx], iChild);
   66995     }
   66996     pIns = pPage->aCellIdx + i*2;
   66997     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
   66998     put2byte(pIns, idx);
   66999     pPage->nCell++;
   67000     /* increment the cell count */
   67001     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
   67002     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
   67003 #ifndef SQLITE_OMIT_AUTOVACUUM
   67004     if( pPage->pBt->autoVacuum ){
   67005       /* The cell may contain a pointer to an overflow page. If so, write
   67006       ** the entry for the overflow page into the pointer map.
   67007       */
   67008       ptrmapPutOvflPtr(pPage, pCell, pRC);
   67009     }
   67010 #endif
   67011   }
   67012 }
   67013 
   67014 /*
   67015 ** A CellArray object contains a cache of pointers and sizes for a
   67016 ** consecutive sequence of cells that might be held on multiple pages.
   67017 */
   67018 typedef struct CellArray CellArray;
   67019 struct CellArray {
   67020   int nCell;              /* Number of cells in apCell[] */
   67021   MemPage *pRef;          /* Reference page */
   67022   u8 **apCell;            /* All cells begin balanced */
   67023   u16 *szCell;            /* Local size of all cells in apCell[] */
   67024 };
   67025 
   67026 /*
   67027 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
   67028 ** computed.
   67029 */
   67030 static void populateCellCache(CellArray *p, int idx, int N){
   67031   assert( idx>=0 && idx+N<=p->nCell );
   67032   while( N>0 ){
   67033     assert( p->apCell[idx]!=0 );
   67034     if( p->szCell[idx]==0 ){
   67035       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
   67036     }else{
   67037       assert( CORRUPT_DB ||
   67038               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
   67039     }
   67040     idx++;
   67041     N--;
   67042   }
   67043 }
   67044 
   67045 /*
   67046 ** Return the size of the Nth element of the cell array
   67047 */
   67048 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
   67049   assert( N>=0 && N<p->nCell );
   67050   assert( p->szCell[N]==0 );
   67051   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
   67052   return p->szCell[N];
   67053 }
   67054 static u16 cachedCellSize(CellArray *p, int N){
   67055   assert( N>=0 && N<p->nCell );
   67056   if( p->szCell[N] ) return p->szCell[N];
   67057   return computeCellSize(p, N);
   67058 }
   67059 
   67060 /*
   67061 ** Array apCell[] contains pointers to nCell b-tree page cells. The
   67062 ** szCell[] array contains the size in bytes of each cell. This function
   67063 ** replaces the current contents of page pPg with the contents of the cell
   67064 ** array.
   67065 **
   67066 ** Some of the cells in apCell[] may currently be stored in pPg. This
   67067 ** function works around problems caused by this by making a copy of any
   67068 ** such cells before overwriting the page data.
   67069 **
   67070 ** The MemPage.nFree field is invalidated by this function. It is the
   67071 ** responsibility of the caller to set it correctly.
   67072 */
   67073 static int rebuildPage(
   67074   MemPage *pPg,                   /* Edit this page */
   67075   int nCell,                      /* Final number of cells on page */
   67076   u8 **apCell,                    /* Array of cells */
   67077   u16 *szCell                     /* Array of cell sizes */
   67078 ){
   67079   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
   67080   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
   67081   const int usableSize = pPg->pBt->usableSize;
   67082   u8 * const pEnd = &aData[usableSize];
   67083   int i;
   67084   u8 *pCellptr = pPg->aCellIdx;
   67085   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
   67086   u8 *pData;
   67087 
   67088   i = get2byte(&aData[hdr+5]);
   67089   memcpy(&pTmp[i], &aData[i], usableSize - i);
   67090 
   67091   pData = pEnd;
   67092   for(i=0; i<nCell; i++){
   67093     u8 *pCell = apCell[i];
   67094     if( SQLITE_WITHIN(pCell,aData,pEnd) ){
   67095       pCell = &pTmp[pCell - aData];
   67096     }
   67097     pData -= szCell[i];
   67098     put2byte(pCellptr, (pData - aData));
   67099     pCellptr += 2;
   67100     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
   67101     memcpy(pData, pCell, szCell[i]);
   67102     assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
   67103     testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
   67104   }
   67105 
   67106   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
   67107   pPg->nCell = nCell;
   67108   pPg->nOverflow = 0;
   67109 
   67110   put2byte(&aData[hdr+1], 0);
   67111   put2byte(&aData[hdr+3], pPg->nCell);
   67112   put2byte(&aData[hdr+5], pData - aData);
   67113   aData[hdr+7] = 0x00;
   67114   return SQLITE_OK;
   67115 }
   67116 
   67117 /*
   67118 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
   67119 ** contains the size in bytes of each such cell. This function attempts to
   67120 ** add the cells stored in the array to page pPg. If it cannot (because
   67121 ** the page needs to be defragmented before the cells will fit), non-zero
   67122 ** is returned. Otherwise, if the cells are added successfully, zero is
   67123 ** returned.
   67124 **
   67125 ** Argument pCellptr points to the first entry in the cell-pointer array
   67126 ** (part of page pPg) to populate. After cell apCell[0] is written to the
   67127 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
   67128 ** cell in the array. It is the responsibility of the caller to ensure
   67129 ** that it is safe to overwrite this part of the cell-pointer array.
   67130 **
   67131 ** When this function is called, *ppData points to the start of the
   67132 ** content area on page pPg. If the size of the content area is extended,
   67133 ** *ppData is updated to point to the new start of the content area
   67134 ** before returning.
   67135 **
   67136 ** Finally, argument pBegin points to the byte immediately following the
   67137 ** end of the space required by this page for the cell-pointer area (for
   67138 ** all cells - not just those inserted by the current call). If the content
   67139 ** area must be extended to before this point in order to accomodate all
   67140 ** cells in apCell[], then the cells do not fit and non-zero is returned.
   67141 */
   67142 static int pageInsertArray(
   67143   MemPage *pPg,                   /* Page to add cells to */
   67144   u8 *pBegin,                     /* End of cell-pointer array */
   67145   u8 **ppData,                    /* IN/OUT: Page content -area pointer */
   67146   u8 *pCellptr,                   /* Pointer to cell-pointer area */
   67147   int iFirst,                     /* Index of first cell to add */
   67148   int nCell,                      /* Number of cells to add to pPg */
   67149   CellArray *pCArray              /* Array of cells */
   67150 ){
   67151   int i;
   67152   u8 *aData = pPg->aData;
   67153   u8 *pData = *ppData;
   67154   int iEnd = iFirst + nCell;
   67155   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
   67156   for(i=iFirst; i<iEnd; i++){
   67157     int sz, rc;
   67158     u8 *pSlot;
   67159     sz = cachedCellSize(pCArray, i);
   67160     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
   67161       if( (pData - pBegin)<sz ) return 1;
   67162       pData -= sz;
   67163       pSlot = pData;
   67164     }
   67165     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
   67166     ** database.  But they might for a corrupt database.  Hence use memmove()
   67167     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
   67168     assert( (pSlot+sz)<=pCArray->apCell[i]
   67169          || pSlot>=(pCArray->apCell[i]+sz)
   67170          || CORRUPT_DB );
   67171     memmove(pSlot, pCArray->apCell[i], sz);
   67172     put2byte(pCellptr, (pSlot - aData));
   67173     pCellptr += 2;
   67174   }
   67175   *ppData = pData;
   67176   return 0;
   67177 }
   67178 
   67179 /*
   67180 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
   67181 ** contains the size in bytes of each such cell. This function adds the
   67182 ** space associated with each cell in the array that is currently stored
   67183 ** within the body of pPg to the pPg free-list. The cell-pointers and other
   67184 ** fields of the page are not updated.
   67185 **
   67186 ** This function returns the total number of cells added to the free-list.
   67187 */
   67188 static int pageFreeArray(
   67189   MemPage *pPg,                   /* Page to edit */
   67190   int iFirst,                     /* First cell to delete */
   67191   int nCell,                      /* Cells to delete */
   67192   CellArray *pCArray              /* Array of cells */
   67193 ){
   67194   u8 * const aData = pPg->aData;
   67195   u8 * const pEnd = &aData[pPg->pBt->usableSize];
   67196   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
   67197   int nRet = 0;
   67198   int i;
   67199   int iEnd = iFirst + nCell;
   67200   u8 *pFree = 0;
   67201   int szFree = 0;
   67202 
   67203   for(i=iFirst; i<iEnd; i++){
   67204     u8 *pCell = pCArray->apCell[i];
   67205     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
   67206       int sz;
   67207       /* No need to use cachedCellSize() here.  The sizes of all cells that
   67208       ** are to be freed have already been computing while deciding which
   67209       ** cells need freeing */
   67210       sz = pCArray->szCell[i];  assert( sz>0 );
   67211       if( pFree!=(pCell + sz) ){
   67212         if( pFree ){
   67213           assert( pFree>aData && (pFree - aData)<65536 );
   67214           freeSpace(pPg, (u16)(pFree - aData), szFree);
   67215         }
   67216         pFree = pCell;
   67217         szFree = sz;
   67218         if( pFree+sz>pEnd ) return 0;
   67219       }else{
   67220         pFree = pCell;
   67221         szFree += sz;
   67222       }
   67223       nRet++;
   67224     }
   67225   }
   67226   if( pFree ){
   67227     assert( pFree>aData && (pFree - aData)<65536 );
   67228     freeSpace(pPg, (u16)(pFree - aData), szFree);
   67229   }
   67230   return nRet;
   67231 }
   67232 
   67233 /*
   67234 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
   67235 ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
   67236 ** with apCell[iOld].  After balancing, this page should hold nNew cells
   67237 ** starting at apCell[iNew].
   67238 **
   67239 ** This routine makes the necessary adjustments to pPg so that it contains
   67240 ** the correct cells after being balanced.
   67241 **
   67242 ** The pPg->nFree field is invalid when this function returns. It is the
   67243 ** responsibility of the caller to set it correctly.
   67244 */
   67245 static int editPage(
   67246   MemPage *pPg,                   /* Edit this page */
   67247   int iOld,                       /* Index of first cell currently on page */
   67248   int iNew,                       /* Index of new first cell on page */
   67249   int nNew,                       /* Final number of cells on page */
   67250   CellArray *pCArray              /* Array of cells and sizes */
   67251 ){
   67252   u8 * const aData = pPg->aData;
   67253   const int hdr = pPg->hdrOffset;
   67254   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
   67255   int nCell = pPg->nCell;       /* Cells stored on pPg */
   67256   u8 *pData;
   67257   u8 *pCellptr;
   67258   int i;
   67259   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
   67260   int iNewEnd = iNew + nNew;
   67261 
   67262 #ifdef SQLITE_DEBUG
   67263   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
   67264   memcpy(pTmp, aData, pPg->pBt->usableSize);
   67265 #endif
   67266 
   67267   /* Remove cells from the start and end of the page */
   67268   if( iOld<iNew ){
   67269     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
   67270     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
   67271     nCell -= nShift;
   67272   }
   67273   if( iNewEnd < iOldEnd ){
   67274     nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
   67275   }
   67276 
   67277   pData = &aData[get2byteNotZero(&aData[hdr+5])];
   67278   if( pData<pBegin ) goto editpage_fail;
   67279 
   67280   /* Add cells to the start of the page */
   67281   if( iNew<iOld ){
   67282     int nAdd = MIN(nNew,iOld-iNew);
   67283     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
   67284     pCellptr = pPg->aCellIdx;
   67285     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
   67286     if( pageInsertArray(
   67287           pPg, pBegin, &pData, pCellptr,
   67288           iNew, nAdd, pCArray
   67289     ) ) goto editpage_fail;
   67290     nCell += nAdd;
   67291   }
   67292 
   67293   /* Add any overflow cells */
   67294   for(i=0; i<pPg->nOverflow; i++){
   67295     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
   67296     if( iCell>=0 && iCell<nNew ){
   67297       pCellptr = &pPg->aCellIdx[iCell * 2];
   67298       memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
   67299       nCell++;
   67300       if( pageInsertArray(
   67301             pPg, pBegin, &pData, pCellptr,
   67302             iCell+iNew, 1, pCArray
   67303       ) ) goto editpage_fail;
   67304     }
   67305   }
   67306 
   67307   /* Append cells to the end of the page */
   67308   pCellptr = &pPg->aCellIdx[nCell*2];
   67309   if( pageInsertArray(
   67310         pPg, pBegin, &pData, pCellptr,
   67311         iNew+nCell, nNew-nCell, pCArray
   67312   ) ) goto editpage_fail;
   67313 
   67314   pPg->nCell = nNew;
   67315   pPg->nOverflow = 0;
   67316 
   67317   put2byte(&aData[hdr+3], pPg->nCell);
   67318   put2byte(&aData[hdr+5], pData - aData);
   67319 
   67320 #ifdef SQLITE_DEBUG
   67321   for(i=0; i<nNew && !CORRUPT_DB; i++){
   67322     u8 *pCell = pCArray->apCell[i+iNew];
   67323     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
   67324     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
   67325       pCell = &pTmp[pCell - aData];
   67326     }
   67327     assert( 0==memcmp(pCell, &aData[iOff],
   67328             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
   67329   }
   67330 #endif
   67331 
   67332   return SQLITE_OK;
   67333  editpage_fail:
   67334   /* Unable to edit this page. Rebuild it from scratch instead. */
   67335   populateCellCache(pCArray, iNew, nNew);
   67336   return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
   67337 }
   67338 
   67339 /*
   67340 ** The following parameters determine how many adjacent pages get involved
   67341 ** in a balancing operation.  NN is the number of neighbors on either side
   67342 ** of the page that participate in the balancing operation.  NB is the
   67343 ** total number of pages that participate, including the target page and
   67344 ** NN neighbors on either side.
   67345 **
   67346 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
   67347 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
   67348 ** in exchange for a larger degradation in INSERT and UPDATE performance.
   67349 ** The value of NN appears to give the best results overall.
   67350 */
   67351 #define NN 1             /* Number of neighbors on either side of pPage */
   67352 #define NB (NN*2+1)      /* Total pages involved in the balance */
   67353 
   67354 
   67355 #ifndef SQLITE_OMIT_QUICKBALANCE
   67356 /*
   67357 ** This version of balance() handles the common special case where
   67358 ** a new entry is being inserted on the extreme right-end of the
   67359 ** tree, in other words, when the new entry will become the largest
   67360 ** entry in the tree.
   67361 **
   67362 ** Instead of trying to balance the 3 right-most leaf pages, just add
   67363 ** a new page to the right-hand side and put the one new entry in
   67364 ** that page.  This leaves the right side of the tree somewhat
   67365 ** unbalanced.  But odds are that we will be inserting new entries
   67366 ** at the end soon afterwards so the nearly empty page will quickly
   67367 ** fill up.  On average.
   67368 **
   67369 ** pPage is the leaf page which is the right-most page in the tree.
   67370 ** pParent is its parent.  pPage must have a single overflow entry
   67371 ** which is also the right-most entry on the page.
   67372 **
   67373 ** The pSpace buffer is used to store a temporary copy of the divider
   67374 ** cell that will be inserted into pParent. Such a cell consists of a 4
   67375 ** byte page number followed by a variable length integer. In other
   67376 ** words, at most 13 bytes. Hence the pSpace buffer must be at
   67377 ** least 13 bytes in size.
   67378 */
   67379 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   67380   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
   67381   MemPage *pNew;                       /* Newly allocated page */
   67382   int rc;                              /* Return Code */
   67383   Pgno pgnoNew;                        /* Page number of pNew */
   67384 
   67385   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   67386   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   67387   assert( pPage->nOverflow==1 );
   67388 
   67389   /* This error condition is now caught prior to reaching this function */
   67390   if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
   67391 
   67392   /* Allocate a new page. This page will become the right-sibling of
   67393   ** pPage. Make the parent page writable, so that the new divider cell
   67394   ** may be inserted. If both these operations are successful, proceed.
   67395   */
   67396   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
   67397 
   67398   if( rc==SQLITE_OK ){
   67399 
   67400     u8 *pOut = &pSpace[4];
   67401     u8 *pCell = pPage->apOvfl[0];
   67402     u16 szCell = pPage->xCellSize(pPage, pCell);
   67403     u8 *pStop;
   67404 
   67405     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
   67406     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
   67407     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
   67408     rc = rebuildPage(pNew, 1, &pCell, &szCell);
   67409     if( NEVER(rc) ) return rc;
   67410     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
   67411 
   67412     /* If this is an auto-vacuum database, update the pointer map
   67413     ** with entries for the new page, and any pointer from the
   67414     ** cell on the page to an overflow page. If either of these
   67415     ** operations fails, the return code is set, but the contents
   67416     ** of the parent page are still manipulated by thh code below.
   67417     ** That is Ok, at this point the parent page is guaranteed to
   67418     ** be marked as dirty. Returning an error code will cause a
   67419     ** rollback, undoing any changes made to the parent page.
   67420     */
   67421     if( ISAUTOVACUUM ){
   67422       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
   67423       if( szCell>pNew->minLocal ){
   67424         ptrmapPutOvflPtr(pNew, pCell, &rc);
   67425       }
   67426     }
   67427 
   67428     /* Create a divider cell to insert into pParent. The divider cell
   67429     ** consists of a 4-byte page number (the page number of pPage) and
   67430     ** a variable length key value (which must be the same value as the
   67431     ** largest key on pPage).
   67432     **
   67433     ** To find the largest key value on pPage, first find the right-most
   67434     ** cell on pPage. The first two fields of this cell are the
   67435     ** record-length (a variable length integer at most 32-bits in size)
   67436     ** and the key value (a variable length integer, may have any value).
   67437     ** The first of the while(...) loops below skips over the record-length
   67438     ** field. The second while(...) loop copies the key value from the
   67439     ** cell on pPage into the pSpace buffer.
   67440     */
   67441     pCell = findCell(pPage, pPage->nCell-1);
   67442     pStop = &pCell[9];
   67443     while( (*(pCell++)&0x80) && pCell<pStop );
   67444     pStop = &pCell[9];
   67445     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
   67446 
   67447     /* Insert the new divider cell into pParent. */
   67448     if( rc==SQLITE_OK ){
   67449       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
   67450                    0, pPage->pgno, &rc);
   67451     }
   67452 
   67453     /* Set the right-child pointer of pParent to point to the new page. */
   67454     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
   67455 
   67456     /* Release the reference to the new page. */
   67457     releasePage(pNew);
   67458   }
   67459 
   67460   return rc;
   67461 }
   67462 #endif /* SQLITE_OMIT_QUICKBALANCE */
   67463 
   67464 #if 0
   67465 /*
   67466 ** This function does not contribute anything to the operation of SQLite.
   67467 ** it is sometimes activated temporarily while debugging code responsible
   67468 ** for setting pointer-map entries.
   67469 */
   67470 static int ptrmapCheckPages(MemPage **apPage, int nPage){
   67471   int i, j;
   67472   for(i=0; i<nPage; i++){
   67473     Pgno n;
   67474     u8 e;
   67475     MemPage *pPage = apPage[i];
   67476     BtShared *pBt = pPage->pBt;
   67477     assert( pPage->isInit );
   67478 
   67479     for(j=0; j<pPage->nCell; j++){
   67480       CellInfo info;
   67481       u8 *z;
   67482 
   67483       z = findCell(pPage, j);
   67484       pPage->xParseCell(pPage, z, &info);
   67485       if( info.nLocal<info.nPayload ){
   67486         Pgno ovfl = get4byte(&z[info.nSize-4]);
   67487         ptrmapGet(pBt, ovfl, &e, &n);
   67488         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
   67489       }
   67490       if( !pPage->leaf ){
   67491         Pgno child = get4byte(z);
   67492         ptrmapGet(pBt, child, &e, &n);
   67493         assert( n==pPage->pgno && e==PTRMAP_BTREE );
   67494       }
   67495     }
   67496     if( !pPage->leaf ){
   67497       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   67498       ptrmapGet(pBt, child, &e, &n);
   67499       assert( n==pPage->pgno && e==PTRMAP_BTREE );
   67500     }
   67501   }
   67502   return 1;
   67503 }
   67504 #endif
   67505 
   67506 /*
   67507 ** This function is used to copy the contents of the b-tree node stored
   67508 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
   67509 ** the pointer-map entries for each child page are updated so that the
   67510 ** parent page stored in the pointer map is page pTo. If pFrom contained
   67511 ** any cells with overflow page pointers, then the corresponding pointer
   67512 ** map entries are also updated so that the parent page is page pTo.
   67513 **
   67514 ** If pFrom is currently carrying any overflow cells (entries in the
   67515 ** MemPage.apOvfl[] array), they are not copied to pTo.
   67516 **
   67517 ** Before returning, page pTo is reinitialized using btreeInitPage().
   67518 **
   67519 ** The performance of this function is not critical. It is only used by
   67520 ** the balance_shallower() and balance_deeper() procedures, neither of
   67521 ** which are called often under normal circumstances.
   67522 */
   67523 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
   67524   if( (*pRC)==SQLITE_OK ){
   67525     BtShared * const pBt = pFrom->pBt;
   67526     u8 * const aFrom = pFrom->aData;
   67527     u8 * const aTo = pTo->aData;
   67528     int const iFromHdr = pFrom->hdrOffset;
   67529     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
   67530     int rc;
   67531     int iData;
   67532 
   67533 
   67534     assert( pFrom->isInit );
   67535     assert( pFrom->nFree>=iToHdr );
   67536     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
   67537 
   67538     /* Copy the b-tree node content from page pFrom to page pTo. */
   67539     iData = get2byte(&aFrom[iFromHdr+5]);
   67540     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
   67541     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
   67542 
   67543     /* Reinitialize page pTo so that the contents of the MemPage structure
   67544     ** match the new data. The initialization of pTo can actually fail under
   67545     ** fairly obscure circumstances, even though it is a copy of initialized
   67546     ** page pFrom.
   67547     */
   67548     pTo->isInit = 0;
   67549     rc = btreeInitPage(pTo);
   67550     if( rc!=SQLITE_OK ){
   67551       *pRC = rc;
   67552       return;
   67553     }
   67554 
   67555     /* If this is an auto-vacuum database, update the pointer-map entries
   67556     ** for any b-tree or overflow pages that pTo now contains the pointers to.
   67557     */
   67558     if( ISAUTOVACUUM ){
   67559       *pRC = setChildPtrmaps(pTo);
   67560     }
   67561   }
   67562 }
   67563 
   67564 /*
   67565 ** This routine redistributes cells on the iParentIdx'th child of pParent
   67566 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
   67567 ** same amount of free space. Usually a single sibling on either side of the
   67568 ** page are used in the balancing, though both siblings might come from one
   67569 ** side if the page is the first or last child of its parent. If the page
   67570 ** has fewer than 2 siblings (something which can only happen if the page
   67571 ** is a root page or a child of a root page) then all available siblings
   67572 ** participate in the balancing.
   67573 **
   67574 ** The number of siblings of the page might be increased or decreased by
   67575 ** one or two in an effort to keep pages nearly full but not over full.
   67576 **
   67577 ** Note that when this routine is called, some of the cells on the page
   67578 ** might not actually be stored in MemPage.aData[]. This can happen
   67579 ** if the page is overfull. This routine ensures that all cells allocated
   67580 ** to the page and its siblings fit into MemPage.aData[] before returning.
   67581 **
   67582 ** In the course of balancing the page and its siblings, cells may be
   67583 ** inserted into or removed from the parent page (pParent). Doing so
   67584 ** may cause the parent page to become overfull or underfull. If this
   67585 ** happens, it is the responsibility of the caller to invoke the correct
   67586 ** balancing routine to fix this problem (see the balance() routine).
   67587 **
   67588 ** If this routine fails for any reason, it might leave the database
   67589 ** in a corrupted state. So if this routine fails, the database should
   67590 ** be rolled back.
   67591 **
   67592 ** The third argument to this function, aOvflSpace, is a pointer to a
   67593 ** buffer big enough to hold one page. If while inserting cells into the parent
   67594 ** page (pParent) the parent page becomes overfull, this buffer is
   67595 ** used to store the parent's overflow cells. Because this function inserts
   67596 ** a maximum of four divider cells into the parent page, and the maximum
   67597 ** size of a cell stored within an internal node is always less than 1/4
   67598 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
   67599 ** enough for all overflow cells.
   67600 **
   67601 ** If aOvflSpace is set to a null pointer, this function returns
   67602 ** SQLITE_NOMEM.
   67603 */
   67604 static int balance_nonroot(
   67605   MemPage *pParent,               /* Parent page of siblings being balanced */
   67606   int iParentIdx,                 /* Index of "the page" in pParent */
   67607   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
   67608   int isRoot,                     /* True if pParent is a root-page */
   67609   int bBulk                       /* True if this call is part of a bulk load */
   67610 ){
   67611   BtShared *pBt;               /* The whole database */
   67612   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
   67613   int nNew = 0;                /* Number of pages in apNew[] */
   67614   int nOld;                    /* Number of pages in apOld[] */
   67615   int i, j, k;                 /* Loop counters */
   67616   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
   67617   int rc = SQLITE_OK;          /* The return code */
   67618   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
   67619   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
   67620   int usableSpace;             /* Bytes in pPage beyond the header */
   67621   int pageFlags;               /* Value of pPage->aData[0] */
   67622   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
   67623   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
   67624   int szScratch;               /* Size of scratch memory requested */
   67625   MemPage *apOld[NB];          /* pPage and up to two siblings */
   67626   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
   67627   u8 *pRight;                  /* Location in parent of right-sibling pointer */
   67628   u8 *apDiv[NB-1];             /* Divider cells in pParent */
   67629   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
   67630   int cntOld[NB+2];            /* Old index in b.apCell[] */
   67631   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
   67632   u8 *aSpace1;                 /* Space for copies of dividers cells */
   67633   Pgno pgno;                   /* Temp var to store a page number in */
   67634   u8 abDone[NB+2];             /* True after i'th new page is populated */
   67635   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
   67636   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
   67637   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
   67638   CellArray b;                  /* Parsed information on cells being balanced */
   67639 
   67640   memset(abDone, 0, sizeof(abDone));
   67641   b.nCell = 0;
   67642   b.apCell = 0;
   67643   pBt = pParent->pBt;
   67644   assert( sqlite3_mutex_held(pBt->mutex) );
   67645   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   67646 
   67647 #if 0
   67648   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
   67649 #endif
   67650 
   67651   /* At this point pParent may have at most one overflow cell. And if
   67652   ** this overflow cell is present, it must be the cell with
   67653   ** index iParentIdx. This scenario comes about when this function
   67654   ** is called (indirectly) from sqlite3BtreeDelete().
   67655   */
   67656   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
   67657   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
   67658 
   67659   if( !aOvflSpace ){
   67660     return SQLITE_NOMEM_BKPT;
   67661   }
   67662 
   67663   /* Find the sibling pages to balance. Also locate the cells in pParent
   67664   ** that divide the siblings. An attempt is made to find NN siblings on
   67665   ** either side of pPage. More siblings are taken from one side, however,
   67666   ** if there are fewer than NN siblings on the other side. If pParent
   67667   ** has NB or fewer children then all children of pParent are taken.
   67668   **
   67669   ** This loop also drops the divider cells from the parent page. This
   67670   ** way, the remainder of the function does not have to deal with any
   67671   ** overflow cells in the parent page, since if any existed they will
   67672   ** have already been removed.
   67673   */
   67674   i = pParent->nOverflow + pParent->nCell;
   67675   if( i<2 ){
   67676     nxDiv = 0;
   67677   }else{
   67678     assert( bBulk==0 || bBulk==1 );
   67679     if( iParentIdx==0 ){
   67680       nxDiv = 0;
   67681     }else if( iParentIdx==i ){
   67682       nxDiv = i-2+bBulk;
   67683     }else{
   67684       nxDiv = iParentIdx-1;
   67685     }
   67686     i = 2-bBulk;
   67687   }
   67688   nOld = i+1;
   67689   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
   67690     pRight = &pParent->aData[pParent->hdrOffset+8];
   67691   }else{
   67692     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
   67693   }
   67694   pgno = get4byte(pRight);
   67695   while( 1 ){
   67696     rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
   67697     if( rc ){
   67698       memset(apOld, 0, (i+1)*sizeof(MemPage*));
   67699       goto balance_cleanup;
   67700     }
   67701     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
   67702     if( (i--)==0 ) break;
   67703 
   67704     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
   67705       apDiv[i] = pParent->apOvfl[0];
   67706       pgno = get4byte(apDiv[i]);
   67707       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
   67708       pParent->nOverflow = 0;
   67709     }else{
   67710       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
   67711       pgno = get4byte(apDiv[i]);
   67712       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
   67713 
   67714       /* Drop the cell from the parent page. apDiv[i] still points to
   67715       ** the cell within the parent, even though it has been dropped.
   67716       ** This is safe because dropping a cell only overwrites the first
   67717       ** four bytes of it, and this function does not need the first
   67718       ** four bytes of the divider cell. So the pointer is safe to use
   67719       ** later on.
   67720       **
   67721       ** But not if we are in secure-delete mode. In secure-delete mode,
   67722       ** the dropCell() routine will overwrite the entire cell with zeroes.
   67723       ** In this case, temporarily copy the cell into the aOvflSpace[]
   67724       ** buffer. It will be copied out again as soon as the aSpace[] buffer
   67725       ** is allocated.  */
   67726       if( pBt->btsFlags & BTS_FAST_SECURE ){
   67727         int iOff;
   67728 
   67729         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
   67730         if( (iOff+szNew[i])>(int)pBt->usableSize ){
   67731           rc = SQLITE_CORRUPT_BKPT;
   67732           memset(apOld, 0, (i+1)*sizeof(MemPage*));
   67733           goto balance_cleanup;
   67734         }else{
   67735           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
   67736           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
   67737         }
   67738       }
   67739       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
   67740     }
   67741   }
   67742 
   67743   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   67744   ** alignment */
   67745   nMaxCells = (nMaxCells + 3)&~3;
   67746 
   67747   /*
   67748   ** Allocate space for memory structures
   67749   */
   67750   szScratch =
   67751        nMaxCells*sizeof(u8*)                       /* b.apCell */
   67752      + nMaxCells*sizeof(u16)                       /* b.szCell */
   67753      + pBt->pageSize;                              /* aSpace1 */
   67754 
   67755   assert( szScratch<=6*(int)pBt->pageSize );
   67756   b.apCell = sqlite3StackAllocRaw(0, szScratch );
   67757   if( b.apCell==0 ){
   67758     rc = SQLITE_NOMEM_BKPT;
   67759     goto balance_cleanup;
   67760   }
   67761   b.szCell = (u16*)&b.apCell[nMaxCells];
   67762   aSpace1 = (u8*)&b.szCell[nMaxCells];
   67763   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
   67764 
   67765   /*
   67766   ** Load pointers to all cells on sibling pages and the divider cells
   67767   ** into the local b.apCell[] array.  Make copies of the divider cells
   67768   ** into space obtained from aSpace1[]. The divider cells have already
   67769   ** been removed from pParent.
   67770   **
   67771   ** If the siblings are on leaf pages, then the child pointers of the
   67772   ** divider cells are stripped from the cells before they are copied
   67773   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
   67774   ** child pointers.  If siblings are not leaves, then all cell in
   67775   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
   67776   ** are alike.
   67777   **
   67778   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
   67779   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
   67780   */
   67781   b.pRef = apOld[0];
   67782   leafCorrection = b.pRef->leaf*4;
   67783   leafData = b.pRef->intKeyLeaf;
   67784   for(i=0; i<nOld; i++){
   67785     MemPage *pOld = apOld[i];
   67786     int limit = pOld->nCell;
   67787     u8 *aData = pOld->aData;
   67788     u16 maskPage = pOld->maskPage;
   67789     u8 *piCell = aData + pOld->cellOffset;
   67790     u8 *piEnd;
   67791 
   67792     /* Verify that all sibling pages are of the same "type" (table-leaf,
   67793     ** table-interior, index-leaf, or index-interior).
   67794     */
   67795     if( pOld->aData[0]!=apOld[0]->aData[0] ){
   67796       rc = SQLITE_CORRUPT_BKPT;
   67797       goto balance_cleanup;
   67798     }
   67799 
   67800     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
   67801     ** constains overflow cells, include them in the b.apCell[] array
   67802     ** in the correct spot.
   67803     **
   67804     ** Note that when there are multiple overflow cells, it is always the
   67805     ** case that they are sequential and adjacent.  This invariant arises
   67806     ** because multiple overflows can only occurs when inserting divider
   67807     ** cells into a parent on a prior balance, and divider cells are always
   67808     ** adjacent and are inserted in order.  There is an assert() tagged
   67809     ** with "NOTE 1" in the overflow cell insertion loop to prove this
   67810     ** invariant.
   67811     **
   67812     ** This must be done in advance.  Once the balance starts, the cell
   67813     ** offset section of the btree page will be overwritten and we will no
   67814     ** long be able to find the cells if a pointer to each cell is not saved
   67815     ** first.
   67816     */
   67817     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
   67818     if( pOld->nOverflow>0 ){
   67819       limit = pOld->aiOvfl[0];
   67820       for(j=0; j<limit; j++){
   67821         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
   67822         piCell += 2;
   67823         b.nCell++;
   67824       }
   67825       for(k=0; k<pOld->nOverflow; k++){
   67826         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
   67827         b.apCell[b.nCell] = pOld->apOvfl[k];
   67828         b.nCell++;
   67829       }
   67830     }
   67831     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
   67832     while( piCell<piEnd ){
   67833       assert( b.nCell<nMaxCells );
   67834       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
   67835       piCell += 2;
   67836       b.nCell++;
   67837     }
   67838 
   67839     cntOld[i] = b.nCell;
   67840     if( i<nOld-1 && !leafData){
   67841       u16 sz = (u16)szNew[i];
   67842       u8 *pTemp;
   67843       assert( b.nCell<nMaxCells );
   67844       b.szCell[b.nCell] = sz;
   67845       pTemp = &aSpace1[iSpace1];
   67846       iSpace1 += sz;
   67847       assert( sz<=pBt->maxLocal+23 );
   67848       assert( iSpace1 <= (int)pBt->pageSize );
   67849       memcpy(pTemp, apDiv[i], sz);
   67850       b.apCell[b.nCell] = pTemp+leafCorrection;
   67851       assert( leafCorrection==0 || leafCorrection==4 );
   67852       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
   67853       if( !pOld->leaf ){
   67854         assert( leafCorrection==0 );
   67855         assert( pOld->hdrOffset==0 );
   67856         /* The right pointer of the child page pOld becomes the left
   67857         ** pointer of the divider cell */
   67858         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
   67859       }else{
   67860         assert( leafCorrection==4 );
   67861         while( b.szCell[b.nCell]<4 ){
   67862           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
   67863           ** does exist, pad it with 0x00 bytes. */
   67864           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
   67865           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
   67866           aSpace1[iSpace1++] = 0x00;
   67867           b.szCell[b.nCell]++;
   67868         }
   67869       }
   67870       b.nCell++;
   67871     }
   67872   }
   67873 
   67874   /*
   67875   ** Figure out the number of pages needed to hold all b.nCell cells.
   67876   ** Store this number in "k".  Also compute szNew[] which is the total
   67877   ** size of all cells on the i-th page and cntNew[] which is the index
   67878   ** in b.apCell[] of the cell that divides page i from page i+1.
   67879   ** cntNew[k] should equal b.nCell.
   67880   **
   67881   ** Values computed by this block:
   67882   **
   67883   **           k: The total number of sibling pages
   67884   **    szNew[i]: Spaced used on the i-th sibling page.
   67885   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
   67886   **              the right of the i-th sibling page.
   67887   ** usableSpace: Number of bytes of space available on each sibling.
   67888   **
   67889   */
   67890   usableSpace = pBt->usableSize - 12 + leafCorrection;
   67891   for(i=0; i<nOld; i++){
   67892     MemPage *p = apOld[i];
   67893     szNew[i] = usableSpace - p->nFree;
   67894     for(j=0; j<p->nOverflow; j++){
   67895       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
   67896     }
   67897     cntNew[i] = cntOld[i];
   67898   }
   67899   k = nOld;
   67900   for(i=0; i<k; i++){
   67901     int sz;
   67902     while( szNew[i]>usableSpace ){
   67903       if( i+1>=k ){
   67904         k = i+2;
   67905         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
   67906         szNew[k-1] = 0;
   67907         cntNew[k-1] = b.nCell;
   67908       }
   67909       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
   67910       szNew[i] -= sz;
   67911       if( !leafData ){
   67912         if( cntNew[i]<b.nCell ){
   67913           sz = 2 + cachedCellSize(&b, cntNew[i]);
   67914         }else{
   67915           sz = 0;
   67916         }
   67917       }
   67918       szNew[i+1] += sz;
   67919       cntNew[i]--;
   67920     }
   67921     while( cntNew[i]<b.nCell ){
   67922       sz = 2 + cachedCellSize(&b, cntNew[i]);
   67923       if( szNew[i]+sz>usableSpace ) break;
   67924       szNew[i] += sz;
   67925       cntNew[i]++;
   67926       if( !leafData ){
   67927         if( cntNew[i]<b.nCell ){
   67928           sz = 2 + cachedCellSize(&b, cntNew[i]);
   67929         }else{
   67930           sz = 0;
   67931         }
   67932       }
   67933       szNew[i+1] -= sz;
   67934     }
   67935     if( cntNew[i]>=b.nCell ){
   67936       k = i+1;
   67937     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
   67938       rc = SQLITE_CORRUPT_BKPT;
   67939       goto balance_cleanup;
   67940     }
   67941   }
   67942 
   67943   /*
   67944   ** The packing computed by the previous block is biased toward the siblings
   67945   ** on the left side (siblings with smaller keys). The left siblings are
   67946   ** always nearly full, while the right-most sibling might be nearly empty.
   67947   ** The next block of code attempts to adjust the packing of siblings to
   67948   ** get a better balance.
   67949   **
   67950   ** This adjustment is more than an optimization.  The packing above might
   67951   ** be so out of balance as to be illegal.  For example, the right-most
   67952   ** sibling might be completely empty.  This adjustment is not optional.
   67953   */
   67954   for(i=k-1; i>0; i--){
   67955     int szRight = szNew[i];  /* Size of sibling on the right */
   67956     int szLeft = szNew[i-1]; /* Size of sibling on the left */
   67957     int r;              /* Index of right-most cell in left sibling */
   67958     int d;              /* Index of first cell to the left of right sibling */
   67959 
   67960     r = cntNew[i-1] - 1;
   67961     d = r + 1 - leafData;
   67962     (void)cachedCellSize(&b, d);
   67963     do{
   67964       assert( d<nMaxCells );
   67965       assert( r<nMaxCells );
   67966       (void)cachedCellSize(&b, r);
   67967       if( szRight!=0
   67968        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
   67969         break;
   67970       }
   67971       szRight += b.szCell[d] + 2;
   67972       szLeft -= b.szCell[r] + 2;
   67973       cntNew[i-1] = r;
   67974       r--;
   67975       d--;
   67976     }while( r>=0 );
   67977     szNew[i] = szRight;
   67978     szNew[i-1] = szLeft;
   67979     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
   67980       rc = SQLITE_CORRUPT_BKPT;
   67981       goto balance_cleanup;
   67982     }
   67983   }
   67984 
   67985   /* Sanity check:  For a non-corrupt database file one of the follwing
   67986   ** must be true:
   67987   **    (1) We found one or more cells (cntNew[0])>0), or
   67988   **    (2) pPage is a virtual root page.  A virtual root page is when
   67989   **        the real root page is page 1 and we are the only child of
   67990   **        that page.
   67991   */
   67992   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
   67993   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
   67994     apOld[0]->pgno, apOld[0]->nCell,
   67995     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
   67996     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
   67997   ));
   67998 
   67999   /*
   68000   ** Allocate k new pages.  Reuse old pages where possible.
   68001   */
   68002   pageFlags = apOld[0]->aData[0];
   68003   for(i=0; i<k; i++){
   68004     MemPage *pNew;
   68005     if( i<nOld ){
   68006       pNew = apNew[i] = apOld[i];
   68007       apOld[i] = 0;
   68008       rc = sqlite3PagerWrite(pNew->pDbPage);
   68009       nNew++;
   68010       if( rc ) goto balance_cleanup;
   68011     }else{
   68012       assert( i>0 );
   68013       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
   68014       if( rc ) goto balance_cleanup;
   68015       zeroPage(pNew, pageFlags);
   68016       apNew[i] = pNew;
   68017       nNew++;
   68018       cntOld[i] = b.nCell;
   68019 
   68020       /* Set the pointer-map entry for the new sibling page. */
   68021       if( ISAUTOVACUUM ){
   68022         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
   68023         if( rc!=SQLITE_OK ){
   68024           goto balance_cleanup;
   68025         }
   68026       }
   68027     }
   68028   }
   68029 
   68030   /*
   68031   ** Reassign page numbers so that the new pages are in ascending order.
   68032   ** This helps to keep entries in the disk file in order so that a scan
   68033   ** of the table is closer to a linear scan through the file. That in turn
   68034   ** helps the operating system to deliver pages from the disk more rapidly.
   68035   **
   68036   ** An O(n^2) insertion sort algorithm is used, but since n is never more
   68037   ** than (NB+2) (a small constant), that should not be a problem.
   68038   **
   68039   ** When NB==3, this one optimization makes the database about 25% faster
   68040   ** for large insertions and deletions.
   68041   */
   68042   for(i=0; i<nNew; i++){
   68043     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
   68044     aPgFlags[i] = apNew[i]->pDbPage->flags;
   68045     for(j=0; j<i; j++){
   68046       if( aPgno[j]==aPgno[i] ){
   68047         /* This branch is taken if the set of sibling pages somehow contains
   68048         ** duplicate entries. This can happen if the database is corrupt.
   68049         ** It would be simpler to detect this as part of the loop below, but
   68050         ** we do the detection here in order to avoid populating the pager
   68051         ** cache with two separate objects associated with the same
   68052         ** page number.  */
   68053         assert( CORRUPT_DB );
   68054         rc = SQLITE_CORRUPT_BKPT;
   68055         goto balance_cleanup;
   68056       }
   68057     }
   68058   }
   68059   for(i=0; i<nNew; i++){
   68060     int iBest = 0;                /* aPgno[] index of page number to use */
   68061     for(j=1; j<nNew; j++){
   68062       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
   68063     }
   68064     pgno = aPgOrder[iBest];
   68065     aPgOrder[iBest] = 0xffffffff;
   68066     if( iBest!=i ){
   68067       if( iBest>i ){
   68068         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
   68069       }
   68070       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
   68071       apNew[i]->pgno = pgno;
   68072     }
   68073   }
   68074 
   68075   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
   68076          "%d(%d nc=%d) %d(%d nc=%d)\n",
   68077     apNew[0]->pgno, szNew[0], cntNew[0],
   68078     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
   68079     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
   68080     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
   68081     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
   68082     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
   68083     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
   68084     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
   68085     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
   68086   ));
   68087 
   68088   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   68089   put4byte(pRight, apNew[nNew-1]->pgno);
   68090 
   68091   /* If the sibling pages are not leaves, ensure that the right-child pointer
   68092   ** of the right-most new sibling page is set to the value that was
   68093   ** originally in the same field of the right-most old sibling page. */
   68094   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
   68095     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
   68096     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
   68097   }
   68098 
   68099   /* Make any required updates to pointer map entries associated with
   68100   ** cells stored on sibling pages following the balance operation. Pointer
   68101   ** map entries associated with divider cells are set by the insertCell()
   68102   ** routine. The associated pointer map entries are:
   68103   **
   68104   **   a) if the cell contains a reference to an overflow chain, the
   68105   **      entry associated with the first page in the overflow chain, and
   68106   **
   68107   **   b) if the sibling pages are not leaves, the child page associated
   68108   **      with the cell.
   68109   **
   68110   ** If the sibling pages are not leaves, then the pointer map entry
   68111   ** associated with the right-child of each sibling may also need to be
   68112   ** updated. This happens below, after the sibling pages have been
   68113   ** populated, not here.
   68114   */
   68115   if( ISAUTOVACUUM ){
   68116     MemPage *pNew = apNew[0];
   68117     u8 *aOld = pNew->aData;
   68118     int cntOldNext = pNew->nCell + pNew->nOverflow;
   68119     int usableSize = pBt->usableSize;
   68120     int iNew = 0;
   68121     int iOld = 0;
   68122 
   68123     for(i=0; i<b.nCell; i++){
   68124       u8 *pCell = b.apCell[i];
   68125       if( i==cntOldNext ){
   68126         MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
   68127         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
   68128         aOld = pOld->aData;
   68129       }
   68130       if( i==cntNew[iNew] ){
   68131         pNew = apNew[++iNew];
   68132         if( !leafData ) continue;
   68133       }
   68134 
   68135       /* Cell pCell is destined for new sibling page pNew. Originally, it
   68136       ** was either part of sibling page iOld (possibly an overflow cell),
   68137       ** or else the divider cell to the left of sibling page iOld. So,
   68138       ** if sibling page iOld had the same page number as pNew, and if
   68139       ** pCell really was a part of sibling page iOld (not a divider or
   68140       ** overflow cell), we can skip updating the pointer map entries.  */
   68141       if( iOld>=nNew
   68142        || pNew->pgno!=aPgno[iOld]
   68143        || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
   68144       ){
   68145         if( !leafCorrection ){
   68146           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
   68147         }
   68148         if( cachedCellSize(&b,i)>pNew->minLocal ){
   68149           ptrmapPutOvflPtr(pNew, pCell, &rc);
   68150         }
   68151         if( rc ) goto balance_cleanup;
   68152       }
   68153     }
   68154   }
   68155 
   68156   /* Insert new divider cells into pParent. */
   68157   for(i=0; i<nNew-1; i++){
   68158     u8 *pCell;
   68159     u8 *pTemp;
   68160     int sz;
   68161     MemPage *pNew = apNew[i];
   68162     j = cntNew[i];
   68163 
   68164     assert( j<nMaxCells );
   68165     assert( b.apCell[j]!=0 );
   68166     pCell = b.apCell[j];
   68167     sz = b.szCell[j] + leafCorrection;
   68168     pTemp = &aOvflSpace[iOvflSpace];
   68169     if( !pNew->leaf ){
   68170       memcpy(&pNew->aData[8], pCell, 4);
   68171     }else if( leafData ){
   68172       /* If the tree is a leaf-data tree, and the siblings are leaves,
   68173       ** then there is no divider cell in b.apCell[]. Instead, the divider
   68174       ** cell consists of the integer key for the right-most cell of
   68175       ** the sibling-page assembled above only.
   68176       */
   68177       CellInfo info;
   68178       j--;
   68179       pNew->xParseCell(pNew, b.apCell[j], &info);
   68180       pCell = pTemp;
   68181       sz = 4 + putVarint(&pCell[4], info.nKey);
   68182       pTemp = 0;
   68183     }else{
   68184       pCell -= 4;
   68185       /* Obscure case for non-leaf-data trees: If the cell at pCell was
   68186       ** previously stored on a leaf node, and its reported size was 4
   68187       ** bytes, then it may actually be smaller than this
   68188       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
   68189       ** any cell). But it is important to pass the correct size to
   68190       ** insertCell(), so reparse the cell now.
   68191       **
   68192       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
   68193       ** and WITHOUT ROWID tables with exactly one column which is the
   68194       ** primary key.
   68195       */
   68196       if( b.szCell[j]==4 ){
   68197         assert(leafCorrection==4);
   68198         sz = pParent->xCellSize(pParent, pCell);
   68199       }
   68200     }
   68201     iOvflSpace += sz;
   68202     assert( sz<=pBt->maxLocal+23 );
   68203     assert( iOvflSpace <= (int)pBt->pageSize );
   68204     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
   68205     if( rc!=SQLITE_OK ) goto balance_cleanup;
   68206     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   68207   }
   68208 
   68209   /* Now update the actual sibling pages. The order in which they are updated
   68210   ** is important, as this code needs to avoid disrupting any page from which
   68211   ** cells may still to be read. In practice, this means:
   68212   **
   68213   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
   68214   **      then it is not safe to update page apNew[iPg] until after
   68215   **      the left-hand sibling apNew[iPg-1] has been updated.
   68216   **
   68217   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
   68218   **      then it is not safe to update page apNew[iPg] until after
   68219   **      the right-hand sibling apNew[iPg+1] has been updated.
   68220   **
   68221   ** If neither of the above apply, the page is safe to update.
   68222   **
   68223   ** The iPg value in the following loop starts at nNew-1 goes down
   68224   ** to 0, then back up to nNew-1 again, thus making two passes over
   68225   ** the pages.  On the initial downward pass, only condition (1) above
   68226   ** needs to be tested because (2) will always be true from the previous
   68227   ** step.  On the upward pass, both conditions are always true, so the
   68228   ** upwards pass simply processes pages that were missed on the downward
   68229   ** pass.
   68230   */
   68231   for(i=1-nNew; i<nNew; i++){
   68232     int iPg = i<0 ? -i : i;
   68233     assert( iPg>=0 && iPg<nNew );
   68234     if( abDone[iPg] ) continue;         /* Skip pages already processed */
   68235     if( i>=0                            /* On the upwards pass, or... */
   68236      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
   68237     ){
   68238       int iNew;
   68239       int iOld;
   68240       int nNewCell;
   68241 
   68242       /* Verify condition (1):  If cells are moving left, update iPg
   68243       ** only after iPg-1 has already been updated. */
   68244       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
   68245 
   68246       /* Verify condition (2):  If cells are moving right, update iPg
   68247       ** only after iPg+1 has already been updated. */
   68248       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
   68249 
   68250       if( iPg==0 ){
   68251         iNew = iOld = 0;
   68252         nNewCell = cntNew[0];
   68253       }else{
   68254         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
   68255         iNew = cntNew[iPg-1] + !leafData;
   68256         nNewCell = cntNew[iPg] - iNew;
   68257       }
   68258 
   68259       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
   68260       if( rc ) goto balance_cleanup;
   68261       abDone[iPg]++;
   68262       apNew[iPg]->nFree = usableSpace-szNew[iPg];
   68263       assert( apNew[iPg]->nOverflow==0 );
   68264       assert( apNew[iPg]->nCell==nNewCell );
   68265     }
   68266   }
   68267 
   68268   /* All pages have been processed exactly once */
   68269   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
   68270 
   68271   assert( nOld>0 );
   68272   assert( nNew>0 );
   68273 
   68274   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
   68275     /* The root page of the b-tree now contains no cells. The only sibling
   68276     ** page is the right-child of the parent. Copy the contents of the
   68277     ** child page into the parent, decreasing the overall height of the
   68278     ** b-tree structure by one. This is described as the "balance-shallower"
   68279     ** sub-algorithm in some documentation.
   68280     **
   68281     ** If this is an auto-vacuum database, the call to copyNodeContent()
   68282     ** sets all pointer-map entries corresponding to database image pages
   68283     ** for which the pointer is stored within the content being copied.
   68284     **
   68285     ** It is critical that the child page be defragmented before being
   68286     ** copied into the parent, because if the parent is page 1 then it will
   68287     ** by smaller than the child due to the database header, and so all the
   68288     ** free space needs to be up front.
   68289     */
   68290     assert( nNew==1 || CORRUPT_DB );
   68291     rc = defragmentPage(apNew[0], -1);
   68292     testcase( rc!=SQLITE_OK );
   68293     assert( apNew[0]->nFree ==
   68294         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
   68295       || rc!=SQLITE_OK
   68296     );
   68297     copyNodeContent(apNew[0], pParent, &rc);
   68298     freePage(apNew[0], &rc);
   68299   }else if( ISAUTOVACUUM && !leafCorrection ){
   68300     /* Fix the pointer map entries associated with the right-child of each
   68301     ** sibling page. All other pointer map entries have already been taken
   68302     ** care of.  */
   68303     for(i=0; i<nNew; i++){
   68304       u32 key = get4byte(&apNew[i]->aData[8]);
   68305       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
   68306     }
   68307   }
   68308 
   68309   assert( pParent->isInit );
   68310   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
   68311           nOld, nNew, b.nCell));
   68312 
   68313   /* Free any old pages that were not reused as new pages.
   68314   */
   68315   for(i=nNew; i<nOld; i++){
   68316     freePage(apOld[i], &rc);
   68317   }
   68318 
   68319 #if 0
   68320   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
   68321     /* The ptrmapCheckPages() contains assert() statements that verify that
   68322     ** all pointer map pages are set correctly. This is helpful while
   68323     ** debugging. This is usually disabled because a corrupt database may
   68324     ** cause an assert() statement to fail.  */
   68325     ptrmapCheckPages(apNew, nNew);
   68326     ptrmapCheckPages(&pParent, 1);
   68327   }
   68328 #endif
   68329 
   68330   /*
   68331   ** Cleanup before returning.
   68332   */
   68333 balance_cleanup:
   68334   sqlite3StackFree(0, b.apCell);
   68335   for(i=0; i<nOld; i++){
   68336     releasePage(apOld[i]);
   68337   }
   68338   for(i=0; i<nNew; i++){
   68339     releasePage(apNew[i]);
   68340   }
   68341 
   68342   return rc;
   68343 }
   68344 
   68345 
   68346 /*
   68347 ** This function is called when the root page of a b-tree structure is
   68348 ** overfull (has one or more overflow pages).
   68349 **
   68350 ** A new child page is allocated and the contents of the current root
   68351 ** page, including overflow cells, are copied into the child. The root
   68352 ** page is then overwritten to make it an empty page with the right-child
   68353 ** pointer pointing to the new page.
   68354 **
   68355 ** Before returning, all pointer-map entries corresponding to pages
   68356 ** that the new child-page now contains pointers to are updated. The
   68357 ** entry corresponding to the new right-child pointer of the root
   68358 ** page is also updated.
   68359 **
   68360 ** If successful, *ppChild is set to contain a reference to the child
   68361 ** page and SQLITE_OK is returned. In this case the caller is required
   68362 ** to call releasePage() on *ppChild exactly once. If an error occurs,
   68363 ** an error code is returned and *ppChild is set to 0.
   68364 */
   68365 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   68366   int rc;                        /* Return value from subprocedures */
   68367   MemPage *pChild = 0;           /* Pointer to a new child page */
   68368   Pgno pgnoChild = 0;            /* Page number of the new child page */
   68369   BtShared *pBt = pRoot->pBt;    /* The BTree */
   68370 
   68371   assert( pRoot->nOverflow>0 );
   68372   assert( sqlite3_mutex_held(pBt->mutex) );
   68373 
   68374   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   68375   ** page that will become the new right-child of pPage. Copy the contents
   68376   ** of the node stored on pRoot into the new child page.
   68377   */
   68378   rc = sqlite3PagerWrite(pRoot->pDbPage);
   68379   if( rc==SQLITE_OK ){
   68380     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
   68381     copyNodeContent(pRoot, pChild, &rc);
   68382     if( ISAUTOVACUUM ){
   68383       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
   68384     }
   68385   }
   68386   if( rc ){
   68387     *ppChild = 0;
   68388     releasePage(pChild);
   68389     return rc;
   68390   }
   68391   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
   68392   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   68393   assert( pChild->nCell==pRoot->nCell );
   68394 
   68395   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
   68396 
   68397   /* Copy the overflow cells from pRoot to pChild */
   68398   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
   68399          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
   68400   memcpy(pChild->apOvfl, pRoot->apOvfl,
   68401          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
   68402   pChild->nOverflow = pRoot->nOverflow;
   68403 
   68404   /* Zero the contents of pRoot. Then install pChild as the right-child. */
   68405   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
   68406   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
   68407 
   68408   *ppChild = pChild;
   68409   return SQLITE_OK;
   68410 }
   68411 
   68412 /*
   68413 ** The page that pCur currently points to has just been modified in
   68414 ** some way. This function figures out if this modification means the
   68415 ** tree needs to be balanced, and if so calls the appropriate balancing
   68416 ** routine. Balancing routines are:
   68417 **
   68418 **   balance_quick()
   68419 **   balance_deeper()
   68420 **   balance_nonroot()
   68421 */
   68422 static int balance(BtCursor *pCur){
   68423   int rc = SQLITE_OK;
   68424   const int nMin = pCur->pBt->usableSize * 2 / 3;
   68425   u8 aBalanceQuickSpace[13];
   68426   u8 *pFree = 0;
   68427 
   68428   VVA_ONLY( int balance_quick_called = 0 );
   68429   VVA_ONLY( int balance_deeper_called = 0 );
   68430 
   68431   do {
   68432     int iPage = pCur->iPage;
   68433     MemPage *pPage = pCur->pPage;
   68434 
   68435     if( iPage==0 ){
   68436       if( pPage->nOverflow ){
   68437         /* The root page of the b-tree is overfull. In this case call the
   68438         ** balance_deeper() function to create a new child for the root-page
   68439         ** and copy the current contents of the root-page to it. The
   68440         ** next iteration of the do-loop will balance the child page.
   68441         */
   68442         assert( balance_deeper_called==0 );
   68443         VVA_ONLY( balance_deeper_called++ );
   68444         rc = balance_deeper(pPage, &pCur->apPage[1]);
   68445         if( rc==SQLITE_OK ){
   68446           pCur->iPage = 1;
   68447           pCur->ix = 0;
   68448           pCur->aiIdx[0] = 0;
   68449           pCur->apPage[0] = pPage;
   68450           pCur->pPage = pCur->apPage[1];
   68451           assert( pCur->pPage->nOverflow );
   68452         }
   68453       }else{
   68454         break;
   68455       }
   68456     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
   68457       break;
   68458     }else{
   68459       MemPage * const pParent = pCur->apPage[iPage-1];
   68460       int const iIdx = pCur->aiIdx[iPage-1];
   68461 
   68462       rc = sqlite3PagerWrite(pParent->pDbPage);
   68463       if( rc==SQLITE_OK ){
   68464 #ifndef SQLITE_OMIT_QUICKBALANCE
   68465         if( pPage->intKeyLeaf
   68466          && pPage->nOverflow==1
   68467          && pPage->aiOvfl[0]==pPage->nCell
   68468          && pParent->pgno!=1
   68469          && pParent->nCell==iIdx
   68470         ){
   68471           /* Call balance_quick() to create a new sibling of pPage on which
   68472           ** to store the overflow cell. balance_quick() inserts a new cell
   68473           ** into pParent, which may cause pParent overflow. If this
   68474           ** happens, the next iteration of the do-loop will balance pParent
   68475           ** use either balance_nonroot() or balance_deeper(). Until this
   68476           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
   68477           ** buffer.
   68478           **
   68479           ** The purpose of the following assert() is to check that only a
   68480           ** single call to balance_quick() is made for each call to this
   68481           ** function. If this were not verified, a subtle bug involving reuse
   68482           ** of the aBalanceQuickSpace[] might sneak in.
   68483           */
   68484           assert( balance_quick_called==0 );
   68485           VVA_ONLY( balance_quick_called++ );
   68486           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
   68487         }else
   68488 #endif
   68489         {
   68490           /* In this case, call balance_nonroot() to redistribute cells
   68491           ** between pPage and up to 2 of its sibling pages. This involves
   68492           ** modifying the contents of pParent, which may cause pParent to
   68493           ** become overfull or underfull. The next iteration of the do-loop
   68494           ** will balance the parent page to correct this.
   68495           **
   68496           ** If the parent page becomes overfull, the overflow cell or cells
   68497           ** are stored in the pSpace buffer allocated immediately below.
   68498           ** A subsequent iteration of the do-loop will deal with this by
   68499           ** calling balance_nonroot() (balance_deeper() may be called first,
   68500           ** but it doesn't deal with overflow cells - just moves them to a
   68501           ** different page). Once this subsequent call to balance_nonroot()
   68502           ** has completed, it is safe to release the pSpace buffer used by
   68503           ** the previous call, as the overflow cell data will have been
   68504           ** copied either into the body of a database page or into the new
   68505           ** pSpace buffer passed to the latter call to balance_nonroot().
   68506           */
   68507           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
   68508           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
   68509                                pCur->hints&BTREE_BULKLOAD);
   68510           if( pFree ){
   68511             /* If pFree is not NULL, it points to the pSpace buffer used
   68512             ** by a previous call to balance_nonroot(). Its contents are
   68513             ** now stored either on real database pages or within the
   68514             ** new pSpace buffer, so it may be safely freed here. */
   68515             sqlite3PageFree(pFree);
   68516           }
   68517 
   68518           /* The pSpace buffer will be freed after the next call to
   68519           ** balance_nonroot(), or just before this function returns, whichever
   68520           ** comes first. */
   68521           pFree = pSpace;
   68522         }
   68523       }
   68524 
   68525       pPage->nOverflow = 0;
   68526 
   68527       /* The next iteration of the do-loop balances the parent page. */
   68528       releasePage(pPage);
   68529       pCur->iPage--;
   68530       assert( pCur->iPage>=0 );
   68531       pCur->pPage = pCur->apPage[pCur->iPage];
   68532     }
   68533   }while( rc==SQLITE_OK );
   68534 
   68535   if( pFree ){
   68536     sqlite3PageFree(pFree);
   68537   }
   68538   return rc;
   68539 }
   68540 
   68541 
   68542 /*
   68543 ** Insert a new record into the BTree.  The content of the new record
   68544 ** is described by the pX object.  The pCur cursor is used only to
   68545 ** define what table the record should be inserted into, and is left
   68546 ** pointing at a random location.
   68547 **
   68548 ** For a table btree (used for rowid tables), only the pX.nKey value of
   68549 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
   68550 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
   68551 ** hold the content of the row.
   68552 **
   68553 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
   68554 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
   68555 ** pX.pData,nData,nZero fields must be zero.
   68556 **
   68557 ** If the seekResult parameter is non-zero, then a successful call to
   68558 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
   68559 ** been performed.  In other words, if seekResult!=0 then the cursor
   68560 ** is currently pointing to a cell that will be adjacent to the cell
   68561 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
   68562 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
   68563 ** that is larger than (pKey,nKey).
   68564 **
   68565 ** If seekResult==0, that means pCur is pointing at some unknown location.
   68566 ** In that case, this routine must seek the cursor to the correct insertion
   68567 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
   68568 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
   68569 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
   68570 ** to decode the key.
   68571 */
   68572 SQLITE_PRIVATE int sqlite3BtreeInsert(
   68573   BtCursor *pCur,                /* Insert data into the table of this cursor */
   68574   const BtreePayload *pX,        /* Content of the row to be inserted */
   68575   int flags,                     /* True if this is likely an append */
   68576   int seekResult                 /* Result of prior MovetoUnpacked() call */
   68577 ){
   68578   int rc;
   68579   int loc = seekResult;          /* -1: before desired location  +1: after */
   68580   int szNew = 0;
   68581   int idx;
   68582   MemPage *pPage;
   68583   Btree *p = pCur->pBtree;
   68584   BtShared *pBt = p->pBt;
   68585   unsigned char *oldCell;
   68586   unsigned char *newCell = 0;
   68587 
   68588   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
   68589 
   68590   if( pCur->eState==CURSOR_FAULT ){
   68591     assert( pCur->skipNext!=SQLITE_OK );
   68592     return pCur->skipNext;
   68593   }
   68594 
   68595   assert( cursorOwnsBtShared(pCur) );
   68596   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
   68597               && pBt->inTransaction==TRANS_WRITE
   68598               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
   68599   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   68600 
   68601   /* Assert that the caller has been consistent. If this cursor was opened
   68602   ** expecting an index b-tree, then the caller should be inserting blob
   68603   ** keys with no associated data. If the cursor was opened expecting an
   68604   ** intkey table, the caller should be inserting integer keys with a
   68605   ** blob of associated data.  */
   68606   assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
   68607 
   68608   /* Save the positions of any other cursors open on this table.
   68609   **
   68610   ** In some cases, the call to btreeMoveto() below is a no-op. For
   68611   ** example, when inserting data into a table with auto-generated integer
   68612   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
   68613   ** integer key to use. It then calls this function to actually insert the
   68614   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   68615   ** that the cursor is already where it needs to be and returns without
   68616   ** doing any work. To avoid thwarting these optimizations, it is important
   68617   ** not to clear the cursor here.
   68618   */
   68619   if( pCur->curFlags & BTCF_Multiple ){
   68620     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   68621     if( rc ) return rc;
   68622   }
   68623 
   68624   if( pCur->pKeyInfo==0 ){
   68625     assert( pX->pKey==0 );
   68626     /* If this is an insert into a table b-tree, invalidate any incrblob
   68627     ** cursors open on the row being replaced */
   68628     invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
   68629 
   68630     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
   68631     ** to a row with the same key as the new entry being inserted.  */
   68632     assert( (flags & BTREE_SAVEPOSITION)==0 ||
   68633             ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
   68634 
   68635     /* If the cursor is currently on the last row and we are appending a
   68636     ** new row onto the end, set the "loc" to avoid an unnecessary
   68637     ** btreeMoveto() call */
   68638     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
   68639       loc = 0;
   68640     }else if( loc==0 ){
   68641       rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
   68642       if( rc ) return rc;
   68643     }
   68644   }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
   68645     if( pX->nMem ){
   68646       UnpackedRecord r;
   68647       r.pKeyInfo = pCur->pKeyInfo;
   68648       r.aMem = pX->aMem;
   68649       r.nField = pX->nMem;
   68650       r.default_rc = 0;
   68651       r.errCode = 0;
   68652       r.r1 = 0;
   68653       r.r2 = 0;
   68654       r.eqSeen = 0;
   68655       rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
   68656     }else{
   68657       rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
   68658     }
   68659     if( rc ) return rc;
   68660   }
   68661   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
   68662 
   68663   pPage = pCur->pPage;
   68664   assert( pPage->intKey || pX->nKey>=0 );
   68665   assert( pPage->leaf || !pPage->intKey );
   68666 
   68667   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
   68668           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
   68669           loc==0 ? "overwrite" : "new entry"));
   68670   assert( pPage->isInit );
   68671   newCell = pBt->pTmpSpace;
   68672   assert( newCell!=0 );
   68673   rc = fillInCell(pPage, newCell, pX, &szNew);
   68674   if( rc ) goto end_insert;
   68675   assert( szNew==pPage->xCellSize(pPage, newCell) );
   68676   assert( szNew <= MX_CELL_SIZE(pBt) );
   68677   idx = pCur->ix;
   68678   if( loc==0 ){
   68679     CellInfo info;
   68680     assert( idx<pPage->nCell );
   68681     rc = sqlite3PagerWrite(pPage->pDbPage);
   68682     if( rc ){
   68683       goto end_insert;
   68684     }
   68685     oldCell = findCell(pPage, idx);
   68686     if( !pPage->leaf ){
   68687       memcpy(newCell, oldCell, 4);
   68688     }
   68689     rc = clearCell(pPage, oldCell, &info);
   68690     if( info.nSize==szNew && info.nLocal==info.nPayload
   68691      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
   68692     ){
   68693       /* Overwrite the old cell with the new if they are the same size.
   68694       ** We could also try to do this if the old cell is smaller, then add
   68695       ** the leftover space to the free list.  But experiments show that
   68696       ** doing that is no faster then skipping this optimization and just
   68697       ** calling dropCell() and insertCell().
   68698       **
   68699       ** This optimization cannot be used on an autovacuum database if the
   68700       ** new entry uses overflow pages, as the insertCell() call below is
   68701       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
   68702       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
   68703       if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
   68704       memcpy(oldCell, newCell, szNew);
   68705       return SQLITE_OK;
   68706     }
   68707     dropCell(pPage, idx, info.nSize, &rc);
   68708     if( rc ) goto end_insert;
   68709   }else if( loc<0 && pPage->nCell>0 ){
   68710     assert( pPage->leaf );
   68711     idx = ++pCur->ix;
   68712     pCur->curFlags &= ~BTCF_ValidNKey;
   68713   }else{
   68714     assert( pPage->leaf );
   68715   }
   68716   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
   68717   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
   68718   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
   68719 
   68720   /* If no error has occurred and pPage has an overflow cell, call balance()
   68721   ** to redistribute the cells within the tree. Since balance() may move
   68722   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
   68723   ** variables.
   68724   **
   68725   ** Previous versions of SQLite called moveToRoot() to move the cursor
   68726   ** back to the root page as balance() used to invalidate the contents
   68727   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
   68728   ** set the cursor state to "invalid". This makes common insert operations
   68729   ** slightly faster.
   68730   **
   68731   ** There is a subtle but important optimization here too. When inserting
   68732   ** multiple records into an intkey b-tree using a single cursor (as can
   68733   ** happen while processing an "INSERT INTO ... SELECT" statement), it
   68734   ** is advantageous to leave the cursor pointing to the last entry in
   68735   ** the b-tree if possible. If the cursor is left pointing to the last
   68736   ** entry in the table, and the next row inserted has an integer key
   68737   ** larger than the largest existing key, it is possible to insert the
   68738   ** row without seeking the cursor. This can be a big performance boost.
   68739   */
   68740   pCur->info.nSize = 0;
   68741   if( pPage->nOverflow ){
   68742     assert( rc==SQLITE_OK );
   68743     pCur->curFlags &= ~(BTCF_ValidNKey);
   68744     rc = balance(pCur);
   68745 
   68746     /* Must make sure nOverflow is reset to zero even if the balance()
   68747     ** fails. Internal data structure corruption will result otherwise.
   68748     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
   68749     ** from trying to save the current position of the cursor.  */
   68750     pCur->pPage->nOverflow = 0;
   68751     pCur->eState = CURSOR_INVALID;
   68752     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
   68753       btreeReleaseAllCursorPages(pCur);
   68754       if( pCur->pKeyInfo ){
   68755         assert( pCur->pKey==0 );
   68756         pCur->pKey = sqlite3Malloc( pX->nKey );
   68757         if( pCur->pKey==0 ){
   68758           rc = SQLITE_NOMEM;
   68759         }else{
   68760           memcpy(pCur->pKey, pX->pKey, pX->nKey);
   68761         }
   68762       }
   68763       pCur->eState = CURSOR_REQUIRESEEK;
   68764       pCur->nKey = pX->nKey;
   68765     }
   68766   }
   68767   assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
   68768 
   68769 end_insert:
   68770   return rc;
   68771 }
   68772 
   68773 /*
   68774 ** Delete the entry that the cursor is pointing to.
   68775 **
   68776 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
   68777 ** the cursor is left pointing at an arbitrary location after the delete.
   68778 ** But if that bit is set, then the cursor is left in a state such that
   68779 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
   68780 ** as it would have been on if the call to BtreeDelete() had been omitted.
   68781 **
   68782 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
   68783 ** associated with a single table entry and its indexes.  Only one of those
   68784 ** deletes is considered the "primary" delete.  The primary delete occurs
   68785 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
   68786 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
   68787 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
   68788 ** but which might be used by alternative storage engines.
   68789 */
   68790 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   68791   Btree *p = pCur->pBtree;
   68792   BtShared *pBt = p->pBt;
   68793   int rc;                              /* Return code */
   68794   MemPage *pPage;                      /* Page to delete cell from */
   68795   unsigned char *pCell;                /* Pointer to cell to delete */
   68796   int iCellIdx;                        /* Index of cell to delete */
   68797   int iCellDepth;                      /* Depth of node containing pCell */
   68798   CellInfo info;                       /* Size of the cell being deleted */
   68799   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
   68800   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
   68801 
   68802   assert( cursorOwnsBtShared(pCur) );
   68803   assert( pBt->inTransaction==TRANS_WRITE );
   68804   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   68805   assert( pCur->curFlags & BTCF_WriteFlag );
   68806   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   68807   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   68808   assert( pCur->ix<pCur->pPage->nCell );
   68809   assert( pCur->eState==CURSOR_VALID );
   68810   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
   68811 
   68812   iCellDepth = pCur->iPage;
   68813   iCellIdx = pCur->ix;
   68814   pPage = pCur->pPage;
   68815   pCell = findCell(pPage, iCellIdx);
   68816 
   68817   /* If the bPreserve flag is set to true, then the cursor position must
   68818   ** be preserved following this delete operation. If the current delete
   68819   ** will cause a b-tree rebalance, then this is done by saving the cursor
   68820   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
   68821   ** returning.
   68822   **
   68823   ** Or, if the current delete will not cause a rebalance, then the cursor
   68824   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
   68825   ** before or after the deleted entry. In this case set bSkipnext to true.  */
   68826   if( bPreserve ){
   68827     if( !pPage->leaf
   68828      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
   68829     ){
   68830       /* A b-tree rebalance will be required after deleting this entry.
   68831       ** Save the cursor key.  */
   68832       rc = saveCursorKey(pCur);
   68833       if( rc ) return rc;
   68834     }else{
   68835       bSkipnext = 1;
   68836     }
   68837   }
   68838 
   68839   /* If the page containing the entry to delete is not a leaf page, move
   68840   ** the cursor to the largest entry in the tree that is smaller than
   68841   ** the entry being deleted. This cell will replace the cell being deleted
   68842   ** from the internal node. The 'previous' entry is used for this instead
   68843   ** of the 'next' entry, as the previous entry is always a part of the
   68844   ** sub-tree headed by the child page of the cell being deleted. This makes
   68845   ** balancing the tree following the delete operation easier.  */
   68846   if( !pPage->leaf ){
   68847     rc = sqlite3BtreePrevious(pCur, 0);
   68848     assert( rc!=SQLITE_DONE );
   68849     if( rc ) return rc;
   68850   }
   68851 
   68852   /* Save the positions of any other cursors open on this table before
   68853   ** making any modifications.  */
   68854   if( pCur->curFlags & BTCF_Multiple ){
   68855     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   68856     if( rc ) return rc;
   68857   }
   68858 
   68859   /* If this is a delete operation to remove a row from a table b-tree,
   68860   ** invalidate any incrblob cursors open on the row being deleted.  */
   68861   if( pCur->pKeyInfo==0 ){
   68862     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
   68863   }
   68864 
   68865   /* Make the page containing the entry to be deleted writable. Then free any
   68866   ** overflow pages associated with the entry and finally remove the cell
   68867   ** itself from within the page.  */
   68868   rc = sqlite3PagerWrite(pPage->pDbPage);
   68869   if( rc ) return rc;
   68870   rc = clearCell(pPage, pCell, &info);
   68871   dropCell(pPage, iCellIdx, info.nSize, &rc);
   68872   if( rc ) return rc;
   68873 
   68874   /* If the cell deleted was not located on a leaf page, then the cursor
   68875   ** is currently pointing to the largest entry in the sub-tree headed
   68876   ** by the child-page of the cell that was just deleted from an internal
   68877   ** node. The cell from the leaf node needs to be moved to the internal
   68878   ** node to replace the deleted cell.  */
   68879   if( !pPage->leaf ){
   68880     MemPage *pLeaf = pCur->pPage;
   68881     int nCell;
   68882     Pgno n;
   68883     unsigned char *pTmp;
   68884 
   68885     if( iCellDepth<pCur->iPage-1 ){
   68886       n = pCur->apPage[iCellDepth+1]->pgno;
   68887     }else{
   68888       n = pCur->pPage->pgno;
   68889     }
   68890     pCell = findCell(pLeaf, pLeaf->nCell-1);
   68891     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
   68892     nCell = pLeaf->xCellSize(pLeaf, pCell);
   68893     assert( MX_CELL_SIZE(pBt) >= nCell );
   68894     pTmp = pBt->pTmpSpace;
   68895     assert( pTmp!=0 );
   68896     rc = sqlite3PagerWrite(pLeaf->pDbPage);
   68897     if( rc==SQLITE_OK ){
   68898       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
   68899     }
   68900     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
   68901     if( rc ) return rc;
   68902   }
   68903 
   68904   /* Balance the tree. If the entry deleted was located on a leaf page,
   68905   ** then the cursor still points to that page. In this case the first
   68906   ** call to balance() repairs the tree, and the if(...) condition is
   68907   ** never true.
   68908   **
   68909   ** Otherwise, if the entry deleted was on an internal node page, then
   68910   ** pCur is pointing to the leaf page from which a cell was removed to
   68911   ** replace the cell deleted from the internal node. This is slightly
   68912   ** tricky as the leaf node may be underfull, and the internal node may
   68913   ** be either under or overfull. In this case run the balancing algorithm
   68914   ** on the leaf node first. If the balance proceeds far enough up the
   68915   ** tree that we can be sure that any problem in the internal node has
   68916   ** been corrected, so be it. Otherwise, after balancing the leaf node,
   68917   ** walk the cursor up the tree to the internal node and balance it as
   68918   ** well.  */
   68919   rc = balance(pCur);
   68920   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
   68921     releasePageNotNull(pCur->pPage);
   68922     pCur->iPage--;
   68923     while( pCur->iPage>iCellDepth ){
   68924       releasePage(pCur->apPage[pCur->iPage--]);
   68925     }
   68926     pCur->pPage = pCur->apPage[pCur->iPage];
   68927     rc = balance(pCur);
   68928   }
   68929 
   68930   if( rc==SQLITE_OK ){
   68931     if( bSkipnext ){
   68932       assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
   68933       assert( pPage==pCur->pPage || CORRUPT_DB );
   68934       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
   68935       pCur->eState = CURSOR_SKIPNEXT;
   68936       if( iCellIdx>=pPage->nCell ){
   68937         pCur->skipNext = -1;
   68938         pCur->ix = pPage->nCell-1;
   68939       }else{
   68940         pCur->skipNext = 1;
   68941       }
   68942     }else{
   68943       rc = moveToRoot(pCur);
   68944       if( bPreserve ){
   68945         btreeReleaseAllCursorPages(pCur);
   68946         pCur->eState = CURSOR_REQUIRESEEK;
   68947       }
   68948       if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
   68949     }
   68950   }
   68951   return rc;
   68952 }
   68953 
   68954 /*
   68955 ** Create a new BTree table.  Write into *piTable the page
   68956 ** number for the root page of the new table.
   68957 **
   68958 ** The type of type is determined by the flags parameter.  Only the
   68959 ** following values of flags are currently in use.  Other values for
   68960 ** flags might not work:
   68961 **
   68962 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
   68963 **     BTREE_ZERODATA                  Used for SQL indices
   68964 */
   68965 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
   68966   BtShared *pBt = p->pBt;
   68967   MemPage *pRoot;
   68968   Pgno pgnoRoot;
   68969   int rc;
   68970   int ptfFlags;          /* Page-type flage for the root page of new table */
   68971 
   68972   assert( sqlite3BtreeHoldsMutex(p) );
   68973   assert( pBt->inTransaction==TRANS_WRITE );
   68974   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   68975 
   68976 #ifdef SQLITE_OMIT_AUTOVACUUM
   68977   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   68978   if( rc ){
   68979     return rc;
   68980   }
   68981 #else
   68982   if( pBt->autoVacuum ){
   68983     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
   68984     MemPage *pPageMove; /* The page to move to. */
   68985 
   68986     /* Creating a new table may probably require moving an existing database
   68987     ** to make room for the new tables root page. In case this page turns
   68988     ** out to be an overflow page, delete all overflow page-map caches
   68989     ** held by open cursors.
   68990     */
   68991     invalidateAllOverflowCache(pBt);
   68992 
   68993     /* Read the value of meta[3] from the database to determine where the
   68994     ** root page of the new table should go. meta[3] is the largest root-page
   68995     ** created so far, so the new root-page is (meta[3]+1).
   68996     */
   68997     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
   68998     pgnoRoot++;
   68999 
   69000     /* The new root-page may not be allocated on a pointer-map page, or the
   69001     ** PENDING_BYTE page.
   69002     */
   69003     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
   69004         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
   69005       pgnoRoot++;
   69006     }
   69007     assert( pgnoRoot>=3 || CORRUPT_DB );
   69008     testcase( pgnoRoot<3 );
   69009 
   69010     /* Allocate a page. The page that currently resides at pgnoRoot will
   69011     ** be moved to the allocated page (unless the allocated page happens
   69012     ** to reside at pgnoRoot).
   69013     */
   69014     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
   69015     if( rc!=SQLITE_OK ){
   69016       return rc;
   69017     }
   69018 
   69019     if( pgnoMove!=pgnoRoot ){
   69020       /* pgnoRoot is the page that will be used for the root-page of
   69021       ** the new table (assuming an error did not occur). But we were
   69022       ** allocated pgnoMove. If required (i.e. if it was not allocated
   69023       ** by extending the file), the current page at position pgnoMove
   69024       ** is already journaled.
   69025       */
   69026       u8 eType = 0;
   69027       Pgno iPtrPage = 0;
   69028 
   69029       /* Save the positions of any open cursors. This is required in
   69030       ** case they are holding a reference to an xFetch reference
   69031       ** corresponding to page pgnoRoot.  */
   69032       rc = saveAllCursors(pBt, 0, 0);
   69033       releasePage(pPageMove);
   69034       if( rc!=SQLITE_OK ){
   69035         return rc;
   69036       }
   69037 
   69038       /* Move the page currently at pgnoRoot to pgnoMove. */
   69039       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   69040       if( rc!=SQLITE_OK ){
   69041         return rc;
   69042       }
   69043       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
   69044       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
   69045         rc = SQLITE_CORRUPT_BKPT;
   69046       }
   69047       if( rc!=SQLITE_OK ){
   69048         releasePage(pRoot);
   69049         return rc;
   69050       }
   69051       assert( eType!=PTRMAP_ROOTPAGE );
   69052       assert( eType!=PTRMAP_FREEPAGE );
   69053       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
   69054       releasePage(pRoot);
   69055 
   69056       /* Obtain the page at pgnoRoot */
   69057       if( rc!=SQLITE_OK ){
   69058         return rc;
   69059       }
   69060       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   69061       if( rc!=SQLITE_OK ){
   69062         return rc;
   69063       }
   69064       rc = sqlite3PagerWrite(pRoot->pDbPage);
   69065       if( rc!=SQLITE_OK ){
   69066         releasePage(pRoot);
   69067         return rc;
   69068       }
   69069     }else{
   69070       pRoot = pPageMove;
   69071     }
   69072 
   69073     /* Update the pointer-map and meta-data with the new root-page number. */
   69074     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
   69075     if( rc ){
   69076       releasePage(pRoot);
   69077       return rc;
   69078     }
   69079 
   69080     /* When the new root page was allocated, page 1 was made writable in
   69081     ** order either to increase the database filesize, or to decrement the
   69082     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
   69083     */
   69084     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
   69085     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
   69086     if( NEVER(rc) ){
   69087       releasePage(pRoot);
   69088       return rc;
   69089     }
   69090 
   69091   }else{
   69092     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   69093     if( rc ) return rc;
   69094   }
   69095 #endif
   69096   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   69097   if( createTabFlags & BTREE_INTKEY ){
   69098     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
   69099   }else{
   69100     ptfFlags = PTF_ZERODATA | PTF_LEAF;
   69101   }
   69102   zeroPage(pRoot, ptfFlags);
   69103   sqlite3PagerUnref(pRoot->pDbPage);
   69104   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
   69105   *piTable = (int)pgnoRoot;
   69106   return SQLITE_OK;
   69107 }
   69108 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
   69109   int rc;
   69110   sqlite3BtreeEnter(p);
   69111   rc = btreeCreateTable(p, piTable, flags);
   69112   sqlite3BtreeLeave(p);
   69113   return rc;
   69114 }
   69115 
   69116 /*
   69117 ** Erase the given database page and all its children.  Return
   69118 ** the page to the freelist.
   69119 */
   69120 static int clearDatabasePage(
   69121   BtShared *pBt,           /* The BTree that contains the table */
   69122   Pgno pgno,               /* Page number to clear */
   69123   int freePageFlag,        /* Deallocate page if true */
   69124   int *pnChange            /* Add number of Cells freed to this counter */
   69125 ){
   69126   MemPage *pPage;
   69127   int rc;
   69128   unsigned char *pCell;
   69129   int i;
   69130   int hdr;
   69131   CellInfo info;
   69132 
   69133   assert( sqlite3_mutex_held(pBt->mutex) );
   69134   if( pgno>btreePagecount(pBt) ){
   69135     return SQLITE_CORRUPT_BKPT;
   69136   }
   69137   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
   69138   if( rc ) return rc;
   69139   if( pPage->bBusy ){
   69140     rc = SQLITE_CORRUPT_BKPT;
   69141     goto cleardatabasepage_out;
   69142   }
   69143   pPage->bBusy = 1;
   69144   hdr = pPage->hdrOffset;
   69145   for(i=0; i<pPage->nCell; i++){
   69146     pCell = findCell(pPage, i);
   69147     if( !pPage->leaf ){
   69148       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
   69149       if( rc ) goto cleardatabasepage_out;
   69150     }
   69151     rc = clearCell(pPage, pCell, &info);
   69152     if( rc ) goto cleardatabasepage_out;
   69153   }
   69154   if( !pPage->leaf ){
   69155     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
   69156     if( rc ) goto cleardatabasepage_out;
   69157   }else if( pnChange ){
   69158     assert( pPage->intKey || CORRUPT_DB );
   69159     testcase( !pPage->intKey );
   69160     *pnChange += pPage->nCell;
   69161   }
   69162   if( freePageFlag ){
   69163     freePage(pPage, &rc);
   69164   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
   69165     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
   69166   }
   69167 
   69168 cleardatabasepage_out:
   69169   pPage->bBusy = 0;
   69170   releasePage(pPage);
   69171   return rc;
   69172 }
   69173 
   69174 /*
   69175 ** Delete all information from a single table in the database.  iTable is
   69176 ** the page number of the root of the table.  After this routine returns,
   69177 ** the root page is empty, but still exists.
   69178 **
   69179 ** This routine will fail with SQLITE_LOCKED if there are any open
   69180 ** read cursors on the table.  Open write cursors are moved to the
   69181 ** root of the table.
   69182 **
   69183 ** If pnChange is not NULL, then table iTable must be an intkey table. The
   69184 ** integer value pointed to by pnChange is incremented by the number of
   69185 ** entries in the table.
   69186 */
   69187 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
   69188   int rc;
   69189   BtShared *pBt = p->pBt;
   69190   sqlite3BtreeEnter(p);
   69191   assert( p->inTrans==TRANS_WRITE );
   69192 
   69193   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
   69194 
   69195   if( SQLITE_OK==rc ){
   69196     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
   69197     ** is the root of a table b-tree - if it is not, the following call is
   69198     ** a no-op).  */
   69199     invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
   69200     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   69201   }
   69202   sqlite3BtreeLeave(p);
   69203   return rc;
   69204 }
   69205 
   69206 /*
   69207 ** Delete all information from the single table that pCur is open on.
   69208 **
   69209 ** This routine only work for pCur on an ephemeral table.
   69210 */
   69211 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
   69212   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
   69213 }
   69214 
   69215 /*
   69216 ** Erase all information in a table and add the root of the table to
   69217 ** the freelist.  Except, the root of the principle table (the one on
   69218 ** page 1) is never added to the freelist.
   69219 **
   69220 ** This routine will fail with SQLITE_LOCKED if there are any open
   69221 ** cursors on the table.
   69222 **
   69223 ** If AUTOVACUUM is enabled and the page at iTable is not the last
   69224 ** root page in the database file, then the last root page
   69225 ** in the database file is moved into the slot formerly occupied by
   69226 ** iTable and that last slot formerly occupied by the last root page
   69227 ** is added to the freelist instead of iTable.  In this say, all
   69228 ** root pages are kept at the beginning of the database file, which
   69229 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
   69230 ** page number that used to be the last root page in the file before
   69231 ** the move.  If no page gets moved, *piMoved is set to 0.
   69232 ** The last root page is recorded in meta[3] and the value of
   69233 ** meta[3] is updated by this procedure.
   69234 */
   69235 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
   69236   int rc;
   69237   MemPage *pPage = 0;
   69238   BtShared *pBt = p->pBt;
   69239 
   69240   assert( sqlite3BtreeHoldsMutex(p) );
   69241   assert( p->inTrans==TRANS_WRITE );
   69242   assert( iTable>=2 );
   69243 
   69244   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
   69245   if( rc ) return rc;
   69246   rc = sqlite3BtreeClearTable(p, iTable, 0);
   69247   if( rc ){
   69248     releasePage(pPage);
   69249     return rc;
   69250   }
   69251 
   69252   *piMoved = 0;
   69253 
   69254 #ifdef SQLITE_OMIT_AUTOVACUUM
   69255   freePage(pPage, &rc);
   69256   releasePage(pPage);
   69257 #else
   69258   if( pBt->autoVacuum ){
   69259     Pgno maxRootPgno;
   69260     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
   69261 
   69262     if( iTable==maxRootPgno ){
   69263       /* If the table being dropped is the table with the largest root-page
   69264       ** number in the database, put the root page on the free list.
   69265       */
   69266       freePage(pPage, &rc);
   69267       releasePage(pPage);
   69268       if( rc!=SQLITE_OK ){
   69269         return rc;
   69270       }
   69271     }else{
   69272       /* The table being dropped does not have the largest root-page
   69273       ** number in the database. So move the page that does into the
   69274       ** gap left by the deleted root-page.
   69275       */
   69276       MemPage *pMove;
   69277       releasePage(pPage);
   69278       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   69279       if( rc!=SQLITE_OK ){
   69280         return rc;
   69281       }
   69282       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
   69283       releasePage(pMove);
   69284       if( rc!=SQLITE_OK ){
   69285         return rc;
   69286       }
   69287       pMove = 0;
   69288       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   69289       freePage(pMove, &rc);
   69290       releasePage(pMove);
   69291       if( rc!=SQLITE_OK ){
   69292         return rc;
   69293       }
   69294       *piMoved = maxRootPgno;
   69295     }
   69296 
   69297     /* Set the new 'max-root-page' value in the database header. This
   69298     ** is the old value less one, less one more if that happens to
   69299     ** be a root-page number, less one again if that is the
   69300     ** PENDING_BYTE_PAGE.
   69301     */
   69302     maxRootPgno--;
   69303     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
   69304            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
   69305       maxRootPgno--;
   69306     }
   69307     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
   69308 
   69309     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
   69310   }else{
   69311     freePage(pPage, &rc);
   69312     releasePage(pPage);
   69313   }
   69314 #endif
   69315   return rc;
   69316 }
   69317 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   69318   int rc;
   69319   sqlite3BtreeEnter(p);
   69320   rc = btreeDropTable(p, iTable, piMoved);
   69321   sqlite3BtreeLeave(p);
   69322   return rc;
   69323 }
   69324 
   69325 
   69326 /*
   69327 ** This function may only be called if the b-tree connection already
   69328 ** has a read or write transaction open on the database.
   69329 **
   69330 ** Read the meta-information out of a database file.  Meta[0]
   69331 ** is the number of free pages currently in the database.  Meta[1]
   69332 ** through meta[15] are available for use by higher layers.  Meta[0]
   69333 ** is read-only, the others are read/write.
   69334 **
   69335 ** The schema layer numbers meta values differently.  At the schema
   69336 ** layer (and the SetCookie and ReadCookie opcodes) the number of
   69337 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
   69338 **
   69339 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
   69340 ** of reading the value out of the header, it instead loads the "DataVersion"
   69341 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
   69342 ** database file.  It is a number computed by the pager.  But its access
   69343 ** pattern is the same as header meta values, and so it is convenient to
   69344 ** read it from this routine.
   69345 */
   69346 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
   69347   BtShared *pBt = p->pBt;
   69348 
   69349   sqlite3BtreeEnter(p);
   69350   assert( p->inTrans>TRANS_NONE );
   69351   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
   69352   assert( pBt->pPage1 );
   69353   assert( idx>=0 && idx<=15 );
   69354 
   69355   if( idx==BTREE_DATA_VERSION ){
   69356     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
   69357   }else{
   69358     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   69359   }
   69360 
   69361   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
   69362   ** database, mark the database as read-only.  */
   69363 #ifdef SQLITE_OMIT_AUTOVACUUM
   69364   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
   69365     pBt->btsFlags |= BTS_READ_ONLY;
   69366   }
   69367 #endif
   69368 
   69369   sqlite3BtreeLeave(p);
   69370 }
   69371 
   69372 /*
   69373 ** Write meta-information back into the database.  Meta[0] is
   69374 ** read-only and may not be written.
   69375 */
   69376 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   69377   BtShared *pBt = p->pBt;
   69378   unsigned char *pP1;
   69379   int rc;
   69380   assert( idx>=1 && idx<=15 );
   69381   sqlite3BtreeEnter(p);
   69382   assert( p->inTrans==TRANS_WRITE );
   69383   assert( pBt->pPage1!=0 );
   69384   pP1 = pBt->pPage1->aData;
   69385   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   69386   if( rc==SQLITE_OK ){
   69387     put4byte(&pP1[36 + idx*4], iMeta);
   69388 #ifndef SQLITE_OMIT_AUTOVACUUM
   69389     if( idx==BTREE_INCR_VACUUM ){
   69390       assert( pBt->autoVacuum || iMeta==0 );
   69391       assert( iMeta==0 || iMeta==1 );
   69392       pBt->incrVacuum = (u8)iMeta;
   69393     }
   69394 #endif
   69395   }
   69396   sqlite3BtreeLeave(p);
   69397   return rc;
   69398 }
   69399 
   69400 #ifndef SQLITE_OMIT_BTREECOUNT
   69401 /*
   69402 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
   69403 ** number of entries in the b-tree and write the result to *pnEntry.
   69404 **
   69405 ** SQLITE_OK is returned if the operation is successfully executed.
   69406 ** Otherwise, if an error is encountered (i.e. an IO error or database
   69407 ** corruption) an SQLite error code is returned.
   69408 */
   69409 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   69410   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   69411   int rc;                              /* Return code */
   69412 
   69413   rc = moveToRoot(pCur);
   69414   if( rc==SQLITE_EMPTY ){
   69415     *pnEntry = 0;
   69416     return SQLITE_OK;
   69417   }
   69418 
   69419   /* Unless an error occurs, the following loop runs one iteration for each
   69420   ** page in the B-Tree structure (not including overflow pages).
   69421   */
   69422   while( rc==SQLITE_OK ){
   69423     int iIdx;                          /* Index of child node in parent */
   69424     MemPage *pPage;                    /* Current page of the b-tree */
   69425 
   69426     /* If this is a leaf page or the tree is not an int-key tree, then
   69427     ** this page contains countable entries. Increment the entry counter
   69428     ** accordingly.
   69429     */
   69430     pPage = pCur->pPage;
   69431     if( pPage->leaf || !pPage->intKey ){
   69432       nEntry += pPage->nCell;
   69433     }
   69434 
   69435     /* pPage is a leaf node. This loop navigates the cursor so that it
   69436     ** points to the first interior cell that it points to the parent of
   69437     ** the next page in the tree that has not yet been visited. The
   69438     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
   69439     ** of the page, or to the number of cells in the page if the next page
   69440     ** to visit is the right-child of its parent.
   69441     **
   69442     ** If all pages in the tree have been visited, return SQLITE_OK to the
   69443     ** caller.
   69444     */
   69445     if( pPage->leaf ){
   69446       do {
   69447         if( pCur->iPage==0 ){
   69448           /* All pages of the b-tree have been visited. Return successfully. */
   69449           *pnEntry = nEntry;
   69450           return moveToRoot(pCur);
   69451         }
   69452         moveToParent(pCur);
   69453       }while ( pCur->ix>=pCur->pPage->nCell );
   69454 
   69455       pCur->ix++;
   69456       pPage = pCur->pPage;
   69457     }
   69458 
   69459     /* Descend to the child node of the cell that the cursor currently
   69460     ** points at. This is the right-child if (iIdx==pPage->nCell).
   69461     */
   69462     iIdx = pCur->ix;
   69463     if( iIdx==pPage->nCell ){
   69464       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   69465     }else{
   69466       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
   69467     }
   69468   }
   69469 
   69470   /* An error has occurred. Return an error code. */
   69471   return rc;
   69472 }
   69473 #endif
   69474 
   69475 /*
   69476 ** Return the pager associated with a BTree.  This routine is used for
   69477 ** testing and debugging only.
   69478 */
   69479 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
   69480   return p->pBt->pPager;
   69481 }
   69482 
   69483 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   69484 /*
   69485 ** Append a message to the error message string.
   69486 */
   69487 static void checkAppendMsg(
   69488   IntegrityCk *pCheck,
   69489   const char *zFormat,
   69490   ...
   69491 ){
   69492   va_list ap;
   69493   if( !pCheck->mxErr ) return;
   69494   pCheck->mxErr--;
   69495   pCheck->nErr++;
   69496   va_start(ap, zFormat);
   69497   if( pCheck->errMsg.nChar ){
   69498     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
   69499   }
   69500   if( pCheck->zPfx ){
   69501     sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
   69502   }
   69503   sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
   69504   va_end(ap);
   69505   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
   69506     pCheck->mallocFailed = 1;
   69507   }
   69508 }
   69509 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   69510 
   69511 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   69512 
   69513 /*
   69514 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
   69515 ** corresponds to page iPg is already set.
   69516 */
   69517 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
   69518   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
   69519   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
   69520 }
   69521 
   69522 /*
   69523 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
   69524 */
   69525 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
   69526   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
   69527   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
   69528 }
   69529 
   69530 
   69531 /*
   69532 ** Add 1 to the reference count for page iPage.  If this is the second
   69533 ** reference to the page, add an error message to pCheck->zErrMsg.
   69534 ** Return 1 if there are 2 or more references to the page and 0 if
   69535 ** if this is the first reference to the page.
   69536 **
   69537 ** Also check that the page number is in bounds.
   69538 */
   69539 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
   69540   if( iPage==0 ) return 1;
   69541   if( iPage>pCheck->nPage ){
   69542     checkAppendMsg(pCheck, "invalid page number %d", iPage);
   69543     return 1;
   69544   }
   69545   if( getPageReferenced(pCheck, iPage) ){
   69546     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
   69547     return 1;
   69548   }
   69549   setPageReferenced(pCheck, iPage);
   69550   return 0;
   69551 }
   69552 
   69553 #ifndef SQLITE_OMIT_AUTOVACUUM
   69554 /*
   69555 ** Check that the entry in the pointer-map for page iChild maps to
   69556 ** page iParent, pointer type ptrType. If not, append an error message
   69557 ** to pCheck.
   69558 */
   69559 static void checkPtrmap(
   69560   IntegrityCk *pCheck,   /* Integrity check context */
   69561   Pgno iChild,           /* Child page number */
   69562   u8 eType,              /* Expected pointer map type */
   69563   Pgno iParent           /* Expected pointer map parent page number */
   69564 ){
   69565   int rc;
   69566   u8 ePtrmapType;
   69567   Pgno iPtrmapParent;
   69568 
   69569   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   69570   if( rc!=SQLITE_OK ){
   69571     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
   69572     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
   69573     return;
   69574   }
   69575 
   69576   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
   69577     checkAppendMsg(pCheck,
   69578       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
   69579       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   69580   }
   69581 }
   69582 #endif
   69583 
   69584 /*
   69585 ** Check the integrity of the freelist or of an overflow page list.
   69586 ** Verify that the number of pages on the list is N.
   69587 */
   69588 static void checkList(
   69589   IntegrityCk *pCheck,  /* Integrity checking context */
   69590   int isFreeList,       /* True for a freelist.  False for overflow page list */
   69591   int iPage,            /* Page number for first page in the list */
   69592   int N                 /* Expected number of pages in the list */
   69593 ){
   69594   int i;
   69595   int expected = N;
   69596   int iFirst = iPage;
   69597   while( N-- > 0 && pCheck->mxErr ){
   69598     DbPage *pOvflPage;
   69599     unsigned char *pOvflData;
   69600     if( iPage<1 ){
   69601       checkAppendMsg(pCheck,
   69602          "%d of %d pages missing from overflow list starting at %d",
   69603           N+1, expected, iFirst);
   69604       break;
   69605     }
   69606     if( checkRef(pCheck, iPage) ) break;
   69607     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
   69608       checkAppendMsg(pCheck, "failed to get page %d", iPage);
   69609       break;
   69610     }
   69611     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
   69612     if( isFreeList ){
   69613       int n = get4byte(&pOvflData[4]);
   69614 #ifndef SQLITE_OMIT_AUTOVACUUM
   69615       if( pCheck->pBt->autoVacuum ){
   69616         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
   69617       }
   69618 #endif
   69619       if( n>(int)pCheck->pBt->usableSize/4-2 ){
   69620         checkAppendMsg(pCheck,
   69621            "freelist leaf count too big on page %d", iPage);
   69622         N--;
   69623       }else{
   69624         for(i=0; i<n; i++){
   69625           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
   69626 #ifndef SQLITE_OMIT_AUTOVACUUM
   69627           if( pCheck->pBt->autoVacuum ){
   69628             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
   69629           }
   69630 #endif
   69631           checkRef(pCheck, iFreePage);
   69632         }
   69633         N -= n;
   69634       }
   69635     }
   69636 #ifndef SQLITE_OMIT_AUTOVACUUM
   69637     else{
   69638       /* If this database supports auto-vacuum and iPage is not the last
   69639       ** page in this overflow list, check that the pointer-map entry for
   69640       ** the following page matches iPage.
   69641       */
   69642       if( pCheck->pBt->autoVacuum && N>0 ){
   69643         i = get4byte(pOvflData);
   69644         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
   69645       }
   69646     }
   69647 #endif
   69648     iPage = get4byte(pOvflData);
   69649     sqlite3PagerUnref(pOvflPage);
   69650 
   69651     if( isFreeList && N<(iPage!=0) ){
   69652       checkAppendMsg(pCheck, "free-page count in header is too small");
   69653     }
   69654   }
   69655 }
   69656 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   69657 
   69658 /*
   69659 ** An implementation of a min-heap.
   69660 **
   69661 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
   69662 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
   69663 ** and aHeap[N*2+1].
   69664 **
   69665 ** The heap property is this:  Every node is less than or equal to both
   69666 ** of its daughter nodes.  A consequence of the heap property is that the
   69667 ** root node aHeap[1] is always the minimum value currently in the heap.
   69668 **
   69669 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
   69670 ** the heap, preserving the heap property.  The btreeHeapPull() routine
   69671 ** removes the root element from the heap (the minimum value in the heap)
   69672 ** and then moves other nodes around as necessary to preserve the heap
   69673 ** property.
   69674 **
   69675 ** This heap is used for cell overlap and coverage testing.  Each u32
   69676 ** entry represents the span of a cell or freeblock on a btree page.
   69677 ** The upper 16 bits are the index of the first byte of a range and the
   69678 ** lower 16 bits are the index of the last byte of that range.
   69679 */
   69680 static void btreeHeapInsert(u32 *aHeap, u32 x){
   69681   u32 j, i = ++aHeap[0];
   69682   aHeap[i] = x;
   69683   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
   69684     x = aHeap[j];
   69685     aHeap[j] = aHeap[i];
   69686     aHeap[i] = x;
   69687     i = j;
   69688   }
   69689 }
   69690 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
   69691   u32 j, i, x;
   69692   if( (x = aHeap[0])==0 ) return 0;
   69693   *pOut = aHeap[1];
   69694   aHeap[1] = aHeap[x];
   69695   aHeap[x] = 0xffffffff;
   69696   aHeap[0]--;
   69697   i = 1;
   69698   while( (j = i*2)<=aHeap[0] ){
   69699     if( aHeap[j]>aHeap[j+1] ) j++;
   69700     if( aHeap[i]<aHeap[j] ) break;
   69701     x = aHeap[i];
   69702     aHeap[i] = aHeap[j];
   69703     aHeap[j] = x;
   69704     i = j;
   69705   }
   69706   return 1;
   69707 }
   69708 
   69709 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   69710 /*
   69711 ** Do various sanity checks on a single page of a tree.  Return
   69712 ** the tree depth.  Root pages return 0.  Parents of root pages
   69713 ** return 1, and so forth.
   69714 **
   69715 ** These checks are done:
   69716 **
   69717 **      1.  Make sure that cells and freeblocks do not overlap
   69718 **          but combine to completely cover the page.
   69719 **      2.  Make sure integer cell keys are in order.
   69720 **      3.  Check the integrity of overflow pages.
   69721 **      4.  Recursively call checkTreePage on all children.
   69722 **      5.  Verify that the depth of all children is the same.
   69723 */
   69724 static int checkTreePage(
   69725   IntegrityCk *pCheck,  /* Context for the sanity check */
   69726   int iPage,            /* Page number of the page to check */
   69727   i64 *piMinKey,        /* Write minimum integer primary key here */
   69728   i64 maxKey            /* Error if integer primary key greater than this */
   69729 ){
   69730   MemPage *pPage = 0;      /* The page being analyzed */
   69731   int i;                   /* Loop counter */
   69732   int rc;                  /* Result code from subroutine call */
   69733   int depth = -1, d2;      /* Depth of a subtree */
   69734   int pgno;                /* Page number */
   69735   int nFrag;               /* Number of fragmented bytes on the page */
   69736   int hdr;                 /* Offset to the page header */
   69737   int cellStart;           /* Offset to the start of the cell pointer array */
   69738   int nCell;               /* Number of cells */
   69739   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
   69740   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
   69741                            ** False if IPK must be strictly less than maxKey */
   69742   u8 *data;                /* Page content */
   69743   u8 *pCell;               /* Cell content */
   69744   u8 *pCellIdx;            /* Next element of the cell pointer array */
   69745   BtShared *pBt;           /* The BtShared object that owns pPage */
   69746   u32 pc;                  /* Address of a cell */
   69747   u32 usableSize;          /* Usable size of the page */
   69748   u32 contentOffset;       /* Offset to the start of the cell content area */
   69749   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
   69750   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
   69751   const char *saved_zPfx = pCheck->zPfx;
   69752   int saved_v1 = pCheck->v1;
   69753   int saved_v2 = pCheck->v2;
   69754   u8 savedIsInit = 0;
   69755 
   69756   /* Check that the page exists
   69757   */
   69758   pBt = pCheck->pBt;
   69759   usableSize = pBt->usableSize;
   69760   if( iPage==0 ) return 0;
   69761   if( checkRef(pCheck, iPage) ) return 0;
   69762   pCheck->zPfx = "Page %d: ";
   69763   pCheck->v1 = iPage;
   69764   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
   69765     checkAppendMsg(pCheck,
   69766        "unable to get the page. error code=%d", rc);
   69767     goto end_of_check;
   69768   }
   69769 
   69770   /* Clear MemPage.isInit to make sure the corruption detection code in
   69771   ** btreeInitPage() is executed.  */
   69772   savedIsInit = pPage->isInit;
   69773   pPage->isInit = 0;
   69774   if( (rc = btreeInitPage(pPage))!=0 ){
   69775     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
   69776     checkAppendMsg(pCheck,
   69777                    "btreeInitPage() returns error code %d", rc);
   69778     goto end_of_check;
   69779   }
   69780   data = pPage->aData;
   69781   hdr = pPage->hdrOffset;
   69782 
   69783   /* Set up for cell analysis */
   69784   pCheck->zPfx = "On tree page %d cell %d: ";
   69785   contentOffset = get2byteNotZero(&data[hdr+5]);
   69786   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
   69787 
   69788   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
   69789   ** number of cells on the page. */
   69790   nCell = get2byte(&data[hdr+3]);
   69791   assert( pPage->nCell==nCell );
   69792 
   69793   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
   69794   ** immediately follows the b-tree page header. */
   69795   cellStart = hdr + 12 - 4*pPage->leaf;
   69796   assert( pPage->aCellIdx==&data[cellStart] );
   69797   pCellIdx = &data[cellStart + 2*(nCell-1)];
   69798 
   69799   if( !pPage->leaf ){
   69800     /* Analyze the right-child page of internal pages */
   69801     pgno = get4byte(&data[hdr+8]);
   69802 #ifndef SQLITE_OMIT_AUTOVACUUM
   69803     if( pBt->autoVacuum ){
   69804       pCheck->zPfx = "On page %d at right child: ";
   69805       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
   69806     }
   69807 #endif
   69808     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
   69809     keyCanBeEqual = 0;
   69810   }else{
   69811     /* For leaf pages, the coverage check will occur in the same loop
   69812     ** as the other cell checks, so initialize the heap.  */
   69813     heap = pCheck->heap;
   69814     heap[0] = 0;
   69815   }
   69816 
   69817   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
   69818   ** integer offsets to the cell contents. */
   69819   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
   69820     CellInfo info;
   69821 
   69822     /* Check cell size */
   69823     pCheck->v2 = i;
   69824     assert( pCellIdx==&data[cellStart + i*2] );
   69825     pc = get2byteAligned(pCellIdx);
   69826     pCellIdx -= 2;
   69827     if( pc<contentOffset || pc>usableSize-4 ){
   69828       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
   69829                              pc, contentOffset, usableSize-4);
   69830       doCoverageCheck = 0;
   69831       continue;
   69832     }
   69833     pCell = &data[pc];
   69834     pPage->xParseCell(pPage, pCell, &info);
   69835     if( pc+info.nSize>usableSize ){
   69836       checkAppendMsg(pCheck, "Extends off end of page");
   69837       doCoverageCheck = 0;
   69838       continue;
   69839     }
   69840 
   69841     /* Check for integer primary key out of range */
   69842     if( pPage->intKey ){
   69843       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
   69844         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
   69845       }
   69846       maxKey = info.nKey;
   69847       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
   69848     }
   69849 
   69850     /* Check the content overflow list */
   69851     if( info.nPayload>info.nLocal ){
   69852       int nPage;       /* Number of pages on the overflow chain */
   69853       Pgno pgnoOvfl;   /* First page of the overflow chain */
   69854       assert( pc + info.nSize - 4 <= usableSize );
   69855       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
   69856       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
   69857 #ifndef SQLITE_OMIT_AUTOVACUUM
   69858       if( pBt->autoVacuum ){
   69859         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
   69860       }
   69861 #endif
   69862       checkList(pCheck, 0, pgnoOvfl, nPage);
   69863     }
   69864 
   69865     if( !pPage->leaf ){
   69866       /* Check sanity of left child page for internal pages */
   69867       pgno = get4byte(pCell);
   69868 #ifndef SQLITE_OMIT_AUTOVACUUM
   69869       if( pBt->autoVacuum ){
   69870         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
   69871       }
   69872 #endif
   69873       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
   69874       keyCanBeEqual = 0;
   69875       if( d2!=depth ){
   69876         checkAppendMsg(pCheck, "Child page depth differs");
   69877         depth = d2;
   69878       }
   69879     }else{
   69880       /* Populate the coverage-checking heap for leaf pages */
   69881       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
   69882     }
   69883   }
   69884   *piMinKey = maxKey;
   69885 
   69886   /* Check for complete coverage of the page
   69887   */
   69888   pCheck->zPfx = 0;
   69889   if( doCoverageCheck && pCheck->mxErr>0 ){
   69890     /* For leaf pages, the min-heap has already been initialized and the
   69891     ** cells have already been inserted.  But for internal pages, that has
   69892     ** not yet been done, so do it now */
   69893     if( !pPage->leaf ){
   69894       heap = pCheck->heap;
   69895       heap[0] = 0;
   69896       for(i=nCell-1; i>=0; i--){
   69897         u32 size;
   69898         pc = get2byteAligned(&data[cellStart+i*2]);
   69899         size = pPage->xCellSize(pPage, &data[pc]);
   69900         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
   69901       }
   69902     }
   69903     /* Add the freeblocks to the min-heap
   69904     **
   69905     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
   69906     ** is the offset of the first freeblock, or zero if there are no
   69907     ** freeblocks on the page.
   69908     */
   69909     i = get2byte(&data[hdr+1]);
   69910     while( i>0 ){
   69911       int size, j;
   69912       assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
   69913       size = get2byte(&data[i+2]);
   69914       assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
   69915       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
   69916       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
   69917       ** big-endian integer which is the offset in the b-tree page of the next
   69918       ** freeblock in the chain, or zero if the freeblock is the last on the
   69919       ** chain. */
   69920       j = get2byte(&data[i]);
   69921       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
   69922       ** increasing offset. */
   69923       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
   69924       assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
   69925       i = j;
   69926     }
   69927     /* Analyze the min-heap looking for overlap between cells and/or
   69928     ** freeblocks, and counting the number of untracked bytes in nFrag.
   69929     **
   69930     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
   69931     ** There is an implied first entry the covers the page header, the cell
   69932     ** pointer index, and the gap between the cell pointer index and the start
   69933     ** of cell content.
   69934     **
   69935     ** The loop below pulls entries from the min-heap in order and compares
   69936     ** the start_address against the previous end_address.  If there is an
   69937     ** overlap, that means bytes are used multiple times.  If there is a gap,
   69938     ** that gap is added to the fragmentation count.
   69939     */
   69940     nFrag = 0;
   69941     prev = contentOffset - 1;   /* Implied first min-heap entry */
   69942     while( btreeHeapPull(heap,&x) ){
   69943       if( (prev&0xffff)>=(x>>16) ){
   69944         checkAppendMsg(pCheck,
   69945           "Multiple uses for byte %u of page %d", x>>16, iPage);
   69946         break;
   69947       }else{
   69948         nFrag += (x>>16) - (prev&0xffff) - 1;
   69949         prev = x;
   69950       }
   69951     }
   69952     nFrag += usableSize - (prev&0xffff) - 1;
   69953     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
   69954     ** is stored in the fifth field of the b-tree page header.
   69955     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
   69956     ** number of fragmented free bytes within the cell content area.
   69957     */
   69958     if( heap[0]==0 && nFrag!=data[hdr+7] ){
   69959       checkAppendMsg(pCheck,
   69960           "Fragmentation of %d bytes reported as %d on page %d",
   69961           nFrag, data[hdr+7], iPage);
   69962     }
   69963   }
   69964 
   69965 end_of_check:
   69966   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
   69967   releasePage(pPage);
   69968   pCheck->zPfx = saved_zPfx;
   69969   pCheck->v1 = saved_v1;
   69970   pCheck->v2 = saved_v2;
   69971   return depth+1;
   69972 }
   69973 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   69974 
   69975 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   69976 /*
   69977 ** This routine does a complete check of the given BTree file.  aRoot[] is
   69978 ** an array of pages numbers were each page number is the root page of
   69979 ** a table.  nRoot is the number of entries in aRoot.
   69980 **
   69981 ** A read-only or read-write transaction must be opened before calling
   69982 ** this function.
   69983 **
   69984 ** Write the number of error seen in *pnErr.  Except for some memory
   69985 ** allocation errors,  an error message held in memory obtained from
   69986 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
   69987 ** returned.  If a memory allocation error occurs, NULL is returned.
   69988 */
   69989 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   69990   Btree *p,     /* The btree to be checked */
   69991   int *aRoot,   /* An array of root pages numbers for individual trees */
   69992   int nRoot,    /* Number of entries in aRoot[] */
   69993   int mxErr,    /* Stop reporting errors after this many */
   69994   int *pnErr    /* Write number of errors seen to this variable */
   69995 ){
   69996   Pgno i;
   69997   IntegrityCk sCheck;
   69998   BtShared *pBt = p->pBt;
   69999   int savedDbFlags = pBt->db->flags;
   70000   char zErr[100];
   70001   VVA_ONLY( int nRef );
   70002 
   70003   sqlite3BtreeEnter(p);
   70004   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   70005   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
   70006   assert( nRef>=0 );
   70007   sCheck.pBt = pBt;
   70008   sCheck.pPager = pBt->pPager;
   70009   sCheck.nPage = btreePagecount(sCheck.pBt);
   70010   sCheck.mxErr = mxErr;
   70011   sCheck.nErr = 0;
   70012   sCheck.mallocFailed = 0;
   70013   sCheck.zPfx = 0;
   70014   sCheck.v1 = 0;
   70015   sCheck.v2 = 0;
   70016   sCheck.aPgRef = 0;
   70017   sCheck.heap = 0;
   70018   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
   70019   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
   70020   if( sCheck.nPage==0 ){
   70021     goto integrity_ck_cleanup;
   70022   }
   70023 
   70024   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
   70025   if( !sCheck.aPgRef ){
   70026     sCheck.mallocFailed = 1;
   70027     goto integrity_ck_cleanup;
   70028   }
   70029   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
   70030   if( sCheck.heap==0 ){
   70031     sCheck.mallocFailed = 1;
   70032     goto integrity_ck_cleanup;
   70033   }
   70034 
   70035   i = PENDING_BYTE_PAGE(pBt);
   70036   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
   70037 
   70038   /* Check the integrity of the freelist
   70039   */
   70040   sCheck.zPfx = "Main freelist: ";
   70041   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
   70042             get4byte(&pBt->pPage1->aData[36]));
   70043   sCheck.zPfx = 0;
   70044 
   70045   /* Check all the tables.
   70046   */
   70047   testcase( pBt->db->flags & SQLITE_CellSizeCk );
   70048   pBt->db->flags &= ~SQLITE_CellSizeCk;
   70049   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
   70050     i64 notUsed;
   70051     if( aRoot[i]==0 ) continue;
   70052 #ifndef SQLITE_OMIT_AUTOVACUUM
   70053     if( pBt->autoVacuum && aRoot[i]>1 ){
   70054       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
   70055     }
   70056 #endif
   70057     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
   70058   }
   70059   pBt->db->flags = savedDbFlags;
   70060 
   70061   /* Make sure every page in the file is referenced
   70062   */
   70063   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
   70064 #ifdef SQLITE_OMIT_AUTOVACUUM
   70065     if( getPageReferenced(&sCheck, i)==0 ){
   70066       checkAppendMsg(&sCheck, "Page %d is never used", i);
   70067     }
   70068 #else
   70069     /* If the database supports auto-vacuum, make sure no tables contain
   70070     ** references to pointer-map pages.
   70071     */
   70072     if( getPageReferenced(&sCheck, i)==0 &&
   70073        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
   70074       checkAppendMsg(&sCheck, "Page %d is never used", i);
   70075     }
   70076     if( getPageReferenced(&sCheck, i)!=0 &&
   70077        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
   70078       checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
   70079     }
   70080 #endif
   70081   }
   70082 
   70083   /* Clean  up and report errors.
   70084   */
   70085 integrity_ck_cleanup:
   70086   sqlite3PageFree(sCheck.heap);
   70087   sqlite3_free(sCheck.aPgRef);
   70088   if( sCheck.mallocFailed ){
   70089     sqlite3StrAccumReset(&sCheck.errMsg);
   70090     sCheck.nErr++;
   70091   }
   70092   *pnErr = sCheck.nErr;
   70093   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
   70094   /* Make sure this analysis did not leave any unref() pages. */
   70095   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
   70096   sqlite3BtreeLeave(p);
   70097   return sqlite3StrAccumFinish(&sCheck.errMsg);
   70098 }
   70099 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   70100 
   70101 /*
   70102 ** Return the full pathname of the underlying database file.  Return
   70103 ** an empty string if the database is in-memory or a TEMP database.
   70104 **
   70105 ** The pager filename is invariant as long as the pager is
   70106 ** open so it is safe to access without the BtShared mutex.
   70107 */
   70108 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
   70109   assert( p->pBt->pPager!=0 );
   70110   return sqlite3PagerFilename(p->pBt->pPager, 1);
   70111 }
   70112 
   70113 /*
   70114 ** Return the pathname of the journal file for this database. The return
   70115 ** value of this routine is the same regardless of whether the journal file
   70116 ** has been created or not.
   70117 **
   70118 ** The pager journal filename is invariant as long as the pager is
   70119 ** open so it is safe to access without the BtShared mutex.
   70120 */
   70121 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
   70122   assert( p->pBt->pPager!=0 );
   70123   return sqlite3PagerJournalname(p->pBt->pPager);
   70124 }
   70125 
   70126 /*
   70127 ** Return non-zero if a transaction is active.
   70128 */
   70129 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
   70130   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
   70131   return (p && (p->inTrans==TRANS_WRITE));
   70132 }
   70133 
   70134 #ifndef SQLITE_OMIT_WAL
   70135 /*
   70136 ** Run a checkpoint on the Btree passed as the first argument.
   70137 **
   70138 ** Return SQLITE_LOCKED if this or any other connection has an open
   70139 ** transaction on the shared-cache the argument Btree is connected to.
   70140 **
   70141 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   70142 */
   70143 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
   70144   int rc = SQLITE_OK;
   70145   if( p ){
   70146     BtShared *pBt = p->pBt;
   70147     sqlite3BtreeEnter(p);
   70148     if( pBt->inTransaction!=TRANS_NONE ){
   70149       rc = SQLITE_LOCKED;
   70150     }else{
   70151       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
   70152     }
   70153     sqlite3BtreeLeave(p);
   70154   }
   70155   return rc;
   70156 }
   70157 #endif
   70158 
   70159 /*
   70160 ** Return non-zero if a read (or write) transaction is active.
   70161 */
   70162 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
   70163   assert( p );
   70164   assert( sqlite3_mutex_held(p->db->mutex) );
   70165   return p->inTrans!=TRANS_NONE;
   70166 }
   70167 
   70168 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   70169   assert( p );
   70170   assert( sqlite3_mutex_held(p->db->mutex) );
   70171   return p->nBackup!=0;
   70172 }
   70173 
   70174 /*
   70175 ** This function returns a pointer to a blob of memory associated with
   70176 ** a single shared-btree. The memory is used by client code for its own
   70177 ** purposes (for example, to store a high-level schema associated with
   70178 ** the shared-btree). The btree layer manages reference counting issues.
   70179 **
   70180 ** The first time this is called on a shared-btree, nBytes bytes of memory
   70181 ** are allocated, zeroed, and returned to the caller. For each subsequent
   70182 ** call the nBytes parameter is ignored and a pointer to the same blob
   70183 ** of memory returned.
   70184 **
   70185 ** If the nBytes parameter is 0 and the blob of memory has not yet been
   70186 ** allocated, a null pointer is returned. If the blob has already been
   70187 ** allocated, it is returned as normal.
   70188 **
   70189 ** Just before the shared-btree is closed, the function passed as the
   70190 ** xFree argument when the memory allocation was made is invoked on the
   70191 ** blob of allocated memory. The xFree function should not call sqlite3_free()
   70192 ** on the memory, the btree layer does that.
   70193 */
   70194 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
   70195   BtShared *pBt = p->pBt;
   70196   sqlite3BtreeEnter(p);
   70197   if( !pBt->pSchema && nBytes ){
   70198     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
   70199     pBt->xFreeSchema = xFree;
   70200   }
   70201   sqlite3BtreeLeave(p);
   70202   return pBt->pSchema;
   70203 }
   70204 
   70205 /*
   70206 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
   70207 ** btree as the argument handle holds an exclusive lock on the
   70208 ** sqlite_master table. Otherwise SQLITE_OK.
   70209 */
   70210 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   70211   int rc;
   70212   assert( sqlite3_mutex_held(p->db->mutex) );
   70213   sqlite3BtreeEnter(p);
   70214   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   70215   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   70216   sqlite3BtreeLeave(p);
   70217   return rc;
   70218 }
   70219 
   70220 
   70221 #ifndef SQLITE_OMIT_SHARED_CACHE
   70222 /*
   70223 ** Obtain a lock on the table whose root page is iTab.  The
   70224 ** lock is a write lock if isWritelock is true or a read lock
   70225 ** if it is false.
   70226 */
   70227 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
   70228   int rc = SQLITE_OK;
   70229   assert( p->inTrans!=TRANS_NONE );
   70230   if( p->sharable ){
   70231     u8 lockType = READ_LOCK + isWriteLock;
   70232     assert( READ_LOCK+1==WRITE_LOCK );
   70233     assert( isWriteLock==0 || isWriteLock==1 );
   70234 
   70235     sqlite3BtreeEnter(p);
   70236     rc = querySharedCacheTableLock(p, iTab, lockType);
   70237     if( rc==SQLITE_OK ){
   70238       rc = setSharedCacheTableLock(p, iTab, lockType);
   70239     }
   70240     sqlite3BtreeLeave(p);
   70241   }
   70242   return rc;
   70243 }
   70244 #endif
   70245 
   70246 #ifndef SQLITE_OMIT_INCRBLOB
   70247 /*
   70248 ** Argument pCsr must be a cursor opened for writing on an
   70249 ** INTKEY table currently pointing at a valid table entry.
   70250 ** This function modifies the data stored as part of that entry.
   70251 **
   70252 ** Only the data content may only be modified, it is not possible to
   70253 ** change the length of the data stored. If this function is called with
   70254 ** parameters that attempt to write past the end of the existing data,
   70255 ** no modifications are made and SQLITE_CORRUPT is returned.
   70256 */
   70257 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
   70258   int rc;
   70259   assert( cursorOwnsBtShared(pCsr) );
   70260   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
   70261   assert( pCsr->curFlags & BTCF_Incrblob );
   70262 
   70263   rc = restoreCursorPosition(pCsr);
   70264   if( rc!=SQLITE_OK ){
   70265     return rc;
   70266   }
   70267   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
   70268   if( pCsr->eState!=CURSOR_VALID ){
   70269     return SQLITE_ABORT;
   70270   }
   70271 
   70272   /* Save the positions of all other cursors open on this table. This is
   70273   ** required in case any of them are holding references to an xFetch
   70274   ** version of the b-tree page modified by the accessPayload call below.
   70275   **
   70276   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
   70277   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
   70278   ** saveAllCursors can only return SQLITE_OK.
   70279   */
   70280   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
   70281   assert( rc==SQLITE_OK );
   70282 
   70283   /* Check some assumptions:
   70284   **   (a) the cursor is open for writing,
   70285   **   (b) there is a read/write transaction open,
   70286   **   (c) the connection holds a write-lock on the table (if required),
   70287   **   (d) there are no conflicting read-locks, and
   70288   **   (e) the cursor points at a valid row of an intKey table.
   70289   */
   70290   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
   70291     return SQLITE_READONLY;
   70292   }
   70293   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
   70294               && pCsr->pBt->inTransaction==TRANS_WRITE );
   70295   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
   70296   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
   70297   assert( pCsr->pPage->intKey );
   70298 
   70299   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
   70300 }
   70301 
   70302 /*
   70303 ** Mark this cursor as an incremental blob cursor.
   70304 */
   70305 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
   70306   pCur->curFlags |= BTCF_Incrblob;
   70307   pCur->pBtree->hasIncrblobCur = 1;
   70308 }
   70309 #endif
   70310 
   70311 /*
   70312 ** Set both the "read version" (single byte at byte offset 18) and
   70313 ** "write version" (single byte at byte offset 19) fields in the database
   70314 ** header to iVersion.
   70315 */
   70316 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
   70317   BtShared *pBt = pBtree->pBt;
   70318   int rc;                         /* Return code */
   70319 
   70320   assert( iVersion==1 || iVersion==2 );
   70321 
   70322   /* If setting the version fields to 1, do not automatically open the
   70323   ** WAL connection, even if the version fields are currently set to 2.
   70324   */
   70325   pBt->btsFlags &= ~BTS_NO_WAL;
   70326   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
   70327 
   70328   rc = sqlite3BtreeBeginTrans(pBtree, 0);
   70329   if( rc==SQLITE_OK ){
   70330     u8 *aData = pBt->pPage1->aData;
   70331     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
   70332       rc = sqlite3BtreeBeginTrans(pBtree, 2);
   70333       if( rc==SQLITE_OK ){
   70334         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   70335         if( rc==SQLITE_OK ){
   70336           aData[18] = (u8)iVersion;
   70337           aData[19] = (u8)iVersion;
   70338         }
   70339       }
   70340     }
   70341   }
   70342 
   70343   pBt->btsFlags &= ~BTS_NO_WAL;
   70344   return rc;
   70345 }
   70346 
   70347 /*
   70348 ** Return true if the cursor has a hint specified.  This routine is
   70349 ** only used from within assert() statements
   70350 */
   70351 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
   70352   return (pCsr->hints & mask)!=0;
   70353 }
   70354 
   70355 /*
   70356 ** Return true if the given Btree is read-only.
   70357 */
   70358 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
   70359   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
   70360 }
   70361 
   70362 /*
   70363 ** Return the size of the header added to each page by this module.
   70364 */
   70365 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
   70366 
   70367 #if !defined(SQLITE_OMIT_SHARED_CACHE)
   70368 /*
   70369 ** Return true if the Btree passed as the only argument is sharable.
   70370 */
   70371 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
   70372   return p->sharable;
   70373 }
   70374 
   70375 /*
   70376 ** Return the number of connections to the BtShared object accessed by
   70377 ** the Btree handle passed as the only argument. For private caches
   70378 ** this is always 1. For shared caches it may be 1 or greater.
   70379 */
   70380 SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
   70381   testcase( p->sharable );
   70382   return p->pBt->nRef;
   70383 }
   70384 #endif
   70385 
   70386 /************** End of btree.c ***********************************************/
   70387 /************** Begin file backup.c ******************************************/
   70388 /*
   70389 ** 2009 January 28
   70390 **
   70391 ** The author disclaims copyright to this source code.  In place of
   70392 ** a legal notice, here is a blessing:
   70393 **
   70394 **    May you do good and not evil.
   70395 **    May you find forgiveness for yourself and forgive others.
   70396 **    May you share freely, never taking more than you give.
   70397 **
   70398 *************************************************************************
   70399 ** This file contains the implementation of the sqlite3_backup_XXX()
   70400 ** API functions and the related features.
   70401 */
   70402 /* #include "sqliteInt.h" */
   70403 /* #include "btreeInt.h" */
   70404 
   70405 /*
   70406 ** Structure allocated for each backup operation.
   70407 */
   70408 struct sqlite3_backup {
   70409   sqlite3* pDestDb;        /* Destination database handle */
   70410   Btree *pDest;            /* Destination b-tree file */
   70411   u32 iDestSchema;         /* Original schema cookie in destination */
   70412   int bDestLocked;         /* True once a write-transaction is open on pDest */
   70413 
   70414   Pgno iNext;              /* Page number of the next source page to copy */
   70415   sqlite3* pSrcDb;         /* Source database handle */
   70416   Btree *pSrc;             /* Source b-tree file */
   70417 
   70418   int rc;                  /* Backup process error code */
   70419 
   70420   /* These two variables are set by every call to backup_step(). They are
   70421   ** read by calls to backup_remaining() and backup_pagecount().
   70422   */
   70423   Pgno nRemaining;         /* Number of pages left to copy */
   70424   Pgno nPagecount;         /* Total number of pages to copy */
   70425 
   70426   int isAttached;          /* True once backup has been registered with pager */
   70427   sqlite3_backup *pNext;   /* Next backup associated with source pager */
   70428 };
   70429 
   70430 /*
   70431 ** THREAD SAFETY NOTES:
   70432 **
   70433 **   Once it has been created using backup_init(), a single sqlite3_backup
   70434 **   structure may be accessed via two groups of thread-safe entry points:
   70435 **
   70436 **     * Via the sqlite3_backup_XXX() API function backup_step() and
   70437 **       backup_finish(). Both these functions obtain the source database
   70438 **       handle mutex and the mutex associated with the source BtShared
   70439 **       structure, in that order.
   70440 **
   70441 **     * Via the BackupUpdate() and BackupRestart() functions, which are
   70442 **       invoked by the pager layer to report various state changes in
   70443 **       the page cache associated with the source database. The mutex
   70444 **       associated with the source database BtShared structure will always
   70445 **       be held when either of these functions are invoked.
   70446 **
   70447 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
   70448 **   backup_pagecount() are not thread-safe functions. If they are called
   70449 **   while some other thread is calling backup_step() or backup_finish(),
   70450 **   the values returned may be invalid. There is no way for a call to
   70451 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
   70452 **   or backup_pagecount().
   70453 **
   70454 **   Depending on the SQLite configuration, the database handles and/or
   70455 **   the Btree objects may have their own mutexes that require locking.
   70456 **   Non-sharable Btrees (in-memory databases for example), do not have
   70457 **   associated mutexes.
   70458 */
   70459 
   70460 /*
   70461 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
   70462 ** in connection handle pDb. If such a database cannot be found, return
   70463 ** a NULL pointer and write an error message to pErrorDb.
   70464 **
   70465 ** If the "temp" database is requested, it may need to be opened by this
   70466 ** function. If an error occurs while doing so, return 0 and write an
   70467 ** error message to pErrorDb.
   70468 */
   70469 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   70470   int i = sqlite3FindDbName(pDb, zDb);
   70471 
   70472   if( i==1 ){
   70473     Parse sParse;
   70474     int rc = 0;
   70475     memset(&sParse, 0, sizeof(sParse));
   70476     sParse.db = pDb;
   70477     if( sqlite3OpenTempDatabase(&sParse) ){
   70478       sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
   70479       rc = SQLITE_ERROR;
   70480     }
   70481     sqlite3DbFree(pErrorDb, sParse.zErrMsg);
   70482     sqlite3ParserReset(&sParse);
   70483     if( rc ){
   70484       return 0;
   70485     }
   70486   }
   70487 
   70488   if( i<0 ){
   70489     sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
   70490     return 0;
   70491   }
   70492 
   70493   return pDb->aDb[i].pBt;
   70494 }
   70495 
   70496 /*
   70497 ** Attempt to set the page size of the destination to match the page size
   70498 ** of the source.
   70499 */
   70500 static int setDestPgsz(sqlite3_backup *p){
   70501   int rc;
   70502   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
   70503   return rc;
   70504 }
   70505 
   70506 /*
   70507 ** Check that there is no open read-transaction on the b-tree passed as the
   70508 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
   70509 ** is an open read-transaction, return SQLITE_ERROR and leave an error
   70510 ** message in database handle db.
   70511 */
   70512 static int checkReadTransaction(sqlite3 *db, Btree *p){
   70513   if( sqlite3BtreeIsInReadTrans(p) ){
   70514     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
   70515     return SQLITE_ERROR;
   70516   }
   70517   return SQLITE_OK;
   70518 }
   70519 
   70520 /*
   70521 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
   70522 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
   70523 ** a pointer to the new sqlite3_backup object.
   70524 **
   70525 ** If an error occurs, NULL is returned and an error code and error message
   70526 ** stored in database handle pDestDb.
   70527 */
   70528 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   70529   sqlite3* pDestDb,                     /* Database to write to */
   70530   const char *zDestDb,                  /* Name of database within pDestDb */
   70531   sqlite3* pSrcDb,                      /* Database connection to read from */
   70532   const char *zSrcDb                    /* Name of database within pSrcDb */
   70533 ){
   70534   sqlite3_backup *p;                    /* Value to return */
   70535 
   70536 #ifdef SQLITE_ENABLE_API_ARMOR
   70537   if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
   70538     (void)SQLITE_MISUSE_BKPT;
   70539     return 0;
   70540   }
   70541 #endif
   70542 
   70543   /* Lock the source database handle. The destination database
   70544   ** handle is not locked in this routine, but it is locked in
   70545   ** sqlite3_backup_step(). The user is required to ensure that no
   70546   ** other thread accesses the destination handle for the duration
   70547   ** of the backup operation.  Any attempt to use the destination
   70548   ** database connection while a backup is in progress may cause
   70549   ** a malfunction or a deadlock.
   70550   */
   70551   sqlite3_mutex_enter(pSrcDb->mutex);
   70552   sqlite3_mutex_enter(pDestDb->mutex);
   70553 
   70554   if( pSrcDb==pDestDb ){
   70555     sqlite3ErrorWithMsg(
   70556         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
   70557     );
   70558     p = 0;
   70559   }else {
   70560     /* Allocate space for a new sqlite3_backup object...
   70561     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   70562     ** call to sqlite3_backup_init() and is destroyed by a call to
   70563     ** sqlite3_backup_finish(). */
   70564     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
   70565     if( !p ){
   70566       sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
   70567     }
   70568   }
   70569 
   70570   /* If the allocation succeeded, populate the new object. */
   70571   if( p ){
   70572     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
   70573     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   70574     p->pDestDb = pDestDb;
   70575     p->pSrcDb = pSrcDb;
   70576     p->iNext = 1;
   70577     p->isAttached = 0;
   70578 
   70579     if( 0==p->pSrc || 0==p->pDest
   70580      || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
   70581      ){
   70582       /* One (or both) of the named databases did not exist or an OOM
   70583       ** error was hit. Or there is a transaction open on the destination
   70584       ** database. The error has already been written into the pDestDb
   70585       ** handle. All that is left to do here is free the sqlite3_backup
   70586       ** structure.  */
   70587       sqlite3_free(p);
   70588       p = 0;
   70589     }
   70590   }
   70591   if( p ){
   70592     p->pSrc->nBackup++;
   70593   }
   70594 
   70595   sqlite3_mutex_leave(pDestDb->mutex);
   70596   sqlite3_mutex_leave(pSrcDb->mutex);
   70597   return p;
   70598 }
   70599 
   70600 /*
   70601 ** Argument rc is an SQLite error code. Return true if this error is
   70602 ** considered fatal if encountered during a backup operation. All errors
   70603 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
   70604 */
   70605 static int isFatalError(int rc){
   70606   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
   70607 }
   70608 
   70609 /*
   70610 ** Parameter zSrcData points to a buffer containing the data for
   70611 ** page iSrcPg from the source database. Copy this data into the
   70612 ** destination database.
   70613 */
   70614 static int backupOnePage(
   70615   sqlite3_backup *p,              /* Backup handle */
   70616   Pgno iSrcPg,                    /* Source database page to backup */
   70617   const u8 *zSrcData,             /* Source database page data */
   70618   int bUpdate                     /* True for an update, false otherwise */
   70619 ){
   70620   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
   70621   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
   70622   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   70623   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   70624   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
   70625 #ifdef SQLITE_HAS_CODEC
   70626   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
   70627   ** guaranteed that the shared-mutex is held by this thread, handle
   70628   ** p->pSrc may not actually be the owner.  */
   70629   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
   70630   int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
   70631 #endif
   70632   int rc = SQLITE_OK;
   70633   i64 iOff;
   70634 
   70635   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
   70636   assert( p->bDestLocked );
   70637   assert( !isFatalError(p->rc) );
   70638   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
   70639   assert( zSrcData );
   70640 
   70641   /* Catch the case where the destination is an in-memory database and the
   70642   ** page sizes of the source and destination differ.
   70643   */
   70644   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
   70645     rc = SQLITE_READONLY;
   70646   }
   70647 
   70648 #ifdef SQLITE_HAS_CODEC
   70649   /* Backup is not possible if the page size of the destination is changing
   70650   ** and a codec is in use.
   70651   */
   70652   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
   70653     rc = SQLITE_READONLY;
   70654   }
   70655 
   70656   /* Backup is not possible if the number of bytes of reserve space differ
   70657   ** between source and destination.  If there is a difference, try to
   70658   ** fix the destination to agree with the source.  If that is not possible,
   70659   ** then the backup cannot proceed.
   70660   */
   70661   if( nSrcReserve!=nDestReserve ){
   70662     u32 newPgsz = nSrcPgsz;
   70663     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
   70664     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
   70665   }
   70666 #endif
   70667 
   70668   /* This loop runs once for each destination page spanned by the source
   70669   ** page. For each iteration, variable iOff is set to the byte offset
   70670   ** of the destination page.
   70671   */
   70672   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
   70673     DbPage *pDestPg = 0;
   70674     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
   70675     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
   70676     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
   70677      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
   70678     ){
   70679       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
   70680       u8 *zDestData = sqlite3PagerGetData(pDestPg);
   70681       u8 *zOut = &zDestData[iOff%nDestPgsz];
   70682 
   70683       /* Copy the data from the source page into the destination page.
   70684       ** Then clear the Btree layer MemPage.isInit flag. Both this module
   70685       ** and the pager code use this trick (clearing the first byte
   70686       ** of the page 'extra' space to invalidate the Btree layers
   70687       ** cached parse of the page). MemPage.isInit is marked
   70688       ** "MUST BE FIRST" for this purpose.
   70689       */
   70690       memcpy(zOut, zIn, nCopy);
   70691       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
   70692       if( iOff==0 && bUpdate==0 ){
   70693         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
   70694       }
   70695     }
   70696     sqlite3PagerUnref(pDestPg);
   70697   }
   70698 
   70699   return rc;
   70700 }
   70701 
   70702 /*
   70703 ** If pFile is currently larger than iSize bytes, then truncate it to
   70704 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
   70705 ** this function is a no-op.
   70706 **
   70707 ** Return SQLITE_OK if everything is successful, or an SQLite error
   70708 ** code if an error occurs.
   70709 */
   70710 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
   70711   i64 iCurrent;
   70712   int rc = sqlite3OsFileSize(pFile, &iCurrent);
   70713   if( rc==SQLITE_OK && iCurrent>iSize ){
   70714     rc = sqlite3OsTruncate(pFile, iSize);
   70715   }
   70716   return rc;
   70717 }
   70718 
   70719 /*
   70720 ** Register this backup object with the associated source pager for
   70721 ** callbacks when pages are changed or the cache invalidated.
   70722 */
   70723 static void attachBackupObject(sqlite3_backup *p){
   70724   sqlite3_backup **pp;
   70725   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
   70726   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   70727   p->pNext = *pp;
   70728   *pp = p;
   70729   p->isAttached = 1;
   70730 }
   70731 
   70732 /*
   70733 ** Copy nPage pages from the source b-tree to the destination.
   70734 */
   70735 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
   70736   int rc;
   70737   int destMode;       /* Destination journal mode */
   70738   int pgszSrc = 0;    /* Source page size */
   70739   int pgszDest = 0;   /* Destination page size */
   70740 
   70741 #ifdef SQLITE_ENABLE_API_ARMOR
   70742   if( p==0 ) return SQLITE_MISUSE_BKPT;
   70743 #endif
   70744   sqlite3_mutex_enter(p->pSrcDb->mutex);
   70745   sqlite3BtreeEnter(p->pSrc);
   70746   if( p->pDestDb ){
   70747     sqlite3_mutex_enter(p->pDestDb->mutex);
   70748   }
   70749 
   70750   rc = p->rc;
   70751   if( !isFatalError(rc) ){
   70752     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
   70753     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
   70754     int ii;                            /* Iterator variable */
   70755     int nSrcPage = -1;                 /* Size of source db in pages */
   70756     int bCloseTrans = 0;               /* True if src db requires unlocking */
   70757 
   70758     /* If the source pager is currently in a write-transaction, return
   70759     ** SQLITE_BUSY immediately.
   70760     */
   70761     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   70762       rc = SQLITE_BUSY;
   70763     }else{
   70764       rc = SQLITE_OK;
   70765     }
   70766 
   70767     /* If there is no open read-transaction on the source database, open
   70768     ** one now. If a transaction is opened here, then it will be closed
   70769     ** before this function exits.
   70770     */
   70771     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   70772       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   70773       bCloseTrans = 1;
   70774     }
   70775 
   70776     /* If the destination database has not yet been locked (i.e. if this
   70777     ** is the first call to backup_step() for the current backup operation),
   70778     ** try to set its page size to the same as the source database. This
   70779     ** is especially important on ZipVFS systems, as in that case it is
   70780     ** not possible to create a database file that uses one page size by
   70781     ** writing to it with another.  */
   70782     if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
   70783       rc = SQLITE_NOMEM;
   70784     }
   70785 
   70786     /* Lock the destination database, if it is not locked already. */
   70787     if( SQLITE_OK==rc && p->bDestLocked==0
   70788      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
   70789     ){
   70790       p->bDestLocked = 1;
   70791       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   70792     }
   70793 
   70794     /* Do not allow backup if the destination database is in WAL mode
   70795     ** and the page sizes are different between source and destination */
   70796     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
   70797     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
   70798     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
   70799     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
   70800       rc = SQLITE_READONLY;
   70801     }
   70802 
   70803     /* Now that there is a read-lock on the source database, query the
   70804     ** source pager for the number of pages in the database.
   70805     */
   70806     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
   70807     assert( nSrcPage>=0 );
   70808     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
   70809       const Pgno iSrcPg = p->iNext;                 /* Source page number */
   70810       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
   70811         DbPage *pSrcPg;                             /* Source page object */
   70812         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
   70813         if( rc==SQLITE_OK ){
   70814           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
   70815           sqlite3PagerUnref(pSrcPg);
   70816         }
   70817       }
   70818       p->iNext++;
   70819     }
   70820     if( rc==SQLITE_OK ){
   70821       p->nPagecount = nSrcPage;
   70822       p->nRemaining = nSrcPage+1-p->iNext;
   70823       if( p->iNext>(Pgno)nSrcPage ){
   70824         rc = SQLITE_DONE;
   70825       }else if( !p->isAttached ){
   70826         attachBackupObject(p);
   70827       }
   70828     }
   70829 
   70830     /* Update the schema version field in the destination database. This
   70831     ** is to make sure that the schema-version really does change in
   70832     ** the case where the source and destination databases have the
   70833     ** same schema version.
   70834     */
   70835     if( rc==SQLITE_DONE ){
   70836       if( nSrcPage==0 ){
   70837         rc = sqlite3BtreeNewDb(p->pDest);
   70838         nSrcPage = 1;
   70839       }
   70840       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   70841         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
   70842       }
   70843       if( rc==SQLITE_OK ){
   70844         if( p->pDestDb ){
   70845           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
   70846         }
   70847         if( destMode==PAGER_JOURNALMODE_WAL ){
   70848           rc = sqlite3BtreeSetVersion(p->pDest, 2);
   70849         }
   70850       }
   70851       if( rc==SQLITE_OK ){
   70852         int nDestTruncate;
   70853         /* Set nDestTruncate to the final number of pages in the destination
   70854         ** database. The complication here is that the destination page
   70855         ** size may be different to the source page size.
   70856         **
   70857         ** If the source page size is smaller than the destination page size,
   70858         ** round up. In this case the call to sqlite3OsTruncate() below will
   70859         ** fix the size of the file. However it is important to call
   70860         ** sqlite3PagerTruncateImage() here so that any pages in the
   70861         ** destination file that lie beyond the nDestTruncate page mark are
   70862         ** journalled by PagerCommitPhaseOne() before they are destroyed
   70863         ** by the file truncation.
   70864         */
   70865         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
   70866         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
   70867         if( pgszSrc<pgszDest ){
   70868           int ratio = pgszDest/pgszSrc;
   70869           nDestTruncate = (nSrcPage+ratio-1)/ratio;
   70870           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
   70871             nDestTruncate--;
   70872           }
   70873         }else{
   70874           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
   70875         }
   70876         assert( nDestTruncate>0 );
   70877 
   70878         if( pgszSrc<pgszDest ){
   70879           /* If the source page-size is smaller than the destination page-size,
   70880           ** two extra things may need to happen:
   70881           **
   70882           **   * The destination may need to be truncated, and
   70883           **
   70884           **   * Data stored on the pages immediately following the
   70885           **     pending-byte page in the source database may need to be
   70886           **     copied into the destination database.
   70887           */
   70888           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
   70889           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
   70890           Pgno iPg;
   70891           int nDstPage;
   70892           i64 iOff;
   70893           i64 iEnd;
   70894 
   70895           assert( pFile );
   70896           assert( nDestTruncate==0
   70897               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
   70898                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
   70899              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
   70900           ));
   70901 
   70902           /* This block ensures that all data required to recreate the original
   70903           ** database has been stored in the journal for pDestPager and the
   70904           ** journal synced to disk. So at this point we may safely modify
   70905           ** the database file in any way, knowing that if a power failure
   70906           ** occurs, the original database will be reconstructed from the
   70907           ** journal file.  */
   70908           sqlite3PagerPagecount(pDestPager, &nDstPage);
   70909           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
   70910             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
   70911               DbPage *pPg;
   70912               rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
   70913               if( rc==SQLITE_OK ){
   70914                 rc = sqlite3PagerWrite(pPg);
   70915                 sqlite3PagerUnref(pPg);
   70916               }
   70917             }
   70918           }
   70919           if( rc==SQLITE_OK ){
   70920             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
   70921           }
   70922 
   70923           /* Write the extra pages and truncate the database file as required */
   70924           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
   70925           for(
   70926             iOff=PENDING_BYTE+pgszSrc;
   70927             rc==SQLITE_OK && iOff<iEnd;
   70928             iOff+=pgszSrc
   70929           ){
   70930             PgHdr *pSrcPg = 0;
   70931             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
   70932             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
   70933             if( rc==SQLITE_OK ){
   70934               u8 *zData = sqlite3PagerGetData(pSrcPg);
   70935               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
   70936             }
   70937             sqlite3PagerUnref(pSrcPg);
   70938           }
   70939           if( rc==SQLITE_OK ){
   70940             rc = backupTruncateFile(pFile, iSize);
   70941           }
   70942 
   70943           /* Sync the database file to disk. */
   70944           if( rc==SQLITE_OK ){
   70945             rc = sqlite3PagerSync(pDestPager, 0);
   70946           }
   70947         }else{
   70948           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
   70949           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
   70950         }
   70951 
   70952         /* Finish committing the transaction to the destination database. */
   70953         if( SQLITE_OK==rc
   70954          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
   70955         ){
   70956           rc = SQLITE_DONE;
   70957         }
   70958       }
   70959     }
   70960 
   70961     /* If bCloseTrans is true, then this function opened a read transaction
   70962     ** on the source database. Close the read transaction here. There is
   70963     ** no need to check the return values of the btree methods here, as
   70964     ** "committing" a read-only transaction cannot fail.
   70965     */
   70966     if( bCloseTrans ){
   70967       TESTONLY( int rc2 );
   70968       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
   70969       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
   70970       assert( rc2==SQLITE_OK );
   70971     }
   70972 
   70973     if( rc==SQLITE_IOERR_NOMEM ){
   70974       rc = SQLITE_NOMEM_BKPT;
   70975     }
   70976     p->rc = rc;
   70977   }
   70978   if( p->pDestDb ){
   70979     sqlite3_mutex_leave(p->pDestDb->mutex);
   70980   }
   70981   sqlite3BtreeLeave(p->pSrc);
   70982   sqlite3_mutex_leave(p->pSrcDb->mutex);
   70983   return rc;
   70984 }
   70985 
   70986 /*
   70987 ** Release all resources associated with an sqlite3_backup* handle.
   70988 */
   70989 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
   70990   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
   70991   sqlite3 *pSrcDb;                     /* Source database connection */
   70992   int rc;                              /* Value to return */
   70993 
   70994   /* Enter the mutexes */
   70995   if( p==0 ) return SQLITE_OK;
   70996   pSrcDb = p->pSrcDb;
   70997   sqlite3_mutex_enter(pSrcDb->mutex);
   70998   sqlite3BtreeEnter(p->pSrc);
   70999   if( p->pDestDb ){
   71000     sqlite3_mutex_enter(p->pDestDb->mutex);
   71001   }
   71002 
   71003   /* Detach this backup from the source pager. */
   71004   if( p->pDestDb ){
   71005     p->pSrc->nBackup--;
   71006   }
   71007   if( p->isAttached ){
   71008     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   71009     while( *pp!=p ){
   71010       pp = &(*pp)->pNext;
   71011     }
   71012     *pp = p->pNext;
   71013   }
   71014 
   71015   /* If a transaction is still open on the Btree, roll it back. */
   71016   sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
   71017 
   71018   /* Set the error code of the destination database handle. */
   71019   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
   71020   if( p->pDestDb ){
   71021     sqlite3Error(p->pDestDb, rc);
   71022 
   71023     /* Exit the mutexes and free the backup context structure. */
   71024     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
   71025   }
   71026   sqlite3BtreeLeave(p->pSrc);
   71027   if( p->pDestDb ){
   71028     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   71029     ** call to sqlite3_backup_init() and is destroyed by a call to
   71030     ** sqlite3_backup_finish(). */
   71031     sqlite3_free(p);
   71032   }
   71033   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
   71034   return rc;
   71035 }
   71036 
   71037 /*
   71038 ** Return the number of pages still to be backed up as of the most recent
   71039 ** call to sqlite3_backup_step().
   71040 */
   71041 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
   71042 #ifdef SQLITE_ENABLE_API_ARMOR
   71043   if( p==0 ){
   71044     (void)SQLITE_MISUSE_BKPT;
   71045     return 0;
   71046   }
   71047 #endif
   71048   return p->nRemaining;
   71049 }
   71050 
   71051 /*
   71052 ** Return the total number of pages in the source database as of the most
   71053 ** recent call to sqlite3_backup_step().
   71054 */
   71055 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
   71056 #ifdef SQLITE_ENABLE_API_ARMOR
   71057   if( p==0 ){
   71058     (void)SQLITE_MISUSE_BKPT;
   71059     return 0;
   71060   }
   71061 #endif
   71062   return p->nPagecount;
   71063 }
   71064 
   71065 /*
   71066 ** This function is called after the contents of page iPage of the
   71067 ** source database have been modified. If page iPage has already been
   71068 ** copied into the destination database, then the data written to the
   71069 ** destination is now invalidated. The destination copy of iPage needs
   71070 ** to be updated with the new data before the backup operation is
   71071 ** complete.
   71072 **
   71073 ** It is assumed that the mutex associated with the BtShared object
   71074 ** corresponding to the source database is held when this function is
   71075 ** called.
   71076 */
   71077 static SQLITE_NOINLINE void backupUpdate(
   71078   sqlite3_backup *p,
   71079   Pgno iPage,
   71080   const u8 *aData
   71081 ){
   71082   assert( p!=0 );
   71083   do{
   71084     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   71085     if( !isFatalError(p->rc) && iPage<p->iNext ){
   71086       /* The backup process p has already copied page iPage. But now it
   71087       ** has been modified by a transaction on the source pager. Copy
   71088       ** the new data into the backup.
   71089       */
   71090       int rc;
   71091       assert( p->pDestDb );
   71092       sqlite3_mutex_enter(p->pDestDb->mutex);
   71093       rc = backupOnePage(p, iPage, aData, 1);
   71094       sqlite3_mutex_leave(p->pDestDb->mutex);
   71095       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
   71096       if( rc!=SQLITE_OK ){
   71097         p->rc = rc;
   71098       }
   71099     }
   71100   }while( (p = p->pNext)!=0 );
   71101 }
   71102 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
   71103   if( pBackup ) backupUpdate(pBackup, iPage, aData);
   71104 }
   71105 
   71106 /*
   71107 ** Restart the backup process. This is called when the pager layer
   71108 ** detects that the database has been modified by an external database
   71109 ** connection. In this case there is no way of knowing which of the
   71110 ** pages that have been copied into the destination database are still
   71111 ** valid and which are not, so the entire process needs to be restarted.
   71112 **
   71113 ** It is assumed that the mutex associated with the BtShared object
   71114 ** corresponding to the source database is held when this function is
   71115 ** called.
   71116 */
   71117 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
   71118   sqlite3_backup *p;                   /* Iterator variable */
   71119   for(p=pBackup; p; p=p->pNext){
   71120     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   71121     p->iNext = 1;
   71122   }
   71123 }
   71124 
   71125 #ifndef SQLITE_OMIT_VACUUM
   71126 /*
   71127 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
   71128 ** must be active for both files.
   71129 **
   71130 ** The size of file pTo may be reduced by this operation. If anything
   71131 ** goes wrong, the transaction on pTo is rolled back. If successful, the
   71132 ** transaction is committed before returning.
   71133 */
   71134 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   71135   int rc;
   71136   sqlite3_file *pFd;              /* File descriptor for database pTo */
   71137   sqlite3_backup b;
   71138   sqlite3BtreeEnter(pTo);
   71139   sqlite3BtreeEnter(pFrom);
   71140 
   71141   assert( sqlite3BtreeIsInTrans(pTo) );
   71142   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
   71143   if( pFd->pMethods ){
   71144     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
   71145     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
   71146     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   71147     if( rc ) goto copy_finished;
   71148   }
   71149 
   71150   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   71151   ** to 0. This is used by the implementations of sqlite3_backup_step()
   71152   ** and sqlite3_backup_finish() to detect that they are being called
   71153   ** from this function, not directly by the user.
   71154   */
   71155   memset(&b, 0, sizeof(b));
   71156   b.pSrcDb = pFrom->db;
   71157   b.pSrc = pFrom;
   71158   b.pDest = pTo;
   71159   b.iNext = 1;
   71160 
   71161 #ifdef SQLITE_HAS_CODEC
   71162   sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
   71163 #endif
   71164 
   71165   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   71166   ** file. By passing this as the number of pages to copy to
   71167   ** sqlite3_backup_step(), we can guarantee that the copy finishes
   71168   ** within a single call (unless an error occurs). The assert() statement
   71169   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   71170   ** or an error code.  */
   71171   sqlite3_backup_step(&b, 0x7FFFFFFF);
   71172   assert( b.rc!=SQLITE_OK );
   71173 
   71174   rc = sqlite3_backup_finish(&b);
   71175   if( rc==SQLITE_OK ){
   71176     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
   71177   }else{
   71178     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
   71179   }
   71180 
   71181   assert( sqlite3BtreeIsInTrans(pTo)==0 );
   71182 copy_finished:
   71183   sqlite3BtreeLeave(pFrom);
   71184   sqlite3BtreeLeave(pTo);
   71185   return rc;
   71186 }
   71187 #endif /* SQLITE_OMIT_VACUUM */
   71188 
   71189 /************** End of backup.c **********************************************/
   71190 /************** Begin file vdbemem.c *****************************************/
   71191 /*
   71192 ** 2004 May 26
   71193 **
   71194 ** The author disclaims copyright to this source code.  In place of
   71195 ** a legal notice, here is a blessing:
   71196 **
   71197 **    May you do good and not evil.
   71198 **    May you find forgiveness for yourself and forgive others.
   71199 **    May you share freely, never taking more than you give.
   71200 **
   71201 *************************************************************************
   71202 **
   71203 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
   71204 ** stores a single value in the VDBE.  Mem is an opaque structure visible
   71205 ** only within the VDBE.  Interface routines refer to a Mem using the
   71206 ** name sqlite_value
   71207 */
   71208 /* #include "sqliteInt.h" */
   71209 /* #include "vdbeInt.h" */
   71210 
   71211 #ifdef SQLITE_DEBUG
   71212 /*
   71213 ** Check invariants on a Mem object.
   71214 **
   71215 ** This routine is intended for use inside of assert() statements, like
   71216 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
   71217 */
   71218 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
   71219   /* If MEM_Dyn is set then Mem.xDel!=0.
   71220   ** Mem.xDel might not be initialized if MEM_Dyn is clear.
   71221   */
   71222   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
   71223 
   71224   /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
   71225   ** ensure that if Mem.szMalloc>0 then it is safe to do
   71226   ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
   71227   ** That saves a few cycles in inner loops. */
   71228   assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
   71229 
   71230   /* Cannot be both MEM_Int and MEM_Real at the same time */
   71231   assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
   71232 
   71233   if( p->flags & MEM_Null ){
   71234     /* Cannot be both MEM_Null and some other type */
   71235     assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob
   71236                          |MEM_RowSet|MEM_Frame|MEM_Agg))==0 );
   71237 
   71238     /* If MEM_Null is set, then either the value is a pure NULL (the usual
   71239     ** case) or it is a pointer set using sqlite3_bind_pointer() or
   71240     ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
   71241     ** set.
   71242     */
   71243     if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
   71244       /* This is a pointer type.  There may be a flag to indicate what to
   71245       ** do with the pointer. */
   71246       assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
   71247               ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
   71248               ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
   71249 
   71250       /* No other bits set */
   71251       assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
   71252                            |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
   71253     }else{
   71254       /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
   71255       ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
   71256     }
   71257   }else{
   71258     /* The MEM_Cleared bit is only allowed on NULLs */
   71259     assert( (p->flags & MEM_Cleared)==0 );
   71260   }
   71261 
   71262   /* The szMalloc field holds the correct memory allocation size */
   71263   assert( p->szMalloc==0
   71264        || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
   71265 
   71266   /* If p holds a string or blob, the Mem.z must point to exactly
   71267   ** one of the following:
   71268   **
   71269   **   (1) Memory in Mem.zMalloc and managed by the Mem object
   71270   **   (2) Memory to be freed using Mem.xDel
   71271   **   (3) An ephemeral string or blob
   71272   **   (4) A static string or blob
   71273   */
   71274   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
   71275     assert(
   71276       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
   71277       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
   71278       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
   71279       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
   71280     );
   71281   }
   71282   return 1;
   71283 }
   71284 #endif
   71285 
   71286 
   71287 /*
   71288 ** If pMem is an object with a valid string representation, this routine
   71289 ** ensures the internal encoding for the string representation is
   71290 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
   71291 **
   71292 ** If pMem is not a string object, or the encoding of the string
   71293 ** representation is already stored using the requested encoding, then this
   71294 ** routine is a no-op.
   71295 **
   71296 ** SQLITE_OK is returned if the conversion is successful (or not required).
   71297 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
   71298 ** between formats.
   71299 */
   71300 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
   71301 #ifndef SQLITE_OMIT_UTF16
   71302   int rc;
   71303 #endif
   71304   assert( (pMem->flags&MEM_RowSet)==0 );
   71305   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
   71306            || desiredEnc==SQLITE_UTF16BE );
   71307   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
   71308     return SQLITE_OK;
   71309   }
   71310   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71311 #ifdef SQLITE_OMIT_UTF16
   71312   return SQLITE_ERROR;
   71313 #else
   71314 
   71315   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
   71316   ** then the encoding of the value may not have changed.
   71317   */
   71318   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
   71319   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
   71320   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
   71321   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
   71322   return rc;
   71323 #endif
   71324 }
   71325 
   71326 /*
   71327 ** Make sure pMem->z points to a writable allocation of at least
   71328 ** min(n,32) bytes.
   71329 **
   71330 ** If the bPreserve argument is true, then copy of the content of
   71331 ** pMem->z into the new allocation.  pMem must be either a string or
   71332 ** blob if bPreserve is true.  If bPreserve is false, any prior content
   71333 ** in pMem->z is discarded.
   71334 */
   71335 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
   71336   assert( sqlite3VdbeCheckMemInvariants(pMem) );
   71337   assert( (pMem->flags&MEM_RowSet)==0 );
   71338   testcase( pMem->db==0 );
   71339 
   71340   /* If the bPreserve flag is set to true, then the memory cell must already
   71341   ** contain a valid string or blob value.  */
   71342   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
   71343   testcase( bPreserve && pMem->z==0 );
   71344 
   71345   assert( pMem->szMalloc==0
   71346        || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
   71347   if( n<32 ) n = 32;
   71348   if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
   71349     pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
   71350     bPreserve = 0;
   71351   }else{
   71352     if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
   71353     pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
   71354   }
   71355   if( pMem->zMalloc==0 ){
   71356     sqlite3VdbeMemSetNull(pMem);
   71357     pMem->z = 0;
   71358     pMem->szMalloc = 0;
   71359     return SQLITE_NOMEM_BKPT;
   71360   }else{
   71361     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
   71362   }
   71363 
   71364   if( bPreserve && pMem->z ){
   71365     assert( pMem->z!=pMem->zMalloc );
   71366     memcpy(pMem->zMalloc, pMem->z, pMem->n);
   71367   }
   71368   if( (pMem->flags&MEM_Dyn)!=0 ){
   71369     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
   71370     pMem->xDel((void *)(pMem->z));
   71371   }
   71372 
   71373   pMem->z = pMem->zMalloc;
   71374   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
   71375   return SQLITE_OK;
   71376 }
   71377 
   71378 /*
   71379 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
   71380 ** If pMem->zMalloc already meets or exceeds the requested size, this
   71381 ** routine is a no-op.
   71382 **
   71383 ** Any prior string or blob content in the pMem object may be discarded.
   71384 ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
   71385 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
   71386 ** values are preserved.
   71387 **
   71388 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
   71389 ** if unable to complete the resizing.
   71390 */
   71391 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
   71392   assert( szNew>0 );
   71393   assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
   71394   if( pMem->szMalloc<szNew ){
   71395     return sqlite3VdbeMemGrow(pMem, szNew, 0);
   71396   }
   71397   assert( (pMem->flags & MEM_Dyn)==0 );
   71398   pMem->z = pMem->zMalloc;
   71399   pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
   71400   return SQLITE_OK;
   71401 }
   71402 
   71403 /*
   71404 ** It is already known that pMem contains an unterminated string.
   71405 ** Add the zero terminator.
   71406 */
   71407 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
   71408   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
   71409     return SQLITE_NOMEM_BKPT;
   71410   }
   71411   pMem->z[pMem->n] = 0;
   71412   pMem->z[pMem->n+1] = 0;
   71413   pMem->flags |= MEM_Term;
   71414   return SQLITE_OK;
   71415 }
   71416 
   71417 /*
   71418 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
   71419 ** MEM.zMalloc, where it can be safely written.
   71420 **
   71421 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
   71422 */
   71423 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
   71424   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71425   assert( (pMem->flags&MEM_RowSet)==0 );
   71426   if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
   71427     if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
   71428     if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
   71429       int rc = vdbeMemAddTerminator(pMem);
   71430       if( rc ) return rc;
   71431     }
   71432   }
   71433   pMem->flags &= ~MEM_Ephem;
   71434 #ifdef SQLITE_DEBUG
   71435   pMem->pScopyFrom = 0;
   71436 #endif
   71437 
   71438   return SQLITE_OK;
   71439 }
   71440 
   71441 /*
   71442 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
   71443 ** blob stored in dynamically allocated space.
   71444 */
   71445 #ifndef SQLITE_OMIT_INCRBLOB
   71446 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   71447   int nByte;
   71448   assert( pMem->flags & MEM_Zero );
   71449   assert( pMem->flags&MEM_Blob );
   71450   assert( (pMem->flags&MEM_RowSet)==0 );
   71451   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71452 
   71453   /* Set nByte to the number of bytes required to store the expanded blob. */
   71454   nByte = pMem->n + pMem->u.nZero;
   71455   if( nByte<=0 ){
   71456     nByte = 1;
   71457   }
   71458   if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
   71459     return SQLITE_NOMEM_BKPT;
   71460   }
   71461 
   71462   memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   71463   pMem->n += pMem->u.nZero;
   71464   pMem->flags &= ~(MEM_Zero|MEM_Term);
   71465   return SQLITE_OK;
   71466 }
   71467 #endif
   71468 
   71469 /*
   71470 ** Make sure the given Mem is \u0000 terminated.
   71471 */
   71472 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
   71473   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71474   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
   71475   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
   71476   if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
   71477     return SQLITE_OK;   /* Nothing to do */
   71478   }else{
   71479     return vdbeMemAddTerminator(pMem);
   71480   }
   71481 }
   71482 
   71483 /*
   71484 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
   71485 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
   71486 ** is a no-op.
   71487 **
   71488 ** Existing representations MEM_Int and MEM_Real are invalidated if
   71489 ** bForce is true but are retained if bForce is false.
   71490 **
   71491 ** A MEM_Null value will never be passed to this function. This function is
   71492 ** used for converting values to text for returning to the user (i.e. via
   71493 ** sqlite3_value_text()), or for ensuring that values to be used as btree
   71494 ** keys are strings. In the former case a NULL pointer is returned the
   71495 ** user and the latter is an internal programming error.
   71496 */
   71497 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
   71498   int fg = pMem->flags;
   71499   const int nByte = 32;
   71500 
   71501   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71502   assert( !(fg&MEM_Zero) );
   71503   assert( !(fg&(MEM_Str|MEM_Blob)) );
   71504   assert( fg&(MEM_Int|MEM_Real) );
   71505   assert( (pMem->flags&MEM_RowSet)==0 );
   71506   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   71507 
   71508 
   71509   if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
   71510     pMem->enc = 0;
   71511     return SQLITE_NOMEM_BKPT;
   71512   }
   71513 
   71514   /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
   71515   ** string representation of the value. Then, if the required encoding
   71516   ** is UTF-16le or UTF-16be do a translation.
   71517   **
   71518   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
   71519   */
   71520   if( fg & MEM_Int ){
   71521     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
   71522   }else{
   71523     assert( fg & MEM_Real );
   71524     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
   71525   }
   71526   pMem->n = sqlite3Strlen30(pMem->z);
   71527   pMem->enc = SQLITE_UTF8;
   71528   pMem->flags |= MEM_Str|MEM_Term;
   71529   if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
   71530   sqlite3VdbeChangeEncoding(pMem, enc);
   71531   return SQLITE_OK;
   71532 }
   71533 
   71534 /*
   71535 ** Memory cell pMem contains the context of an aggregate function.
   71536 ** This routine calls the finalize method for that function.  The
   71537 ** result of the aggregate is stored back into pMem.
   71538 **
   71539 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
   71540 ** otherwise.
   71541 */
   71542 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   71543   sqlite3_context ctx;
   71544   Mem t;
   71545   assert( pFunc!=0 );
   71546   assert( pFunc->xFinalize!=0 );
   71547   assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   71548   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71549   memset(&ctx, 0, sizeof(ctx));
   71550   memset(&t, 0, sizeof(t));
   71551   t.flags = MEM_Null;
   71552   t.db = pMem->db;
   71553   ctx.pOut = &t;
   71554   ctx.pMem = pMem;
   71555   ctx.pFunc = pFunc;
   71556   pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
   71557   assert( (pMem->flags & MEM_Dyn)==0 );
   71558   if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
   71559   memcpy(pMem, &t, sizeof(t));
   71560   return ctx.isError;
   71561 }
   71562 
   71563 /*
   71564 ** If the memory cell contains a value that must be freed by
   71565 ** invoking the external callback in Mem.xDel, then this routine
   71566 ** will free that value.  It also sets Mem.flags to MEM_Null.
   71567 **
   71568 ** This is a helper routine for sqlite3VdbeMemSetNull() and
   71569 ** for sqlite3VdbeMemRelease().  Use those other routines as the
   71570 ** entry point for releasing Mem resources.
   71571 */
   71572 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
   71573   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   71574   assert( VdbeMemDynamic(p) );
   71575   if( p->flags&MEM_Agg ){
   71576     sqlite3VdbeMemFinalize(p, p->u.pDef);
   71577     assert( (p->flags & MEM_Agg)==0 );
   71578     testcase( p->flags & MEM_Dyn );
   71579   }
   71580   if( p->flags&MEM_Dyn ){
   71581     assert( (p->flags&MEM_RowSet)==0 );
   71582     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
   71583     p->xDel((void *)p->z);
   71584   }else if( p->flags&MEM_RowSet ){
   71585     sqlite3RowSetClear(p->u.pRowSet);
   71586   }else if( p->flags&MEM_Frame ){
   71587     VdbeFrame *pFrame = p->u.pFrame;
   71588     pFrame->pParent = pFrame->v->pDelFrame;
   71589     pFrame->v->pDelFrame = pFrame;
   71590   }
   71591   p->flags = MEM_Null;
   71592 }
   71593 
   71594 /*
   71595 ** Release memory held by the Mem p, both external memory cleared
   71596 ** by p->xDel and memory in p->zMalloc.
   71597 **
   71598 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
   71599 ** the unusual case where there really is memory in p that needs
   71600 ** to be freed.
   71601 */
   71602 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
   71603   if( VdbeMemDynamic(p) ){
   71604     vdbeMemClearExternAndSetNull(p);
   71605   }
   71606   if( p->szMalloc ){
   71607     sqlite3DbFreeNN(p->db, p->zMalloc);
   71608     p->szMalloc = 0;
   71609   }
   71610   p->z = 0;
   71611 }
   71612 
   71613 /*
   71614 ** Release any memory resources held by the Mem.  Both the memory that is
   71615 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
   71616 **
   71617 ** Use this routine prior to clean up prior to abandoning a Mem, or to
   71618 ** reset a Mem back to its minimum memory utilization.
   71619 **
   71620 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
   71621 ** prior to inserting new content into the Mem.
   71622 */
   71623 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
   71624   assert( sqlite3VdbeCheckMemInvariants(p) );
   71625   if( VdbeMemDynamic(p) || p->szMalloc ){
   71626     vdbeMemClear(p);
   71627   }
   71628 }
   71629 
   71630 /*
   71631 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
   71632 ** If the double is out of range of a 64-bit signed integer then
   71633 ** return the closest available 64-bit signed integer.
   71634 */
   71635 static SQLITE_NOINLINE i64 doubleToInt64(double r){
   71636 #ifdef SQLITE_OMIT_FLOATING_POINT
   71637   /* When floating-point is omitted, double and int64 are the same thing */
   71638   return r;
   71639 #else
   71640   /*
   71641   ** Many compilers we encounter do not define constants for the
   71642   ** minimum and maximum 64-bit integers, or they define them
   71643   ** inconsistently.  And many do not understand the "LL" notation.
   71644   ** So we define our own static constants here using nothing
   71645   ** larger than a 32-bit integer constant.
   71646   */
   71647   static const i64 maxInt = LARGEST_INT64;
   71648   static const i64 minInt = SMALLEST_INT64;
   71649 
   71650   if( r<=(double)minInt ){
   71651     return minInt;
   71652   }else if( r>=(double)maxInt ){
   71653     return maxInt;
   71654   }else{
   71655     return (i64)r;
   71656   }
   71657 #endif
   71658 }
   71659 
   71660 /*
   71661 ** Return some kind of integer value which is the best we can do
   71662 ** at representing the value that *pMem describes as an integer.
   71663 ** If pMem is an integer, then the value is exact.  If pMem is
   71664 ** a floating-point then the value returned is the integer part.
   71665 ** If pMem is a string or blob, then we make an attempt to convert
   71666 ** it into an integer and return that.  If pMem represents an
   71667 ** an SQL-NULL value, return 0.
   71668 **
   71669 ** If pMem represents a string value, its encoding might be changed.
   71670 */
   71671 static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
   71672   i64 value = 0;
   71673   sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
   71674   return value;
   71675 }
   71676 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
   71677   int flags;
   71678   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71679   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   71680   flags = pMem->flags;
   71681   if( flags & MEM_Int ){
   71682     return pMem->u.i;
   71683   }else if( flags & MEM_Real ){
   71684     return doubleToInt64(pMem->u.r);
   71685   }else if( flags & (MEM_Str|MEM_Blob) ){
   71686     assert( pMem->z || pMem->n==0 );
   71687     return memIntValue(pMem);
   71688   }else{
   71689     return 0;
   71690   }
   71691 }
   71692 
   71693 /*
   71694 ** Return the best representation of pMem that we can get into a
   71695 ** double.  If pMem is already a double or an integer, return its
   71696 ** value.  If it is a string or blob, try to convert it to a double.
   71697 ** If it is a NULL, return 0.0.
   71698 */
   71699 static SQLITE_NOINLINE double memRealValue(Mem *pMem){
   71700   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   71701   double val = (double)0;
   71702   sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
   71703   return val;
   71704 }
   71705 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
   71706   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71707   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   71708   if( pMem->flags & MEM_Real ){
   71709     return pMem->u.r;
   71710   }else if( pMem->flags & MEM_Int ){
   71711     return (double)pMem->u.i;
   71712   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
   71713     return memRealValue(pMem);
   71714   }else{
   71715     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   71716     return (double)0;
   71717   }
   71718 }
   71719 
   71720 /*
   71721 ** The MEM structure is already a MEM_Real.  Try to also make it a
   71722 ** MEM_Int if we can.
   71723 */
   71724 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   71725   i64 ix;
   71726   assert( pMem->flags & MEM_Real );
   71727   assert( (pMem->flags & MEM_RowSet)==0 );
   71728   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71729   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   71730 
   71731   ix = doubleToInt64(pMem->u.r);
   71732 
   71733   /* Only mark the value as an integer if
   71734   **
   71735   **    (1) the round-trip conversion real->int->real is a no-op, and
   71736   **    (2) The integer is neither the largest nor the smallest
   71737   **        possible integer (ticket #3922)
   71738   **
   71739   ** The second and third terms in the following conditional enforces
   71740   ** the second condition under the assumption that addition overflow causes
   71741   ** values to wrap around.
   71742   */
   71743   if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
   71744     pMem->u.i = ix;
   71745     MemSetTypeFlag(pMem, MEM_Int);
   71746   }
   71747 }
   71748 
   71749 /*
   71750 ** Convert pMem to type integer.  Invalidate any prior representations.
   71751 */
   71752 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
   71753   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71754   assert( (pMem->flags & MEM_RowSet)==0 );
   71755   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   71756 
   71757   pMem->u.i = sqlite3VdbeIntValue(pMem);
   71758   MemSetTypeFlag(pMem, MEM_Int);
   71759   return SQLITE_OK;
   71760 }
   71761 
   71762 /*
   71763 ** Convert pMem so that it is of type MEM_Real.
   71764 ** Invalidate any prior representations.
   71765 */
   71766 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
   71767   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71768   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   71769 
   71770   pMem->u.r = sqlite3VdbeRealValue(pMem);
   71771   MemSetTypeFlag(pMem, MEM_Real);
   71772   return SQLITE_OK;
   71773 }
   71774 
   71775 /*
   71776 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
   71777 ** Invalidate any prior representations.
   71778 **
   71779 ** Every effort is made to force the conversion, even if the input
   71780 ** is a string that does not look completely like a number.  Convert
   71781 ** as much of the string as we can and ignore the rest.
   71782 */
   71783 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
   71784   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
   71785     int rc;
   71786     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
   71787     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   71788     rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
   71789     if( rc==0 ){
   71790       MemSetTypeFlag(pMem, MEM_Int);
   71791     }else{
   71792       i64 i = pMem->u.i;
   71793       sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
   71794       if( rc==1 && pMem->u.r==(double)i ){
   71795         pMem->u.i = i;
   71796         MemSetTypeFlag(pMem, MEM_Int);
   71797       }else{
   71798         MemSetTypeFlag(pMem, MEM_Real);
   71799       }
   71800     }
   71801   }
   71802   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
   71803   pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
   71804   return SQLITE_OK;
   71805 }
   71806 
   71807 /*
   71808 ** Cast the datatype of the value in pMem according to the affinity
   71809 ** "aff".  Casting is different from applying affinity in that a cast
   71810 ** is forced.  In other words, the value is converted into the desired
   71811 ** affinity even if that results in loss of data.  This routine is
   71812 ** used (for example) to implement the SQL "cast()" operator.
   71813 */
   71814 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
   71815   if( pMem->flags & MEM_Null ) return;
   71816   switch( aff ){
   71817     case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
   71818       if( (pMem->flags & MEM_Blob)==0 ){
   71819         sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
   71820         assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
   71821         if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
   71822       }else{
   71823         pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
   71824       }
   71825       break;
   71826     }
   71827     case SQLITE_AFF_NUMERIC: {
   71828       sqlite3VdbeMemNumerify(pMem);
   71829       break;
   71830     }
   71831     case SQLITE_AFF_INTEGER: {
   71832       sqlite3VdbeMemIntegerify(pMem);
   71833       break;
   71834     }
   71835     case SQLITE_AFF_REAL: {
   71836       sqlite3VdbeMemRealify(pMem);
   71837       break;
   71838     }
   71839     default: {
   71840       assert( aff==SQLITE_AFF_TEXT );
   71841       assert( MEM_Str==(MEM_Blob>>3) );
   71842       pMem->flags |= (pMem->flags&MEM_Blob)>>3;
   71843       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
   71844       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
   71845       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
   71846       break;
   71847     }
   71848   }
   71849 }
   71850 
   71851 /*
   71852 ** Initialize bulk memory to be a consistent Mem object.
   71853 **
   71854 ** The minimum amount of initialization feasible is performed.
   71855 */
   71856 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
   71857   assert( (flags & ~MEM_TypeMask)==0 );
   71858   pMem->flags = flags;
   71859   pMem->db = db;
   71860   pMem->szMalloc = 0;
   71861 }
   71862 
   71863 
   71864 /*
   71865 ** Delete any previous value and set the value stored in *pMem to NULL.
   71866 **
   71867 ** This routine calls the Mem.xDel destructor to dispose of values that
   71868 ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
   71869 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
   71870 ** routine to invoke the destructor and deallocates Mem.zMalloc.
   71871 **
   71872 ** Use this routine to reset the Mem prior to insert a new value.
   71873 **
   71874 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
   71875 */
   71876 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   71877   if( VdbeMemDynamic(pMem) ){
   71878     vdbeMemClearExternAndSetNull(pMem);
   71879   }else{
   71880     pMem->flags = MEM_Null;
   71881   }
   71882 }
   71883 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
   71884   sqlite3VdbeMemSetNull((Mem*)p);
   71885 }
   71886 
   71887 /*
   71888 ** Delete any previous value and set the value to be a BLOB of length
   71889 ** n containing all zeros.
   71890 */
   71891 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   71892   sqlite3VdbeMemRelease(pMem);
   71893   pMem->flags = MEM_Blob|MEM_Zero;
   71894   pMem->n = 0;
   71895   if( n<0 ) n = 0;
   71896   pMem->u.nZero = n;
   71897   pMem->enc = SQLITE_UTF8;
   71898   pMem->z = 0;
   71899 }
   71900 
   71901 /*
   71902 ** The pMem is known to contain content that needs to be destroyed prior
   71903 ** to a value change.  So invoke the destructor, then set the value to
   71904 ** a 64-bit integer.
   71905 */
   71906 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
   71907   sqlite3VdbeMemSetNull(pMem);
   71908   pMem->u.i = val;
   71909   pMem->flags = MEM_Int;
   71910 }
   71911 
   71912 /*
   71913 ** Delete any previous value and set the value stored in *pMem to val,
   71914 ** manifest type INTEGER.
   71915 */
   71916 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
   71917   if( VdbeMemDynamic(pMem) ){
   71918     vdbeReleaseAndSetInt64(pMem, val);
   71919   }else{
   71920     pMem->u.i = val;
   71921     pMem->flags = MEM_Int;
   71922   }
   71923 }
   71924 
   71925 /* A no-op destructor */
   71926 static void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
   71927 
   71928 /*
   71929 ** Set the value stored in *pMem should already be a NULL.
   71930 ** Also store a pointer to go with it.
   71931 */
   71932 SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
   71933   Mem *pMem,
   71934   void *pPtr,
   71935   const char *zPType,
   71936   void (*xDestructor)(void*)
   71937 ){
   71938   assert( pMem->flags==MEM_Null );
   71939   pMem->u.zPType = zPType ? zPType : "";
   71940   pMem->z = pPtr;
   71941   pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
   71942   pMem->eSubtype = 'p';
   71943   pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
   71944 }
   71945 
   71946 #ifndef SQLITE_OMIT_FLOATING_POINT
   71947 /*
   71948 ** Delete any previous value and set the value stored in *pMem to val,
   71949 ** manifest type REAL.
   71950 */
   71951 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
   71952   sqlite3VdbeMemSetNull(pMem);
   71953   if( !sqlite3IsNaN(val) ){
   71954     pMem->u.r = val;
   71955     pMem->flags = MEM_Real;
   71956   }
   71957 }
   71958 #endif
   71959 
   71960 /*
   71961 ** Delete any previous value and set the value of pMem to be an
   71962 ** empty boolean index.
   71963 */
   71964 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
   71965   sqlite3 *db = pMem->db;
   71966   assert( db!=0 );
   71967   assert( (pMem->flags & MEM_RowSet)==0 );
   71968   sqlite3VdbeMemRelease(pMem);
   71969   pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
   71970   if( db->mallocFailed ){
   71971     pMem->flags = MEM_Null;
   71972     pMem->szMalloc = 0;
   71973   }else{
   71974     assert( pMem->zMalloc );
   71975     pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
   71976     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
   71977     assert( pMem->u.pRowSet!=0 );
   71978     pMem->flags = MEM_RowSet;
   71979   }
   71980 }
   71981 
   71982 /*
   71983 ** Return true if the Mem object contains a TEXT or BLOB that is
   71984 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
   71985 */
   71986 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
   71987   assert( p->db!=0 );
   71988   if( p->flags & (MEM_Str|MEM_Blob) ){
   71989     int n = p->n;
   71990     if( p->flags & MEM_Zero ){
   71991       n += p->u.nZero;
   71992     }
   71993     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   71994   }
   71995   return 0;
   71996 }
   71997 
   71998 #ifdef SQLITE_DEBUG
   71999 /*
   72000 ** This routine prepares a memory cell for modification by breaking
   72001 ** its link to a shallow copy and by marking any current shallow
   72002 ** copies of this cell as invalid.
   72003 **
   72004 ** This is used for testing and debugging only - to make sure shallow
   72005 ** copies are not misused.
   72006 */
   72007 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
   72008   int i;
   72009   Mem *pX;
   72010   for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
   72011     if( pX->pScopyFrom==pMem ){
   72012       pX->flags |= MEM_Undefined;
   72013       pX->pScopyFrom = 0;
   72014     }
   72015   }
   72016   pMem->pScopyFrom = 0;
   72017 }
   72018 #endif /* SQLITE_DEBUG */
   72019 
   72020 
   72021 /*
   72022 ** Make an shallow copy of pFrom into pTo.  Prior contents of
   72023 ** pTo are freed.  The pFrom->z field is not duplicated.  If
   72024 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
   72025 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
   72026 */
   72027 static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
   72028   vdbeMemClearExternAndSetNull(pTo);
   72029   assert( !VdbeMemDynamic(pTo) );
   72030   sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
   72031 }
   72032 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
   72033   assert( (pFrom->flags & MEM_RowSet)==0 );
   72034   assert( pTo->db==pFrom->db );
   72035   if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
   72036   memcpy(pTo, pFrom, MEMCELLSIZE);
   72037   if( (pFrom->flags&MEM_Static)==0 ){
   72038     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
   72039     assert( srcType==MEM_Ephem || srcType==MEM_Static );
   72040     pTo->flags |= srcType;
   72041   }
   72042 }
   72043 
   72044 /*
   72045 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
   72046 ** freed before the copy is made.
   72047 */
   72048 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   72049   int rc = SQLITE_OK;
   72050 
   72051   assert( (pFrom->flags & MEM_RowSet)==0 );
   72052   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
   72053   memcpy(pTo, pFrom, MEMCELLSIZE);
   72054   pTo->flags &= ~MEM_Dyn;
   72055   if( pTo->flags&(MEM_Str|MEM_Blob) ){
   72056     if( 0==(pFrom->flags&MEM_Static) ){
   72057       pTo->flags |= MEM_Ephem;
   72058       rc = sqlite3VdbeMemMakeWriteable(pTo);
   72059     }
   72060   }
   72061 
   72062   return rc;
   72063 }
   72064 
   72065 /*
   72066 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
   72067 ** freed. If pFrom contains ephemeral data, a copy is made.
   72068 **
   72069 ** pFrom contains an SQL NULL when this routine returns.
   72070 */
   72071 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
   72072   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
   72073   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
   72074   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
   72075 
   72076   sqlite3VdbeMemRelease(pTo);
   72077   memcpy(pTo, pFrom, sizeof(Mem));
   72078   pFrom->flags = MEM_Null;
   72079   pFrom->szMalloc = 0;
   72080 }
   72081 
   72082 /*
   72083 ** Change the value of a Mem to be a string or a BLOB.
   72084 **
   72085 ** The memory management strategy depends on the value of the xDel
   72086 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
   72087 ** string is copied into a (possibly existing) buffer managed by the
   72088 ** Mem structure. Otherwise, any existing buffer is freed and the
   72089 ** pointer copied.
   72090 **
   72091 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
   72092 ** size limit) then no memory allocation occurs.  If the string can be
   72093 ** stored without allocating memory, then it is.  If a memory allocation
   72094 ** is required to store the string, then value of pMem is unchanged.  In
   72095 ** either case, SQLITE_TOOBIG is returned.
   72096 */
   72097 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   72098   Mem *pMem,          /* Memory cell to set to string value */
   72099   const char *z,      /* String pointer */
   72100   int n,              /* Bytes in string, or negative */
   72101   u8 enc,             /* Encoding of z.  0 for BLOBs */
   72102   void (*xDel)(void*) /* Destructor function */
   72103 ){
   72104   int nByte = n;      /* New value for pMem->n */
   72105   int iLimit;         /* Maximum allowed string or blob size */
   72106   u16 flags = 0;      /* New value for pMem->flags */
   72107 
   72108   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   72109   assert( (pMem->flags & MEM_RowSet)==0 );
   72110 
   72111   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
   72112   if( !z ){
   72113     sqlite3VdbeMemSetNull(pMem);
   72114     return SQLITE_OK;
   72115   }
   72116 
   72117   if( pMem->db ){
   72118     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
   72119   }else{
   72120     iLimit = SQLITE_MAX_LENGTH;
   72121   }
   72122   flags = (enc==0?MEM_Blob:MEM_Str);
   72123   if( nByte<0 ){
   72124     assert( enc!=0 );
   72125     if( enc==SQLITE_UTF8 ){
   72126       nByte = 0x7fffffff & (int)strlen(z);
   72127       if( nByte>iLimit ) nByte = iLimit+1;
   72128     }else{
   72129       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
   72130     }
   72131     flags |= MEM_Term;
   72132   }
   72133 
   72134   /* The following block sets the new values of Mem.z and Mem.xDel. It
   72135   ** also sets a flag in local variable "flags" to indicate the memory
   72136   ** management (one of MEM_Dyn or MEM_Static).
   72137   */
   72138   if( xDel==SQLITE_TRANSIENT ){
   72139     int nAlloc = nByte;
   72140     if( flags&MEM_Term ){
   72141       nAlloc += (enc==SQLITE_UTF8?1:2);
   72142     }
   72143     if( nByte>iLimit ){
   72144       return SQLITE_TOOBIG;
   72145     }
   72146     testcase( nAlloc==0 );
   72147     testcase( nAlloc==31 );
   72148     testcase( nAlloc==32 );
   72149     if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
   72150       return SQLITE_NOMEM_BKPT;
   72151     }
   72152     memcpy(pMem->z, z, nAlloc);
   72153   }else if( xDel==SQLITE_DYNAMIC ){
   72154     sqlite3VdbeMemRelease(pMem);
   72155     pMem->zMalloc = pMem->z = (char *)z;
   72156     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
   72157   }else{
   72158     sqlite3VdbeMemRelease(pMem);
   72159     pMem->z = (char *)z;
   72160     pMem->xDel = xDel;
   72161     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
   72162   }
   72163 
   72164   pMem->n = nByte;
   72165   pMem->flags = flags;
   72166   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
   72167 
   72168 #ifndef SQLITE_OMIT_UTF16
   72169   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
   72170     return SQLITE_NOMEM_BKPT;
   72171   }
   72172 #endif
   72173 
   72174   if( nByte>iLimit ){
   72175     return SQLITE_TOOBIG;
   72176   }
   72177 
   72178   return SQLITE_OK;
   72179 }
   72180 
   72181 /*
   72182 ** Move data out of a btree key or data field and into a Mem structure.
   72183 ** The data is payload from the entry that pCur is currently pointing
   72184 ** to.  offset and amt determine what portion of the data or key to retrieve.
   72185 ** The result is written into the pMem element.
   72186 **
   72187 ** The pMem object must have been initialized.  This routine will use
   72188 ** pMem->zMalloc to hold the content from the btree, if possible.  New
   72189 ** pMem->zMalloc space will be allocated if necessary.  The calling routine
   72190 ** is responsible for making sure that the pMem object is eventually
   72191 ** destroyed.
   72192 **
   72193 ** If this routine fails for any reason (malloc returns NULL or unable
   72194 ** to read from the disk) then the pMem is left in an inconsistent state.
   72195 */
   72196 static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
   72197   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   72198   u32 offset,       /* Offset from the start of data to return bytes from. */
   72199   u32 amt,          /* Number of bytes to return. */
   72200   Mem *pMem         /* OUT: Return data in this Mem structure. */
   72201 ){
   72202   int rc;
   72203   pMem->flags = MEM_Null;
   72204   if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
   72205     rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
   72206     if( rc==SQLITE_OK ){
   72207       pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */
   72208       pMem->flags = MEM_Blob;
   72209       pMem->n = (int)amt;
   72210     }else{
   72211       sqlite3VdbeMemRelease(pMem);
   72212     }
   72213   }
   72214   return rc;
   72215 }
   72216 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   72217   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   72218   u32 offset,       /* Offset from the start of data to return bytes from. */
   72219   u32 amt,          /* Number of bytes to return. */
   72220   Mem *pMem         /* OUT: Return data in this Mem structure. */
   72221 ){
   72222   char *zData;        /* Data from the btree layer */
   72223   u32 available = 0;  /* Number of bytes available on the local btree page */
   72224   int rc = SQLITE_OK; /* Return code */
   72225 
   72226   assert( sqlite3BtreeCursorIsValid(pCur) );
   72227   assert( !VdbeMemDynamic(pMem) );
   72228 
   72229   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   72230   ** that both the BtShared and database handle mutexes are held. */
   72231   assert( (pMem->flags & MEM_RowSet)==0 );
   72232   zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
   72233   assert( zData!=0 );
   72234 
   72235   if( offset+amt<=available ){
   72236     pMem->z = &zData[offset];
   72237     pMem->flags = MEM_Blob|MEM_Ephem;
   72238     pMem->n = (int)amt;
   72239   }else{
   72240     rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
   72241   }
   72242 
   72243   return rc;
   72244 }
   72245 
   72246 /*
   72247 ** The pVal argument is known to be a value other than NULL.
   72248 ** Convert it into a string with encoding enc and return a pointer
   72249 ** to a zero-terminated version of that string.
   72250 */
   72251 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
   72252   assert( pVal!=0 );
   72253   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   72254   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   72255   assert( (pVal->flags & MEM_RowSet)==0 );
   72256   assert( (pVal->flags & (MEM_Null))==0 );
   72257   if( pVal->flags & (MEM_Blob|MEM_Str) ){
   72258     if( ExpandBlob(pVal) ) return 0;
   72259     pVal->flags |= MEM_Str;
   72260     if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
   72261       sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
   72262     }
   72263     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
   72264       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
   72265       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
   72266         return 0;
   72267       }
   72268     }
   72269     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
   72270   }else{
   72271     sqlite3VdbeMemStringify(pVal, enc, 0);
   72272     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
   72273   }
   72274   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
   72275               || pVal->db->mallocFailed );
   72276   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
   72277     return pVal->z;
   72278   }else{
   72279     return 0;
   72280   }
   72281 }
   72282 
   72283 /* This function is only available internally, it is not part of the
   72284 ** external API. It works in a similar way to sqlite3_value_text(),
   72285 ** except the data returned is in the encoding specified by the second
   72286 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
   72287 ** SQLITE_UTF8.
   72288 **
   72289 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
   72290 ** If that is the case, then the result must be aligned on an even byte
   72291 ** boundary.
   72292 */
   72293 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
   72294   if( !pVal ) return 0;
   72295   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   72296   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   72297   assert( (pVal->flags & MEM_RowSet)==0 );
   72298   if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
   72299     return pVal->z;
   72300   }
   72301   if( pVal->flags&MEM_Null ){
   72302     return 0;
   72303   }
   72304   return valueToText(pVal, enc);
   72305 }
   72306 
   72307 /*
   72308 ** Create a new sqlite3_value object.
   72309 */
   72310 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
   72311   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
   72312   if( p ){
   72313     p->flags = MEM_Null;
   72314     p->db = db;
   72315   }
   72316   return p;
   72317 }
   72318 
   72319 /*
   72320 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
   72321 ** valueNew(). See comments above valueNew() for details.
   72322 */
   72323 struct ValueNewStat4Ctx {
   72324   Parse *pParse;
   72325   Index *pIdx;
   72326   UnpackedRecord **ppRec;
   72327   int iVal;
   72328 };
   72329 
   72330 /*
   72331 ** Allocate and return a pointer to a new sqlite3_value object. If
   72332 ** the second argument to this function is NULL, the object is allocated
   72333 ** by calling sqlite3ValueNew().
   72334 **
   72335 ** Otherwise, if the second argument is non-zero, then this function is
   72336 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
   72337 ** already been allocated, allocate the UnpackedRecord structure that
   72338 ** that function will return to its caller here. Then return a pointer to
   72339 ** an sqlite3_value within the UnpackedRecord.a[] array.
   72340 */
   72341 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
   72342 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   72343   if( p ){
   72344     UnpackedRecord *pRec = p->ppRec[0];
   72345 
   72346     if( pRec==0 ){
   72347       Index *pIdx = p->pIdx;      /* Index being probed */
   72348       int nByte;                  /* Bytes of space to allocate */
   72349       int i;                      /* Counter variable */
   72350       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
   72351 
   72352       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
   72353       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
   72354       if( pRec ){
   72355         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
   72356         if( pRec->pKeyInfo ){
   72357           assert( pRec->pKeyInfo->nAllField==nCol );
   72358           assert( pRec->pKeyInfo->enc==ENC(db) );
   72359           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
   72360           for(i=0; i<nCol; i++){
   72361             pRec->aMem[i].flags = MEM_Null;
   72362             pRec->aMem[i].db = db;
   72363           }
   72364         }else{
   72365           sqlite3DbFreeNN(db, pRec);
   72366           pRec = 0;
   72367         }
   72368       }
   72369       if( pRec==0 ) return 0;
   72370       p->ppRec[0] = pRec;
   72371     }
   72372 
   72373     pRec->nField = p->iVal+1;
   72374     return &pRec->aMem[p->iVal];
   72375   }
   72376 #else
   72377   UNUSED_PARAMETER(p);
   72378 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
   72379   return sqlite3ValueNew(db);
   72380 }
   72381 
   72382 /*
   72383 ** The expression object indicated by the second argument is guaranteed
   72384 ** to be a scalar SQL function. If
   72385 **
   72386 **   * all function arguments are SQL literals,
   72387 **   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
   72388 **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
   72389 **
   72390 ** then this routine attempts to invoke the SQL function. Assuming no
   72391 ** error occurs, output parameter (*ppVal) is set to point to a value
   72392 ** object containing the result before returning SQLITE_OK.
   72393 **
   72394 ** Affinity aff is applied to the result of the function before returning.
   72395 ** If the result is a text value, the sqlite3_value object uses encoding
   72396 ** enc.
   72397 **
   72398 ** If the conditions above are not met, this function returns SQLITE_OK
   72399 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
   72400 ** NULL and an SQLite error code returned.
   72401 */
   72402 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   72403 static int valueFromFunction(
   72404   sqlite3 *db,                    /* The database connection */
   72405   Expr *p,                        /* The expression to evaluate */
   72406   u8 enc,                         /* Encoding to use */
   72407   u8 aff,                         /* Affinity to use */
   72408   sqlite3_value **ppVal,          /* Write the new value here */
   72409   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
   72410 ){
   72411   sqlite3_context ctx;            /* Context object for function invocation */
   72412   sqlite3_value **apVal = 0;      /* Function arguments */
   72413   int nVal = 0;                   /* Size of apVal[] array */
   72414   FuncDef *pFunc = 0;             /* Function definition */
   72415   sqlite3_value *pVal = 0;        /* New value */
   72416   int rc = SQLITE_OK;             /* Return code */
   72417   ExprList *pList = 0;            /* Function arguments */
   72418   int i;                          /* Iterator variable */
   72419 
   72420   assert( pCtx!=0 );
   72421   assert( (p->flags & EP_TokenOnly)==0 );
   72422   pList = p->x.pList;
   72423   if( pList ) nVal = pList->nExpr;
   72424   pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
   72425   assert( pFunc );
   72426   if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
   72427    || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
   72428   ){
   72429     return SQLITE_OK;
   72430   }
   72431 
   72432   if( pList ){
   72433     apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
   72434     if( apVal==0 ){
   72435       rc = SQLITE_NOMEM_BKPT;
   72436       goto value_from_function_out;
   72437     }
   72438     for(i=0; i<nVal; i++){
   72439       rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
   72440       if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
   72441     }
   72442   }
   72443 
   72444   pVal = valueNew(db, pCtx);
   72445   if( pVal==0 ){
   72446     rc = SQLITE_NOMEM_BKPT;
   72447     goto value_from_function_out;
   72448   }
   72449 
   72450   assert( pCtx->pParse->rc==SQLITE_OK );
   72451   memset(&ctx, 0, sizeof(ctx));
   72452   ctx.pOut = pVal;
   72453   ctx.pFunc = pFunc;
   72454   pFunc->xSFunc(&ctx, nVal, apVal);
   72455   if( ctx.isError ){
   72456     rc = ctx.isError;
   72457     sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
   72458   }else{
   72459     sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
   72460     assert( rc==SQLITE_OK );
   72461     rc = sqlite3VdbeChangeEncoding(pVal, enc);
   72462     if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
   72463       rc = SQLITE_TOOBIG;
   72464       pCtx->pParse->nErr++;
   72465     }
   72466   }
   72467   pCtx->pParse->rc = rc;
   72468 
   72469  value_from_function_out:
   72470   if( rc!=SQLITE_OK ){
   72471     pVal = 0;
   72472   }
   72473   if( apVal ){
   72474     for(i=0; i<nVal; i++){
   72475       sqlite3ValueFree(apVal[i]);
   72476     }
   72477     sqlite3DbFreeNN(db, apVal);
   72478   }
   72479 
   72480   *ppVal = pVal;
   72481   return rc;
   72482 }
   72483 #else
   72484 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
   72485 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
   72486 
   72487 /*
   72488 ** Extract a value from the supplied expression in the manner described
   72489 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
   72490 ** using valueNew().
   72491 **
   72492 ** If pCtx is NULL and an error occurs after the sqlite3_value object
   72493 ** has been allocated, it is freed before returning. Or, if pCtx is not
   72494 ** NULL, it is assumed that the caller will free any allocated object
   72495 ** in all cases.
   72496 */
   72497 static int valueFromExpr(
   72498   sqlite3 *db,                    /* The database connection */
   72499   Expr *pExpr,                    /* The expression to evaluate */
   72500   u8 enc,                         /* Encoding to use */
   72501   u8 affinity,                    /* Affinity to use */
   72502   sqlite3_value **ppVal,          /* Write the new value here */
   72503   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
   72504 ){
   72505   int op;
   72506   char *zVal = 0;
   72507   sqlite3_value *pVal = 0;
   72508   int negInt = 1;
   72509   const char *zNeg = "";
   72510   int rc = SQLITE_OK;
   72511 
   72512   assert( pExpr!=0 );
   72513   while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
   72514 #if defined(SQLITE_ENABLE_STAT3_OR_STAT4)
   72515   if( op==TK_REGISTER ) op = pExpr->op2;
   72516 #else
   72517   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
   72518 #endif
   72519 
   72520   /* Compressed expressions only appear when parsing the DEFAULT clause
   72521   ** on a table column definition, and hence only when pCtx==0.  This
   72522   ** check ensures that an EP_TokenOnly expression is never passed down
   72523   ** into valueFromFunction(). */
   72524   assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
   72525 
   72526   if( op==TK_CAST ){
   72527     u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
   72528     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
   72529     testcase( rc!=SQLITE_OK );
   72530     if( *ppVal ){
   72531       sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
   72532       sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
   72533     }
   72534     return rc;
   72535   }
   72536 
   72537   /* Handle negative integers in a single step.  This is needed in the
   72538   ** case when the value is -9223372036854775808.
   72539   */
   72540   if( op==TK_UMINUS
   72541    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
   72542     pExpr = pExpr->pLeft;
   72543     op = pExpr->op;
   72544     negInt = -1;
   72545     zNeg = "-";
   72546   }
   72547 
   72548   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
   72549     pVal = valueNew(db, pCtx);
   72550     if( pVal==0 ) goto no_mem;
   72551     if( ExprHasProperty(pExpr, EP_IntValue) ){
   72552       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
   72553     }else{
   72554       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
   72555       if( zVal==0 ) goto no_mem;
   72556       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
   72557     }
   72558     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
   72559       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
   72560     }else{
   72561       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
   72562     }
   72563     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
   72564     if( enc!=SQLITE_UTF8 ){
   72565       rc = sqlite3VdbeChangeEncoding(pVal, enc);
   72566     }
   72567   }else if( op==TK_UMINUS ) {
   72568     /* This branch happens for multiple negative signs.  Ex: -(-5) */
   72569     if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
   72570      && pVal!=0
   72571     ){
   72572       sqlite3VdbeMemNumerify(pVal);
   72573       if( pVal->flags & MEM_Real ){
   72574         pVal->u.r = -pVal->u.r;
   72575       }else if( pVal->u.i==SMALLEST_INT64 ){
   72576         pVal->u.r = -(double)SMALLEST_INT64;
   72577         MemSetTypeFlag(pVal, MEM_Real);
   72578       }else{
   72579         pVal->u.i = -pVal->u.i;
   72580       }
   72581       sqlite3ValueApplyAffinity(pVal, affinity, enc);
   72582     }
   72583   }else if( op==TK_NULL ){
   72584     pVal = valueNew(db, pCtx);
   72585     if( pVal==0 ) goto no_mem;
   72586     sqlite3VdbeMemNumerify(pVal);
   72587   }
   72588 #ifndef SQLITE_OMIT_BLOB_LITERAL
   72589   else if( op==TK_BLOB ){
   72590     int nVal;
   72591     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   72592     assert( pExpr->u.zToken[1]=='\'' );
   72593     pVal = valueNew(db, pCtx);
   72594     if( !pVal ) goto no_mem;
   72595     zVal = &pExpr->u.zToken[2];
   72596     nVal = sqlite3Strlen30(zVal)-1;
   72597     assert( zVal[nVal]=='\'' );
   72598     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
   72599                          0, SQLITE_DYNAMIC);
   72600   }
   72601 #endif
   72602 
   72603 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   72604   else if( op==TK_FUNCTION && pCtx!=0 ){
   72605     rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
   72606   }
   72607 #endif
   72608 
   72609   *ppVal = pVal;
   72610   return rc;
   72611 
   72612 no_mem:
   72613 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   72614   if( pCtx==0 || pCtx->pParse->nErr==0 )
   72615 #endif
   72616     sqlite3OomFault(db);
   72617   sqlite3DbFree(db, zVal);
   72618   assert( *ppVal==0 );
   72619 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   72620   if( pCtx==0 ) sqlite3ValueFree(pVal);
   72621 #else
   72622   assert( pCtx==0 ); sqlite3ValueFree(pVal);
   72623 #endif
   72624   return SQLITE_NOMEM_BKPT;
   72625 }
   72626 
   72627 /*
   72628 ** Create a new sqlite3_value object, containing the value of pExpr.
   72629 **
   72630 ** This only works for very simple expressions that consist of one constant
   72631 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
   72632 ** be converted directly into a value, then the value is allocated and
   72633 ** a pointer written to *ppVal. The caller is responsible for deallocating
   72634 ** the value by passing it to sqlite3ValueFree() later on. If the expression
   72635 ** cannot be converted to a value, then *ppVal is set to NULL.
   72636 */
   72637 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   72638   sqlite3 *db,              /* The database connection */
   72639   Expr *pExpr,              /* The expression to evaluate */
   72640   u8 enc,                   /* Encoding to use */
   72641   u8 affinity,              /* Affinity to use */
   72642   sqlite3_value **ppVal     /* Write the new value here */
   72643 ){
   72644   return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
   72645 }
   72646 
   72647 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   72648 /*
   72649 ** The implementation of the sqlite_record() function. This function accepts
   72650 ** a single argument of any type. The return value is a formatted database
   72651 ** record (a blob) containing the argument value.
   72652 **
   72653 ** This is used to convert the value stored in the 'sample' column of the
   72654 ** sqlite_stat3 table to the record format SQLite uses internally.
   72655 */
   72656 static void recordFunc(
   72657   sqlite3_context *context,
   72658   int argc,
   72659   sqlite3_value **argv
   72660 ){
   72661   const int file_format = 1;
   72662   u32 iSerial;                    /* Serial type */
   72663   int nSerial;                    /* Bytes of space for iSerial as varint */
   72664   u32 nVal;                       /* Bytes of space required for argv[0] */
   72665   int nRet;
   72666   sqlite3 *db;
   72667   u8 *aRet;
   72668 
   72669   UNUSED_PARAMETER( argc );
   72670   iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
   72671   nSerial = sqlite3VarintLen(iSerial);
   72672   db = sqlite3_context_db_handle(context);
   72673 
   72674   nRet = 1 + nSerial + nVal;
   72675   aRet = sqlite3DbMallocRawNN(db, nRet);
   72676   if( aRet==0 ){
   72677     sqlite3_result_error_nomem(context);
   72678   }else{
   72679     aRet[0] = nSerial+1;
   72680     putVarint32(&aRet[1], iSerial);
   72681     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
   72682     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
   72683     sqlite3DbFreeNN(db, aRet);
   72684   }
   72685 }
   72686 
   72687 /*
   72688 ** Register built-in functions used to help read ANALYZE data.
   72689 */
   72690 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
   72691   static FuncDef aAnalyzeTableFuncs[] = {
   72692     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
   72693   };
   72694   sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
   72695 }
   72696 
   72697 /*
   72698 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
   72699 **
   72700 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
   72701 ** pAlloc if one does not exist and the new value is added to the
   72702 ** UnpackedRecord object.
   72703 **
   72704 ** A value is extracted in the following cases:
   72705 **
   72706 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
   72707 **
   72708 **  * The expression is a bound variable, and this is a reprepare, or
   72709 **
   72710 **  * The expression is a literal value.
   72711 **
   72712 ** On success, *ppVal is made to point to the extracted value.  The caller
   72713 ** is responsible for ensuring that the value is eventually freed.
   72714 */
   72715 static int stat4ValueFromExpr(
   72716   Parse *pParse,                  /* Parse context */
   72717   Expr *pExpr,                    /* The expression to extract a value from */
   72718   u8 affinity,                    /* Affinity to use */
   72719   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
   72720   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
   72721 ){
   72722   int rc = SQLITE_OK;
   72723   sqlite3_value *pVal = 0;
   72724   sqlite3 *db = pParse->db;
   72725 
   72726   /* Skip over any TK_COLLATE nodes */
   72727   pExpr = sqlite3ExprSkipCollate(pExpr);
   72728 
   72729   assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
   72730   if( !pExpr ){
   72731     pVal = valueNew(db, pAlloc);
   72732     if( pVal ){
   72733       sqlite3VdbeMemSetNull((Mem*)pVal);
   72734     }
   72735   }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
   72736     Vdbe *v;
   72737     int iBindVar = pExpr->iColumn;
   72738     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
   72739     if( (v = pParse->pReprepare)!=0 ){
   72740       pVal = valueNew(db, pAlloc);
   72741       if( pVal ){
   72742         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
   72743         sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
   72744         pVal->db = pParse->db;
   72745       }
   72746     }
   72747   }else{
   72748     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
   72749   }
   72750 
   72751   assert( pVal==0 || pVal->db==db );
   72752   *ppVal = pVal;
   72753   return rc;
   72754 }
   72755 
   72756 /*
   72757 ** This function is used to allocate and populate UnpackedRecord
   72758 ** structures intended to be compared against sample index keys stored
   72759 ** in the sqlite_stat4 table.
   72760 **
   72761 ** A single call to this function populates zero or more fields of the
   72762 ** record starting with field iVal (fields are numbered from left to
   72763 ** right starting with 0). A single field is populated if:
   72764 **
   72765 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
   72766 **
   72767 **  * The expression is a bound variable, and this is a reprepare, or
   72768 **
   72769 **  * The sqlite3ValueFromExpr() function is able to extract a value
   72770 **    from the expression (i.e. the expression is a literal value).
   72771 **
   72772 ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
   72773 ** vector components that match either of the two latter criteria listed
   72774 ** above.
   72775 **
   72776 ** Before any value is appended to the record, the affinity of the
   72777 ** corresponding column within index pIdx is applied to it. Before
   72778 ** this function returns, output parameter *pnExtract is set to the
   72779 ** number of values appended to the record.
   72780 **
   72781 ** When this function is called, *ppRec must either point to an object
   72782 ** allocated by an earlier call to this function, or must be NULL. If it
   72783 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
   72784 ** is allocated (and *ppRec set to point to it) before returning.
   72785 **
   72786 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
   72787 ** error if a value cannot be extracted from pExpr. If an error does
   72788 ** occur, an SQLite error code is returned.
   72789 */
   72790 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
   72791   Parse *pParse,                  /* Parse context */
   72792   Index *pIdx,                    /* Index being probed */
   72793   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
   72794   Expr *pExpr,                    /* The expression to extract a value from */
   72795   int nElem,                      /* Maximum number of values to append */
   72796   int iVal,                       /* Array element to populate */
   72797   int *pnExtract                  /* OUT: Values appended to the record */
   72798 ){
   72799   int rc = SQLITE_OK;
   72800   int nExtract = 0;
   72801 
   72802   if( pExpr==0 || pExpr->op!=TK_SELECT ){
   72803     int i;
   72804     struct ValueNewStat4Ctx alloc;
   72805 
   72806     alloc.pParse = pParse;
   72807     alloc.pIdx = pIdx;
   72808     alloc.ppRec = ppRec;
   72809 
   72810     for(i=0; i<nElem; i++){
   72811       sqlite3_value *pVal = 0;
   72812       Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
   72813       u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
   72814       alloc.iVal = iVal+i;
   72815       rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
   72816       if( !pVal ) break;
   72817       nExtract++;
   72818     }
   72819   }
   72820 
   72821   *pnExtract = nExtract;
   72822   return rc;
   72823 }
   72824 
   72825 /*
   72826 ** Attempt to extract a value from expression pExpr using the methods
   72827 ** as described for sqlite3Stat4ProbeSetValue() above.
   72828 **
   72829 ** If successful, set *ppVal to point to a new value object and return
   72830 ** SQLITE_OK. If no value can be extracted, but no other error occurs
   72831 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
   72832 ** does occur, return an SQLite error code. The final value of *ppVal
   72833 ** is undefined in this case.
   72834 */
   72835 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
   72836   Parse *pParse,                  /* Parse context */
   72837   Expr *pExpr,                    /* The expression to extract a value from */
   72838   u8 affinity,                    /* Affinity to use */
   72839   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
   72840 ){
   72841   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
   72842 }
   72843 
   72844 /*
   72845 ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
   72846 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
   72847 ** sqlite3_value object is allocated.
   72848 **
   72849 ** If *ppVal is initially NULL then the caller is responsible for
   72850 ** ensuring that the value written into *ppVal is eventually freed.
   72851 */
   72852 SQLITE_PRIVATE int sqlite3Stat4Column(
   72853   sqlite3 *db,                    /* Database handle */
   72854   const void *pRec,               /* Pointer to buffer containing record */
   72855   int nRec,                       /* Size of buffer pRec in bytes */
   72856   int iCol,                       /* Column to extract */
   72857   sqlite3_value **ppVal           /* OUT: Extracted value */
   72858 ){
   72859   u32 t;                          /* a column type code */
   72860   int nHdr;                       /* Size of the header in the record */
   72861   int iHdr;                       /* Next unread header byte */
   72862   int iField;                     /* Next unread data byte */
   72863   int szField;                    /* Size of the current data field */
   72864   int i;                          /* Column index */
   72865   u8 *a = (u8*)pRec;              /* Typecast byte array */
   72866   Mem *pMem = *ppVal;             /* Write result into this Mem object */
   72867 
   72868   assert( iCol>0 );
   72869   iHdr = getVarint32(a, nHdr);
   72870   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
   72871   iField = nHdr;
   72872   for(i=0; i<=iCol; i++){
   72873     iHdr += getVarint32(&a[iHdr], t);
   72874     testcase( iHdr==nHdr );
   72875     testcase( iHdr==nHdr+1 );
   72876     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
   72877     szField = sqlite3VdbeSerialTypeLen(t);
   72878     iField += szField;
   72879   }
   72880   testcase( iField==nRec );
   72881   testcase( iField==nRec+1 );
   72882   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
   72883   if( pMem==0 ){
   72884     pMem = *ppVal = sqlite3ValueNew(db);
   72885     if( pMem==0 ) return SQLITE_NOMEM_BKPT;
   72886   }
   72887   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
   72888   pMem->enc = ENC(db);
   72889   return SQLITE_OK;
   72890 }
   72891 
   72892 /*
   72893 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
   72894 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
   72895 ** the object.
   72896 */
   72897 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
   72898   if( pRec ){
   72899     int i;
   72900     int nCol = pRec->pKeyInfo->nAllField;
   72901     Mem *aMem = pRec->aMem;
   72902     sqlite3 *db = aMem[0].db;
   72903     for(i=0; i<nCol; i++){
   72904       sqlite3VdbeMemRelease(&aMem[i]);
   72905     }
   72906     sqlite3KeyInfoUnref(pRec->pKeyInfo);
   72907     sqlite3DbFreeNN(db, pRec);
   72908   }
   72909 }
   72910 #endif /* ifdef SQLITE_ENABLE_STAT4 */
   72911 
   72912 /*
   72913 ** Change the string value of an sqlite3_value object
   72914 */
   72915 SQLITE_PRIVATE void sqlite3ValueSetStr(
   72916   sqlite3_value *v,     /* Value to be set */
   72917   int n,                /* Length of string z */
   72918   const void *z,        /* Text of the new string */
   72919   u8 enc,               /* Encoding to use */
   72920   void (*xDel)(void*)   /* Destructor for the string */
   72921 ){
   72922   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
   72923 }
   72924 
   72925 /*
   72926 ** Free an sqlite3_value object
   72927 */
   72928 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
   72929   if( !v ) return;
   72930   sqlite3VdbeMemRelease((Mem *)v);
   72931   sqlite3DbFreeNN(((Mem*)v)->db, v);
   72932 }
   72933 
   72934 /*
   72935 ** The sqlite3ValueBytes() routine returns the number of bytes in the
   72936 ** sqlite3_value object assuming that it uses the encoding "enc".
   72937 ** The valueBytes() routine is a helper function.
   72938 */
   72939 static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
   72940   return valueToText(pVal, enc)!=0 ? pVal->n : 0;
   72941 }
   72942 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
   72943   Mem *p = (Mem*)pVal;
   72944   assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
   72945   if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
   72946     return p->n;
   72947   }
   72948   if( (p->flags & MEM_Blob)!=0 ){
   72949     if( p->flags & MEM_Zero ){
   72950       return p->n + p->u.nZero;
   72951     }else{
   72952       return p->n;
   72953     }
   72954   }
   72955   if( p->flags & MEM_Null ) return 0;
   72956   return valueBytes(pVal, enc);
   72957 }
   72958 
   72959 /************** End of vdbemem.c *********************************************/
   72960 /************** Begin file vdbeaux.c *****************************************/
   72961 /*
   72962 ** 2003 September 6
   72963 **
   72964 ** The author disclaims copyright to this source code.  In place of
   72965 ** a legal notice, here is a blessing:
   72966 **
   72967 **    May you do good and not evil.
   72968 **    May you find forgiveness for yourself and forgive others.
   72969 **    May you share freely, never taking more than you give.
   72970 **
   72971 *************************************************************************
   72972 ** This file contains code used for creating, destroying, and populating
   72973 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
   72974 */
   72975 /* #include "sqliteInt.h" */
   72976 /* #include "vdbeInt.h" */
   72977 
   72978 /*
   72979 ** Create a new virtual database engine.
   72980 */
   72981 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
   72982   sqlite3 *db = pParse->db;
   72983   Vdbe *p;
   72984   p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
   72985   if( p==0 ) return 0;
   72986   memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
   72987   p->db = db;
   72988   if( db->pVdbe ){
   72989     db->pVdbe->pPrev = p;
   72990   }
   72991   p->pNext = db->pVdbe;
   72992   p->pPrev = 0;
   72993   db->pVdbe = p;
   72994   p->magic = VDBE_MAGIC_INIT;
   72995   p->pParse = pParse;
   72996   pParse->pVdbe = p;
   72997   assert( pParse->aLabel==0 );
   72998   assert( pParse->nLabel==0 );
   72999   assert( pParse->nOpAlloc==0 );
   73000   assert( pParse->szOpAlloc==0 );
   73001   sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
   73002   return p;
   73003 }
   73004 
   73005 /*
   73006 ** Change the error string stored in Vdbe.zErrMsg
   73007 */
   73008 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
   73009   va_list ap;
   73010   sqlite3DbFree(p->db, p->zErrMsg);
   73011   va_start(ap, zFormat);
   73012   p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
   73013   va_end(ap);
   73014 }
   73015 
   73016 /*
   73017 ** Remember the SQL string for a prepared statement.
   73018 */
   73019 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
   73020   if( p==0 ) return;
   73021   p->prepFlags = prepFlags;
   73022   if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
   73023     p->expmask = 0;
   73024   }
   73025   assert( p->zSql==0 );
   73026   p->zSql = sqlite3DbStrNDup(p->db, z, n);
   73027 }
   73028 
   73029 /*
   73030 ** Swap all content between two VDBE structures.
   73031 */
   73032 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   73033   Vdbe tmp, *pTmp;
   73034   char *zTmp;
   73035   assert( pA->db==pB->db );
   73036   tmp = *pA;
   73037   *pA = *pB;
   73038   *pB = tmp;
   73039   pTmp = pA->pNext;
   73040   pA->pNext = pB->pNext;
   73041   pB->pNext = pTmp;
   73042   pTmp = pA->pPrev;
   73043   pA->pPrev = pB->pPrev;
   73044   pB->pPrev = pTmp;
   73045   zTmp = pA->zSql;
   73046   pA->zSql = pB->zSql;
   73047   pB->zSql = zTmp;
   73048   pB->expmask = pA->expmask;
   73049   pB->prepFlags = pA->prepFlags;
   73050   memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
   73051   pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
   73052 }
   73053 
   73054 /*
   73055 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
   73056 ** than its current size. nOp is guaranteed to be less than or equal
   73057 ** to 1024/sizeof(Op).
   73058 **
   73059 ** If an out-of-memory error occurs while resizing the array, return
   73060 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
   73061 ** unchanged (this is so that any opcodes already allocated can be
   73062 ** correctly deallocated along with the rest of the Vdbe).
   73063 */
   73064 static int growOpArray(Vdbe *v, int nOp){
   73065   VdbeOp *pNew;
   73066   Parse *p = v->pParse;
   73067 
   73068   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
   73069   ** more frequent reallocs and hence provide more opportunities for
   73070   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
   73071   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
   73072   ** by the minimum* amount required until the size reaches 512.  Normal
   73073   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
   73074   ** size of the op array or add 1KB of space, whichever is smaller. */
   73075 #ifdef SQLITE_TEST_REALLOC_STRESS
   73076   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
   73077 #else
   73078   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
   73079   UNUSED_PARAMETER(nOp);
   73080 #endif
   73081 
   73082   /* Ensure that the size of a VDBE does not grow too large */
   73083   if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
   73084     sqlite3OomFault(p->db);
   73085     return SQLITE_NOMEM;
   73086   }
   73087 
   73088   assert( nOp<=(1024/sizeof(Op)) );
   73089   assert( nNew>=(p->nOpAlloc+nOp) );
   73090   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
   73091   if( pNew ){
   73092     p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
   73093     p->nOpAlloc = p->szOpAlloc/sizeof(Op);
   73094     v->aOp = pNew;
   73095   }
   73096   return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
   73097 }
   73098 
   73099 #ifdef SQLITE_DEBUG
   73100 /* This routine is just a convenient place to set a breakpoint that will
   73101 ** fire after each opcode is inserted and displayed using
   73102 ** "PRAGMA vdbe_addoptrace=on".
   73103 */
   73104 static void test_addop_breakpoint(void){
   73105   static int n = 0;
   73106   n++;
   73107 }
   73108 #endif
   73109 
   73110 /*
   73111 ** Add a new instruction to the list of instructions current in the
   73112 ** VDBE.  Return the address of the new instruction.
   73113 **
   73114 ** Parameters:
   73115 **
   73116 **    p               Pointer to the VDBE
   73117 **
   73118 **    op              The opcode for this instruction
   73119 **
   73120 **    p1, p2, p3      Operands
   73121 **
   73122 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   73123 ** the sqlite3VdbeChangeP4() function to change the value of the P4
   73124 ** operand.
   73125 */
   73126 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
   73127   assert( p->pParse->nOpAlloc<=p->nOp );
   73128   if( growOpArray(p, 1) ) return 1;
   73129   assert( p->pParse->nOpAlloc>p->nOp );
   73130   return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   73131 }
   73132 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   73133   int i;
   73134   VdbeOp *pOp;
   73135 
   73136   i = p->nOp;
   73137   assert( p->magic==VDBE_MAGIC_INIT );
   73138   assert( op>=0 && op<0xff );
   73139   if( p->pParse->nOpAlloc<=i ){
   73140     return growOp3(p, op, p1, p2, p3);
   73141   }
   73142   p->nOp++;
   73143   pOp = &p->aOp[i];
   73144   pOp->opcode = (u8)op;
   73145   pOp->p5 = 0;
   73146   pOp->p1 = p1;
   73147   pOp->p2 = p2;
   73148   pOp->p3 = p3;
   73149   pOp->p4.p = 0;
   73150   pOp->p4type = P4_NOTUSED;
   73151 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   73152   pOp->zComment = 0;
   73153 #endif
   73154 #ifdef SQLITE_DEBUG
   73155   if( p->db->flags & SQLITE_VdbeAddopTrace ){
   73156     int jj, kk;
   73157     Parse *pParse = p->pParse;
   73158     for(jj=kk=0; jj<pParse->nColCache; jj++){
   73159       struct yColCache *x = pParse->aColCache + jj;
   73160       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
   73161       kk++;
   73162     }
   73163     if( kk ) printf("\n");
   73164     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   73165     test_addop_breakpoint();
   73166   }
   73167 #endif
   73168 #ifdef VDBE_PROFILE
   73169   pOp->cycles = 0;
   73170   pOp->cnt = 0;
   73171 #endif
   73172 #ifdef SQLITE_VDBE_COVERAGE
   73173   pOp->iSrcLine = 0;
   73174 #endif
   73175   return i;
   73176 }
   73177 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
   73178   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   73179 }
   73180 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   73181   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
   73182 }
   73183 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
   73184   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
   73185 }
   73186 
   73187 /* Generate code for an unconditional jump to instruction iDest
   73188 */
   73189 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
   73190   return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
   73191 }
   73192 
   73193 /* Generate code to cause the string zStr to be loaded into
   73194 ** register iDest
   73195 */
   73196 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
   73197   return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
   73198 }
   73199 
   73200 /*
   73201 ** Generate code that initializes multiple registers to string or integer
   73202 ** constants.  The registers begin with iDest and increase consecutively.
   73203 ** One register is initialized for each characgter in zTypes[].  For each
   73204 ** "s" character in zTypes[], the register is a string if the argument is
   73205 ** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
   73206 ** in zTypes[], the register is initialized to an integer.
   73207 **
   73208 ** If the input string does not end with "X" then an OP_ResultRow instruction
   73209 ** is generated for the values inserted.
   73210 */
   73211 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
   73212   va_list ap;
   73213   int i;
   73214   char c;
   73215   va_start(ap, zTypes);
   73216   for(i=0; (c = zTypes[i])!=0; i++){
   73217     if( c=='s' ){
   73218       const char *z = va_arg(ap, const char*);
   73219       sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
   73220     }else if( c=='i' ){
   73221       sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
   73222     }else{
   73223       goto skip_op_resultrow;
   73224     }
   73225   }
   73226   sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
   73227 skip_op_resultrow:
   73228   va_end(ap);
   73229 }
   73230 
   73231 /*
   73232 ** Add an opcode that includes the p4 value as a pointer.
   73233 */
   73234 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
   73235   Vdbe *p,            /* Add the opcode to this VM */
   73236   int op,             /* The new opcode */
   73237   int p1,             /* The P1 operand */
   73238   int p2,             /* The P2 operand */
   73239   int p3,             /* The P3 operand */
   73240   const char *zP4,    /* The P4 operand */
   73241   int p4type          /* P4 operand type */
   73242 ){
   73243   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   73244   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
   73245   return addr;
   73246 }
   73247 
   73248 /*
   73249 ** Add an opcode that includes the p4 value with a P4_INT64 or
   73250 ** P4_REAL type.
   73251 */
   73252 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
   73253   Vdbe *p,            /* Add the opcode to this VM */
   73254   int op,             /* The new opcode */
   73255   int p1,             /* The P1 operand */
   73256   int p2,             /* The P2 operand */
   73257   int p3,             /* The P3 operand */
   73258   const u8 *zP4,      /* The P4 operand */
   73259   int p4type          /* P4 operand type */
   73260 ){
   73261   char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
   73262   if( p4copy ) memcpy(p4copy, zP4, 8);
   73263   return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
   73264 }
   73265 
   73266 /*
   73267 ** Add an OP_ParseSchema opcode.  This routine is broken out from
   73268 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
   73269 ** as having been used.
   73270 **
   73271 ** The zWhere string must have been obtained from sqlite3_malloc().
   73272 ** This routine will take ownership of the allocated memory.
   73273 */
   73274 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
   73275   int j;
   73276   sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
   73277   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
   73278 }
   73279 
   73280 /*
   73281 ** Add an opcode that includes the p4 value as an integer.
   73282 */
   73283 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
   73284   Vdbe *p,            /* Add the opcode to this VM */
   73285   int op,             /* The new opcode */
   73286   int p1,             /* The P1 operand */
   73287   int p2,             /* The P2 operand */
   73288   int p3,             /* The P3 operand */
   73289   int p4              /* The P4 operand as an integer */
   73290 ){
   73291   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   73292   if( p->db->mallocFailed==0 ){
   73293     VdbeOp *pOp = &p->aOp[addr];
   73294     pOp->p4type = P4_INT32;
   73295     pOp->p4.i = p4;
   73296   }
   73297   return addr;
   73298 }
   73299 
   73300 /* Insert the end of a co-routine
   73301 */
   73302 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
   73303   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
   73304 
   73305   /* Clear the temporary register cache, thereby ensuring that each
   73306   ** co-routine has its own independent set of registers, because co-routines
   73307   ** might expect their registers to be preserved across an OP_Yield, and
   73308   ** that could cause problems if two or more co-routines are using the same
   73309   ** temporary register.
   73310   */
   73311   v->pParse->nTempReg = 0;
   73312   v->pParse->nRangeReg = 0;
   73313 }
   73314 
   73315 /*
   73316 ** Create a new symbolic label for an instruction that has yet to be
   73317 ** coded.  The symbolic label is really just a negative number.  The
   73318 ** label can be used as the P2 value of an operation.  Later, when
   73319 ** the label is resolved to a specific address, the VDBE will scan
   73320 ** through its operation list and change all values of P2 which match
   73321 ** the label into the resolved address.
   73322 **
   73323 ** The VDBE knows that a P2 value is a label because labels are
   73324 ** always negative and P2 values are suppose to be non-negative.
   73325 ** Hence, a negative P2 value is a label that has yet to be resolved.
   73326 **
   73327 ** Zero is returned if a malloc() fails.
   73328 */
   73329 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
   73330   Parse *p = v->pParse;
   73331   int i = p->nLabel++;
   73332   assert( v->magic==VDBE_MAGIC_INIT );
   73333   if( (i & (i-1))==0 ){
   73334     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   73335                                        (i*2+1)*sizeof(p->aLabel[0]));
   73336   }
   73337   if( p->aLabel ){
   73338     p->aLabel[i] = -1;
   73339   }
   73340   return ADDR(i);
   73341 }
   73342 
   73343 /*
   73344 ** Resolve label "x" to be the address of the next instruction to
   73345 ** be inserted.  The parameter "x" must have been obtained from
   73346 ** a prior call to sqlite3VdbeMakeLabel().
   73347 */
   73348 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
   73349   Parse *p = v->pParse;
   73350   int j = ADDR(x);
   73351   assert( v->magic==VDBE_MAGIC_INIT );
   73352   assert( j<p->nLabel );
   73353   assert( j>=0 );
   73354   if( p->aLabel ){
   73355     p->aLabel[j] = v->nOp;
   73356   }
   73357 }
   73358 
   73359 /*
   73360 ** Mark the VDBE as one that can only be run one time.
   73361 */
   73362 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
   73363   p->runOnlyOnce = 1;
   73364 }
   73365 
   73366 /*
   73367 ** Mark the VDBE as one that can only be run multiple times.
   73368 */
   73369 SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
   73370   p->runOnlyOnce = 0;
   73371 }
   73372 
   73373 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
   73374 
   73375 /*
   73376 ** The following type and function are used to iterate through all opcodes
   73377 ** in a Vdbe main program and each of the sub-programs (triggers) it may
   73378 ** invoke directly or indirectly. It should be used as follows:
   73379 **
   73380 **   Op *pOp;
   73381 **   VdbeOpIter sIter;
   73382 **
   73383 **   memset(&sIter, 0, sizeof(sIter));
   73384 **   sIter.v = v;                            // v is of type Vdbe*
   73385 **   while( (pOp = opIterNext(&sIter)) ){
   73386 **     // Do something with pOp
   73387 **   }
   73388 **   sqlite3DbFree(v->db, sIter.apSub);
   73389 **
   73390 */
   73391 typedef struct VdbeOpIter VdbeOpIter;
   73392 struct VdbeOpIter {
   73393   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
   73394   SubProgram **apSub;        /* Array of subprograms */
   73395   int nSub;                  /* Number of entries in apSub */
   73396   int iAddr;                 /* Address of next instruction to return */
   73397   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
   73398 };
   73399 static Op *opIterNext(VdbeOpIter *p){
   73400   Vdbe *v = p->v;
   73401   Op *pRet = 0;
   73402   Op *aOp;
   73403   int nOp;
   73404 
   73405   if( p->iSub<=p->nSub ){
   73406 
   73407     if( p->iSub==0 ){
   73408       aOp = v->aOp;
   73409       nOp = v->nOp;
   73410     }else{
   73411       aOp = p->apSub[p->iSub-1]->aOp;
   73412       nOp = p->apSub[p->iSub-1]->nOp;
   73413     }
   73414     assert( p->iAddr<nOp );
   73415 
   73416     pRet = &aOp[p->iAddr];
   73417     p->iAddr++;
   73418     if( p->iAddr==nOp ){
   73419       p->iSub++;
   73420       p->iAddr = 0;
   73421     }
   73422 
   73423     if( pRet->p4type==P4_SUBPROGRAM ){
   73424       int nByte = (p->nSub+1)*sizeof(SubProgram*);
   73425       int j;
   73426       for(j=0; j<p->nSub; j++){
   73427         if( p->apSub[j]==pRet->p4.pProgram ) break;
   73428       }
   73429       if( j==p->nSub ){
   73430         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
   73431         if( !p->apSub ){
   73432           pRet = 0;
   73433         }else{
   73434           p->apSub[p->nSub++] = pRet->p4.pProgram;
   73435         }
   73436       }
   73437     }
   73438   }
   73439 
   73440   return pRet;
   73441 }
   73442 
   73443 /*
   73444 ** Check if the program stored in the VM associated with pParse may
   73445 ** throw an ABORT exception (causing the statement, but not entire transaction
   73446 ** to be rolled back). This condition is true if the main program or any
   73447 ** sub-programs contains any of the following:
   73448 **
   73449 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   73450 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   73451 **   *  OP_Destroy
   73452 **   *  OP_VUpdate
   73453 **   *  OP_VRename
   73454 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
   73455 **   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
   73456 **      (for CREATE TABLE AS SELECT ...)
   73457 **
   73458 ** Then check that the value of Parse.mayAbort is true if an
   73459 ** ABORT may be thrown, or false otherwise. Return true if it does
   73460 ** match, or false otherwise. This function is intended to be used as
   73461 ** part of an assert statement in the compiler. Similar to:
   73462 **
   73463 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
   73464 */
   73465 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
   73466   int hasAbort = 0;
   73467   int hasFkCounter = 0;
   73468   int hasCreateTable = 0;
   73469   int hasInitCoroutine = 0;
   73470   Op *pOp;
   73471   VdbeOpIter sIter;
   73472   memset(&sIter, 0, sizeof(sIter));
   73473   sIter.v = v;
   73474 
   73475   while( (pOp = opIterNext(&sIter))!=0 ){
   73476     int opcode = pOp->opcode;
   73477     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
   73478      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
   73479       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
   73480     ){
   73481       hasAbort = 1;
   73482       break;
   73483     }
   73484     if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
   73485     if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
   73486 #ifndef SQLITE_OMIT_FOREIGN_KEY
   73487     if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
   73488       hasFkCounter = 1;
   73489     }
   73490 #endif
   73491   }
   73492   sqlite3DbFree(v->db, sIter.apSub);
   73493 
   73494   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
   73495   ** If malloc failed, then the while() loop above may not have iterated
   73496   ** through all opcodes and hasAbort may be set incorrectly. Return
   73497   ** true for this case to prevent the assert() in the callers frame
   73498   ** from failing.  */
   73499   return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
   73500               || (hasCreateTable && hasInitCoroutine) );
   73501 }
   73502 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
   73503 
   73504 /*
   73505 ** This routine is called after all opcodes have been inserted.  It loops
   73506 ** through all the opcodes and fixes up some details.
   73507 **
   73508 ** (1) For each jump instruction with a negative P2 value (a label)
   73509 **     resolve the P2 value to an actual address.
   73510 **
   73511 ** (2) Compute the maximum number of arguments used by any SQL function
   73512 **     and store that value in *pMaxFuncArgs.
   73513 **
   73514 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
   73515 **     indicate what the prepared statement actually does.
   73516 **
   73517 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
   73518 **
   73519 ** (5) Reclaim the memory allocated for storing labels.
   73520 **
   73521 ** This routine will only function correctly if the mkopcodeh.tcl generator
   73522 ** script numbers the opcodes correctly.  Changes to this routine must be
   73523 ** coordinated with changes to mkopcodeh.tcl.
   73524 */
   73525 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   73526   int nMaxArgs = *pMaxFuncArgs;
   73527   Op *pOp;
   73528   Parse *pParse = p->pParse;
   73529   int *aLabel = pParse->aLabel;
   73530   p->readOnly = 1;
   73531   p->bIsReader = 0;
   73532   pOp = &p->aOp[p->nOp-1];
   73533   while(1){
   73534 
   73535     /* Only JUMP opcodes and the short list of special opcodes in the switch
   73536     ** below need to be considered.  The mkopcodeh.tcl generator script groups
   73537     ** all these opcodes together near the front of the opcode list.  Skip
   73538     ** any opcode that does not need processing by virtual of the fact that
   73539     ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
   73540     */
   73541     if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
   73542       /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
   73543       ** cases from this switch! */
   73544       switch( pOp->opcode ){
   73545         case OP_Transaction: {
   73546           if( pOp->p2!=0 ) p->readOnly = 0;
   73547           /* fall thru */
   73548         }
   73549         case OP_AutoCommit:
   73550         case OP_Savepoint: {
   73551           p->bIsReader = 1;
   73552           break;
   73553         }
   73554 #ifndef SQLITE_OMIT_WAL
   73555         case OP_Checkpoint:
   73556 #endif
   73557         case OP_Vacuum:
   73558         case OP_JournalMode: {
   73559           p->readOnly = 0;
   73560           p->bIsReader = 1;
   73561           break;
   73562         }
   73563         case OP_Next:
   73564         case OP_NextIfOpen:
   73565         case OP_SorterNext: {
   73566           pOp->p4.xAdvance = sqlite3BtreeNext;
   73567           pOp->p4type = P4_ADVANCE;
   73568           /* The code generator never codes any of these opcodes as a jump
   73569           ** to a label.  They are always coded as a jump backwards to a
   73570           ** known address */
   73571           assert( pOp->p2>=0 );
   73572           break;
   73573         }
   73574         case OP_Prev:
   73575         case OP_PrevIfOpen: {
   73576           pOp->p4.xAdvance = sqlite3BtreePrevious;
   73577           pOp->p4type = P4_ADVANCE;
   73578           /* The code generator never codes any of these opcodes as a jump
   73579           ** to a label.  They are always coded as a jump backwards to a
   73580           ** known address */
   73581           assert( pOp->p2>=0 );
   73582           break;
   73583         }
   73584 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73585         case OP_VUpdate: {
   73586           if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   73587           break;
   73588         }
   73589         case OP_VFilter: {
   73590           int n;
   73591           assert( (pOp - p->aOp) >= 3 );
   73592           assert( pOp[-1].opcode==OP_Integer );
   73593           n = pOp[-1].p1;
   73594           if( n>nMaxArgs ) nMaxArgs = n;
   73595           /* Fall through into the default case */
   73596         }
   73597 #endif
   73598         default: {
   73599           if( pOp->p2<0 ){
   73600             /* The mkopcodeh.tcl script has so arranged things that the only
   73601             ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
   73602             ** have non-negative values for P2. */
   73603             assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
   73604             assert( ADDR(pOp->p2)<pParse->nLabel );
   73605             pOp->p2 = aLabel[ADDR(pOp->p2)];
   73606           }
   73607           break;
   73608         }
   73609       }
   73610       /* The mkopcodeh.tcl script has so arranged things that the only
   73611       ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
   73612       ** have non-negative values for P2. */
   73613       assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
   73614     }
   73615     if( pOp==p->aOp ) break;
   73616     pOp--;
   73617   }
   73618   sqlite3DbFree(p->db, pParse->aLabel);
   73619   pParse->aLabel = 0;
   73620   pParse->nLabel = 0;
   73621   *pMaxFuncArgs = nMaxArgs;
   73622   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
   73623 }
   73624 
   73625 /*
   73626 ** Return the address of the next instruction to be inserted.
   73627 */
   73628 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
   73629   assert( p->magic==VDBE_MAGIC_INIT );
   73630   return p->nOp;
   73631 }
   73632 
   73633 /*
   73634 ** Verify that at least N opcode slots are available in p without
   73635 ** having to malloc for more space (except when compiled using
   73636 ** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
   73637 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
   73638 ** fail due to a OOM fault and hence that the return value from
   73639 ** sqlite3VdbeAddOpList() will always be non-NULL.
   73640 */
   73641 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
   73642 SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
   73643   assert( p->nOp + N <= p->pParse->nOpAlloc );
   73644 }
   73645 #endif
   73646 
   73647 /*
   73648 ** Verify that the VM passed as the only argument does not contain
   73649 ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
   73650 ** by code in pragma.c to ensure that the implementation of certain
   73651 ** pragmas comports with the flags specified in the mkpragmatab.tcl
   73652 ** script.
   73653 */
   73654 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
   73655 SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
   73656   int i;
   73657   for(i=0; i<p->nOp; i++){
   73658     assert( p->aOp[i].opcode!=OP_ResultRow );
   73659   }
   73660 }
   73661 #endif
   73662 
   73663 /*
   73664 ** This function returns a pointer to the array of opcodes associated with
   73665 ** the Vdbe passed as the first argument. It is the callers responsibility
   73666 ** to arrange for the returned array to be eventually freed using the
   73667 ** vdbeFreeOpArray() function.
   73668 **
   73669 ** Before returning, *pnOp is set to the number of entries in the returned
   73670 ** array. Also, *pnMaxArg is set to the larger of its current value and
   73671 ** the number of entries in the Vdbe.apArg[] array required to execute the
   73672 ** returned program.
   73673 */
   73674 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   73675   VdbeOp *aOp = p->aOp;
   73676   assert( aOp && !p->db->mallocFailed );
   73677 
   73678   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
   73679   assert( DbMaskAllZero(p->btreeMask) );
   73680 
   73681   resolveP2Values(p, pnMaxArg);
   73682   *pnOp = p->nOp;
   73683   p->aOp = 0;
   73684   return aOp;
   73685 }
   73686 
   73687 /*
   73688 ** Add a whole list of operations to the operation stack.  Return a
   73689 ** pointer to the first operation inserted.
   73690 **
   73691 ** Non-zero P2 arguments to jump instructions are automatically adjusted
   73692 ** so that the jump target is relative to the first operation inserted.
   73693 */
   73694 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
   73695   Vdbe *p,                     /* Add opcodes to the prepared statement */
   73696   int nOp,                     /* Number of opcodes to add */
   73697   VdbeOpList const *aOp,       /* The opcodes to be added */
   73698   int iLineno                  /* Source-file line number of first opcode */
   73699 ){
   73700   int i;
   73701   VdbeOp *pOut, *pFirst;
   73702   assert( nOp>0 );
   73703   assert( p->magic==VDBE_MAGIC_INIT );
   73704   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
   73705     return 0;
   73706   }
   73707   pFirst = pOut = &p->aOp[p->nOp];
   73708   for(i=0; i<nOp; i++, aOp++, pOut++){
   73709     pOut->opcode = aOp->opcode;
   73710     pOut->p1 = aOp->p1;
   73711     pOut->p2 = aOp->p2;
   73712     assert( aOp->p2>=0 );
   73713     if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
   73714       pOut->p2 += p->nOp;
   73715     }
   73716     pOut->p3 = aOp->p3;
   73717     pOut->p4type = P4_NOTUSED;
   73718     pOut->p4.p = 0;
   73719     pOut->p5 = 0;
   73720 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   73721     pOut->zComment = 0;
   73722 #endif
   73723 #ifdef SQLITE_VDBE_COVERAGE
   73724     pOut->iSrcLine = iLineno+i;
   73725 #else
   73726     (void)iLineno;
   73727 #endif
   73728 #ifdef SQLITE_DEBUG
   73729     if( p->db->flags & SQLITE_VdbeAddopTrace ){
   73730       sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
   73731     }
   73732 #endif
   73733   }
   73734   p->nOp += nOp;
   73735   return pFirst;
   73736 }
   73737 
   73738 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
   73739 /*
   73740 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
   73741 */
   73742 SQLITE_PRIVATE void sqlite3VdbeScanStatus(
   73743   Vdbe *p,                        /* VM to add scanstatus() to */
   73744   int addrExplain,                /* Address of OP_Explain (or 0) */
   73745   int addrLoop,                   /* Address of loop counter */
   73746   int addrVisit,                  /* Address of rows visited counter */
   73747   LogEst nEst,                    /* Estimated number of output rows */
   73748   const char *zName               /* Name of table or index being scanned */
   73749 ){
   73750   int nByte = (p->nScan+1) * sizeof(ScanStatus);
   73751   ScanStatus *aNew;
   73752   aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
   73753   if( aNew ){
   73754     ScanStatus *pNew = &aNew[p->nScan++];
   73755     pNew->addrExplain = addrExplain;
   73756     pNew->addrLoop = addrLoop;
   73757     pNew->addrVisit = addrVisit;
   73758     pNew->nEst = nEst;
   73759     pNew->zName = sqlite3DbStrDup(p->db, zName);
   73760     p->aScan = aNew;
   73761   }
   73762 }
   73763 #endif
   73764 
   73765 
   73766 /*
   73767 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
   73768 ** for a specific instruction.
   73769 */
   73770 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
   73771   sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
   73772 }
   73773 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
   73774   sqlite3VdbeGetOp(p,addr)->p1 = val;
   73775 }
   73776 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
   73777   sqlite3VdbeGetOp(p,addr)->p2 = val;
   73778 }
   73779 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
   73780   sqlite3VdbeGetOp(p,addr)->p3 = val;
   73781 }
   73782 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
   73783   assert( p->nOp>0 || p->db->mallocFailed );
   73784   if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
   73785 }
   73786 
   73787 /*
   73788 ** Change the P2 operand of instruction addr so that it points to
   73789 ** the address of the next instruction to be coded.
   73790 */
   73791 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   73792   sqlite3VdbeChangeP2(p, addr, p->nOp);
   73793 }
   73794 
   73795 
   73796 /*
   73797 ** If the input FuncDef structure is ephemeral, then free it.  If
   73798 ** the FuncDef is not ephermal, then do nothing.
   73799 */
   73800 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   73801   if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
   73802     sqlite3DbFreeNN(db, pDef);
   73803   }
   73804 }
   73805 
   73806 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
   73807 
   73808 /*
   73809 ** Delete a P4 value if necessary.
   73810 */
   73811 static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
   73812   if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
   73813   sqlite3DbFreeNN(db, p);
   73814 }
   73815 static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
   73816   freeEphemeralFunction(db, p->pFunc);
   73817  sqlite3DbFreeNN(db, p);
   73818 }
   73819 static void freeP4(sqlite3 *db, int p4type, void *p4){
   73820   assert( db );
   73821   switch( p4type ){
   73822     case P4_FUNCCTX: {
   73823       freeP4FuncCtx(db, (sqlite3_context*)p4);
   73824       break;
   73825     }
   73826     case P4_REAL:
   73827     case P4_INT64:
   73828     case P4_DYNAMIC:
   73829     case P4_DYNBLOB:
   73830     case P4_INTARRAY: {
   73831       sqlite3DbFree(db, p4);
   73832       break;
   73833     }
   73834     case P4_KEYINFO: {
   73835       if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
   73836       break;
   73837     }
   73838 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   73839     case P4_EXPR: {
   73840       sqlite3ExprDelete(db, (Expr*)p4);
   73841       break;
   73842     }
   73843 #endif
   73844     case P4_FUNCDEF: {
   73845       freeEphemeralFunction(db, (FuncDef*)p4);
   73846       break;
   73847     }
   73848     case P4_MEM: {
   73849       if( db->pnBytesFreed==0 ){
   73850         sqlite3ValueFree((sqlite3_value*)p4);
   73851       }else{
   73852         freeP4Mem(db, (Mem*)p4);
   73853       }
   73854       break;
   73855     }
   73856     case P4_VTAB : {
   73857       if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
   73858       break;
   73859     }
   73860   }
   73861 }
   73862 
   73863 /*
   73864 ** Free the space allocated for aOp and any p4 values allocated for the
   73865 ** opcodes contained within. If aOp is not NULL it is assumed to contain
   73866 ** nOp entries.
   73867 */
   73868 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   73869   if( aOp ){
   73870     Op *pOp;
   73871     for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
   73872       if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
   73873 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   73874       sqlite3DbFree(db, pOp->zComment);
   73875 #endif
   73876     }
   73877     sqlite3DbFreeNN(db, aOp);
   73878   }
   73879 }
   73880 
   73881 /*
   73882 ** Link the SubProgram object passed as the second argument into the linked
   73883 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
   73884 ** objects when the VM is no longer required.
   73885 */
   73886 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
   73887   p->pNext = pVdbe->pProgram;
   73888   pVdbe->pProgram = p;
   73889 }
   73890 
   73891 /*
   73892 ** Change the opcode at addr into OP_Noop
   73893 */
   73894 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
   73895   VdbeOp *pOp;
   73896   if( p->db->mallocFailed ) return 0;
   73897   assert( addr>=0 && addr<p->nOp );
   73898   pOp = &p->aOp[addr];
   73899   freeP4(p->db, pOp->p4type, pOp->p4.p);
   73900   pOp->p4type = P4_NOTUSED;
   73901   pOp->p4.z = 0;
   73902   pOp->opcode = OP_Noop;
   73903   return 1;
   73904 }
   73905 
   73906 /*
   73907 ** If the last opcode is "op" and it is not a jump destination,
   73908 ** then remove it.  Return true if and only if an opcode was removed.
   73909 */
   73910 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
   73911   if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
   73912     return sqlite3VdbeChangeToNoop(p, p->nOp-1);
   73913   }else{
   73914     return 0;
   73915   }
   73916 }
   73917 
   73918 /*
   73919 ** Change the value of the P4 operand for a specific instruction.
   73920 ** This routine is useful when a large program is loaded from a
   73921 ** static array using sqlite3VdbeAddOpList but we want to make a
   73922 ** few minor changes to the program.
   73923 **
   73924 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
   73925 ** the string is made into memory obtained from sqlite3_malloc().
   73926 ** A value of n==0 means copy bytes of zP4 up to and including the
   73927 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
   73928 **
   73929 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
   73930 ** to a string or structure that is guaranteed to exist for the lifetime of
   73931 ** the Vdbe. In these cases we can just copy the pointer.
   73932 **
   73933 ** If addr<0 then change P4 on the most recently inserted instruction.
   73934 */
   73935 static void SQLITE_NOINLINE vdbeChangeP4Full(
   73936   Vdbe *p,
   73937   Op *pOp,
   73938   const char *zP4,
   73939   int n
   73940 ){
   73941   if( pOp->p4type ){
   73942     freeP4(p->db, pOp->p4type, pOp->p4.p);
   73943     pOp->p4type = 0;
   73944     pOp->p4.p = 0;
   73945   }
   73946   if( n<0 ){
   73947     sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
   73948   }else{
   73949     if( n==0 ) n = sqlite3Strlen30(zP4);
   73950     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
   73951     pOp->p4type = P4_DYNAMIC;
   73952   }
   73953 }
   73954 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
   73955   Op *pOp;
   73956   sqlite3 *db;
   73957   assert( p!=0 );
   73958   db = p->db;
   73959   assert( p->magic==VDBE_MAGIC_INIT );
   73960   assert( p->aOp!=0 || db->mallocFailed );
   73961   if( db->mallocFailed ){
   73962     if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
   73963     return;
   73964   }
   73965   assert( p->nOp>0 );
   73966   assert( addr<p->nOp );
   73967   if( addr<0 ){
   73968     addr = p->nOp - 1;
   73969   }
   73970   pOp = &p->aOp[addr];
   73971   if( n>=0 || pOp->p4type ){
   73972     vdbeChangeP4Full(p, pOp, zP4, n);
   73973     return;
   73974   }
   73975   if( n==P4_INT32 ){
   73976     /* Note: this cast is safe, because the origin data point was an int
   73977     ** that was cast to a (const char *). */
   73978     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   73979     pOp->p4type = P4_INT32;
   73980   }else if( zP4!=0 ){
   73981     assert( n<0 );
   73982     pOp->p4.p = (void*)zP4;
   73983     pOp->p4type = (signed char)n;
   73984     if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
   73985   }
   73986 }
   73987 
   73988 /*
   73989 ** Change the P4 operand of the most recently coded instruction
   73990 ** to the value defined by the arguments.  This is a high-speed
   73991 ** version of sqlite3VdbeChangeP4().
   73992 **
   73993 ** The P4 operand must not have been previously defined.  And the new
   73994 ** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
   73995 ** those cases.
   73996 */
   73997 SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
   73998   VdbeOp *pOp;
   73999   assert( n!=P4_INT32 && n!=P4_VTAB );
   74000   assert( n<=0 );
   74001   if( p->db->mallocFailed ){
   74002     freeP4(p->db, n, pP4);
   74003   }else{
   74004     assert( pP4!=0 );
   74005     assert( p->nOp>0 );
   74006     pOp = &p->aOp[p->nOp-1];
   74007     assert( pOp->p4type==P4_NOTUSED );
   74008     pOp->p4type = n;
   74009     pOp->p4.p = pP4;
   74010   }
   74011 }
   74012 
   74013 /*
   74014 ** Set the P4 on the most recently added opcode to the KeyInfo for the
   74015 ** index given.
   74016 */
   74017 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
   74018   Vdbe *v = pParse->pVdbe;
   74019   KeyInfo *pKeyInfo;
   74020   assert( v!=0 );
   74021   assert( pIdx!=0 );
   74022   pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
   74023   if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
   74024 }
   74025 
   74026 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   74027 /*
   74028 ** Change the comment on the most recently coded instruction.  Or
   74029 ** insert a No-op and add the comment to that new instruction.  This
   74030 ** makes the code easier to read during debugging.  None of this happens
   74031 ** in a production build.
   74032 */
   74033 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
   74034   assert( p->nOp>0 || p->aOp==0 );
   74035   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   74036   if( p->nOp ){
   74037     assert( p->aOp );
   74038     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
   74039     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
   74040   }
   74041 }
   74042 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   74043   va_list ap;
   74044   if( p ){
   74045     va_start(ap, zFormat);
   74046     vdbeVComment(p, zFormat, ap);
   74047     va_end(ap);
   74048   }
   74049 }
   74050 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   74051   va_list ap;
   74052   if( p ){
   74053     sqlite3VdbeAddOp0(p, OP_Noop);
   74054     va_start(ap, zFormat);
   74055     vdbeVComment(p, zFormat, ap);
   74056     va_end(ap);
   74057   }
   74058 }
   74059 #endif  /* NDEBUG */
   74060 
   74061 #ifdef SQLITE_VDBE_COVERAGE
   74062 /*
   74063 ** Set the value if the iSrcLine field for the previously coded instruction.
   74064 */
   74065 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
   74066   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
   74067 }
   74068 #endif /* SQLITE_VDBE_COVERAGE */
   74069 
   74070 /*
   74071 ** Return the opcode for a given address.  If the address is -1, then
   74072 ** return the most recently inserted opcode.
   74073 **
   74074 ** If a memory allocation error has occurred prior to the calling of this
   74075 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   74076 ** is readable but not writable, though it is cast to a writable value.
   74077 ** The return of a dummy opcode allows the call to continue functioning
   74078 ** after an OOM fault without having to check to see if the return from
   74079 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
   74080 ** dummy will never be written to.  This is verified by code inspection and
   74081 ** by running with Valgrind.
   74082 */
   74083 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   74084   /* C89 specifies that the constant "dummy" will be initialized to all
   74085   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
   74086   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
   74087   assert( p->magic==VDBE_MAGIC_INIT );
   74088   if( addr<0 ){
   74089     addr = p->nOp - 1;
   74090   }
   74091   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   74092   if( p->db->mallocFailed ){
   74093     return (VdbeOp*)&dummy;
   74094   }else{
   74095     return &p->aOp[addr];
   74096   }
   74097 }
   74098 
   74099 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
   74100 /*
   74101 ** Return an integer value for one of the parameters to the opcode pOp
   74102 ** determined by character c.
   74103 */
   74104 static int translateP(char c, const Op *pOp){
   74105   if( c=='1' ) return pOp->p1;
   74106   if( c=='2' ) return pOp->p2;
   74107   if( c=='3' ) return pOp->p3;
   74108   if( c=='4' ) return pOp->p4.i;
   74109   return pOp->p5;
   74110 }
   74111 
   74112 /*
   74113 ** Compute a string for the "comment" field of a VDBE opcode listing.
   74114 **
   74115 ** The Synopsis: field in comments in the vdbe.c source file gets converted
   74116 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
   74117 ** absence of other comments, this synopsis becomes the comment on the opcode.
   74118 ** Some translation occurs:
   74119 **
   74120 **       "PX"      ->  "r[X]"
   74121 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
   74122 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
   74123 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
   74124 */
   74125 static int displayComment(
   74126   const Op *pOp,     /* The opcode to be commented */
   74127   const char *zP4,   /* Previously obtained value for P4 */
   74128   char *zTemp,       /* Write result here */
   74129   int nTemp          /* Space available in zTemp[] */
   74130 ){
   74131   const char *zOpName;
   74132   const char *zSynopsis;
   74133   int nOpName;
   74134   int ii, jj;
   74135   char zAlt[50];
   74136   zOpName = sqlite3OpcodeName(pOp->opcode);
   74137   nOpName = sqlite3Strlen30(zOpName);
   74138   if( zOpName[nOpName+1] ){
   74139     int seenCom = 0;
   74140     char c;
   74141     zSynopsis = zOpName += nOpName + 1;
   74142     if( strncmp(zSynopsis,"IF ",3)==0 ){
   74143       if( pOp->p5 & SQLITE_STOREP2 ){
   74144         sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
   74145       }else{
   74146         sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
   74147       }
   74148       zSynopsis = zAlt;
   74149     }
   74150     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
   74151       if( c=='P' ){
   74152         c = zSynopsis[++ii];
   74153         if( c=='4' ){
   74154           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
   74155         }else if( c=='X' ){
   74156           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
   74157           seenCom = 1;
   74158         }else{
   74159           int v1 = translateP(c, pOp);
   74160           int v2;
   74161           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
   74162           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
   74163             ii += 3;
   74164             jj += sqlite3Strlen30(zTemp+jj);
   74165             v2 = translateP(zSynopsis[ii], pOp);
   74166             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
   74167               ii += 2;
   74168               v2++;
   74169             }
   74170             if( v2>1 ){
   74171               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
   74172             }
   74173           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
   74174             ii += 4;
   74175           }
   74176         }
   74177         jj += sqlite3Strlen30(zTemp+jj);
   74178       }else{
   74179         zTemp[jj++] = c;
   74180       }
   74181     }
   74182     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
   74183       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
   74184       jj += sqlite3Strlen30(zTemp+jj);
   74185     }
   74186     if( jj<nTemp ) zTemp[jj] = 0;
   74187   }else if( pOp->zComment ){
   74188     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
   74189     jj = sqlite3Strlen30(zTemp);
   74190   }else{
   74191     zTemp[0] = 0;
   74192     jj = 0;
   74193   }
   74194   return jj;
   74195 }
   74196 #endif /* SQLITE_DEBUG */
   74197 
   74198 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
   74199 /*
   74200 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
   74201 ** that can be displayed in the P4 column of EXPLAIN output.
   74202 */
   74203 static void displayP4Expr(StrAccum *p, Expr *pExpr){
   74204   const char *zOp = 0;
   74205   switch( pExpr->op ){
   74206     case TK_STRING:
   74207       sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
   74208       break;
   74209     case TK_INTEGER:
   74210       sqlite3XPrintf(p, "%d", pExpr->u.iValue);
   74211       break;
   74212     case TK_NULL:
   74213       sqlite3XPrintf(p, "NULL");
   74214       break;
   74215     case TK_REGISTER: {
   74216       sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
   74217       break;
   74218     }
   74219     case TK_COLUMN: {
   74220       if( pExpr->iColumn<0 ){
   74221         sqlite3XPrintf(p, "rowid");
   74222       }else{
   74223         sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
   74224       }
   74225       break;
   74226     }
   74227     case TK_LT:      zOp = "LT";      break;
   74228     case TK_LE:      zOp = "LE";      break;
   74229     case TK_GT:      zOp = "GT";      break;
   74230     case TK_GE:      zOp = "GE";      break;
   74231     case TK_NE:      zOp = "NE";      break;
   74232     case TK_EQ:      zOp = "EQ";      break;
   74233     case TK_IS:      zOp = "IS";      break;
   74234     case TK_ISNOT:   zOp = "ISNOT";   break;
   74235     case TK_AND:     zOp = "AND";     break;
   74236     case TK_OR:      zOp = "OR";      break;
   74237     case TK_PLUS:    zOp = "ADD";     break;
   74238     case TK_STAR:    zOp = "MUL";     break;
   74239     case TK_MINUS:   zOp = "SUB";     break;
   74240     case TK_REM:     zOp = "REM";     break;
   74241     case TK_BITAND:  zOp = "BITAND";  break;
   74242     case TK_BITOR:   zOp = "BITOR";   break;
   74243     case TK_SLASH:   zOp = "DIV";     break;
   74244     case TK_LSHIFT:  zOp = "LSHIFT";  break;
   74245     case TK_RSHIFT:  zOp = "RSHIFT";  break;
   74246     case TK_CONCAT:  zOp = "CONCAT";  break;
   74247     case TK_UMINUS:  zOp = "MINUS";   break;
   74248     case TK_UPLUS:   zOp = "PLUS";    break;
   74249     case TK_BITNOT:  zOp = "BITNOT";  break;
   74250     case TK_NOT:     zOp = "NOT";     break;
   74251     case TK_ISNULL:  zOp = "ISNULL";  break;
   74252     case TK_NOTNULL: zOp = "NOTNULL"; break;
   74253 
   74254     default:
   74255       sqlite3XPrintf(p, "%s", "expr");
   74256       break;
   74257   }
   74258 
   74259   if( zOp ){
   74260     sqlite3XPrintf(p, "%s(", zOp);
   74261     displayP4Expr(p, pExpr->pLeft);
   74262     if( pExpr->pRight ){
   74263       sqlite3StrAccumAppend(p, ",", 1);
   74264       displayP4Expr(p, pExpr->pRight);
   74265     }
   74266     sqlite3StrAccumAppend(p, ")", 1);
   74267   }
   74268 }
   74269 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
   74270 
   74271 
   74272 #if VDBE_DISPLAY_P4
   74273 /*
   74274 ** Compute a string that describes the P4 parameter for an opcode.
   74275 ** Use zTemp for any required temporary buffer space.
   74276 */
   74277 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
   74278   char *zP4 = zTemp;
   74279   StrAccum x;
   74280   assert( nTemp>=20 );
   74281   sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
   74282   switch( pOp->p4type ){
   74283     case P4_KEYINFO: {
   74284       int j;
   74285       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
   74286       assert( pKeyInfo->aSortOrder!=0 );
   74287       sqlite3XPrintf(&x, "k(%d", pKeyInfo->nKeyField);
   74288       for(j=0; j<pKeyInfo->nKeyField; j++){
   74289         CollSeq *pColl = pKeyInfo->aColl[j];
   74290         const char *zColl = pColl ? pColl->zName : "";
   74291         if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
   74292         sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
   74293       }
   74294       sqlite3StrAccumAppend(&x, ")", 1);
   74295       break;
   74296     }
   74297 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   74298     case P4_EXPR: {
   74299       displayP4Expr(&x, pOp->p4.pExpr);
   74300       break;
   74301     }
   74302 #endif
   74303     case P4_COLLSEQ: {
   74304       CollSeq *pColl = pOp->p4.pColl;
   74305       sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
   74306       break;
   74307     }
   74308     case P4_FUNCDEF: {
   74309       FuncDef *pDef = pOp->p4.pFunc;
   74310       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
   74311       break;
   74312     }
   74313 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   74314     case P4_FUNCCTX: {
   74315       FuncDef *pDef = pOp->p4.pCtx->pFunc;
   74316       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
   74317       break;
   74318     }
   74319 #endif
   74320     case P4_INT64: {
   74321       sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
   74322       break;
   74323     }
   74324     case P4_INT32: {
   74325       sqlite3XPrintf(&x, "%d", pOp->p4.i);
   74326       break;
   74327     }
   74328     case P4_REAL: {
   74329       sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
   74330       break;
   74331     }
   74332     case P4_MEM: {
   74333       Mem *pMem = pOp->p4.pMem;
   74334       if( pMem->flags & MEM_Str ){
   74335         zP4 = pMem->z;
   74336       }else if( pMem->flags & MEM_Int ){
   74337         sqlite3XPrintf(&x, "%lld", pMem->u.i);
   74338       }else if( pMem->flags & MEM_Real ){
   74339         sqlite3XPrintf(&x, "%.16g", pMem->u.r);
   74340       }else if( pMem->flags & MEM_Null ){
   74341         zP4 = "NULL";
   74342       }else{
   74343         assert( pMem->flags & MEM_Blob );
   74344         zP4 = "(blob)";
   74345       }
   74346       break;
   74347     }
   74348 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74349     case P4_VTAB: {
   74350       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
   74351       sqlite3XPrintf(&x, "vtab:%p", pVtab);
   74352       break;
   74353     }
   74354 #endif
   74355     case P4_INTARRAY: {
   74356       int i;
   74357       int *ai = pOp->p4.ai;
   74358       int n = ai[0];   /* The first element of an INTARRAY is always the
   74359                        ** count of the number of elements to follow */
   74360       for(i=1; i<=n; i++){
   74361         sqlite3XPrintf(&x, ",%d", ai[i]);
   74362       }
   74363       zTemp[0] = '[';
   74364       sqlite3StrAccumAppend(&x, "]", 1);
   74365       break;
   74366     }
   74367     case P4_SUBPROGRAM: {
   74368       sqlite3XPrintf(&x, "program");
   74369       break;
   74370     }
   74371     case P4_DYNBLOB:
   74372     case P4_ADVANCE: {
   74373       zTemp[0] = 0;
   74374       break;
   74375     }
   74376     case P4_TABLE: {
   74377       sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
   74378       break;
   74379     }
   74380     default: {
   74381       zP4 = pOp->p4.z;
   74382       if( zP4==0 ){
   74383         zP4 = zTemp;
   74384         zTemp[0] = 0;
   74385       }
   74386     }
   74387   }
   74388   sqlite3StrAccumFinish(&x);
   74389   assert( zP4!=0 );
   74390   return zP4;
   74391 }
   74392 #endif /* VDBE_DISPLAY_P4 */
   74393 
   74394 /*
   74395 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   74396 **
   74397 ** The prepared statements need to know in advance the complete set of
   74398 ** attached databases that will be use.  A mask of these databases
   74399 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
   74400 ** p->btreeMask of databases that will require a lock.
   74401 */
   74402 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   74403   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
   74404   assert( i<(int)sizeof(p->btreeMask)*8 );
   74405   DbMaskSet(p->btreeMask, i);
   74406   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
   74407     DbMaskSet(p->lockMask, i);
   74408   }
   74409 }
   74410 
   74411 #if !defined(SQLITE_OMIT_SHARED_CACHE)
   74412 /*
   74413 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
   74414 ** this routine obtains the mutex associated with each BtShared structure
   74415 ** that may be accessed by the VM passed as an argument. In doing so it also
   74416 ** sets the BtShared.db member of each of the BtShared structures, ensuring
   74417 ** that the correct busy-handler callback is invoked if required.
   74418 **
   74419 ** If SQLite is not threadsafe but does support shared-cache mode, then
   74420 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
   74421 ** of all of BtShared structures accessible via the database handle
   74422 ** associated with the VM.
   74423 **
   74424 ** If SQLite is not threadsafe and does not support shared-cache mode, this
   74425 ** function is a no-op.
   74426 **
   74427 ** The p->btreeMask field is a bitmask of all btrees that the prepared
   74428 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
   74429 ** corresponding to btrees that use shared cache.  Then the runtime of
   74430 ** this routine is N*N.  But as N is rarely more than 1, this should not
   74431 ** be a problem.
   74432 */
   74433 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
   74434   int i;
   74435   sqlite3 *db;
   74436   Db *aDb;
   74437   int nDb;
   74438   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
   74439   db = p->db;
   74440   aDb = db->aDb;
   74441   nDb = db->nDb;
   74442   for(i=0; i<nDb; i++){
   74443     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
   74444       sqlite3BtreeEnter(aDb[i].pBt);
   74445     }
   74446   }
   74447 }
   74448 #endif
   74449 
   74450 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   74451 /*
   74452 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
   74453 */
   74454 static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
   74455   int i;
   74456   sqlite3 *db;
   74457   Db *aDb;
   74458   int nDb;
   74459   db = p->db;
   74460   aDb = db->aDb;
   74461   nDb = db->nDb;
   74462   for(i=0; i<nDb; i++){
   74463     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
   74464       sqlite3BtreeLeave(aDb[i].pBt);
   74465     }
   74466   }
   74467 }
   74468 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
   74469   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
   74470   vdbeLeave(p);
   74471 }
   74472 #endif
   74473 
   74474 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   74475 /*
   74476 ** Print a single opcode.  This routine is used for debugging only.
   74477 */
   74478 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   74479   char *zP4;
   74480   char zPtr[50];
   74481   char zCom[100];
   74482   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
   74483   if( pOut==0 ) pOut = stdout;
   74484   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
   74485 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   74486   displayComment(pOp, zP4, zCom, sizeof(zCom));
   74487 #else
   74488   zCom[0] = 0;
   74489 #endif
   74490   /* NB:  The sqlite3OpcodeName() function is implemented by code created
   74491   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
   74492   ** information from the vdbe.c source text */
   74493   fprintf(pOut, zFormat1, pc,
   74494       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
   74495       zCom
   74496   );
   74497   fflush(pOut);
   74498 }
   74499 #endif
   74500 
   74501 /*
   74502 ** Initialize an array of N Mem element.
   74503 */
   74504 static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
   74505   while( (N--)>0 ){
   74506     p->db = db;
   74507     p->flags = flags;
   74508     p->szMalloc = 0;
   74509 #ifdef SQLITE_DEBUG
   74510     p->pScopyFrom = 0;
   74511 #endif
   74512     p++;
   74513   }
   74514 }
   74515 
   74516 /*
   74517 ** Release an array of N Mem elements
   74518 */
   74519 static void releaseMemArray(Mem *p, int N){
   74520   if( p && N ){
   74521     Mem *pEnd = &p[N];
   74522     sqlite3 *db = p->db;
   74523     if( db->pnBytesFreed ){
   74524       do{
   74525         if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
   74526       }while( (++p)<pEnd );
   74527       return;
   74528     }
   74529     do{
   74530       assert( (&p[1])==pEnd || p[0].db==p[1].db );
   74531       assert( sqlite3VdbeCheckMemInvariants(p) );
   74532 
   74533       /* This block is really an inlined version of sqlite3VdbeMemRelease()
   74534       ** that takes advantage of the fact that the memory cell value is
   74535       ** being set to NULL after releasing any dynamic resources.
   74536       **
   74537       ** The justification for duplicating code is that according to
   74538       ** callgrind, this causes a certain test case to hit the CPU 4.7
   74539       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
   74540       ** sqlite3MemRelease() were called from here. With -O2, this jumps
   74541       ** to 6.6 percent. The test case is inserting 1000 rows into a table
   74542       ** with no indexes using a single prepared INSERT statement, bind()
   74543       ** and reset(). Inserts are grouped into a transaction.
   74544       */
   74545       testcase( p->flags & MEM_Agg );
   74546       testcase( p->flags & MEM_Dyn );
   74547       testcase( p->flags & MEM_Frame );
   74548       testcase( p->flags & MEM_RowSet );
   74549       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   74550         sqlite3VdbeMemRelease(p);
   74551       }else if( p->szMalloc ){
   74552         sqlite3DbFreeNN(db, p->zMalloc);
   74553         p->szMalloc = 0;
   74554       }
   74555 
   74556       p->flags = MEM_Undefined;
   74557     }while( (++p)<pEnd );
   74558   }
   74559 }
   74560 
   74561 /*
   74562 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
   74563 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
   74564 */
   74565 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
   74566   int i;
   74567   Mem *aMem = VdbeFrameMem(p);
   74568   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   74569   for(i=0; i<p->nChildCsr; i++){
   74570     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   74571   }
   74572   releaseMemArray(aMem, p->nChildMem);
   74573   sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
   74574   sqlite3DbFree(p->v->db, p);
   74575 }
   74576 
   74577 #ifndef SQLITE_OMIT_EXPLAIN
   74578 /*
   74579 ** Give a listing of the program in the virtual machine.
   74580 **
   74581 ** The interface is the same as sqlite3VdbeExec().  But instead of
   74582 ** running the code, it invokes the callback once for each instruction.
   74583 ** This feature is used to implement "EXPLAIN".
   74584 **
   74585 ** When p->explain==1, each instruction is listed.  When
   74586 ** p->explain==2, only OP_Explain instructions are listed and these
   74587 ** are shown in a different format.  p->explain==2 is used to implement
   74588 ** EXPLAIN QUERY PLAN.
   74589 **
   74590 ** When p->explain==1, first the main program is listed, then each of
   74591 ** the trigger subprograms are listed one by one.
   74592 */
   74593 SQLITE_PRIVATE int sqlite3VdbeList(
   74594   Vdbe *p                   /* The VDBE */
   74595 ){
   74596   int nRow;                            /* Stop when row count reaches this */
   74597   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   74598   SubProgram **apSub = 0;              /* Array of sub-vdbes */
   74599   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
   74600   sqlite3 *db = p->db;                 /* The database connection */
   74601   int i;                               /* Loop counter */
   74602   int rc = SQLITE_OK;                  /* Return code */
   74603   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
   74604   int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
   74605   Op *pOp = 0;
   74606 
   74607   assert( p->explain );
   74608   assert( p->magic==VDBE_MAGIC_RUN );
   74609   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   74610 
   74611   /* Even though this opcode does not use dynamic strings for
   74612   ** the result, result columns may become dynamic if the user calls
   74613   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   74614   */
   74615   releaseMemArray(pMem, 8);
   74616   p->pResultSet = 0;
   74617 
   74618   if( p->rc==SQLITE_NOMEM ){
   74619     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   74620     ** sqlite3_column_text16() failed.  */
   74621     sqlite3OomFault(db);
   74622     return SQLITE_ERROR;
   74623   }
   74624 
   74625   /* When the number of output rows reaches nRow, that means the
   74626   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
   74627   ** nRow is the sum of the number of rows in the main program, plus
   74628   ** the sum of the number of rows in all trigger subprograms encountered
   74629   ** so far.  The nRow value will increase as new trigger subprograms are
   74630   ** encountered, but p->pc will eventually catch up to nRow.
   74631   */
   74632   nRow = p->nOp;
   74633   if( bListSubprogs ){
   74634     /* The first 8 memory cells are used for the result set.  So we will
   74635     ** commandeer the 9th cell to use as storage for an array of pointers
   74636     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
   74637     ** cells.  */
   74638     assert( p->nMem>9 );
   74639     pSub = &p->aMem[9];
   74640     if( pSub->flags&MEM_Blob ){
   74641       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
   74642       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
   74643       nSub = pSub->n/sizeof(Vdbe*);
   74644       apSub = (SubProgram **)pSub->z;
   74645     }
   74646     for(i=0; i<nSub; i++){
   74647       nRow += apSub[i]->nOp;
   74648     }
   74649   }
   74650 
   74651   do{
   74652     i = p->pc++;
   74653     if( i>=nRow ){
   74654       p->rc = SQLITE_OK;
   74655       rc = SQLITE_DONE;
   74656       break;
   74657     }
   74658     if( i<p->nOp ){
   74659       /* The output line number is small enough that we are still in the
   74660       ** main program. */
   74661       pOp = &p->aOp[i];
   74662     }else{
   74663       /* We are currently listing subprograms.  Figure out which one and
   74664       ** pick up the appropriate opcode. */
   74665       int j;
   74666       i -= p->nOp;
   74667       for(j=0; i>=apSub[j]->nOp; j++){
   74668         i -= apSub[j]->nOp;
   74669       }
   74670       pOp = &apSub[j]->aOp[i];
   74671     }
   74672 
   74673     /* When an OP_Program opcode is encounter (the only opcode that has
   74674     ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
   74675     ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
   74676     ** has not already been seen.
   74677     */
   74678     if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
   74679       int nByte = (nSub+1)*sizeof(SubProgram*);
   74680       int j;
   74681       for(j=0; j<nSub; j++){
   74682         if( apSub[j]==pOp->p4.pProgram ) break;
   74683       }
   74684       if( j==nSub ){
   74685         p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
   74686         if( p->rc!=SQLITE_OK ){
   74687           rc = SQLITE_ERROR;
   74688           break;
   74689         }
   74690         apSub = (SubProgram **)pSub->z;
   74691         apSub[nSub++] = pOp->p4.pProgram;
   74692         pSub->flags |= MEM_Blob;
   74693         pSub->n = nSub*sizeof(SubProgram*);
   74694         nRow += pOp->p4.pProgram->nOp;
   74695       }
   74696     }
   74697   }while( p->explain==2 && pOp->opcode!=OP_Explain );
   74698 
   74699   if( rc==SQLITE_OK ){
   74700     if( db->u1.isInterrupted ){
   74701       p->rc = SQLITE_INTERRUPT;
   74702       rc = SQLITE_ERROR;
   74703       sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
   74704     }else{
   74705       char *zP4;
   74706       if( p->explain==1 ){
   74707         pMem->flags = MEM_Int;
   74708         pMem->u.i = i;                                /* Program counter */
   74709         pMem++;
   74710 
   74711         pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   74712         pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
   74713         assert( pMem->z!=0 );
   74714         pMem->n = sqlite3Strlen30(pMem->z);
   74715         pMem->enc = SQLITE_UTF8;
   74716         pMem++;
   74717       }
   74718 
   74719       pMem->flags = MEM_Int;
   74720       pMem->u.i = pOp->p1;                          /* P1 */
   74721       pMem++;
   74722 
   74723       pMem->flags = MEM_Int;
   74724       pMem->u.i = pOp->p2;                          /* P2 */
   74725       pMem++;
   74726 
   74727       pMem->flags = MEM_Int;
   74728       pMem->u.i = pOp->p3;                          /* P3 */
   74729       pMem++;
   74730 
   74731       if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
   74732         assert( p->db->mallocFailed );
   74733         return SQLITE_ERROR;
   74734       }
   74735       pMem->flags = MEM_Str|MEM_Term;
   74736       zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
   74737       if( zP4!=pMem->z ){
   74738         pMem->n = 0;
   74739         sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
   74740       }else{
   74741         assert( pMem->z!=0 );
   74742         pMem->n = sqlite3Strlen30(pMem->z);
   74743         pMem->enc = SQLITE_UTF8;
   74744       }
   74745       pMem++;
   74746 
   74747       if( p->explain==1 ){
   74748         if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
   74749           assert( p->db->mallocFailed );
   74750           return SQLITE_ERROR;
   74751         }
   74752         pMem->flags = MEM_Str|MEM_Term;
   74753         pMem->n = 2;
   74754         sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
   74755         pMem->enc = SQLITE_UTF8;
   74756         pMem++;
   74757 
   74758 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   74759         if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
   74760           assert( p->db->mallocFailed );
   74761           return SQLITE_ERROR;
   74762         }
   74763         pMem->flags = MEM_Str|MEM_Term;
   74764         pMem->n = displayComment(pOp, zP4, pMem->z, 500);
   74765         pMem->enc = SQLITE_UTF8;
   74766 #else
   74767         pMem->flags = MEM_Null;                       /* Comment */
   74768 #endif
   74769       }
   74770 
   74771       p->nResColumn = 8 - 4*(p->explain-1);
   74772       p->pResultSet = &p->aMem[1];
   74773       p->rc = SQLITE_OK;
   74774       rc = SQLITE_ROW;
   74775     }
   74776   }
   74777   return rc;
   74778 }
   74779 #endif /* SQLITE_OMIT_EXPLAIN */
   74780 
   74781 #ifdef SQLITE_DEBUG
   74782 /*
   74783 ** Print the SQL that was used to generate a VDBE program.
   74784 */
   74785 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
   74786   const char *z = 0;
   74787   if( p->zSql ){
   74788     z = p->zSql;
   74789   }else if( p->nOp>=1 ){
   74790     const VdbeOp *pOp = &p->aOp[0];
   74791     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
   74792       z = pOp->p4.z;
   74793       while( sqlite3Isspace(*z) ) z++;
   74794     }
   74795   }
   74796   if( z ) printf("SQL: [%s]\n", z);
   74797 }
   74798 #endif
   74799 
   74800 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   74801 /*
   74802 ** Print an IOTRACE message showing SQL content.
   74803 */
   74804 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
   74805   int nOp = p->nOp;
   74806   VdbeOp *pOp;
   74807   if( sqlite3IoTrace==0 ) return;
   74808   if( nOp<1 ) return;
   74809   pOp = &p->aOp[0];
   74810   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
   74811     int i, j;
   74812     char z[1000];
   74813     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
   74814     for(i=0; sqlite3Isspace(z[i]); i++){}
   74815     for(j=0; z[i]; i++){
   74816       if( sqlite3Isspace(z[i]) ){
   74817         if( z[i-1]!=' ' ){
   74818           z[j++] = ' ';
   74819         }
   74820       }else{
   74821         z[j++] = z[i];
   74822       }
   74823     }
   74824     z[j] = 0;
   74825     sqlite3IoTrace("SQL %s\n", z);
   74826   }
   74827 }
   74828 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   74829 
   74830 /* An instance of this object describes bulk memory available for use
   74831 ** by subcomponents of a prepared statement.  Space is allocated out
   74832 ** of a ReusableSpace object by the allocSpace() routine below.
   74833 */
   74834 struct ReusableSpace {
   74835   u8 *pSpace;          /* Available memory */
   74836   int nFree;           /* Bytes of available memory */
   74837   int nNeeded;         /* Total bytes that could not be allocated */
   74838 };
   74839 
   74840 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
   74841 ** from the ReusableSpace object.  Return a pointer to the allocated
   74842 ** memory on success.  If insufficient memory is available in the
   74843 ** ReusableSpace object, increase the ReusableSpace.nNeeded
   74844 ** value by the amount needed and return NULL.
   74845 **
   74846 ** If pBuf is not initially NULL, that means that the memory has already
   74847 ** been allocated by a prior call to this routine, so just return a copy
   74848 ** of pBuf and leave ReusableSpace unchanged.
   74849 **
   74850 ** This allocator is employed to repurpose unused slots at the end of the
   74851 ** opcode array of prepared state for other memory needs of the prepared
   74852 ** statement.
   74853 */
   74854 static void *allocSpace(
   74855   struct ReusableSpace *p,  /* Bulk memory available for allocation */
   74856   void *pBuf,               /* Pointer to a prior allocation */
   74857   int nByte                 /* Bytes of memory needed */
   74858 ){
   74859   assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
   74860   if( pBuf==0 ){
   74861     nByte = ROUND8(nByte);
   74862     if( nByte <= p->nFree ){
   74863       p->nFree -= nByte;
   74864       pBuf = &p->pSpace[p->nFree];
   74865     }else{
   74866       p->nNeeded += nByte;
   74867     }
   74868   }
   74869   assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
   74870   return pBuf;
   74871 }
   74872 
   74873 /*
   74874 ** Rewind the VDBE back to the beginning in preparation for
   74875 ** running it.
   74876 */
   74877 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
   74878 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   74879   int i;
   74880 #endif
   74881   assert( p!=0 );
   74882   assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
   74883 
   74884   /* There should be at least one opcode.
   74885   */
   74886   assert( p->nOp>0 );
   74887 
   74888   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
   74889   p->magic = VDBE_MAGIC_RUN;
   74890 
   74891 #ifdef SQLITE_DEBUG
   74892   for(i=0; i<p->nMem; i++){
   74893     assert( p->aMem[i].db==p->db );
   74894   }
   74895 #endif
   74896   p->pc = -1;
   74897   p->rc = SQLITE_OK;
   74898   p->errorAction = OE_Abort;
   74899   p->nChange = 0;
   74900   p->cacheCtr = 1;
   74901   p->minWriteFileFormat = 255;
   74902   p->iStatement = 0;
   74903   p->nFkConstraint = 0;
   74904 #ifdef VDBE_PROFILE
   74905   for(i=0; i<p->nOp; i++){
   74906     p->aOp[i].cnt = 0;
   74907     p->aOp[i].cycles = 0;
   74908   }
   74909 #endif
   74910 }
   74911 
   74912 /*
   74913 ** Prepare a virtual machine for execution for the first time after
   74914 ** creating the virtual machine.  This involves things such
   74915 ** as allocating registers and initializing the program counter.
   74916 ** After the VDBE has be prepped, it can be executed by one or more
   74917 ** calls to sqlite3VdbeExec().
   74918 **
   74919 ** This function may be called exactly once on each virtual machine.
   74920 ** After this routine is called the VM has been "packaged" and is ready
   74921 ** to run.  After this routine is called, further calls to
   74922 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
   74923 ** the Vdbe from the Parse object that helped generate it so that the
   74924 ** the Vdbe becomes an independent entity and the Parse object can be
   74925 ** destroyed.
   74926 **
   74927 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
   74928 ** to its initial state after it has been run.
   74929 */
   74930 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   74931   Vdbe *p,                       /* The VDBE */
   74932   Parse *pParse                  /* Parsing context */
   74933 ){
   74934   sqlite3 *db;                   /* The database connection */
   74935   int nVar;                      /* Number of parameters */
   74936   int nMem;                      /* Number of VM memory registers */
   74937   int nCursor;                   /* Number of cursors required */
   74938   int nArg;                      /* Number of arguments in subprograms */
   74939   int n;                         /* Loop counter */
   74940   struct ReusableSpace x;        /* Reusable bulk memory */
   74941 
   74942   assert( p!=0 );
   74943   assert( p->nOp>0 );
   74944   assert( pParse!=0 );
   74945   assert( p->magic==VDBE_MAGIC_INIT );
   74946   assert( pParse==p->pParse );
   74947   db = p->db;
   74948   assert( db->mallocFailed==0 );
   74949   nVar = pParse->nVar;
   74950   nMem = pParse->nMem;
   74951   nCursor = pParse->nTab;
   74952   nArg = pParse->nMaxArg;
   74953 
   74954   /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
   74955   ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
   74956   ** space at the end of aMem[] for cursors 1 and greater.
   74957   ** See also: allocateCursor().
   74958   */
   74959   nMem += nCursor;
   74960   if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
   74961 
   74962   /* Figure out how much reusable memory is available at the end of the
   74963   ** opcode array.  This extra memory will be reallocated for other elements
   74964   ** of the prepared statement.
   74965   */
   74966   n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
   74967   x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
   74968   assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
   74969   x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
   74970   assert( x.nFree>=0 );
   74971   assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
   74972 
   74973   resolveP2Values(p, &nArg);
   74974   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
   74975   if( pParse->explain && nMem<10 ){
   74976     nMem = 10;
   74977   }
   74978   p->expired = 0;
   74979 
   74980   /* Memory for registers, parameters, cursor, etc, is allocated in one or two
   74981   ** passes.  On the first pass, we try to reuse unused memory at the
   74982   ** end of the opcode array.  If we are unable to satisfy all memory
   74983   ** requirements by reusing the opcode array tail, then the second
   74984   ** pass will fill in the remainder using a fresh memory allocation.
   74985   **
   74986   ** This two-pass approach that reuses as much memory as possible from
   74987   ** the leftover memory at the end of the opcode array.  This can significantly
   74988   ** reduce the amount of memory held by a prepared statement.
   74989   */
   74990   do {
   74991     x.nNeeded = 0;
   74992     p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
   74993     p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
   74994     p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
   74995     p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
   74996 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   74997     p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
   74998 #endif
   74999     if( x.nNeeded==0 ) break;
   75000     x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
   75001     x.nFree = x.nNeeded;
   75002   }while( !db->mallocFailed );
   75003 
   75004   p->pVList = pParse->pVList;
   75005   pParse->pVList =  0;
   75006   p->explain = pParse->explain;
   75007   if( db->mallocFailed ){
   75008     p->nVar = 0;
   75009     p->nCursor = 0;
   75010     p->nMem = 0;
   75011   }else{
   75012     p->nCursor = nCursor;
   75013     p->nVar = (ynVar)nVar;
   75014     initMemArray(p->aVar, nVar, db, MEM_Null);
   75015     p->nMem = nMem;
   75016     initMemArray(p->aMem, nMem, db, MEM_Undefined);
   75017     memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
   75018 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   75019     memset(p->anExec, 0, p->nOp*sizeof(i64));
   75020 #endif
   75021   }
   75022   sqlite3VdbeRewind(p);
   75023 }
   75024 
   75025 /*
   75026 ** Close a VDBE cursor and release all the resources that cursor
   75027 ** happens to hold.
   75028 */
   75029 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   75030   if( pCx==0 ){
   75031     return;
   75032   }
   75033   assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
   75034   switch( pCx->eCurType ){
   75035     case CURTYPE_SORTER: {
   75036       sqlite3VdbeSorterClose(p->db, pCx);
   75037       break;
   75038     }
   75039     case CURTYPE_BTREE: {
   75040       if( pCx->isEphemeral ){
   75041         if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
   75042         /* The pCx->pCursor will be close automatically, if it exists, by
   75043         ** the call above. */
   75044       }else{
   75045         assert( pCx->uc.pCursor!=0 );
   75046         sqlite3BtreeCloseCursor(pCx->uc.pCursor);
   75047       }
   75048       break;
   75049     }
   75050 #ifndef SQLITE_OMIT_VIRTUALTABLE
   75051     case CURTYPE_VTAB: {
   75052       sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
   75053       const sqlite3_module *pModule = pVCur->pVtab->pModule;
   75054       assert( pVCur->pVtab->nRef>0 );
   75055       pVCur->pVtab->nRef--;
   75056       pModule->xClose(pVCur);
   75057       break;
   75058     }
   75059 #endif
   75060   }
   75061 }
   75062 
   75063 /*
   75064 ** Close all cursors in the current frame.
   75065 */
   75066 static void closeCursorsInFrame(Vdbe *p){
   75067   if( p->apCsr ){
   75068     int i;
   75069     for(i=0; i<p->nCursor; i++){
   75070       VdbeCursor *pC = p->apCsr[i];
   75071       if( pC ){
   75072         sqlite3VdbeFreeCursor(p, pC);
   75073         p->apCsr[i] = 0;
   75074       }
   75075     }
   75076   }
   75077 }
   75078 
   75079 /*
   75080 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
   75081 ** is used, for example, when a trigger sub-program is halted to restore
   75082 ** control to the main program.
   75083 */
   75084 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
   75085   Vdbe *v = pFrame->v;
   75086   closeCursorsInFrame(v);
   75087 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   75088   v->anExec = pFrame->anExec;
   75089 #endif
   75090   v->aOp = pFrame->aOp;
   75091   v->nOp = pFrame->nOp;
   75092   v->aMem = pFrame->aMem;
   75093   v->nMem = pFrame->nMem;
   75094   v->apCsr = pFrame->apCsr;
   75095   v->nCursor = pFrame->nCursor;
   75096   v->db->lastRowid = pFrame->lastRowid;
   75097   v->nChange = pFrame->nChange;
   75098   v->db->nChange = pFrame->nDbChange;
   75099   sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
   75100   v->pAuxData = pFrame->pAuxData;
   75101   pFrame->pAuxData = 0;
   75102   return pFrame->pc;
   75103 }
   75104 
   75105 /*
   75106 ** Close all cursors.
   75107 **
   75108 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
   75109 ** cell array. This is necessary as the memory cell array may contain
   75110 ** pointers to VdbeFrame objects, which may in turn contain pointers to
   75111 ** open cursors.
   75112 */
   75113 static void closeAllCursors(Vdbe *p){
   75114   if( p->pFrame ){
   75115     VdbeFrame *pFrame;
   75116     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   75117     sqlite3VdbeFrameRestore(pFrame);
   75118     p->pFrame = 0;
   75119     p->nFrame = 0;
   75120   }
   75121   assert( p->nFrame==0 );
   75122   closeCursorsInFrame(p);
   75123   if( p->aMem ){
   75124     releaseMemArray(p->aMem, p->nMem);
   75125   }
   75126   while( p->pDelFrame ){
   75127     VdbeFrame *pDel = p->pDelFrame;
   75128     p->pDelFrame = pDel->pParent;
   75129     sqlite3VdbeFrameDelete(pDel);
   75130   }
   75131 
   75132   /* Delete any auxdata allocations made by the VM */
   75133   if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
   75134   assert( p->pAuxData==0 );
   75135 }
   75136 
   75137 /*
   75138 ** Set the number of result columns that will be returned by this SQL
   75139 ** statement. This is now set at compile time, rather than during
   75140 ** execution of the vdbe program so that sqlite3_column_count() can
   75141 ** be called on an SQL statement before sqlite3_step().
   75142 */
   75143 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
   75144   int n;
   75145   sqlite3 *db = p->db;
   75146 
   75147   if( p->nResColumn ){
   75148     releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   75149     sqlite3DbFree(db, p->aColName);
   75150   }
   75151   n = nResColumn*COLNAME_N;
   75152   p->nResColumn = (u16)nResColumn;
   75153   p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
   75154   if( p->aColName==0 ) return;
   75155   initMemArray(p->aColName, n, db, MEM_Null);
   75156 }
   75157 
   75158 /*
   75159 ** Set the name of the idx'th column to be returned by the SQL statement.
   75160 ** zName must be a pointer to a nul terminated string.
   75161 **
   75162 ** This call must be made after a call to sqlite3VdbeSetNumCols().
   75163 **
   75164 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
   75165 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
   75166 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
   75167 */
   75168 SQLITE_PRIVATE int sqlite3VdbeSetColName(
   75169   Vdbe *p,                         /* Vdbe being configured */
   75170   int idx,                         /* Index of column zName applies to */
   75171   int var,                         /* One of the COLNAME_* constants */
   75172   const char *zName,               /* Pointer to buffer containing name */
   75173   void (*xDel)(void*)              /* Memory management strategy for zName */
   75174 ){
   75175   int rc;
   75176   Mem *pColName;
   75177   assert( idx<p->nResColumn );
   75178   assert( var<COLNAME_N );
   75179   if( p->db->mallocFailed ){
   75180     assert( !zName || xDel!=SQLITE_DYNAMIC );
   75181     return SQLITE_NOMEM_BKPT;
   75182   }
   75183   assert( p->aColName!=0 );
   75184   pColName = &(p->aColName[idx+var*p->nResColumn]);
   75185   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
   75186   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
   75187   return rc;
   75188 }
   75189 
   75190 /*
   75191 ** A read or write transaction may or may not be active on database handle
   75192 ** db. If a transaction is active, commit it. If there is a
   75193 ** write-transaction spanning more than one database file, this routine
   75194 ** takes care of the master journal trickery.
   75195 */
   75196 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   75197   int i;
   75198   int nTrans = 0;  /* Number of databases with an active write-transaction
   75199                    ** that are candidates for a two-phase commit using a
   75200                    ** master-journal */
   75201   int rc = SQLITE_OK;
   75202   int needXcommit = 0;
   75203 
   75204 #ifdef SQLITE_OMIT_VIRTUALTABLE
   75205   /* With this option, sqlite3VtabSync() is defined to be simply
   75206   ** SQLITE_OK so p is not used.
   75207   */
   75208   UNUSED_PARAMETER(p);
   75209 #endif
   75210 
   75211   /* Before doing anything else, call the xSync() callback for any
   75212   ** virtual module tables written in this transaction. This has to
   75213   ** be done before determining whether a master journal file is
   75214   ** required, as an xSync() callback may add an attached database
   75215   ** to the transaction.
   75216   */
   75217   rc = sqlite3VtabSync(db, p);
   75218 
   75219   /* This loop determines (a) if the commit hook should be invoked and
   75220   ** (b) how many database files have open write transactions, not
   75221   ** including the temp database. (b) is important because if more than
   75222   ** one database file has an open write transaction, a master journal
   75223   ** file is required for an atomic commit.
   75224   */
   75225   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   75226     Btree *pBt = db->aDb[i].pBt;
   75227     if( sqlite3BtreeIsInTrans(pBt) ){
   75228       /* Whether or not a database might need a master journal depends upon
   75229       ** its journal mode (among other things).  This matrix determines which
   75230       ** journal modes use a master journal and which do not */
   75231       static const u8 aMJNeeded[] = {
   75232         /* DELETE   */  1,
   75233         /* PERSIST   */ 1,
   75234         /* OFF       */ 0,
   75235         /* TRUNCATE  */ 1,
   75236         /* MEMORY    */ 0,
   75237         /* WAL       */ 0
   75238       };
   75239       Pager *pPager;   /* Pager associated with pBt */
   75240       needXcommit = 1;
   75241       sqlite3BtreeEnter(pBt);
   75242       pPager = sqlite3BtreePager(pBt);
   75243       if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
   75244        && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
   75245        && sqlite3PagerIsMemdb(pPager)==0
   75246       ){
   75247         assert( i!=1 );
   75248         nTrans++;
   75249       }
   75250       rc = sqlite3PagerExclusiveLock(pPager);
   75251       sqlite3BtreeLeave(pBt);
   75252     }
   75253   }
   75254   if( rc!=SQLITE_OK ){
   75255     return rc;
   75256   }
   75257 
   75258   /* If there are any write-transactions at all, invoke the commit hook */
   75259   if( needXcommit && db->xCommitCallback ){
   75260     rc = db->xCommitCallback(db->pCommitArg);
   75261     if( rc ){
   75262       return SQLITE_CONSTRAINT_COMMITHOOK;
   75263     }
   75264   }
   75265 
   75266   /* The simple case - no more than one database file (not counting the
   75267   ** TEMP database) has a transaction active.   There is no need for the
   75268   ** master-journal.
   75269   **
   75270   ** If the return value of sqlite3BtreeGetFilename() is a zero length
   75271   ** string, it means the main database is :memory: or a temp file.  In
   75272   ** that case we do not support atomic multi-file commits, so use the
   75273   ** simple case then too.
   75274   */
   75275   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   75276    || nTrans<=1
   75277   ){
   75278     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   75279       Btree *pBt = db->aDb[i].pBt;
   75280       if( pBt ){
   75281         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
   75282       }
   75283     }
   75284 
   75285     /* Do the commit only if all databases successfully complete phase 1.
   75286     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
   75287     ** IO error while deleting or truncating a journal file. It is unlikely,
   75288     ** but could happen. In this case abandon processing and return the error.
   75289     */
   75290     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   75291       Btree *pBt = db->aDb[i].pBt;
   75292       if( pBt ){
   75293         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
   75294       }
   75295     }
   75296     if( rc==SQLITE_OK ){
   75297       sqlite3VtabCommit(db);
   75298     }
   75299   }
   75300 
   75301   /* The complex case - There is a multi-file write-transaction active.
   75302   ** This requires a master journal file to ensure the transaction is
   75303   ** committed atomically.
   75304   */
   75305 #ifndef SQLITE_OMIT_DISKIO
   75306   else{
   75307     sqlite3_vfs *pVfs = db->pVfs;
   75308     char *zMaster = 0;   /* File-name for the master journal */
   75309     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
   75310     sqlite3_file *pMaster = 0;
   75311     i64 offset = 0;
   75312     int res;
   75313     int retryCount = 0;
   75314     int nMainFile;
   75315 
   75316     /* Select a master journal file name */
   75317     nMainFile = sqlite3Strlen30(zMainFile);
   75318     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
   75319     if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
   75320     do {
   75321       u32 iRandom;
   75322       if( retryCount ){
   75323         if( retryCount>100 ){
   75324           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
   75325           sqlite3OsDelete(pVfs, zMaster, 0);
   75326           break;
   75327         }else if( retryCount==1 ){
   75328           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
   75329         }
   75330       }
   75331       retryCount++;
   75332       sqlite3_randomness(sizeof(iRandom), &iRandom);
   75333       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
   75334                                (iRandom>>8)&0xffffff, iRandom&0xff);
   75335       /* The antipenultimate character of the master journal name must
   75336       ** be "9" to avoid name collisions when using 8+3 filenames. */
   75337       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
   75338       sqlite3FileSuffix3(zMainFile, zMaster);
   75339       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   75340     }while( rc==SQLITE_OK && res );
   75341     if( rc==SQLITE_OK ){
   75342       /* Open the master journal. */
   75343       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
   75344           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   75345           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
   75346       );
   75347     }
   75348     if( rc!=SQLITE_OK ){
   75349       sqlite3DbFree(db, zMaster);
   75350       return rc;
   75351     }
   75352 
   75353     /* Write the name of each database file in the transaction into the new
   75354     ** master journal file. If an error occurs at this point close
   75355     ** and delete the master journal file. All the individual journal files
   75356     ** still have 'null' as the master journal pointer, so they will roll
   75357     ** back independently if a failure occurs.
   75358     */
   75359     for(i=0; i<db->nDb; i++){
   75360       Btree *pBt = db->aDb[i].pBt;
   75361       if( sqlite3BtreeIsInTrans(pBt) ){
   75362         char const *zFile = sqlite3BtreeGetJournalname(pBt);
   75363         if( zFile==0 ){
   75364           continue;  /* Ignore TEMP and :memory: databases */
   75365         }
   75366         assert( zFile[0]!=0 );
   75367         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
   75368         offset += sqlite3Strlen30(zFile)+1;
   75369         if( rc!=SQLITE_OK ){
   75370           sqlite3OsCloseFree(pMaster);
   75371           sqlite3OsDelete(pVfs, zMaster, 0);
   75372           sqlite3DbFree(db, zMaster);
   75373           return rc;
   75374         }
   75375       }
   75376     }
   75377 
   75378     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
   75379     ** flag is set this is not required.
   75380     */
   75381     if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
   75382      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
   75383     ){
   75384       sqlite3OsCloseFree(pMaster);
   75385       sqlite3OsDelete(pVfs, zMaster, 0);
   75386       sqlite3DbFree(db, zMaster);
   75387       return rc;
   75388     }
   75389 
   75390     /* Sync all the db files involved in the transaction. The same call
   75391     ** sets the master journal pointer in each individual journal. If
   75392     ** an error occurs here, do not delete the master journal file.
   75393     **
   75394     ** If the error occurs during the first call to
   75395     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
   75396     ** master journal file will be orphaned. But we cannot delete it,
   75397     ** in case the master journal file name was written into the journal
   75398     ** file before the failure occurred.
   75399     */
   75400     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   75401       Btree *pBt = db->aDb[i].pBt;
   75402       if( pBt ){
   75403         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
   75404       }
   75405     }
   75406     sqlite3OsCloseFree(pMaster);
   75407     assert( rc!=SQLITE_BUSY );
   75408     if( rc!=SQLITE_OK ){
   75409       sqlite3DbFree(db, zMaster);
   75410       return rc;
   75411     }
   75412 
   75413     /* Delete the master journal file. This commits the transaction. After
   75414     ** doing this the directory is synced again before any individual
   75415     ** transaction files are deleted.
   75416     */
   75417     rc = sqlite3OsDelete(pVfs, zMaster, 1);
   75418     sqlite3DbFree(db, zMaster);
   75419     zMaster = 0;
   75420     if( rc ){
   75421       return rc;
   75422     }
   75423 
   75424     /* All files and directories have already been synced, so the following
   75425     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
   75426     ** deleting or truncating journals. If something goes wrong while
   75427     ** this is happening we don't really care. The integrity of the
   75428     ** transaction is already guaranteed, but some stray 'cold' journals
   75429     ** may be lying around. Returning an error code won't help matters.
   75430     */
   75431     disable_simulated_io_errors();
   75432     sqlite3BeginBenignMalloc();
   75433     for(i=0; i<db->nDb; i++){
   75434       Btree *pBt = db->aDb[i].pBt;
   75435       if( pBt ){
   75436         sqlite3BtreeCommitPhaseTwo(pBt, 1);
   75437       }
   75438     }
   75439     sqlite3EndBenignMalloc();
   75440     enable_simulated_io_errors();
   75441 
   75442     sqlite3VtabCommit(db);
   75443   }
   75444 #endif
   75445 
   75446   return rc;
   75447 }
   75448 
   75449 /*
   75450 ** This routine checks that the sqlite3.nVdbeActive count variable
   75451 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
   75452 ** currently active. An assertion fails if the two counts do not match.
   75453 ** This is an internal self-check only - it is not an essential processing
   75454 ** step.
   75455 **
   75456 ** This is a no-op if NDEBUG is defined.
   75457 */
   75458 #ifndef NDEBUG
   75459 static void checkActiveVdbeCnt(sqlite3 *db){
   75460   Vdbe *p;
   75461   int cnt = 0;
   75462   int nWrite = 0;
   75463   int nRead = 0;
   75464   p = db->pVdbe;
   75465   while( p ){
   75466     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
   75467       cnt++;
   75468       if( p->readOnly==0 ) nWrite++;
   75469       if( p->bIsReader ) nRead++;
   75470     }
   75471     p = p->pNext;
   75472   }
   75473   assert( cnt==db->nVdbeActive );
   75474   assert( nWrite==db->nVdbeWrite );
   75475   assert( nRead==db->nVdbeRead );
   75476 }
   75477 #else
   75478 #define checkActiveVdbeCnt(x)
   75479 #endif
   75480 
   75481 /*
   75482 ** If the Vdbe passed as the first argument opened a statement-transaction,
   75483 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
   75484 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
   75485 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
   75486 ** statement transaction is committed.
   75487 **
   75488 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
   75489 ** Otherwise SQLITE_OK.
   75490 */
   75491 static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
   75492   sqlite3 *const db = p->db;
   75493   int rc = SQLITE_OK;
   75494   int i;
   75495   const int iSavepoint = p->iStatement-1;
   75496 
   75497   assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
   75498   assert( db->nStatement>0 );
   75499   assert( p->iStatement==(db->nStatement+db->nSavepoint) );
   75500 
   75501   for(i=0; i<db->nDb; i++){
   75502     int rc2 = SQLITE_OK;
   75503     Btree *pBt = db->aDb[i].pBt;
   75504     if( pBt ){
   75505       if( eOp==SAVEPOINT_ROLLBACK ){
   75506         rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
   75507       }
   75508       if( rc2==SQLITE_OK ){
   75509         rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
   75510       }
   75511       if( rc==SQLITE_OK ){
   75512         rc = rc2;
   75513       }
   75514     }
   75515   }
   75516   db->nStatement--;
   75517   p->iStatement = 0;
   75518 
   75519   if( rc==SQLITE_OK ){
   75520     if( eOp==SAVEPOINT_ROLLBACK ){
   75521       rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
   75522     }
   75523     if( rc==SQLITE_OK ){
   75524       rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
   75525     }
   75526   }
   75527 
   75528   /* If the statement transaction is being rolled back, also restore the
   75529   ** database handles deferred constraint counter to the value it had when
   75530   ** the statement transaction was opened.  */
   75531   if( eOp==SAVEPOINT_ROLLBACK ){
   75532     db->nDeferredCons = p->nStmtDefCons;
   75533     db->nDeferredImmCons = p->nStmtDefImmCons;
   75534   }
   75535   return rc;
   75536 }
   75537 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
   75538   if( p->db->nStatement && p->iStatement ){
   75539     return vdbeCloseStatement(p, eOp);
   75540   }
   75541   return SQLITE_OK;
   75542 }
   75543 
   75544 
   75545 /*
   75546 ** This function is called when a transaction opened by the database
   75547 ** handle associated with the VM passed as an argument is about to be
   75548 ** committed. If there are outstanding deferred foreign key constraint
   75549 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
   75550 **
   75551 ** If there are outstanding FK violations and this function returns
   75552 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
   75553 ** and write an error message to it. Then return SQLITE_ERROR.
   75554 */
   75555 #ifndef SQLITE_OMIT_FOREIGN_KEY
   75556 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   75557   sqlite3 *db = p->db;
   75558   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
   75559    || (!deferred && p->nFkConstraint>0)
   75560   ){
   75561     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
   75562     p->errorAction = OE_Abort;
   75563     sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
   75564     return SQLITE_ERROR;
   75565   }
   75566   return SQLITE_OK;
   75567 }
   75568 #endif
   75569 
   75570 /*
   75571 ** This routine is called the when a VDBE tries to halt.  If the VDBE
   75572 ** has made changes and is in autocommit mode, then commit those
   75573 ** changes.  If a rollback is needed, then do the rollback.
   75574 **
   75575 ** This routine is the only way to move the state of a VM from
   75576 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
   75577 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
   75578 **
   75579 ** Return an error code.  If the commit could not complete because of
   75580 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
   75581 ** means the close did not happen and needs to be repeated.
   75582 */
   75583 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   75584   int rc;                         /* Used to store transient return codes */
   75585   sqlite3 *db = p->db;
   75586 
   75587   /* This function contains the logic that determines if a statement or
   75588   ** transaction will be committed or rolled back as a result of the
   75589   ** execution of this virtual machine.
   75590   **
   75591   ** If any of the following errors occur:
   75592   **
   75593   **     SQLITE_NOMEM
   75594   **     SQLITE_IOERR
   75595   **     SQLITE_FULL
   75596   **     SQLITE_INTERRUPT
   75597   **
   75598   ** Then the internal cache might have been left in an inconsistent
   75599   ** state.  We need to rollback the statement transaction, if there is
   75600   ** one, or the complete transaction if there is no statement transaction.
   75601   */
   75602 
   75603   if( p->magic!=VDBE_MAGIC_RUN ){
   75604     return SQLITE_OK;
   75605   }
   75606   if( db->mallocFailed ){
   75607     p->rc = SQLITE_NOMEM_BKPT;
   75608   }
   75609   closeAllCursors(p);
   75610   checkActiveVdbeCnt(db);
   75611 
   75612   /* No commit or rollback needed if the program never started or if the
   75613   ** SQL statement does not read or write a database file.  */
   75614   if( p->pc>=0 && p->bIsReader ){
   75615     int mrc;   /* Primary error code from p->rc */
   75616     int eStatementOp = 0;
   75617     int isSpecialError;            /* Set to true if a 'special' error */
   75618 
   75619     /* Lock all btrees used by the statement */
   75620     sqlite3VdbeEnter(p);
   75621 
   75622     /* Check for one of the special errors */
   75623     mrc = p->rc & 0xff;
   75624     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
   75625                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
   75626     if( isSpecialError ){
   75627       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
   75628       ** no rollback is necessary. Otherwise, at least a savepoint
   75629       ** transaction must be rolled back to restore the database to a
   75630       ** consistent state.
   75631       **
   75632       ** Even if the statement is read-only, it is important to perform
   75633       ** a statement or transaction rollback operation. If the error
   75634       ** occurred while writing to the journal, sub-journal or database
   75635       ** file as part of an effort to free up cache space (see function
   75636       ** pagerStress() in pager.c), the rollback is required to restore
   75637       ** the pager to a consistent state.
   75638       */
   75639       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
   75640         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
   75641           eStatementOp = SAVEPOINT_ROLLBACK;
   75642         }else{
   75643           /* We are forced to roll back the active transaction. Before doing
   75644           ** so, abort any other statements this handle currently has active.
   75645           */
   75646           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   75647           sqlite3CloseSavepoints(db);
   75648           db->autoCommit = 1;
   75649           p->nChange = 0;
   75650         }
   75651       }
   75652     }
   75653 
   75654     /* Check for immediate foreign key violations. */
   75655     if( p->rc==SQLITE_OK ){
   75656       sqlite3VdbeCheckFk(p, 0);
   75657     }
   75658 
   75659     /* If the auto-commit flag is set and this is the only active writer
   75660     ** VM, then we do either a commit or rollback of the current transaction.
   75661     **
   75662     ** Note: This block also runs if one of the special errors handled
   75663     ** above has occurred.
   75664     */
   75665     if( !sqlite3VtabInSync(db)
   75666      && db->autoCommit
   75667      && db->nVdbeWrite==(p->readOnly==0)
   75668     ){
   75669       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
   75670         rc = sqlite3VdbeCheckFk(p, 1);
   75671         if( rc!=SQLITE_OK ){
   75672           if( NEVER(p->readOnly) ){
   75673             sqlite3VdbeLeave(p);
   75674             return SQLITE_ERROR;
   75675           }
   75676           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
   75677         }else{
   75678           /* The auto-commit flag is true, the vdbe program was successful
   75679           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
   75680           ** key constraints to hold up the transaction. This means a commit
   75681           ** is required. */
   75682           rc = vdbeCommit(db, p);
   75683         }
   75684         if( rc==SQLITE_BUSY && p->readOnly ){
   75685           sqlite3VdbeLeave(p);
   75686           return SQLITE_BUSY;
   75687         }else if( rc!=SQLITE_OK ){
   75688           p->rc = rc;
   75689           sqlite3RollbackAll(db, SQLITE_OK);
   75690           p->nChange = 0;
   75691         }else{
   75692           db->nDeferredCons = 0;
   75693           db->nDeferredImmCons = 0;
   75694           db->flags &= ~SQLITE_DeferFKs;
   75695           sqlite3CommitInternalChanges(db);
   75696         }
   75697       }else{
   75698         sqlite3RollbackAll(db, SQLITE_OK);
   75699         p->nChange = 0;
   75700       }
   75701       db->nStatement = 0;
   75702     }else if( eStatementOp==0 ){
   75703       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
   75704         eStatementOp = SAVEPOINT_RELEASE;
   75705       }else if( p->errorAction==OE_Abort ){
   75706         eStatementOp = SAVEPOINT_ROLLBACK;
   75707       }else{
   75708         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   75709         sqlite3CloseSavepoints(db);
   75710         db->autoCommit = 1;
   75711         p->nChange = 0;
   75712       }
   75713     }
   75714 
   75715     /* If eStatementOp is non-zero, then a statement transaction needs to
   75716     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
   75717     ** do so. If this operation returns an error, and the current statement
   75718     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
   75719     ** current statement error code.
   75720     */
   75721     if( eStatementOp ){
   75722       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
   75723       if( rc ){
   75724         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
   75725           p->rc = rc;
   75726           sqlite3DbFree(db, p->zErrMsg);
   75727           p->zErrMsg = 0;
   75728         }
   75729         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   75730         sqlite3CloseSavepoints(db);
   75731         db->autoCommit = 1;
   75732         p->nChange = 0;
   75733       }
   75734     }
   75735 
   75736     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
   75737     ** has been rolled back, update the database connection change-counter.
   75738     */
   75739     if( p->changeCntOn ){
   75740       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
   75741         sqlite3VdbeSetChanges(db, p->nChange);
   75742       }else{
   75743         sqlite3VdbeSetChanges(db, 0);
   75744       }
   75745       p->nChange = 0;
   75746     }
   75747 
   75748     /* Release the locks */
   75749     sqlite3VdbeLeave(p);
   75750   }
   75751 
   75752   /* We have successfully halted and closed the VM.  Record this fact. */
   75753   if( p->pc>=0 ){
   75754     db->nVdbeActive--;
   75755     if( !p->readOnly ) db->nVdbeWrite--;
   75756     if( p->bIsReader ) db->nVdbeRead--;
   75757     assert( db->nVdbeActive>=db->nVdbeRead );
   75758     assert( db->nVdbeRead>=db->nVdbeWrite );
   75759     assert( db->nVdbeWrite>=0 );
   75760   }
   75761   p->magic = VDBE_MAGIC_HALT;
   75762   checkActiveVdbeCnt(db);
   75763   if( db->mallocFailed ){
   75764     p->rc = SQLITE_NOMEM_BKPT;
   75765   }
   75766 
   75767   /* If the auto-commit flag is set to true, then any locks that were held
   75768   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   75769   ** to invoke any required unlock-notify callbacks.
   75770   */
   75771   if( db->autoCommit ){
   75772     sqlite3ConnectionUnlocked(db);
   75773   }
   75774 
   75775   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
   75776   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
   75777 }
   75778 
   75779 
   75780 /*
   75781 ** Each VDBE holds the result of the most recent sqlite3_step() call
   75782 ** in p->rc.  This routine sets that result back to SQLITE_OK.
   75783 */
   75784 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
   75785   p->rc = SQLITE_OK;
   75786 }
   75787 
   75788 /*
   75789 ** Copy the error code and error message belonging to the VDBE passed
   75790 ** as the first argument to its database handle (so that they will be
   75791 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
   75792 **
   75793 ** This function does not clear the VDBE error code or message, just
   75794 ** copies them to the database handle.
   75795 */
   75796 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
   75797   sqlite3 *db = p->db;
   75798   int rc = p->rc;
   75799   if( p->zErrMsg ){
   75800     db->bBenignMalloc++;
   75801     sqlite3BeginBenignMalloc();
   75802     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
   75803     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   75804     sqlite3EndBenignMalloc();
   75805     db->bBenignMalloc--;
   75806   }else if( db->pErr ){
   75807     sqlite3ValueSetNull(db->pErr);
   75808   }
   75809   db->errCode = rc;
   75810   return rc;
   75811 }
   75812 
   75813 #ifdef SQLITE_ENABLE_SQLLOG
   75814 /*
   75815 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
   75816 ** invoke it.
   75817 */
   75818 static void vdbeInvokeSqllog(Vdbe *v){
   75819   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
   75820     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
   75821     assert( v->db->init.busy==0 );
   75822     if( zExpanded ){
   75823       sqlite3GlobalConfig.xSqllog(
   75824           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
   75825       );
   75826       sqlite3DbFree(v->db, zExpanded);
   75827     }
   75828   }
   75829 }
   75830 #else
   75831 # define vdbeInvokeSqllog(x)
   75832 #endif
   75833 
   75834 /*
   75835 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
   75836 ** Write any error messages into *pzErrMsg.  Return the result code.
   75837 **
   75838 ** After this routine is run, the VDBE should be ready to be executed
   75839 ** again.
   75840 **
   75841 ** To look at it another way, this routine resets the state of the
   75842 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
   75843 ** VDBE_MAGIC_INIT.
   75844 */
   75845 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   75846 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   75847   int i;
   75848 #endif
   75849 
   75850   sqlite3 *db;
   75851   db = p->db;
   75852 
   75853   /* If the VM did not run to completion or if it encountered an
   75854   ** error, then it might not have been halted properly.  So halt
   75855   ** it now.
   75856   */
   75857   sqlite3VdbeHalt(p);
   75858 
   75859   /* If the VDBE has be run even partially, then transfer the error code
   75860   ** and error message from the VDBE into the main database structure.  But
   75861   ** if the VDBE has just been set to run but has not actually executed any
   75862   ** instructions yet, leave the main database error information unchanged.
   75863   */
   75864   if( p->pc>=0 ){
   75865     vdbeInvokeSqllog(p);
   75866     sqlite3VdbeTransferError(p);
   75867     if( p->runOnlyOnce ) p->expired = 1;
   75868   }else if( p->rc && p->expired ){
   75869     /* The expired flag was set on the VDBE before the first call
   75870     ** to sqlite3_step(). For consistency (since sqlite3_step() was
   75871     ** called), set the database error in this case as well.
   75872     */
   75873     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
   75874   }
   75875 
   75876   /* Reset register contents and reclaim error message memory.
   75877   */
   75878 #ifdef SQLITE_DEBUG
   75879   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   75880   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   75881   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
   75882   if( p->aMem ){
   75883     for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
   75884   }
   75885 #endif
   75886   sqlite3DbFree(db, p->zErrMsg);
   75887   p->zErrMsg = 0;
   75888   p->pResultSet = 0;
   75889 
   75890   /* Save profiling information from this VDBE run.
   75891   */
   75892 #ifdef VDBE_PROFILE
   75893   {
   75894     FILE *out = fopen("vdbe_profile.out", "a");
   75895     if( out ){
   75896       fprintf(out, "---- ");
   75897       for(i=0; i<p->nOp; i++){
   75898         fprintf(out, "%02x", p->aOp[i].opcode);
   75899       }
   75900       fprintf(out, "\n");
   75901       if( p->zSql ){
   75902         char c, pc = 0;
   75903         fprintf(out, "-- ");
   75904         for(i=0; (c = p->zSql[i])!=0; i++){
   75905           if( pc=='\n' ) fprintf(out, "-- ");
   75906           putc(c, out);
   75907           pc = c;
   75908         }
   75909         if( pc!='\n' ) fprintf(out, "\n");
   75910       }
   75911       for(i=0; i<p->nOp; i++){
   75912         char zHdr[100];
   75913         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
   75914            p->aOp[i].cnt,
   75915            p->aOp[i].cycles,
   75916            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
   75917         );
   75918         fprintf(out, "%s", zHdr);
   75919         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
   75920       }
   75921       fclose(out);
   75922     }
   75923   }
   75924 #endif
   75925   p->magic = VDBE_MAGIC_RESET;
   75926   return p->rc & db->errMask;
   75927 }
   75928 
   75929 /*
   75930 ** Clean up and delete a VDBE after execution.  Return an integer which is
   75931 ** the result code.  Write any error message text into *pzErrMsg.
   75932 */
   75933 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   75934   int rc = SQLITE_OK;
   75935   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
   75936     rc = sqlite3VdbeReset(p);
   75937     assert( (rc & p->db->errMask)==rc );
   75938   }
   75939   sqlite3VdbeDelete(p);
   75940   return rc;
   75941 }
   75942 
   75943 /*
   75944 ** If parameter iOp is less than zero, then invoke the destructor for
   75945 ** all auxiliary data pointers currently cached by the VM passed as
   75946 ** the first argument.
   75947 **
   75948 ** Or, if iOp is greater than or equal to zero, then the destructor is
   75949 ** only invoked for those auxiliary data pointers created by the user
   75950 ** function invoked by the OP_Function opcode at instruction iOp of
   75951 ** VM pVdbe, and only then if:
   75952 **
   75953 **    * the associated function parameter is the 32nd or later (counting
   75954 **      from left to right), or
   75955 **
   75956 **    * the corresponding bit in argument mask is clear (where the first
   75957 **      function parameter corresponds to bit 0 etc.).
   75958 */
   75959 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
   75960   while( *pp ){
   75961     AuxData *pAux = *pp;
   75962     if( (iOp<0)
   75963      || (pAux->iAuxOp==iOp
   75964           && pAux->iAuxArg>=0
   75965           && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
   75966     ){
   75967       testcase( pAux->iAuxArg==31 );
   75968       if( pAux->xDeleteAux ){
   75969         pAux->xDeleteAux(pAux->pAux);
   75970       }
   75971       *pp = pAux->pNextAux;
   75972       sqlite3DbFree(db, pAux);
   75973     }else{
   75974       pp= &pAux->pNextAux;
   75975     }
   75976   }
   75977 }
   75978 
   75979 /*
   75980 ** Free all memory associated with the Vdbe passed as the second argument,
   75981 ** except for object itself, which is preserved.
   75982 **
   75983 ** The difference between this function and sqlite3VdbeDelete() is that
   75984 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
   75985 ** the database connection and frees the object itself.
   75986 */
   75987 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
   75988   SubProgram *pSub, *pNext;
   75989   assert( p->db==0 || p->db==db );
   75990   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   75991   for(pSub=p->pProgram; pSub; pSub=pNext){
   75992     pNext = pSub->pNext;
   75993     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
   75994     sqlite3DbFree(db, pSub);
   75995   }
   75996   if( p->magic!=VDBE_MAGIC_INIT ){
   75997     releaseMemArray(p->aVar, p->nVar);
   75998     sqlite3DbFree(db, p->pVList);
   75999     sqlite3DbFree(db, p->pFree);
   76000   }
   76001   vdbeFreeOpArray(db, p->aOp, p->nOp);
   76002   sqlite3DbFree(db, p->aColName);
   76003   sqlite3DbFree(db, p->zSql);
   76004 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   76005   {
   76006     int i;
   76007     for(i=0; i<p->nScan; i++){
   76008       sqlite3DbFree(db, p->aScan[i].zName);
   76009     }
   76010     sqlite3DbFree(db, p->aScan);
   76011   }
   76012 #endif
   76013 }
   76014 
   76015 /*
   76016 ** Delete an entire VDBE.
   76017 */
   76018 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
   76019   sqlite3 *db;
   76020 
   76021   assert( p!=0 );
   76022   db = p->db;
   76023   assert( sqlite3_mutex_held(db->mutex) );
   76024   sqlite3VdbeClearObject(db, p);
   76025   if( p->pPrev ){
   76026     p->pPrev->pNext = p->pNext;
   76027   }else{
   76028     assert( db->pVdbe==p );
   76029     db->pVdbe = p->pNext;
   76030   }
   76031   if( p->pNext ){
   76032     p->pNext->pPrev = p->pPrev;
   76033   }
   76034   p->magic = VDBE_MAGIC_DEAD;
   76035   p->db = 0;
   76036   sqlite3DbFreeNN(db, p);
   76037 }
   76038 
   76039 /*
   76040 ** The cursor "p" has a pending seek operation that has not yet been
   76041 ** carried out.  Seek the cursor now.  If an error occurs, return
   76042 ** the appropriate error code.
   76043 */
   76044 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
   76045   int res, rc;
   76046 #ifdef SQLITE_TEST
   76047   extern int sqlite3_search_count;
   76048 #endif
   76049   assert( p->deferredMoveto );
   76050   assert( p->isTable );
   76051   assert( p->eCurType==CURTYPE_BTREE );
   76052   rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
   76053   if( rc ) return rc;
   76054   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
   76055 #ifdef SQLITE_TEST
   76056   sqlite3_search_count++;
   76057 #endif
   76058   p->deferredMoveto = 0;
   76059   p->cacheStatus = CACHE_STALE;
   76060   return SQLITE_OK;
   76061 }
   76062 
   76063 /*
   76064 ** Something has moved cursor "p" out of place.  Maybe the row it was
   76065 ** pointed to was deleted out from under it.  Or maybe the btree was
   76066 ** rebalanced.  Whatever the cause, try to restore "p" to the place it
   76067 ** is supposed to be pointing.  If the row was deleted out from under the
   76068 ** cursor, set the cursor to point to a NULL row.
   76069 */
   76070 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
   76071   int isDifferentRow, rc;
   76072   assert( p->eCurType==CURTYPE_BTREE );
   76073   assert( p->uc.pCursor!=0 );
   76074   assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
   76075   rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
   76076   p->cacheStatus = CACHE_STALE;
   76077   if( isDifferentRow ) p->nullRow = 1;
   76078   return rc;
   76079 }
   76080 
   76081 /*
   76082 ** Check to ensure that the cursor is valid.  Restore the cursor
   76083 ** if need be.  Return any I/O error from the restore operation.
   76084 */
   76085 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
   76086   assert( p->eCurType==CURTYPE_BTREE );
   76087   if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
   76088     return handleMovedCursor(p);
   76089   }
   76090   return SQLITE_OK;
   76091 }
   76092 
   76093 /*
   76094 ** Make sure the cursor p is ready to read or write the row to which it
   76095 ** was last positioned.  Return an error code if an OOM fault or I/O error
   76096 ** prevents us from positioning the cursor to its correct position.
   76097 **
   76098 ** If a MoveTo operation is pending on the given cursor, then do that
   76099 ** MoveTo now.  If no move is pending, check to see if the row has been
   76100 ** deleted out from under the cursor and if it has, mark the row as
   76101 ** a NULL row.
   76102 **
   76103 ** If the cursor is already pointing to the correct row and that row has
   76104 ** not been deleted out from under the cursor, then this routine is a no-op.
   76105 */
   76106 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
   76107   VdbeCursor *p = *pp;
   76108   assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
   76109   if( p->deferredMoveto ){
   76110     int iMap;
   76111     if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
   76112       *pp = p->pAltCursor;
   76113       *piCol = iMap - 1;
   76114       return SQLITE_OK;
   76115     }
   76116     return handleDeferredMoveto(p);
   76117   }
   76118   if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
   76119     return handleMovedCursor(p);
   76120   }
   76121   return SQLITE_OK;
   76122 }
   76123 
   76124 /*
   76125 ** The following functions:
   76126 **
   76127 ** sqlite3VdbeSerialType()
   76128 ** sqlite3VdbeSerialTypeLen()
   76129 ** sqlite3VdbeSerialLen()
   76130 ** sqlite3VdbeSerialPut()
   76131 ** sqlite3VdbeSerialGet()
   76132 **
   76133 ** encapsulate the code that serializes values for storage in SQLite
   76134 ** data and index records. Each serialized value consists of a
   76135 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
   76136 ** integer, stored as a varint.
   76137 **
   76138 ** In an SQLite index record, the serial type is stored directly before
   76139 ** the blob of data that it corresponds to. In a table record, all serial
   76140 ** types are stored at the start of the record, and the blobs of data at
   76141 ** the end. Hence these functions allow the caller to handle the
   76142 ** serial-type and data blob separately.
   76143 **
   76144 ** The following table describes the various storage classes for data:
   76145 **
   76146 **   serial type        bytes of data      type
   76147 **   --------------     ---------------    ---------------
   76148 **      0                     0            NULL
   76149 **      1                     1            signed integer
   76150 **      2                     2            signed integer
   76151 **      3                     3            signed integer
   76152 **      4                     4            signed integer
   76153 **      5                     6            signed integer
   76154 **      6                     8            signed integer
   76155 **      7                     8            IEEE float
   76156 **      8                     0            Integer constant 0
   76157 **      9                     0            Integer constant 1
   76158 **     10,11                               reserved for expansion
   76159 **    N>=12 and even       (N-12)/2        BLOB
   76160 **    N>=13 and odd        (N-13)/2        text
   76161 **
   76162 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
   76163 ** of SQLite will not understand those serial types.
   76164 */
   76165 
   76166 /*
   76167 ** Return the serial-type for the value stored in pMem.
   76168 */
   76169 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
   76170   int flags = pMem->flags;
   76171   u32 n;
   76172 
   76173   assert( pLen!=0 );
   76174   if( flags&MEM_Null ){
   76175     *pLen = 0;
   76176     return 0;
   76177   }
   76178   if( flags&MEM_Int ){
   76179     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
   76180 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
   76181     i64 i = pMem->u.i;
   76182     u64 u;
   76183     if( i<0 ){
   76184       u = ~i;
   76185     }else{
   76186       u = i;
   76187     }
   76188     if( u<=127 ){
   76189       if( (i&1)==i && file_format>=4 ){
   76190         *pLen = 0;
   76191         return 8+(u32)u;
   76192       }else{
   76193         *pLen = 1;
   76194         return 1;
   76195       }
   76196     }
   76197     if( u<=32767 ){ *pLen = 2; return 2; }
   76198     if( u<=8388607 ){ *pLen = 3; return 3; }
   76199     if( u<=2147483647 ){ *pLen = 4; return 4; }
   76200     if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
   76201     *pLen = 8;
   76202     return 6;
   76203   }
   76204   if( flags&MEM_Real ){
   76205     *pLen = 8;
   76206     return 7;
   76207   }
   76208   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
   76209   assert( pMem->n>=0 );
   76210   n = (u32)pMem->n;
   76211   if( flags & MEM_Zero ){
   76212     n += pMem->u.nZero;
   76213   }
   76214   *pLen = n;
   76215   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
   76216 }
   76217 
   76218 /*
   76219 ** The sizes for serial types less than 128
   76220 */
   76221 static const u8 sqlite3SmallTypeSizes[] = {
   76222         /*  0   1   2   3   4   5   6   7   8   9 */
   76223 /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
   76224 /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
   76225 /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
   76226 /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
   76227 /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
   76228 /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
   76229 /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
   76230 /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
   76231 /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
   76232 /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
   76233 /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
   76234 /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
   76235 /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
   76236 };
   76237 
   76238 /*
   76239 ** Return the length of the data corresponding to the supplied serial-type.
   76240 */
   76241 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   76242   if( serial_type>=128 ){
   76243     return (serial_type-12)/2;
   76244   }else{
   76245     assert( serial_type<12
   76246             || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
   76247     return sqlite3SmallTypeSizes[serial_type];
   76248   }
   76249 }
   76250 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
   76251   assert( serial_type<128 );
   76252   return sqlite3SmallTypeSizes[serial_type];
   76253 }
   76254 
   76255 /*
   76256 ** If we are on an architecture with mixed-endian floating
   76257 ** points (ex: ARM7) then swap the lower 4 bytes with the
   76258 ** upper 4 bytes.  Return the result.
   76259 **
   76260 ** For most architectures, this is a no-op.
   76261 **
   76262 ** (later):  It is reported to me that the mixed-endian problem
   76263 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
   76264 ** that early versions of GCC stored the two words of a 64-bit
   76265 ** float in the wrong order.  And that error has been propagated
   76266 ** ever since.  The blame is not necessarily with GCC, though.
   76267 ** GCC might have just copying the problem from a prior compiler.
   76268 ** I am also told that newer versions of GCC that follow a different
   76269 ** ABI get the byte order right.
   76270 **
   76271 ** Developers using SQLite on an ARM7 should compile and run their
   76272 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
   76273 ** enabled, some asserts below will ensure that the byte order of
   76274 ** floating point values is correct.
   76275 **
   76276 ** (2007-08-30)  Frank van Vugt has studied this problem closely
   76277 ** and has send his findings to the SQLite developers.  Frank
   76278 ** writes that some Linux kernels offer floating point hardware
   76279 ** emulation that uses only 32-bit mantissas instead of a full
   76280 ** 48-bits as required by the IEEE standard.  (This is the
   76281 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
   76282 ** byte swapping becomes very complicated.  To avoid problems,
   76283 ** the necessary byte swapping is carried out using a 64-bit integer
   76284 ** rather than a 64-bit float.  Frank assures us that the code here
   76285 ** works for him.  We, the developers, have no way to independently
   76286 ** verify this, but Frank seems to know what he is talking about
   76287 ** so we trust him.
   76288 */
   76289 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   76290 static u64 floatSwap(u64 in){
   76291   union {
   76292     u64 r;
   76293     u32 i[2];
   76294   } u;
   76295   u32 t;
   76296 
   76297   u.r = in;
   76298   t = u.i[0];
   76299   u.i[0] = u.i[1];
   76300   u.i[1] = t;
   76301   return u.r;
   76302 }
   76303 # define swapMixedEndianFloat(X)  X = floatSwap(X)
   76304 #else
   76305 # define swapMixedEndianFloat(X)
   76306 #endif
   76307 
   76308 /*
   76309 ** Write the serialized data blob for the value stored in pMem into
   76310 ** buf. It is assumed that the caller has allocated sufficient space.
   76311 ** Return the number of bytes written.
   76312 **
   76313 ** nBuf is the amount of space left in buf[].  The caller is responsible
   76314 ** for allocating enough space to buf[] to hold the entire field, exclusive
   76315 ** of the pMem->u.nZero bytes for a MEM_Zero value.
   76316 **
   76317 ** Return the number of bytes actually written into buf[].  The number
   76318 ** of bytes in the zero-filled tail is included in the return value only
   76319 ** if those bytes were zeroed in buf[].
   76320 */
   76321 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
   76322   u32 len;
   76323 
   76324   /* Integer and Real */
   76325   if( serial_type<=7 && serial_type>0 ){
   76326     u64 v;
   76327     u32 i;
   76328     if( serial_type==7 ){
   76329       assert( sizeof(v)==sizeof(pMem->u.r) );
   76330       memcpy(&v, &pMem->u.r, sizeof(v));
   76331       swapMixedEndianFloat(v);
   76332     }else{
   76333       v = pMem->u.i;
   76334     }
   76335     len = i = sqlite3SmallTypeSizes[serial_type];
   76336     assert( i>0 );
   76337     do{
   76338       buf[--i] = (u8)(v&0xFF);
   76339       v >>= 8;
   76340     }while( i );
   76341     return len;
   76342   }
   76343 
   76344   /* String or blob */
   76345   if( serial_type>=12 ){
   76346     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
   76347              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
   76348     len = pMem->n;
   76349     if( len>0 ) memcpy(buf, pMem->z, len);
   76350     return len;
   76351   }
   76352 
   76353   /* NULL or constants 0 or 1 */
   76354   return 0;
   76355 }
   76356 
   76357 /* Input "x" is a sequence of unsigned characters that represent a
   76358 ** big-endian integer.  Return the equivalent native integer
   76359 */
   76360 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
   76361 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
   76362 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
   76363 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
   76364 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
   76365 
   76366 /*
   76367 ** Deserialize the data blob pointed to by buf as serial type serial_type
   76368 ** and store the result in pMem.  Return the number of bytes read.
   76369 **
   76370 ** This function is implemented as two separate routines for performance.
   76371 ** The few cases that require local variables are broken out into a separate
   76372 ** routine so that in most cases the overhead of moving the stack pointer
   76373 ** is avoided.
   76374 */
   76375 static u32 SQLITE_NOINLINE serialGet(
   76376   const unsigned char *buf,     /* Buffer to deserialize from */
   76377   u32 serial_type,              /* Serial type to deserialize */
   76378   Mem *pMem                     /* Memory cell to write value into */
   76379 ){
   76380   u64 x = FOUR_BYTE_UINT(buf);
   76381   u32 y = FOUR_BYTE_UINT(buf+4);
   76382   x = (x<<32) + y;
   76383   if( serial_type==6 ){
   76384     /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
   76385     ** twos-complement integer. */
   76386     pMem->u.i = *(i64*)&x;
   76387     pMem->flags = MEM_Int;
   76388     testcase( pMem->u.i<0 );
   76389   }else{
   76390     /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
   76391     ** floating point number. */
   76392 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
   76393     /* Verify that integers and floating point values use the same
   76394     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
   76395     ** defined that 64-bit floating point values really are mixed
   76396     ** endian.
   76397     */
   76398     static const u64 t1 = ((u64)0x3ff00000)<<32;
   76399     static const double r1 = 1.0;
   76400     u64 t2 = t1;
   76401     swapMixedEndianFloat(t2);
   76402     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
   76403 #endif
   76404     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
   76405     swapMixedEndianFloat(x);
   76406     memcpy(&pMem->u.r, &x, sizeof(x));
   76407     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
   76408   }
   76409   return 8;
   76410 }
   76411 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
   76412   const unsigned char *buf,     /* Buffer to deserialize from */
   76413   u32 serial_type,              /* Serial type to deserialize */
   76414   Mem *pMem                     /* Memory cell to write value into */
   76415 ){
   76416   switch( serial_type ){
   76417     case 10: { /* Internal use only: NULL with virtual table
   76418                ** UPDATE no-change flag set */
   76419       pMem->flags = MEM_Null|MEM_Zero;
   76420       pMem->n = 0;
   76421       pMem->u.nZero = 0;
   76422       break;
   76423     }
   76424     case 11:   /* Reserved for future use */
   76425     case 0: {  /* Null */
   76426       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
   76427       pMem->flags = MEM_Null;
   76428       break;
   76429     }
   76430     case 1: {
   76431       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
   76432       ** integer. */
   76433       pMem->u.i = ONE_BYTE_INT(buf);
   76434       pMem->flags = MEM_Int;
   76435       testcase( pMem->u.i<0 );
   76436       return 1;
   76437     }
   76438     case 2: { /* 2-byte signed integer */
   76439       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
   76440       ** twos-complement integer. */
   76441       pMem->u.i = TWO_BYTE_INT(buf);
   76442       pMem->flags = MEM_Int;
   76443       testcase( pMem->u.i<0 );
   76444       return 2;
   76445     }
   76446     case 3: { /* 3-byte signed integer */
   76447       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
   76448       ** twos-complement integer. */
   76449       pMem->u.i = THREE_BYTE_INT(buf);
   76450       pMem->flags = MEM_Int;
   76451       testcase( pMem->u.i<0 );
   76452       return 3;
   76453     }
   76454     case 4: { /* 4-byte signed integer */
   76455       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
   76456       ** twos-complement integer. */
   76457       pMem->u.i = FOUR_BYTE_INT(buf);
   76458 #ifdef __HP_cc
   76459       /* Work around a sign-extension bug in the HP compiler for HP/UX */
   76460       if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
   76461 #endif
   76462       pMem->flags = MEM_Int;
   76463       testcase( pMem->u.i<0 );
   76464       return 4;
   76465     }
   76466     case 5: { /* 6-byte signed integer */
   76467       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
   76468       ** twos-complement integer. */
   76469       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
   76470       pMem->flags = MEM_Int;
   76471       testcase( pMem->u.i<0 );
   76472       return 6;
   76473     }
   76474     case 6:   /* 8-byte signed integer */
   76475     case 7: { /* IEEE floating point */
   76476       /* These use local variables, so do them in a separate routine
   76477       ** to avoid having to move the frame pointer in the common case */
   76478       return serialGet(buf,serial_type,pMem);
   76479     }
   76480     case 8:    /* Integer 0 */
   76481     case 9: {  /* Integer 1 */
   76482       /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
   76483       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
   76484       pMem->u.i = serial_type-8;
   76485       pMem->flags = MEM_Int;
   76486       return 0;
   76487     }
   76488     default: {
   76489       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
   76490       ** length.
   76491       ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
   76492       ** (N-13)/2 bytes in length. */
   76493       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
   76494       pMem->z = (char *)buf;
   76495       pMem->n = (serial_type-12)/2;
   76496       pMem->flags = aFlag[serial_type&1];
   76497       return pMem->n;
   76498     }
   76499   }
   76500   return 0;
   76501 }
   76502 /*
   76503 ** This routine is used to allocate sufficient space for an UnpackedRecord
   76504 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
   76505 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
   76506 **
   76507 ** The space is either allocated using sqlite3DbMallocRaw() or from within
   76508 ** the unaligned buffer passed via the second and third arguments (presumably
   76509 ** stack space). If the former, then *ppFree is set to a pointer that should
   76510 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
   76511 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
   76512 ** before returning.
   76513 **
   76514 ** If an OOM error occurs, NULL is returned.
   76515 */
   76516 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
   76517   KeyInfo *pKeyInfo               /* Description of the record */
   76518 ){
   76519   UnpackedRecord *p;              /* Unpacked record to return */
   76520   int nByte;                      /* Number of bytes required for *p */
   76521   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
   76522   p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
   76523   if( !p ) return 0;
   76524   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
   76525   assert( pKeyInfo->aSortOrder!=0 );
   76526   p->pKeyInfo = pKeyInfo;
   76527   p->nField = pKeyInfo->nKeyField + 1;
   76528   return p;
   76529 }
   76530 
   76531 /*
   76532 ** Given the nKey-byte encoding of a record in pKey[], populate the
   76533 ** UnpackedRecord structure indicated by the fourth argument with the
   76534 ** contents of the decoded record.
   76535 */
   76536 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   76537   KeyInfo *pKeyInfo,     /* Information about the record format */
   76538   int nKey,              /* Size of the binary record */
   76539   const void *pKey,      /* The binary record */
   76540   UnpackedRecord *p      /* Populate this structure before returning. */
   76541 ){
   76542   const unsigned char *aKey = (const unsigned char *)pKey;
   76543   int d;
   76544   u32 idx;                        /* Offset in aKey[] to read from */
   76545   u16 u;                          /* Unsigned loop counter */
   76546   u32 szHdr;
   76547   Mem *pMem = p->aMem;
   76548 
   76549   p->default_rc = 0;
   76550   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   76551   idx = getVarint32(aKey, szHdr);
   76552   d = szHdr;
   76553   u = 0;
   76554   while( idx<szHdr && d<=nKey ){
   76555     u32 serial_type;
   76556 
   76557     idx += getVarint32(&aKey[idx], serial_type);
   76558     pMem->enc = pKeyInfo->enc;
   76559     pMem->db = pKeyInfo->db;
   76560     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
   76561     pMem->szMalloc = 0;
   76562     pMem->z = 0;
   76563     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
   76564     pMem++;
   76565     if( (++u)>=p->nField ) break;
   76566   }
   76567   assert( u<=pKeyInfo->nKeyField + 1 );
   76568   p->nField = u;
   76569 }
   76570 
   76571 #ifdef SQLITE_DEBUG
   76572 /*
   76573 ** This function compares two index or table record keys in the same way
   76574 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
   76575 ** this function deserializes and compares values using the
   76576 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
   76577 ** in assert() statements to ensure that the optimized code in
   76578 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
   76579 **
   76580 ** Return true if the result of comparison is equivalent to desiredResult.
   76581 ** Return false if there is a disagreement.
   76582 */
   76583 static int vdbeRecordCompareDebug(
   76584   int nKey1, const void *pKey1, /* Left key */
   76585   const UnpackedRecord *pPKey2, /* Right key */
   76586   int desiredResult             /* Correct answer */
   76587 ){
   76588   u32 d1;            /* Offset into aKey[] of next data element */
   76589   u32 idx1;          /* Offset into aKey[] of next header element */
   76590   u32 szHdr1;        /* Number of bytes in header */
   76591   int i = 0;
   76592   int rc = 0;
   76593   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   76594   KeyInfo *pKeyInfo;
   76595   Mem mem1;
   76596 
   76597   pKeyInfo = pPKey2->pKeyInfo;
   76598   if( pKeyInfo->db==0 ) return 1;
   76599   mem1.enc = pKeyInfo->enc;
   76600   mem1.db = pKeyInfo->db;
   76601   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
   76602   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
   76603 
   76604   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   76605   ** We could initialize it, as shown here, to silence those complaints.
   76606   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
   76607   ** the unnecessary initialization has a measurable negative performance
   76608   ** impact, since this routine is a very high runner.  And so, we choose
   76609   ** to ignore the compiler warnings and leave this variable uninitialized.
   76610   */
   76611   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
   76612 
   76613   idx1 = getVarint32(aKey1, szHdr1);
   76614   if( szHdr1>98307 ) return SQLITE_CORRUPT;
   76615   d1 = szHdr1;
   76616   assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
   76617   assert( pKeyInfo->aSortOrder!=0 );
   76618   assert( pKeyInfo->nKeyField>0 );
   76619   assert( idx1<=szHdr1 || CORRUPT_DB );
   76620   do{
   76621     u32 serial_type1;
   76622 
   76623     /* Read the serial types for the next element in each key. */
   76624     idx1 += getVarint32( aKey1+idx1, serial_type1 );
   76625 
   76626     /* Verify that there is enough key space remaining to avoid
   76627     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
   76628     ** always be greater than or equal to the amount of required key space.
   76629     ** Use that approximation to avoid the more expensive call to
   76630     ** sqlite3VdbeSerialTypeLen() in the common case.
   76631     */
   76632     if( d1+serial_type1+2>(u32)nKey1
   76633      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
   76634     ){
   76635       break;
   76636     }
   76637 
   76638     /* Extract the values to be compared.
   76639     */
   76640     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
   76641 
   76642     /* Do the comparison
   76643     */
   76644     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
   76645     if( rc!=0 ){
   76646       assert( mem1.szMalloc==0 );  /* See comment below */
   76647       if( pKeyInfo->aSortOrder[i] ){
   76648         rc = -rc;  /* Invert the result for DESC sort order. */
   76649       }
   76650       goto debugCompareEnd;
   76651     }
   76652     i++;
   76653   }while( idx1<szHdr1 && i<pPKey2->nField );
   76654 
   76655   /* No memory allocation is ever used on mem1.  Prove this using
   76656   ** the following assert().  If the assert() fails, it indicates a
   76657   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
   76658   */
   76659   assert( mem1.szMalloc==0 );
   76660 
   76661   /* rc==0 here means that one of the keys ran out of fields and
   76662   ** all the fields up to that point were equal. Return the default_rc
   76663   ** value.  */
   76664   rc = pPKey2->default_rc;
   76665 
   76666 debugCompareEnd:
   76667   if( desiredResult==0 && rc==0 ) return 1;
   76668   if( desiredResult<0 && rc<0 ) return 1;
   76669   if( desiredResult>0 && rc>0 ) return 1;
   76670   if( CORRUPT_DB ) return 1;
   76671   if( pKeyInfo->db->mallocFailed ) return 1;
   76672   return 0;
   76673 }
   76674 #endif
   76675 
   76676 #ifdef SQLITE_DEBUG
   76677 /*
   76678 ** Count the number of fields (a.k.a. columns) in the record given by
   76679 ** pKey,nKey.  The verify that this count is less than or equal to the
   76680 ** limit given by pKeyInfo->nAllField.
   76681 **
   76682 ** If this constraint is not satisfied, it means that the high-speed
   76683 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
   76684 ** not work correctly.  If this assert() ever fires, it probably means
   76685 ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
   76686 ** incorrectly.
   76687 */
   76688 static void vdbeAssertFieldCountWithinLimits(
   76689   int nKey, const void *pKey,   /* The record to verify */
   76690   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
   76691 ){
   76692   int nField = 0;
   76693   u32 szHdr;
   76694   u32 idx;
   76695   u32 notUsed;
   76696   const unsigned char *aKey = (const unsigned char*)pKey;
   76697 
   76698   if( CORRUPT_DB ) return;
   76699   idx = getVarint32(aKey, szHdr);
   76700   assert( nKey>=0 );
   76701   assert( szHdr<=(u32)nKey );
   76702   while( idx<szHdr ){
   76703     idx += getVarint32(aKey+idx, notUsed);
   76704     nField++;
   76705   }
   76706   assert( nField <= pKeyInfo->nAllField );
   76707 }
   76708 #else
   76709 # define vdbeAssertFieldCountWithinLimits(A,B,C)
   76710 #endif
   76711 
   76712 /*
   76713 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
   76714 ** using the collation sequence pColl. As usual, return a negative , zero
   76715 ** or positive value if *pMem1 is less than, equal to or greater than
   76716 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
   76717 */
   76718 static int vdbeCompareMemString(
   76719   const Mem *pMem1,
   76720   const Mem *pMem2,
   76721   const CollSeq *pColl,
   76722   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
   76723 ){
   76724   if( pMem1->enc==pColl->enc ){
   76725     /* The strings are already in the correct encoding.  Call the
   76726      ** comparison function directly */
   76727     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   76728   }else{
   76729     int rc;
   76730     const void *v1, *v2;
   76731     Mem c1;
   76732     Mem c2;
   76733     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
   76734     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
   76735     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   76736     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   76737     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   76738     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   76739     if( (v1==0 || v2==0) ){
   76740       if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
   76741       rc = 0;
   76742     }else{
   76743       rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
   76744     }
   76745     sqlite3VdbeMemRelease(&c1);
   76746     sqlite3VdbeMemRelease(&c2);
   76747     return rc;
   76748   }
   76749 }
   76750 
   76751 /*
   76752 ** The input pBlob is guaranteed to be a Blob that is not marked
   76753 ** with MEM_Zero.  Return true if it could be a zero-blob.
   76754 */
   76755 static int isAllZero(const char *z, int n){
   76756   int i;
   76757   for(i=0; i<n; i++){
   76758     if( z[i] ) return 0;
   76759   }
   76760   return 1;
   76761 }
   76762 
   76763 /*
   76764 ** Compare two blobs.  Return negative, zero, or positive if the first
   76765 ** is less than, equal to, or greater than the second, respectively.
   76766 ** If one blob is a prefix of the other, then the shorter is the lessor.
   76767 */
   76768 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
   76769   int c;
   76770   int n1 = pB1->n;
   76771   int n2 = pB2->n;
   76772 
   76773   /* It is possible to have a Blob value that has some non-zero content
   76774   ** followed by zero content.  But that only comes up for Blobs formed
   76775   ** by the OP_MakeRecord opcode, and such Blobs never get passed into
   76776   ** sqlite3MemCompare(). */
   76777   assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
   76778   assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
   76779 
   76780   if( (pB1->flags|pB2->flags) & MEM_Zero ){
   76781     if( pB1->flags & pB2->flags & MEM_Zero ){
   76782       return pB1->u.nZero - pB2->u.nZero;
   76783     }else if( pB1->flags & MEM_Zero ){
   76784       if( !isAllZero(pB2->z, pB2->n) ) return -1;
   76785       return pB1->u.nZero - n2;
   76786     }else{
   76787       if( !isAllZero(pB1->z, pB1->n) ) return +1;
   76788       return n1 - pB2->u.nZero;
   76789     }
   76790   }
   76791   c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
   76792   if( c ) return c;
   76793   return n1 - n2;
   76794 }
   76795 
   76796 /*
   76797 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
   76798 ** number.  Return negative, zero, or positive if the first (i64) is less than,
   76799 ** equal to, or greater than the second (double).
   76800 */
   76801 static int sqlite3IntFloatCompare(i64 i, double r){
   76802   if( sizeof(LONGDOUBLE_TYPE)>8 ){
   76803     LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
   76804     if( x<r ) return -1;
   76805     if( x>r ) return +1;
   76806     return 0;
   76807   }else{
   76808     i64 y;
   76809     double s;
   76810     if( r<-9223372036854775808.0 ) return +1;
   76811     if( r>9223372036854775807.0 ) return -1;
   76812     y = (i64)r;
   76813     if( i<y ) return -1;
   76814     if( i>y ){
   76815       if( y==SMALLEST_INT64 && r>0.0 ) return -1;
   76816       return +1;
   76817     }
   76818     s = (double)i;
   76819     if( s<r ) return -1;
   76820     if( s>r ) return +1;
   76821     return 0;
   76822   }
   76823 }
   76824 
   76825 /*
   76826 ** Compare the values contained by the two memory cells, returning
   76827 ** negative, zero or positive if pMem1 is less than, equal to, or greater
   76828 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   76829 ** and reals) sorted numerically, followed by text ordered by the collating
   76830 ** sequence pColl and finally blob's ordered by memcmp().
   76831 **
   76832 ** Two NULL values are considered equal by this function.
   76833 */
   76834 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   76835   int f1, f2;
   76836   int combined_flags;
   76837 
   76838   f1 = pMem1->flags;
   76839   f2 = pMem2->flags;
   76840   combined_flags = f1|f2;
   76841   assert( (combined_flags & MEM_RowSet)==0 );
   76842 
   76843   /* If one value is NULL, it is less than the other. If both values
   76844   ** are NULL, return 0.
   76845   */
   76846   if( combined_flags&MEM_Null ){
   76847     return (f2&MEM_Null) - (f1&MEM_Null);
   76848   }
   76849 
   76850   /* At least one of the two values is a number
   76851   */
   76852   if( combined_flags&(MEM_Int|MEM_Real) ){
   76853     if( (f1 & f2 & MEM_Int)!=0 ){
   76854       if( pMem1->u.i < pMem2->u.i ) return -1;
   76855       if( pMem1->u.i > pMem2->u.i ) return +1;
   76856       return 0;
   76857     }
   76858     if( (f1 & f2 & MEM_Real)!=0 ){
   76859       if( pMem1->u.r < pMem2->u.r ) return -1;
   76860       if( pMem1->u.r > pMem2->u.r ) return +1;
   76861       return 0;
   76862     }
   76863     if( (f1&MEM_Int)!=0 ){
   76864       if( (f2&MEM_Real)!=0 ){
   76865         return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
   76866       }else{
   76867         return -1;
   76868       }
   76869     }
   76870     if( (f1&MEM_Real)!=0 ){
   76871       if( (f2&MEM_Int)!=0 ){
   76872         return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
   76873       }else{
   76874         return -1;
   76875       }
   76876     }
   76877     return +1;
   76878   }
   76879 
   76880   /* If one value is a string and the other is a blob, the string is less.
   76881   ** If both are strings, compare using the collating functions.
   76882   */
   76883   if( combined_flags&MEM_Str ){
   76884     if( (f1 & MEM_Str)==0 ){
   76885       return 1;
   76886     }
   76887     if( (f2 & MEM_Str)==0 ){
   76888       return -1;
   76889     }
   76890 
   76891     assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
   76892     assert( pMem1->enc==SQLITE_UTF8 ||
   76893             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   76894 
   76895     /* The collation sequence must be defined at this point, even if
   76896     ** the user deletes the collation sequence after the vdbe program is
   76897     ** compiled (this was not always the case).
   76898     */
   76899     assert( !pColl || pColl->xCmp );
   76900 
   76901     if( pColl ){
   76902       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
   76903     }
   76904     /* If a NULL pointer was passed as the collate function, fall through
   76905     ** to the blob case and use memcmp().  */
   76906   }
   76907 
   76908   /* Both values must be blobs.  Compare using memcmp().  */
   76909   return sqlite3BlobCompare(pMem1, pMem2);
   76910 }
   76911 
   76912 
   76913 /*
   76914 ** The first argument passed to this function is a serial-type that
   76915 ** corresponds to an integer - all values between 1 and 9 inclusive
   76916 ** except 7. The second points to a buffer containing an integer value
   76917 ** serialized according to serial_type. This function deserializes
   76918 ** and returns the value.
   76919 */
   76920 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
   76921   u32 y;
   76922   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
   76923   switch( serial_type ){
   76924     case 0:
   76925     case 1:
   76926       testcase( aKey[0]&0x80 );
   76927       return ONE_BYTE_INT(aKey);
   76928     case 2:
   76929       testcase( aKey[0]&0x80 );
   76930       return TWO_BYTE_INT(aKey);
   76931     case 3:
   76932       testcase( aKey[0]&0x80 );
   76933       return THREE_BYTE_INT(aKey);
   76934     case 4: {
   76935       testcase( aKey[0]&0x80 );
   76936       y = FOUR_BYTE_UINT(aKey);
   76937       return (i64)*(int*)&y;
   76938     }
   76939     case 5: {
   76940       testcase( aKey[0]&0x80 );
   76941       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
   76942     }
   76943     case 6: {
   76944       u64 x = FOUR_BYTE_UINT(aKey);
   76945       testcase( aKey[0]&0x80 );
   76946       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
   76947       return (i64)*(i64*)&x;
   76948     }
   76949   }
   76950 
   76951   return (serial_type - 8);
   76952 }
   76953 
   76954 /*
   76955 ** This function compares the two table rows or index records
   76956 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
   76957 ** or positive integer if key1 is less than, equal to or
   76958 ** greater than key2.  The {nKey1, pKey1} key must be a blob
   76959 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
   76960 ** key must be a parsed key such as obtained from
   76961 ** sqlite3VdbeParseRecord.
   76962 **
   76963 ** If argument bSkip is non-zero, it is assumed that the caller has already
   76964 ** determined that the first fields of the keys are equal.
   76965 **
   76966 ** Key1 and Key2 do not have to contain the same number of fields. If all
   76967 ** fields that appear in both keys are equal, then pPKey2->default_rc is
   76968 ** returned.
   76969 **
   76970 ** If database corruption is discovered, set pPKey2->errCode to
   76971 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
   76972 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
   76973 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
   76974 */
   76975 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
   76976   int nKey1, const void *pKey1,   /* Left key */
   76977   UnpackedRecord *pPKey2,         /* Right key */
   76978   int bSkip                       /* If true, skip the first field */
   76979 ){
   76980   u32 d1;                         /* Offset into aKey[] of next data element */
   76981   int i;                          /* Index of next field to compare */
   76982   u32 szHdr1;                     /* Size of record header in bytes */
   76983   u32 idx1;                       /* Offset of first type in header */
   76984   int rc = 0;                     /* Return value */
   76985   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
   76986   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
   76987   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   76988   Mem mem1;
   76989 
   76990   /* If bSkip is true, then the caller has already determined that the first
   76991   ** two elements in the keys are equal. Fix the various stack variables so
   76992   ** that this routine begins comparing at the second field. */
   76993   if( bSkip ){
   76994     u32 s1;
   76995     idx1 = 1 + getVarint32(&aKey1[1], s1);
   76996     szHdr1 = aKey1[0];
   76997     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
   76998     i = 1;
   76999     pRhs++;
   77000   }else{
   77001     idx1 = getVarint32(aKey1, szHdr1);
   77002     d1 = szHdr1;
   77003     if( d1>(unsigned)nKey1 ){
   77004       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
   77005       return 0;  /* Corruption */
   77006     }
   77007     i = 0;
   77008   }
   77009 
   77010   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
   77011   assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
   77012        || CORRUPT_DB );
   77013   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
   77014   assert( pPKey2->pKeyInfo->nKeyField>0 );
   77015   assert( idx1<=szHdr1 || CORRUPT_DB );
   77016   do{
   77017     u32 serial_type;
   77018 
   77019     /* RHS is an integer */
   77020     if( pRhs->flags & MEM_Int ){
   77021       serial_type = aKey1[idx1];
   77022       testcase( serial_type==12 );
   77023       if( serial_type>=10 ){
   77024         rc = +1;
   77025       }else if( serial_type==0 ){
   77026         rc = -1;
   77027       }else if( serial_type==7 ){
   77028         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
   77029         rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
   77030       }else{
   77031         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
   77032         i64 rhs = pRhs->u.i;
   77033         if( lhs<rhs ){
   77034           rc = -1;
   77035         }else if( lhs>rhs ){
   77036           rc = +1;
   77037         }
   77038       }
   77039     }
   77040 
   77041     /* RHS is real */
   77042     else if( pRhs->flags & MEM_Real ){
   77043       serial_type = aKey1[idx1];
   77044       if( serial_type>=10 ){
   77045         /* Serial types 12 or greater are strings and blobs (greater than
   77046         ** numbers). Types 10 and 11 are currently "reserved for future
   77047         ** use", so it doesn't really matter what the results of comparing
   77048         ** them to numberic values are.  */
   77049         rc = +1;
   77050       }else if( serial_type==0 ){
   77051         rc = -1;
   77052       }else{
   77053         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
   77054         if( serial_type==7 ){
   77055           if( mem1.u.r<pRhs->u.r ){
   77056             rc = -1;
   77057           }else if( mem1.u.r>pRhs->u.r ){
   77058             rc = +1;
   77059           }
   77060         }else{
   77061           rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
   77062         }
   77063       }
   77064     }
   77065 
   77066     /* RHS is a string */
   77067     else if( pRhs->flags & MEM_Str ){
   77068       getVarint32(&aKey1[idx1], serial_type);
   77069       testcase( serial_type==12 );
   77070       if( serial_type<12 ){
   77071         rc = -1;
   77072       }else if( !(serial_type & 0x01) ){
   77073         rc = +1;
   77074       }else{
   77075         mem1.n = (serial_type - 12) / 2;
   77076         testcase( (d1+mem1.n)==(unsigned)nKey1 );
   77077         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
   77078         if( (d1+mem1.n) > (unsigned)nKey1 ){
   77079           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
   77080           return 0;                /* Corruption */
   77081         }else if( pKeyInfo->aColl[i] ){
   77082           mem1.enc = pKeyInfo->enc;
   77083           mem1.db = pKeyInfo->db;
   77084           mem1.flags = MEM_Str;
   77085           mem1.z = (char*)&aKey1[d1];
   77086           rc = vdbeCompareMemString(
   77087               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
   77088           );
   77089         }else{
   77090           int nCmp = MIN(mem1.n, pRhs->n);
   77091           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
   77092           if( rc==0 ) rc = mem1.n - pRhs->n;
   77093         }
   77094       }
   77095     }
   77096 
   77097     /* RHS is a blob */
   77098     else if( pRhs->flags & MEM_Blob ){
   77099       assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
   77100       getVarint32(&aKey1[idx1], serial_type);
   77101       testcase( serial_type==12 );
   77102       if( serial_type<12 || (serial_type & 0x01) ){
   77103         rc = -1;
   77104       }else{
   77105         int nStr = (serial_type - 12) / 2;
   77106         testcase( (d1+nStr)==(unsigned)nKey1 );
   77107         testcase( (d1+nStr+1)==(unsigned)nKey1 );
   77108         if( (d1+nStr) > (unsigned)nKey1 ){
   77109           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
   77110           return 0;                /* Corruption */
   77111         }else if( pRhs->flags & MEM_Zero ){
   77112           if( !isAllZero((const char*)&aKey1[d1],nStr) ){
   77113             rc = 1;
   77114           }else{
   77115             rc = nStr - pRhs->u.nZero;
   77116           }
   77117         }else{
   77118           int nCmp = MIN(nStr, pRhs->n);
   77119           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
   77120           if( rc==0 ) rc = nStr - pRhs->n;
   77121         }
   77122       }
   77123     }
   77124 
   77125     /* RHS is null */
   77126     else{
   77127       serial_type = aKey1[idx1];
   77128       rc = (serial_type!=0);
   77129     }
   77130 
   77131     if( rc!=0 ){
   77132       if( pKeyInfo->aSortOrder[i] ){
   77133         rc = -rc;
   77134       }
   77135       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
   77136       assert( mem1.szMalloc==0 );  /* See comment below */
   77137       return rc;
   77138     }
   77139 
   77140     i++;
   77141     pRhs++;
   77142     d1 += sqlite3VdbeSerialTypeLen(serial_type);
   77143     idx1 += sqlite3VarintLen(serial_type);
   77144   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
   77145 
   77146   /* No memory allocation is ever used on mem1.  Prove this using
   77147   ** the following assert().  If the assert() fails, it indicates a
   77148   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
   77149   assert( mem1.szMalloc==0 );
   77150 
   77151   /* rc==0 here means that one or both of the keys ran out of fields and
   77152   ** all the fields up to that point were equal. Return the default_rc
   77153   ** value.  */
   77154   assert( CORRUPT_DB
   77155        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
   77156        || pKeyInfo->db->mallocFailed
   77157   );
   77158   pPKey2->eqSeen = 1;
   77159   return pPKey2->default_rc;
   77160 }
   77161 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
   77162   int nKey1, const void *pKey1,   /* Left key */
   77163   UnpackedRecord *pPKey2          /* Right key */
   77164 ){
   77165   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
   77166 }
   77167 
   77168 
   77169 /*
   77170 ** This function is an optimized version of sqlite3VdbeRecordCompare()
   77171 ** that (a) the first field of pPKey2 is an integer, and (b) the
   77172 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
   77173 ** byte (i.e. is less than 128).
   77174 **
   77175 ** To avoid concerns about buffer overreads, this routine is only used
   77176 ** on schemas where the maximum valid header size is 63 bytes or less.
   77177 */
   77178 static int vdbeRecordCompareInt(
   77179   int nKey1, const void *pKey1, /* Left key */
   77180   UnpackedRecord *pPKey2        /* Right key */
   77181 ){
   77182   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
   77183   int serial_type = ((const u8*)pKey1)[1];
   77184   int res;
   77185   u32 y;
   77186   u64 x;
   77187   i64 v;
   77188   i64 lhs;
   77189 
   77190   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
   77191   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
   77192   switch( serial_type ){
   77193     case 1: { /* 1-byte signed integer */
   77194       lhs = ONE_BYTE_INT(aKey);
   77195       testcase( lhs<0 );
   77196       break;
   77197     }
   77198     case 2: { /* 2-byte signed integer */
   77199       lhs = TWO_BYTE_INT(aKey);
   77200       testcase( lhs<0 );
   77201       break;
   77202     }
   77203     case 3: { /* 3-byte signed integer */
   77204       lhs = THREE_BYTE_INT(aKey);
   77205       testcase( lhs<0 );
   77206       break;
   77207     }
   77208     case 4: { /* 4-byte signed integer */
   77209       y = FOUR_BYTE_UINT(aKey);
   77210       lhs = (i64)*(int*)&y;
   77211       testcase( lhs<0 );
   77212       break;
   77213     }
   77214     case 5: { /* 6-byte signed integer */
   77215       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
   77216       testcase( lhs<0 );
   77217       break;
   77218     }
   77219     case 6: { /* 8-byte signed integer */
   77220       x = FOUR_BYTE_UINT(aKey);
   77221       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
   77222       lhs = *(i64*)&x;
   77223       testcase( lhs<0 );
   77224       break;
   77225     }
   77226     case 8:
   77227       lhs = 0;
   77228       break;
   77229     case 9:
   77230       lhs = 1;
   77231       break;
   77232 
   77233     /* This case could be removed without changing the results of running
   77234     ** this code. Including it causes gcc to generate a faster switch
   77235     ** statement (since the range of switch targets now starts at zero and
   77236     ** is contiguous) but does not cause any duplicate code to be generated
   77237     ** (as gcc is clever enough to combine the two like cases). Other
   77238     ** compilers might be similar.  */
   77239     case 0: case 7:
   77240       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
   77241 
   77242     default:
   77243       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
   77244   }
   77245 
   77246   v = pPKey2->aMem[0].u.i;
   77247   if( v>lhs ){
   77248     res = pPKey2->r1;
   77249   }else if( v<lhs ){
   77250     res = pPKey2->r2;
   77251   }else if( pPKey2->nField>1 ){
   77252     /* The first fields of the two keys are equal. Compare the trailing
   77253     ** fields.  */
   77254     res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
   77255   }else{
   77256     /* The first fields of the two keys are equal and there are no trailing
   77257     ** fields. Return pPKey2->default_rc in this case. */
   77258     res = pPKey2->default_rc;
   77259     pPKey2->eqSeen = 1;
   77260   }
   77261 
   77262   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
   77263   return res;
   77264 }
   77265 
   77266 /*
   77267 ** This function is an optimized version of sqlite3VdbeRecordCompare()
   77268 ** that (a) the first field of pPKey2 is a string, that (b) the first field
   77269 ** uses the collation sequence BINARY and (c) that the size-of-header varint
   77270 ** at the start of (pKey1/nKey1) fits in a single byte.
   77271 */
   77272 static int vdbeRecordCompareString(
   77273   int nKey1, const void *pKey1, /* Left key */
   77274   UnpackedRecord *pPKey2        /* Right key */
   77275 ){
   77276   const u8 *aKey1 = (const u8*)pKey1;
   77277   int serial_type;
   77278   int res;
   77279 
   77280   assert( pPKey2->aMem[0].flags & MEM_Str );
   77281   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
   77282   getVarint32(&aKey1[1], serial_type);
   77283   if( serial_type<12 ){
   77284     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
   77285   }else if( !(serial_type & 0x01) ){
   77286     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
   77287   }else{
   77288     int nCmp;
   77289     int nStr;
   77290     int szHdr = aKey1[0];
   77291 
   77292     nStr = (serial_type-12) / 2;
   77293     if( (szHdr + nStr) > nKey1 ){
   77294       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
   77295       return 0;    /* Corruption */
   77296     }
   77297     nCmp = MIN( pPKey2->aMem[0].n, nStr );
   77298     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
   77299 
   77300     if( res==0 ){
   77301       res = nStr - pPKey2->aMem[0].n;
   77302       if( res==0 ){
   77303         if( pPKey2->nField>1 ){
   77304           res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
   77305         }else{
   77306           res = pPKey2->default_rc;
   77307           pPKey2->eqSeen = 1;
   77308         }
   77309       }else if( res>0 ){
   77310         res = pPKey2->r2;
   77311       }else{
   77312         res = pPKey2->r1;
   77313       }
   77314     }else if( res>0 ){
   77315       res = pPKey2->r2;
   77316     }else{
   77317       res = pPKey2->r1;
   77318     }
   77319   }
   77320 
   77321   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
   77322        || CORRUPT_DB
   77323        || pPKey2->pKeyInfo->db->mallocFailed
   77324   );
   77325   return res;
   77326 }
   77327 
   77328 /*
   77329 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
   77330 ** suitable for comparing serialized records to the unpacked record passed
   77331 ** as the only argument.
   77332 */
   77333 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
   77334   /* varintRecordCompareInt() and varintRecordCompareString() both assume
   77335   ** that the size-of-header varint that occurs at the start of each record
   77336   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
   77337   ** also assumes that it is safe to overread a buffer by at least the
   77338   ** maximum possible legal header size plus 8 bytes. Because there is
   77339   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
   77340   ** buffer passed to varintRecordCompareInt() this makes it convenient to
   77341   ** limit the size of the header to 64 bytes in cases where the first field
   77342   ** is an integer.
   77343   **
   77344   ** The easiest way to enforce this limit is to consider only records with
   77345   ** 13 fields or less. If the first field is an integer, the maximum legal
   77346   ** header size is (12*5 + 1 + 1) bytes.  */
   77347   if( p->pKeyInfo->nAllField<=13 ){
   77348     int flags = p->aMem[0].flags;
   77349     if( p->pKeyInfo->aSortOrder[0] ){
   77350       p->r1 = 1;
   77351       p->r2 = -1;
   77352     }else{
   77353       p->r1 = -1;
   77354       p->r2 = 1;
   77355     }
   77356     if( (flags & MEM_Int) ){
   77357       return vdbeRecordCompareInt;
   77358     }
   77359     testcase( flags & MEM_Real );
   77360     testcase( flags & MEM_Null );
   77361     testcase( flags & MEM_Blob );
   77362     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
   77363       assert( flags & MEM_Str );
   77364       return vdbeRecordCompareString;
   77365     }
   77366   }
   77367 
   77368   return sqlite3VdbeRecordCompare;
   77369 }
   77370 
   77371 /*
   77372 ** pCur points at an index entry created using the OP_MakeRecord opcode.
   77373 ** Read the rowid (the last field in the record) and store it in *rowid.
   77374 ** Return SQLITE_OK if everything works, or an error code otherwise.
   77375 **
   77376 ** pCur might be pointing to text obtained from a corrupt database file.
   77377 ** So the content cannot be trusted.  Do appropriate checks on the content.
   77378 */
   77379 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   77380   i64 nCellKey = 0;
   77381   int rc;
   77382   u32 szHdr;        /* Size of the header */
   77383   u32 typeRowid;    /* Serial type of the rowid */
   77384   u32 lenRowid;     /* Size of the rowid */
   77385   Mem m, v;
   77386 
   77387   /* Get the size of the index entry.  Only indices entries of less
   77388   ** than 2GiB are support - anything large must be database corruption.
   77389   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
   77390   ** this code can safely assume that nCellKey is 32-bits
   77391   */
   77392   assert( sqlite3BtreeCursorIsValid(pCur) );
   77393   nCellKey = sqlite3BtreePayloadSize(pCur);
   77394   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
   77395 
   77396   /* Read in the complete content of the index entry */
   77397   sqlite3VdbeMemInit(&m, db, 0);
   77398   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
   77399   if( rc ){
   77400     return rc;
   77401   }
   77402 
   77403   /* The index entry must begin with a header size */
   77404   (void)getVarint32((u8*)m.z, szHdr);
   77405   testcase( szHdr==3 );
   77406   testcase( szHdr==m.n );
   77407   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
   77408     goto idx_rowid_corruption;
   77409   }
   77410 
   77411   /* The last field of the index should be an integer - the ROWID.
   77412   ** Verify that the last entry really is an integer. */
   77413   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
   77414   testcase( typeRowid==1 );
   77415   testcase( typeRowid==2 );
   77416   testcase( typeRowid==3 );
   77417   testcase( typeRowid==4 );
   77418   testcase( typeRowid==5 );
   77419   testcase( typeRowid==6 );
   77420   testcase( typeRowid==8 );
   77421   testcase( typeRowid==9 );
   77422   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
   77423     goto idx_rowid_corruption;
   77424   }
   77425   lenRowid = sqlite3SmallTypeSizes[typeRowid];
   77426   testcase( (u32)m.n==szHdr+lenRowid );
   77427   if( unlikely((u32)m.n<szHdr+lenRowid) ){
   77428     goto idx_rowid_corruption;
   77429   }
   77430 
   77431   /* Fetch the integer off the end of the index record */
   77432   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
   77433   *rowid = v.u.i;
   77434   sqlite3VdbeMemRelease(&m);
   77435   return SQLITE_OK;
   77436 
   77437   /* Jump here if database corruption is detected after m has been
   77438   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
   77439 idx_rowid_corruption:
   77440   testcase( m.szMalloc!=0 );
   77441   sqlite3VdbeMemRelease(&m);
   77442   return SQLITE_CORRUPT_BKPT;
   77443 }
   77444 
   77445 /*
   77446 ** Compare the key of the index entry that cursor pC is pointing to against
   77447 ** the key string in pUnpacked.  Write into *pRes a number
   77448 ** that is negative, zero, or positive if pC is less than, equal to,
   77449 ** or greater than pUnpacked.  Return SQLITE_OK on success.
   77450 **
   77451 ** pUnpacked is either created without a rowid or is truncated so that it
   77452 ** omits the rowid at the end.  The rowid at the end of the index entry
   77453 ** is ignored as well.  Hence, this routine only compares the prefixes
   77454 ** of the keys prior to the final rowid, not the entire key.
   77455 */
   77456 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
   77457   sqlite3 *db,                     /* Database connection */
   77458   VdbeCursor *pC,                  /* The cursor to compare against */
   77459   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
   77460   int *res                         /* Write the comparison result here */
   77461 ){
   77462   i64 nCellKey = 0;
   77463   int rc;
   77464   BtCursor *pCur;
   77465   Mem m;
   77466 
   77467   assert( pC->eCurType==CURTYPE_BTREE );
   77468   pCur = pC->uc.pCursor;
   77469   assert( sqlite3BtreeCursorIsValid(pCur) );
   77470   nCellKey = sqlite3BtreePayloadSize(pCur);
   77471   /* nCellKey will always be between 0 and 0xffffffff because of the way
   77472   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
   77473   if( nCellKey<=0 || nCellKey>0x7fffffff ){
   77474     *res = 0;
   77475     return SQLITE_CORRUPT_BKPT;
   77476   }
   77477   sqlite3VdbeMemInit(&m, db, 0);
   77478   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
   77479   if( rc ){
   77480     return rc;
   77481   }
   77482   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
   77483   sqlite3VdbeMemRelease(&m);
   77484   return SQLITE_OK;
   77485 }
   77486 
   77487 /*
   77488 ** This routine sets the value to be returned by subsequent calls to
   77489 ** sqlite3_changes() on the database handle 'db'.
   77490 */
   77491 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
   77492   assert( sqlite3_mutex_held(db->mutex) );
   77493   db->nChange = nChange;
   77494   db->nTotalChange += nChange;
   77495 }
   77496 
   77497 /*
   77498 ** Set a flag in the vdbe to update the change counter when it is finalised
   77499 ** or reset.
   77500 */
   77501 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
   77502   v->changeCntOn = 1;
   77503 }
   77504 
   77505 /*
   77506 ** Mark every prepared statement associated with a database connection
   77507 ** as expired.
   77508 **
   77509 ** An expired statement means that recompilation of the statement is
   77510 ** recommend.  Statements expire when things happen that make their
   77511 ** programs obsolete.  Removing user-defined functions or collating
   77512 ** sequences, or changing an authorization function are the types of
   77513 ** things that make prepared statements obsolete.
   77514 */
   77515 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
   77516   Vdbe *p;
   77517   for(p = db->pVdbe; p; p=p->pNext){
   77518     p->expired = 1;
   77519   }
   77520 }
   77521 
   77522 /*
   77523 ** Return the database associated with the Vdbe.
   77524 */
   77525 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
   77526   return v->db;
   77527 }
   77528 
   77529 /*
   77530 ** Return the SQLITE_PREPARE flags for a Vdbe.
   77531 */
   77532 SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
   77533   return v->prepFlags;
   77534 }
   77535 
   77536 /*
   77537 ** Return a pointer to an sqlite3_value structure containing the value bound
   77538 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
   77539 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
   77540 ** constants) to the value before returning it.
   77541 **
   77542 ** The returned value must be freed by the caller using sqlite3ValueFree().
   77543 */
   77544 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
   77545   assert( iVar>0 );
   77546   if( v ){
   77547     Mem *pMem = &v->aVar[iVar-1];
   77548     assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
   77549     if( 0==(pMem->flags & MEM_Null) ){
   77550       sqlite3_value *pRet = sqlite3ValueNew(v->db);
   77551       if( pRet ){
   77552         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
   77553         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
   77554       }
   77555       return pRet;
   77556     }
   77557   }
   77558   return 0;
   77559 }
   77560 
   77561 /*
   77562 ** Configure SQL variable iVar so that binding a new value to it signals
   77563 ** to sqlite3_reoptimize() that re-preparing the statement may result
   77564 ** in a better query plan.
   77565 */
   77566 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
   77567   assert( iVar>0 );
   77568   assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
   77569   if( iVar>=32 ){
   77570     v->expmask |= 0x80000000;
   77571   }else{
   77572     v->expmask |= ((u32)1 << (iVar-1));
   77573   }
   77574 }
   77575 
   77576 /*
   77577 ** Cause a function to throw an error if it was call from OP_PureFunc
   77578 ** rather than OP_Function.
   77579 **
   77580 ** OP_PureFunc means that the function must be deterministic, and should
   77581 ** throw an error if it is given inputs that would make it non-deterministic.
   77582 ** This routine is invoked by date/time functions that use non-deterministic
   77583 ** features such as 'now'.
   77584 */
   77585 SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
   77586 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   77587   if( pCtx->pVdbe==0 ) return 1;
   77588 #endif
   77589   if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
   77590     sqlite3_result_error(pCtx,
   77591        "non-deterministic function in index expression or CHECK constraint",
   77592        -1);
   77593     return 0;
   77594   }
   77595   return 1;
   77596 }
   77597 
   77598 #ifndef SQLITE_OMIT_VIRTUALTABLE
   77599 /*
   77600 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
   77601 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
   77602 ** in memory obtained from sqlite3DbMalloc).
   77603 */
   77604 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
   77605   if( pVtab->zErrMsg ){
   77606     sqlite3 *db = p->db;
   77607     sqlite3DbFree(db, p->zErrMsg);
   77608     p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   77609     sqlite3_free(pVtab->zErrMsg);
   77610     pVtab->zErrMsg = 0;
   77611   }
   77612 }
   77613 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   77614 
   77615 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   77616 
   77617 /*
   77618 ** If the second argument is not NULL, release any allocations associated
   77619 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
   77620 ** structure itself, using sqlite3DbFree().
   77621 **
   77622 ** This function is used to free UnpackedRecord structures allocated by
   77623 ** the vdbeUnpackRecord() function found in vdbeapi.c.
   77624 */
   77625 static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
   77626   if( p ){
   77627     int i;
   77628     for(i=0; i<nField; i++){
   77629       Mem *pMem = &p->aMem[i];
   77630       if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
   77631     }
   77632     sqlite3DbFreeNN(db, p);
   77633   }
   77634 }
   77635 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   77636 
   77637 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   77638 /*
   77639 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
   77640 ** then cursor passed as the second argument should point to the row about
   77641 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
   77642 ** the required value will be read from the row the cursor points to.
   77643 */
   77644 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
   77645   Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
   77646   VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
   77647   int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
   77648   const char *zDb,                /* Database name */
   77649   Table *pTab,                    /* Modified table */
   77650   i64 iKey1,                      /* Initial key value */
   77651   int iReg                        /* Register for new.* record */
   77652 ){
   77653   sqlite3 *db = v->db;
   77654   i64 iKey2;
   77655   PreUpdate preupdate;
   77656   const char *zTbl = pTab->zName;
   77657   static const u8 fakeSortOrder = 0;
   77658 
   77659   assert( db->pPreUpdate==0 );
   77660   memset(&preupdate, 0, sizeof(PreUpdate));
   77661   if( HasRowid(pTab)==0 ){
   77662     iKey1 = iKey2 = 0;
   77663     preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
   77664   }else{
   77665     if( op==SQLITE_UPDATE ){
   77666       iKey2 = v->aMem[iReg].u.i;
   77667     }else{
   77668       iKey2 = iKey1;
   77669     }
   77670   }
   77671 
   77672   assert( pCsr->nField==pTab->nCol
   77673        || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
   77674   );
   77675 
   77676   preupdate.v = v;
   77677   preupdate.pCsr = pCsr;
   77678   preupdate.op = op;
   77679   preupdate.iNewReg = iReg;
   77680   preupdate.keyinfo.db = db;
   77681   preupdate.keyinfo.enc = ENC(db);
   77682   preupdate.keyinfo.nKeyField = pTab->nCol;
   77683   preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
   77684   preupdate.iKey1 = iKey1;
   77685   preupdate.iKey2 = iKey2;
   77686   preupdate.pTab = pTab;
   77687 
   77688   db->pPreUpdate = &preupdate;
   77689   db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
   77690   db->pPreUpdate = 0;
   77691   sqlite3DbFree(db, preupdate.aRecord);
   77692   vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
   77693   vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
   77694   if( preupdate.aNew ){
   77695     int i;
   77696     for(i=0; i<pCsr->nField; i++){
   77697       sqlite3VdbeMemRelease(&preupdate.aNew[i]);
   77698     }
   77699     sqlite3DbFreeNN(db, preupdate.aNew);
   77700   }
   77701 }
   77702 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   77703 
   77704 /************** End of vdbeaux.c *********************************************/
   77705 /************** Begin file vdbeapi.c *****************************************/
   77706 /*
   77707 ** 2004 May 26
   77708 **
   77709 ** The author disclaims copyright to this source code.  In place of
   77710 ** a legal notice, here is a blessing:
   77711 **
   77712 **    May you do good and not evil.
   77713 **    May you find forgiveness for yourself and forgive others.
   77714 **    May you share freely, never taking more than you give.
   77715 **
   77716 *************************************************************************
   77717 **
   77718 ** This file contains code use to implement APIs that are part of the
   77719 ** VDBE.
   77720 */
   77721 /* #include "sqliteInt.h" */
   77722 /* #include "vdbeInt.h" */
   77723 
   77724 #ifndef SQLITE_OMIT_DEPRECATED
   77725 /*
   77726 ** Return TRUE (non-zero) of the statement supplied as an argument needs
   77727 ** to be recompiled.  A statement needs to be recompiled whenever the
   77728 ** execution environment changes in a way that would alter the program
   77729 ** that sqlite3_prepare() generates.  For example, if new functions or
   77730 ** collating sequences are registered or if an authorizer function is
   77731 ** added or changed.
   77732 */
   77733 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
   77734   Vdbe *p = (Vdbe*)pStmt;
   77735   return p==0 || p->expired;
   77736 }
   77737 #endif
   77738 
   77739 /*
   77740 ** Check on a Vdbe to make sure it has not been finalized.  Log
   77741 ** an error and return true if it has been finalized (or is otherwise
   77742 ** invalid).  Return false if it is ok.
   77743 */
   77744 static int vdbeSafety(Vdbe *p){
   77745   if( p->db==0 ){
   77746     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
   77747     return 1;
   77748   }else{
   77749     return 0;
   77750   }
   77751 }
   77752 static int vdbeSafetyNotNull(Vdbe *p){
   77753   if( p==0 ){
   77754     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
   77755     return 1;
   77756   }else{
   77757     return vdbeSafety(p);
   77758   }
   77759 }
   77760 
   77761 #ifndef SQLITE_OMIT_TRACE
   77762 /*
   77763 ** Invoke the profile callback.  This routine is only called if we already
   77764 ** know that the profile callback is defined and needs to be invoked.
   77765 */
   77766 static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
   77767   sqlite3_int64 iNow;
   77768   sqlite3_int64 iElapse;
   77769   assert( p->startTime>0 );
   77770   assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
   77771   assert( db->init.busy==0 );
   77772   assert( p->zSql!=0 );
   77773   sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
   77774   iElapse = (iNow - p->startTime)*1000000;
   77775   if( db->xProfile ){
   77776     db->xProfile(db->pProfileArg, p->zSql, iElapse);
   77777   }
   77778   if( db->mTrace & SQLITE_TRACE_PROFILE ){
   77779     db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
   77780   }
   77781   p->startTime = 0;
   77782 }
   77783 /*
   77784 ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
   77785 ** is needed, and it invokes the callback if it is needed.
   77786 */
   77787 # define checkProfileCallback(DB,P) \
   77788    if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
   77789 #else
   77790 # define checkProfileCallback(DB,P)  /*no-op*/
   77791 #endif
   77792 
   77793 /*
   77794 ** The following routine destroys a virtual machine that is created by
   77795 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
   77796 ** success/failure code that describes the result of executing the virtual
   77797 ** machine.
   77798 **
   77799 ** This routine sets the error code and string returned by
   77800 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   77801 */
   77802 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
   77803   int rc;
   77804   if( pStmt==0 ){
   77805     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
   77806     ** pointer is a harmless no-op. */
   77807     rc = SQLITE_OK;
   77808   }else{
   77809     Vdbe *v = (Vdbe*)pStmt;
   77810     sqlite3 *db = v->db;
   77811     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
   77812     sqlite3_mutex_enter(db->mutex);
   77813     checkProfileCallback(db, v);
   77814     rc = sqlite3VdbeFinalize(v);
   77815     rc = sqlite3ApiExit(db, rc);
   77816     sqlite3LeaveMutexAndCloseZombie(db);
   77817   }
   77818   return rc;
   77819 }
   77820 
   77821 /*
   77822 ** Terminate the current execution of an SQL statement and reset it
   77823 ** back to its starting state so that it can be reused. A success code from
   77824 ** the prior execution is returned.
   77825 **
   77826 ** This routine sets the error code and string returned by
   77827 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   77828 */
   77829 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
   77830   int rc;
   77831   if( pStmt==0 ){
   77832     rc = SQLITE_OK;
   77833   }else{
   77834     Vdbe *v = (Vdbe*)pStmt;
   77835     sqlite3 *db = v->db;
   77836     sqlite3_mutex_enter(db->mutex);
   77837     checkProfileCallback(db, v);
   77838     rc = sqlite3VdbeReset(v);
   77839     sqlite3VdbeRewind(v);
   77840     assert( (rc & (db->errMask))==rc );
   77841     rc = sqlite3ApiExit(db, rc);
   77842     sqlite3_mutex_leave(db->mutex);
   77843   }
   77844   return rc;
   77845 }
   77846 
   77847 /*
   77848 ** Set all the parameters in the compiled SQL statement to NULL.
   77849 */
   77850 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
   77851   int i;
   77852   int rc = SQLITE_OK;
   77853   Vdbe *p = (Vdbe*)pStmt;
   77854 #if SQLITE_THREADSAFE
   77855   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
   77856 #endif
   77857   sqlite3_mutex_enter(mutex);
   77858   for(i=0; i<p->nVar; i++){
   77859     sqlite3VdbeMemRelease(&p->aVar[i]);
   77860     p->aVar[i].flags = MEM_Null;
   77861   }
   77862   assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
   77863   if( p->expmask ){
   77864     p->expired = 1;
   77865   }
   77866   sqlite3_mutex_leave(mutex);
   77867   return rc;
   77868 }
   77869 
   77870 
   77871 /**************************** sqlite3_value_  *******************************
   77872 ** The following routines extract information from a Mem or sqlite3_value
   77873 ** structure.
   77874 */
   77875 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
   77876   Mem *p = (Mem*)pVal;
   77877   if( p->flags & (MEM_Blob|MEM_Str) ){
   77878     if( ExpandBlob(p)!=SQLITE_OK ){
   77879       assert( p->flags==MEM_Null && p->z==0 );
   77880       return 0;
   77881     }
   77882     p->flags |= MEM_Blob;
   77883     return p->n ? p->z : 0;
   77884   }else{
   77885     return sqlite3_value_text(pVal);
   77886   }
   77887 }
   77888 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
   77889   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
   77890 }
   77891 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
   77892   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
   77893 }
   77894 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
   77895   return sqlite3VdbeRealValue((Mem*)pVal);
   77896 }
   77897 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
   77898   return (int)sqlite3VdbeIntValue((Mem*)pVal);
   77899 }
   77900 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   77901   return sqlite3VdbeIntValue((Mem*)pVal);
   77902 }
   77903 SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
   77904   Mem *pMem = (Mem*)pVal;
   77905   return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
   77906 }
   77907 SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
   77908   Mem *p = (Mem*)pVal;
   77909   if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
   77910                  (MEM_Null|MEM_Term|MEM_Subtype)
   77911    && zPType!=0
   77912    && p->eSubtype=='p'
   77913    && strcmp(p->u.zPType, zPType)==0
   77914   ){
   77915     return (void*)p->z;
   77916   }else{
   77917     return 0;
   77918   }
   77919 }
   77920 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   77921   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   77922 }
   77923 #ifndef SQLITE_OMIT_UTF16
   77924 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
   77925   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
   77926 }
   77927 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
   77928   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
   77929 }
   77930 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
   77931   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
   77932 }
   77933 #endif /* SQLITE_OMIT_UTF16 */
   77934 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
   77935 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
   77936 ** point number string BLOB NULL
   77937 */
   77938 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
   77939   static const u8 aType[] = {
   77940      SQLITE_BLOB,     /* 0x00 */
   77941      SQLITE_NULL,     /* 0x01 */
   77942      SQLITE_TEXT,     /* 0x02 */
   77943      SQLITE_NULL,     /* 0x03 */
   77944      SQLITE_INTEGER,  /* 0x04 */
   77945      SQLITE_NULL,     /* 0x05 */
   77946      SQLITE_INTEGER,  /* 0x06 */
   77947      SQLITE_NULL,     /* 0x07 */
   77948      SQLITE_FLOAT,    /* 0x08 */
   77949      SQLITE_NULL,     /* 0x09 */
   77950      SQLITE_FLOAT,    /* 0x0a */
   77951      SQLITE_NULL,     /* 0x0b */
   77952      SQLITE_INTEGER,  /* 0x0c */
   77953      SQLITE_NULL,     /* 0x0d */
   77954      SQLITE_INTEGER,  /* 0x0e */
   77955      SQLITE_NULL,     /* 0x0f */
   77956      SQLITE_BLOB,     /* 0x10 */
   77957      SQLITE_NULL,     /* 0x11 */
   77958      SQLITE_TEXT,     /* 0x12 */
   77959      SQLITE_NULL,     /* 0x13 */
   77960      SQLITE_INTEGER,  /* 0x14 */
   77961      SQLITE_NULL,     /* 0x15 */
   77962      SQLITE_INTEGER,  /* 0x16 */
   77963      SQLITE_NULL,     /* 0x17 */
   77964      SQLITE_FLOAT,    /* 0x18 */
   77965      SQLITE_NULL,     /* 0x19 */
   77966      SQLITE_FLOAT,    /* 0x1a */
   77967      SQLITE_NULL,     /* 0x1b */
   77968      SQLITE_INTEGER,  /* 0x1c */
   77969      SQLITE_NULL,     /* 0x1d */
   77970      SQLITE_INTEGER,  /* 0x1e */
   77971      SQLITE_NULL,     /* 0x1f */
   77972   };
   77973   return aType[pVal->flags&MEM_AffMask];
   77974 }
   77975 
   77976 /* Return true if a parameter to xUpdate represents an unchanged column */
   77977 SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
   77978   return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
   77979 }
   77980 
   77981 /* Make a copy of an sqlite3_value object
   77982 */
   77983 SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
   77984   sqlite3_value *pNew;
   77985   if( pOrig==0 ) return 0;
   77986   pNew = sqlite3_malloc( sizeof(*pNew) );
   77987   if( pNew==0 ) return 0;
   77988   memset(pNew, 0, sizeof(*pNew));
   77989   memcpy(pNew, pOrig, MEMCELLSIZE);
   77990   pNew->flags &= ~MEM_Dyn;
   77991   pNew->db = 0;
   77992   if( pNew->flags&(MEM_Str|MEM_Blob) ){
   77993     pNew->flags &= ~(MEM_Static|MEM_Dyn);
   77994     pNew->flags |= MEM_Ephem;
   77995     if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
   77996       sqlite3ValueFree(pNew);
   77997       pNew = 0;
   77998     }
   77999   }
   78000   return pNew;
   78001 }
   78002 
   78003 /* Destroy an sqlite3_value object previously obtained from
   78004 ** sqlite3_value_dup().
   78005 */
   78006 SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
   78007   sqlite3ValueFree(pOld);
   78008 }
   78009 
   78010 
   78011 /**************************** sqlite3_result_  *******************************
   78012 ** The following routines are used by user-defined functions to specify
   78013 ** the function result.
   78014 **
   78015 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
   78016 ** result as a string or blob but if the string or blob is too large, it
   78017 ** then sets the error code to SQLITE_TOOBIG
   78018 **
   78019 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
   78020 ** on value P is not going to be used and need to be destroyed.
   78021 */
   78022 static void setResultStrOrError(
   78023   sqlite3_context *pCtx,  /* Function context */
   78024   const char *z,          /* String pointer */
   78025   int n,                  /* Bytes in string, or negative */
   78026   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   78027   void (*xDel)(void*)     /* Destructor function */
   78028 ){
   78029   if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
   78030     sqlite3_result_error_toobig(pCtx);
   78031   }
   78032 }
   78033 static int invokeValueDestructor(
   78034   const void *p,             /* Value to destroy */
   78035   void (*xDel)(void*),       /* The destructor */
   78036   sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
   78037 ){
   78038   assert( xDel!=SQLITE_DYNAMIC );
   78039   if( xDel==0 ){
   78040     /* noop */
   78041   }else if( xDel==SQLITE_TRANSIENT ){
   78042     /* noop */
   78043   }else{
   78044     xDel((void*)p);
   78045   }
   78046   if( pCtx ) sqlite3_result_error_toobig(pCtx);
   78047   return SQLITE_TOOBIG;
   78048 }
   78049 SQLITE_API void sqlite3_result_blob(
   78050   sqlite3_context *pCtx,
   78051   const void *z,
   78052   int n,
   78053   void (*xDel)(void *)
   78054 ){
   78055   assert( n>=0 );
   78056   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78057   setResultStrOrError(pCtx, z, n, 0, xDel);
   78058 }
   78059 SQLITE_API void sqlite3_result_blob64(
   78060   sqlite3_context *pCtx,
   78061   const void *z,
   78062   sqlite3_uint64 n,
   78063   void (*xDel)(void *)
   78064 ){
   78065   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78066   assert( xDel!=SQLITE_DYNAMIC );
   78067   if( n>0x7fffffff ){
   78068     (void)invokeValueDestructor(z, xDel, pCtx);
   78069   }else{
   78070     setResultStrOrError(pCtx, z, (int)n, 0, xDel);
   78071   }
   78072 }
   78073 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
   78074   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78075   sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
   78076 }
   78077 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
   78078   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78079   pCtx->isError = SQLITE_ERROR;
   78080   pCtx->fErrorOrAux = 1;
   78081   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
   78082 }
   78083 #ifndef SQLITE_OMIT_UTF16
   78084 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
   78085   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78086   pCtx->isError = SQLITE_ERROR;
   78087   pCtx->fErrorOrAux = 1;
   78088   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
   78089 }
   78090 #endif
   78091 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   78092   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78093   sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
   78094 }
   78095 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   78096   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78097   sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
   78098 }
   78099 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
   78100   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78101   sqlite3VdbeMemSetNull(pCtx->pOut);
   78102 }
   78103 SQLITE_API void sqlite3_result_pointer(
   78104   sqlite3_context *pCtx,
   78105   void *pPtr,
   78106   const char *zPType,
   78107   void (*xDestructor)(void*)
   78108 ){
   78109   Mem *pOut = pCtx->pOut;
   78110   assert( sqlite3_mutex_held(pOut->db->mutex) );
   78111   sqlite3VdbeMemRelease(pOut);
   78112   pOut->flags = MEM_Null;
   78113   sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
   78114 }
   78115 SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
   78116   Mem *pOut = pCtx->pOut;
   78117   assert( sqlite3_mutex_held(pOut->db->mutex) );
   78118   pOut->eSubtype = eSubtype & 0xff;
   78119   pOut->flags |= MEM_Subtype;
   78120 }
   78121 SQLITE_API void sqlite3_result_text(
   78122   sqlite3_context *pCtx,
   78123   const char *z,
   78124   int n,
   78125   void (*xDel)(void *)
   78126 ){
   78127   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78128   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
   78129 }
   78130 SQLITE_API void sqlite3_result_text64(
   78131   sqlite3_context *pCtx,
   78132   const char *z,
   78133   sqlite3_uint64 n,
   78134   void (*xDel)(void *),
   78135   unsigned char enc
   78136 ){
   78137   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78138   assert( xDel!=SQLITE_DYNAMIC );
   78139   if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
   78140   if( n>0x7fffffff ){
   78141     (void)invokeValueDestructor(z, xDel, pCtx);
   78142   }else{
   78143     setResultStrOrError(pCtx, z, (int)n, enc, xDel);
   78144   }
   78145 }
   78146 #ifndef SQLITE_OMIT_UTF16
   78147 SQLITE_API void sqlite3_result_text16(
   78148   sqlite3_context *pCtx,
   78149   const void *z,
   78150   int n,
   78151   void (*xDel)(void *)
   78152 ){
   78153   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78154   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
   78155 }
   78156 SQLITE_API void sqlite3_result_text16be(
   78157   sqlite3_context *pCtx,
   78158   const void *z,
   78159   int n,
   78160   void (*xDel)(void *)
   78161 ){
   78162   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78163   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
   78164 }
   78165 SQLITE_API void sqlite3_result_text16le(
   78166   sqlite3_context *pCtx,
   78167   const void *z,
   78168   int n,
   78169   void (*xDel)(void *)
   78170 ){
   78171   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78172   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
   78173 }
   78174 #endif /* SQLITE_OMIT_UTF16 */
   78175 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
   78176   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78177   sqlite3VdbeMemCopy(pCtx->pOut, pValue);
   78178 }
   78179 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
   78180   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78181   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
   78182 }
   78183 SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
   78184   Mem *pOut = pCtx->pOut;
   78185   assert( sqlite3_mutex_held(pOut->db->mutex) );
   78186   if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
   78187     return SQLITE_TOOBIG;
   78188   }
   78189   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
   78190   return SQLITE_OK;
   78191 }
   78192 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   78193   pCtx->isError = errCode;
   78194   pCtx->fErrorOrAux = 1;
   78195 #ifdef SQLITE_DEBUG
   78196   if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
   78197 #endif
   78198   if( pCtx->pOut->flags & MEM_Null ){
   78199     sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
   78200                          SQLITE_UTF8, SQLITE_STATIC);
   78201   }
   78202 }
   78203 
   78204 /* Force an SQLITE_TOOBIG error. */
   78205 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   78206   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78207   pCtx->isError = SQLITE_TOOBIG;
   78208   pCtx->fErrorOrAux = 1;
   78209   sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
   78210                        SQLITE_UTF8, SQLITE_STATIC);
   78211 }
   78212 
   78213 /* An SQLITE_NOMEM error. */
   78214 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   78215   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78216   sqlite3VdbeMemSetNull(pCtx->pOut);
   78217   pCtx->isError = SQLITE_NOMEM_BKPT;
   78218   pCtx->fErrorOrAux = 1;
   78219   sqlite3OomFault(pCtx->pOut->db);
   78220 }
   78221 
   78222 /*
   78223 ** This function is called after a transaction has been committed. It
   78224 ** invokes callbacks registered with sqlite3_wal_hook() as required.
   78225 */
   78226 static int doWalCallbacks(sqlite3 *db){
   78227   int rc = SQLITE_OK;
   78228 #ifndef SQLITE_OMIT_WAL
   78229   int i;
   78230   for(i=0; i<db->nDb; i++){
   78231     Btree *pBt = db->aDb[i].pBt;
   78232     if( pBt ){
   78233       int nEntry;
   78234       sqlite3BtreeEnter(pBt);
   78235       nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
   78236       sqlite3BtreeLeave(pBt);
   78237       if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
   78238         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
   78239       }
   78240     }
   78241   }
   78242 #endif
   78243   return rc;
   78244 }
   78245 
   78246 
   78247 /*
   78248 ** Execute the statement pStmt, either until a row of data is ready, the
   78249 ** statement is completely executed or an error occurs.
   78250 **
   78251 ** This routine implements the bulk of the logic behind the sqlite_step()
   78252 ** API.  The only thing omitted is the automatic recompile if a
   78253 ** schema change has occurred.  That detail is handled by the
   78254 ** outer sqlite3_step() wrapper procedure.
   78255 */
   78256 static int sqlite3Step(Vdbe *p){
   78257   sqlite3 *db;
   78258   int rc;
   78259 
   78260   assert(p);
   78261   if( p->magic!=VDBE_MAGIC_RUN ){
   78262     /* We used to require that sqlite3_reset() be called before retrying
   78263     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
   78264     ** with version 3.7.0, we changed this so that sqlite3_reset() would
   78265     ** be called automatically instead of throwing the SQLITE_MISUSE error.
   78266     ** This "automatic-reset" change is not technically an incompatibility,
   78267     ** since any application that receives an SQLITE_MISUSE is broken by
   78268     ** definition.
   78269     **
   78270     ** Nevertheless, some published applications that were originally written
   78271     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
   78272     ** returns, and those were broken by the automatic-reset change.  As a
   78273     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
   78274     ** legacy behavior of returning SQLITE_MISUSE for cases where the
   78275     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
   78276     ** or SQLITE_BUSY error.
   78277     */
   78278 #ifdef SQLITE_OMIT_AUTORESET
   78279     if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
   78280       sqlite3_reset((sqlite3_stmt*)p);
   78281     }else{
   78282       return SQLITE_MISUSE_BKPT;
   78283     }
   78284 #else
   78285     sqlite3_reset((sqlite3_stmt*)p);
   78286 #endif
   78287   }
   78288 
   78289   /* Check that malloc() has not failed. If it has, return early. */
   78290   db = p->db;
   78291   if( db->mallocFailed ){
   78292     p->rc = SQLITE_NOMEM;
   78293     return SQLITE_NOMEM_BKPT;
   78294   }
   78295 
   78296   if( p->pc<=0 && p->expired ){
   78297     p->rc = SQLITE_SCHEMA;
   78298     rc = SQLITE_ERROR;
   78299     goto end_of_step;
   78300   }
   78301   if( p->pc<0 ){
   78302     /* If there are no other statements currently running, then
   78303     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
   78304     ** from interrupting a statement that has not yet started.
   78305     */
   78306     if( db->nVdbeActive==0 ){
   78307       db->u1.isInterrupted = 0;
   78308     }
   78309 
   78310     assert( db->nVdbeWrite>0 || db->autoCommit==0
   78311         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
   78312     );
   78313 
   78314 #ifndef SQLITE_OMIT_TRACE
   78315     if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
   78316         && !db->init.busy && p->zSql ){
   78317       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
   78318     }else{
   78319       assert( p->startTime==0 );
   78320     }
   78321 #endif
   78322 
   78323     db->nVdbeActive++;
   78324     if( p->readOnly==0 ) db->nVdbeWrite++;
   78325     if( p->bIsReader ) db->nVdbeRead++;
   78326     p->pc = 0;
   78327   }
   78328 #ifdef SQLITE_DEBUG
   78329   p->rcApp = SQLITE_OK;
   78330 #endif
   78331 #ifndef SQLITE_OMIT_EXPLAIN
   78332   if( p->explain ){
   78333     rc = sqlite3VdbeList(p);
   78334   }else
   78335 #endif /* SQLITE_OMIT_EXPLAIN */
   78336   {
   78337     db->nVdbeExec++;
   78338     rc = sqlite3VdbeExec(p);
   78339     db->nVdbeExec--;
   78340   }
   78341 
   78342 #ifndef SQLITE_OMIT_TRACE
   78343   /* If the statement completed successfully, invoke the profile callback */
   78344   if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
   78345 #endif
   78346 
   78347   if( rc==SQLITE_DONE && db->autoCommit ){
   78348     assert( p->rc==SQLITE_OK );
   78349     p->rc = doWalCallbacks(db);
   78350     if( p->rc!=SQLITE_OK ){
   78351       rc = SQLITE_ERROR;
   78352     }
   78353   }
   78354 
   78355   db->errCode = rc;
   78356   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
   78357     p->rc = SQLITE_NOMEM_BKPT;
   78358   }
   78359 end_of_step:
   78360   /* At this point local variable rc holds the value that should be
   78361   ** returned if this statement was compiled using the legacy
   78362   ** sqlite3_prepare() interface. According to the docs, this can only
   78363   ** be one of the values in the first assert() below. Variable p->rc
   78364   ** contains the value that would be returned if sqlite3_finalize()
   78365   ** were called on statement p.
   78366   */
   78367   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
   78368        || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
   78369   );
   78370   assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
   78371   if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
   78372    && rc!=SQLITE_ROW
   78373    && rc!=SQLITE_DONE
   78374   ){
   78375     /* If this statement was prepared using saved SQL and an
   78376     ** error has occurred, then return the error code in p->rc to the
   78377     ** caller. Set the error code in the database handle to the same value.
   78378     */
   78379     rc = sqlite3VdbeTransferError(p);
   78380   }
   78381   return (rc&db->errMask);
   78382 }
   78383 
   78384 /*
   78385 ** This is the top-level implementation of sqlite3_step().  Call
   78386 ** sqlite3Step() to do most of the work.  If a schema error occurs,
   78387 ** call sqlite3Reprepare() and try again.
   78388 */
   78389 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
   78390   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
   78391   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
   78392   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
   78393   sqlite3 *db;             /* The database connection */
   78394 
   78395   if( vdbeSafetyNotNull(v) ){
   78396     return SQLITE_MISUSE_BKPT;
   78397   }
   78398   db = v->db;
   78399   sqlite3_mutex_enter(db->mutex);
   78400   v->doingRerun = 0;
   78401   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
   78402          && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
   78403     int savedPc = v->pc;
   78404     rc = sqlite3Reprepare(v);
   78405     if( rc!=SQLITE_OK ){
   78406       /* This case occurs after failing to recompile an sql statement.
   78407       ** The error message from the SQL compiler has already been loaded
   78408       ** into the database handle. This block copies the error message
   78409       ** from the database handle into the statement and sets the statement
   78410       ** program counter to 0 to ensure that when the statement is
   78411       ** finalized or reset the parser error message is available via
   78412       ** sqlite3_errmsg() and sqlite3_errcode().
   78413       */
   78414       const char *zErr = (const char *)sqlite3_value_text(db->pErr);
   78415       sqlite3DbFree(db, v->zErrMsg);
   78416       if( !db->mallocFailed ){
   78417         v->zErrMsg = sqlite3DbStrDup(db, zErr);
   78418         v->rc = rc = sqlite3ApiExit(db, rc);
   78419       } else {
   78420         v->zErrMsg = 0;
   78421         v->rc = rc = SQLITE_NOMEM_BKPT;
   78422       }
   78423       break;
   78424     }
   78425     sqlite3_reset(pStmt);
   78426     if( savedPc>=0 ) v->doingRerun = 1;
   78427     assert( v->expired==0 );
   78428   }
   78429   sqlite3_mutex_leave(db->mutex);
   78430   return rc;
   78431 }
   78432 
   78433 
   78434 /*
   78435 ** Extract the user data from a sqlite3_context structure and return a
   78436 ** pointer to it.
   78437 */
   78438 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
   78439   assert( p && p->pFunc );
   78440   return p->pFunc->pUserData;
   78441 }
   78442 
   78443 /*
   78444 ** Extract the user data from a sqlite3_context structure and return a
   78445 ** pointer to it.
   78446 **
   78447 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
   78448 ** returns a copy of the pointer to the database connection (the 1st
   78449 ** parameter) of the sqlite3_create_function() and
   78450 ** sqlite3_create_function16() routines that originally registered the
   78451 ** application defined function.
   78452 */
   78453 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
   78454   assert( p && p->pOut );
   78455   return p->pOut->db;
   78456 }
   78457 
   78458 /*
   78459 ** If this routine is invoked from within an xColumn method of a virtual
   78460 ** table, then it returns true if and only if the the call is during an
   78461 ** UPDATE operation and the value of the column will not be modified
   78462 ** by the UPDATE.
   78463 **
   78464 ** If this routine is called from any context other than within the
   78465 ** xColumn method of a virtual table, then the return value is meaningless
   78466 ** and arbitrary.
   78467 **
   78468 ** Virtual table implements might use this routine to optimize their
   78469 ** performance by substituting a NULL result, or some other light-weight
   78470 ** value, as a signal to the xUpdate routine that the column is unchanged.
   78471 */
   78472 SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
   78473   assert( p );
   78474   return sqlite3_value_nochange(p->pOut);
   78475 }
   78476 
   78477 /*
   78478 ** Return the current time for a statement.  If the current time
   78479 ** is requested more than once within the same run of a single prepared
   78480 ** statement, the exact same time is returned for each invocation regardless
   78481 ** of the amount of time that elapses between invocations.  In other words,
   78482 ** the time returned is always the time of the first call.
   78483 */
   78484 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
   78485   int rc;
   78486 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
   78487   sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
   78488   assert( p->pVdbe!=0 );
   78489 #else
   78490   sqlite3_int64 iTime = 0;
   78491   sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
   78492 #endif
   78493   if( *piTime==0 ){
   78494     rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
   78495     if( rc ) *piTime = 0;
   78496   }
   78497   return *piTime;
   78498 }
   78499 
   78500 /*
   78501 ** The following is the implementation of an SQL function that always
   78502 ** fails with an error message stating that the function is used in the
   78503 ** wrong context.  The sqlite3_overload_function() API might construct
   78504 ** SQL function that use this routine so that the functions will exist
   78505 ** for name resolution but are actually overloaded by the xFindFunction
   78506 ** method of virtual tables.
   78507 */
   78508 SQLITE_PRIVATE void sqlite3InvalidFunction(
   78509   sqlite3_context *context,  /* The function calling context */
   78510   int NotUsed,               /* Number of arguments to the function */
   78511   sqlite3_value **NotUsed2   /* Value of each argument */
   78512 ){
   78513   const char *zName = context->pFunc->zName;
   78514   char *zErr;
   78515   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   78516   zErr = sqlite3_mprintf(
   78517       "unable to use function %s in the requested context", zName);
   78518   sqlite3_result_error(context, zErr, -1);
   78519   sqlite3_free(zErr);
   78520 }
   78521 
   78522 /*
   78523 ** Create a new aggregate context for p and return a pointer to
   78524 ** its pMem->z element.
   78525 */
   78526 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
   78527   Mem *pMem = p->pMem;
   78528   assert( (pMem->flags & MEM_Agg)==0 );
   78529   if( nByte<=0 ){
   78530     sqlite3VdbeMemSetNull(pMem);
   78531     pMem->z = 0;
   78532   }else{
   78533     sqlite3VdbeMemClearAndResize(pMem, nByte);
   78534     pMem->flags = MEM_Agg;
   78535     pMem->u.pDef = p->pFunc;
   78536     if( pMem->z ){
   78537       memset(pMem->z, 0, nByte);
   78538     }
   78539   }
   78540   return (void*)pMem->z;
   78541 }
   78542 
   78543 /*
   78544 ** Allocate or return the aggregate context for a user function.  A new
   78545 ** context is allocated on the first call.  Subsequent calls return the
   78546 ** same context that was returned on prior calls.
   78547 */
   78548 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
   78549   assert( p && p->pFunc && p->pFunc->xFinalize );
   78550   assert( sqlite3_mutex_held(p->pOut->db->mutex) );
   78551   testcase( nByte<0 );
   78552   if( (p->pMem->flags & MEM_Agg)==0 ){
   78553     return createAggContext(p, nByte);
   78554   }else{
   78555     return (void*)p->pMem->z;
   78556   }
   78557 }
   78558 
   78559 /*
   78560 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
   78561 ** the user-function defined by pCtx.
   78562 **
   78563 ** The left-most argument is 0.
   78564 **
   78565 ** Undocumented behavior:  If iArg is negative then access a cache of
   78566 ** auxiliary data pointers that is available to all functions within a
   78567 ** single prepared statement.  The iArg values must match.
   78568 */
   78569 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
   78570   AuxData *pAuxData;
   78571 
   78572   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78573 #if SQLITE_ENABLE_STAT3_OR_STAT4
   78574   if( pCtx->pVdbe==0 ) return 0;
   78575 #else
   78576   assert( pCtx->pVdbe!=0 );
   78577 #endif
   78578   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
   78579     if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
   78580       return pAuxData->pAux;
   78581     }
   78582   }
   78583   return 0;
   78584 }
   78585 
   78586 /*
   78587 ** Set the auxiliary data pointer and delete function, for the iArg'th
   78588 ** argument to the user-function defined by pCtx. Any previous value is
   78589 ** deleted by calling the delete function specified when it was set.
   78590 **
   78591 ** The left-most argument is 0.
   78592 **
   78593 ** Undocumented behavior:  If iArg is negative then make the data available
   78594 ** to all functions within the current prepared statement using iArg as an
   78595 ** access code.
   78596 */
   78597 SQLITE_API void sqlite3_set_auxdata(
   78598   sqlite3_context *pCtx,
   78599   int iArg,
   78600   void *pAux,
   78601   void (*xDelete)(void*)
   78602 ){
   78603   AuxData *pAuxData;
   78604   Vdbe *pVdbe = pCtx->pVdbe;
   78605 
   78606   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   78607 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   78608   if( pVdbe==0 ) goto failed;
   78609 #else
   78610   assert( pVdbe!=0 );
   78611 #endif
   78612 
   78613   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
   78614     if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
   78615       break;
   78616     }
   78617   }
   78618   if( pAuxData==0 ){
   78619     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
   78620     if( !pAuxData ) goto failed;
   78621     pAuxData->iAuxOp = pCtx->iOp;
   78622     pAuxData->iAuxArg = iArg;
   78623     pAuxData->pNextAux = pVdbe->pAuxData;
   78624     pVdbe->pAuxData = pAuxData;
   78625     if( pCtx->fErrorOrAux==0 ){
   78626       pCtx->isError = 0;
   78627       pCtx->fErrorOrAux = 1;
   78628     }
   78629   }else if( pAuxData->xDeleteAux ){
   78630     pAuxData->xDeleteAux(pAuxData->pAux);
   78631   }
   78632 
   78633   pAuxData->pAux = pAux;
   78634   pAuxData->xDeleteAux = xDelete;
   78635   return;
   78636 
   78637 failed:
   78638   if( xDelete ){
   78639     xDelete(pAux);
   78640   }
   78641 }
   78642 
   78643 #ifndef SQLITE_OMIT_DEPRECATED
   78644 /*
   78645 ** Return the number of times the Step function of an aggregate has been
   78646 ** called.
   78647 **
   78648 ** This function is deprecated.  Do not use it for new code.  It is
   78649 ** provide only to avoid breaking legacy code.  New aggregate function
   78650 ** implementations should keep their own counts within their aggregate
   78651 ** context.
   78652 */
   78653 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
   78654   assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
   78655   return p->pMem->n;
   78656 }
   78657 #endif
   78658 
   78659 /*
   78660 ** Return the number of columns in the result set for the statement pStmt.
   78661 */
   78662 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
   78663   Vdbe *pVm = (Vdbe *)pStmt;
   78664   return pVm ? pVm->nResColumn : 0;
   78665 }
   78666 
   78667 /*
   78668 ** Return the number of values available from the current row of the
   78669 ** currently executing statement pStmt.
   78670 */
   78671 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
   78672   Vdbe *pVm = (Vdbe *)pStmt;
   78673   if( pVm==0 || pVm->pResultSet==0 ) return 0;
   78674   return pVm->nResColumn;
   78675 }
   78676 
   78677 /*
   78678 ** Return a pointer to static memory containing an SQL NULL value.
   78679 */
   78680 static const Mem *columnNullValue(void){
   78681   /* Even though the Mem structure contains an element
   78682   ** of type i64, on certain architectures (x86) with certain compiler
   78683   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
   78684   ** instead of an 8-byte one. This all works fine, except that when
   78685   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
   78686   ** that a Mem structure is located on an 8-byte boundary. To prevent
   78687   ** these assert()s from failing, when building with SQLITE_DEBUG defined
   78688   ** using gcc, we force nullMem to be 8-byte aligned using the magical
   78689   ** __attribute__((aligned(8))) macro.  */
   78690   static const Mem nullMem
   78691 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
   78692     __attribute__((aligned(8)))
   78693 #endif
   78694     = {
   78695         /* .u          = */ {0},
   78696         /* .flags      = */ (u16)MEM_Null,
   78697         /* .enc        = */ (u8)0,
   78698         /* .eSubtype   = */ (u8)0,
   78699         /* .n          = */ (int)0,
   78700         /* .z          = */ (char*)0,
   78701         /* .zMalloc    = */ (char*)0,
   78702         /* .szMalloc   = */ (int)0,
   78703         /* .uTemp      = */ (u32)0,
   78704         /* .db         = */ (sqlite3*)0,
   78705         /* .xDel       = */ (void(*)(void*))0,
   78706 #ifdef SQLITE_DEBUG
   78707         /* .pScopyFrom = */ (Mem*)0,
   78708         /* .pFiller    = */ (void*)0,
   78709 #endif
   78710       };
   78711   return &nullMem;
   78712 }
   78713 
   78714 /*
   78715 ** Check to see if column iCol of the given statement is valid.  If
   78716 ** it is, return a pointer to the Mem for the value of that column.
   78717 ** If iCol is not valid, return a pointer to a Mem which has a value
   78718 ** of NULL.
   78719 */
   78720 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
   78721   Vdbe *pVm;
   78722   Mem *pOut;
   78723 
   78724   pVm = (Vdbe *)pStmt;
   78725   if( pVm==0 ) return (Mem*)columnNullValue();
   78726   assert( pVm->db );
   78727   sqlite3_mutex_enter(pVm->db->mutex);
   78728   if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
   78729     pOut = &pVm->pResultSet[i];
   78730   }else{
   78731     sqlite3Error(pVm->db, SQLITE_RANGE);
   78732     pOut = (Mem*)columnNullValue();
   78733   }
   78734   return pOut;
   78735 }
   78736 
   78737 /*
   78738 ** This function is called after invoking an sqlite3_value_XXX function on a
   78739 ** column value (i.e. a value returned by evaluating an SQL expression in the
   78740 ** select list of a SELECT statement) that may cause a malloc() failure. If
   78741 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
   78742 ** code of statement pStmt set to SQLITE_NOMEM.
   78743 **
   78744 ** Specifically, this is called from within:
   78745 **
   78746 **     sqlite3_column_int()
   78747 **     sqlite3_column_int64()
   78748 **     sqlite3_column_text()
   78749 **     sqlite3_column_text16()
   78750 **     sqlite3_column_real()
   78751 **     sqlite3_column_bytes()
   78752 **     sqlite3_column_bytes16()
   78753 **     sqiite3_column_blob()
   78754 */
   78755 static void columnMallocFailure(sqlite3_stmt *pStmt)
   78756 {
   78757   /* If malloc() failed during an encoding conversion within an
   78758   ** sqlite3_column_XXX API, then set the return code of the statement to
   78759   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
   78760   ** and _finalize() will return NOMEM.
   78761   */
   78762   Vdbe *p = (Vdbe *)pStmt;
   78763   if( p ){
   78764     assert( p->db!=0 );
   78765     assert( sqlite3_mutex_held(p->db->mutex) );
   78766     p->rc = sqlite3ApiExit(p->db, p->rc);
   78767     sqlite3_mutex_leave(p->db->mutex);
   78768   }
   78769 }
   78770 
   78771 /**************************** sqlite3_column_  *******************************
   78772 ** The following routines are used to access elements of the current row
   78773 ** in the result set.
   78774 */
   78775 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   78776   const void *val;
   78777   val = sqlite3_value_blob( columnMem(pStmt,i) );
   78778   /* Even though there is no encoding conversion, value_blob() might
   78779   ** need to call malloc() to expand the result of a zeroblob()
   78780   ** expression.
   78781   */
   78782   columnMallocFailure(pStmt);
   78783   return val;
   78784 }
   78785 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   78786   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
   78787   columnMallocFailure(pStmt);
   78788   return val;
   78789 }
   78790 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   78791   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
   78792   columnMallocFailure(pStmt);
   78793   return val;
   78794 }
   78795 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   78796   double val = sqlite3_value_double( columnMem(pStmt,i) );
   78797   columnMallocFailure(pStmt);
   78798   return val;
   78799 }
   78800 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   78801   int val = sqlite3_value_int( columnMem(pStmt,i) );
   78802   columnMallocFailure(pStmt);
   78803   return val;
   78804 }
   78805 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   78806   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
   78807   columnMallocFailure(pStmt);
   78808   return val;
   78809 }
   78810 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   78811   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
   78812   columnMallocFailure(pStmt);
   78813   return val;
   78814 }
   78815 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   78816   Mem *pOut = columnMem(pStmt, i);
   78817   if( pOut->flags&MEM_Static ){
   78818     pOut->flags &= ~MEM_Static;
   78819     pOut->flags |= MEM_Ephem;
   78820   }
   78821   columnMallocFailure(pStmt);
   78822   return (sqlite3_value *)pOut;
   78823 }
   78824 #ifndef SQLITE_OMIT_UTF16
   78825 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   78826   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
   78827   columnMallocFailure(pStmt);
   78828   return val;
   78829 }
   78830 #endif /* SQLITE_OMIT_UTF16 */
   78831 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   78832   int iType = sqlite3_value_type( columnMem(pStmt,i) );
   78833   columnMallocFailure(pStmt);
   78834   return iType;
   78835 }
   78836 
   78837 /*
   78838 ** Convert the N-th element of pStmt->pColName[] into a string using
   78839 ** xFunc() then return that string.  If N is out of range, return 0.
   78840 **
   78841 ** There are up to 5 names for each column.  useType determines which
   78842 ** name is returned.  Here are the names:
   78843 **
   78844 **    0      The column name as it should be displayed for output
   78845 **    1      The datatype name for the column
   78846 **    2      The name of the database that the column derives from
   78847 **    3      The name of the table that the column derives from
   78848 **    4      The name of the table column that the result column derives from
   78849 **
   78850 ** If the result is not a simple column reference (if it is an expression
   78851 ** or a constant) then useTypes 2, 3, and 4 return NULL.
   78852 */
   78853 static const void *columnName(
   78854   sqlite3_stmt *pStmt,
   78855   int N,
   78856   const void *(*xFunc)(Mem*),
   78857   int useType
   78858 ){
   78859   const void *ret;
   78860   Vdbe *p;
   78861   int n;
   78862   sqlite3 *db;
   78863 #ifdef SQLITE_ENABLE_API_ARMOR
   78864   if( pStmt==0 ){
   78865     (void)SQLITE_MISUSE_BKPT;
   78866     return 0;
   78867   }
   78868 #endif
   78869   ret = 0;
   78870   p = (Vdbe *)pStmt;
   78871   db = p->db;
   78872   assert( db!=0 );
   78873   n = sqlite3_column_count(pStmt);
   78874   if( N<n && N>=0 ){
   78875     N += useType*n;
   78876     sqlite3_mutex_enter(db->mutex);
   78877     assert( db->mallocFailed==0 );
   78878     ret = xFunc(&p->aColName[N]);
   78879      /* A malloc may have failed inside of the xFunc() call. If this
   78880     ** is the case, clear the mallocFailed flag and return NULL.
   78881     */
   78882     if( db->mallocFailed ){
   78883       sqlite3OomClear(db);
   78884       ret = 0;
   78885     }
   78886     sqlite3_mutex_leave(db->mutex);
   78887   }
   78888   return ret;
   78889 }
   78890 
   78891 /*
   78892 ** Return the name of the Nth column of the result set returned by SQL
   78893 ** statement pStmt.
   78894 */
   78895 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   78896   return columnName(
   78897       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
   78898 }
   78899 #ifndef SQLITE_OMIT_UTF16
   78900 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
   78901   return columnName(
   78902       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
   78903 }
   78904 #endif
   78905 
   78906 /*
   78907 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
   78908 ** not define OMIT_DECLTYPE.
   78909 */
   78910 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
   78911 # error "Must not define both SQLITE_OMIT_DECLTYPE \
   78912          and SQLITE_ENABLE_COLUMN_METADATA"
   78913 #endif
   78914 
   78915 #ifndef SQLITE_OMIT_DECLTYPE
   78916 /*
   78917 ** Return the column declaration type (if applicable) of the 'i'th column
   78918 ** of the result set of SQL statement pStmt.
   78919 */
   78920 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
   78921   return columnName(
   78922       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
   78923 }
   78924 #ifndef SQLITE_OMIT_UTF16
   78925 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
   78926   return columnName(
   78927       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
   78928 }
   78929 #endif /* SQLITE_OMIT_UTF16 */
   78930 #endif /* SQLITE_OMIT_DECLTYPE */
   78931 
   78932 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   78933 /*
   78934 ** Return the name of the database from which a result column derives.
   78935 ** NULL is returned if the result column is an expression or constant or
   78936 ** anything else which is not an unambiguous reference to a database column.
   78937 */
   78938 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
   78939   return columnName(
   78940       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
   78941 }
   78942 #ifndef SQLITE_OMIT_UTF16
   78943 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
   78944   return columnName(
   78945       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
   78946 }
   78947 #endif /* SQLITE_OMIT_UTF16 */
   78948 
   78949 /*
   78950 ** Return the name of the table from which a result column derives.
   78951 ** NULL is returned if the result column is an expression or constant or
   78952 ** anything else which is not an unambiguous reference to a database column.
   78953 */
   78954 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
   78955   return columnName(
   78956       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
   78957 }
   78958 #ifndef SQLITE_OMIT_UTF16
   78959 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
   78960   return columnName(
   78961       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
   78962 }
   78963 #endif /* SQLITE_OMIT_UTF16 */
   78964 
   78965 /*
   78966 ** Return the name of the table column from which a result column derives.
   78967 ** NULL is returned if the result column is an expression or constant or
   78968 ** anything else which is not an unambiguous reference to a database column.
   78969 */
   78970 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
   78971   return columnName(
   78972       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
   78973 }
   78974 #ifndef SQLITE_OMIT_UTF16
   78975 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
   78976   return columnName(
   78977       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
   78978 }
   78979 #endif /* SQLITE_OMIT_UTF16 */
   78980 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
   78981 
   78982 
   78983 /******************************* sqlite3_bind_  ***************************
   78984 **
   78985 ** Routines used to attach values to wildcards in a compiled SQL statement.
   78986 */
   78987 /*
   78988 ** Unbind the value bound to variable i in virtual machine p. This is the
   78989 ** the same as binding a NULL value to the column. If the "i" parameter is
   78990 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
   78991 **
   78992 ** A successful evaluation of this routine acquires the mutex on p.
   78993 ** the mutex is released if any kind of error occurs.
   78994 **
   78995 ** The error code stored in database p->db is overwritten with the return
   78996 ** value in any case.
   78997 */
   78998 static int vdbeUnbind(Vdbe *p, int i){
   78999   Mem *pVar;
   79000   if( vdbeSafetyNotNull(p) ){
   79001     return SQLITE_MISUSE_BKPT;
   79002   }
   79003   sqlite3_mutex_enter(p->db->mutex);
   79004   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
   79005     sqlite3Error(p->db, SQLITE_MISUSE);
   79006     sqlite3_mutex_leave(p->db->mutex);
   79007     sqlite3_log(SQLITE_MISUSE,
   79008         "bind on a busy prepared statement: [%s]", p->zSql);
   79009     return SQLITE_MISUSE_BKPT;
   79010   }
   79011   if( i<1 || i>p->nVar ){
   79012     sqlite3Error(p->db, SQLITE_RANGE);
   79013     sqlite3_mutex_leave(p->db->mutex);
   79014     return SQLITE_RANGE;
   79015   }
   79016   i--;
   79017   pVar = &p->aVar[i];
   79018   sqlite3VdbeMemRelease(pVar);
   79019   pVar->flags = MEM_Null;
   79020   sqlite3Error(p->db, SQLITE_OK);
   79021 
   79022   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   79023   ** binding a new value to this variable invalidates the current query plan.
   79024   **
   79025   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
   79026   ** parameter in the WHERE clause might influence the choice of query plan
   79027   ** for a statement, then the statement will be automatically recompiled,
   79028   ** as if there had been a schema change, on the first sqlite3_step() call
   79029   ** following any change to the bindings of that parameter.
   79030   */
   79031   assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
   79032   if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
   79033     p->expired = 1;
   79034   }
   79035   return SQLITE_OK;
   79036 }
   79037 
   79038 /*
   79039 ** Bind a text or BLOB value.
   79040 */
   79041 static int bindText(
   79042   sqlite3_stmt *pStmt,   /* The statement to bind against */
   79043   int i,                 /* Index of the parameter to bind */
   79044   const void *zData,     /* Pointer to the data to be bound */
   79045   int nData,             /* Number of bytes of data to be bound */
   79046   void (*xDel)(void*),   /* Destructor for the data */
   79047   u8 encoding            /* Encoding for the data */
   79048 ){
   79049   Vdbe *p = (Vdbe *)pStmt;
   79050   Mem *pVar;
   79051   int rc;
   79052 
   79053   rc = vdbeUnbind(p, i);
   79054   if( rc==SQLITE_OK ){
   79055     if( zData!=0 ){
   79056       pVar = &p->aVar[i-1];
   79057       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
   79058       if( rc==SQLITE_OK && encoding!=0 ){
   79059         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
   79060       }
   79061       if( rc ){
   79062         sqlite3Error(p->db, rc);
   79063         rc = sqlite3ApiExit(p->db, rc);
   79064       }
   79065     }
   79066     sqlite3_mutex_leave(p->db->mutex);
   79067   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
   79068     xDel((void*)zData);
   79069   }
   79070   return rc;
   79071 }
   79072 
   79073 
   79074 /*
   79075 ** Bind a blob value to an SQL statement variable.
   79076 */
   79077 SQLITE_API int sqlite3_bind_blob(
   79078   sqlite3_stmt *pStmt,
   79079   int i,
   79080   const void *zData,
   79081   int nData,
   79082   void (*xDel)(void*)
   79083 ){
   79084 #ifdef SQLITE_ENABLE_API_ARMOR
   79085   if( nData<0 ) return SQLITE_MISUSE_BKPT;
   79086 #endif
   79087   return bindText(pStmt, i, zData, nData, xDel, 0);
   79088 }
   79089 SQLITE_API int sqlite3_bind_blob64(
   79090   sqlite3_stmt *pStmt,
   79091   int i,
   79092   const void *zData,
   79093   sqlite3_uint64 nData,
   79094   void (*xDel)(void*)
   79095 ){
   79096   assert( xDel!=SQLITE_DYNAMIC );
   79097   if( nData>0x7fffffff ){
   79098     return invokeValueDestructor(zData, xDel, 0);
   79099   }else{
   79100     return bindText(pStmt, i, zData, (int)nData, xDel, 0);
   79101   }
   79102 }
   79103 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   79104   int rc;
   79105   Vdbe *p = (Vdbe *)pStmt;
   79106   rc = vdbeUnbind(p, i);
   79107   if( rc==SQLITE_OK ){
   79108     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
   79109     sqlite3_mutex_leave(p->db->mutex);
   79110   }
   79111   return rc;
   79112 }
   79113 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
   79114   return sqlite3_bind_int64(p, i, (i64)iValue);
   79115 }
   79116 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
   79117   int rc;
   79118   Vdbe *p = (Vdbe *)pStmt;
   79119   rc = vdbeUnbind(p, i);
   79120   if( rc==SQLITE_OK ){
   79121     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
   79122     sqlite3_mutex_leave(p->db->mutex);
   79123   }
   79124   return rc;
   79125 }
   79126 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
   79127   int rc;
   79128   Vdbe *p = (Vdbe*)pStmt;
   79129   rc = vdbeUnbind(p, i);
   79130   if( rc==SQLITE_OK ){
   79131     sqlite3_mutex_leave(p->db->mutex);
   79132   }
   79133   return rc;
   79134 }
   79135 SQLITE_API int sqlite3_bind_pointer(
   79136   sqlite3_stmt *pStmt,
   79137   int i,
   79138   void *pPtr,
   79139   const char *zPTtype,
   79140   void (*xDestructor)(void*)
   79141 ){
   79142   int rc;
   79143   Vdbe *p = (Vdbe*)pStmt;
   79144   rc = vdbeUnbind(p, i);
   79145   if( rc==SQLITE_OK ){
   79146     sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
   79147     sqlite3_mutex_leave(p->db->mutex);
   79148   }else if( xDestructor ){
   79149     xDestructor(pPtr);
   79150   }
   79151   return rc;
   79152 }
   79153 SQLITE_API int sqlite3_bind_text(
   79154   sqlite3_stmt *pStmt,
   79155   int i,
   79156   const char *zData,
   79157   int nData,
   79158   void (*xDel)(void*)
   79159 ){
   79160   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
   79161 }
   79162 SQLITE_API int sqlite3_bind_text64(
   79163   sqlite3_stmt *pStmt,
   79164   int i,
   79165   const char *zData,
   79166   sqlite3_uint64 nData,
   79167   void (*xDel)(void*),
   79168   unsigned char enc
   79169 ){
   79170   assert( xDel!=SQLITE_DYNAMIC );
   79171   if( nData>0x7fffffff ){
   79172     return invokeValueDestructor(zData, xDel, 0);
   79173   }else{
   79174     if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
   79175     return bindText(pStmt, i, zData, (int)nData, xDel, enc);
   79176   }
   79177 }
   79178 #ifndef SQLITE_OMIT_UTF16
   79179 SQLITE_API int sqlite3_bind_text16(
   79180   sqlite3_stmt *pStmt,
   79181   int i,
   79182   const void *zData,
   79183   int nData,
   79184   void (*xDel)(void*)
   79185 ){
   79186   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
   79187 }
   79188 #endif /* SQLITE_OMIT_UTF16 */
   79189 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
   79190   int rc;
   79191   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
   79192     case SQLITE_INTEGER: {
   79193       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
   79194       break;
   79195     }
   79196     case SQLITE_FLOAT: {
   79197       rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
   79198       break;
   79199     }
   79200     case SQLITE_BLOB: {
   79201       if( pValue->flags & MEM_Zero ){
   79202         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
   79203       }else{
   79204         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
   79205       }
   79206       break;
   79207     }
   79208     case SQLITE_TEXT: {
   79209       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
   79210                               pValue->enc);
   79211       break;
   79212     }
   79213     default: {
   79214       rc = sqlite3_bind_null(pStmt, i);
   79215       break;
   79216     }
   79217   }
   79218   return rc;
   79219 }
   79220 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   79221   int rc;
   79222   Vdbe *p = (Vdbe *)pStmt;
   79223   rc = vdbeUnbind(p, i);
   79224   if( rc==SQLITE_OK ){
   79225     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
   79226     sqlite3_mutex_leave(p->db->mutex);
   79227   }
   79228   return rc;
   79229 }
   79230 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
   79231   int rc;
   79232   Vdbe *p = (Vdbe *)pStmt;
   79233   sqlite3_mutex_enter(p->db->mutex);
   79234   if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
   79235     rc = SQLITE_TOOBIG;
   79236   }else{
   79237     assert( (n & 0x7FFFFFFF)==n );
   79238     rc = sqlite3_bind_zeroblob(pStmt, i, n);
   79239   }
   79240   rc = sqlite3ApiExit(p->db, rc);
   79241   sqlite3_mutex_leave(p->db->mutex);
   79242   return rc;
   79243 }
   79244 
   79245 /*
   79246 ** Return the number of wildcards that can be potentially bound to.
   79247 ** This routine is added to support DBD::SQLite.
   79248 */
   79249 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   79250   Vdbe *p = (Vdbe*)pStmt;
   79251   return p ? p->nVar : 0;
   79252 }
   79253 
   79254 /*
   79255 ** Return the name of a wildcard parameter.  Return NULL if the index
   79256 ** is out of range or if the wildcard is unnamed.
   79257 **
   79258 ** The result is always UTF-8.
   79259 */
   79260 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
   79261   Vdbe *p = (Vdbe*)pStmt;
   79262   if( p==0 ) return 0;
   79263   return sqlite3VListNumToName(p->pVList, i);
   79264 }
   79265 
   79266 /*
   79267 ** Given a wildcard parameter name, return the index of the variable
   79268 ** with that name.  If there is no variable with the given name,
   79269 ** return 0.
   79270 */
   79271 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
   79272   if( p==0 || zName==0 ) return 0;
   79273   return sqlite3VListNameToNum(p->pVList, zName, nName);
   79274 }
   79275 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
   79276   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
   79277 }
   79278 
   79279 /*
   79280 ** Transfer all bindings from the first statement over to the second.
   79281 */
   79282 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   79283   Vdbe *pFrom = (Vdbe*)pFromStmt;
   79284   Vdbe *pTo = (Vdbe*)pToStmt;
   79285   int i;
   79286   assert( pTo->db==pFrom->db );
   79287   assert( pTo->nVar==pFrom->nVar );
   79288   sqlite3_mutex_enter(pTo->db->mutex);
   79289   for(i=0; i<pFrom->nVar; i++){
   79290     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
   79291   }
   79292   sqlite3_mutex_leave(pTo->db->mutex);
   79293   return SQLITE_OK;
   79294 }
   79295 
   79296 #ifndef SQLITE_OMIT_DEPRECATED
   79297 /*
   79298 ** Deprecated external interface.  Internal/core SQLite code
   79299 ** should call sqlite3TransferBindings.
   79300 **
   79301 ** It is misuse to call this routine with statements from different
   79302 ** database connections.  But as this is a deprecated interface, we
   79303 ** will not bother to check for that condition.
   79304 **
   79305 ** If the two statements contain a different number of bindings, then
   79306 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
   79307 ** SQLITE_OK is returned.
   79308 */
   79309 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   79310   Vdbe *pFrom = (Vdbe*)pFromStmt;
   79311   Vdbe *pTo = (Vdbe*)pToStmt;
   79312   if( pFrom->nVar!=pTo->nVar ){
   79313     return SQLITE_ERROR;
   79314   }
   79315   assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
   79316   if( pTo->expmask ){
   79317     pTo->expired = 1;
   79318   }
   79319   assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
   79320   if( pFrom->expmask ){
   79321     pFrom->expired = 1;
   79322   }
   79323   return sqlite3TransferBindings(pFromStmt, pToStmt);
   79324 }
   79325 #endif
   79326 
   79327 /*
   79328 ** Return the sqlite3* database handle to which the prepared statement given
   79329 ** in the argument belongs.  This is the same database handle that was
   79330 ** the first argument to the sqlite3_prepare() that was used to create
   79331 ** the statement in the first place.
   79332 */
   79333 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
   79334   return pStmt ? ((Vdbe*)pStmt)->db : 0;
   79335 }
   79336 
   79337 /*
   79338 ** Return true if the prepared statement is guaranteed to not modify the
   79339 ** database.
   79340 */
   79341 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
   79342   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
   79343 }
   79344 
   79345 /*
   79346 ** Return true if the prepared statement is in need of being reset.
   79347 */
   79348 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
   79349   Vdbe *v = (Vdbe*)pStmt;
   79350   return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
   79351 }
   79352 
   79353 /*
   79354 ** Return a pointer to the next prepared statement after pStmt associated
   79355 ** with database connection pDb.  If pStmt is NULL, return the first
   79356 ** prepared statement for the database connection.  Return NULL if there
   79357 ** are no more.
   79358 */
   79359 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
   79360   sqlite3_stmt *pNext;
   79361 #ifdef SQLITE_ENABLE_API_ARMOR
   79362   if( !sqlite3SafetyCheckOk(pDb) ){
   79363     (void)SQLITE_MISUSE_BKPT;
   79364     return 0;
   79365   }
   79366 #endif
   79367   sqlite3_mutex_enter(pDb->mutex);
   79368   if( pStmt==0 ){
   79369     pNext = (sqlite3_stmt*)pDb->pVdbe;
   79370   }else{
   79371     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
   79372   }
   79373   sqlite3_mutex_leave(pDb->mutex);
   79374   return pNext;
   79375 }
   79376 
   79377 /*
   79378 ** Return the value of a status counter for a prepared statement
   79379 */
   79380 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   79381   Vdbe *pVdbe = (Vdbe*)pStmt;
   79382   u32 v;
   79383 #ifdef SQLITE_ENABLE_API_ARMOR
   79384   if( !pStmt ){
   79385     (void)SQLITE_MISUSE_BKPT;
   79386     return 0;
   79387   }
   79388 #endif
   79389   if( op==SQLITE_STMTSTATUS_MEMUSED ){
   79390     sqlite3 *db = pVdbe->db;
   79391     sqlite3_mutex_enter(db->mutex);
   79392     v = 0;
   79393     db->pnBytesFreed = (int*)&v;
   79394     sqlite3VdbeClearObject(db, pVdbe);
   79395     sqlite3DbFree(db, pVdbe);
   79396     db->pnBytesFreed = 0;
   79397     sqlite3_mutex_leave(db->mutex);
   79398   }else{
   79399     v = pVdbe->aCounter[op];
   79400     if( resetFlag ) pVdbe->aCounter[op] = 0;
   79401   }
   79402   return (int)v;
   79403 }
   79404 
   79405 /*
   79406 ** Return the SQL associated with a prepared statement
   79407 */
   79408 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
   79409   Vdbe *p = (Vdbe *)pStmt;
   79410   return p ? p->zSql : 0;
   79411 }
   79412 
   79413 /*
   79414 ** Return the SQL associated with a prepared statement with
   79415 ** bound parameters expanded.  Space to hold the returned string is
   79416 ** obtained from sqlite3_malloc().  The caller is responsible for
   79417 ** freeing the returned string by passing it to sqlite3_free().
   79418 **
   79419 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
   79420 ** expanded bound parameters.
   79421 */
   79422 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
   79423 #ifdef SQLITE_OMIT_TRACE
   79424   return 0;
   79425 #else
   79426   char *z = 0;
   79427   const char *zSql = sqlite3_sql(pStmt);
   79428   if( zSql ){
   79429     Vdbe *p = (Vdbe *)pStmt;
   79430     sqlite3_mutex_enter(p->db->mutex);
   79431     z = sqlite3VdbeExpandSql(p, zSql);
   79432     sqlite3_mutex_leave(p->db->mutex);
   79433   }
   79434   return z;
   79435 #endif
   79436 }
   79437 
   79438 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   79439 /*
   79440 ** Allocate and populate an UnpackedRecord structure based on the serialized
   79441 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
   79442 ** if successful, or a NULL pointer if an OOM error is encountered.
   79443 */
   79444 static UnpackedRecord *vdbeUnpackRecord(
   79445   KeyInfo *pKeyInfo,
   79446   int nKey,
   79447   const void *pKey
   79448 ){
   79449   UnpackedRecord *pRet;           /* Return value */
   79450 
   79451   pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
   79452   if( pRet ){
   79453     memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
   79454     sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
   79455   }
   79456   return pRet;
   79457 }
   79458 
   79459 /*
   79460 ** This function is called from within a pre-update callback to retrieve
   79461 ** a field of the row currently being updated or deleted.
   79462 */
   79463 SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
   79464   PreUpdate *p = db->pPreUpdate;
   79465   Mem *pMem;
   79466   int rc = SQLITE_OK;
   79467 
   79468   /* Test that this call is being made from within an SQLITE_DELETE or
   79469   ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
   79470   if( !p || p->op==SQLITE_INSERT ){
   79471     rc = SQLITE_MISUSE_BKPT;
   79472     goto preupdate_old_out;
   79473   }
   79474   if( p->pPk ){
   79475     iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
   79476   }
   79477   if( iIdx>=p->pCsr->nField || iIdx<0 ){
   79478     rc = SQLITE_RANGE;
   79479     goto preupdate_old_out;
   79480   }
   79481 
   79482   /* If the old.* record has not yet been loaded into memory, do so now. */
   79483   if( p->pUnpacked==0 ){
   79484     u32 nRec;
   79485     u8 *aRec;
   79486 
   79487     nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
   79488     aRec = sqlite3DbMallocRaw(db, nRec);
   79489     if( !aRec ) goto preupdate_old_out;
   79490     rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
   79491     if( rc==SQLITE_OK ){
   79492       p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
   79493       if( !p->pUnpacked ) rc = SQLITE_NOMEM;
   79494     }
   79495     if( rc!=SQLITE_OK ){
   79496       sqlite3DbFree(db, aRec);
   79497       goto preupdate_old_out;
   79498     }
   79499     p->aRecord = aRec;
   79500   }
   79501 
   79502   pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
   79503   if( iIdx==p->pTab->iPKey ){
   79504     sqlite3VdbeMemSetInt64(pMem, p->iKey1);
   79505   }else if( iIdx>=p->pUnpacked->nField ){
   79506     *ppValue = (sqlite3_value *)columnNullValue();
   79507   }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
   79508     if( pMem->flags & MEM_Int ){
   79509       sqlite3VdbeMemRealify(pMem);
   79510     }
   79511   }
   79512 
   79513  preupdate_old_out:
   79514   sqlite3Error(db, rc);
   79515   return sqlite3ApiExit(db, rc);
   79516 }
   79517 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   79518 
   79519 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   79520 /*
   79521 ** This function is called from within a pre-update callback to retrieve
   79522 ** the number of columns in the row being updated, deleted or inserted.
   79523 */
   79524 SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
   79525   PreUpdate *p = db->pPreUpdate;
   79526   return (p ? p->keyinfo.nKeyField : 0);
   79527 }
   79528 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   79529 
   79530 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   79531 /*
   79532 ** This function is designed to be called from within a pre-update callback
   79533 ** only. It returns zero if the change that caused the callback was made
   79534 ** immediately by a user SQL statement. Or, if the change was made by a
   79535 ** trigger program, it returns the number of trigger programs currently
   79536 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
   79537 ** top-level trigger etc.).
   79538 **
   79539 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
   79540 ** or SET DEFAULT action is considered a trigger.
   79541 */
   79542 SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
   79543   PreUpdate *p = db->pPreUpdate;
   79544   return (p ? p->v->nFrame : 0);
   79545 }
   79546 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   79547 
   79548 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   79549 /*
   79550 ** This function is called from within a pre-update callback to retrieve
   79551 ** a field of the row currently being updated or inserted.
   79552 */
   79553 SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
   79554   PreUpdate *p = db->pPreUpdate;
   79555   int rc = SQLITE_OK;
   79556   Mem *pMem;
   79557 
   79558   if( !p || p->op==SQLITE_DELETE ){
   79559     rc = SQLITE_MISUSE_BKPT;
   79560     goto preupdate_new_out;
   79561   }
   79562   if( p->pPk && p->op!=SQLITE_UPDATE ){
   79563     iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
   79564   }
   79565   if( iIdx>=p->pCsr->nField || iIdx<0 ){
   79566     rc = SQLITE_RANGE;
   79567     goto preupdate_new_out;
   79568   }
   79569 
   79570   if( p->op==SQLITE_INSERT ){
   79571     /* For an INSERT, memory cell p->iNewReg contains the serialized record
   79572     ** that is being inserted. Deserialize it. */
   79573     UnpackedRecord *pUnpack = p->pNewUnpacked;
   79574     if( !pUnpack ){
   79575       Mem *pData = &p->v->aMem[p->iNewReg];
   79576       rc = ExpandBlob(pData);
   79577       if( rc!=SQLITE_OK ) goto preupdate_new_out;
   79578       pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
   79579       if( !pUnpack ){
   79580         rc = SQLITE_NOMEM;
   79581         goto preupdate_new_out;
   79582       }
   79583       p->pNewUnpacked = pUnpack;
   79584     }
   79585     pMem = &pUnpack->aMem[iIdx];
   79586     if( iIdx==p->pTab->iPKey ){
   79587       sqlite3VdbeMemSetInt64(pMem, p->iKey2);
   79588     }else if( iIdx>=pUnpack->nField ){
   79589       pMem = (sqlite3_value *)columnNullValue();
   79590     }
   79591   }else{
   79592     /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
   79593     ** value. Make a copy of the cell contents and return a pointer to it.
   79594     ** It is not safe to return a pointer to the memory cell itself as the
   79595     ** caller may modify the value text encoding.
   79596     */
   79597     assert( p->op==SQLITE_UPDATE );
   79598     if( !p->aNew ){
   79599       p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
   79600       if( !p->aNew ){
   79601         rc = SQLITE_NOMEM;
   79602         goto preupdate_new_out;
   79603       }
   79604     }
   79605     assert( iIdx>=0 && iIdx<p->pCsr->nField );
   79606     pMem = &p->aNew[iIdx];
   79607     if( pMem->flags==0 ){
   79608       if( iIdx==p->pTab->iPKey ){
   79609         sqlite3VdbeMemSetInt64(pMem, p->iKey2);
   79610       }else{
   79611         rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
   79612         if( rc!=SQLITE_OK ) goto preupdate_new_out;
   79613       }
   79614     }
   79615   }
   79616   *ppValue = pMem;
   79617 
   79618  preupdate_new_out:
   79619   sqlite3Error(db, rc);
   79620   return sqlite3ApiExit(db, rc);
   79621 }
   79622 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   79623 
   79624 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   79625 /*
   79626 ** Return status data for a single loop within query pStmt.
   79627 */
   79628 SQLITE_API int sqlite3_stmt_scanstatus(
   79629   sqlite3_stmt *pStmt,            /* Prepared statement being queried */
   79630   int idx,                        /* Index of loop to report on */
   79631   int iScanStatusOp,              /* Which metric to return */
   79632   void *pOut                      /* OUT: Write the answer here */
   79633 ){
   79634   Vdbe *p = (Vdbe*)pStmt;
   79635   ScanStatus *pScan;
   79636   if( idx<0 || idx>=p->nScan ) return 1;
   79637   pScan = &p->aScan[idx];
   79638   switch( iScanStatusOp ){
   79639     case SQLITE_SCANSTAT_NLOOP: {
   79640       *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
   79641       break;
   79642     }
   79643     case SQLITE_SCANSTAT_NVISIT: {
   79644       *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
   79645       break;
   79646     }
   79647     case SQLITE_SCANSTAT_EST: {
   79648       double r = 1.0;
   79649       LogEst x = pScan->nEst;
   79650       while( x<100 ){
   79651         x += 10;
   79652         r *= 0.5;
   79653       }
   79654       *(double*)pOut = r*sqlite3LogEstToInt(x);
   79655       break;
   79656     }
   79657     case SQLITE_SCANSTAT_NAME: {
   79658       *(const char**)pOut = pScan->zName;
   79659       break;
   79660     }
   79661     case SQLITE_SCANSTAT_EXPLAIN: {
   79662       if( pScan->addrExplain ){
   79663         *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
   79664       }else{
   79665         *(const char**)pOut = 0;
   79666       }
   79667       break;
   79668     }
   79669     case SQLITE_SCANSTAT_SELECTID: {
   79670       if( pScan->addrExplain ){
   79671         *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
   79672       }else{
   79673         *(int*)pOut = -1;
   79674       }
   79675       break;
   79676     }
   79677     default: {
   79678       return 1;
   79679     }
   79680   }
   79681   return 0;
   79682 }
   79683 
   79684 /*
   79685 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
   79686 */
   79687 SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
   79688   Vdbe *p = (Vdbe*)pStmt;
   79689   memset(p->anExec, 0, p->nOp * sizeof(i64));
   79690 }
   79691 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
   79692 
   79693 /************** End of vdbeapi.c *********************************************/
   79694 /************** Begin file vdbetrace.c ***************************************/
   79695 /*
   79696 ** 2009 November 25
   79697 **
   79698 ** The author disclaims copyright to this source code.  In place of
   79699 ** a legal notice, here is a blessing:
   79700 **
   79701 **    May you do good and not evil.
   79702 **    May you find forgiveness for yourself and forgive others.
   79703 **    May you share freely, never taking more than you give.
   79704 **
   79705 *************************************************************************
   79706 **
   79707 ** This file contains code used to insert the values of host parameters
   79708 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
   79709 **
   79710 ** The Vdbe parse-tree explainer is also found here.
   79711 */
   79712 /* #include "sqliteInt.h" */
   79713 /* #include "vdbeInt.h" */
   79714 
   79715 #ifndef SQLITE_OMIT_TRACE
   79716 
   79717 /*
   79718 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
   79719 ** bytes in this text up to but excluding the first character in
   79720 ** a host parameter.  If the text contains no host parameters, return
   79721 ** the total number of bytes in the text.
   79722 */
   79723 static int findNextHostParameter(const char *zSql, int *pnToken){
   79724   int tokenType;
   79725   int nTotal = 0;
   79726   int n;
   79727 
   79728   *pnToken = 0;
   79729   while( zSql[0] ){
   79730     n = sqlite3GetToken((u8*)zSql, &tokenType);
   79731     assert( n>0 && tokenType!=TK_ILLEGAL );
   79732     if( tokenType==TK_VARIABLE ){
   79733       *pnToken = n;
   79734       break;
   79735     }
   79736     nTotal += n;
   79737     zSql += n;
   79738   }
   79739   return nTotal;
   79740 }
   79741 
   79742 /*
   79743 ** This function returns a pointer to a nul-terminated string in memory
   79744 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
   79745 ** string contains a copy of zRawSql but with host parameters expanded to
   79746 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
   79747 ** then the returned string holds a copy of zRawSql with "-- " prepended
   79748 ** to each line of text.
   79749 **
   79750 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
   79751 ** then long strings and blobs are truncated to that many bytes.  This
   79752 ** can be used to prevent unreasonably large trace strings when dealing
   79753 ** with large (multi-megabyte) strings and blobs.
   79754 **
   79755 ** The calling function is responsible for making sure the memory returned
   79756 ** is eventually freed.
   79757 **
   79758 ** ALGORITHM:  Scan the input string looking for host parameters in any of
   79759 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
   79760 ** string literals, quoted identifier names, and comments.  For text forms,
   79761 ** the host parameter index is found by scanning the prepared
   79762 ** statement for the corresponding OP_Variable opcode.  Once the host
   79763 ** parameter index is known, locate the value in p->aVar[].  Then render
   79764 ** the value as a literal in place of the host parameter name.
   79765 */
   79766 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   79767   Vdbe *p,                 /* The prepared statement being evaluated */
   79768   const char *zRawSql      /* Raw text of the SQL statement */
   79769 ){
   79770   sqlite3 *db;             /* The database connection */
   79771   int idx = 0;             /* Index of a host parameter */
   79772   int nextIndex = 1;       /* Index of next ? host parameter */
   79773   int n;                   /* Length of a token prefix */
   79774   int nToken;              /* Length of the parameter token */
   79775   int i;                   /* Loop counter */
   79776   Mem *pVar;               /* Value of a host parameter */
   79777   StrAccum out;            /* Accumulate the output here */
   79778 #ifndef SQLITE_OMIT_UTF16
   79779   Mem utf8;                /* Used to convert UTF16 into UTF8 for display */
   79780 #endif
   79781   char zBase[100];         /* Initial working space */
   79782 
   79783   db = p->db;
   79784   sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
   79785                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   79786   if( db->nVdbeExec>1 ){
   79787     while( *zRawSql ){
   79788       const char *zStart = zRawSql;
   79789       while( *(zRawSql++)!='\n' && *zRawSql );
   79790       sqlite3StrAccumAppend(&out, "-- ", 3);
   79791       assert( (zRawSql - zStart) > 0 );
   79792       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
   79793     }
   79794   }else if( p->nVar==0 ){
   79795     sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
   79796   }else{
   79797     while( zRawSql[0] ){
   79798       n = findNextHostParameter(zRawSql, &nToken);
   79799       assert( n>0 );
   79800       sqlite3StrAccumAppend(&out, zRawSql, n);
   79801       zRawSql += n;
   79802       assert( zRawSql[0] || nToken==0 );
   79803       if( nToken==0 ) break;
   79804       if( zRawSql[0]=='?' ){
   79805         if( nToken>1 ){
   79806           assert( sqlite3Isdigit(zRawSql[1]) );
   79807           sqlite3GetInt32(&zRawSql[1], &idx);
   79808         }else{
   79809           idx = nextIndex;
   79810         }
   79811       }else{
   79812         assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
   79813                 zRawSql[0]=='@' || zRawSql[0]=='#' );
   79814         testcase( zRawSql[0]==':' );
   79815         testcase( zRawSql[0]=='$' );
   79816         testcase( zRawSql[0]=='@' );
   79817         testcase( zRawSql[0]=='#' );
   79818         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
   79819         assert( idx>0 );
   79820       }
   79821       zRawSql += nToken;
   79822       nextIndex = idx + 1;
   79823       assert( idx>0 && idx<=p->nVar );
   79824       pVar = &p->aVar[idx-1];
   79825       if( pVar->flags & MEM_Null ){
   79826         sqlite3StrAccumAppend(&out, "NULL", 4);
   79827       }else if( pVar->flags & MEM_Int ){
   79828         sqlite3XPrintf(&out, "%lld", pVar->u.i);
   79829       }else if( pVar->flags & MEM_Real ){
   79830         sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
   79831       }else if( pVar->flags & MEM_Str ){
   79832         int nOut;  /* Number of bytes of the string text to include in output */
   79833 #ifndef SQLITE_OMIT_UTF16
   79834         u8 enc = ENC(db);
   79835         if( enc!=SQLITE_UTF8 ){
   79836           memset(&utf8, 0, sizeof(utf8));
   79837           utf8.db = db;
   79838           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
   79839           if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
   79840             out.accError = STRACCUM_NOMEM;
   79841             out.nAlloc = 0;
   79842           }
   79843           pVar = &utf8;
   79844         }
   79845 #endif
   79846         nOut = pVar->n;
   79847 #ifdef SQLITE_TRACE_SIZE_LIMIT
   79848         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
   79849           nOut = SQLITE_TRACE_SIZE_LIMIT;
   79850           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
   79851         }
   79852 #endif
   79853         sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
   79854 #ifdef SQLITE_TRACE_SIZE_LIMIT
   79855         if( nOut<pVar->n ){
   79856           sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
   79857         }
   79858 #endif
   79859 #ifndef SQLITE_OMIT_UTF16
   79860         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
   79861 #endif
   79862       }else if( pVar->flags & MEM_Zero ){
   79863         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
   79864       }else{
   79865         int nOut;  /* Number of bytes of the blob to include in output */
   79866         assert( pVar->flags & MEM_Blob );
   79867         sqlite3StrAccumAppend(&out, "x'", 2);
   79868         nOut = pVar->n;
   79869 #ifdef SQLITE_TRACE_SIZE_LIMIT
   79870         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
   79871 #endif
   79872         for(i=0; i<nOut; i++){
   79873           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
   79874         }
   79875         sqlite3StrAccumAppend(&out, "'", 1);
   79876 #ifdef SQLITE_TRACE_SIZE_LIMIT
   79877         if( nOut<pVar->n ){
   79878           sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
   79879         }
   79880 #endif
   79881       }
   79882     }
   79883   }
   79884   if( out.accError ) sqlite3StrAccumReset(&out);
   79885   return sqlite3StrAccumFinish(&out);
   79886 }
   79887 
   79888 #endif /* #ifndef SQLITE_OMIT_TRACE */
   79889 
   79890 /************** End of vdbetrace.c *******************************************/
   79891 /************** Begin file vdbe.c ********************************************/
   79892 /*
   79893 ** 2001 September 15
   79894 **
   79895 ** The author disclaims copyright to this source code.  In place of
   79896 ** a legal notice, here is a blessing:
   79897 **
   79898 **    May you do good and not evil.
   79899 **    May you find forgiveness for yourself and forgive others.
   79900 **    May you share freely, never taking more than you give.
   79901 **
   79902 *************************************************************************
   79903 ** The code in this file implements the function that runs the
   79904 ** bytecode of a prepared statement.
   79905 **
   79906 ** Various scripts scan this source file in order to generate HTML
   79907 ** documentation, headers files, or other derived files.  The formatting
   79908 ** of the code in this file is, therefore, important.  See other comments
   79909 ** in this file for details.  If in doubt, do not deviate from existing
   79910 ** commenting and indentation practices when changing or adding code.
   79911 */
   79912 /* #include "sqliteInt.h" */
   79913 /* #include "vdbeInt.h" */
   79914 
   79915 /*
   79916 ** Invoke this macro on memory cells just prior to changing the
   79917 ** value of the cell.  This macro verifies that shallow copies are
   79918 ** not misused.  A shallow copy of a string or blob just copies a
   79919 ** pointer to the string or blob, not the content.  If the original
   79920 ** is changed while the copy is still in use, the string or blob might
   79921 ** be changed out from under the copy.  This macro verifies that nothing
   79922 ** like that ever happens.
   79923 */
   79924 #ifdef SQLITE_DEBUG
   79925 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
   79926 #else
   79927 # define memAboutToChange(P,M)
   79928 #endif
   79929 
   79930 /*
   79931 ** The following global variable is incremented every time a cursor
   79932 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
   79933 ** procedures use this information to make sure that indices are
   79934 ** working correctly.  This variable has no function other than to
   79935 ** help verify the correct operation of the library.
   79936 */
   79937 #ifdef SQLITE_TEST
   79938 SQLITE_API int sqlite3_search_count = 0;
   79939 #endif
   79940 
   79941 /*
   79942 ** When this global variable is positive, it gets decremented once before
   79943 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
   79944 ** field of the sqlite3 structure is set in order to simulate an interrupt.
   79945 **
   79946 ** This facility is used for testing purposes only.  It does not function
   79947 ** in an ordinary build.
   79948 */
   79949 #ifdef SQLITE_TEST
   79950 SQLITE_API int sqlite3_interrupt_count = 0;
   79951 #endif
   79952 
   79953 /*
   79954 ** The next global variable is incremented each type the OP_Sort opcode
   79955 ** is executed.  The test procedures use this information to make sure that
   79956 ** sorting is occurring or not occurring at appropriate times.   This variable
   79957 ** has no function other than to help verify the correct operation of the
   79958 ** library.
   79959 */
   79960 #ifdef SQLITE_TEST
   79961 SQLITE_API int sqlite3_sort_count = 0;
   79962 #endif
   79963 
   79964 /*
   79965 ** The next global variable records the size of the largest MEM_Blob
   79966 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
   79967 ** use this information to make sure that the zero-blob functionality
   79968 ** is working correctly.   This variable has no function other than to
   79969 ** help verify the correct operation of the library.
   79970 */
   79971 #ifdef SQLITE_TEST
   79972 SQLITE_API int sqlite3_max_blobsize = 0;
   79973 static void updateMaxBlobsize(Mem *p){
   79974   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
   79975     sqlite3_max_blobsize = p->n;
   79976   }
   79977 }
   79978 #endif
   79979 
   79980 /*
   79981 ** This macro evaluates to true if either the update hook or the preupdate
   79982 ** hook are enabled for database connect DB.
   79983 */
   79984 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   79985 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
   79986 #else
   79987 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
   79988 #endif
   79989 
   79990 /*
   79991 ** The next global variable is incremented each time the OP_Found opcode
   79992 ** is executed. This is used to test whether or not the foreign key
   79993 ** operation implemented using OP_FkIsZero is working. This variable
   79994 ** has no function other than to help verify the correct operation of the
   79995 ** library.
   79996 */
   79997 #ifdef SQLITE_TEST
   79998 SQLITE_API int sqlite3_found_count = 0;
   79999 #endif
   80000 
   80001 /*
   80002 ** Test a register to see if it exceeds the current maximum blob size.
   80003 ** If it does, record the new maximum blob size.
   80004 */
   80005 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
   80006 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   80007 #else
   80008 # define UPDATE_MAX_BLOBSIZE(P)
   80009 #endif
   80010 
   80011 /*
   80012 ** Invoke the VDBE coverage callback, if that callback is defined.  This
   80013 ** feature is used for test suite validation only and does not appear an
   80014 ** production builds.
   80015 **
   80016 ** M is an integer, 2 or 3, that indices how many different ways the
   80017 ** branch can go.  It is usually 2.  "I" is the direction the branch
   80018 ** goes.  0 means falls through.  1 means branch is taken.  2 means the
   80019 ** second alternative branch is taken.
   80020 **
   80021 ** iSrcLine is the source code line (from the __LINE__ macro) that
   80022 ** generated the VDBE instruction.  This instrumentation assumes that all
   80023 ** source code is in a single file (the amalgamation).  Special values 1
   80024 ** and 2 for the iSrcLine parameter mean that this particular branch is
   80025 ** always taken or never taken, respectively.
   80026 */
   80027 #if !defined(SQLITE_VDBE_COVERAGE)
   80028 # define VdbeBranchTaken(I,M)
   80029 #else
   80030 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
   80031   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
   80032     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
   80033       M = iSrcLine;
   80034       /* Assert the truth of VdbeCoverageAlwaysTaken() and
   80035       ** VdbeCoverageNeverTaken() */
   80036       assert( (M & I)==I );
   80037     }else{
   80038       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
   80039       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
   80040                                       iSrcLine,I,M);
   80041     }
   80042   }
   80043 #endif
   80044 
   80045 /*
   80046 ** Convert the given register into a string if it isn't one
   80047 ** already. Return non-zero if a malloc() fails.
   80048 */
   80049 #define Stringify(P, enc) \
   80050    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
   80051      { goto no_mem; }
   80052 
   80053 /*
   80054 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
   80055 ** a pointer to a dynamically allocated string where some other entity
   80056 ** is responsible for deallocating that string.  Because the register
   80057 ** does not control the string, it might be deleted without the register
   80058 ** knowing it.
   80059 **
   80060 ** This routine converts an ephemeral string into a dynamically allocated
   80061 ** string that the register itself controls.  In other words, it
   80062 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
   80063 */
   80064 #define Deephemeralize(P) \
   80065    if( ((P)->flags&MEM_Ephem)!=0 \
   80066        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   80067 
   80068 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
   80069 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
   80070 
   80071 /*
   80072 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
   80073 ** if we run out of memory.
   80074 */
   80075 static VdbeCursor *allocateCursor(
   80076   Vdbe *p,              /* The virtual machine */
   80077   int iCur,             /* Index of the new VdbeCursor */
   80078   int nField,           /* Number of fields in the table or index */
   80079   int iDb,              /* Database the cursor belongs to, or -1 */
   80080   u8 eCurType           /* Type of the new cursor */
   80081 ){
   80082   /* Find the memory cell that will be used to store the blob of memory
   80083   ** required for this VdbeCursor structure. It is convenient to use a
   80084   ** vdbe memory cell to manage the memory allocation required for a
   80085   ** VdbeCursor structure for the following reasons:
   80086   **
   80087   **   * Sometimes cursor numbers are used for a couple of different
   80088   **     purposes in a vdbe program. The different uses might require
   80089   **     different sized allocations. Memory cells provide growable
   80090   **     allocations.
   80091   **
   80092   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
   80093   **     be freed lazily via the sqlite3_release_memory() API. This
   80094   **     minimizes the number of malloc calls made by the system.
   80095   **
   80096   ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
   80097   ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
   80098   ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
   80099   */
   80100   Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
   80101 
   80102   int nByte;
   80103   VdbeCursor *pCx = 0;
   80104   nByte =
   80105       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
   80106       (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
   80107 
   80108   assert( iCur>=0 && iCur<p->nCursor );
   80109   if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
   80110     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
   80111     p->apCsr[iCur] = 0;
   80112   }
   80113   if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
   80114     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
   80115     memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
   80116     pCx->eCurType = eCurType;
   80117     pCx->iDb = iDb;
   80118     pCx->nField = nField;
   80119     pCx->aOffset = &pCx->aType[nField];
   80120     if( eCurType==CURTYPE_BTREE ){
   80121       pCx->uc.pCursor = (BtCursor*)
   80122           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
   80123       sqlite3BtreeCursorZero(pCx->uc.pCursor);
   80124     }
   80125   }
   80126   return pCx;
   80127 }
   80128 
   80129 /*
   80130 ** Try to convert a value into a numeric representation if we can
   80131 ** do so without loss of information.  In other words, if the string
   80132 ** looks like a number, convert it into a number.  If it does not
   80133 ** look like a number, leave it alone.
   80134 **
   80135 ** If the bTryForInt flag is true, then extra effort is made to give
   80136 ** an integer representation.  Strings that look like floating point
   80137 ** values but which have no fractional component (example: '48.00')
   80138 ** will have a MEM_Int representation when bTryForInt is true.
   80139 **
   80140 ** If bTryForInt is false, then if the input string contains a decimal
   80141 ** point or exponential notation, the result is only MEM_Real, even
   80142 ** if there is an exact integer representation of the quantity.
   80143 */
   80144 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
   80145   double rValue;
   80146   i64 iValue;
   80147   u8 enc = pRec->enc;
   80148   assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
   80149   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
   80150   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
   80151     pRec->u.i = iValue;
   80152     pRec->flags |= MEM_Int;
   80153   }else{
   80154     pRec->u.r = rValue;
   80155     pRec->flags |= MEM_Real;
   80156     if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
   80157   }
   80158 }
   80159 
   80160 /*
   80161 ** Processing is determine by the affinity parameter:
   80162 **
   80163 ** SQLITE_AFF_INTEGER:
   80164 ** SQLITE_AFF_REAL:
   80165 ** SQLITE_AFF_NUMERIC:
   80166 **    Try to convert pRec to an integer representation or a
   80167 **    floating-point representation if an integer representation
   80168 **    is not possible.  Note that the integer representation is
   80169 **    always preferred, even if the affinity is REAL, because
   80170 **    an integer representation is more space efficient on disk.
   80171 **
   80172 ** SQLITE_AFF_TEXT:
   80173 **    Convert pRec to a text representation.
   80174 **
   80175 ** SQLITE_AFF_BLOB:
   80176 **    No-op.  pRec is unchanged.
   80177 */
   80178 static void applyAffinity(
   80179   Mem *pRec,          /* The value to apply affinity to */
   80180   char affinity,      /* The affinity to be applied */
   80181   u8 enc              /* Use this text encoding */
   80182 ){
   80183   if( affinity>=SQLITE_AFF_NUMERIC ){
   80184     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
   80185              || affinity==SQLITE_AFF_NUMERIC );
   80186     if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
   80187       if( (pRec->flags & MEM_Real)==0 ){
   80188         if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
   80189       }else{
   80190         sqlite3VdbeIntegerAffinity(pRec);
   80191       }
   80192     }
   80193   }else if( affinity==SQLITE_AFF_TEXT ){
   80194     /* Only attempt the conversion to TEXT if there is an integer or real
   80195     ** representation (blob and NULL do not get converted) but no string
   80196     ** representation.  It would be harmless to repeat the conversion if
   80197     ** there is already a string rep, but it is pointless to waste those
   80198     ** CPU cycles. */
   80199     if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
   80200       if( (pRec->flags&(MEM_Real|MEM_Int)) ){
   80201         sqlite3VdbeMemStringify(pRec, enc, 1);
   80202       }
   80203     }
   80204     pRec->flags &= ~(MEM_Real|MEM_Int);
   80205   }
   80206 }
   80207 
   80208 /*
   80209 ** Try to convert the type of a function argument or a result column
   80210 ** into a numeric representation.  Use either INTEGER or REAL whichever
   80211 ** is appropriate.  But only do the conversion if it is possible without
   80212 ** loss of information and return the revised type of the argument.
   80213 */
   80214 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
   80215   int eType = sqlite3_value_type(pVal);
   80216   if( eType==SQLITE_TEXT ){
   80217     Mem *pMem = (Mem*)pVal;
   80218     applyNumericAffinity(pMem, 0);
   80219     eType = sqlite3_value_type(pVal);
   80220   }
   80221   return eType;
   80222 }
   80223 
   80224 /*
   80225 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
   80226 ** not the internal Mem* type.
   80227 */
   80228 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
   80229   sqlite3_value *pVal,
   80230   u8 affinity,
   80231   u8 enc
   80232 ){
   80233   applyAffinity((Mem *)pVal, affinity, enc);
   80234 }
   80235 
   80236 /*
   80237 ** pMem currently only holds a string type (or maybe a BLOB that we can
   80238 ** interpret as a string if we want to).  Compute its corresponding
   80239 ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
   80240 ** accordingly.
   80241 */
   80242 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
   80243   assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
   80244   assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
   80245   if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
   80246     return 0;
   80247   }
   80248   if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
   80249     return MEM_Int;
   80250   }
   80251   return MEM_Real;
   80252 }
   80253 
   80254 /*
   80255 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
   80256 ** none.
   80257 **
   80258 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
   80259 ** But it does set pMem->u.r and pMem->u.i appropriately.
   80260 */
   80261 static u16 numericType(Mem *pMem){
   80262   if( pMem->flags & (MEM_Int|MEM_Real) ){
   80263     return pMem->flags & (MEM_Int|MEM_Real);
   80264   }
   80265   if( pMem->flags & (MEM_Str|MEM_Blob) ){
   80266     return computeNumericType(pMem);
   80267   }
   80268   return 0;
   80269 }
   80270 
   80271 #ifdef SQLITE_DEBUG
   80272 /*
   80273 ** Write a nice string representation of the contents of cell pMem
   80274 ** into buffer zBuf, length nBuf.
   80275 */
   80276 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
   80277   char *zCsr = zBuf;
   80278   int f = pMem->flags;
   80279 
   80280   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
   80281 
   80282   if( f&MEM_Blob ){
   80283     int i;
   80284     char c;
   80285     if( f & MEM_Dyn ){
   80286       c = 'z';
   80287       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   80288     }else if( f & MEM_Static ){
   80289       c = 't';
   80290       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   80291     }else if( f & MEM_Ephem ){
   80292       c = 'e';
   80293       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   80294     }else{
   80295       c = 's';
   80296     }
   80297     *(zCsr++) = c;
   80298     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
   80299     zCsr += sqlite3Strlen30(zCsr);
   80300     for(i=0; i<16 && i<pMem->n; i++){
   80301       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
   80302       zCsr += sqlite3Strlen30(zCsr);
   80303     }
   80304     for(i=0; i<16 && i<pMem->n; i++){
   80305       char z = pMem->z[i];
   80306       if( z<32 || z>126 ) *zCsr++ = '.';
   80307       else *zCsr++ = z;
   80308     }
   80309     *(zCsr++) = ']';
   80310     if( f & MEM_Zero ){
   80311       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
   80312       zCsr += sqlite3Strlen30(zCsr);
   80313     }
   80314     *zCsr = '\0';
   80315   }else if( f & MEM_Str ){
   80316     int j, k;
   80317     zBuf[0] = ' ';
   80318     if( f & MEM_Dyn ){
   80319       zBuf[1] = 'z';
   80320       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   80321     }else if( f & MEM_Static ){
   80322       zBuf[1] = 't';
   80323       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   80324     }else if( f & MEM_Ephem ){
   80325       zBuf[1] = 'e';
   80326       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   80327     }else{
   80328       zBuf[1] = 's';
   80329     }
   80330     k = 2;
   80331     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
   80332     k += sqlite3Strlen30(&zBuf[k]);
   80333     zBuf[k++] = '[';
   80334     for(j=0; j<15 && j<pMem->n; j++){
   80335       u8 c = pMem->z[j];
   80336       if( c>=0x20 && c<0x7f ){
   80337         zBuf[k++] = c;
   80338       }else{
   80339         zBuf[k++] = '.';
   80340       }
   80341     }
   80342     zBuf[k++] = ']';
   80343     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
   80344     k += sqlite3Strlen30(&zBuf[k]);
   80345     zBuf[k++] = 0;
   80346   }
   80347 }
   80348 #endif
   80349 
   80350 #ifdef SQLITE_DEBUG
   80351 /*
   80352 ** Print the value of a register for tracing purposes:
   80353 */
   80354 static void memTracePrint(Mem *p){
   80355   if( p->flags & MEM_Undefined ){
   80356     printf(" undefined");
   80357   }else if( p->flags & MEM_Null ){
   80358     printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
   80359   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
   80360     printf(" si:%lld", p->u.i);
   80361   }else if( p->flags & MEM_Int ){
   80362     printf(" i:%lld", p->u.i);
   80363 #ifndef SQLITE_OMIT_FLOATING_POINT
   80364   }else if( p->flags & MEM_Real ){
   80365     printf(" r:%g", p->u.r);
   80366 #endif
   80367   }else if( p->flags & MEM_RowSet ){
   80368     printf(" (rowset)");
   80369   }else{
   80370     char zBuf[200];
   80371     sqlite3VdbeMemPrettyPrint(p, zBuf);
   80372     printf(" %s", zBuf);
   80373   }
   80374   if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
   80375 }
   80376 static void registerTrace(int iReg, Mem *p){
   80377   printf("REG[%d] = ", iReg);
   80378   memTracePrint(p);
   80379   printf("\n");
   80380   sqlite3VdbeCheckMemInvariants(p);
   80381 }
   80382 #endif
   80383 
   80384 #ifdef SQLITE_DEBUG
   80385 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
   80386 #else
   80387 #  define REGISTER_TRACE(R,M)
   80388 #endif
   80389 
   80390 
   80391 #ifdef VDBE_PROFILE
   80392 
   80393 /*
   80394 ** hwtime.h contains inline assembler code for implementing
   80395 ** high-performance timing routines.
   80396 */
   80397 /************** Include hwtime.h in the middle of vdbe.c *********************/
   80398 /************** Begin file hwtime.h ******************************************/
   80399 /*
   80400 ** 2008 May 27
   80401 **
   80402 ** The author disclaims copyright to this source code.  In place of
   80403 ** a legal notice, here is a blessing:
   80404 **
   80405 **    May you do good and not evil.
   80406 **    May you find forgiveness for yourself and forgive others.
   80407 **    May you share freely, never taking more than you give.
   80408 **
   80409 ******************************************************************************
   80410 **
   80411 ** This file contains inline asm code for retrieving "high-performance"
   80412 ** counters for x86 class CPUs.
   80413 */
   80414 #ifndef SQLITE_HWTIME_H
   80415 #define SQLITE_HWTIME_H
   80416 
   80417 /*
   80418 ** The following routine only works on pentium-class (or newer) processors.
   80419 ** It uses the RDTSC opcode to read the cycle count value out of the
   80420 ** processor and returns that value.  This can be used for high-res
   80421 ** profiling.
   80422 */
   80423 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   80424       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   80425 
   80426   #if defined(__GNUC__)
   80427 
   80428   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   80429      unsigned int lo, hi;
   80430      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   80431      return (sqlite_uint64)hi << 32 | lo;
   80432   }
   80433 
   80434   #elif defined(_MSC_VER)
   80435 
   80436   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   80437      __asm {
   80438         rdtsc
   80439         ret       ; return value at EDX:EAX
   80440      }
   80441   }
   80442 
   80443   #endif
   80444 
   80445 #elif (defined(__GNUC__) && defined(__x86_64__))
   80446 
   80447   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   80448       unsigned long val;
   80449       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   80450       return val;
   80451   }
   80452 
   80453 #elif (defined(__GNUC__) && defined(__ppc__))
   80454 
   80455   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   80456       unsigned long long retval;
   80457       unsigned long junk;
   80458       __asm__ __volatile__ ("\n\
   80459           1:      mftbu   %1\n\
   80460                   mftb    %L0\n\
   80461                   mftbu   %0\n\
   80462                   cmpw    %0,%1\n\
   80463                   bne     1b"
   80464                   : "=r" (retval), "=r" (junk));
   80465       return retval;
   80466   }
   80467 
   80468 #else
   80469 
   80470   #error Need implementation of sqlite3Hwtime() for your platform.
   80471 
   80472   /*
   80473   ** To compile without implementing sqlite3Hwtime() for your platform,
   80474   ** you can remove the above #error and use the following
   80475   ** stub function.  You will lose timing support for many
   80476   ** of the debugging and testing utilities, but it should at
   80477   ** least compile and run.
   80478   */
   80479 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   80480 
   80481 #endif
   80482 
   80483 #endif /* !defined(SQLITE_HWTIME_H) */
   80484 
   80485 /************** End of hwtime.h **********************************************/
   80486 /************** Continuing where we left off in vdbe.c ***********************/
   80487 
   80488 #endif
   80489 
   80490 #ifndef NDEBUG
   80491 /*
   80492 ** This function is only called from within an assert() expression. It
   80493 ** checks that the sqlite3.nTransaction variable is correctly set to
   80494 ** the number of non-transaction savepoints currently in the
   80495 ** linked list starting at sqlite3.pSavepoint.
   80496 **
   80497 ** Usage:
   80498 **
   80499 **     assert( checkSavepointCount(db) );
   80500 */
   80501 static int checkSavepointCount(sqlite3 *db){
   80502   int n = 0;
   80503   Savepoint *p;
   80504   for(p=db->pSavepoint; p; p=p->pNext) n++;
   80505   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
   80506   return 1;
   80507 }
   80508 #endif
   80509 
   80510 /*
   80511 ** Return the register of pOp->p2 after first preparing it to be
   80512 ** overwritten with an integer value.
   80513 */
   80514 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
   80515   sqlite3VdbeMemSetNull(pOut);
   80516   pOut->flags = MEM_Int;
   80517   return pOut;
   80518 }
   80519 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
   80520   Mem *pOut;
   80521   assert( pOp->p2>0 );
   80522   assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
   80523   pOut = &p->aMem[pOp->p2];
   80524   memAboutToChange(p, pOut);
   80525   if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
   80526     return out2PrereleaseWithClear(pOut);
   80527   }else{
   80528     pOut->flags = MEM_Int;
   80529     return pOut;
   80530   }
   80531 }
   80532 
   80533 
   80534 /*
   80535 ** Execute as much of a VDBE program as we can.
   80536 ** This is the core of sqlite3_step().
   80537 */
   80538 SQLITE_PRIVATE int sqlite3VdbeExec(
   80539   Vdbe *p                    /* The VDBE */
   80540 ){
   80541   Op *aOp = p->aOp;          /* Copy of p->aOp */
   80542   Op *pOp = aOp;             /* Current operation */
   80543 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   80544   Op *pOrigOp;               /* Value of pOp at the top of the loop */
   80545 #endif
   80546 #ifdef SQLITE_DEBUG
   80547   int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
   80548 #endif
   80549   int rc = SQLITE_OK;        /* Value to return */
   80550   sqlite3 *db = p->db;       /* The database */
   80551   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
   80552   u8 encoding = ENC(db);     /* The database encoding */
   80553   int iCompare = 0;          /* Result of last comparison */
   80554   unsigned nVmStep = 0;      /* Number of virtual machine steps */
   80555 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   80556   unsigned nProgressLimit;   /* Invoke xProgress() when nVmStep reaches this */
   80557 #endif
   80558   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   80559   Mem *pIn1 = 0;             /* 1st input operand */
   80560   Mem *pIn2 = 0;             /* 2nd input operand */
   80561   Mem *pIn3 = 0;             /* 3rd input operand */
   80562   Mem *pOut = 0;             /* Output operand */
   80563 #ifdef VDBE_PROFILE
   80564   u64 start;                 /* CPU clock count at start of opcode */
   80565 #endif
   80566   /*** INSERT STACK UNION HERE ***/
   80567 
   80568   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   80569   sqlite3VdbeEnter(p);
   80570   if( p->rc==SQLITE_NOMEM ){
   80571     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   80572     ** sqlite3_column_text16() failed.  */
   80573     goto no_mem;
   80574   }
   80575   assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
   80576   assert( p->bIsReader || p->readOnly!=0 );
   80577   p->iCurrentTime = 0;
   80578   assert( p->explain==0 );
   80579   p->pResultSet = 0;
   80580   db->busyHandler.nBusy = 0;
   80581   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   80582   sqlite3VdbeIOTraceSql(p);
   80583 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   80584   if( db->xProgress ){
   80585     u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
   80586     assert( 0 < db->nProgressOps );
   80587     nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
   80588   }else{
   80589     nProgressLimit = 0xffffffff;
   80590   }
   80591 #endif
   80592 #ifdef SQLITE_DEBUG
   80593   sqlite3BeginBenignMalloc();
   80594   if( p->pc==0
   80595    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
   80596   ){
   80597     int i;
   80598     int once = 1;
   80599     sqlite3VdbePrintSql(p);
   80600     if( p->db->flags & SQLITE_VdbeListing ){
   80601       printf("VDBE Program Listing:\n");
   80602       for(i=0; i<p->nOp; i++){
   80603         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
   80604       }
   80605     }
   80606     if( p->db->flags & SQLITE_VdbeEQP ){
   80607       for(i=0; i<p->nOp; i++){
   80608         if( aOp[i].opcode==OP_Explain ){
   80609           if( once ) printf("VDBE Query Plan:\n");
   80610           printf("%s\n", aOp[i].p4.z);
   80611           once = 0;
   80612         }
   80613       }
   80614     }
   80615     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
   80616   }
   80617   sqlite3EndBenignMalloc();
   80618 #endif
   80619   for(pOp=&aOp[p->pc]; 1; pOp++){
   80620     /* Errors are detected by individual opcodes, with an immediate
   80621     ** jumps to abort_due_to_error. */
   80622     assert( rc==SQLITE_OK );
   80623 
   80624     assert( pOp>=aOp && pOp<&aOp[p->nOp]);
   80625 #ifdef VDBE_PROFILE
   80626     start = sqlite3Hwtime();
   80627 #endif
   80628     nVmStep++;
   80629 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   80630     if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
   80631 #endif
   80632 
   80633     /* Only allow tracing if SQLITE_DEBUG is defined.
   80634     */
   80635 #ifdef SQLITE_DEBUG
   80636     if( db->flags & SQLITE_VdbeTrace ){
   80637       sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
   80638     }
   80639 #endif
   80640 
   80641 
   80642     /* Check to see if we need to simulate an interrupt.  This only happens
   80643     ** if we have a special test build.
   80644     */
   80645 #ifdef SQLITE_TEST
   80646     if( sqlite3_interrupt_count>0 ){
   80647       sqlite3_interrupt_count--;
   80648       if( sqlite3_interrupt_count==0 ){
   80649         sqlite3_interrupt(db);
   80650       }
   80651     }
   80652 #endif
   80653 
   80654     /* Sanity checking on other operands */
   80655 #ifdef SQLITE_DEBUG
   80656     {
   80657       u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
   80658       if( (opProperty & OPFLG_IN1)!=0 ){
   80659         assert( pOp->p1>0 );
   80660         assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
   80661         assert( memIsValid(&aMem[pOp->p1]) );
   80662         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
   80663         REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   80664       }
   80665       if( (opProperty & OPFLG_IN2)!=0 ){
   80666         assert( pOp->p2>0 );
   80667         assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
   80668         assert( memIsValid(&aMem[pOp->p2]) );
   80669         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
   80670         REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   80671       }
   80672       if( (opProperty & OPFLG_IN3)!=0 ){
   80673         assert( pOp->p3>0 );
   80674         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
   80675         assert( memIsValid(&aMem[pOp->p3]) );
   80676         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
   80677         REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   80678       }
   80679       if( (opProperty & OPFLG_OUT2)!=0 ){
   80680         assert( pOp->p2>0 );
   80681         assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
   80682         memAboutToChange(p, &aMem[pOp->p2]);
   80683       }
   80684       if( (opProperty & OPFLG_OUT3)!=0 ){
   80685         assert( pOp->p3>0 );
   80686         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
   80687         memAboutToChange(p, &aMem[pOp->p3]);
   80688       }
   80689     }
   80690 #endif
   80691 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   80692     pOrigOp = pOp;
   80693 #endif
   80694 
   80695     switch( pOp->opcode ){
   80696 
   80697 /*****************************************************************************
   80698 ** What follows is a massive switch statement where each case implements a
   80699 ** separate instruction in the virtual machine.  If we follow the usual
   80700 ** indentation conventions, each case should be indented by 6 spaces.  But
   80701 ** that is a lot of wasted space on the left margin.  So the code within
   80702 ** the switch statement will break with convention and be flush-left. Another
   80703 ** big comment (similar to this one) will mark the point in the code where
   80704 ** we transition back to normal indentation.
   80705 **
   80706 ** The formatting of each case is important.  The makefile for SQLite
   80707 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
   80708 ** file looking for lines that begin with "case OP_".  The opcodes.h files
   80709 ** will be filled with #defines that give unique integer values to each
   80710 ** opcode and the opcodes.c file is filled with an array of strings where
   80711 ** each string is the symbolic name for the corresponding opcode.  If the
   80712 ** case statement is followed by a comment of the form "/# same as ... #/"
   80713 ** that comment is used to determine the particular value of the opcode.
   80714 **
   80715 ** Other keywords in the comment that follows each case are used to
   80716 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
   80717 ** Keywords include: in1, in2, in3, out2, out3.  See
   80718 ** the mkopcodeh.awk script for additional information.
   80719 **
   80720 ** Documentation about VDBE opcodes is generated by scanning this file
   80721 ** for lines of that contain "Opcode:".  That line and all subsequent
   80722 ** comment lines are used in the generation of the opcode.html documentation
   80723 ** file.
   80724 **
   80725 ** SUMMARY:
   80726 **
   80727 **     Formatting is important to scripts that scan this file.
   80728 **     Do not deviate from the formatting style currently in use.
   80729 **
   80730 *****************************************************************************/
   80731 
   80732 /* Opcode:  Goto * P2 * * *
   80733 **
   80734 ** An unconditional jump to address P2.
   80735 ** The next instruction executed will be
   80736 ** the one at index P2 from the beginning of
   80737 ** the program.
   80738 **
   80739 ** The P1 parameter is not actually used by this opcode.  However, it
   80740 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
   80741 ** that this Goto is the bottom of a loop and that the lines from P2 down
   80742 ** to the current line should be indented for EXPLAIN output.
   80743 */
   80744 case OP_Goto: {             /* jump */
   80745 jump_to_p2_and_check_for_interrupt:
   80746   pOp = &aOp[pOp->p2 - 1];
   80747 
   80748   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
   80749   ** OP_VNext, or OP_SorterNext) all jump here upon
   80750   ** completion.  Check to see if sqlite3_interrupt() has been called
   80751   ** or if the progress callback needs to be invoked.
   80752   **
   80753   ** This code uses unstructured "goto" statements and does not look clean.
   80754   ** But that is not due to sloppy coding habits. The code is written this
   80755   ** way for performance, to avoid having to run the interrupt and progress
   80756   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
   80757   ** faster according to "valgrind --tool=cachegrind" */
   80758 check_for_interrupt:
   80759   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   80760 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   80761   /* Call the progress callback if it is configured and the required number
   80762   ** of VDBE ops have been executed (either since this invocation of
   80763   ** sqlite3VdbeExec() or since last time the progress callback was called).
   80764   ** If the progress callback returns non-zero, exit the virtual machine with
   80765   ** a return code SQLITE_ABORT.
   80766   */
   80767   if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
   80768     assert( db->nProgressOps!=0 );
   80769     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
   80770     if( db->xProgress(db->pProgressArg) ){
   80771       rc = SQLITE_INTERRUPT;
   80772       goto abort_due_to_error;
   80773     }
   80774   }
   80775 #endif
   80776 
   80777   break;
   80778 }
   80779 
   80780 /* Opcode:  Gosub P1 P2 * * *
   80781 **
   80782 ** Write the current address onto register P1
   80783 ** and then jump to address P2.
   80784 */
   80785 case OP_Gosub: {            /* jump */
   80786   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
   80787   pIn1 = &aMem[pOp->p1];
   80788   assert( VdbeMemDynamic(pIn1)==0 );
   80789   memAboutToChange(p, pIn1);
   80790   pIn1->flags = MEM_Int;
   80791   pIn1->u.i = (int)(pOp-aOp);
   80792   REGISTER_TRACE(pOp->p1, pIn1);
   80793 
   80794   /* Most jump operations do a goto to this spot in order to update
   80795   ** the pOp pointer. */
   80796 jump_to_p2:
   80797   pOp = &aOp[pOp->p2 - 1];
   80798   break;
   80799 }
   80800 
   80801 /* Opcode:  Return P1 * * * *
   80802 **
   80803 ** Jump to the next instruction after the address in register P1.  After
   80804 ** the jump, register P1 becomes undefined.
   80805 */
   80806 case OP_Return: {           /* in1 */
   80807   pIn1 = &aMem[pOp->p1];
   80808   assert( pIn1->flags==MEM_Int );
   80809   pOp = &aOp[pIn1->u.i];
   80810   pIn1->flags = MEM_Undefined;
   80811   break;
   80812 }
   80813 
   80814 /* Opcode: InitCoroutine P1 P2 P3 * *
   80815 **
   80816 ** Set up register P1 so that it will Yield to the coroutine
   80817 ** located at address P3.
   80818 **
   80819 ** If P2!=0 then the coroutine implementation immediately follows
   80820 ** this opcode.  So jump over the coroutine implementation to
   80821 ** address P2.
   80822 **
   80823 ** See also: EndCoroutine
   80824 */
   80825 case OP_InitCoroutine: {     /* jump */
   80826   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
   80827   assert( pOp->p2>=0 && pOp->p2<p->nOp );
   80828   assert( pOp->p3>=0 && pOp->p3<p->nOp );
   80829   pOut = &aMem[pOp->p1];
   80830   assert( !VdbeMemDynamic(pOut) );
   80831   pOut->u.i = pOp->p3 - 1;
   80832   pOut->flags = MEM_Int;
   80833   if( pOp->p2 ) goto jump_to_p2;
   80834   break;
   80835 }
   80836 
   80837 /* Opcode:  EndCoroutine P1 * * * *
   80838 **
   80839 ** The instruction at the address in register P1 is a Yield.
   80840 ** Jump to the P2 parameter of that Yield.
   80841 ** After the jump, register P1 becomes undefined.
   80842 **
   80843 ** See also: InitCoroutine
   80844 */
   80845 case OP_EndCoroutine: {           /* in1 */
   80846   VdbeOp *pCaller;
   80847   pIn1 = &aMem[pOp->p1];
   80848   assert( pIn1->flags==MEM_Int );
   80849   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
   80850   pCaller = &aOp[pIn1->u.i];
   80851   assert( pCaller->opcode==OP_Yield );
   80852   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
   80853   pOp = &aOp[pCaller->p2 - 1];
   80854   pIn1->flags = MEM_Undefined;
   80855   break;
   80856 }
   80857 
   80858 /* Opcode:  Yield P1 P2 * * *
   80859 **
   80860 ** Swap the program counter with the value in register P1.  This
   80861 ** has the effect of yielding to a coroutine.
   80862 **
   80863 ** If the coroutine that is launched by this instruction ends with
   80864 ** Yield or Return then continue to the next instruction.  But if
   80865 ** the coroutine launched by this instruction ends with
   80866 ** EndCoroutine, then jump to P2 rather than continuing with the
   80867 ** next instruction.
   80868 **
   80869 ** See also: InitCoroutine
   80870 */
   80871 case OP_Yield: {            /* in1, jump */
   80872   int pcDest;
   80873   pIn1 = &aMem[pOp->p1];
   80874   assert( VdbeMemDynamic(pIn1)==0 );
   80875   pIn1->flags = MEM_Int;
   80876   pcDest = (int)pIn1->u.i;
   80877   pIn1->u.i = (int)(pOp - aOp);
   80878   REGISTER_TRACE(pOp->p1, pIn1);
   80879   pOp = &aOp[pcDest];
   80880   break;
   80881 }
   80882 
   80883 /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
   80884 ** Synopsis: if r[P3]=null halt
   80885 **
   80886 ** Check the value in register P3.  If it is NULL then Halt using
   80887 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
   80888 ** value in register P3 is not NULL, then this routine is a no-op.
   80889 ** The P5 parameter should be 1.
   80890 */
   80891 case OP_HaltIfNull: {      /* in3 */
   80892   pIn3 = &aMem[pOp->p3];
   80893   if( (pIn3->flags & MEM_Null)==0 ) break;
   80894   /* Fall through into OP_Halt */
   80895 }
   80896 
   80897 /* Opcode:  Halt P1 P2 * P4 P5
   80898 **
   80899 ** Exit immediately.  All open cursors, etc are closed
   80900 ** automatically.
   80901 **
   80902 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
   80903 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
   80904 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
   80905 ** whether or not to rollback the current transaction.  Do not rollback
   80906 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
   80907 ** then back out all changes that have occurred during this execution of the
   80908 ** VDBE, but do not rollback the transaction.
   80909 **
   80910 ** If P4 is not null then it is an error message string.
   80911 **
   80912 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
   80913 **
   80914 **    0:  (no change)
   80915 **    1:  NOT NULL contraint failed: P4
   80916 **    2:  UNIQUE constraint failed: P4
   80917 **    3:  CHECK constraint failed: P4
   80918 **    4:  FOREIGN KEY constraint failed: P4
   80919 **
   80920 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
   80921 ** omitted.
   80922 **
   80923 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   80924 ** every program.  So a jump past the last instruction of the program
   80925 ** is the same as executing Halt.
   80926 */
   80927 case OP_Halt: {
   80928   VdbeFrame *pFrame;
   80929   int pcx;
   80930 
   80931   pcx = (int)(pOp - aOp);
   80932   if( pOp->p1==SQLITE_OK && p->pFrame ){
   80933     /* Halt the sub-program. Return control to the parent frame. */
   80934     pFrame = p->pFrame;
   80935     p->pFrame = pFrame->pParent;
   80936     p->nFrame--;
   80937     sqlite3VdbeSetChanges(db, p->nChange);
   80938     pcx = sqlite3VdbeFrameRestore(pFrame);
   80939     if( pOp->p2==OE_Ignore ){
   80940       /* Instruction pcx is the OP_Program that invoked the sub-program
   80941       ** currently being halted. If the p2 instruction of this OP_Halt
   80942       ** instruction is set to OE_Ignore, then the sub-program is throwing
   80943       ** an IGNORE exception. In this case jump to the address specified
   80944       ** as the p2 of the calling OP_Program.  */
   80945       pcx = p->aOp[pcx].p2-1;
   80946     }
   80947     aOp = p->aOp;
   80948     aMem = p->aMem;
   80949     pOp = &aOp[pcx];
   80950     break;
   80951   }
   80952   p->rc = pOp->p1;
   80953   p->errorAction = (u8)pOp->p2;
   80954   p->pc = pcx;
   80955   assert( pOp->p5<=4 );
   80956   if( p->rc ){
   80957     if( pOp->p5 ){
   80958       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
   80959                                              "FOREIGN KEY" };
   80960       testcase( pOp->p5==1 );
   80961       testcase( pOp->p5==2 );
   80962       testcase( pOp->p5==3 );
   80963       testcase( pOp->p5==4 );
   80964       sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
   80965       if( pOp->p4.z ){
   80966         p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
   80967       }
   80968     }else{
   80969       sqlite3VdbeError(p, "%s", pOp->p4.z);
   80970     }
   80971     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
   80972   }
   80973   rc = sqlite3VdbeHalt(p);
   80974   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
   80975   if( rc==SQLITE_BUSY ){
   80976     p->rc = SQLITE_BUSY;
   80977   }else{
   80978     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
   80979     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
   80980     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
   80981   }
   80982   goto vdbe_return;
   80983 }
   80984 
   80985 /* Opcode: Integer P1 P2 * * *
   80986 ** Synopsis: r[P2]=P1
   80987 **
   80988 ** The 32-bit integer value P1 is written into register P2.
   80989 */
   80990 case OP_Integer: {         /* out2 */
   80991   pOut = out2Prerelease(p, pOp);
   80992   pOut->u.i = pOp->p1;
   80993   break;
   80994 }
   80995 
   80996 /* Opcode: Int64 * P2 * P4 *
   80997 ** Synopsis: r[P2]=P4
   80998 **
   80999 ** P4 is a pointer to a 64-bit integer value.
   81000 ** Write that value into register P2.
   81001 */
   81002 case OP_Int64: {           /* out2 */
   81003   pOut = out2Prerelease(p, pOp);
   81004   assert( pOp->p4.pI64!=0 );
   81005   pOut->u.i = *pOp->p4.pI64;
   81006   break;
   81007 }
   81008 
   81009 #ifndef SQLITE_OMIT_FLOATING_POINT
   81010 /* Opcode: Real * P2 * P4 *
   81011 ** Synopsis: r[P2]=P4
   81012 **
   81013 ** P4 is a pointer to a 64-bit floating point value.
   81014 ** Write that value into register P2.
   81015 */
   81016 case OP_Real: {            /* same as TK_FLOAT, out2 */
   81017   pOut = out2Prerelease(p, pOp);
   81018   pOut->flags = MEM_Real;
   81019   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
   81020   pOut->u.r = *pOp->p4.pReal;
   81021   break;
   81022 }
   81023 #endif
   81024 
   81025 /* Opcode: String8 * P2 * P4 *
   81026 ** Synopsis: r[P2]='P4'
   81027 **
   81028 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
   81029 ** into a String opcode before it is executed for the first time.  During
   81030 ** this transformation, the length of string P4 is computed and stored
   81031 ** as the P1 parameter.
   81032 */
   81033 case OP_String8: {         /* same as TK_STRING, out2 */
   81034   assert( pOp->p4.z!=0 );
   81035   pOut = out2Prerelease(p, pOp);
   81036   pOp->opcode = OP_String;
   81037   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
   81038 
   81039 #ifndef SQLITE_OMIT_UTF16
   81040   if( encoding!=SQLITE_UTF8 ){
   81041     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   81042     assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
   81043     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   81044     assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
   81045     assert( VdbeMemDynamic(pOut)==0 );
   81046     pOut->szMalloc = 0;
   81047     pOut->flags |= MEM_Static;
   81048     if( pOp->p4type==P4_DYNAMIC ){
   81049       sqlite3DbFree(db, pOp->p4.z);
   81050     }
   81051     pOp->p4type = P4_DYNAMIC;
   81052     pOp->p4.z = pOut->z;
   81053     pOp->p1 = pOut->n;
   81054   }
   81055   testcase( rc==SQLITE_TOOBIG );
   81056 #endif
   81057   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   81058     goto too_big;
   81059   }
   81060   assert( rc==SQLITE_OK );
   81061   /* Fall through to the next case, OP_String */
   81062 }
   81063 
   81064 /* Opcode: String P1 P2 P3 P4 P5
   81065 ** Synopsis: r[P2]='P4' (len=P1)
   81066 **
   81067 ** The string value P4 of length P1 (bytes) is stored in register P2.
   81068 **
   81069 ** If P3 is not zero and the content of register P3 is equal to P5, then
   81070 ** the datatype of the register P2 is converted to BLOB.  The content is
   81071 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
   81072 ** of a string, as if it had been CAST.  In other words:
   81073 **
   81074 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
   81075 */
   81076 case OP_String: {          /* out2 */
   81077   assert( pOp->p4.z!=0 );
   81078   pOut = out2Prerelease(p, pOp);
   81079   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   81080   pOut->z = pOp->p4.z;
   81081   pOut->n = pOp->p1;
   81082   pOut->enc = encoding;
   81083   UPDATE_MAX_BLOBSIZE(pOut);
   81084 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   81085   if( pOp->p3>0 ){
   81086     assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
   81087     pIn3 = &aMem[pOp->p3];
   81088     assert( pIn3->flags & MEM_Int );
   81089     if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
   81090   }
   81091 #endif
   81092   break;
   81093 }
   81094 
   81095 /* Opcode: Null P1 P2 P3 * *
   81096 ** Synopsis: r[P2..P3]=NULL
   81097 **
   81098 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
   81099 ** NULL into register P3 and every register in between P2 and P3.  If P3
   81100 ** is less than P2 (typically P3 is zero) then only register P2 is
   81101 ** set to NULL.
   81102 **
   81103 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
   81104 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
   81105 ** OP_Ne or OP_Eq.
   81106 */
   81107 case OP_Null: {           /* out2 */
   81108   int cnt;
   81109   u16 nullFlag;
   81110   pOut = out2Prerelease(p, pOp);
   81111   cnt = pOp->p3-pOp->p2;
   81112   assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
   81113   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
   81114   pOut->n = 0;
   81115   while( cnt>0 ){
   81116     pOut++;
   81117     memAboutToChange(p, pOut);
   81118     sqlite3VdbeMemSetNull(pOut);
   81119     pOut->flags = nullFlag;
   81120     pOut->n = 0;
   81121     cnt--;
   81122   }
   81123   break;
   81124 }
   81125 
   81126 /* Opcode: SoftNull P1 * * * *
   81127 ** Synopsis: r[P1]=NULL
   81128 **
   81129 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
   81130 ** instruction, but do not free any string or blob memory associated with
   81131 ** the register, so that if the value was a string or blob that was
   81132 ** previously copied using OP_SCopy, the copies will continue to be valid.
   81133 */
   81134 case OP_SoftNull: {
   81135   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
   81136   pOut = &aMem[pOp->p1];
   81137   pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
   81138   break;
   81139 }
   81140 
   81141 /* Opcode: Blob P1 P2 * P4 *
   81142 ** Synopsis: r[P2]=P4 (len=P1)
   81143 **
   81144 ** P4 points to a blob of data P1 bytes long.  Store this
   81145 ** blob in register P2.
   81146 */
   81147 case OP_Blob: {                /* out2 */
   81148   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   81149   pOut = out2Prerelease(p, pOp);
   81150   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
   81151   pOut->enc = encoding;
   81152   UPDATE_MAX_BLOBSIZE(pOut);
   81153   break;
   81154 }
   81155 
   81156 /* Opcode: Variable P1 P2 * P4 *
   81157 ** Synopsis: r[P2]=parameter(P1,P4)
   81158 **
   81159 ** Transfer the values of bound parameter P1 into register P2
   81160 **
   81161 ** If the parameter is named, then its name appears in P4.
   81162 ** The P4 value is used by sqlite3_bind_parameter_name().
   81163 */
   81164 case OP_Variable: {            /* out2 */
   81165   Mem *pVar;       /* Value being transferred */
   81166 
   81167   assert( pOp->p1>0 && pOp->p1<=p->nVar );
   81168   assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
   81169   pVar = &p->aVar[pOp->p1 - 1];
   81170   if( sqlite3VdbeMemTooBig(pVar) ){
   81171     goto too_big;
   81172   }
   81173   pOut = &aMem[pOp->p2];
   81174   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
   81175   UPDATE_MAX_BLOBSIZE(pOut);
   81176   break;
   81177 }
   81178 
   81179 /* Opcode: Move P1 P2 P3 * *
   81180 ** Synopsis: r[P2@P3]=r[P1@P3]
   81181 **
   81182 ** Move the P3 values in register P1..P1+P3-1 over into
   81183 ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
   81184 ** left holding a NULL.  It is an error for register ranges
   81185 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
   81186 ** for P3 to be less than 1.
   81187 */
   81188 case OP_Move: {
   81189   int n;           /* Number of registers left to copy */
   81190   int p1;          /* Register to copy from */
   81191   int p2;          /* Register to copy to */
   81192 
   81193   n = pOp->p3;
   81194   p1 = pOp->p1;
   81195   p2 = pOp->p2;
   81196   assert( n>0 && p1>0 && p2>0 );
   81197   assert( p1+n<=p2 || p2+n<=p1 );
   81198 
   81199   pIn1 = &aMem[p1];
   81200   pOut = &aMem[p2];
   81201   do{
   81202     assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
   81203     assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
   81204     assert( memIsValid(pIn1) );
   81205     memAboutToChange(p, pOut);
   81206     sqlite3VdbeMemMove(pOut, pIn1);
   81207 #ifdef SQLITE_DEBUG
   81208     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
   81209       pOut->pScopyFrom += pOp->p2 - p1;
   81210     }
   81211 #endif
   81212     Deephemeralize(pOut);
   81213     REGISTER_TRACE(p2++, pOut);
   81214     pIn1++;
   81215     pOut++;
   81216   }while( --n );
   81217   break;
   81218 }
   81219 
   81220 /* Opcode: Copy P1 P2 P3 * *
   81221 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
   81222 **
   81223 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
   81224 **
   81225 ** This instruction makes a deep copy of the value.  A duplicate
   81226 ** is made of any string or blob constant.  See also OP_SCopy.
   81227 */
   81228 case OP_Copy: {
   81229   int n;
   81230 
   81231   n = pOp->p3;
   81232   pIn1 = &aMem[pOp->p1];
   81233   pOut = &aMem[pOp->p2];
   81234   assert( pOut!=pIn1 );
   81235   while( 1 ){
   81236     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   81237     Deephemeralize(pOut);
   81238 #ifdef SQLITE_DEBUG
   81239     pOut->pScopyFrom = 0;
   81240 #endif
   81241     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
   81242     if( (n--)==0 ) break;
   81243     pOut++;
   81244     pIn1++;
   81245   }
   81246   break;
   81247 }
   81248 
   81249 /* Opcode: SCopy P1 P2 * * *
   81250 ** Synopsis: r[P2]=r[P1]
   81251 **
   81252 ** Make a shallow copy of register P1 into register P2.
   81253 **
   81254 ** This instruction makes a shallow copy of the value.  If the value
   81255 ** is a string or blob, then the copy is only a pointer to the
   81256 ** original and hence if the original changes so will the copy.
   81257 ** Worse, if the original is deallocated, the copy becomes invalid.
   81258 ** Thus the program must guarantee that the original will not change
   81259 ** during the lifetime of the copy.  Use OP_Copy to make a complete
   81260 ** copy.
   81261 */
   81262 case OP_SCopy: {            /* out2 */
   81263   pIn1 = &aMem[pOp->p1];
   81264   pOut = &aMem[pOp->p2];
   81265   assert( pOut!=pIn1 );
   81266   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   81267 #ifdef SQLITE_DEBUG
   81268   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
   81269 #endif
   81270   break;
   81271 }
   81272 
   81273 /* Opcode: IntCopy P1 P2 * * *
   81274 ** Synopsis: r[P2]=r[P1]
   81275 **
   81276 ** Transfer the integer value held in register P1 into register P2.
   81277 **
   81278 ** This is an optimized version of SCopy that works only for integer
   81279 ** values.
   81280 */
   81281 case OP_IntCopy: {            /* out2 */
   81282   pIn1 = &aMem[pOp->p1];
   81283   assert( (pIn1->flags & MEM_Int)!=0 );
   81284   pOut = &aMem[pOp->p2];
   81285   sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
   81286   break;
   81287 }
   81288 
   81289 /* Opcode: ResultRow P1 P2 * * *
   81290 ** Synopsis: output=r[P1@P2]
   81291 **
   81292 ** The registers P1 through P1+P2-1 contain a single row of
   81293 ** results. This opcode causes the sqlite3_step() call to terminate
   81294 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
   81295 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
   81296 ** the result row.
   81297 */
   81298 case OP_ResultRow: {
   81299   Mem *pMem;
   81300   int i;
   81301   assert( p->nResColumn==pOp->p2 );
   81302   assert( pOp->p1>0 );
   81303   assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
   81304 
   81305 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   81306   /* Run the progress counter just before returning.
   81307   */
   81308   if( db->xProgress!=0
   81309    && nVmStep>=nProgressLimit
   81310    && db->xProgress(db->pProgressArg)!=0
   81311   ){
   81312     rc = SQLITE_INTERRUPT;
   81313     goto abort_due_to_error;
   81314   }
   81315 #endif
   81316 
   81317   /* If this statement has violated immediate foreign key constraints, do
   81318   ** not return the number of rows modified. And do not RELEASE the statement
   81319   ** transaction. It needs to be rolled back.  */
   81320   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
   81321     assert( db->flags&SQLITE_CountRows );
   81322     assert( p->usesStmtJournal );
   81323     goto abort_due_to_error;
   81324   }
   81325 
   81326   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
   81327   ** DML statements invoke this opcode to return the number of rows
   81328   ** modified to the user. This is the only way that a VM that
   81329   ** opens a statement transaction may invoke this opcode.
   81330   **
   81331   ** In case this is such a statement, close any statement transaction
   81332   ** opened by this VM before returning control to the user. This is to
   81333   ** ensure that statement-transactions are always nested, not overlapping.
   81334   ** If the open statement-transaction is not closed here, then the user
   81335   ** may step another VM that opens its own statement transaction. This
   81336   ** may lead to overlapping statement transactions.
   81337   **
   81338   ** The statement transaction is never a top-level transaction.  Hence
   81339   ** the RELEASE call below can never fail.
   81340   */
   81341   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
   81342   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
   81343   assert( rc==SQLITE_OK );
   81344 
   81345   /* Invalidate all ephemeral cursor row caches */
   81346   p->cacheCtr = (p->cacheCtr + 2)|1;
   81347 
   81348   /* Make sure the results of the current row are \000 terminated
   81349   ** and have an assigned type.  The results are de-ephemeralized as
   81350   ** a side effect.
   81351   */
   81352   pMem = p->pResultSet = &aMem[pOp->p1];
   81353   for(i=0; i<pOp->p2; i++){
   81354     assert( memIsValid(&pMem[i]) );
   81355     Deephemeralize(&pMem[i]);
   81356     assert( (pMem[i].flags & MEM_Ephem)==0
   81357             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
   81358     sqlite3VdbeMemNulTerminate(&pMem[i]);
   81359     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
   81360   }
   81361   if( db->mallocFailed ) goto no_mem;
   81362 
   81363   if( db->mTrace & SQLITE_TRACE_ROW ){
   81364     db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
   81365   }
   81366 
   81367   /* Return SQLITE_ROW
   81368   */
   81369   p->pc = (int)(pOp - aOp) + 1;
   81370   rc = SQLITE_ROW;
   81371   goto vdbe_return;
   81372 }
   81373 
   81374 /* Opcode: Concat P1 P2 P3 * *
   81375 ** Synopsis: r[P3]=r[P2]+r[P1]
   81376 **
   81377 ** Add the text in register P1 onto the end of the text in
   81378 ** register P2 and store the result in register P3.
   81379 ** If either the P1 or P2 text are NULL then store NULL in P3.
   81380 **
   81381 **   P3 = P2 || P1
   81382 **
   81383 ** It is illegal for P1 and P3 to be the same register. Sometimes,
   81384 ** if P3 is the same register as P2, the implementation is able
   81385 ** to avoid a memcpy().
   81386 */
   81387 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   81388   i64 nByte;
   81389 
   81390   pIn1 = &aMem[pOp->p1];
   81391   pIn2 = &aMem[pOp->p2];
   81392   pOut = &aMem[pOp->p3];
   81393   assert( pIn1!=pOut );
   81394   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   81395     sqlite3VdbeMemSetNull(pOut);
   81396     break;
   81397   }
   81398   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
   81399   Stringify(pIn1, encoding);
   81400   Stringify(pIn2, encoding);
   81401   nByte = pIn1->n + pIn2->n;
   81402   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   81403     goto too_big;
   81404   }
   81405   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
   81406     goto no_mem;
   81407   }
   81408   MemSetTypeFlag(pOut, MEM_Str);
   81409   if( pOut!=pIn2 ){
   81410     memcpy(pOut->z, pIn2->z, pIn2->n);
   81411   }
   81412   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
   81413   pOut->z[nByte]=0;
   81414   pOut->z[nByte+1] = 0;
   81415   pOut->flags |= MEM_Term;
   81416   pOut->n = (int)nByte;
   81417   pOut->enc = encoding;
   81418   UPDATE_MAX_BLOBSIZE(pOut);
   81419   break;
   81420 }
   81421 
   81422 /* Opcode: Add P1 P2 P3 * *
   81423 ** Synopsis: r[P3]=r[P1]+r[P2]
   81424 **
   81425 ** Add the value in register P1 to the value in register P2
   81426 ** and store the result in register P3.
   81427 ** If either input is NULL, the result is NULL.
   81428 */
   81429 /* Opcode: Multiply P1 P2 P3 * *
   81430 ** Synopsis: r[P3]=r[P1]*r[P2]
   81431 **
   81432 **
   81433 ** Multiply the value in register P1 by the value in register P2
   81434 ** and store the result in register P3.
   81435 ** If either input is NULL, the result is NULL.
   81436 */
   81437 /* Opcode: Subtract P1 P2 P3 * *
   81438 ** Synopsis: r[P3]=r[P2]-r[P1]
   81439 **
   81440 ** Subtract the value in register P1 from the value in register P2
   81441 ** and store the result in register P3.
   81442 ** If either input is NULL, the result is NULL.
   81443 */
   81444 /* Opcode: Divide P1 P2 P3 * *
   81445 ** Synopsis: r[P3]=r[P2]/r[P1]
   81446 **
   81447 ** Divide the value in register P1 by the value in register P2
   81448 ** and store the result in register P3 (P3=P2/P1). If the value in
   81449 ** register P1 is zero, then the result is NULL. If either input is
   81450 ** NULL, the result is NULL.
   81451 */
   81452 /* Opcode: Remainder P1 P2 P3 * *
   81453 ** Synopsis: r[P3]=r[P2]%r[P1]
   81454 **
   81455 ** Compute the remainder after integer register P2 is divided by
   81456 ** register P1 and store the result in register P3.
   81457 ** If the value in register P1 is zero the result is NULL.
   81458 ** If either operand is NULL, the result is NULL.
   81459 */
   81460 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
   81461 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
   81462 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
   81463 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
   81464 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
   81465   char bIntint;   /* Started out as two integer operands */
   81466   u16 flags;      /* Combined MEM_* flags from both inputs */
   81467   u16 type1;      /* Numeric type of left operand */
   81468   u16 type2;      /* Numeric type of right operand */
   81469   i64 iA;         /* Integer value of left operand */
   81470   i64 iB;         /* Integer value of right operand */
   81471   double rA;      /* Real value of left operand */
   81472   double rB;      /* Real value of right operand */
   81473 
   81474   pIn1 = &aMem[pOp->p1];
   81475   type1 = numericType(pIn1);
   81476   pIn2 = &aMem[pOp->p2];
   81477   type2 = numericType(pIn2);
   81478   pOut = &aMem[pOp->p3];
   81479   flags = pIn1->flags | pIn2->flags;
   81480   if( (type1 & type2 & MEM_Int)!=0 ){
   81481     iA = pIn1->u.i;
   81482     iB = pIn2->u.i;
   81483     bIntint = 1;
   81484     switch( pOp->opcode ){
   81485       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
   81486       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
   81487       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
   81488       case OP_Divide: {
   81489         if( iA==0 ) goto arithmetic_result_is_null;
   81490         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
   81491         iB /= iA;
   81492         break;
   81493       }
   81494       default: {
   81495         if( iA==0 ) goto arithmetic_result_is_null;
   81496         if( iA==-1 ) iA = 1;
   81497         iB %= iA;
   81498         break;
   81499       }
   81500     }
   81501     pOut->u.i = iB;
   81502     MemSetTypeFlag(pOut, MEM_Int);
   81503   }else if( (flags & MEM_Null)!=0 ){
   81504     goto arithmetic_result_is_null;
   81505   }else{
   81506     bIntint = 0;
   81507 fp_math:
   81508     rA = sqlite3VdbeRealValue(pIn1);
   81509     rB = sqlite3VdbeRealValue(pIn2);
   81510     switch( pOp->opcode ){
   81511       case OP_Add:         rB += rA;       break;
   81512       case OP_Subtract:    rB -= rA;       break;
   81513       case OP_Multiply:    rB *= rA;       break;
   81514       case OP_Divide: {
   81515         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   81516         if( rA==(double)0 ) goto arithmetic_result_is_null;
   81517         rB /= rA;
   81518         break;
   81519       }
   81520       default: {
   81521         iA = (i64)rA;
   81522         iB = (i64)rB;
   81523         if( iA==0 ) goto arithmetic_result_is_null;
   81524         if( iA==-1 ) iA = 1;
   81525         rB = (double)(iB % iA);
   81526         break;
   81527       }
   81528     }
   81529 #ifdef SQLITE_OMIT_FLOATING_POINT
   81530     pOut->u.i = rB;
   81531     MemSetTypeFlag(pOut, MEM_Int);
   81532 #else
   81533     if( sqlite3IsNaN(rB) ){
   81534       goto arithmetic_result_is_null;
   81535     }
   81536     pOut->u.r = rB;
   81537     MemSetTypeFlag(pOut, MEM_Real);
   81538     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
   81539       sqlite3VdbeIntegerAffinity(pOut);
   81540     }
   81541 #endif
   81542   }
   81543   break;
   81544 
   81545 arithmetic_result_is_null:
   81546   sqlite3VdbeMemSetNull(pOut);
   81547   break;
   81548 }
   81549 
   81550 /* Opcode: CollSeq P1 * * P4
   81551 **
   81552 ** P4 is a pointer to a CollSeq object. If the next call to a user function
   81553 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
   81554 ** be returned. This is used by the built-in min(), max() and nullif()
   81555 ** functions.
   81556 **
   81557 ** If P1 is not zero, then it is a register that a subsequent min() or
   81558 ** max() aggregate will set to 1 if the current row is not the minimum or
   81559 ** maximum.  The P1 register is initialized to 0 by this instruction.
   81560 **
   81561 ** The interface used by the implementation of the aforementioned functions
   81562 ** to retrieve the collation sequence set by this opcode is not available
   81563 ** publicly.  Only built-in functions have access to this feature.
   81564 */
   81565 case OP_CollSeq: {
   81566   assert( pOp->p4type==P4_COLLSEQ );
   81567   if( pOp->p1 ){
   81568     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
   81569   }
   81570   break;
   81571 }
   81572 
   81573 /* Opcode: BitAnd P1 P2 P3 * *
   81574 ** Synopsis: r[P3]=r[P1]&r[P2]
   81575 **
   81576 ** Take the bit-wise AND of the values in register P1 and P2 and
   81577 ** store the result in register P3.
   81578 ** If either input is NULL, the result is NULL.
   81579 */
   81580 /* Opcode: BitOr P1 P2 P3 * *
   81581 ** Synopsis: r[P3]=r[P1]|r[P2]
   81582 **
   81583 ** Take the bit-wise OR of the values in register P1 and P2 and
   81584 ** store the result in register P3.
   81585 ** If either input is NULL, the result is NULL.
   81586 */
   81587 /* Opcode: ShiftLeft P1 P2 P3 * *
   81588 ** Synopsis: r[P3]=r[P2]<<r[P1]
   81589 **
   81590 ** Shift the integer value in register P2 to the left by the
   81591 ** number of bits specified by the integer in register P1.
   81592 ** Store the result in register P3.
   81593 ** If either input is NULL, the result is NULL.
   81594 */
   81595 /* Opcode: ShiftRight P1 P2 P3 * *
   81596 ** Synopsis: r[P3]=r[P2]>>r[P1]
   81597 **
   81598 ** Shift the integer value in register P2 to the right by the
   81599 ** number of bits specified by the integer in register P1.
   81600 ** Store the result in register P3.
   81601 ** If either input is NULL, the result is NULL.
   81602 */
   81603 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
   81604 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
   81605 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
   81606 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
   81607   i64 iA;
   81608   u64 uA;
   81609   i64 iB;
   81610   u8 op;
   81611 
   81612   pIn1 = &aMem[pOp->p1];
   81613   pIn2 = &aMem[pOp->p2];
   81614   pOut = &aMem[pOp->p3];
   81615   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   81616     sqlite3VdbeMemSetNull(pOut);
   81617     break;
   81618   }
   81619   iA = sqlite3VdbeIntValue(pIn2);
   81620   iB = sqlite3VdbeIntValue(pIn1);
   81621   op = pOp->opcode;
   81622   if( op==OP_BitAnd ){
   81623     iA &= iB;
   81624   }else if( op==OP_BitOr ){
   81625     iA |= iB;
   81626   }else if( iB!=0 ){
   81627     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
   81628 
   81629     /* If shifting by a negative amount, shift in the other direction */
   81630     if( iB<0 ){
   81631       assert( OP_ShiftRight==OP_ShiftLeft+1 );
   81632       op = 2*OP_ShiftLeft + 1 - op;
   81633       iB = iB>(-64) ? -iB : 64;
   81634     }
   81635 
   81636     if( iB>=64 ){
   81637       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
   81638     }else{
   81639       memcpy(&uA, &iA, sizeof(uA));
   81640       if( op==OP_ShiftLeft ){
   81641         uA <<= iB;
   81642       }else{
   81643         uA >>= iB;
   81644         /* Sign-extend on a right shift of a negative number */
   81645         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
   81646       }
   81647       memcpy(&iA, &uA, sizeof(iA));
   81648     }
   81649   }
   81650   pOut->u.i = iA;
   81651   MemSetTypeFlag(pOut, MEM_Int);
   81652   break;
   81653 }
   81654 
   81655 /* Opcode: AddImm  P1 P2 * * *
   81656 ** Synopsis: r[P1]=r[P1]+P2
   81657 **
   81658 ** Add the constant P2 to the value in register P1.
   81659 ** The result is always an integer.
   81660 **
   81661 ** To force any register to be an integer, just add 0.
   81662 */
   81663 case OP_AddImm: {            /* in1 */
   81664   pIn1 = &aMem[pOp->p1];
   81665   memAboutToChange(p, pIn1);
   81666   sqlite3VdbeMemIntegerify(pIn1);
   81667   pIn1->u.i += pOp->p2;
   81668   break;
   81669 }
   81670 
   81671 /* Opcode: MustBeInt P1 P2 * * *
   81672 **
   81673 ** Force the value in register P1 to be an integer.  If the value
   81674 ** in P1 is not an integer and cannot be converted into an integer
   81675 ** without data loss, then jump immediately to P2, or if P2==0
   81676 ** raise an SQLITE_MISMATCH exception.
   81677 */
   81678 case OP_MustBeInt: {            /* jump, in1 */
   81679   pIn1 = &aMem[pOp->p1];
   81680   if( (pIn1->flags & MEM_Int)==0 ){
   81681     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
   81682     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
   81683     if( (pIn1->flags & MEM_Int)==0 ){
   81684       if( pOp->p2==0 ){
   81685         rc = SQLITE_MISMATCH;
   81686         goto abort_due_to_error;
   81687       }else{
   81688         goto jump_to_p2;
   81689       }
   81690     }
   81691   }
   81692   MemSetTypeFlag(pIn1, MEM_Int);
   81693   break;
   81694 }
   81695 
   81696 #ifndef SQLITE_OMIT_FLOATING_POINT
   81697 /* Opcode: RealAffinity P1 * * * *
   81698 **
   81699 ** If register P1 holds an integer convert it to a real value.
   81700 **
   81701 ** This opcode is used when extracting information from a column that
   81702 ** has REAL affinity.  Such column values may still be stored as
   81703 ** integers, for space efficiency, but after extraction we want them
   81704 ** to have only a real value.
   81705 */
   81706 case OP_RealAffinity: {                  /* in1 */
   81707   pIn1 = &aMem[pOp->p1];
   81708   if( pIn1->flags & MEM_Int ){
   81709     sqlite3VdbeMemRealify(pIn1);
   81710   }
   81711   break;
   81712 }
   81713 #endif
   81714 
   81715 #ifndef SQLITE_OMIT_CAST
   81716 /* Opcode: Cast P1 P2 * * *
   81717 ** Synopsis: affinity(r[P1])
   81718 **
   81719 ** Force the value in register P1 to be the type defined by P2.
   81720 **
   81721 ** <ul>
   81722 ** <li> P2=='A' &rarr; BLOB
   81723 ** <li> P2=='B' &rarr; TEXT
   81724 ** <li> P2=='C' &rarr; NUMERIC
   81725 ** <li> P2=='D' &rarr; INTEGER
   81726 ** <li> P2=='E' &rarr; REAL
   81727 ** </ul>
   81728 **
   81729 ** A NULL value is not changed by this routine.  It remains NULL.
   81730 */
   81731 case OP_Cast: {                  /* in1 */
   81732   assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
   81733   testcase( pOp->p2==SQLITE_AFF_TEXT );
   81734   testcase( pOp->p2==SQLITE_AFF_BLOB );
   81735   testcase( pOp->p2==SQLITE_AFF_NUMERIC );
   81736   testcase( pOp->p2==SQLITE_AFF_INTEGER );
   81737   testcase( pOp->p2==SQLITE_AFF_REAL );
   81738   pIn1 = &aMem[pOp->p1];
   81739   memAboutToChange(p, pIn1);
   81740   rc = ExpandBlob(pIn1);
   81741   sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
   81742   UPDATE_MAX_BLOBSIZE(pIn1);
   81743   if( rc ) goto abort_due_to_error;
   81744   break;
   81745 }
   81746 #endif /* SQLITE_OMIT_CAST */
   81747 
   81748 /* Opcode: Eq P1 P2 P3 P4 P5
   81749 ** Synopsis: IF r[P3]==r[P1]
   81750 **
   81751 ** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
   81752 ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then
   81753 ** store the result of comparison in register P2.
   81754 **
   81755 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   81756 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   81757 ** to coerce both inputs according to this affinity before the
   81758 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   81759 ** affinity is used. Note that the affinity conversions are stored
   81760 ** back into the input registers P1 and P3.  So this opcode can cause
   81761 ** persistent changes to registers P1 and P3.
   81762 **
   81763 ** Once any conversions have taken place, and neither value is NULL,
   81764 ** the values are compared. If both values are blobs then memcmp() is
   81765 ** used to determine the results of the comparison.  If both values
   81766 ** are text, then the appropriate collating function specified in
   81767 ** P4 is used to do the comparison.  If P4 is not specified then
   81768 ** memcmp() is used to compare text string.  If both values are
   81769 ** numeric, then a numeric comparison is used. If the two values
   81770 ** are of different types, then numbers are considered less than
   81771 ** strings and strings are considered less than blobs.
   81772 **
   81773 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   81774 ** true or false and is never NULL.  If both operands are NULL then the result
   81775 ** of comparison is true.  If either operand is NULL then the result is false.
   81776 ** If neither operand is NULL the result is the same as it would be if
   81777 ** the SQLITE_NULLEQ flag were omitted from P5.
   81778 **
   81779 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
   81780 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
   81781 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
   81782 */
   81783 /* Opcode: Ne P1 P2 P3 P4 P5
   81784 ** Synopsis: IF r[P3]!=r[P1]
   81785 **
   81786 ** This works just like the Eq opcode except that the jump is taken if
   81787 ** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
   81788 ** additional information.
   81789 **
   81790 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
   81791 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
   81792 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
   81793 */
   81794 /* Opcode: Lt P1 P2 P3 P4 P5
   81795 ** Synopsis: IF r[P3]<r[P1]
   81796 **
   81797 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
   81798 ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store
   81799 ** the result of comparison (0 or 1 or NULL) into register P2.
   81800 **
   81801 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
   81802 ** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL
   81803 ** bit is clear then fall through if either operand is NULL.
   81804 **
   81805 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   81806 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   81807 ** to coerce both inputs according to this affinity before the
   81808 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   81809 ** affinity is used. Note that the affinity conversions are stored
   81810 ** back into the input registers P1 and P3.  So this opcode can cause
   81811 ** persistent changes to registers P1 and P3.
   81812 **
   81813 ** Once any conversions have taken place, and neither value is NULL,
   81814 ** the values are compared. If both values are blobs then memcmp() is
   81815 ** used to determine the results of the comparison.  If both values
   81816 ** are text, then the appropriate collating function specified in
   81817 ** P4 is  used to do the comparison.  If P4 is not specified then
   81818 ** memcmp() is used to compare text string.  If both values are
   81819 ** numeric, then a numeric comparison is used. If the two values
   81820 ** are of different types, then numbers are considered less than
   81821 ** strings and strings are considered less than blobs.
   81822 */
   81823 /* Opcode: Le P1 P2 P3 P4 P5
   81824 ** Synopsis: IF r[P3]<=r[P1]
   81825 **
   81826 ** This works just like the Lt opcode except that the jump is taken if
   81827 ** the content of register P3 is less than or equal to the content of
   81828 ** register P1.  See the Lt opcode for additional information.
   81829 */
   81830 /* Opcode: Gt P1 P2 P3 P4 P5
   81831 ** Synopsis: IF r[P3]>r[P1]
   81832 **
   81833 ** This works just like the Lt opcode except that the jump is taken if
   81834 ** the content of register P3 is greater than the content of
   81835 ** register P1.  See the Lt opcode for additional information.
   81836 */
   81837 /* Opcode: Ge P1 P2 P3 P4 P5
   81838 ** Synopsis: IF r[P3]>=r[P1]
   81839 **
   81840 ** This works just like the Lt opcode except that the jump is taken if
   81841 ** the content of register P3 is greater than or equal to the content of
   81842 ** register P1.  See the Lt opcode for additional information.
   81843 */
   81844 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
   81845 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
   81846 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
   81847 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
   81848 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
   81849 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   81850   int res, res2;      /* Result of the comparison of pIn1 against pIn3 */
   81851   char affinity;      /* Affinity to use for comparison */
   81852   u16 flags1;         /* Copy of initial value of pIn1->flags */
   81853   u16 flags3;         /* Copy of initial value of pIn3->flags */
   81854 
   81855   pIn1 = &aMem[pOp->p1];
   81856   pIn3 = &aMem[pOp->p3];
   81857   flags1 = pIn1->flags;
   81858   flags3 = pIn3->flags;
   81859   if( (flags1 | flags3)&MEM_Null ){
   81860     /* One or both operands are NULL */
   81861     if( pOp->p5 & SQLITE_NULLEQ ){
   81862       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
   81863       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
   81864       ** or not both operands are null.
   81865       */
   81866       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
   81867       assert( (flags1 & MEM_Cleared)==0 );
   81868       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
   81869       if( (flags1&flags3&MEM_Null)!=0
   81870        && (flags3&MEM_Cleared)==0
   81871       ){
   81872         res = 0;  /* Operands are equal */
   81873       }else{
   81874         res = 1;  /* Operands are not equal */
   81875       }
   81876     }else{
   81877       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
   81878       ** then the result is always NULL.
   81879       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
   81880       */
   81881       if( pOp->p5 & SQLITE_STOREP2 ){
   81882         pOut = &aMem[pOp->p2];
   81883         iCompare = 1;    /* Operands are not equal */
   81884         memAboutToChange(p, pOut);
   81885         MemSetTypeFlag(pOut, MEM_Null);
   81886         REGISTER_TRACE(pOp->p2, pOut);
   81887       }else{
   81888         VdbeBranchTaken(2,3);
   81889         if( pOp->p5 & SQLITE_JUMPIFNULL ){
   81890           goto jump_to_p2;
   81891         }
   81892       }
   81893       break;
   81894     }
   81895   }else{
   81896     /* Neither operand is NULL.  Do a comparison. */
   81897     affinity = pOp->p5 & SQLITE_AFF_MASK;
   81898     if( affinity>=SQLITE_AFF_NUMERIC ){
   81899       if( (flags1 | flags3)&MEM_Str ){
   81900         if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
   81901           applyNumericAffinity(pIn1,0);
   81902           testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
   81903           flags3 = pIn3->flags;
   81904         }
   81905         if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
   81906           applyNumericAffinity(pIn3,0);
   81907         }
   81908       }
   81909       /* Handle the common case of integer comparison here, as an
   81910       ** optimization, to avoid a call to sqlite3MemCompare() */
   81911       if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
   81912         if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
   81913         if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
   81914         res = 0;
   81915         goto compare_op;
   81916       }
   81917     }else if( affinity==SQLITE_AFF_TEXT ){
   81918       if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
   81919         testcase( pIn1->flags & MEM_Int );
   81920         testcase( pIn1->flags & MEM_Real );
   81921         sqlite3VdbeMemStringify(pIn1, encoding, 1);
   81922         testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
   81923         flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
   81924         assert( pIn1!=pIn3 );
   81925       }
   81926       if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
   81927         testcase( pIn3->flags & MEM_Int );
   81928         testcase( pIn3->flags & MEM_Real );
   81929         sqlite3VdbeMemStringify(pIn3, encoding, 1);
   81930         testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
   81931         flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
   81932       }
   81933     }
   81934     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
   81935     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   81936   }
   81937 compare_op:
   81938   /* At this point, res is negative, zero, or positive if reg[P1] is
   81939   ** less than, equal to, or greater than reg[P3], respectively.  Compute
   81940   ** the answer to this operator in res2, depending on what the comparison
   81941   ** operator actually is.  The next block of code depends on the fact
   81942   ** that the 6 comparison operators are consecutive integers in this
   81943   ** order:  NE, EQ, GT, LE, LT, GE */
   81944   assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
   81945   assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
   81946   if( res<0 ){                        /* ne, eq, gt, le, lt, ge */
   81947     static const unsigned char aLTb[] = { 1,  0,  0,  1,  1,  0 };
   81948     res2 = aLTb[pOp->opcode - OP_Ne];
   81949   }else if( res==0 ){
   81950     static const unsigned char aEQb[] = { 0,  1,  0,  1,  0,  1 };
   81951     res2 = aEQb[pOp->opcode - OP_Ne];
   81952   }else{
   81953     static const unsigned char aGTb[] = { 1,  0,  1,  0,  0,  1 };
   81954     res2 = aGTb[pOp->opcode - OP_Ne];
   81955   }
   81956 
   81957   /* Undo any changes made by applyAffinity() to the input registers. */
   81958   assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
   81959   pIn1->flags = flags1;
   81960   assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
   81961   pIn3->flags = flags3;
   81962 
   81963   if( pOp->p5 & SQLITE_STOREP2 ){
   81964     pOut = &aMem[pOp->p2];
   81965     iCompare = res;
   81966     if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
   81967       /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
   81968       ** and prevents OP_Ne from overwriting NULL with 0.  This flag
   81969       ** is only used in contexts where either:
   81970       **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
   81971       **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
   81972       ** Therefore it is not necessary to check the content of r[P2] for
   81973       ** NULL. */
   81974       assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
   81975       assert( res2==0 || res2==1 );
   81976       testcase( res2==0 && pOp->opcode==OP_Eq );
   81977       testcase( res2==1 && pOp->opcode==OP_Eq );
   81978       testcase( res2==0 && pOp->opcode==OP_Ne );
   81979       testcase( res2==1 && pOp->opcode==OP_Ne );
   81980       if( (pOp->opcode==OP_Eq)==res2 ) break;
   81981     }
   81982     memAboutToChange(p, pOut);
   81983     MemSetTypeFlag(pOut, MEM_Int);
   81984     pOut->u.i = res2;
   81985     REGISTER_TRACE(pOp->p2, pOut);
   81986   }else{
   81987     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
   81988     if( res2 ){
   81989       goto jump_to_p2;
   81990     }
   81991   }
   81992   break;
   81993 }
   81994 
   81995 /* Opcode: ElseNotEq * P2 * * *
   81996 **
   81997 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
   81998 ** If result of an OP_Eq comparison on the same two operands
   81999 ** would have be NULL or false (0), then then jump to P2.
   82000 ** If the result of an OP_Eq comparison on the two previous operands
   82001 ** would have been true (1), then fall through.
   82002 */
   82003 case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
   82004   assert( pOp>aOp );
   82005   assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
   82006   assert( pOp[-1].p5 & SQLITE_STOREP2 );
   82007   VdbeBranchTaken(iCompare!=0, 2);
   82008   if( iCompare!=0 ) goto jump_to_p2;
   82009   break;
   82010 }
   82011 
   82012 
   82013 /* Opcode: Permutation * * * P4 *
   82014 **
   82015 ** Set the permutation used by the OP_Compare operator in the next
   82016 ** instruction.  The permutation is stored in the P4 operand.
   82017 **
   82018 ** The permutation is only valid until the next OP_Compare that has
   82019 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
   82020 ** occur immediately prior to the OP_Compare.
   82021 **
   82022 ** The first integer in the P4 integer array is the length of the array
   82023 ** and does not become part of the permutation.
   82024 */
   82025 case OP_Permutation: {
   82026   assert( pOp->p4type==P4_INTARRAY );
   82027   assert( pOp->p4.ai );
   82028   assert( pOp[1].opcode==OP_Compare );
   82029   assert( pOp[1].p5 & OPFLAG_PERMUTE );
   82030   break;
   82031 }
   82032 
   82033 /* Opcode: Compare P1 P2 P3 P4 P5
   82034 ** Synopsis: r[P1@P3] <-> r[P2@P3]
   82035 **
   82036 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
   82037 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
   82038 ** the comparison for use by the next OP_Jump instruct.
   82039 **
   82040 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
   82041 ** determined by the most recent OP_Permutation operator.  If the
   82042 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
   82043 ** order.
   82044 **
   82045 ** P4 is a KeyInfo structure that defines collating sequences and sort
   82046 ** orders for the comparison.  The permutation applies to registers
   82047 ** only.  The KeyInfo elements are used sequentially.
   82048 **
   82049 ** The comparison is a sort comparison, so NULLs compare equal,
   82050 ** NULLs are less than numbers, numbers are less than strings,
   82051 ** and strings are less than blobs.
   82052 */
   82053 case OP_Compare: {
   82054   int n;
   82055   int i;
   82056   int p1;
   82057   int p2;
   82058   const KeyInfo *pKeyInfo;
   82059   int idx;
   82060   CollSeq *pColl;    /* Collating sequence to use on this term */
   82061   int bRev;          /* True for DESCENDING sort order */
   82062   int *aPermute;     /* The permutation */
   82063 
   82064   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
   82065     aPermute = 0;
   82066   }else{
   82067     assert( pOp>aOp );
   82068     assert( pOp[-1].opcode==OP_Permutation );
   82069     assert( pOp[-1].p4type==P4_INTARRAY );
   82070     aPermute = pOp[-1].p4.ai + 1;
   82071     assert( aPermute!=0 );
   82072   }
   82073   n = pOp->p3;
   82074   pKeyInfo = pOp->p4.pKeyInfo;
   82075   assert( n>0 );
   82076   assert( pKeyInfo!=0 );
   82077   p1 = pOp->p1;
   82078   p2 = pOp->p2;
   82079 #ifdef SQLITE_DEBUG
   82080   if( aPermute ){
   82081     int k, mx = 0;
   82082     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
   82083     assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
   82084     assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
   82085   }else{
   82086     assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
   82087     assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
   82088   }
   82089 #endif /* SQLITE_DEBUG */
   82090   for(i=0; i<n; i++){
   82091     idx = aPermute ? aPermute[i] : i;
   82092     assert( memIsValid(&aMem[p1+idx]) );
   82093     assert( memIsValid(&aMem[p2+idx]) );
   82094     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
   82095     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
   82096     assert( i<pKeyInfo->nKeyField );
   82097     pColl = pKeyInfo->aColl[i];
   82098     bRev = pKeyInfo->aSortOrder[i];
   82099     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
   82100     if( iCompare ){
   82101       if( bRev ) iCompare = -iCompare;
   82102       break;
   82103     }
   82104   }
   82105   break;
   82106 }
   82107 
   82108 /* Opcode: Jump P1 P2 P3 * *
   82109 **
   82110 ** Jump to the instruction at address P1, P2, or P3 depending on whether
   82111 ** in the most recent OP_Compare instruction the P1 vector was less than
   82112 ** equal to, or greater than the P2 vector, respectively.
   82113 */
   82114 case OP_Jump: {             /* jump */
   82115   if( iCompare<0 ){
   82116     VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
   82117   }else if( iCompare==0 ){
   82118     VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
   82119   }else{
   82120     VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
   82121   }
   82122   break;
   82123 }
   82124 
   82125 /* Opcode: And P1 P2 P3 * *
   82126 ** Synopsis: r[P3]=(r[P1] && r[P2])
   82127 **
   82128 ** Take the logical AND of the values in registers P1 and P2 and
   82129 ** write the result into register P3.
   82130 **
   82131 ** If either P1 or P2 is 0 (false) then the result is 0 even if
   82132 ** the other input is NULL.  A NULL and true or two NULLs give
   82133 ** a NULL output.
   82134 */
   82135 /* Opcode: Or P1 P2 P3 * *
   82136 ** Synopsis: r[P3]=(r[P1] || r[P2])
   82137 **
   82138 ** Take the logical OR of the values in register P1 and P2 and
   82139 ** store the answer in register P3.
   82140 **
   82141 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
   82142 ** even if the other input is NULL.  A NULL and false or two NULLs
   82143 ** give a NULL output.
   82144 */
   82145 case OP_And:              /* same as TK_AND, in1, in2, out3 */
   82146 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
   82147   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   82148   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   82149 
   82150   pIn1 = &aMem[pOp->p1];
   82151   if( pIn1->flags & MEM_Null ){
   82152     v1 = 2;
   82153   }else{
   82154     v1 = sqlite3VdbeIntValue(pIn1)!=0;
   82155   }
   82156   pIn2 = &aMem[pOp->p2];
   82157   if( pIn2->flags & MEM_Null ){
   82158     v2 = 2;
   82159   }else{
   82160     v2 = sqlite3VdbeIntValue(pIn2)!=0;
   82161   }
   82162   if( pOp->opcode==OP_And ){
   82163     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
   82164     v1 = and_logic[v1*3+v2];
   82165   }else{
   82166     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
   82167     v1 = or_logic[v1*3+v2];
   82168   }
   82169   pOut = &aMem[pOp->p3];
   82170   if( v1==2 ){
   82171     MemSetTypeFlag(pOut, MEM_Null);
   82172   }else{
   82173     pOut->u.i = v1;
   82174     MemSetTypeFlag(pOut, MEM_Int);
   82175   }
   82176   break;
   82177 }
   82178 
   82179 /* Opcode: Not P1 P2 * * *
   82180 ** Synopsis: r[P2]= !r[P1]
   82181 **
   82182 ** Interpret the value in register P1 as a boolean value.  Store the
   82183 ** boolean complement in register P2.  If the value in register P1 is
   82184 ** NULL, then a NULL is stored in P2.
   82185 */
   82186 case OP_Not: {                /* same as TK_NOT, in1, out2 */
   82187   pIn1 = &aMem[pOp->p1];
   82188   pOut = &aMem[pOp->p2];
   82189   sqlite3VdbeMemSetNull(pOut);
   82190   if( (pIn1->flags & MEM_Null)==0 ){
   82191     pOut->flags = MEM_Int;
   82192     pOut->u.i = !sqlite3VdbeIntValue(pIn1);
   82193   }
   82194   break;
   82195 }
   82196 
   82197 /* Opcode: BitNot P1 P2 * * *
   82198 ** Synopsis: r[P1]= ~r[P1]
   82199 **
   82200 ** Interpret the content of register P1 as an integer.  Store the
   82201 ** ones-complement of the P1 value into register P2.  If P1 holds
   82202 ** a NULL then store a NULL in P2.
   82203 */
   82204 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
   82205   pIn1 = &aMem[pOp->p1];
   82206   pOut = &aMem[pOp->p2];
   82207   sqlite3VdbeMemSetNull(pOut);
   82208   if( (pIn1->flags & MEM_Null)==0 ){
   82209     pOut->flags = MEM_Int;
   82210     pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
   82211   }
   82212   break;
   82213 }
   82214 
   82215 /* Opcode: Once P1 P2 * * *
   82216 **
   82217 ** Fall through to the next instruction the first time this opcode is
   82218 ** encountered on each invocation of the byte-code program.  Jump to P2
   82219 ** on the second and all subsequent encounters during the same invocation.
   82220 **
   82221 ** Top-level programs determine first invocation by comparing the P1
   82222 ** operand against the P1 operand on the OP_Init opcode at the beginning
   82223 ** of the program.  If the P1 values differ, then fall through and make
   82224 ** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are
   82225 ** the same then take the jump.
   82226 **
   82227 ** For subprograms, there is a bitmask in the VdbeFrame that determines
   82228 ** whether or not the jump should be taken.  The bitmask is necessary
   82229 ** because the self-altering code trick does not work for recursive
   82230 ** triggers.
   82231 */
   82232 case OP_Once: {             /* jump */
   82233   u32 iAddr;                /* Address of this instruction */
   82234   assert( p->aOp[0].opcode==OP_Init );
   82235   if( p->pFrame ){
   82236     iAddr = (int)(pOp - p->aOp);
   82237     if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
   82238       VdbeBranchTaken(1, 2);
   82239       goto jump_to_p2;
   82240     }
   82241     p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
   82242   }else{
   82243     if( p->aOp[0].p1==pOp->p1 ){
   82244       VdbeBranchTaken(1, 2);
   82245       goto jump_to_p2;
   82246     }
   82247   }
   82248   VdbeBranchTaken(0, 2);
   82249   pOp->p1 = p->aOp[0].p1;
   82250   break;
   82251 }
   82252 
   82253 /* Opcode: If P1 P2 P3 * *
   82254 **
   82255 ** Jump to P2 if the value in register P1 is true.  The value
   82256 ** is considered true if it is numeric and non-zero.  If the value
   82257 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
   82258 */
   82259 /* Opcode: IfNot P1 P2 P3 * *
   82260 **
   82261 ** Jump to P2 if the value in register P1 is False.  The value
   82262 ** is considered false if it has a numeric value of zero.  If the value
   82263 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
   82264 */
   82265 case OP_If:                 /* jump, in1 */
   82266 case OP_IfNot: {            /* jump, in1 */
   82267   int c;
   82268   pIn1 = &aMem[pOp->p1];
   82269   if( pIn1->flags & MEM_Null ){
   82270     c = pOp->p3;
   82271   }else{
   82272 #ifdef SQLITE_OMIT_FLOATING_POINT
   82273     c = sqlite3VdbeIntValue(pIn1)!=0;
   82274 #else
   82275     c = sqlite3VdbeRealValue(pIn1)!=0.0;
   82276 #endif
   82277     if( pOp->opcode==OP_IfNot ) c = !c;
   82278   }
   82279   VdbeBranchTaken(c!=0, 2);
   82280   if( c ){
   82281     goto jump_to_p2;
   82282   }
   82283   break;
   82284 }
   82285 
   82286 /* Opcode: IsNull P1 P2 * * *
   82287 ** Synopsis: if r[P1]==NULL goto P2
   82288 **
   82289 ** Jump to P2 if the value in register P1 is NULL.
   82290 */
   82291 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   82292   pIn1 = &aMem[pOp->p1];
   82293   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
   82294   if( (pIn1->flags & MEM_Null)!=0 ){
   82295     goto jump_to_p2;
   82296   }
   82297   break;
   82298 }
   82299 
   82300 /* Opcode: NotNull P1 P2 * * *
   82301 ** Synopsis: if r[P1]!=NULL goto P2
   82302 **
   82303 ** Jump to P2 if the value in register P1 is not NULL.
   82304 */
   82305 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   82306   pIn1 = &aMem[pOp->p1];
   82307   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
   82308   if( (pIn1->flags & MEM_Null)==0 ){
   82309     goto jump_to_p2;
   82310   }
   82311   break;
   82312 }
   82313 
   82314 /* Opcode: IfNullRow P1 P2 P3 * *
   82315 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
   82316 **
   82317 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
   82318 ** If it is, then set register P3 to NULL and jump immediately to P2.
   82319 ** If P1 is not on a NULL row, then fall through without making any
   82320 ** changes.
   82321 */
   82322 case OP_IfNullRow: {         /* jump */
   82323   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   82324   assert( p->apCsr[pOp->p1]!=0 );
   82325   if( p->apCsr[pOp->p1]->nullRow ){
   82326     sqlite3VdbeMemSetNull(aMem + pOp->p3);
   82327     goto jump_to_p2;
   82328   }
   82329   break;
   82330 }
   82331 
   82332 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
   82333 /* Opcode: Offset P1 P2 P3 * *
   82334 ** Synopsis: r[P3] = sqlite_offset(P1)
   82335 **
   82336 ** Store in register r[P3] the byte offset into the database file that is the
   82337 ** start of the payload for the record at which that cursor P1 is currently
   82338 ** pointing.
   82339 **
   82340 ** P2 is the column number for the argument to the sqlite_offset() function.
   82341 ** This opcode does not use P2 itself, but the P2 value is used by the
   82342 ** code generator.  The P1, P2, and P3 operands to this opcode are the
   82343 ** as as for OP_Column.
   82344 **
   82345 ** This opcode is only available if SQLite is compiled with the
   82346 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
   82347 */
   82348 case OP_Offset: {          /* out3 */
   82349   VdbeCursor *pC;    /* The VDBE cursor */
   82350   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   82351   pC = p->apCsr[pOp->p1];
   82352   pOut = &p->aMem[pOp->p3];
   82353   if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
   82354     sqlite3VdbeMemSetNull(pOut);
   82355   }else{
   82356     sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
   82357   }
   82358   break;
   82359 }
   82360 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
   82361 
   82362 /* Opcode: Column P1 P2 P3 P4 P5
   82363 ** Synopsis: r[P3]=PX
   82364 **
   82365 ** Interpret the data that cursor P1 points to as a structure built using
   82366 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
   82367 ** information about the format of the data.)  Extract the P2-th column
   82368 ** from this record.  If there are less that (P2+1)
   82369 ** values in the record, extract a NULL.
   82370 **
   82371 ** The value extracted is stored in register P3.
   82372 **
   82373 ** If the record contains fewer than P2 fields, then extract a NULL.  Or,
   82374 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
   82375 ** the result.
   82376 **
   82377 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
   82378 ** then the cache of the cursor is reset prior to extracting the column.
   82379 ** The first OP_Column against a pseudo-table after the value of the content
   82380 ** register has changed should have this bit set.
   82381 **
   82382 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
   82383 ** the result is guaranteed to only be used as the argument of a length()
   82384 ** or typeof() function, respectively.  The loading of large blobs can be
   82385 ** skipped for length() and all content loading can be skipped for typeof().
   82386 */
   82387 case OP_Column: {
   82388   int p2;            /* column number to retrieve */
   82389   VdbeCursor *pC;    /* The VDBE cursor */
   82390   BtCursor *pCrsr;   /* The BTree cursor */
   82391   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   82392   int len;           /* The length of the serialized data for the column */
   82393   int i;             /* Loop counter */
   82394   Mem *pDest;        /* Where to write the extracted value */
   82395   Mem sMem;          /* For storing the record being decoded */
   82396   const u8 *zData;   /* Part of the record being decoded */
   82397   const u8 *zHdr;    /* Next unparsed byte of the header */
   82398   const u8 *zEndHdr; /* Pointer to first byte after the header */
   82399   u64 offset64;      /* 64-bit offset */
   82400   u32 t;             /* A type code from the record header */
   82401   Mem *pReg;         /* PseudoTable input register */
   82402 
   82403   pC = p->apCsr[pOp->p1];
   82404   p2 = pOp->p2;
   82405 
   82406   /* If the cursor cache is stale (meaning it is not currently point at
   82407   ** the correct row) then bring it up-to-date by doing the necessary
   82408   ** B-Tree seek. */
   82409   rc = sqlite3VdbeCursorMoveto(&pC, &p2);
   82410   if( rc ) goto abort_due_to_error;
   82411 
   82412   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   82413   pDest = &aMem[pOp->p3];
   82414   memAboutToChange(p, pDest);
   82415   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   82416   assert( pC!=0 );
   82417   assert( p2<pC->nField );
   82418   aOffset = pC->aOffset;
   82419   assert( pC->eCurType!=CURTYPE_VTAB );
   82420   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
   82421   assert( pC->eCurType!=CURTYPE_SORTER );
   82422 
   82423   if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
   82424     if( pC->nullRow ){
   82425       if( pC->eCurType==CURTYPE_PSEUDO ){
   82426         /* For the special case of as pseudo-cursor, the seekResult field
   82427         ** identifies the register that holds the record */
   82428         assert( pC->seekResult>0 );
   82429         pReg = &aMem[pC->seekResult];
   82430         assert( pReg->flags & MEM_Blob );
   82431         assert( memIsValid(pReg) );
   82432         pC->payloadSize = pC->szRow = pReg->n;
   82433         pC->aRow = (u8*)pReg->z;
   82434       }else{
   82435         sqlite3VdbeMemSetNull(pDest);
   82436         goto op_column_out;
   82437       }
   82438     }else{
   82439       pCrsr = pC->uc.pCursor;
   82440       assert( pC->eCurType==CURTYPE_BTREE );
   82441       assert( pCrsr );
   82442       assert( sqlite3BtreeCursorIsValid(pCrsr) );
   82443       pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
   82444       pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
   82445       assert( pC->szRow<=pC->payloadSize );
   82446       assert( pC->szRow<=65536 );  /* Maximum page size is 64KiB */
   82447       if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   82448         goto too_big;
   82449       }
   82450     }
   82451     pC->cacheStatus = p->cacheCtr;
   82452     pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
   82453     pC->nHdrParsed = 0;
   82454 
   82455 
   82456     if( pC->szRow<aOffset[0] ){      /*OPTIMIZATION-IF-FALSE*/
   82457       /* pC->aRow does not have to hold the entire row, but it does at least
   82458       ** need to cover the header of the record.  If pC->aRow does not contain
   82459       ** the complete header, then set it to zero, forcing the header to be
   82460       ** dynamically allocated. */
   82461       pC->aRow = 0;
   82462       pC->szRow = 0;
   82463 
   82464       /* Make sure a corrupt database has not given us an oversize header.
   82465       ** Do this now to avoid an oversize memory allocation.
   82466       **
   82467       ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
   82468       ** types use so much data space that there can only be 4096 and 32 of
   82469       ** them, respectively.  So the maximum header length results from a
   82470       ** 3-byte type for each of the maximum of 32768 columns plus three
   82471       ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
   82472       */
   82473       if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
   82474         goto op_column_corrupt;
   82475       }
   82476     }else{
   82477       /* This is an optimization.  By skipping over the first few tests
   82478       ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
   82479       ** measurable performance gain.
   82480       **
   82481       ** This branch is taken even if aOffset[0]==0.  Such a record is never
   82482       ** generated by SQLite, and could be considered corruption, but we
   82483       ** accept it for historical reasons.  When aOffset[0]==0, the code this
   82484       ** branch jumps to reads past the end of the record, but never more
   82485       ** than a few bytes.  Even if the record occurs at the end of the page
   82486       ** content area, the "page header" comes after the page content and so
   82487       ** this overread is harmless.  Similar overreads can occur for a corrupt
   82488       ** database file.
   82489       */
   82490       zData = pC->aRow;
   82491       assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
   82492       testcase( aOffset[0]==0 );
   82493       goto op_column_read_header;
   82494     }
   82495   }
   82496 
   82497   /* Make sure at least the first p2+1 entries of the header have been
   82498   ** parsed and valid information is in aOffset[] and pC->aType[].
   82499   */
   82500   if( pC->nHdrParsed<=p2 ){
   82501     /* If there is more header available for parsing in the record, try
   82502     ** to extract additional fields up through the p2+1-th field
   82503     */
   82504     if( pC->iHdrOffset<aOffset[0] ){
   82505       /* Make sure zData points to enough of the record to cover the header. */
   82506       if( pC->aRow==0 ){
   82507         memset(&sMem, 0, sizeof(sMem));
   82508         rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
   82509         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   82510         zData = (u8*)sMem.z;
   82511       }else{
   82512         zData = pC->aRow;
   82513       }
   82514 
   82515       /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
   82516     op_column_read_header:
   82517       i = pC->nHdrParsed;
   82518       offset64 = aOffset[i];
   82519       zHdr = zData + pC->iHdrOffset;
   82520       zEndHdr = zData + aOffset[0];
   82521       testcase( zHdr>=zEndHdr );
   82522       do{
   82523         if( (t = zHdr[0])<0x80 ){
   82524           zHdr++;
   82525           offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
   82526         }else{
   82527           zHdr += sqlite3GetVarint32(zHdr, &t);
   82528           offset64 += sqlite3VdbeSerialTypeLen(t);
   82529         }
   82530         pC->aType[i++] = t;
   82531         aOffset[i] = (u32)(offset64 & 0xffffffff);
   82532       }while( i<=p2 && zHdr<zEndHdr );
   82533 
   82534       /* The record is corrupt if any of the following are true:
   82535       ** (1) the bytes of the header extend past the declared header size
   82536       ** (2) the entire header was used but not all data was used
   82537       ** (3) the end of the data extends beyond the end of the record.
   82538       */
   82539       if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
   82540        || (offset64 > pC->payloadSize)
   82541       ){
   82542         if( aOffset[0]==0 ){
   82543           i = 0;
   82544           zHdr = zEndHdr;
   82545         }else{
   82546           if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
   82547           goto op_column_corrupt;
   82548         }
   82549       }
   82550 
   82551       pC->nHdrParsed = i;
   82552       pC->iHdrOffset = (u32)(zHdr - zData);
   82553       if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
   82554     }else{
   82555       t = 0;
   82556     }
   82557 
   82558     /* If after trying to extract new entries from the header, nHdrParsed is
   82559     ** still not up to p2, that means that the record has fewer than p2
   82560     ** columns.  So the result will be either the default value or a NULL.
   82561     */
   82562     if( pC->nHdrParsed<=p2 ){
   82563       if( pOp->p4type==P4_MEM ){
   82564         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
   82565       }else{
   82566         sqlite3VdbeMemSetNull(pDest);
   82567       }
   82568       goto op_column_out;
   82569     }
   82570   }else{
   82571     t = pC->aType[p2];
   82572   }
   82573 
   82574   /* Extract the content for the p2+1-th column.  Control can only
   82575   ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
   82576   ** all valid.
   82577   */
   82578   assert( p2<pC->nHdrParsed );
   82579   assert( rc==SQLITE_OK );
   82580   assert( sqlite3VdbeCheckMemInvariants(pDest) );
   82581   if( VdbeMemDynamic(pDest) ){
   82582     sqlite3VdbeMemSetNull(pDest);
   82583   }
   82584   assert( t==pC->aType[p2] );
   82585   if( pC->szRow>=aOffset[p2+1] ){
   82586     /* This is the common case where the desired content fits on the original
   82587     ** page - where the content is not on an overflow page */
   82588     zData = pC->aRow + aOffset[p2];
   82589     if( t<12 ){
   82590       sqlite3VdbeSerialGet(zData, t, pDest);
   82591     }else{
   82592       /* If the column value is a string, we need a persistent value, not
   82593       ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
   82594       ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
   82595       */
   82596       static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
   82597       pDest->n = len = (t-12)/2;
   82598       pDest->enc = encoding;
   82599       if( pDest->szMalloc < len+2 ){
   82600         pDest->flags = MEM_Null;
   82601         if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
   82602       }else{
   82603         pDest->z = pDest->zMalloc;
   82604       }
   82605       memcpy(pDest->z, zData, len);
   82606       pDest->z[len] = 0;
   82607       pDest->z[len+1] = 0;
   82608       pDest->flags = aFlag[t&1];
   82609     }
   82610   }else{
   82611     pDest->enc = encoding;
   82612     /* This branch happens only when content is on overflow pages */
   82613     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
   82614           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
   82615      || (len = sqlite3VdbeSerialTypeLen(t))==0
   82616     ){
   82617       /* Content is irrelevant for
   82618       **    1. the typeof() function,
   82619       **    2. the length(X) function if X is a blob, and
   82620       **    3. if the content length is zero.
   82621       ** So we might as well use bogus content rather than reading
   82622       ** content from disk.
   82623       **
   82624       ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
   82625       ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
   82626       ** read up to 16. So 16 bytes of bogus content is supplied.
   82627       */
   82628       static u8 aZero[16];  /* This is the bogus content */
   82629       sqlite3VdbeSerialGet(aZero, t, pDest);
   82630     }else{
   82631       rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
   82632       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   82633       sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
   82634       pDest->flags &= ~MEM_Ephem;
   82635     }
   82636   }
   82637 
   82638 op_column_out:
   82639   UPDATE_MAX_BLOBSIZE(pDest);
   82640   REGISTER_TRACE(pOp->p3, pDest);
   82641   break;
   82642 
   82643 op_column_corrupt:
   82644   if( aOp[0].p3>0 ){
   82645     pOp = &aOp[aOp[0].p3-1];
   82646     break;
   82647   }else{
   82648     rc = SQLITE_CORRUPT_BKPT;
   82649     goto abort_due_to_error;
   82650   }
   82651 }
   82652 
   82653 /* Opcode: Affinity P1 P2 * P4 *
   82654 ** Synopsis: affinity(r[P1@P2])
   82655 **
   82656 ** Apply affinities to a range of P2 registers starting with P1.
   82657 **
   82658 ** P4 is a string that is P2 characters long. The N-th character of the
   82659 ** string indicates the column affinity that should be used for the N-th
   82660 ** memory cell in the range.
   82661 */
   82662 case OP_Affinity: {
   82663   const char *zAffinity;   /* The affinity to be applied */
   82664 
   82665   zAffinity = pOp->p4.z;
   82666   assert( zAffinity!=0 );
   82667   assert( pOp->p2>0 );
   82668   assert( zAffinity[pOp->p2]==0 );
   82669   pIn1 = &aMem[pOp->p1];
   82670   do{
   82671     assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
   82672     assert( memIsValid(pIn1) );
   82673     applyAffinity(pIn1, *(zAffinity++), encoding);
   82674     pIn1++;
   82675   }while( zAffinity[0] );
   82676   break;
   82677 }
   82678 
   82679 /* Opcode: MakeRecord P1 P2 P3 P4 *
   82680 ** Synopsis: r[P3]=mkrec(r[P1@P2])
   82681 **
   82682 ** Convert P2 registers beginning with P1 into the [record format]
   82683 ** use as a data record in a database table or as a key
   82684 ** in an index.  The OP_Column opcode can decode the record later.
   82685 **
   82686 ** P4 may be a string that is P2 characters long.  The N-th character of the
   82687 ** string indicates the column affinity that should be used for the N-th
   82688 ** field of the index key.
   82689 **
   82690 ** The mapping from character to affinity is given by the SQLITE_AFF_
   82691 ** macros defined in sqliteInt.h.
   82692 **
   82693 ** If P4 is NULL then all index fields have the affinity BLOB.
   82694 */
   82695 case OP_MakeRecord: {
   82696   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   82697   Mem *pRec;             /* The new record */
   82698   u64 nData;             /* Number of bytes of data space */
   82699   int nHdr;              /* Number of bytes of header space */
   82700   i64 nByte;             /* Data space required for this record */
   82701   i64 nZero;             /* Number of zero bytes at the end of the record */
   82702   int nVarint;           /* Number of bytes in a varint */
   82703   u32 serial_type;       /* Type field */
   82704   Mem *pData0;           /* First field to be combined into the record */
   82705   Mem *pLast;            /* Last field of the record */
   82706   int nField;            /* Number of fields in the record */
   82707   char *zAffinity;       /* The affinity string for the record */
   82708   int file_format;       /* File format to use for encoding */
   82709   int i;                 /* Space used in zNewRecord[] header */
   82710   int j;                 /* Space used in zNewRecord[] content */
   82711   u32 len;               /* Length of a field */
   82712 
   82713   /* Assuming the record contains N fields, the record format looks
   82714   ** like this:
   82715   **
   82716   ** ------------------------------------------------------------------------
   82717   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   82718   ** ------------------------------------------------------------------------
   82719   **
   82720   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   82721   ** and so forth.
   82722   **
   82723   ** Each type field is a varint representing the serial type of the
   82724   ** corresponding data element (see sqlite3VdbeSerialType()). The
   82725   ** hdr-size field is also a varint which is the offset from the beginning
   82726   ** of the record to data0.
   82727   */
   82728   nData = 0;         /* Number of bytes of data space */
   82729   nHdr = 0;          /* Number of bytes of header space */
   82730   nZero = 0;         /* Number of zero bytes at the end of the record */
   82731   nField = pOp->p1;
   82732   zAffinity = pOp->p4.z;
   82733   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
   82734   pData0 = &aMem[nField];
   82735   nField = pOp->p2;
   82736   pLast = &pData0[nField-1];
   82737   file_format = p->minWriteFileFormat;
   82738 
   82739   /* Identify the output register */
   82740   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
   82741   pOut = &aMem[pOp->p3];
   82742   memAboutToChange(p, pOut);
   82743 
   82744   /* Apply the requested affinity to all inputs
   82745   */
   82746   assert( pData0<=pLast );
   82747   if( zAffinity ){
   82748     pRec = pData0;
   82749     do{
   82750       applyAffinity(pRec++, *(zAffinity++), encoding);
   82751       assert( zAffinity[0]==0 || pRec<=pLast );
   82752     }while( zAffinity[0] );
   82753   }
   82754 
   82755 #ifdef SQLITE_ENABLE_NULL_TRIM
   82756   /* NULLs can be safely trimmed from the end of the record, as long as
   82757   ** as the schema format is 2 or more and none of the omitted columns
   82758   ** have a non-NULL default value.  Also, the record must be left with
   82759   ** at least one field.  If P5>0 then it will be one more than the
   82760   ** index of the right-most column with a non-NULL default value */
   82761   if( pOp->p5 ){
   82762     while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
   82763       pLast--;
   82764       nField--;
   82765     }
   82766   }
   82767 #endif
   82768 
   82769   /* Loop through the elements that will make up the record to figure
   82770   ** out how much space is required for the new record.
   82771   */
   82772   pRec = pLast;
   82773   do{
   82774     assert( memIsValid(pRec) );
   82775     serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
   82776     if( pRec->flags & MEM_Zero ){
   82777       if( serial_type==0 ){
   82778         /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
   82779         ** table methods that never invoke sqlite3_result_xxxxx() while
   82780         ** computing an unchanging column value in an UPDATE statement.
   82781         ** Give such values a special internal-use-only serial-type of 10
   82782         ** so that they can be passed through to xUpdate and have
   82783         ** a true sqlite3_value_nochange(). */
   82784         assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
   82785         serial_type = 10;
   82786       }else if( nData ){
   82787         if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
   82788       }else{
   82789         nZero += pRec->u.nZero;
   82790         len -= pRec->u.nZero;
   82791       }
   82792     }
   82793     nData += len;
   82794     testcase( serial_type==127 );
   82795     testcase( serial_type==128 );
   82796     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
   82797     pRec->uTemp = serial_type;
   82798     if( pRec==pData0 ) break;
   82799     pRec--;
   82800   }while(1);
   82801 
   82802   /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
   82803   ** which determines the total number of bytes in the header. The varint
   82804   ** value is the size of the header in bytes including the size varint
   82805   ** itself. */
   82806   testcase( nHdr==126 );
   82807   testcase( nHdr==127 );
   82808   if( nHdr<=126 ){
   82809     /* The common case */
   82810     nHdr += 1;
   82811   }else{
   82812     /* Rare case of a really large header */
   82813     nVarint = sqlite3VarintLen(nHdr);
   82814     nHdr += nVarint;
   82815     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
   82816   }
   82817   nByte = nHdr+nData;
   82818   if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   82819     goto too_big;
   82820   }
   82821 
   82822   /* Make sure the output register has a buffer large enough to store
   82823   ** the new record. The output register (pOp->p3) is not allowed to
   82824   ** be one of the input registers (because the following call to
   82825   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
   82826   */
   82827   if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
   82828     goto no_mem;
   82829   }
   82830   zNewRecord = (u8 *)pOut->z;
   82831 
   82832   /* Write the record */
   82833   i = putVarint32(zNewRecord, nHdr);
   82834   j = nHdr;
   82835   assert( pData0<=pLast );
   82836   pRec = pData0;
   82837   do{
   82838     serial_type = pRec->uTemp;
   82839     /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
   82840     ** additional varints, one per column. */
   82841     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
   82842     /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
   82843     ** immediately follow the header. */
   82844     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
   82845   }while( (++pRec)<=pLast );
   82846   assert( i==nHdr );
   82847   assert( j==nByte );
   82848 
   82849   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   82850   pOut->n = (int)nByte;
   82851   pOut->flags = MEM_Blob;
   82852   if( nZero ){
   82853     pOut->u.nZero = nZero;
   82854     pOut->flags |= MEM_Zero;
   82855   }
   82856   REGISTER_TRACE(pOp->p3, pOut);
   82857   UPDATE_MAX_BLOBSIZE(pOut);
   82858   break;
   82859 }
   82860 
   82861 /* Opcode: Count P1 P2 * * *
   82862 ** Synopsis: r[P2]=count()
   82863 **
   82864 ** Store the number of entries (an integer value) in the table or index
   82865 ** opened by cursor P1 in register P2
   82866 */
   82867 #ifndef SQLITE_OMIT_BTREECOUNT
   82868 case OP_Count: {         /* out2 */
   82869   i64 nEntry;
   82870   BtCursor *pCrsr;
   82871 
   82872   assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
   82873   pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
   82874   assert( pCrsr );
   82875   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
   82876   rc = sqlite3BtreeCount(pCrsr, &nEntry);
   82877   if( rc ) goto abort_due_to_error;
   82878   pOut = out2Prerelease(p, pOp);
   82879   pOut->u.i = nEntry;
   82880   break;
   82881 }
   82882 #endif
   82883 
   82884 /* Opcode: Savepoint P1 * * P4 *
   82885 **
   82886 ** Open, release or rollback the savepoint named by parameter P4, depending
   82887 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
   82888 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
   82889 */
   82890 case OP_Savepoint: {
   82891   int p1;                         /* Value of P1 operand */
   82892   char *zName;                    /* Name of savepoint */
   82893   int nName;
   82894   Savepoint *pNew;
   82895   Savepoint *pSavepoint;
   82896   Savepoint *pTmp;
   82897   int iSavepoint;
   82898   int ii;
   82899 
   82900   p1 = pOp->p1;
   82901   zName = pOp->p4.z;
   82902 
   82903   /* Assert that the p1 parameter is valid. Also that if there is no open
   82904   ** transaction, then there cannot be any savepoints.
   82905   */
   82906   assert( db->pSavepoint==0 || db->autoCommit==0 );
   82907   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
   82908   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
   82909   assert( checkSavepointCount(db) );
   82910   assert( p->bIsReader );
   82911 
   82912   if( p1==SAVEPOINT_BEGIN ){
   82913     if( db->nVdbeWrite>0 ){
   82914       /* A new savepoint cannot be created if there are active write
   82915       ** statements (i.e. open read/write incremental blob handles).
   82916       */
   82917       sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
   82918       rc = SQLITE_BUSY;
   82919     }else{
   82920       nName = sqlite3Strlen30(zName);
   82921 
   82922 #ifndef SQLITE_OMIT_VIRTUALTABLE
   82923       /* This call is Ok even if this savepoint is actually a transaction
   82924       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
   82925       ** If this is a transaction savepoint being opened, it is guaranteed
   82926       ** that the db->aVTrans[] array is empty.  */
   82927       assert( db->autoCommit==0 || db->nVTrans==0 );
   82928       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
   82929                                 db->nStatement+db->nSavepoint);
   82930       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   82931 #endif
   82932 
   82933       /* Create a new savepoint structure. */
   82934       pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
   82935       if( pNew ){
   82936         pNew->zName = (char *)&pNew[1];
   82937         memcpy(pNew->zName, zName, nName+1);
   82938 
   82939         /* If there is no open transaction, then mark this as a special
   82940         ** "transaction savepoint". */
   82941         if( db->autoCommit ){
   82942           db->autoCommit = 0;
   82943           db->isTransactionSavepoint = 1;
   82944         }else{
   82945           db->nSavepoint++;
   82946         }
   82947 
   82948         /* Link the new savepoint into the database handle's list. */
   82949         pNew->pNext = db->pSavepoint;
   82950         db->pSavepoint = pNew;
   82951         pNew->nDeferredCons = db->nDeferredCons;
   82952         pNew->nDeferredImmCons = db->nDeferredImmCons;
   82953       }
   82954     }
   82955   }else{
   82956     iSavepoint = 0;
   82957 
   82958     /* Find the named savepoint. If there is no such savepoint, then an
   82959     ** an error is returned to the user.  */
   82960     for(
   82961       pSavepoint = db->pSavepoint;
   82962       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
   82963       pSavepoint = pSavepoint->pNext
   82964     ){
   82965       iSavepoint++;
   82966     }
   82967     if( !pSavepoint ){
   82968       sqlite3VdbeError(p, "no such savepoint: %s", zName);
   82969       rc = SQLITE_ERROR;
   82970     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
   82971       /* It is not possible to release (commit) a savepoint if there are
   82972       ** active write statements.
   82973       */
   82974       sqlite3VdbeError(p, "cannot release savepoint - "
   82975                           "SQL statements in progress");
   82976       rc = SQLITE_BUSY;
   82977     }else{
   82978 
   82979       /* Determine whether or not this is a transaction savepoint. If so,
   82980       ** and this is a RELEASE command, then the current transaction
   82981       ** is committed.
   82982       */
   82983       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
   82984       if( isTransaction && p1==SAVEPOINT_RELEASE ){
   82985         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   82986           goto vdbe_return;
   82987         }
   82988         db->autoCommit = 1;
   82989         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   82990           p->pc = (int)(pOp - aOp);
   82991           db->autoCommit = 0;
   82992           p->rc = rc = SQLITE_BUSY;
   82993           goto vdbe_return;
   82994         }
   82995         db->isTransactionSavepoint = 0;
   82996         rc = p->rc;
   82997       }else{
   82998         int isSchemaChange;
   82999         iSavepoint = db->nSavepoint - iSavepoint - 1;
   83000         if( p1==SAVEPOINT_ROLLBACK ){
   83001           isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
   83002           for(ii=0; ii<db->nDb; ii++){
   83003             rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
   83004                                        SQLITE_ABORT_ROLLBACK,
   83005                                        isSchemaChange==0);
   83006             if( rc!=SQLITE_OK ) goto abort_due_to_error;
   83007           }
   83008         }else{
   83009           isSchemaChange = 0;
   83010         }
   83011         for(ii=0; ii<db->nDb; ii++){
   83012           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
   83013           if( rc!=SQLITE_OK ){
   83014             goto abort_due_to_error;
   83015           }
   83016         }
   83017         if( isSchemaChange ){
   83018           sqlite3ExpirePreparedStatements(db);
   83019           sqlite3ResetAllSchemasOfConnection(db);
   83020           db->mDbFlags |= DBFLAG_SchemaChange;
   83021         }
   83022       }
   83023 
   83024       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
   83025       ** savepoints nested inside of the savepoint being operated on. */
   83026       while( db->pSavepoint!=pSavepoint ){
   83027         pTmp = db->pSavepoint;
   83028         db->pSavepoint = pTmp->pNext;
   83029         sqlite3DbFree(db, pTmp);
   83030         db->nSavepoint--;
   83031       }
   83032 
   83033       /* If it is a RELEASE, then destroy the savepoint being operated on
   83034       ** too. If it is a ROLLBACK TO, then set the number of deferred
   83035       ** constraint violations present in the database to the value stored
   83036       ** when the savepoint was created.  */
   83037       if( p1==SAVEPOINT_RELEASE ){
   83038         assert( pSavepoint==db->pSavepoint );
   83039         db->pSavepoint = pSavepoint->pNext;
   83040         sqlite3DbFree(db, pSavepoint);
   83041         if( !isTransaction ){
   83042           db->nSavepoint--;
   83043         }
   83044       }else{
   83045         db->nDeferredCons = pSavepoint->nDeferredCons;
   83046         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
   83047       }
   83048 
   83049       if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
   83050         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
   83051         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   83052       }
   83053     }
   83054   }
   83055   if( rc ) goto abort_due_to_error;
   83056 
   83057   break;
   83058 }
   83059 
   83060 /* Opcode: AutoCommit P1 P2 * * *
   83061 **
   83062 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
   83063 ** back any currently active btree transactions. If there are any active
   83064 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
   83065 ** there are active writing VMs or active VMs that use shared cache.
   83066 **
   83067 ** This instruction causes the VM to halt.
   83068 */
   83069 case OP_AutoCommit: {
   83070   int desiredAutoCommit;
   83071   int iRollback;
   83072 
   83073   desiredAutoCommit = pOp->p1;
   83074   iRollback = pOp->p2;
   83075   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
   83076   assert( desiredAutoCommit==1 || iRollback==0 );
   83077   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
   83078   assert( p->bIsReader );
   83079 
   83080   if( desiredAutoCommit!=db->autoCommit ){
   83081     if( iRollback ){
   83082       assert( desiredAutoCommit==1 );
   83083       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   83084       db->autoCommit = 1;
   83085     }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
   83086       /* If this instruction implements a COMMIT and other VMs are writing
   83087       ** return an error indicating that the other VMs must complete first.
   83088       */
   83089       sqlite3VdbeError(p, "cannot commit transaction - "
   83090                           "SQL statements in progress");
   83091       rc = SQLITE_BUSY;
   83092       goto abort_due_to_error;
   83093     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   83094       goto vdbe_return;
   83095     }else{
   83096       db->autoCommit = (u8)desiredAutoCommit;
   83097     }
   83098     if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   83099       p->pc = (int)(pOp - aOp);
   83100       db->autoCommit = (u8)(1-desiredAutoCommit);
   83101       p->rc = rc = SQLITE_BUSY;
   83102       goto vdbe_return;
   83103     }
   83104     assert( db->nStatement==0 );
   83105     sqlite3CloseSavepoints(db);
   83106     if( p->rc==SQLITE_OK ){
   83107       rc = SQLITE_DONE;
   83108     }else{
   83109       rc = SQLITE_ERROR;
   83110     }
   83111     goto vdbe_return;
   83112   }else{
   83113     sqlite3VdbeError(p,
   83114         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
   83115         (iRollback)?"cannot rollback - no transaction is active":
   83116                    "cannot commit - no transaction is active"));
   83117 
   83118     rc = SQLITE_ERROR;
   83119     goto abort_due_to_error;
   83120   }
   83121   break;
   83122 }
   83123 
   83124 /* Opcode: Transaction P1 P2 P3 P4 P5
   83125 **
   83126 ** Begin a transaction on database P1 if a transaction is not already
   83127 ** active.
   83128 ** If P2 is non-zero, then a write-transaction is started, or if a
   83129 ** read-transaction is already active, it is upgraded to a write-transaction.
   83130 ** If P2 is zero, then a read-transaction is started.
   83131 **
   83132 ** P1 is the index of the database file on which the transaction is
   83133 ** started.  Index 0 is the main database file and index 1 is the
   83134 ** file used for temporary tables.  Indices of 2 or more are used for
   83135 ** attached databases.
   83136 **
   83137 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
   83138 ** true (this flag is set if the Vdbe may modify more than one row and may
   83139 ** throw an ABORT exception), a statement transaction may also be opened.
   83140 ** More specifically, a statement transaction is opened iff the database
   83141 ** connection is currently not in autocommit mode, or if there are other
   83142 ** active statements. A statement transaction allows the changes made by this
   83143 ** VDBE to be rolled back after an error without having to roll back the
   83144 ** entire transaction. If no error is encountered, the statement transaction
   83145 ** will automatically commit when the VDBE halts.
   83146 **
   83147 ** If P5!=0 then this opcode also checks the schema cookie against P3
   83148 ** and the schema generation counter against P4.
   83149 ** The cookie changes its value whenever the database schema changes.
   83150 ** This operation is used to detect when that the cookie has changed
   83151 ** and that the current process needs to reread the schema.  If the schema
   83152 ** cookie in P3 differs from the schema cookie in the database header or
   83153 ** if the schema generation counter in P4 differs from the current
   83154 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
   83155 ** halts.  The sqlite3_step() wrapper function might then reprepare the
   83156 ** statement and rerun it from the beginning.
   83157 */
   83158 case OP_Transaction: {
   83159   Btree *pBt;
   83160   int iMeta;
   83161   int iGen;
   83162 
   83163   assert( p->bIsReader );
   83164   assert( p->readOnly==0 || pOp->p2==0 );
   83165   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   83166   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   83167   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
   83168     rc = SQLITE_READONLY;
   83169     goto abort_due_to_error;
   83170   }
   83171   pBt = db->aDb[pOp->p1].pBt;
   83172 
   83173   if( pBt ){
   83174     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
   83175     testcase( rc==SQLITE_BUSY_SNAPSHOT );
   83176     testcase( rc==SQLITE_BUSY_RECOVERY );
   83177     if( rc!=SQLITE_OK ){
   83178       if( (rc&0xff)==SQLITE_BUSY ){
   83179         p->pc = (int)(pOp - aOp);
   83180         p->rc = rc;
   83181         goto vdbe_return;
   83182       }
   83183       goto abort_due_to_error;
   83184     }
   83185 
   83186     if( pOp->p2 && p->usesStmtJournal
   83187      && (db->autoCommit==0 || db->nVdbeRead>1)
   83188     ){
   83189       assert( sqlite3BtreeIsInTrans(pBt) );
   83190       if( p->iStatement==0 ){
   83191         assert( db->nStatement>=0 && db->nSavepoint>=0 );
   83192         db->nStatement++;
   83193         p->iStatement = db->nSavepoint + db->nStatement;
   83194       }
   83195 
   83196       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
   83197       if( rc==SQLITE_OK ){
   83198         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
   83199       }
   83200 
   83201       /* Store the current value of the database handles deferred constraint
   83202       ** counter. If the statement transaction needs to be rolled back,
   83203       ** the value of this counter needs to be restored too.  */
   83204       p->nStmtDefCons = db->nDeferredCons;
   83205       p->nStmtDefImmCons = db->nDeferredImmCons;
   83206     }
   83207 
   83208     /* Gather the schema version number for checking:
   83209     ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
   83210     ** version is checked to ensure that the schema has not changed since the
   83211     ** SQL statement was prepared.
   83212     */
   83213     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
   83214     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
   83215   }else{
   83216     iGen = iMeta = 0;
   83217   }
   83218   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
   83219   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
   83220     sqlite3DbFree(db, p->zErrMsg);
   83221     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
   83222     /* If the schema-cookie from the database file matches the cookie
   83223     ** stored with the in-memory representation of the schema, do
   83224     ** not reload the schema from the database file.
   83225     **
   83226     ** If virtual-tables are in use, this is not just an optimization.
   83227     ** Often, v-tables store their data in other SQLite tables, which
   83228     ** are queried from within xNext() and other v-table methods using
   83229     ** prepared queries. If such a query is out-of-date, we do not want to
   83230     ** discard the database schema, as the user code implementing the
   83231     ** v-table would have to be ready for the sqlite3_vtab structure itself
   83232     ** to be invalidated whenever sqlite3_step() is called from within
   83233     ** a v-table method.
   83234     */
   83235     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
   83236       sqlite3ResetOneSchema(db, pOp->p1);
   83237     }
   83238     p->expired = 1;
   83239     rc = SQLITE_SCHEMA;
   83240   }
   83241   if( rc ) goto abort_due_to_error;
   83242   break;
   83243 }
   83244 
   83245 /* Opcode: ReadCookie P1 P2 P3 * *
   83246 **
   83247 ** Read cookie number P3 from database P1 and write it into register P2.
   83248 ** P3==1 is the schema version.  P3==2 is the database format.
   83249 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
   83250 ** the main database file and P1==1 is the database file used to store
   83251 ** temporary tables.
   83252 **
   83253 ** There must be a read-lock on the database (either a transaction
   83254 ** must be started or there must be an open cursor) before
   83255 ** executing this instruction.
   83256 */
   83257 case OP_ReadCookie: {               /* out2 */
   83258   int iMeta;
   83259   int iDb;
   83260   int iCookie;
   83261 
   83262   assert( p->bIsReader );
   83263   iDb = pOp->p1;
   83264   iCookie = pOp->p3;
   83265   assert( pOp->p3<SQLITE_N_BTREE_META );
   83266   assert( iDb>=0 && iDb<db->nDb );
   83267   assert( db->aDb[iDb].pBt!=0 );
   83268   assert( DbMaskTest(p->btreeMask, iDb) );
   83269 
   83270   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
   83271   pOut = out2Prerelease(p, pOp);
   83272   pOut->u.i = iMeta;
   83273   break;
   83274 }
   83275 
   83276 /* Opcode: SetCookie P1 P2 P3 * *
   83277 **
   83278 ** Write the integer value P3 into cookie number P2 of database P1.
   83279 ** P2==1 is the schema version.  P2==2 is the database format.
   83280 ** P2==3 is the recommended pager cache
   83281 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
   83282 ** database file used to store temporary tables.
   83283 **
   83284 ** A transaction must be started before executing this opcode.
   83285 */
   83286 case OP_SetCookie: {
   83287   Db *pDb;
   83288   assert( pOp->p2<SQLITE_N_BTREE_META );
   83289   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   83290   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   83291   assert( p->readOnly==0 );
   83292   pDb = &db->aDb[pOp->p1];
   83293   assert( pDb->pBt!=0 );
   83294   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
   83295   /* See note about index shifting on OP_ReadCookie */
   83296   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
   83297   if( pOp->p2==BTREE_SCHEMA_VERSION ){
   83298     /* When the schema cookie changes, record the new cookie internally */
   83299     pDb->pSchema->schema_cookie = pOp->p3;
   83300     db->mDbFlags |= DBFLAG_SchemaChange;
   83301   }else if( pOp->p2==BTREE_FILE_FORMAT ){
   83302     /* Record changes in the file format */
   83303     pDb->pSchema->file_format = pOp->p3;
   83304   }
   83305   if( pOp->p1==1 ){
   83306     /* Invalidate all prepared statements whenever the TEMP database
   83307     ** schema is changed.  Ticket #1644 */
   83308     sqlite3ExpirePreparedStatements(db);
   83309     p->expired = 0;
   83310   }
   83311   if( rc ) goto abort_due_to_error;
   83312   break;
   83313 }
   83314 
   83315 /* Opcode: OpenRead P1 P2 P3 P4 P5
   83316 ** Synopsis: root=P2 iDb=P3
   83317 **
   83318 ** Open a read-only cursor for the database table whose root page is
   83319 ** P2 in a database file.  The database file is determined by P3.
   83320 ** P3==0 means the main database, P3==1 means the database used for
   83321 ** temporary tables, and P3>1 means used the corresponding attached
   83322 ** database.  Give the new cursor an identifier of P1.  The P1
   83323 ** values need not be contiguous but all P1 values should be small integers.
   83324 ** It is an error for P1 to be negative.
   83325 **
   83326 ** If P5!=0 then use the content of register P2 as the root page, not
   83327 ** the value of P2 itself.
   83328 **
   83329 ** There will be a read lock on the database whenever there is an
   83330 ** open cursor.  If the database was unlocked prior to this instruction
   83331 ** then a read lock is acquired as part of this instruction.  A read
   83332 ** lock allows other processes to read the database but prohibits
   83333 ** any other process from modifying the database.  The read lock is
   83334 ** released when all cursors are closed.  If this instruction attempts
   83335 ** to get a read lock but fails, the script terminates with an
   83336 ** SQLITE_BUSY error code.
   83337 **
   83338 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   83339 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   83340 ** structure, then said structure defines the content and collating
   83341 ** sequence of the index being opened. Otherwise, if P4 is an integer
   83342 ** value, it is set to the number of columns in the table.
   83343 **
   83344 ** See also: OpenWrite, ReopenIdx
   83345 */
   83346 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
   83347 ** Synopsis: root=P2 iDb=P3
   83348 **
   83349 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
   83350 ** checks to see if the cursor on P1 is already open with a root page
   83351 ** number of P2 and if it is this opcode becomes a no-op.  In other words,
   83352 ** if the cursor is already open, do not reopen it.
   83353 **
   83354 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
   83355 ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
   83356 ** every other ReopenIdx or OpenRead for the same cursor number.
   83357 **
   83358 ** See the OpenRead opcode documentation for additional information.
   83359 */
   83360 /* Opcode: OpenWrite P1 P2 P3 P4 P5
   83361 ** Synopsis: root=P2 iDb=P3
   83362 **
   83363 ** Open a read/write cursor named P1 on the table or index whose root
   83364 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
   83365 ** root page.
   83366 **
   83367 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   83368 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   83369 ** structure, then said structure defines the content and collating
   83370 ** sequence of the index being opened. Otherwise, if P4 is an integer
   83371 ** value, it is set to the number of columns in the table, or to the
   83372 ** largest index of any column of the table that is actually used.
   83373 **
   83374 ** This instruction works just like OpenRead except that it opens the cursor
   83375 ** in read/write mode.  For a given table, there can be one or more read-only
   83376 ** cursors or a single read/write cursor but not both.
   83377 **
   83378 ** See also OpenRead.
   83379 */
   83380 case OP_ReopenIdx: {
   83381   int nField;
   83382   KeyInfo *pKeyInfo;
   83383   int p2;
   83384   int iDb;
   83385   int wrFlag;
   83386   Btree *pX;
   83387   VdbeCursor *pCur;
   83388   Db *pDb;
   83389 
   83390   assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
   83391   assert( pOp->p4type==P4_KEYINFO );
   83392   pCur = p->apCsr[pOp->p1];
   83393   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
   83394     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
   83395     goto open_cursor_set_hints;
   83396   }
   83397   /* If the cursor is not currently open or is open on a different
   83398   ** index, then fall through into OP_OpenRead to force a reopen */
   83399 case OP_OpenRead:
   83400 case OP_OpenWrite:
   83401 
   83402   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
   83403   assert( p->bIsReader );
   83404   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
   83405           || p->readOnly==0 );
   83406 
   83407   if( p->expired ){
   83408     rc = SQLITE_ABORT_ROLLBACK;
   83409     goto abort_due_to_error;
   83410   }
   83411 
   83412   nField = 0;
   83413   pKeyInfo = 0;
   83414   p2 = pOp->p2;
   83415   iDb = pOp->p3;
   83416   assert( iDb>=0 && iDb<db->nDb );
   83417   assert( DbMaskTest(p->btreeMask, iDb) );
   83418   pDb = &db->aDb[iDb];
   83419   pX = pDb->pBt;
   83420   assert( pX!=0 );
   83421   if( pOp->opcode==OP_OpenWrite ){
   83422     assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
   83423     wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
   83424     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   83425     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
   83426       p->minWriteFileFormat = pDb->pSchema->file_format;
   83427     }
   83428   }else{
   83429     wrFlag = 0;
   83430   }
   83431   if( pOp->p5 & OPFLAG_P2ISREG ){
   83432     assert( p2>0 );
   83433     assert( p2<=(p->nMem+1 - p->nCursor) );
   83434     pIn2 = &aMem[p2];
   83435     assert( memIsValid(pIn2) );
   83436     assert( (pIn2->flags & MEM_Int)!=0 );
   83437     sqlite3VdbeMemIntegerify(pIn2);
   83438     p2 = (int)pIn2->u.i;
   83439     /* The p2 value always comes from a prior OP_CreateBtree opcode and
   83440     ** that opcode will always set the p2 value to 2 or more or else fail.
   83441     ** If there were a failure, the prepared statement would have halted
   83442     ** before reaching this instruction. */
   83443     assert( p2>=2 );
   83444   }
   83445   if( pOp->p4type==P4_KEYINFO ){
   83446     pKeyInfo = pOp->p4.pKeyInfo;
   83447     assert( pKeyInfo->enc==ENC(db) );
   83448     assert( pKeyInfo->db==db );
   83449     nField = pKeyInfo->nAllField;
   83450   }else if( pOp->p4type==P4_INT32 ){
   83451     nField = pOp->p4.i;
   83452   }
   83453   assert( pOp->p1>=0 );
   83454   assert( nField>=0 );
   83455   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
   83456   pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
   83457   if( pCur==0 ) goto no_mem;
   83458   pCur->nullRow = 1;
   83459   pCur->isOrdered = 1;
   83460   pCur->pgnoRoot = p2;
   83461 #ifdef SQLITE_DEBUG
   83462   pCur->wrFlag = wrFlag;
   83463 #endif
   83464   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
   83465   pCur->pKeyInfo = pKeyInfo;
   83466   /* Set the VdbeCursor.isTable variable. Previous versions of
   83467   ** SQLite used to check if the root-page flags were sane at this point
   83468   ** and report database corruption if they were not, but this check has
   83469   ** since moved into the btree layer.  */
   83470   pCur->isTable = pOp->p4type!=P4_KEYINFO;
   83471 
   83472 open_cursor_set_hints:
   83473   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
   83474   assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
   83475   testcase( pOp->p5 & OPFLAG_BULKCSR );
   83476 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   83477   testcase( pOp->p2 & OPFLAG_SEEKEQ );
   83478 #endif
   83479   sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
   83480                                (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
   83481   if( rc ) goto abort_due_to_error;
   83482   break;
   83483 }
   83484 
   83485 /* Opcode: OpenDup P1 P2 * * *
   83486 **
   83487 ** Open a new cursor P1 that points to the same ephemeral table as
   83488 ** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
   83489 ** opcode.  Only ephemeral cursors may be duplicated.
   83490 **
   83491 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
   83492 */
   83493 case OP_OpenDup: {
   83494   VdbeCursor *pOrig;    /* The original cursor to be duplicated */
   83495   VdbeCursor *pCx;      /* The new cursor */
   83496 
   83497   pOrig = p->apCsr[pOp->p2];
   83498   assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */
   83499 
   83500   pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
   83501   if( pCx==0 ) goto no_mem;
   83502   pCx->nullRow = 1;
   83503   pCx->isEphemeral = 1;
   83504   pCx->pKeyInfo = pOrig->pKeyInfo;
   83505   pCx->isTable = pOrig->isTable;
   83506   rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
   83507                           pCx->pKeyInfo, pCx->uc.pCursor);
   83508   /* The sqlite3BtreeCursor() routine can only fail for the first cursor
   83509   ** opened for a database.  Since there is already an open cursor when this
   83510   ** opcode is run, the sqlite3BtreeCursor() cannot fail */
   83511   assert( rc==SQLITE_OK );
   83512   break;
   83513 }
   83514 
   83515 
   83516 /* Opcode: OpenEphemeral P1 P2 * P4 P5
   83517 ** Synopsis: nColumn=P2
   83518 **
   83519 ** Open a new cursor P1 to a transient table.
   83520 ** The cursor is always opened read/write even if
   83521 ** the main database is read-only.  The ephemeral
   83522 ** table is deleted automatically when the cursor is closed.
   83523 **
   83524 ** P2 is the number of columns in the ephemeral table.
   83525 ** The cursor points to a BTree table if P4==0 and to a BTree index
   83526 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
   83527 ** that defines the format of keys in the index.
   83528 **
   83529 ** The P5 parameter can be a mask of the BTREE_* flags defined
   83530 ** in btree.h.  These flags control aspects of the operation of
   83531 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
   83532 ** added automatically.
   83533 */
   83534 /* Opcode: OpenAutoindex P1 P2 * P4 *
   83535 ** Synopsis: nColumn=P2
   83536 **
   83537 ** This opcode works the same as OP_OpenEphemeral.  It has a
   83538 ** different name to distinguish its use.  Tables created using
   83539 ** by this opcode will be used for automatically created transient
   83540 ** indices in joins.
   83541 */
   83542 case OP_OpenAutoindex:
   83543 case OP_OpenEphemeral: {
   83544   VdbeCursor *pCx;
   83545   KeyInfo *pKeyInfo;
   83546 
   83547   static const int vfsFlags =
   83548       SQLITE_OPEN_READWRITE |
   83549       SQLITE_OPEN_CREATE |
   83550       SQLITE_OPEN_EXCLUSIVE |
   83551       SQLITE_OPEN_DELETEONCLOSE |
   83552       SQLITE_OPEN_TRANSIENT_DB;
   83553   assert( pOp->p1>=0 );
   83554   assert( pOp->p2>=0 );
   83555   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
   83556   if( pCx==0 ) goto no_mem;
   83557   pCx->nullRow = 1;
   83558   pCx->isEphemeral = 1;
   83559   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
   83560                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
   83561   if( rc==SQLITE_OK ){
   83562     rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
   83563   }
   83564   if( rc==SQLITE_OK ){
   83565     /* If a transient index is required, create it by calling
   83566     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
   83567     ** opening it. If a transient table is required, just use the
   83568     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
   83569     */
   83570     if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
   83571       int pgno;
   83572       assert( pOp->p4type==P4_KEYINFO );
   83573       rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
   83574       if( rc==SQLITE_OK ){
   83575         assert( pgno==MASTER_ROOT+1 );
   83576         assert( pKeyInfo->db==db );
   83577         assert( pKeyInfo->enc==ENC(db) );
   83578         rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
   83579                                 pKeyInfo, pCx->uc.pCursor);
   83580       }
   83581       pCx->isTable = 0;
   83582     }else{
   83583       rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
   83584                               0, pCx->uc.pCursor);
   83585       pCx->isTable = 1;
   83586     }
   83587   }
   83588   if( rc ) goto abort_due_to_error;
   83589   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
   83590   break;
   83591 }
   83592 
   83593 /* Opcode: SorterOpen P1 P2 P3 P4 *
   83594 **
   83595 ** This opcode works like OP_OpenEphemeral except that it opens
   83596 ** a transient index that is specifically designed to sort large
   83597 ** tables using an external merge-sort algorithm.
   83598 **
   83599 ** If argument P3 is non-zero, then it indicates that the sorter may
   83600 ** assume that a stable sort considering the first P3 fields of each
   83601 ** key is sufficient to produce the required results.
   83602 */
   83603 case OP_SorterOpen: {
   83604   VdbeCursor *pCx;
   83605 
   83606   assert( pOp->p1>=0 );
   83607   assert( pOp->p2>=0 );
   83608   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
   83609   if( pCx==0 ) goto no_mem;
   83610   pCx->pKeyInfo = pOp->p4.pKeyInfo;
   83611   assert( pCx->pKeyInfo->db==db );
   83612   assert( pCx->pKeyInfo->enc==ENC(db) );
   83613   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
   83614   if( rc ) goto abort_due_to_error;
   83615   break;
   83616 }
   83617 
   83618 /* Opcode: SequenceTest P1 P2 * * *
   83619 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
   83620 **
   83621 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
   83622 ** to P2. Regardless of whether or not the jump is taken, increment the
   83623 ** the sequence value.
   83624 */
   83625 case OP_SequenceTest: {
   83626   VdbeCursor *pC;
   83627   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   83628   pC = p->apCsr[pOp->p1];
   83629   assert( isSorter(pC) );
   83630   if( (pC->seqCount++)==0 ){
   83631     goto jump_to_p2;
   83632   }
   83633   break;
   83634 }
   83635 
   83636 /* Opcode: OpenPseudo P1 P2 P3 * *
   83637 ** Synopsis: P3 columns in r[P2]
   83638 **
   83639 ** Open a new cursor that points to a fake table that contains a single
   83640 ** row of data.  The content of that one row is the content of memory
   83641 ** register P2.  In other words, cursor P1 becomes an alias for the
   83642 ** MEM_Blob content contained in register P2.
   83643 **
   83644 ** A pseudo-table created by this opcode is used to hold a single
   83645 ** row output from the sorter so that the row can be decomposed into
   83646 ** individual columns using the OP_Column opcode.  The OP_Column opcode
   83647 ** is the only cursor opcode that works with a pseudo-table.
   83648 **
   83649 ** P3 is the number of fields in the records that will be stored by
   83650 ** the pseudo-table.
   83651 */
   83652 case OP_OpenPseudo: {
   83653   VdbeCursor *pCx;
   83654 
   83655   assert( pOp->p1>=0 );
   83656   assert( pOp->p3>=0 );
   83657   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
   83658   if( pCx==0 ) goto no_mem;
   83659   pCx->nullRow = 1;
   83660   pCx->seekResult = pOp->p2;
   83661   pCx->isTable = 1;
   83662   /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
   83663   ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
   83664   ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
   83665   ** which is a performance optimization */
   83666   pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
   83667   assert( pOp->p5==0 );
   83668   break;
   83669 }
   83670 
   83671 /* Opcode: Close P1 * * * *
   83672 **
   83673 ** Close a cursor previously opened as P1.  If P1 is not
   83674 ** currently open, this instruction is a no-op.
   83675 */
   83676 case OP_Close: {
   83677   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   83678   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
   83679   p->apCsr[pOp->p1] = 0;
   83680   break;
   83681 }
   83682 
   83683 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
   83684 /* Opcode: ColumnsUsed P1 * * P4 *
   83685 **
   83686 ** This opcode (which only exists if SQLite was compiled with
   83687 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
   83688 ** table or index for cursor P1 are used.  P4 is a 64-bit integer
   83689 ** (P4_INT64) in which the first 63 bits are one for each of the
   83690 ** first 63 columns of the table or index that are actually used
   83691 ** by the cursor.  The high-order bit is set if any column after
   83692 ** the 64th is used.
   83693 */
   83694 case OP_ColumnsUsed: {
   83695   VdbeCursor *pC;
   83696   pC = p->apCsr[pOp->p1];
   83697   assert( pC->eCurType==CURTYPE_BTREE );
   83698   pC->maskUsed = *(u64*)pOp->p4.pI64;
   83699   break;
   83700 }
   83701 #endif
   83702 
   83703 /* Opcode: SeekGE P1 P2 P3 P4 *
   83704 ** Synopsis: key=r[P3@P4]
   83705 **
   83706 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   83707 ** use the value in register P3 as the key.  If cursor P1 refers
   83708 ** to an SQL index, then P3 is the first in an array of P4 registers
   83709 ** that are used as an unpacked index key.
   83710 **
   83711 ** Reposition cursor P1 so that  it points to the smallest entry that
   83712 ** is greater than or equal to the key value. If there are no records
   83713 ** greater than or equal to the key and P2 is not zero, then jump to P2.
   83714 **
   83715 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
   83716 ** opcode will always land on a record that equally equals the key, or
   83717 ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
   83718 ** opcode must be followed by an IdxLE opcode with the same arguments.
   83719 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
   83720 ** IdxLE opcode will be used on subsequent loop iterations.
   83721 **
   83722 ** This opcode leaves the cursor configured to move in forward order,
   83723 ** from the beginning toward the end.  In other words, the cursor is
   83724 ** configured to use Next, not Prev.
   83725 **
   83726 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
   83727 */
   83728 /* Opcode: SeekGT P1 P2 P3 P4 *
   83729 ** Synopsis: key=r[P3@P4]
   83730 **
   83731 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   83732 ** use the value in register P3 as a key. If cursor P1 refers
   83733 ** to an SQL index, then P3 is the first in an array of P4 registers
   83734 ** that are used as an unpacked index key.
   83735 **
   83736 ** Reposition cursor P1 so that  it points to the smallest entry that
   83737 ** is greater than the key value. If there are no records greater than
   83738 ** the key and P2 is not zero, then jump to P2.
   83739 **
   83740 ** This opcode leaves the cursor configured to move in forward order,
   83741 ** from the beginning toward the end.  In other words, the cursor is
   83742 ** configured to use Next, not Prev.
   83743 **
   83744 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
   83745 */
   83746 /* Opcode: SeekLT P1 P2 P3 P4 *
   83747 ** Synopsis: key=r[P3@P4]
   83748 **
   83749 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   83750 ** use the value in register P3 as a key. If cursor P1 refers
   83751 ** to an SQL index, then P3 is the first in an array of P4 registers
   83752 ** that are used as an unpacked index key.
   83753 **
   83754 ** Reposition cursor P1 so that  it points to the largest entry that
   83755 ** is less than the key value. If there are no records less than
   83756 ** the key and P2 is not zero, then jump to P2.
   83757 **
   83758 ** This opcode leaves the cursor configured to move in reverse order,
   83759 ** from the end toward the beginning.  In other words, the cursor is
   83760 ** configured to use Prev, not Next.
   83761 **
   83762 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
   83763 */
   83764 /* Opcode: SeekLE P1 P2 P3 P4 *
   83765 ** Synopsis: key=r[P3@P4]
   83766 **
   83767 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   83768 ** use the value in register P3 as a key. If cursor P1 refers
   83769 ** to an SQL index, then P3 is the first in an array of P4 registers
   83770 ** that are used as an unpacked index key.
   83771 **
   83772 ** Reposition cursor P1 so that it points to the largest entry that
   83773 ** is less than or equal to the key value. If there are no records
   83774 ** less than or equal to the key and P2 is not zero, then jump to P2.
   83775 **
   83776 ** This opcode leaves the cursor configured to move in reverse order,
   83777 ** from the end toward the beginning.  In other words, the cursor is
   83778 ** configured to use Prev, not Next.
   83779 **
   83780 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
   83781 ** opcode will always land on a record that equally equals the key, or
   83782 ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
   83783 ** opcode must be followed by an IdxGE opcode with the same arguments.
   83784 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
   83785 ** IdxGE opcode will be used on subsequent loop iterations.
   83786 **
   83787 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
   83788 */
   83789 case OP_SeekLT:         /* jump, in3 */
   83790 case OP_SeekLE:         /* jump, in3 */
   83791 case OP_SeekGE:         /* jump, in3 */
   83792 case OP_SeekGT: {       /* jump, in3 */
   83793   int res;           /* Comparison result */
   83794   int oc;            /* Opcode */
   83795   VdbeCursor *pC;    /* The cursor to seek */
   83796   UnpackedRecord r;  /* The key to seek for */
   83797   int nField;        /* Number of columns or fields in the key */
   83798   i64 iKey;          /* The rowid we are to seek to */
   83799   int eqOnly;        /* Only interested in == results */
   83800 
   83801   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   83802   assert( pOp->p2!=0 );
   83803   pC = p->apCsr[pOp->p1];
   83804   assert( pC!=0 );
   83805   assert( pC->eCurType==CURTYPE_BTREE );
   83806   assert( OP_SeekLE == OP_SeekLT+1 );
   83807   assert( OP_SeekGE == OP_SeekLT+2 );
   83808   assert( OP_SeekGT == OP_SeekLT+3 );
   83809   assert( pC->isOrdered );
   83810   assert( pC->uc.pCursor!=0 );
   83811   oc = pOp->opcode;
   83812   eqOnly = 0;
   83813   pC->nullRow = 0;
   83814 #ifdef SQLITE_DEBUG
   83815   pC->seekOp = pOp->opcode;
   83816 #endif
   83817 
   83818   if( pC->isTable ){
   83819     /* The BTREE_SEEK_EQ flag is only set on index cursors */
   83820     assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
   83821               || CORRUPT_DB );
   83822 
   83823     /* The input value in P3 might be of any type: integer, real, string,
   83824     ** blob, or NULL.  But it needs to be an integer before we can do
   83825     ** the seek, so convert it. */
   83826     pIn3 = &aMem[pOp->p3];
   83827     if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
   83828       applyNumericAffinity(pIn3, 0);
   83829     }
   83830     iKey = sqlite3VdbeIntValue(pIn3);
   83831 
   83832     /* If the P3 value could not be converted into an integer without
   83833     ** loss of information, then special processing is required... */
   83834     if( (pIn3->flags & MEM_Int)==0 ){
   83835       if( (pIn3->flags & MEM_Real)==0 ){
   83836         /* If the P3 value cannot be converted into any kind of a number,
   83837         ** then the seek is not possible, so jump to P2 */
   83838         VdbeBranchTaken(1,2); goto jump_to_p2;
   83839         break;
   83840       }
   83841 
   83842       /* If the approximation iKey is larger than the actual real search
   83843       ** term, substitute >= for > and < for <=. e.g. if the search term
   83844       ** is 4.9 and the integer approximation 5:
   83845       **
   83846       **        (x >  4.9)    ->     (x >= 5)
   83847       **        (x <= 4.9)    ->     (x <  5)
   83848       */
   83849       if( pIn3->u.r<(double)iKey ){
   83850         assert( OP_SeekGE==(OP_SeekGT-1) );
   83851         assert( OP_SeekLT==(OP_SeekLE-1) );
   83852         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
   83853         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
   83854       }
   83855 
   83856       /* If the approximation iKey is smaller than the actual real search
   83857       ** term, substitute <= for < and > for >=.  */
   83858       else if( pIn3->u.r>(double)iKey ){
   83859         assert( OP_SeekLE==(OP_SeekLT+1) );
   83860         assert( OP_SeekGT==(OP_SeekGE+1) );
   83861         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
   83862         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
   83863       }
   83864     }
   83865     rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
   83866     pC->movetoTarget = iKey;  /* Used by OP_Delete */
   83867     if( rc!=SQLITE_OK ){
   83868       goto abort_due_to_error;
   83869     }
   83870   }else{
   83871     /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
   83872     ** OP_SeekLE opcodes are allowed, and these must be immediately followed
   83873     ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
   83874     */
   83875     if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
   83876       eqOnly = 1;
   83877       assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
   83878       assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
   83879       assert( pOp[1].p1==pOp[0].p1 );
   83880       assert( pOp[1].p2==pOp[0].p2 );
   83881       assert( pOp[1].p3==pOp[0].p3 );
   83882       assert( pOp[1].p4.i==pOp[0].p4.i );
   83883     }
   83884 
   83885     nField = pOp->p4.i;
   83886     assert( pOp->p4type==P4_INT32 );
   83887     assert( nField>0 );
   83888     r.pKeyInfo = pC->pKeyInfo;
   83889     r.nField = (u16)nField;
   83890 
   83891     /* The next line of code computes as follows, only faster:
   83892     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
   83893     **     r.default_rc = -1;
   83894     **   }else{
   83895     **     r.default_rc = +1;
   83896     **   }
   83897     */
   83898     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
   83899     assert( oc!=OP_SeekGT || r.default_rc==-1 );
   83900     assert( oc!=OP_SeekLE || r.default_rc==-1 );
   83901     assert( oc!=OP_SeekGE || r.default_rc==+1 );
   83902     assert( oc!=OP_SeekLT || r.default_rc==+1 );
   83903 
   83904     r.aMem = &aMem[pOp->p3];
   83905 #ifdef SQLITE_DEBUG
   83906     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   83907 #endif
   83908     r.eqSeen = 0;
   83909     rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
   83910     if( rc!=SQLITE_OK ){
   83911       goto abort_due_to_error;
   83912     }
   83913     if( eqOnly && r.eqSeen==0 ){
   83914       assert( res!=0 );
   83915       goto seek_not_found;
   83916     }
   83917   }
   83918   pC->deferredMoveto = 0;
   83919   pC->cacheStatus = CACHE_STALE;
   83920 #ifdef SQLITE_TEST
   83921   sqlite3_search_count++;
   83922 #endif
   83923   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
   83924     if( res<0 || (res==0 && oc==OP_SeekGT) ){
   83925       res = 0;
   83926       rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
   83927       if( rc!=SQLITE_OK ){
   83928         if( rc==SQLITE_DONE ){
   83929           rc = SQLITE_OK;
   83930           res = 1;
   83931         }else{
   83932           goto abort_due_to_error;
   83933         }
   83934       }
   83935     }else{
   83936       res = 0;
   83937     }
   83938   }else{
   83939     assert( oc==OP_SeekLT || oc==OP_SeekLE );
   83940     if( res>0 || (res==0 && oc==OP_SeekLT) ){
   83941       res = 0;
   83942       rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
   83943       if( rc!=SQLITE_OK ){
   83944         if( rc==SQLITE_DONE ){
   83945           rc = SQLITE_OK;
   83946           res = 1;
   83947         }else{
   83948           goto abort_due_to_error;
   83949         }
   83950       }
   83951     }else{
   83952       /* res might be negative because the table is empty.  Check to
   83953       ** see if this is the case.
   83954       */
   83955       res = sqlite3BtreeEof(pC->uc.pCursor);
   83956     }
   83957   }
   83958 seek_not_found:
   83959   assert( pOp->p2>0 );
   83960   VdbeBranchTaken(res!=0,2);
   83961   if( res ){
   83962     goto jump_to_p2;
   83963   }else if( eqOnly ){
   83964     assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
   83965     pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
   83966   }
   83967   break;
   83968 }
   83969 
   83970 /* Opcode: Found P1 P2 P3 P4 *
   83971 ** Synopsis: key=r[P3@P4]
   83972 **
   83973 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   83974 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   83975 ** record.
   83976 **
   83977 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   83978 ** is a prefix of any entry in P1 then a jump is made to P2 and
   83979 ** P1 is left pointing at the matching entry.
   83980 **
   83981 ** This operation leaves the cursor in a state where it can be
   83982 ** advanced in the forward direction.  The Next instruction will work,
   83983 ** but not the Prev instruction.
   83984 **
   83985 ** See also: NotFound, NoConflict, NotExists. SeekGe
   83986 */
   83987 /* Opcode: NotFound P1 P2 P3 P4 *
   83988 ** Synopsis: key=r[P3@P4]
   83989 **
   83990 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   83991 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   83992 ** record.
   83993 **
   83994 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   83995 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
   83996 ** does contain an entry whose prefix matches the P3/P4 record then control
   83997 ** falls through to the next instruction and P1 is left pointing at the
   83998 ** matching entry.
   83999 **
   84000 ** This operation leaves the cursor in a state where it cannot be
   84001 ** advanced in either direction.  In other words, the Next and Prev
   84002 ** opcodes do not work after this operation.
   84003 **
   84004 ** See also: Found, NotExists, NoConflict
   84005 */
   84006 /* Opcode: NoConflict P1 P2 P3 P4 *
   84007 ** Synopsis: key=r[P3@P4]
   84008 **
   84009 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   84010 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   84011 ** record.
   84012 **
   84013 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   84014 ** contains any NULL value, jump immediately to P2.  If all terms of the
   84015 ** record are not-NULL then a check is done to determine if any row in the
   84016 ** P1 index btree has a matching key prefix.  If there are no matches, jump
   84017 ** immediately to P2.  If there is a match, fall through and leave the P1
   84018 ** cursor pointing to the matching row.
   84019 **
   84020 ** This opcode is similar to OP_NotFound with the exceptions that the
   84021 ** branch is always taken if any part of the search key input is NULL.
   84022 **
   84023 ** This operation leaves the cursor in a state where it cannot be
   84024 ** advanced in either direction.  In other words, the Next and Prev
   84025 ** opcodes do not work after this operation.
   84026 **
   84027 ** See also: NotFound, Found, NotExists
   84028 */
   84029 case OP_NoConflict:     /* jump, in3 */
   84030 case OP_NotFound:       /* jump, in3 */
   84031 case OP_Found: {        /* jump, in3 */
   84032   int alreadyExists;
   84033   int takeJump;
   84034   int ii;
   84035   VdbeCursor *pC;
   84036   int res;
   84037   UnpackedRecord *pFree;
   84038   UnpackedRecord *pIdxKey;
   84039   UnpackedRecord r;
   84040 
   84041 #ifdef SQLITE_TEST
   84042   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
   84043 #endif
   84044 
   84045   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84046   assert( pOp->p4type==P4_INT32 );
   84047   pC = p->apCsr[pOp->p1];
   84048   assert( pC!=0 );
   84049 #ifdef SQLITE_DEBUG
   84050   pC->seekOp = pOp->opcode;
   84051 #endif
   84052   pIn3 = &aMem[pOp->p3];
   84053   assert( pC->eCurType==CURTYPE_BTREE );
   84054   assert( pC->uc.pCursor!=0 );
   84055   assert( pC->isTable==0 );
   84056   if( pOp->p4.i>0 ){
   84057     r.pKeyInfo = pC->pKeyInfo;
   84058     r.nField = (u16)pOp->p4.i;
   84059     r.aMem = pIn3;
   84060 #ifdef SQLITE_DEBUG
   84061     for(ii=0; ii<r.nField; ii++){
   84062       assert( memIsValid(&r.aMem[ii]) );
   84063       assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
   84064       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
   84065     }
   84066 #endif
   84067     pIdxKey = &r;
   84068     pFree = 0;
   84069   }else{
   84070     assert( pIn3->flags & MEM_Blob );
   84071     rc = ExpandBlob(pIn3);
   84072     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   84073     if( rc ) goto no_mem;
   84074     pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
   84075     if( pIdxKey==0 ) goto no_mem;
   84076     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
   84077   }
   84078   pIdxKey->default_rc = 0;
   84079   takeJump = 0;
   84080   if( pOp->opcode==OP_NoConflict ){
   84081     /* For the OP_NoConflict opcode, take the jump if any of the
   84082     ** input fields are NULL, since any key with a NULL will not
   84083     ** conflict */
   84084     for(ii=0; ii<pIdxKey->nField; ii++){
   84085       if( pIdxKey->aMem[ii].flags & MEM_Null ){
   84086         takeJump = 1;
   84087         break;
   84088       }
   84089     }
   84090   }
   84091   rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
   84092   if( pFree ) sqlite3DbFreeNN(db, pFree);
   84093   if( rc!=SQLITE_OK ){
   84094     goto abort_due_to_error;
   84095   }
   84096   pC->seekResult = res;
   84097   alreadyExists = (res==0);
   84098   pC->nullRow = 1-alreadyExists;
   84099   pC->deferredMoveto = 0;
   84100   pC->cacheStatus = CACHE_STALE;
   84101   if( pOp->opcode==OP_Found ){
   84102     VdbeBranchTaken(alreadyExists!=0,2);
   84103     if( alreadyExists ) goto jump_to_p2;
   84104   }else{
   84105     VdbeBranchTaken(takeJump||alreadyExists==0,2);
   84106     if( takeJump || !alreadyExists ) goto jump_to_p2;
   84107   }
   84108   break;
   84109 }
   84110 
   84111 /* Opcode: SeekRowid P1 P2 P3 * *
   84112 ** Synopsis: intkey=r[P3]
   84113 **
   84114 ** P1 is the index of a cursor open on an SQL table btree (with integer
   84115 ** keys).  If register P3 does not contain an integer or if P1 does not
   84116 ** contain a record with rowid P3 then jump immediately to P2.
   84117 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
   84118 ** a record with rowid P3 then
   84119 ** leave the cursor pointing at that record and fall through to the next
   84120 ** instruction.
   84121 **
   84122 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
   84123 ** the P3 register must be guaranteed to contain an integer value.  With this
   84124 ** opcode, register P3 might not contain an integer.
   84125 **
   84126 ** The OP_NotFound opcode performs the same operation on index btrees
   84127 ** (with arbitrary multi-value keys).
   84128 **
   84129 ** This opcode leaves the cursor in a state where it cannot be advanced
   84130 ** in either direction.  In other words, the Next and Prev opcodes will
   84131 ** not work following this opcode.
   84132 **
   84133 ** See also: Found, NotFound, NoConflict, SeekRowid
   84134 */
   84135 /* Opcode: NotExists P1 P2 P3 * *
   84136 ** Synopsis: intkey=r[P3]
   84137 **
   84138 ** P1 is the index of a cursor open on an SQL table btree (with integer
   84139 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
   84140 ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
   84141 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
   84142 ** leave the cursor pointing at that record and fall through to the next
   84143 ** instruction.
   84144 **
   84145 ** The OP_SeekRowid opcode performs the same operation but also allows the
   84146 ** P3 register to contain a non-integer value, in which case the jump is
   84147 ** always taken.  This opcode requires that P3 always contain an integer.
   84148 **
   84149 ** The OP_NotFound opcode performs the same operation on index btrees
   84150 ** (with arbitrary multi-value keys).
   84151 **
   84152 ** This opcode leaves the cursor in a state where it cannot be advanced
   84153 ** in either direction.  In other words, the Next and Prev opcodes will
   84154 ** not work following this opcode.
   84155 **
   84156 ** See also: Found, NotFound, NoConflict, SeekRowid
   84157 */
   84158 case OP_SeekRowid: {        /* jump, in3 */
   84159   VdbeCursor *pC;
   84160   BtCursor *pCrsr;
   84161   int res;
   84162   u64 iKey;
   84163 
   84164   pIn3 = &aMem[pOp->p3];
   84165   if( (pIn3->flags & MEM_Int)==0 ){
   84166     applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
   84167     if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
   84168   }
   84169   /* Fall through into OP_NotExists */
   84170 case OP_NotExists:          /* jump, in3 */
   84171   pIn3 = &aMem[pOp->p3];
   84172   assert( pIn3->flags & MEM_Int );
   84173   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84174   pC = p->apCsr[pOp->p1];
   84175   assert( pC!=0 );
   84176 #ifdef SQLITE_DEBUG
   84177   pC->seekOp = 0;
   84178 #endif
   84179   assert( pC->isTable );
   84180   assert( pC->eCurType==CURTYPE_BTREE );
   84181   pCrsr = pC->uc.pCursor;
   84182   assert( pCrsr!=0 );
   84183   res = 0;
   84184   iKey = pIn3->u.i;
   84185   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
   84186   assert( rc==SQLITE_OK || res==0 );
   84187   pC->movetoTarget = iKey;  /* Used by OP_Delete */
   84188   pC->nullRow = 0;
   84189   pC->cacheStatus = CACHE_STALE;
   84190   pC->deferredMoveto = 0;
   84191   VdbeBranchTaken(res!=0,2);
   84192   pC->seekResult = res;
   84193   if( res!=0 ){
   84194     assert( rc==SQLITE_OK );
   84195     if( pOp->p2==0 ){
   84196       rc = SQLITE_CORRUPT_BKPT;
   84197     }else{
   84198       goto jump_to_p2;
   84199     }
   84200   }
   84201   if( rc ) goto abort_due_to_error;
   84202   break;
   84203 }
   84204 
   84205 /* Opcode: Sequence P1 P2 * * *
   84206 ** Synopsis: r[P2]=cursor[P1].ctr++
   84207 **
   84208 ** Find the next available sequence number for cursor P1.
   84209 ** Write the sequence number into register P2.
   84210 ** The sequence number on the cursor is incremented after this
   84211 ** instruction.
   84212 */
   84213 case OP_Sequence: {           /* out2 */
   84214   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84215   assert( p->apCsr[pOp->p1]!=0 );
   84216   assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
   84217   pOut = out2Prerelease(p, pOp);
   84218   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
   84219   break;
   84220 }
   84221 
   84222 
   84223 /* Opcode: NewRowid P1 P2 P3 * *
   84224 ** Synopsis: r[P2]=rowid
   84225 **
   84226 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
   84227 ** The record number is not previously used as a key in the database
   84228 ** table that cursor P1 points to.  The new record number is written
   84229 ** written to register P2.
   84230 **
   84231 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
   84232 ** the largest previously generated record number. No new record numbers are
   84233 ** allowed to be less than this value. When this value reaches its maximum,
   84234 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
   84235 ** generated record number. This P3 mechanism is used to help implement the
   84236 ** AUTOINCREMENT feature.
   84237 */
   84238 case OP_NewRowid: {           /* out2 */
   84239   i64 v;                 /* The new rowid */
   84240   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   84241   int res;               /* Result of an sqlite3BtreeLast() */
   84242   int cnt;               /* Counter to limit the number of searches */
   84243   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   84244   VdbeFrame *pFrame;     /* Root frame of VDBE */
   84245 
   84246   v = 0;
   84247   res = 0;
   84248   pOut = out2Prerelease(p, pOp);
   84249   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84250   pC = p->apCsr[pOp->p1];
   84251   assert( pC!=0 );
   84252   assert( pC->eCurType==CURTYPE_BTREE );
   84253   assert( pC->uc.pCursor!=0 );
   84254   {
   84255     /* The next rowid or record number (different terms for the same
   84256     ** thing) is obtained in a two-step algorithm.
   84257     **
   84258     ** First we attempt to find the largest existing rowid and add one
   84259     ** to that.  But if the largest existing rowid is already the maximum
   84260     ** positive integer, we have to fall through to the second
   84261     ** probabilistic algorithm
   84262     **
   84263     ** The second algorithm is to select a rowid at random and see if
   84264     ** it already exists in the table.  If it does not exist, we have
   84265     ** succeeded.  If the random rowid does exist, we select a new one
   84266     ** and try again, up to 100 times.
   84267     */
   84268     assert( pC->isTable );
   84269 
   84270 #ifdef SQLITE_32BIT_ROWID
   84271 #   define MAX_ROWID 0x7fffffff
   84272 #else
   84273     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
   84274     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
   84275     ** to provide the constant while making all compilers happy.
   84276     */
   84277 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
   84278 #endif
   84279 
   84280     if( !pC->useRandomRowid ){
   84281       rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
   84282       if( rc!=SQLITE_OK ){
   84283         goto abort_due_to_error;
   84284       }
   84285       if( res ){
   84286         v = 1;   /* IMP: R-61914-48074 */
   84287       }else{
   84288         assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
   84289         v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
   84290         if( v>=MAX_ROWID ){
   84291           pC->useRandomRowid = 1;
   84292         }else{
   84293           v++;   /* IMP: R-29538-34987 */
   84294         }
   84295       }
   84296     }
   84297 
   84298 #ifndef SQLITE_OMIT_AUTOINCREMENT
   84299     if( pOp->p3 ){
   84300       /* Assert that P3 is a valid memory cell. */
   84301       assert( pOp->p3>0 );
   84302       if( p->pFrame ){
   84303         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   84304         /* Assert that P3 is a valid memory cell. */
   84305         assert( pOp->p3<=pFrame->nMem );
   84306         pMem = &pFrame->aMem[pOp->p3];
   84307       }else{
   84308         /* Assert that P3 is a valid memory cell. */
   84309         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
   84310         pMem = &aMem[pOp->p3];
   84311         memAboutToChange(p, pMem);
   84312       }
   84313       assert( memIsValid(pMem) );
   84314 
   84315       REGISTER_TRACE(pOp->p3, pMem);
   84316       sqlite3VdbeMemIntegerify(pMem);
   84317       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
   84318       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
   84319         rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
   84320         goto abort_due_to_error;
   84321       }
   84322       if( v<pMem->u.i+1 ){
   84323         v = pMem->u.i + 1;
   84324       }
   84325       pMem->u.i = v;
   84326     }
   84327 #endif
   84328     if( pC->useRandomRowid ){
   84329       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
   84330       ** largest possible integer (9223372036854775807) then the database
   84331       ** engine starts picking positive candidate ROWIDs at random until
   84332       ** it finds one that is not previously used. */
   84333       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
   84334                              ** an AUTOINCREMENT table. */
   84335       cnt = 0;
   84336       do{
   84337         sqlite3_randomness(sizeof(v), &v);
   84338         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
   84339       }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
   84340                                                  0, &res))==SQLITE_OK)
   84341             && (res==0)
   84342             && (++cnt<100));
   84343       if( rc ) goto abort_due_to_error;
   84344       if( res==0 ){
   84345         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
   84346         goto abort_due_to_error;
   84347       }
   84348       assert( v>0 );  /* EV: R-40812-03570 */
   84349     }
   84350     pC->deferredMoveto = 0;
   84351     pC->cacheStatus = CACHE_STALE;
   84352   }
   84353   pOut->u.i = v;
   84354   break;
   84355 }
   84356 
   84357 /* Opcode: Insert P1 P2 P3 P4 P5
   84358 ** Synopsis: intkey=r[P3] data=r[P2]
   84359 **
   84360 ** Write an entry into the table of cursor P1.  A new entry is
   84361 ** created if it doesn't already exist or the data for an existing
   84362 ** entry is overwritten.  The data is the value MEM_Blob stored in register
   84363 ** number P2. The key is stored in register P3. The key must
   84364 ** be a MEM_Int.
   84365 **
   84366 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
   84367 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
   84368 ** then rowid is stored for subsequent return by the
   84369 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
   84370 **
   84371 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
   84372 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
   84373 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
   84374 ** seeks on the cursor or if the most recent seek used a key equal to P3.
   84375 **
   84376 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
   84377 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
   84378 ** is part of an INSERT operation.  The difference is only important to
   84379 ** the update hook.
   84380 **
   84381 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
   84382 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
   84383 ** following a successful insert.
   84384 **
   84385 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
   84386 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
   84387 ** and register P2 becomes ephemeral.  If the cursor is changed, the
   84388 ** value of register P2 will then change.  Make sure this does not
   84389 ** cause any problems.)
   84390 **
   84391 ** This instruction only works on tables.  The equivalent instruction
   84392 ** for indices is OP_IdxInsert.
   84393 */
   84394 /* Opcode: InsertInt P1 P2 P3 P4 P5
   84395 ** Synopsis: intkey=P3 data=r[P2]
   84396 **
   84397 ** This works exactly like OP_Insert except that the key is the
   84398 ** integer value P3, not the value of the integer stored in register P3.
   84399 */
   84400 case OP_Insert:
   84401 case OP_InsertInt: {
   84402   Mem *pData;       /* MEM cell holding data for the record to be inserted */
   84403   Mem *pKey;        /* MEM cell holding key  for the record */
   84404   VdbeCursor *pC;   /* Cursor to table into which insert is written */
   84405   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   84406   const char *zDb;  /* database name - used by the update hook */
   84407   Table *pTab;      /* Table structure - used by update and pre-update hooks */
   84408   BtreePayload x;   /* Payload to be inserted */
   84409 
   84410   pData = &aMem[pOp->p2];
   84411   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84412   assert( memIsValid(pData) );
   84413   pC = p->apCsr[pOp->p1];
   84414   assert( pC!=0 );
   84415   assert( pC->eCurType==CURTYPE_BTREE );
   84416   assert( pC->uc.pCursor!=0 );
   84417   assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
   84418   assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
   84419   REGISTER_TRACE(pOp->p2, pData);
   84420 
   84421   if( pOp->opcode==OP_Insert ){
   84422     pKey = &aMem[pOp->p3];
   84423     assert( pKey->flags & MEM_Int );
   84424     assert( memIsValid(pKey) );
   84425     REGISTER_TRACE(pOp->p3, pKey);
   84426     x.nKey = pKey->u.i;
   84427   }else{
   84428     assert( pOp->opcode==OP_InsertInt );
   84429     x.nKey = pOp->p3;
   84430   }
   84431 
   84432   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
   84433     assert( pC->iDb>=0 );
   84434     zDb = db->aDb[pC->iDb].zDbSName;
   84435     pTab = pOp->p4.pTab;
   84436     assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
   84437   }else{
   84438     pTab = 0;
   84439     zDb = 0;  /* Not needed.  Silence a compiler warning. */
   84440   }
   84441 
   84442 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   84443   /* Invoke the pre-update hook, if any */
   84444   if( pTab ){
   84445     if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
   84446       sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
   84447     }
   84448     if( db->xUpdateCallback==0 || pTab->aCol==0 ){
   84449       /* Prevent post-update hook from running in cases when it should not */
   84450       pTab = 0;
   84451     }
   84452   }
   84453   if( pOp->p5 & OPFLAG_ISNOOP ) break;
   84454 #endif
   84455 
   84456   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   84457   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
   84458   assert( pData->flags & (MEM_Blob|MEM_Str) );
   84459   x.pData = pData->z;
   84460   x.nData = pData->n;
   84461   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
   84462   if( pData->flags & MEM_Zero ){
   84463     x.nZero = pData->u.nZero;
   84464   }else{
   84465     x.nZero = 0;
   84466   }
   84467   x.pKey = 0;
   84468   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
   84469       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
   84470   );
   84471   pC->deferredMoveto = 0;
   84472   pC->cacheStatus = CACHE_STALE;
   84473 
   84474   /* Invoke the update-hook if required. */
   84475   if( rc ) goto abort_due_to_error;
   84476   if( pTab ){
   84477     assert( db->xUpdateCallback!=0 );
   84478     assert( pTab->aCol!=0 );
   84479     db->xUpdateCallback(db->pUpdateArg,
   84480            (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
   84481            zDb, pTab->zName, x.nKey);
   84482   }
   84483   break;
   84484 }
   84485 
   84486 /* Opcode: Delete P1 P2 P3 P4 P5
   84487 **
   84488 ** Delete the record at which the P1 cursor is currently pointing.
   84489 **
   84490 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
   84491 ** the cursor will be left pointing at  either the next or the previous
   84492 ** record in the table. If it is left pointing at the next record, then
   84493 ** the next Next instruction will be a no-op. As a result, in this case
   84494 ** it is ok to delete a record from within a Next loop. If
   84495 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
   84496 ** left in an undefined state.
   84497 **
   84498 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
   84499 ** delete one of several associated with deleting a table row and all its
   84500 ** associated index entries.  Exactly one of those deletes is the "primary"
   84501 ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
   84502 ** marked with the AUXDELETE flag.
   84503 **
   84504 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
   84505 ** change count is incremented (otherwise not).
   84506 **
   84507 ** P1 must not be pseudo-table.  It has to be a real table with
   84508 ** multiple rows.
   84509 **
   84510 ** If P4 is not NULL then it points to a Table object. In this case either
   84511 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
   84512 ** have been positioned using OP_NotFound prior to invoking this opcode in
   84513 ** this case. Specifically, if one is configured, the pre-update hook is
   84514 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
   84515 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
   84516 **
   84517 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
   84518 ** of the memory cell that contains the value that the rowid of the row will
   84519 ** be set to by the update.
   84520 */
   84521 case OP_Delete: {
   84522   VdbeCursor *pC;
   84523   const char *zDb;
   84524   Table *pTab;
   84525   int opflags;
   84526 
   84527   opflags = pOp->p2;
   84528   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84529   pC = p->apCsr[pOp->p1];
   84530   assert( pC!=0 );
   84531   assert( pC->eCurType==CURTYPE_BTREE );
   84532   assert( pC->uc.pCursor!=0 );
   84533   assert( pC->deferredMoveto==0 );
   84534 
   84535 #ifdef SQLITE_DEBUG
   84536   if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
   84537     /* If p5 is zero, the seek operation that positioned the cursor prior to
   84538     ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
   84539     ** the row that is being deleted */
   84540     i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
   84541     assert( pC->movetoTarget==iKey );
   84542   }
   84543 #endif
   84544 
   84545   /* If the update-hook or pre-update-hook will be invoked, set zDb to
   84546   ** the name of the db to pass as to it. Also set local pTab to a copy
   84547   ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
   84548   ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
   84549   ** VdbeCursor.movetoTarget to the current rowid.  */
   84550   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
   84551     assert( pC->iDb>=0 );
   84552     assert( pOp->p4.pTab!=0 );
   84553     zDb = db->aDb[pC->iDb].zDbSName;
   84554     pTab = pOp->p4.pTab;
   84555     if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
   84556       pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
   84557     }
   84558   }else{
   84559     zDb = 0;   /* Not needed.  Silence a compiler warning. */
   84560     pTab = 0;  /* Not needed.  Silence a compiler warning. */
   84561   }
   84562 
   84563 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   84564   /* Invoke the pre-update-hook if required. */
   84565   if( db->xPreUpdateCallback && pOp->p4.pTab ){
   84566     assert( !(opflags & OPFLAG_ISUPDATE)
   84567          || HasRowid(pTab)==0
   84568          || (aMem[pOp->p3].flags & MEM_Int)
   84569     );
   84570     sqlite3VdbePreUpdateHook(p, pC,
   84571         (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
   84572         zDb, pTab, pC->movetoTarget,
   84573         pOp->p3
   84574     );
   84575   }
   84576   if( opflags & OPFLAG_ISNOOP ) break;
   84577 #endif
   84578 
   84579   /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
   84580   assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
   84581   assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
   84582   assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
   84583 
   84584 #ifdef SQLITE_DEBUG
   84585   if( p->pFrame==0 ){
   84586     if( pC->isEphemeral==0
   84587         && (pOp->p5 & OPFLAG_AUXDELETE)==0
   84588         && (pC->wrFlag & OPFLAG_FORDELETE)==0
   84589       ){
   84590       nExtraDelete++;
   84591     }
   84592     if( pOp->p2 & OPFLAG_NCHANGE ){
   84593       nExtraDelete--;
   84594     }
   84595   }
   84596 #endif
   84597 
   84598   rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
   84599   pC->cacheStatus = CACHE_STALE;
   84600   pC->seekResult = 0;
   84601   if( rc ) goto abort_due_to_error;
   84602 
   84603   /* Invoke the update-hook if required. */
   84604   if( opflags & OPFLAG_NCHANGE ){
   84605     p->nChange++;
   84606     if( db->xUpdateCallback && HasRowid(pTab) ){
   84607       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
   84608           pC->movetoTarget);
   84609       assert( pC->iDb>=0 );
   84610     }
   84611   }
   84612 
   84613   break;
   84614 }
   84615 /* Opcode: ResetCount * * * * *
   84616 **
   84617 ** The value of the change counter is copied to the database handle
   84618 ** change counter (returned by subsequent calls to sqlite3_changes()).
   84619 ** Then the VMs internal change counter resets to 0.
   84620 ** This is used by trigger programs.
   84621 */
   84622 case OP_ResetCount: {
   84623   sqlite3VdbeSetChanges(db, p->nChange);
   84624   p->nChange = 0;
   84625   break;
   84626 }
   84627 
   84628 /* Opcode: SorterCompare P1 P2 P3 P4
   84629 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
   84630 **
   84631 ** P1 is a sorter cursor. This instruction compares a prefix of the
   84632 ** record blob in register P3 against a prefix of the entry that
   84633 ** the sorter cursor currently points to.  Only the first P4 fields
   84634 ** of r[P3] and the sorter record are compared.
   84635 **
   84636 ** If either P3 or the sorter contains a NULL in one of their significant
   84637 ** fields (not counting the P4 fields at the end which are ignored) then
   84638 ** the comparison is assumed to be equal.
   84639 **
   84640 ** Fall through to next instruction if the two records compare equal to
   84641 ** each other.  Jump to P2 if they are different.
   84642 */
   84643 case OP_SorterCompare: {
   84644   VdbeCursor *pC;
   84645   int res;
   84646   int nKeyCol;
   84647 
   84648   pC = p->apCsr[pOp->p1];
   84649   assert( isSorter(pC) );
   84650   assert( pOp->p4type==P4_INT32 );
   84651   pIn3 = &aMem[pOp->p3];
   84652   nKeyCol = pOp->p4.i;
   84653   res = 0;
   84654   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
   84655   VdbeBranchTaken(res!=0,2);
   84656   if( rc ) goto abort_due_to_error;
   84657   if( res ) goto jump_to_p2;
   84658   break;
   84659 };
   84660 
   84661 /* Opcode: SorterData P1 P2 P3 * *
   84662 ** Synopsis: r[P2]=data
   84663 **
   84664 ** Write into register P2 the current sorter data for sorter cursor P1.
   84665 ** Then clear the column header cache on cursor P3.
   84666 **
   84667 ** This opcode is normally use to move a record out of the sorter and into
   84668 ** a register that is the source for a pseudo-table cursor created using
   84669 ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
   84670 ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
   84671 ** us from having to issue a separate NullRow instruction to clear that cache.
   84672 */
   84673 case OP_SorterData: {
   84674   VdbeCursor *pC;
   84675 
   84676   pOut = &aMem[pOp->p2];
   84677   pC = p->apCsr[pOp->p1];
   84678   assert( isSorter(pC) );
   84679   rc = sqlite3VdbeSorterRowkey(pC, pOut);
   84680   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
   84681   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84682   if( rc ) goto abort_due_to_error;
   84683   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
   84684   break;
   84685 }
   84686 
   84687 /* Opcode: RowData P1 P2 P3 * *
   84688 ** Synopsis: r[P2]=data
   84689 **
   84690 ** Write into register P2 the complete row content for the row at
   84691 ** which cursor P1 is currently pointing.
   84692 ** There is no interpretation of the data.
   84693 ** It is just copied onto the P2 register exactly as
   84694 ** it is found in the database file.
   84695 **
   84696 ** If cursor P1 is an index, then the content is the key of the row.
   84697 ** If cursor P2 is a table, then the content extracted is the data.
   84698 **
   84699 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   84700 ** of a real table, not a pseudo-table.
   84701 **
   84702 ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
   84703 ** into the database page.  That means that the content of the output
   84704 ** register will be invalidated as soon as the cursor moves - including
   84705 ** moves caused by other cursors that "save" the the current cursors
   84706 ** position in order that they can write to the same table.  If P3==0
   84707 ** then a copy of the data is made into memory.  P3!=0 is faster, but
   84708 ** P3==0 is safer.
   84709 **
   84710 ** If P3!=0 then the content of the P2 register is unsuitable for use
   84711 ** in OP_Result and any OP_Result will invalidate the P2 register content.
   84712 ** The P2 register content is invalidated by opcodes like OP_Function or
   84713 ** by any use of another cursor pointing to the same table.
   84714 */
   84715 case OP_RowData: {
   84716   VdbeCursor *pC;
   84717   BtCursor *pCrsr;
   84718   u32 n;
   84719 
   84720   pOut = out2Prerelease(p, pOp);
   84721 
   84722   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84723   pC = p->apCsr[pOp->p1];
   84724   assert( pC!=0 );
   84725   assert( pC->eCurType==CURTYPE_BTREE );
   84726   assert( isSorter(pC)==0 );
   84727   assert( pC->nullRow==0 );
   84728   assert( pC->uc.pCursor!=0 );
   84729   pCrsr = pC->uc.pCursor;
   84730 
   84731   /* The OP_RowData opcodes always follow OP_NotExists or
   84732   ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
   84733   ** that might invalidate the cursor.
   84734   ** If this where not the case, on of the following assert()s
   84735   ** would fail.  Should this ever change (because of changes in the code
   84736   ** generator) then the fix would be to insert a call to
   84737   ** sqlite3VdbeCursorMoveto().
   84738   */
   84739   assert( pC->deferredMoveto==0 );
   84740   assert( sqlite3BtreeCursorIsValid(pCrsr) );
   84741 #if 0  /* Not required due to the previous to assert() statements */
   84742   rc = sqlite3VdbeCursorMoveto(pC);
   84743   if( rc!=SQLITE_OK ) goto abort_due_to_error;
   84744 #endif
   84745 
   84746   n = sqlite3BtreePayloadSize(pCrsr);
   84747   if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   84748     goto too_big;
   84749   }
   84750   testcase( n==0 );
   84751   rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
   84752   if( rc ) goto abort_due_to_error;
   84753   if( !pOp->p3 ) Deephemeralize(pOut);
   84754   UPDATE_MAX_BLOBSIZE(pOut);
   84755   REGISTER_TRACE(pOp->p2, pOut);
   84756   break;
   84757 }
   84758 
   84759 /* Opcode: Rowid P1 P2 * * *
   84760 ** Synopsis: r[P2]=rowid
   84761 **
   84762 ** Store in register P2 an integer which is the key of the table entry that
   84763 ** P1 is currently point to.
   84764 **
   84765 ** P1 can be either an ordinary table or a virtual table.  There used to
   84766 ** be a separate OP_VRowid opcode for use with virtual tables, but this
   84767 ** one opcode now works for both table types.
   84768 */
   84769 case OP_Rowid: {                 /* out2 */
   84770   VdbeCursor *pC;
   84771   i64 v;
   84772   sqlite3_vtab *pVtab;
   84773   const sqlite3_module *pModule;
   84774 
   84775   pOut = out2Prerelease(p, pOp);
   84776   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84777   pC = p->apCsr[pOp->p1];
   84778   assert( pC!=0 );
   84779   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
   84780   if( pC->nullRow ){
   84781     pOut->flags = MEM_Null;
   84782     break;
   84783   }else if( pC->deferredMoveto ){
   84784     v = pC->movetoTarget;
   84785 #ifndef SQLITE_OMIT_VIRTUALTABLE
   84786   }else if( pC->eCurType==CURTYPE_VTAB ){
   84787     assert( pC->uc.pVCur!=0 );
   84788     pVtab = pC->uc.pVCur->pVtab;
   84789     pModule = pVtab->pModule;
   84790     assert( pModule->xRowid );
   84791     rc = pModule->xRowid(pC->uc.pVCur, &v);
   84792     sqlite3VtabImportErrmsg(p, pVtab);
   84793     if( rc ) goto abort_due_to_error;
   84794 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   84795   }else{
   84796     assert( pC->eCurType==CURTYPE_BTREE );
   84797     assert( pC->uc.pCursor!=0 );
   84798     rc = sqlite3VdbeCursorRestore(pC);
   84799     if( rc ) goto abort_due_to_error;
   84800     if( pC->nullRow ){
   84801       pOut->flags = MEM_Null;
   84802       break;
   84803     }
   84804     v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
   84805   }
   84806   pOut->u.i = v;
   84807   break;
   84808 }
   84809 
   84810 /* Opcode: NullRow P1 * * * *
   84811 **
   84812 ** Move the cursor P1 to a null row.  Any OP_Column operations
   84813 ** that occur while the cursor is on the null row will always
   84814 ** write a NULL.
   84815 */
   84816 case OP_NullRow: {
   84817   VdbeCursor *pC;
   84818 
   84819   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84820   pC = p->apCsr[pOp->p1];
   84821   assert( pC!=0 );
   84822   pC->nullRow = 1;
   84823   pC->cacheStatus = CACHE_STALE;
   84824   if( pC->eCurType==CURTYPE_BTREE ){
   84825     assert( pC->uc.pCursor!=0 );
   84826     sqlite3BtreeClearCursor(pC->uc.pCursor);
   84827   }
   84828   break;
   84829 }
   84830 
   84831 /* Opcode: SeekEnd P1 * * * *
   84832 **
   84833 ** Position cursor P1 at the end of the btree for the purpose of
   84834 ** appending a new entry onto the btree.
   84835 **
   84836 ** It is assumed that the cursor is used only for appending and so
   84837 ** if the cursor is valid, then the cursor must already be pointing
   84838 ** at the end of the btree and so no changes are made to
   84839 ** the cursor.
   84840 */
   84841 /* Opcode: Last P1 P2 * * *
   84842 **
   84843 ** The next use of the Rowid or Column or Prev instruction for P1
   84844 ** will refer to the last entry in the database table or index.
   84845 ** If the table or index is empty and P2>0, then jump immediately to P2.
   84846 ** If P2 is 0 or if the table or index is not empty, fall through
   84847 ** to the following instruction.
   84848 **
   84849 ** This opcode leaves the cursor configured to move in reverse order,
   84850 ** from the end toward the beginning.  In other words, the cursor is
   84851 ** configured to use Prev, not Next.
   84852 */
   84853 case OP_SeekEnd:
   84854 case OP_Last: {        /* jump */
   84855   VdbeCursor *pC;
   84856   BtCursor *pCrsr;
   84857   int res;
   84858 
   84859   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84860   pC = p->apCsr[pOp->p1];
   84861   assert( pC!=0 );
   84862   assert( pC->eCurType==CURTYPE_BTREE );
   84863   pCrsr = pC->uc.pCursor;
   84864   res = 0;
   84865   assert( pCrsr!=0 );
   84866 #ifdef SQLITE_DEBUG
   84867   pC->seekOp = pOp->opcode;
   84868 #endif
   84869   if( pOp->opcode==OP_SeekEnd ){
   84870     assert( pOp->p2==0 );
   84871     pC->seekResult = -1;
   84872     if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
   84873       break;
   84874     }
   84875   }
   84876   rc = sqlite3BtreeLast(pCrsr, &res);
   84877   pC->nullRow = (u8)res;
   84878   pC->deferredMoveto = 0;
   84879   pC->cacheStatus = CACHE_STALE;
   84880   if( rc ) goto abort_due_to_error;
   84881   if( pOp->p2>0 ){
   84882     VdbeBranchTaken(res!=0,2);
   84883     if( res ) goto jump_to_p2;
   84884   }
   84885   break;
   84886 }
   84887 
   84888 /* Opcode: IfSmaller P1 P2 P3 * *
   84889 **
   84890 ** Estimate the number of rows in the table P1.  Jump to P2 if that
   84891 ** estimate is less than approximately 2**(0.1*P3).
   84892 */
   84893 case OP_IfSmaller: {        /* jump */
   84894   VdbeCursor *pC;
   84895   BtCursor *pCrsr;
   84896   int res;
   84897   i64 sz;
   84898 
   84899   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84900   pC = p->apCsr[pOp->p1];
   84901   assert( pC!=0 );
   84902   pCrsr = pC->uc.pCursor;
   84903   assert( pCrsr );
   84904   rc = sqlite3BtreeFirst(pCrsr, &res);
   84905   if( rc ) goto abort_due_to_error;
   84906   if( res==0 ){
   84907     sz = sqlite3BtreeRowCountEst(pCrsr);
   84908     if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
   84909   }
   84910   VdbeBranchTaken(res!=0,2);
   84911   if( res ) goto jump_to_p2;
   84912   break;
   84913 }
   84914 
   84915 
   84916 /* Opcode: SorterSort P1 P2 * * *
   84917 **
   84918 ** After all records have been inserted into the Sorter object
   84919 ** identified by P1, invoke this opcode to actually do the sorting.
   84920 ** Jump to P2 if there are no records to be sorted.
   84921 **
   84922 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
   84923 ** for Sorter objects.
   84924 */
   84925 /* Opcode: Sort P1 P2 * * *
   84926 **
   84927 ** This opcode does exactly the same thing as OP_Rewind except that
   84928 ** it increments an undocumented global variable used for testing.
   84929 **
   84930 ** Sorting is accomplished by writing records into a sorting index,
   84931 ** then rewinding that index and playing it back from beginning to
   84932 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
   84933 ** rewinding so that the global variable will be incremented and
   84934 ** regression tests can determine whether or not the optimizer is
   84935 ** correctly optimizing out sorts.
   84936 */
   84937 case OP_SorterSort:    /* jump */
   84938 case OP_Sort: {        /* jump */
   84939 #ifdef SQLITE_TEST
   84940   sqlite3_sort_count++;
   84941   sqlite3_search_count--;
   84942 #endif
   84943   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
   84944   /* Fall through into OP_Rewind */
   84945 }
   84946 /* Opcode: Rewind P1 P2 * * *
   84947 **
   84948 ** The next use of the Rowid or Column or Next instruction for P1
   84949 ** will refer to the first entry in the database table or index.
   84950 ** If the table or index is empty, jump immediately to P2.
   84951 ** If the table or index is not empty, fall through to the following
   84952 ** instruction.
   84953 **
   84954 ** This opcode leaves the cursor configured to move in forward order,
   84955 ** from the beginning toward the end.  In other words, the cursor is
   84956 ** configured to use Next, not Prev.
   84957 */
   84958 case OP_Rewind: {        /* jump */
   84959   VdbeCursor *pC;
   84960   BtCursor *pCrsr;
   84961   int res;
   84962 
   84963   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   84964   pC = p->apCsr[pOp->p1];
   84965   assert( pC!=0 );
   84966   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
   84967   res = 1;
   84968 #ifdef SQLITE_DEBUG
   84969   pC->seekOp = OP_Rewind;
   84970 #endif
   84971   if( isSorter(pC) ){
   84972     rc = sqlite3VdbeSorterRewind(pC, &res);
   84973   }else{
   84974     assert( pC->eCurType==CURTYPE_BTREE );
   84975     pCrsr = pC->uc.pCursor;
   84976     assert( pCrsr );
   84977     rc = sqlite3BtreeFirst(pCrsr, &res);
   84978     pC->deferredMoveto = 0;
   84979     pC->cacheStatus = CACHE_STALE;
   84980   }
   84981   if( rc ) goto abort_due_to_error;
   84982   pC->nullRow = (u8)res;
   84983   assert( pOp->p2>0 && pOp->p2<p->nOp );
   84984   VdbeBranchTaken(res!=0,2);
   84985   if( res ) goto jump_to_p2;
   84986   break;
   84987 }
   84988 
   84989 /* Opcode: Next P1 P2 P3 P4 P5
   84990 **
   84991 ** Advance cursor P1 so that it points to the next key/data pair in its
   84992 ** table or index.  If there are no more key/value pairs then fall through
   84993 ** to the following instruction.  But if the cursor advance was successful,
   84994 ** jump immediately to P2.
   84995 **
   84996 ** The Next opcode is only valid following an SeekGT, SeekGE, or
   84997 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
   84998 ** to follow SeekLT, SeekLE, or OP_Last.
   84999 **
   85000 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
   85001 ** been opened prior to this opcode or the program will segfault.
   85002 **
   85003 ** The P3 value is a hint to the btree implementation. If P3==1, that
   85004 ** means P1 is an SQL index and that this instruction could have been
   85005 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
   85006 ** always either 0 or 1.
   85007 **
   85008 ** P4 is always of type P4_ADVANCE. The function pointer points to
   85009 ** sqlite3BtreeNext().
   85010 **
   85011 ** If P5 is positive and the jump is taken, then event counter
   85012 ** number P5-1 in the prepared statement is incremented.
   85013 **
   85014 ** See also: Prev, NextIfOpen
   85015 */
   85016 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
   85017 **
   85018 ** This opcode works just like Next except that if cursor P1 is not
   85019 ** open it behaves a no-op.
   85020 */
   85021 /* Opcode: Prev P1 P2 P3 P4 P5
   85022 **
   85023 ** Back up cursor P1 so that it points to the previous key/data pair in its
   85024 ** table or index.  If there is no previous key/value pairs then fall through
   85025 ** to the following instruction.  But if the cursor backup was successful,
   85026 ** jump immediately to P2.
   85027 **
   85028 **
   85029 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
   85030 ** OP_Last opcode used to position the cursor.  Prev is not allowed
   85031 ** to follow SeekGT, SeekGE, or OP_Rewind.
   85032 **
   85033 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
   85034 ** not open then the behavior is undefined.
   85035 **
   85036 ** The P3 value is a hint to the btree implementation. If P3==1, that
   85037 ** means P1 is an SQL index and that this instruction could have been
   85038 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
   85039 ** always either 0 or 1.
   85040 **
   85041 ** P4 is always of type P4_ADVANCE. The function pointer points to
   85042 ** sqlite3BtreePrevious().
   85043 **
   85044 ** If P5 is positive and the jump is taken, then event counter
   85045 ** number P5-1 in the prepared statement is incremented.
   85046 */
   85047 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
   85048 **
   85049 ** This opcode works just like Prev except that if cursor P1 is not
   85050 ** open it behaves a no-op.
   85051 */
   85052 /* Opcode: SorterNext P1 P2 * * P5
   85053 **
   85054 ** This opcode works just like OP_Next except that P1 must be a
   85055 ** sorter object for which the OP_SorterSort opcode has been
   85056 ** invoked.  This opcode advances the cursor to the next sorted
   85057 ** record, or jumps to P2 if there are no more sorted records.
   85058 */
   85059 case OP_SorterNext: {  /* jump */
   85060   VdbeCursor *pC;
   85061 
   85062   pC = p->apCsr[pOp->p1];
   85063   assert( isSorter(pC) );
   85064   rc = sqlite3VdbeSorterNext(db, pC);
   85065   goto next_tail;
   85066 case OP_PrevIfOpen:    /* jump */
   85067 case OP_NextIfOpen:    /* jump */
   85068   if( p->apCsr[pOp->p1]==0 ) break;
   85069   /* Fall through */
   85070 case OP_Prev:          /* jump */
   85071 case OP_Next:          /* jump */
   85072   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   85073   assert( pOp->p5<ArraySize(p->aCounter) );
   85074   pC = p->apCsr[pOp->p1];
   85075   assert( pC!=0 );
   85076   assert( pC->deferredMoveto==0 );
   85077   assert( pC->eCurType==CURTYPE_BTREE );
   85078   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
   85079   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
   85080   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
   85081   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
   85082 
   85083   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
   85084   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
   85085   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
   85086        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
   85087        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
   85088   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
   85089        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
   85090        || pC->seekOp==OP_Last );
   85091 
   85092   rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
   85093 next_tail:
   85094   pC->cacheStatus = CACHE_STALE;
   85095   VdbeBranchTaken(rc==SQLITE_OK,2);
   85096   if( rc==SQLITE_OK ){
   85097     pC->nullRow = 0;
   85098     p->aCounter[pOp->p5]++;
   85099 #ifdef SQLITE_TEST
   85100     sqlite3_search_count++;
   85101 #endif
   85102     goto jump_to_p2_and_check_for_interrupt;
   85103   }
   85104   if( rc!=SQLITE_DONE ) goto abort_due_to_error;
   85105   rc = SQLITE_OK;
   85106   pC->nullRow = 1;
   85107   goto check_for_interrupt;
   85108 }
   85109 
   85110 /* Opcode: IdxInsert P1 P2 P3 P4 P5
   85111 ** Synopsis: key=r[P2]
   85112 **
   85113 ** Register P2 holds an SQL index key made using the
   85114 ** MakeRecord instructions.  This opcode writes that key
   85115 ** into the index P1.  Data for the entry is nil.
   85116 **
   85117 ** If P4 is not zero, then it is the number of values in the unpacked
   85118 ** key of reg(P2).  In that case, P3 is the index of the first register
   85119 ** for the unpacked key.  The availability of the unpacked key can sometimes
   85120 ** be an optimization.
   85121 **
   85122 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
   85123 ** that this insert is likely to be an append.
   85124 **
   85125 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
   85126 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
   85127 ** then the change counter is unchanged.
   85128 **
   85129 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
   85130 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
   85131 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
   85132 ** seeks on the cursor or if the most recent seek used a key equivalent
   85133 ** to P2.
   85134 **
   85135 ** This instruction only works for indices.  The equivalent instruction
   85136 ** for tables is OP_Insert.
   85137 */
   85138 /* Opcode: SorterInsert P1 P2 * * *
   85139 ** Synopsis: key=r[P2]
   85140 **
   85141 ** Register P2 holds an SQL index key made using the
   85142 ** MakeRecord instructions.  This opcode writes that key
   85143 ** into the sorter P1.  Data for the entry is nil.
   85144 */
   85145 case OP_SorterInsert:       /* in2 */
   85146 case OP_IdxInsert: {        /* in2 */
   85147   VdbeCursor *pC;
   85148   BtreePayload x;
   85149 
   85150   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   85151   pC = p->apCsr[pOp->p1];
   85152   assert( pC!=0 );
   85153   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
   85154   pIn2 = &aMem[pOp->p2];
   85155   assert( pIn2->flags & MEM_Blob );
   85156   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   85157   assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
   85158   assert( pC->isTable==0 );
   85159   rc = ExpandBlob(pIn2);
   85160   if( rc ) goto abort_due_to_error;
   85161   if( pOp->opcode==OP_SorterInsert ){
   85162     rc = sqlite3VdbeSorterWrite(pC, pIn2);
   85163   }else{
   85164     x.nKey = pIn2->n;
   85165     x.pKey = pIn2->z;
   85166     x.aMem = aMem + pOp->p3;
   85167     x.nMem = (u16)pOp->p4.i;
   85168     rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
   85169          (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
   85170         ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
   85171         );
   85172     assert( pC->deferredMoveto==0 );
   85173     pC->cacheStatus = CACHE_STALE;
   85174   }
   85175   if( rc) goto abort_due_to_error;
   85176   break;
   85177 }
   85178 
   85179 /* Opcode: IdxDelete P1 P2 P3 * *
   85180 ** Synopsis: key=r[P2@P3]
   85181 **
   85182 ** The content of P3 registers starting at register P2 form
   85183 ** an unpacked index key. This opcode removes that entry from the
   85184 ** index opened by cursor P1.
   85185 */
   85186 case OP_IdxDelete: {
   85187   VdbeCursor *pC;
   85188   BtCursor *pCrsr;
   85189   int res;
   85190   UnpackedRecord r;
   85191 
   85192   assert( pOp->p3>0 );
   85193   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
   85194   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   85195   pC = p->apCsr[pOp->p1];
   85196   assert( pC!=0 );
   85197   assert( pC->eCurType==CURTYPE_BTREE );
   85198   pCrsr = pC->uc.pCursor;
   85199   assert( pCrsr!=0 );
   85200   assert( pOp->p5==0 );
   85201   r.pKeyInfo = pC->pKeyInfo;
   85202   r.nField = (u16)pOp->p3;
   85203   r.default_rc = 0;
   85204   r.aMem = &aMem[pOp->p2];
   85205   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
   85206   if( rc ) goto abort_due_to_error;
   85207   if( res==0 ){
   85208     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
   85209     if( rc ) goto abort_due_to_error;
   85210   }
   85211   assert( pC->deferredMoveto==0 );
   85212   pC->cacheStatus = CACHE_STALE;
   85213   pC->seekResult = 0;
   85214   break;
   85215 }
   85216 
   85217 /* Opcode: DeferredSeek P1 * P3 P4 *
   85218 ** Synopsis: Move P3 to P1.rowid if needed
   85219 **
   85220 ** P1 is an open index cursor and P3 is a cursor on the corresponding
   85221 ** table.  This opcode does a deferred seek of the P3 table cursor
   85222 ** to the row that corresponds to the current row of P1.
   85223 **
   85224 ** This is a deferred seek.  Nothing actually happens until
   85225 ** the cursor is used to read a record.  That way, if no reads
   85226 ** occur, no unnecessary I/O happens.
   85227 **
   85228 ** P4 may be an array of integers (type P4_INTARRAY) containing
   85229 ** one entry for each column in the P3 table.  If array entry a(i)
   85230 ** is non-zero, then reading column a(i)-1 from cursor P3 is
   85231 ** equivalent to performing the deferred seek and then reading column i
   85232 ** from P1.  This information is stored in P3 and used to redirect
   85233 ** reads against P3 over to P1, thus possibly avoiding the need to
   85234 ** seek and read cursor P3.
   85235 */
   85236 /* Opcode: IdxRowid P1 P2 * * *
   85237 ** Synopsis: r[P2]=rowid
   85238 **
   85239 ** Write into register P2 an integer which is the last entry in the record at
   85240 ** the end of the index key pointed to by cursor P1.  This integer should be
   85241 ** the rowid of the table entry to which this index entry points.
   85242 **
   85243 ** See also: Rowid, MakeRecord.
   85244 */
   85245 case OP_DeferredSeek:
   85246 case OP_IdxRowid: {           /* out2 */
   85247   VdbeCursor *pC;             /* The P1 index cursor */
   85248   VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
   85249   i64 rowid;                  /* Rowid that P1 current points to */
   85250 
   85251   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   85252   pC = p->apCsr[pOp->p1];
   85253   assert( pC!=0 );
   85254   assert( pC->eCurType==CURTYPE_BTREE );
   85255   assert( pC->uc.pCursor!=0 );
   85256   assert( pC->isTable==0 );
   85257   assert( pC->deferredMoveto==0 );
   85258   assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
   85259 
   85260   /* The IdxRowid and Seek opcodes are combined because of the commonality
   85261   ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
   85262   rc = sqlite3VdbeCursorRestore(pC);
   85263 
   85264   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
   85265   ** out from under the cursor.  That will never happens for an IdxRowid
   85266   ** or Seek opcode */
   85267   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   85268 
   85269   if( !pC->nullRow ){
   85270     rowid = 0;  /* Not needed.  Only used to silence a warning. */
   85271     rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
   85272     if( rc!=SQLITE_OK ){
   85273       goto abort_due_to_error;
   85274     }
   85275     if( pOp->opcode==OP_DeferredSeek ){
   85276       assert( pOp->p3>=0 && pOp->p3<p->nCursor );
   85277       pTabCur = p->apCsr[pOp->p3];
   85278       assert( pTabCur!=0 );
   85279       assert( pTabCur->eCurType==CURTYPE_BTREE );
   85280       assert( pTabCur->uc.pCursor!=0 );
   85281       assert( pTabCur->isTable );
   85282       pTabCur->nullRow = 0;
   85283       pTabCur->movetoTarget = rowid;
   85284       pTabCur->deferredMoveto = 1;
   85285       assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
   85286       pTabCur->aAltMap = pOp->p4.ai;
   85287       pTabCur->pAltCursor = pC;
   85288     }else{
   85289       pOut = out2Prerelease(p, pOp);
   85290       pOut->u.i = rowid;
   85291     }
   85292   }else{
   85293     assert( pOp->opcode==OP_IdxRowid );
   85294     sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
   85295   }
   85296   break;
   85297 }
   85298 
   85299 /* Opcode: IdxGE P1 P2 P3 P4 P5
   85300 ** Synopsis: key=r[P3@P4]
   85301 **
   85302 ** The P4 register values beginning with P3 form an unpacked index
   85303 ** key that omits the PRIMARY KEY.  Compare this key value against the index
   85304 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
   85305 ** fields at the end.
   85306 **
   85307 ** If the P1 index entry is greater than or equal to the key value
   85308 ** then jump to P2.  Otherwise fall through to the next instruction.
   85309 */
   85310 /* Opcode: IdxGT P1 P2 P3 P4 P5
   85311 ** Synopsis: key=r[P3@P4]
   85312 **
   85313 ** The P4 register values beginning with P3 form an unpacked index
   85314 ** key that omits the PRIMARY KEY.  Compare this key value against the index
   85315 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
   85316 ** fields at the end.
   85317 **
   85318 ** If the P1 index entry is greater than the key value
   85319 ** then jump to P2.  Otherwise fall through to the next instruction.
   85320 */
   85321 /* Opcode: IdxLT P1 P2 P3 P4 P5
   85322 ** Synopsis: key=r[P3@P4]
   85323 **
   85324 ** The P4 register values beginning with P3 form an unpacked index
   85325 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
   85326 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
   85327 ** ROWID on the P1 index.
   85328 **
   85329 ** If the P1 index entry is less than the key value then jump to P2.
   85330 ** Otherwise fall through to the next instruction.
   85331 */
   85332 /* Opcode: IdxLE P1 P2 P3 P4 P5
   85333 ** Synopsis: key=r[P3@P4]
   85334 **
   85335 ** The P4 register values beginning with P3 form an unpacked index
   85336 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
   85337 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
   85338 ** ROWID on the P1 index.
   85339 **
   85340 ** If the P1 index entry is less than or equal to the key value then jump
   85341 ** to P2. Otherwise fall through to the next instruction.
   85342 */
   85343 case OP_IdxLE:          /* jump */
   85344 case OP_IdxGT:          /* jump */
   85345 case OP_IdxLT:          /* jump */
   85346 case OP_IdxGE:  {       /* jump */
   85347   VdbeCursor *pC;
   85348   int res;
   85349   UnpackedRecord r;
   85350 
   85351   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   85352   pC = p->apCsr[pOp->p1];
   85353   assert( pC!=0 );
   85354   assert( pC->isOrdered );
   85355   assert( pC->eCurType==CURTYPE_BTREE );
   85356   assert( pC->uc.pCursor!=0);
   85357   assert( pC->deferredMoveto==0 );
   85358   assert( pOp->p5==0 || pOp->p5==1 );
   85359   assert( pOp->p4type==P4_INT32 );
   85360   r.pKeyInfo = pC->pKeyInfo;
   85361   r.nField = (u16)pOp->p4.i;
   85362   if( pOp->opcode<OP_IdxLT ){
   85363     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
   85364     r.default_rc = -1;
   85365   }else{
   85366     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
   85367     r.default_rc = 0;
   85368   }
   85369   r.aMem = &aMem[pOp->p3];
   85370 #ifdef SQLITE_DEBUG
   85371   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
   85372 #endif
   85373   res = 0;  /* Not needed.  Only used to silence a warning. */
   85374   rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
   85375   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
   85376   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
   85377     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
   85378     res = -res;
   85379   }else{
   85380     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
   85381     res++;
   85382   }
   85383   VdbeBranchTaken(res>0,2);
   85384   if( rc ) goto abort_due_to_error;
   85385   if( res>0 ) goto jump_to_p2;
   85386   break;
   85387 }
   85388 
   85389 /* Opcode: Destroy P1 P2 P3 * *
   85390 **
   85391 ** Delete an entire database table or index whose root page in the database
   85392 ** file is given by P1.
   85393 **
   85394 ** The table being destroyed is in the main database file if P3==0.  If
   85395 ** P3==1 then the table to be clear is in the auxiliary database file
   85396 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   85397 **
   85398 ** If AUTOVACUUM is enabled then it is possible that another root page
   85399 ** might be moved into the newly deleted root page in order to keep all
   85400 ** root pages contiguous at the beginning of the database.  The former
   85401 ** value of the root page that moved - its value before the move occurred -
   85402 ** is stored in register P2. If no page movement was required (because the
   85403 ** table being dropped was already the last one in the database) then a
   85404 ** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero
   85405 ** is stored in register P2.
   85406 **
   85407 ** This opcode throws an error if there are any active reader VMs when
   85408 ** it is invoked. This is done to avoid the difficulty associated with
   85409 ** updating existing cursors when a root page is moved in an AUTOVACUUM
   85410 ** database. This error is thrown even if the database is not an AUTOVACUUM
   85411 ** db in order to avoid introducing an incompatibility between autovacuum
   85412 ** and non-autovacuum modes.
   85413 **
   85414 ** See also: Clear
   85415 */
   85416 case OP_Destroy: {     /* out2 */
   85417   int iMoved;
   85418   int iDb;
   85419 
   85420   assert( p->readOnly==0 );
   85421   assert( pOp->p1>1 );
   85422   pOut = out2Prerelease(p, pOp);
   85423   pOut->flags = MEM_Null;
   85424   if( db->nVdbeRead > db->nVDestroy+1 ){
   85425     rc = SQLITE_LOCKED;
   85426     p->errorAction = OE_Abort;
   85427     goto abort_due_to_error;
   85428   }else{
   85429     iDb = pOp->p3;
   85430     assert( DbMaskTest(p->btreeMask, iDb) );
   85431     iMoved = 0;  /* Not needed.  Only to silence a warning. */
   85432     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
   85433     pOut->flags = MEM_Int;
   85434     pOut->u.i = iMoved;
   85435     if( rc ) goto abort_due_to_error;
   85436 #ifndef SQLITE_OMIT_AUTOVACUUM
   85437     if( iMoved!=0 ){
   85438       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
   85439       /* All OP_Destroy operations occur on the same btree */
   85440       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
   85441       resetSchemaOnFault = iDb+1;
   85442     }
   85443 #endif
   85444   }
   85445   break;
   85446 }
   85447 
   85448 /* Opcode: Clear P1 P2 P3
   85449 **
   85450 ** Delete all contents of the database table or index whose root page
   85451 ** in the database file is given by P1.  But, unlike Destroy, do not
   85452 ** remove the table or index from the database file.
   85453 **
   85454 ** The table being clear is in the main database file if P2==0.  If
   85455 ** P2==1 then the table to be clear is in the auxiliary database file
   85456 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   85457 **
   85458 ** If the P3 value is non-zero, then the table referred to must be an
   85459 ** intkey table (an SQL table, not an index). In this case the row change
   85460 ** count is incremented by the number of rows in the table being cleared.
   85461 ** If P3 is greater than zero, then the value stored in register P3 is
   85462 ** also incremented by the number of rows in the table being cleared.
   85463 **
   85464 ** See also: Destroy
   85465 */
   85466 case OP_Clear: {
   85467   int nChange;
   85468 
   85469   nChange = 0;
   85470   assert( p->readOnly==0 );
   85471   assert( DbMaskTest(p->btreeMask, pOp->p2) );
   85472   rc = sqlite3BtreeClearTable(
   85473       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
   85474   );
   85475   if( pOp->p3 ){
   85476     p->nChange += nChange;
   85477     if( pOp->p3>0 ){
   85478       assert( memIsValid(&aMem[pOp->p3]) );
   85479       memAboutToChange(p, &aMem[pOp->p3]);
   85480       aMem[pOp->p3].u.i += nChange;
   85481     }
   85482   }
   85483   if( rc ) goto abort_due_to_error;
   85484   break;
   85485 }
   85486 
   85487 /* Opcode: ResetSorter P1 * * * *
   85488 **
   85489 ** Delete all contents from the ephemeral table or sorter
   85490 ** that is open on cursor P1.
   85491 **
   85492 ** This opcode only works for cursors used for sorting and
   85493 ** opened with OP_OpenEphemeral or OP_SorterOpen.
   85494 */
   85495 case OP_ResetSorter: {
   85496   VdbeCursor *pC;
   85497 
   85498   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   85499   pC = p->apCsr[pOp->p1];
   85500   assert( pC!=0 );
   85501   if( isSorter(pC) ){
   85502     sqlite3VdbeSorterReset(db, pC->uc.pSorter);
   85503   }else{
   85504     assert( pC->eCurType==CURTYPE_BTREE );
   85505     assert( pC->isEphemeral );
   85506     rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
   85507     if( rc ) goto abort_due_to_error;
   85508   }
   85509   break;
   85510 }
   85511 
   85512 /* Opcode: CreateBtree P1 P2 P3 * *
   85513 ** Synopsis: r[P2]=root iDb=P1 flags=P3
   85514 **
   85515 ** Allocate a new b-tree in the main database file if P1==0 or in the
   85516 ** TEMP database file if P1==1 or in an attached database if
   85517 ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
   85518 ** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
   85519 ** The root page number of the new b-tree is stored in register P2.
   85520 */
   85521 case OP_CreateBtree: {          /* out2 */
   85522   int pgno;
   85523   Db *pDb;
   85524 
   85525   pOut = out2Prerelease(p, pOp);
   85526   pgno = 0;
   85527   assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
   85528   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   85529   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   85530   assert( p->readOnly==0 );
   85531   pDb = &db->aDb[pOp->p1];
   85532   assert( pDb->pBt!=0 );
   85533   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
   85534   if( rc ) goto abort_due_to_error;
   85535   pOut->u.i = pgno;
   85536   break;
   85537 }
   85538 
   85539 /* Opcode: SqlExec * * * P4 *
   85540 **
   85541 ** Run the SQL statement or statements specified in the P4 string.
   85542 */
   85543 case OP_SqlExec: {
   85544   db->nSqlExec++;
   85545   rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
   85546   db->nSqlExec--;
   85547   if( rc ) goto abort_due_to_error;
   85548   break;
   85549 }
   85550 
   85551 /* Opcode: ParseSchema P1 * * P4 *
   85552 **
   85553 ** Read and parse all entries from the SQLITE_MASTER table of database P1
   85554 ** that match the WHERE clause P4.
   85555 **
   85556 ** This opcode invokes the parser to create a new virtual machine,
   85557 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
   85558 */
   85559 case OP_ParseSchema: {
   85560   int iDb;
   85561   const char *zMaster;
   85562   char *zSql;
   85563   InitData initData;
   85564 
   85565   /* Any prepared statement that invokes this opcode will hold mutexes
   85566   ** on every btree.  This is a prerequisite for invoking
   85567   ** sqlite3InitCallback().
   85568   */
   85569 #ifdef SQLITE_DEBUG
   85570   for(iDb=0; iDb<db->nDb; iDb++){
   85571     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   85572   }
   85573 #endif
   85574 
   85575   iDb = pOp->p1;
   85576   assert( iDb>=0 && iDb<db->nDb );
   85577   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
   85578   /* Used to be a conditional */ {
   85579     zMaster = MASTER_NAME;
   85580     initData.db = db;
   85581     initData.iDb = pOp->p1;
   85582     initData.pzErrMsg = &p->zErrMsg;
   85583     zSql = sqlite3MPrintf(db,
   85584        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
   85585        db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
   85586     if( zSql==0 ){
   85587       rc = SQLITE_NOMEM_BKPT;
   85588     }else{
   85589       assert( db->init.busy==0 );
   85590       db->init.busy = 1;
   85591       initData.rc = SQLITE_OK;
   85592       assert( !db->mallocFailed );
   85593       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   85594       if( rc==SQLITE_OK ) rc = initData.rc;
   85595       sqlite3DbFreeNN(db, zSql);
   85596       db->init.busy = 0;
   85597     }
   85598   }
   85599   if( rc ){
   85600     sqlite3ResetAllSchemasOfConnection(db);
   85601     if( rc==SQLITE_NOMEM ){
   85602       goto no_mem;
   85603     }
   85604     goto abort_due_to_error;
   85605   }
   85606   break;
   85607 }
   85608 
   85609 #if !defined(SQLITE_OMIT_ANALYZE)
   85610 /* Opcode: LoadAnalysis P1 * * * *
   85611 **
   85612 ** Read the sqlite_stat1 table for database P1 and load the content
   85613 ** of that table into the internal index hash table.  This will cause
   85614 ** the analysis to be used when preparing all subsequent queries.
   85615 */
   85616 case OP_LoadAnalysis: {
   85617   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   85618   rc = sqlite3AnalysisLoad(db, pOp->p1);
   85619   if( rc ) goto abort_due_to_error;
   85620   break;
   85621 }
   85622 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
   85623 
   85624 /* Opcode: DropTable P1 * * P4 *
   85625 **
   85626 ** Remove the internal (in-memory) data structures that describe
   85627 ** the table named P4 in database P1.  This is called after a table
   85628 ** is dropped from disk (using the Destroy opcode) in order to keep
   85629 ** the internal representation of the
   85630 ** schema consistent with what is on disk.
   85631 */
   85632 case OP_DropTable: {
   85633   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
   85634   break;
   85635 }
   85636 
   85637 /* Opcode: DropIndex P1 * * P4 *
   85638 **
   85639 ** Remove the internal (in-memory) data structures that describe
   85640 ** the index named P4 in database P1.  This is called after an index
   85641 ** is dropped from disk (using the Destroy opcode)
   85642 ** in order to keep the internal representation of the
   85643 ** schema consistent with what is on disk.
   85644 */
   85645 case OP_DropIndex: {
   85646   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
   85647   break;
   85648 }
   85649 
   85650 /* Opcode: DropTrigger P1 * * P4 *
   85651 **
   85652 ** Remove the internal (in-memory) data structures that describe
   85653 ** the trigger named P4 in database P1.  This is called after a trigger
   85654 ** is dropped from disk (using the Destroy opcode) in order to keep
   85655 ** the internal representation of the
   85656 ** schema consistent with what is on disk.
   85657 */
   85658 case OP_DropTrigger: {
   85659   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
   85660   break;
   85661 }
   85662 
   85663 
   85664 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   85665 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
   85666 **
   85667 ** Do an analysis of the currently open database.  Store in
   85668 ** register P1 the text of an error message describing any problems.
   85669 ** If no problems are found, store a NULL in register P1.
   85670 **
   85671 ** The register P3 contains one less than the maximum number of allowed errors.
   85672 ** At most reg(P3) errors will be reported.
   85673 ** In other words, the analysis stops as soon as reg(P1) errors are
   85674 ** seen.  Reg(P1) is updated with the number of errors remaining.
   85675 **
   85676 ** The root page numbers of all tables in the database are integers
   85677 ** stored in P4_INTARRAY argument.
   85678 **
   85679 ** If P5 is not zero, the check is done on the auxiliary database
   85680 ** file, not the main database file.
   85681 **
   85682 ** This opcode is used to implement the integrity_check pragma.
   85683 */
   85684 case OP_IntegrityCk: {
   85685   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   85686   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   85687   int nErr;       /* Number of errors reported */
   85688   char *z;        /* Text of the error report */
   85689   Mem *pnErr;     /* Register keeping track of errors remaining */
   85690 
   85691   assert( p->bIsReader );
   85692   nRoot = pOp->p2;
   85693   aRoot = pOp->p4.ai;
   85694   assert( nRoot>0 );
   85695   assert( aRoot[0]==nRoot );
   85696   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   85697   pnErr = &aMem[pOp->p3];
   85698   assert( (pnErr->flags & MEM_Int)!=0 );
   85699   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
   85700   pIn1 = &aMem[pOp->p1];
   85701   assert( pOp->p5<db->nDb );
   85702   assert( DbMaskTest(p->btreeMask, pOp->p5) );
   85703   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
   85704                                  (int)pnErr->u.i+1, &nErr);
   85705   sqlite3VdbeMemSetNull(pIn1);
   85706   if( nErr==0 ){
   85707     assert( z==0 );
   85708   }else if( z==0 ){
   85709     goto no_mem;
   85710   }else{
   85711     pnErr->u.i -= nErr-1;
   85712     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
   85713   }
   85714   UPDATE_MAX_BLOBSIZE(pIn1);
   85715   sqlite3VdbeChangeEncoding(pIn1, encoding);
   85716   break;
   85717 }
   85718 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   85719 
   85720 /* Opcode: RowSetAdd P1 P2 * * *
   85721 ** Synopsis: rowset(P1)=r[P2]
   85722 **
   85723 ** Insert the integer value held by register P2 into a RowSet object
   85724 ** held in register P1.
   85725 **
   85726 ** An assertion fails if P2 is not an integer.
   85727 */
   85728 case OP_RowSetAdd: {       /* in1, in2 */
   85729   pIn1 = &aMem[pOp->p1];
   85730   pIn2 = &aMem[pOp->p2];
   85731   assert( (pIn2->flags & MEM_Int)!=0 );
   85732   if( (pIn1->flags & MEM_RowSet)==0 ){
   85733     sqlite3VdbeMemSetRowSet(pIn1);
   85734     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   85735   }
   85736   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
   85737   break;
   85738 }
   85739 
   85740 /* Opcode: RowSetRead P1 P2 P3 * *
   85741 ** Synopsis: r[P3]=rowset(P1)
   85742 **
   85743 ** Extract the smallest value from the RowSet object in P1
   85744 ** and put that value into register P3.
   85745 ** Or, if RowSet object P1 is initially empty, leave P3
   85746 ** unchanged and jump to instruction P2.
   85747 */
   85748 case OP_RowSetRead: {       /* jump, in1, out3 */
   85749   i64 val;
   85750 
   85751   pIn1 = &aMem[pOp->p1];
   85752   if( (pIn1->flags & MEM_RowSet)==0
   85753    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
   85754   ){
   85755     /* The boolean index is empty */
   85756     sqlite3VdbeMemSetNull(pIn1);
   85757     VdbeBranchTaken(1,2);
   85758     goto jump_to_p2_and_check_for_interrupt;
   85759   }else{
   85760     /* A value was pulled from the index */
   85761     VdbeBranchTaken(0,2);
   85762     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
   85763   }
   85764   goto check_for_interrupt;
   85765 }
   85766 
   85767 /* Opcode: RowSetTest P1 P2 P3 P4
   85768 ** Synopsis: if r[P3] in rowset(P1) goto P2
   85769 **
   85770 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
   85771 ** contains a RowSet object and that RowSet object contains
   85772 ** the value held in P3, jump to register P2. Otherwise, insert the
   85773 ** integer in P3 into the RowSet and continue on to the
   85774 ** next opcode.
   85775 **
   85776 ** The RowSet object is optimized for the case where sets of integers
   85777 ** are inserted in distinct phases, which each set contains no duplicates.
   85778 ** Each set is identified by a unique P4 value. The first set
   85779 ** must have P4==0, the final set must have P4==-1, and for all other sets
   85780 ** must have P4>0.
   85781 **
   85782 ** This allows optimizations: (a) when P4==0 there is no need to test
   85783 ** the RowSet object for P3, as it is guaranteed not to contain it,
   85784 ** (b) when P4==-1 there is no need to insert the value, as it will
   85785 ** never be tested for, and (c) when a value that is part of set X is
   85786 ** inserted, there is no need to search to see if the same value was
   85787 ** previously inserted as part of set X (only if it was previously
   85788 ** inserted as part of some other set).
   85789 */
   85790 case OP_RowSetTest: {                     /* jump, in1, in3 */
   85791   int iSet;
   85792   int exists;
   85793 
   85794   pIn1 = &aMem[pOp->p1];
   85795   pIn3 = &aMem[pOp->p3];
   85796   iSet = pOp->p4.i;
   85797   assert( pIn3->flags&MEM_Int );
   85798 
   85799   /* If there is anything other than a rowset object in memory cell P1,
   85800   ** delete it now and initialize P1 with an empty rowset
   85801   */
   85802   if( (pIn1->flags & MEM_RowSet)==0 ){
   85803     sqlite3VdbeMemSetRowSet(pIn1);
   85804     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   85805   }
   85806 
   85807   assert( pOp->p4type==P4_INT32 );
   85808   assert( iSet==-1 || iSet>=0 );
   85809   if( iSet ){
   85810     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
   85811     VdbeBranchTaken(exists!=0,2);
   85812     if( exists ) goto jump_to_p2;
   85813   }
   85814   if( iSet>=0 ){
   85815     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
   85816   }
   85817   break;
   85818 }
   85819 
   85820 
   85821 #ifndef SQLITE_OMIT_TRIGGER
   85822 
   85823 /* Opcode: Program P1 P2 P3 P4 P5
   85824 **
   85825 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
   85826 **
   85827 ** P1 contains the address of the memory cell that contains the first memory
   85828 ** cell in an array of values used as arguments to the sub-program. P2
   85829 ** contains the address to jump to if the sub-program throws an IGNORE
   85830 ** exception using the RAISE() function. Register P3 contains the address
   85831 ** of a memory cell in this (the parent) VM that is used to allocate the
   85832 ** memory required by the sub-vdbe at runtime.
   85833 **
   85834 ** P4 is a pointer to the VM containing the trigger program.
   85835 **
   85836 ** If P5 is non-zero, then recursive program invocation is enabled.
   85837 */
   85838 case OP_Program: {        /* jump */
   85839   int nMem;               /* Number of memory registers for sub-program */
   85840   int nByte;              /* Bytes of runtime space required for sub-program */
   85841   Mem *pRt;               /* Register to allocate runtime space */
   85842   Mem *pMem;              /* Used to iterate through memory cells */
   85843   Mem *pEnd;              /* Last memory cell in new array */
   85844   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   85845   SubProgram *pProgram;   /* Sub-program to execute */
   85846   void *t;                /* Token identifying trigger */
   85847 
   85848   pProgram = pOp->p4.pProgram;
   85849   pRt = &aMem[pOp->p3];
   85850   assert( pProgram->nOp>0 );
   85851 
   85852   /* If the p5 flag is clear, then recursive invocation of triggers is
   85853   ** disabled for backwards compatibility (p5 is set if this sub-program
   85854   ** is really a trigger, not a foreign key action, and the flag set
   85855   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
   85856   **
   85857   ** It is recursive invocation of triggers, at the SQL level, that is
   85858   ** disabled. In some cases a single trigger may generate more than one
   85859   ** SubProgram (if the trigger may be executed with more than one different
   85860   ** ON CONFLICT algorithm). SubProgram structures associated with a
   85861   ** single trigger all have the same value for the SubProgram.token
   85862   ** variable.  */
   85863   if( pOp->p5 ){
   85864     t = pProgram->token;
   85865     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
   85866     if( pFrame ) break;
   85867   }
   85868 
   85869   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
   85870     rc = SQLITE_ERROR;
   85871     sqlite3VdbeError(p, "too many levels of trigger recursion");
   85872     goto abort_due_to_error;
   85873   }
   85874 
   85875   /* Register pRt is used to store the memory required to save the state
   85876   ** of the current program, and the memory required at runtime to execute
   85877   ** the trigger program. If this trigger has been fired before, then pRt
   85878   ** is already allocated. Otherwise, it must be initialized.  */
   85879   if( (pRt->flags&MEM_Frame)==0 ){
   85880     /* SubProgram.nMem is set to the number of memory cells used by the
   85881     ** program stored in SubProgram.aOp. As well as these, one memory
   85882     ** cell is required for each cursor used by the program. Set local
   85883     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
   85884     */
   85885     nMem = pProgram->nMem + pProgram->nCsr;
   85886     assert( nMem>0 );
   85887     if( pProgram->nCsr==0 ) nMem++;
   85888     nByte = ROUND8(sizeof(VdbeFrame))
   85889               + nMem * sizeof(Mem)
   85890               + pProgram->nCsr * sizeof(VdbeCursor*)
   85891               + (pProgram->nOp + 7)/8;
   85892     pFrame = sqlite3DbMallocZero(db, nByte);
   85893     if( !pFrame ){
   85894       goto no_mem;
   85895     }
   85896     sqlite3VdbeMemRelease(pRt);
   85897     pRt->flags = MEM_Frame;
   85898     pRt->u.pFrame = pFrame;
   85899 
   85900     pFrame->v = p;
   85901     pFrame->nChildMem = nMem;
   85902     pFrame->nChildCsr = pProgram->nCsr;
   85903     pFrame->pc = (int)(pOp - aOp);
   85904     pFrame->aMem = p->aMem;
   85905     pFrame->nMem = p->nMem;
   85906     pFrame->apCsr = p->apCsr;
   85907     pFrame->nCursor = p->nCursor;
   85908     pFrame->aOp = p->aOp;
   85909     pFrame->nOp = p->nOp;
   85910     pFrame->token = pProgram->token;
   85911 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   85912     pFrame->anExec = p->anExec;
   85913 #endif
   85914 
   85915     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
   85916     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
   85917       pMem->flags = MEM_Undefined;
   85918       pMem->db = db;
   85919     }
   85920   }else{
   85921     pFrame = pRt->u.pFrame;
   85922     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
   85923         || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
   85924     assert( pProgram->nCsr==pFrame->nChildCsr );
   85925     assert( (int)(pOp - aOp)==pFrame->pc );
   85926   }
   85927 
   85928   p->nFrame++;
   85929   pFrame->pParent = p->pFrame;
   85930   pFrame->lastRowid = db->lastRowid;
   85931   pFrame->nChange = p->nChange;
   85932   pFrame->nDbChange = p->db->nChange;
   85933   assert( pFrame->pAuxData==0 );
   85934   pFrame->pAuxData = p->pAuxData;
   85935   p->pAuxData = 0;
   85936   p->nChange = 0;
   85937   p->pFrame = pFrame;
   85938   p->aMem = aMem = VdbeFrameMem(pFrame);
   85939   p->nMem = pFrame->nChildMem;
   85940   p->nCursor = (u16)pFrame->nChildCsr;
   85941   p->apCsr = (VdbeCursor **)&aMem[p->nMem];
   85942   pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
   85943   memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
   85944   p->aOp = aOp = pProgram->aOp;
   85945   p->nOp = pProgram->nOp;
   85946 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   85947   p->anExec = 0;
   85948 #endif
   85949   pOp = &aOp[-1];
   85950 
   85951   break;
   85952 }
   85953 
   85954 /* Opcode: Param P1 P2 * * *
   85955 **
   85956 ** This opcode is only ever present in sub-programs called via the
   85957 ** OP_Program instruction. Copy a value currently stored in a memory
   85958 ** cell of the calling (parent) frame to cell P2 in the current frames
   85959 ** address space. This is used by trigger programs to access the new.*
   85960 ** and old.* values.
   85961 **
   85962 ** The address of the cell in the parent frame is determined by adding
   85963 ** the value of the P1 argument to the value of the P1 argument to the
   85964 ** calling OP_Program instruction.
   85965 */
   85966 case OP_Param: {           /* out2 */
   85967   VdbeFrame *pFrame;
   85968   Mem *pIn;
   85969   pOut = out2Prerelease(p, pOp);
   85970   pFrame = p->pFrame;
   85971   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
   85972   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
   85973   break;
   85974 }
   85975 
   85976 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
   85977 
   85978 #ifndef SQLITE_OMIT_FOREIGN_KEY
   85979 /* Opcode: FkCounter P1 P2 * * *
   85980 ** Synopsis: fkctr[P1]+=P2
   85981 **
   85982 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
   85983 ** If P1 is non-zero, the database constraint counter is incremented
   85984 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
   85985 ** statement counter is incremented (immediate foreign key constraints).
   85986 */
   85987 case OP_FkCounter: {
   85988   if( db->flags & SQLITE_DeferFKs ){
   85989     db->nDeferredImmCons += pOp->p2;
   85990   }else if( pOp->p1 ){
   85991     db->nDeferredCons += pOp->p2;
   85992   }else{
   85993     p->nFkConstraint += pOp->p2;
   85994   }
   85995   break;
   85996 }
   85997 
   85998 /* Opcode: FkIfZero P1 P2 * * *
   85999 ** Synopsis: if fkctr[P1]==0 goto P2
   86000 **
   86001 ** This opcode tests if a foreign key constraint-counter is currently zero.
   86002 ** If so, jump to instruction P2. Otherwise, fall through to the next
   86003 ** instruction.
   86004 **
   86005 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
   86006 ** is zero (the one that counts deferred constraint violations). If P1 is
   86007 ** zero, the jump is taken if the statement constraint-counter is zero
   86008 ** (immediate foreign key constraint violations).
   86009 */
   86010 case OP_FkIfZero: {         /* jump */
   86011   if( pOp->p1 ){
   86012     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
   86013     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
   86014   }else{
   86015     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
   86016     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
   86017   }
   86018   break;
   86019 }
   86020 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
   86021 
   86022 #ifndef SQLITE_OMIT_AUTOINCREMENT
   86023 /* Opcode: MemMax P1 P2 * * *
   86024 ** Synopsis: r[P1]=max(r[P1],r[P2])
   86025 **
   86026 ** P1 is a register in the root frame of this VM (the root frame is
   86027 ** different from the current frame if this instruction is being executed
   86028 ** within a sub-program). Set the value of register P1 to the maximum of
   86029 ** its current value and the value in register P2.
   86030 **
   86031 ** This instruction throws an error if the memory cell is not initially
   86032 ** an integer.
   86033 */
   86034 case OP_MemMax: {        /* in2 */
   86035   VdbeFrame *pFrame;
   86036   if( p->pFrame ){
   86037     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   86038     pIn1 = &pFrame->aMem[pOp->p1];
   86039   }else{
   86040     pIn1 = &aMem[pOp->p1];
   86041   }
   86042   assert( memIsValid(pIn1) );
   86043   sqlite3VdbeMemIntegerify(pIn1);
   86044   pIn2 = &aMem[pOp->p2];
   86045   sqlite3VdbeMemIntegerify(pIn2);
   86046   if( pIn1->u.i<pIn2->u.i){
   86047     pIn1->u.i = pIn2->u.i;
   86048   }
   86049   break;
   86050 }
   86051 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   86052 
   86053 /* Opcode: IfPos P1 P2 P3 * *
   86054 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
   86055 **
   86056 ** Register P1 must contain an integer.
   86057 ** If the value of register P1 is 1 or greater, subtract P3 from the
   86058 ** value in P1 and jump to P2.
   86059 **
   86060 ** If the initial value of register P1 is less than 1, then the
   86061 ** value is unchanged and control passes through to the next instruction.
   86062 */
   86063 case OP_IfPos: {        /* jump, in1 */
   86064   pIn1 = &aMem[pOp->p1];
   86065   assert( pIn1->flags&MEM_Int );
   86066   VdbeBranchTaken( pIn1->u.i>0, 2);
   86067   if( pIn1->u.i>0 ){
   86068     pIn1->u.i -= pOp->p3;
   86069     goto jump_to_p2;
   86070   }
   86071   break;
   86072 }
   86073 
   86074 /* Opcode: OffsetLimit P1 P2 P3 * *
   86075 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
   86076 **
   86077 ** This opcode performs a commonly used computation associated with
   86078 ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
   86079 ** holds the offset counter.  The opcode computes the combined value
   86080 ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
   86081 ** value computed is the total number of rows that will need to be
   86082 ** visited in order to complete the query.
   86083 **
   86084 ** If r[P3] is zero or negative, that means there is no OFFSET
   86085 ** and r[P2] is set to be the value of the LIMIT, r[P1].
   86086 **
   86087 ** if r[P1] is zero or negative, that means there is no LIMIT
   86088 ** and r[P2] is set to -1.
   86089 **
   86090 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
   86091 */
   86092 case OP_OffsetLimit: {    /* in1, out2, in3 */
   86093   i64 x;
   86094   pIn1 = &aMem[pOp->p1];
   86095   pIn3 = &aMem[pOp->p3];
   86096   pOut = out2Prerelease(p, pOp);
   86097   assert( pIn1->flags & MEM_Int );
   86098   assert( pIn3->flags & MEM_Int );
   86099   x = pIn1->u.i;
   86100   if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
   86101     /* If the LIMIT is less than or equal to zero, loop forever.  This
   86102     ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
   86103     ** also loop forever.  This is undocumented.  In fact, one could argue
   86104     ** that the loop should terminate.  But assuming 1 billion iterations
   86105     ** per second (far exceeding the capabilities of any current hardware)
   86106     ** it would take nearly 300 years to actually reach the limit.  So
   86107     ** looping forever is a reasonable approximation. */
   86108     pOut->u.i = -1;
   86109   }else{
   86110     pOut->u.i = x;
   86111   }
   86112   break;
   86113 }
   86114 
   86115 /* Opcode: IfNotZero P1 P2 * * *
   86116 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
   86117 **
   86118 ** Register P1 must contain an integer.  If the content of register P1 is
   86119 ** initially greater than zero, then decrement the value in register P1.
   86120 ** If it is non-zero (negative or positive) and then also jump to P2.
   86121 ** If register P1 is initially zero, leave it unchanged and fall through.
   86122 */
   86123 case OP_IfNotZero: {        /* jump, in1 */
   86124   pIn1 = &aMem[pOp->p1];
   86125   assert( pIn1->flags&MEM_Int );
   86126   VdbeBranchTaken(pIn1->u.i<0, 2);
   86127   if( pIn1->u.i ){
   86128      if( pIn1->u.i>0 ) pIn1->u.i--;
   86129      goto jump_to_p2;
   86130   }
   86131   break;
   86132 }
   86133 
   86134 /* Opcode: DecrJumpZero P1 P2 * * *
   86135 ** Synopsis: if (--r[P1])==0 goto P2
   86136 **
   86137 ** Register P1 must hold an integer.  Decrement the value in P1
   86138 ** and jump to P2 if the new value is exactly zero.
   86139 */
   86140 case OP_DecrJumpZero: {      /* jump, in1 */
   86141   pIn1 = &aMem[pOp->p1];
   86142   assert( pIn1->flags&MEM_Int );
   86143   if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
   86144   VdbeBranchTaken(pIn1->u.i==0, 2);
   86145   if( pIn1->u.i==0 ) goto jump_to_p2;
   86146   break;
   86147 }
   86148 
   86149 
   86150 /* Opcode: AggStep0 * P2 P3 P4 P5
   86151 ** Synopsis: accum=r[P3] step(r[P2@P5])
   86152 **
   86153 ** Execute the step function for an aggregate.  The
   86154 ** function has P5 arguments.   P4 is a pointer to the FuncDef
   86155 ** structure that specifies the function.  Register P3 is the
   86156 ** accumulator.
   86157 **
   86158 ** The P5 arguments are taken from register P2 and its
   86159 ** successors.
   86160 */
   86161 /* Opcode: AggStep * P2 P3 P4 P5
   86162 ** Synopsis: accum=r[P3] step(r[P2@P5])
   86163 **
   86164 ** Execute the step function for an aggregate.  The
   86165 ** function has P5 arguments.   P4 is a pointer to an sqlite3_context
   86166 ** object that is used to run the function.  Register P3 is
   86167 ** as the accumulator.
   86168 **
   86169 ** The P5 arguments are taken from register P2 and its
   86170 ** successors.
   86171 **
   86172 ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
   86173 ** the FuncDef stored in P4 is converted into an sqlite3_context and
   86174 ** the opcode is changed.  In this way, the initialization of the
   86175 ** sqlite3_context only happens once, instead of on each call to the
   86176 ** step function.
   86177 */
   86178 case OP_AggStep0: {
   86179   int n;
   86180   sqlite3_context *pCtx;
   86181 
   86182   assert( pOp->p4type==P4_FUNCDEF );
   86183   n = pOp->p5;
   86184   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   86185   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
   86186   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
   86187   pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
   86188   if( pCtx==0 ) goto no_mem;
   86189   pCtx->pMem = 0;
   86190   pCtx->pFunc = pOp->p4.pFunc;
   86191   pCtx->iOp = (int)(pOp - aOp);
   86192   pCtx->pVdbe = p;
   86193   pCtx->argc = n;
   86194   pOp->p4type = P4_FUNCCTX;
   86195   pOp->p4.pCtx = pCtx;
   86196   pOp->opcode = OP_AggStep;
   86197   /* Fall through into OP_AggStep */
   86198 }
   86199 case OP_AggStep: {
   86200   int i;
   86201   sqlite3_context *pCtx;
   86202   Mem *pMem;
   86203   Mem t;
   86204 
   86205   assert( pOp->p4type==P4_FUNCCTX );
   86206   pCtx = pOp->p4.pCtx;
   86207   pMem = &aMem[pOp->p3];
   86208 
   86209   /* If this function is inside of a trigger, the register array in aMem[]
   86210   ** might change from one evaluation to the next.  The next block of code
   86211   ** checks to see if the register array has changed, and if so it
   86212   ** reinitializes the relavant parts of the sqlite3_context object */
   86213   if( pCtx->pMem != pMem ){
   86214     pCtx->pMem = pMem;
   86215     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
   86216   }
   86217 
   86218 #ifdef SQLITE_DEBUG
   86219   for(i=0; i<pCtx->argc; i++){
   86220     assert( memIsValid(pCtx->argv[i]) );
   86221     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
   86222   }
   86223 #endif
   86224 
   86225   pMem->n++;
   86226   sqlite3VdbeMemInit(&t, db, MEM_Null);
   86227   pCtx->pOut = &t;
   86228   pCtx->fErrorOrAux = 0;
   86229   pCtx->skipFlag = 0;
   86230   (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
   86231   if( pCtx->fErrorOrAux ){
   86232     if( pCtx->isError ){
   86233       sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
   86234       rc = pCtx->isError;
   86235     }
   86236     sqlite3VdbeMemRelease(&t);
   86237     if( rc ) goto abort_due_to_error;
   86238   }else{
   86239     assert( t.flags==MEM_Null );
   86240   }
   86241   if( pCtx->skipFlag ){
   86242     assert( pOp[-1].opcode==OP_CollSeq );
   86243     i = pOp[-1].p1;
   86244     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
   86245   }
   86246   break;
   86247 }
   86248 
   86249 /* Opcode: AggFinal P1 P2 * P4 *
   86250 ** Synopsis: accum=r[P1] N=P2
   86251 **
   86252 ** Execute the finalizer function for an aggregate.  P1 is
   86253 ** the memory location that is the accumulator for the aggregate.
   86254 **
   86255 ** P2 is the number of arguments that the step function takes and
   86256 ** P4 is a pointer to the FuncDef for this function.  The P2
   86257 ** argument is not used by this opcode.  It is only there to disambiguate
   86258 ** functions that can take varying numbers of arguments.  The
   86259 ** P4 argument is only needed for the degenerate case where
   86260 ** the step function was not previously called.
   86261 */
   86262 case OP_AggFinal: {
   86263   Mem *pMem;
   86264   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
   86265   pMem = &aMem[pOp->p1];
   86266   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
   86267   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
   86268   if( rc ){
   86269     sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
   86270     goto abort_due_to_error;
   86271   }
   86272   sqlite3VdbeChangeEncoding(pMem, encoding);
   86273   UPDATE_MAX_BLOBSIZE(pMem);
   86274   if( sqlite3VdbeMemTooBig(pMem) ){
   86275     goto too_big;
   86276   }
   86277   break;
   86278 }
   86279 
   86280 #ifndef SQLITE_OMIT_WAL
   86281 /* Opcode: Checkpoint P1 P2 P3 * *
   86282 **
   86283 ** Checkpoint database P1. This is a no-op if P1 is not currently in
   86284 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
   86285 ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
   86286 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
   86287 ** WAL after the checkpoint into mem[P3+1] and the number of pages
   86288 ** in the WAL that have been checkpointed after the checkpoint
   86289 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
   86290 ** mem[P3+2] are initialized to -1.
   86291 */
   86292 case OP_Checkpoint: {
   86293   int i;                          /* Loop counter */
   86294   int aRes[3];                    /* Results */
   86295   Mem *pMem;                      /* Write results here */
   86296 
   86297   assert( p->readOnly==0 );
   86298   aRes[0] = 0;
   86299   aRes[1] = aRes[2] = -1;
   86300   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
   86301        || pOp->p2==SQLITE_CHECKPOINT_FULL
   86302        || pOp->p2==SQLITE_CHECKPOINT_RESTART
   86303        || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
   86304   );
   86305   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
   86306   if( rc ){
   86307     if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
   86308     rc = SQLITE_OK;
   86309     aRes[0] = 1;
   86310   }
   86311   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
   86312     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
   86313   }
   86314   break;
   86315 };
   86316 #endif
   86317 
   86318 #ifndef SQLITE_OMIT_PRAGMA
   86319 /* Opcode: JournalMode P1 P2 P3 * *
   86320 **
   86321 ** Change the journal mode of database P1 to P3. P3 must be one of the
   86322 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
   86323 ** modes (delete, truncate, persist, off and memory), this is a simple
   86324 ** operation. No IO is required.
   86325 **
   86326 ** If changing into or out of WAL mode the procedure is more complicated.
   86327 **
   86328 ** Write a string containing the final journal-mode to register P2.
   86329 */
   86330 case OP_JournalMode: {    /* out2 */
   86331   Btree *pBt;                     /* Btree to change journal mode of */
   86332   Pager *pPager;                  /* Pager associated with pBt */
   86333   int eNew;                       /* New journal mode */
   86334   int eOld;                       /* The old journal mode */
   86335 #ifndef SQLITE_OMIT_WAL
   86336   const char *zFilename;          /* Name of database file for pPager */
   86337 #endif
   86338 
   86339   pOut = out2Prerelease(p, pOp);
   86340   eNew = pOp->p3;
   86341   assert( eNew==PAGER_JOURNALMODE_DELETE
   86342        || eNew==PAGER_JOURNALMODE_TRUNCATE
   86343        || eNew==PAGER_JOURNALMODE_PERSIST
   86344        || eNew==PAGER_JOURNALMODE_OFF
   86345        || eNew==PAGER_JOURNALMODE_MEMORY
   86346        || eNew==PAGER_JOURNALMODE_WAL
   86347        || eNew==PAGER_JOURNALMODE_QUERY
   86348   );
   86349   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   86350   assert( p->readOnly==0 );
   86351 
   86352   pBt = db->aDb[pOp->p1].pBt;
   86353   pPager = sqlite3BtreePager(pBt);
   86354   eOld = sqlite3PagerGetJournalMode(pPager);
   86355   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
   86356   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
   86357 
   86358 #ifndef SQLITE_OMIT_WAL
   86359   zFilename = sqlite3PagerFilename(pPager, 1);
   86360 
   86361   /* Do not allow a transition to journal_mode=WAL for a database
   86362   ** in temporary storage or if the VFS does not support shared memory
   86363   */
   86364   if( eNew==PAGER_JOURNALMODE_WAL
   86365    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
   86366        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
   86367   ){
   86368     eNew = eOld;
   86369   }
   86370 
   86371   if( (eNew!=eOld)
   86372    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
   86373   ){
   86374     if( !db->autoCommit || db->nVdbeRead>1 ){
   86375       rc = SQLITE_ERROR;
   86376       sqlite3VdbeError(p,
   86377           "cannot change %s wal mode from within a transaction",
   86378           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
   86379       );
   86380       goto abort_due_to_error;
   86381     }else{
   86382 
   86383       if( eOld==PAGER_JOURNALMODE_WAL ){
   86384         /* If leaving WAL mode, close the log file. If successful, the call
   86385         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
   86386         ** file. An EXCLUSIVE lock may still be held on the database file
   86387         ** after a successful return.
   86388         */
   86389         rc = sqlite3PagerCloseWal(pPager, db);
   86390         if( rc==SQLITE_OK ){
   86391           sqlite3PagerSetJournalMode(pPager, eNew);
   86392         }
   86393       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
   86394         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
   86395         ** as an intermediate */
   86396         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
   86397       }
   86398 
   86399       /* Open a transaction on the database file. Regardless of the journal
   86400       ** mode, this transaction always uses a rollback journal.
   86401       */
   86402       assert( sqlite3BtreeIsInTrans(pBt)==0 );
   86403       if( rc==SQLITE_OK ){
   86404         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
   86405       }
   86406     }
   86407   }
   86408 #endif /* ifndef SQLITE_OMIT_WAL */
   86409 
   86410   if( rc ) eNew = eOld;
   86411   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
   86412 
   86413   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   86414   pOut->z = (char *)sqlite3JournalModename(eNew);
   86415   pOut->n = sqlite3Strlen30(pOut->z);
   86416   pOut->enc = SQLITE_UTF8;
   86417   sqlite3VdbeChangeEncoding(pOut, encoding);
   86418   if( rc ) goto abort_due_to_error;
   86419   break;
   86420 };
   86421 #endif /* SQLITE_OMIT_PRAGMA */
   86422 
   86423 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   86424 /* Opcode: Vacuum P1 * * * *
   86425 **
   86426 ** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
   86427 ** for an attached database.  The "temp" database may not be vacuumed.
   86428 */
   86429 case OP_Vacuum: {
   86430   assert( p->readOnly==0 );
   86431   rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
   86432   if( rc ) goto abort_due_to_error;
   86433   break;
   86434 }
   86435 #endif
   86436 
   86437 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   86438 /* Opcode: IncrVacuum P1 P2 * * *
   86439 **
   86440 ** Perform a single step of the incremental vacuum procedure on
   86441 ** the P1 database. If the vacuum has finished, jump to instruction
   86442 ** P2. Otherwise, fall through to the next instruction.
   86443 */
   86444 case OP_IncrVacuum: {        /* jump */
   86445   Btree *pBt;
   86446 
   86447   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   86448   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   86449   assert( p->readOnly==0 );
   86450   pBt = db->aDb[pOp->p1].pBt;
   86451   rc = sqlite3BtreeIncrVacuum(pBt);
   86452   VdbeBranchTaken(rc==SQLITE_DONE,2);
   86453   if( rc ){
   86454     if( rc!=SQLITE_DONE ) goto abort_due_to_error;
   86455     rc = SQLITE_OK;
   86456     goto jump_to_p2;
   86457   }
   86458   break;
   86459 }
   86460 #endif
   86461 
   86462 /* Opcode: Expire P1 * * * *
   86463 **
   86464 ** Cause precompiled statements to expire.  When an expired statement
   86465 ** is executed using sqlite3_step() it will either automatically
   86466 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
   86467 ** or it will fail with SQLITE_SCHEMA.
   86468 **
   86469 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
   86470 ** then only the currently executing statement is expired.
   86471 */
   86472 case OP_Expire: {
   86473   if( !pOp->p1 ){
   86474     sqlite3ExpirePreparedStatements(db);
   86475   }else{
   86476     p->expired = 1;
   86477   }
   86478   break;
   86479 }
   86480 
   86481 #ifndef SQLITE_OMIT_SHARED_CACHE
   86482 /* Opcode: TableLock P1 P2 P3 P4 *
   86483 ** Synopsis: iDb=P1 root=P2 write=P3
   86484 **
   86485 ** Obtain a lock on a particular table. This instruction is only used when
   86486 ** the shared-cache feature is enabled.
   86487 **
   86488 ** P1 is the index of the database in sqlite3.aDb[] of the database
   86489 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
   86490 ** a write lock if P3==1.
   86491 **
   86492 ** P2 contains the root-page of the table to lock.
   86493 **
   86494 ** P4 contains a pointer to the name of the table being locked. This is only
   86495 ** used to generate an error message if the lock cannot be obtained.
   86496 */
   86497 case OP_TableLock: {
   86498   u8 isWriteLock = (u8)pOp->p3;
   86499   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
   86500     int p1 = pOp->p1;
   86501     assert( p1>=0 && p1<db->nDb );
   86502     assert( DbMaskTest(p->btreeMask, p1) );
   86503     assert( isWriteLock==0 || isWriteLock==1 );
   86504     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
   86505     if( rc ){
   86506       if( (rc&0xFF)==SQLITE_LOCKED ){
   86507         const char *z = pOp->p4.z;
   86508         sqlite3VdbeError(p, "database table is locked: %s", z);
   86509       }
   86510       goto abort_due_to_error;
   86511     }
   86512   }
   86513   break;
   86514 }
   86515 #endif /* SQLITE_OMIT_SHARED_CACHE */
   86516 
   86517 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86518 /* Opcode: VBegin * * * P4 *
   86519 **
   86520 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
   86521 ** xBegin method for that table.
   86522 **
   86523 ** Also, whether or not P4 is set, check that this is not being called from
   86524 ** within a callback to a virtual table xSync() method. If it is, the error
   86525 ** code will be set to SQLITE_LOCKED.
   86526 */
   86527 case OP_VBegin: {
   86528   VTable *pVTab;
   86529   pVTab = pOp->p4.pVtab;
   86530   rc = sqlite3VtabBegin(db, pVTab);
   86531   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
   86532   if( rc ) goto abort_due_to_error;
   86533   break;
   86534 }
   86535 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86536 
   86537 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86538 /* Opcode: VCreate P1 P2 * * *
   86539 **
   86540 ** P2 is a register that holds the name of a virtual table in database
   86541 ** P1. Call the xCreate method for that table.
   86542 */
   86543 case OP_VCreate: {
   86544   Mem sMem;          /* For storing the record being decoded */
   86545   const char *zTab;  /* Name of the virtual table */
   86546 
   86547   memset(&sMem, 0, sizeof(sMem));
   86548   sMem.db = db;
   86549   /* Because P2 is always a static string, it is impossible for the
   86550   ** sqlite3VdbeMemCopy() to fail */
   86551   assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
   86552   assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
   86553   rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
   86554   assert( rc==SQLITE_OK );
   86555   zTab = (const char*)sqlite3_value_text(&sMem);
   86556   assert( zTab || db->mallocFailed );
   86557   if( zTab ){
   86558     rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
   86559   }
   86560   sqlite3VdbeMemRelease(&sMem);
   86561   if( rc ) goto abort_due_to_error;
   86562   break;
   86563 }
   86564 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86565 
   86566 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86567 /* Opcode: VDestroy P1 * * P4 *
   86568 **
   86569 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
   86570 ** of that table.
   86571 */
   86572 case OP_VDestroy: {
   86573   db->nVDestroy++;
   86574   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
   86575   db->nVDestroy--;
   86576   if( rc ) goto abort_due_to_error;
   86577   break;
   86578 }
   86579 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86580 
   86581 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86582 /* Opcode: VOpen P1 * * P4 *
   86583 **
   86584 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   86585 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
   86586 ** table and stores that cursor in P1.
   86587 */
   86588 case OP_VOpen: {
   86589   VdbeCursor *pCur;
   86590   sqlite3_vtab_cursor *pVCur;
   86591   sqlite3_vtab *pVtab;
   86592   const sqlite3_module *pModule;
   86593 
   86594   assert( p->bIsReader );
   86595   pCur = 0;
   86596   pVCur = 0;
   86597   pVtab = pOp->p4.pVtab->pVtab;
   86598   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
   86599     rc = SQLITE_LOCKED;
   86600     goto abort_due_to_error;
   86601   }
   86602   pModule = pVtab->pModule;
   86603   rc = pModule->xOpen(pVtab, &pVCur);
   86604   sqlite3VtabImportErrmsg(p, pVtab);
   86605   if( rc ) goto abort_due_to_error;
   86606 
   86607   /* Initialize sqlite3_vtab_cursor base class */
   86608   pVCur->pVtab = pVtab;
   86609 
   86610   /* Initialize vdbe cursor object */
   86611   pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
   86612   if( pCur ){
   86613     pCur->uc.pVCur = pVCur;
   86614     pVtab->nRef++;
   86615   }else{
   86616     assert( db->mallocFailed );
   86617     pModule->xClose(pVCur);
   86618     goto no_mem;
   86619   }
   86620   break;
   86621 }
   86622 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86623 
   86624 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86625 /* Opcode: VFilter P1 P2 P3 P4 *
   86626 ** Synopsis: iplan=r[P3] zplan='P4'
   86627 **
   86628 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
   86629 ** the filtered result set is empty.
   86630 **
   86631 ** P4 is either NULL or a string that was generated by the xBestIndex
   86632 ** method of the module.  The interpretation of the P4 string is left
   86633 ** to the module implementation.
   86634 **
   86635 ** This opcode invokes the xFilter method on the virtual table specified
   86636 ** by P1.  The integer query plan parameter to xFilter is stored in register
   86637 ** P3. Register P3+1 stores the argc parameter to be passed to the
   86638 ** xFilter method. Registers P3+2..P3+1+argc are the argc
   86639 ** additional parameters which are passed to
   86640 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
   86641 **
   86642 ** A jump is made to P2 if the result set after filtering would be empty.
   86643 */
   86644 case OP_VFilter: {   /* jump */
   86645   int nArg;
   86646   int iQuery;
   86647   const sqlite3_module *pModule;
   86648   Mem *pQuery;
   86649   Mem *pArgc;
   86650   sqlite3_vtab_cursor *pVCur;
   86651   sqlite3_vtab *pVtab;
   86652   VdbeCursor *pCur;
   86653   int res;
   86654   int i;
   86655   Mem **apArg;
   86656 
   86657   pQuery = &aMem[pOp->p3];
   86658   pArgc = &pQuery[1];
   86659   pCur = p->apCsr[pOp->p1];
   86660   assert( memIsValid(pQuery) );
   86661   REGISTER_TRACE(pOp->p3, pQuery);
   86662   assert( pCur->eCurType==CURTYPE_VTAB );
   86663   pVCur = pCur->uc.pVCur;
   86664   pVtab = pVCur->pVtab;
   86665   pModule = pVtab->pModule;
   86666 
   86667   /* Grab the index number and argc parameters */
   86668   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
   86669   nArg = (int)pArgc->u.i;
   86670   iQuery = (int)pQuery->u.i;
   86671 
   86672   /* Invoke the xFilter method */
   86673   res = 0;
   86674   apArg = p->apArg;
   86675   for(i = 0; i<nArg; i++){
   86676     apArg[i] = &pArgc[i+1];
   86677   }
   86678   rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
   86679   sqlite3VtabImportErrmsg(p, pVtab);
   86680   if( rc ) goto abort_due_to_error;
   86681   res = pModule->xEof(pVCur);
   86682   pCur->nullRow = 0;
   86683   VdbeBranchTaken(res!=0,2);
   86684   if( res ) goto jump_to_p2;
   86685   break;
   86686 }
   86687 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86688 
   86689 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86690 /* Opcode: VColumn P1 P2 P3 * P5
   86691 ** Synopsis: r[P3]=vcolumn(P2)
   86692 **
   86693 ** Store in register P3 the value of the P2-th column of
   86694 ** the current row of the virtual-table of cursor P1.
   86695 **
   86696 ** If the VColumn opcode is being used to fetch the value of
   86697 ** an unchanging column during an UPDATE operation, then the P5
   86698 ** value is 1.  Otherwise, P5 is 0.  The P5 value is returned
   86699 ** by sqlite3_vtab_nochange() routine can can be used
   86700 ** by virtual table implementations to return special "no-change"
   86701 ** marks which can be more efficient, depending on the virtual table.
   86702 */
   86703 case OP_VColumn: {
   86704   sqlite3_vtab *pVtab;
   86705   const sqlite3_module *pModule;
   86706   Mem *pDest;
   86707   sqlite3_context sContext;
   86708 
   86709   VdbeCursor *pCur = p->apCsr[pOp->p1];
   86710   assert( pCur->eCurType==CURTYPE_VTAB );
   86711   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   86712   pDest = &aMem[pOp->p3];
   86713   memAboutToChange(p, pDest);
   86714   if( pCur->nullRow ){
   86715     sqlite3VdbeMemSetNull(pDest);
   86716     break;
   86717   }
   86718   pVtab = pCur->uc.pVCur->pVtab;
   86719   pModule = pVtab->pModule;
   86720   assert( pModule->xColumn );
   86721   memset(&sContext, 0, sizeof(sContext));
   86722   sContext.pOut = pDest;
   86723   if( pOp->p5 ){
   86724     sqlite3VdbeMemSetNull(pDest);
   86725     pDest->flags = MEM_Null|MEM_Zero;
   86726     pDest->u.nZero = 0;
   86727   }else{
   86728     MemSetTypeFlag(pDest, MEM_Null);
   86729   }
   86730   rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
   86731   sqlite3VtabImportErrmsg(p, pVtab);
   86732   if( sContext.isError ){
   86733     rc = sContext.isError;
   86734   }
   86735   sqlite3VdbeChangeEncoding(pDest, encoding);
   86736   REGISTER_TRACE(pOp->p3, pDest);
   86737   UPDATE_MAX_BLOBSIZE(pDest);
   86738 
   86739   if( sqlite3VdbeMemTooBig(pDest) ){
   86740     goto too_big;
   86741   }
   86742   if( rc ) goto abort_due_to_error;
   86743   break;
   86744 }
   86745 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86746 
   86747 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86748 /* Opcode: VNext P1 P2 * * *
   86749 **
   86750 ** Advance virtual table P1 to the next row in its result set and
   86751 ** jump to instruction P2.  Or, if the virtual table has reached
   86752 ** the end of its result set, then fall through to the next instruction.
   86753 */
   86754 case OP_VNext: {   /* jump */
   86755   sqlite3_vtab *pVtab;
   86756   const sqlite3_module *pModule;
   86757   int res;
   86758   VdbeCursor *pCur;
   86759 
   86760   res = 0;
   86761   pCur = p->apCsr[pOp->p1];
   86762   assert( pCur->eCurType==CURTYPE_VTAB );
   86763   if( pCur->nullRow ){
   86764     break;
   86765   }
   86766   pVtab = pCur->uc.pVCur->pVtab;
   86767   pModule = pVtab->pModule;
   86768   assert( pModule->xNext );
   86769 
   86770   /* Invoke the xNext() method of the module. There is no way for the
   86771   ** underlying implementation to return an error if one occurs during
   86772   ** xNext(). Instead, if an error occurs, true is returned (indicating that
   86773   ** data is available) and the error code returned when xColumn or
   86774   ** some other method is next invoked on the save virtual table cursor.
   86775   */
   86776   rc = pModule->xNext(pCur->uc.pVCur);
   86777   sqlite3VtabImportErrmsg(p, pVtab);
   86778   if( rc ) goto abort_due_to_error;
   86779   res = pModule->xEof(pCur->uc.pVCur);
   86780   VdbeBranchTaken(!res,2);
   86781   if( !res ){
   86782     /* If there is data, jump to P2 */
   86783     goto jump_to_p2_and_check_for_interrupt;
   86784   }
   86785   goto check_for_interrupt;
   86786 }
   86787 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86788 
   86789 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86790 /* Opcode: VRename P1 * * P4 *
   86791 **
   86792 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   86793 ** This opcode invokes the corresponding xRename method. The value
   86794 ** in register P1 is passed as the zName argument to the xRename method.
   86795 */
   86796 case OP_VRename: {
   86797   sqlite3_vtab *pVtab;
   86798   Mem *pName;
   86799 
   86800   pVtab = pOp->p4.pVtab->pVtab;
   86801   pName = &aMem[pOp->p1];
   86802   assert( pVtab->pModule->xRename );
   86803   assert( memIsValid(pName) );
   86804   assert( p->readOnly==0 );
   86805   REGISTER_TRACE(pOp->p1, pName);
   86806   assert( pName->flags & MEM_Str );
   86807   testcase( pName->enc==SQLITE_UTF8 );
   86808   testcase( pName->enc==SQLITE_UTF16BE );
   86809   testcase( pName->enc==SQLITE_UTF16LE );
   86810   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
   86811   if( rc ) goto abort_due_to_error;
   86812   rc = pVtab->pModule->xRename(pVtab, pName->z);
   86813   sqlite3VtabImportErrmsg(p, pVtab);
   86814   p->expired = 0;
   86815   if( rc ) goto abort_due_to_error;
   86816   break;
   86817 }
   86818 #endif
   86819 
   86820 #ifndef SQLITE_OMIT_VIRTUALTABLE
   86821 /* Opcode: VUpdate P1 P2 P3 P4 P5
   86822 ** Synopsis: data=r[P3@P2]
   86823 **
   86824 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   86825 ** This opcode invokes the corresponding xUpdate method. P2 values
   86826 ** are contiguous memory cells starting at P3 to pass to the xUpdate
   86827 ** invocation. The value in register (P3+P2-1) corresponds to the
   86828 ** p2th element of the argv array passed to xUpdate.
   86829 **
   86830 ** The xUpdate method will do a DELETE or an INSERT or both.
   86831 ** The argv[0] element (which corresponds to memory cell P3)
   86832 ** is the rowid of a row to delete.  If argv[0] is NULL then no
   86833 ** deletion occurs.  The argv[1] element is the rowid of the new
   86834 ** row.  This can be NULL to have the virtual table select the new
   86835 ** rowid for itself.  The subsequent elements in the array are
   86836 ** the values of columns in the new row.
   86837 **
   86838 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
   86839 ** a row to delete.
   86840 **
   86841 ** P1 is a boolean flag. If it is set to true and the xUpdate call
   86842 ** is successful, then the value returned by sqlite3_last_insert_rowid()
   86843 ** is set to the value of the rowid for the row just inserted.
   86844 **
   86845 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
   86846 ** apply in the case of a constraint failure on an insert or update.
   86847 */
   86848 case OP_VUpdate: {
   86849   sqlite3_vtab *pVtab;
   86850   const sqlite3_module *pModule;
   86851   int nArg;
   86852   int i;
   86853   sqlite_int64 rowid;
   86854   Mem **apArg;
   86855   Mem *pX;
   86856 
   86857   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
   86858        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
   86859   );
   86860   assert( p->readOnly==0 );
   86861   pVtab = pOp->p4.pVtab->pVtab;
   86862   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
   86863     rc = SQLITE_LOCKED;
   86864     goto abort_due_to_error;
   86865   }
   86866   pModule = pVtab->pModule;
   86867   nArg = pOp->p2;
   86868   assert( pOp->p4type==P4_VTAB );
   86869   if( ALWAYS(pModule->xUpdate) ){
   86870     u8 vtabOnConflict = db->vtabOnConflict;
   86871     apArg = p->apArg;
   86872     pX = &aMem[pOp->p3];
   86873     for(i=0; i<nArg; i++){
   86874       assert( memIsValid(pX) );
   86875       memAboutToChange(p, pX);
   86876       apArg[i] = pX;
   86877       pX++;
   86878     }
   86879     db->vtabOnConflict = pOp->p5;
   86880     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
   86881     db->vtabOnConflict = vtabOnConflict;
   86882     sqlite3VtabImportErrmsg(p, pVtab);
   86883     if( rc==SQLITE_OK && pOp->p1 ){
   86884       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
   86885       db->lastRowid = rowid;
   86886     }
   86887     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
   86888       if( pOp->p5==OE_Ignore ){
   86889         rc = SQLITE_OK;
   86890       }else{
   86891         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
   86892       }
   86893     }else{
   86894       p->nChange++;
   86895     }
   86896     if( rc ) goto abort_due_to_error;
   86897   }
   86898   break;
   86899 }
   86900 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86901 
   86902 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   86903 /* Opcode: Pagecount P1 P2 * * *
   86904 **
   86905 ** Write the current number of pages in database P1 to memory cell P2.
   86906 */
   86907 case OP_Pagecount: {            /* out2 */
   86908   pOut = out2Prerelease(p, pOp);
   86909   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
   86910   break;
   86911 }
   86912 #endif
   86913 
   86914 
   86915 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   86916 /* Opcode: MaxPgcnt P1 P2 P3 * *
   86917 **
   86918 ** Try to set the maximum page count for database P1 to the value in P3.
   86919 ** Do not let the maximum page count fall below the current page count and
   86920 ** do not change the maximum page count value if P3==0.
   86921 **
   86922 ** Store the maximum page count after the change in register P2.
   86923 */
   86924 case OP_MaxPgcnt: {            /* out2 */
   86925   unsigned int newMax;
   86926   Btree *pBt;
   86927 
   86928   pOut = out2Prerelease(p, pOp);
   86929   pBt = db->aDb[pOp->p1].pBt;
   86930   newMax = 0;
   86931   if( pOp->p3 ){
   86932     newMax = sqlite3BtreeLastPage(pBt);
   86933     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
   86934   }
   86935   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
   86936   break;
   86937 }
   86938 #endif
   86939 
   86940 /* Opcode: Function0 P1 P2 P3 P4 P5
   86941 ** Synopsis: r[P3]=func(r[P2@P5])
   86942 **
   86943 ** Invoke a user function (P4 is a pointer to a FuncDef object that
   86944 ** defines the function) with P5 arguments taken from register P2 and
   86945 ** successors.  The result of the function is stored in register P3.
   86946 ** Register P3 must not be one of the function inputs.
   86947 **
   86948 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   86949 ** function was determined to be constant at compile time. If the first
   86950 ** argument was constant then bit 0 of P1 is set. This is used to determine
   86951 ** whether meta data associated with a user function argument using the
   86952 ** sqlite3_set_auxdata() API may be safely retained until the next
   86953 ** invocation of this opcode.
   86954 **
   86955 ** See also: Function, AggStep, AggFinal
   86956 */
   86957 /* Opcode: Function P1 P2 P3 P4 P5
   86958 ** Synopsis: r[P3]=func(r[P2@P5])
   86959 **
   86960 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
   86961 ** contains a pointer to the function to be run) with P5 arguments taken
   86962 ** from register P2 and successors.  The result of the function is stored
   86963 ** in register P3.  Register P3 must not be one of the function inputs.
   86964 **
   86965 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   86966 ** function was determined to be constant at compile time. If the first
   86967 ** argument was constant then bit 0 of P1 is set. This is used to determine
   86968 ** whether meta data associated with a user function argument using the
   86969 ** sqlite3_set_auxdata() API may be safely retained until the next
   86970 ** invocation of this opcode.
   86971 **
   86972 ** SQL functions are initially coded as OP_Function0 with P4 pointing
   86973 ** to a FuncDef object.  But on first evaluation, the P4 operand is
   86974 ** automatically converted into an sqlite3_context object and the operation
   86975 ** changed to this OP_Function opcode.  In this way, the initialization of
   86976 ** the sqlite3_context object occurs only once, rather than once for each
   86977 ** evaluation of the function.
   86978 **
   86979 ** See also: Function0, AggStep, AggFinal
   86980 */
   86981 case OP_PureFunc0:
   86982 case OP_Function0: {
   86983   int n;
   86984   sqlite3_context *pCtx;
   86985 
   86986   assert( pOp->p4type==P4_FUNCDEF );
   86987   n = pOp->p5;
   86988   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   86989   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
   86990   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
   86991   pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
   86992   if( pCtx==0 ) goto no_mem;
   86993   pCtx->pOut = 0;
   86994   pCtx->pFunc = pOp->p4.pFunc;
   86995   pCtx->iOp = (int)(pOp - aOp);
   86996   pCtx->pVdbe = p;
   86997   pCtx->argc = n;
   86998   pOp->p4type = P4_FUNCCTX;
   86999   pOp->p4.pCtx = pCtx;
   87000   assert( OP_PureFunc == OP_PureFunc0+2 );
   87001   assert( OP_Function == OP_Function0+2 );
   87002   pOp->opcode += 2;
   87003   /* Fall through into OP_Function */
   87004 }
   87005 case OP_PureFunc:
   87006 case OP_Function: {
   87007   int i;
   87008   sqlite3_context *pCtx;
   87009 
   87010   assert( pOp->p4type==P4_FUNCCTX );
   87011   pCtx = pOp->p4.pCtx;
   87012 
   87013   /* If this function is inside of a trigger, the register array in aMem[]
   87014   ** might change from one evaluation to the next.  The next block of code
   87015   ** checks to see if the register array has changed, and if so it
   87016   ** reinitializes the relavant parts of the sqlite3_context object */
   87017   pOut = &aMem[pOp->p3];
   87018   if( pCtx->pOut != pOut ){
   87019     pCtx->pOut = pOut;
   87020     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
   87021   }
   87022 
   87023   memAboutToChange(p, pOut);
   87024 #ifdef SQLITE_DEBUG
   87025   for(i=0; i<pCtx->argc; i++){
   87026     assert( memIsValid(pCtx->argv[i]) );
   87027     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
   87028   }
   87029 #endif
   87030   MemSetTypeFlag(pOut, MEM_Null);
   87031   pCtx->fErrorOrAux = 0;
   87032   (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
   87033 
   87034   /* If the function returned an error, throw an exception */
   87035   if( pCtx->fErrorOrAux ){
   87036     if( pCtx->isError ){
   87037       sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
   87038       rc = pCtx->isError;
   87039     }
   87040     sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
   87041     if( rc ) goto abort_due_to_error;
   87042   }
   87043 
   87044   /* Copy the result of the function into register P3 */
   87045   if( pOut->flags & (MEM_Str|MEM_Blob) ){
   87046     sqlite3VdbeChangeEncoding(pOut, encoding);
   87047     if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
   87048   }
   87049 
   87050   REGISTER_TRACE(pOp->p3, pOut);
   87051   UPDATE_MAX_BLOBSIZE(pOut);
   87052   break;
   87053 }
   87054 
   87055 /* Opcode: Trace P1 P2 * P4 *
   87056 **
   87057 ** Write P4 on the statement trace output if statement tracing is
   87058 ** enabled.
   87059 **
   87060 ** Operand P1 must be 0x7fffffff and P2 must positive.
   87061 */
   87062 /* Opcode: Init P1 P2 P3 P4 *
   87063 ** Synopsis: Start at P2
   87064 **
   87065 ** Programs contain a single instance of this opcode as the very first
   87066 ** opcode.
   87067 **
   87068 ** If tracing is enabled (by the sqlite3_trace()) interface, then
   87069 ** the UTF-8 string contained in P4 is emitted on the trace callback.
   87070 ** Or if P4 is blank, use the string returned by sqlite3_sql().
   87071 **
   87072 ** If P2 is not zero, jump to instruction P2.
   87073 **
   87074 ** Increment the value of P1 so that OP_Once opcodes will jump the
   87075 ** first time they are evaluated for this run.
   87076 **
   87077 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
   87078 ** error is encountered.
   87079 */
   87080 case OP_Trace:
   87081 case OP_Init: {          /* jump */
   87082   char *zTrace;
   87083   int i;
   87084 
   87085   /* If the P4 argument is not NULL, then it must be an SQL comment string.
   87086   ** The "--" string is broken up to prevent false-positives with srcck1.c.
   87087   **
   87088   ** This assert() provides evidence for:
   87089   ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
   87090   ** would have been returned by the legacy sqlite3_trace() interface by
   87091   ** using the X argument when X begins with "--" and invoking
   87092   ** sqlite3_expanded_sql(P) otherwise.
   87093   */
   87094   assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
   87095 
   87096   /* OP_Init is always instruction 0 */
   87097   assert( pOp==p->aOp || pOp->opcode==OP_Trace );
   87098 
   87099 #ifndef SQLITE_OMIT_TRACE
   87100   if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
   87101    && !p->doingRerun
   87102    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   87103   ){
   87104 #ifndef SQLITE_OMIT_DEPRECATED
   87105     if( db->mTrace & SQLITE_TRACE_LEGACY ){
   87106       void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
   87107       char *z = sqlite3VdbeExpandSql(p, zTrace);
   87108       x(db->pTraceArg, z);
   87109       sqlite3_free(z);
   87110     }else
   87111 #endif
   87112     if( db->nVdbeExec>1 ){
   87113       char *z = sqlite3MPrintf(db, "-- %s", zTrace);
   87114       (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
   87115       sqlite3DbFree(db, z);
   87116     }else{
   87117       (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
   87118     }
   87119   }
   87120 #ifdef SQLITE_USE_FCNTL_TRACE
   87121   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
   87122   if( zTrace ){
   87123     int j;
   87124     for(j=0; j<db->nDb; j++){
   87125       if( DbMaskTest(p->btreeMask, j)==0 ) continue;
   87126       sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
   87127     }
   87128   }
   87129 #endif /* SQLITE_USE_FCNTL_TRACE */
   87130 #ifdef SQLITE_DEBUG
   87131   if( (db->flags & SQLITE_SqlTrace)!=0
   87132    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   87133   ){
   87134     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
   87135   }
   87136 #endif /* SQLITE_DEBUG */
   87137 #endif /* SQLITE_OMIT_TRACE */
   87138   assert( pOp->p2>0 );
   87139   if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
   87140     if( pOp->opcode==OP_Trace ) break;
   87141     for(i=1; i<p->nOp; i++){
   87142       if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
   87143     }
   87144     pOp->p1 = 0;
   87145   }
   87146   pOp->p1++;
   87147   p->aCounter[SQLITE_STMTSTATUS_RUN]++;
   87148   goto jump_to_p2;
   87149 }
   87150 
   87151 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   87152 /* Opcode: CursorHint P1 * * P4 *
   87153 **
   87154 ** Provide a hint to cursor P1 that it only needs to return rows that
   87155 ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
   87156 ** to values currently held in registers.  TK_COLUMN terms in the P4
   87157 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
   87158 */
   87159 case OP_CursorHint: {
   87160   VdbeCursor *pC;
   87161 
   87162   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   87163   assert( pOp->p4type==P4_EXPR );
   87164   pC = p->apCsr[pOp->p1];
   87165   if( pC ){
   87166     assert( pC->eCurType==CURTYPE_BTREE );
   87167     sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
   87168                            pOp->p4.pExpr, aMem);
   87169   }
   87170   break;
   87171 }
   87172 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
   87173 
   87174 /* Opcode: Noop * * * * *
   87175 **
   87176 ** Do nothing.  This instruction is often useful as a jump
   87177 ** destination.
   87178 */
   87179 /*
   87180 ** The magic Explain opcode are only inserted when explain==2 (which
   87181 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
   87182 ** This opcode records information from the optimizer.  It is the
   87183 ** the same as a no-op.  This opcodesnever appears in a real VM program.
   87184 */
   87185 default: {          /* This is really OP_Noop and OP_Explain */
   87186   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
   87187   break;
   87188 }
   87189 
   87190 /*****************************************************************************
   87191 ** The cases of the switch statement above this line should all be indented
   87192 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
   87193 ** readability.  From this point on down, the normal indentation rules are
   87194 ** restored.
   87195 *****************************************************************************/
   87196     }
   87197 
   87198 #ifdef VDBE_PROFILE
   87199     {
   87200       u64 endTime = sqlite3Hwtime();
   87201       if( endTime>start ) pOrigOp->cycles += endTime - start;
   87202       pOrigOp->cnt++;
   87203     }
   87204 #endif
   87205 
   87206     /* The following code adds nothing to the actual functionality
   87207     ** of the program.  It is only here for testing and debugging.
   87208     ** On the other hand, it does burn CPU cycles every time through
   87209     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
   87210     */
   87211 #ifndef NDEBUG
   87212     assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
   87213 
   87214 #ifdef SQLITE_DEBUG
   87215     if( db->flags & SQLITE_VdbeTrace ){
   87216       u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
   87217       if( rc!=0 ) printf("rc=%d\n",rc);
   87218       if( opProperty & (OPFLG_OUT2) ){
   87219         registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
   87220       }
   87221       if( opProperty & OPFLG_OUT3 ){
   87222         registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
   87223       }
   87224     }
   87225 #endif  /* SQLITE_DEBUG */
   87226 #endif  /* NDEBUG */
   87227   }  /* The end of the for(;;) loop the loops through opcodes */
   87228 
   87229   /* If we reach this point, it means that execution is finished with
   87230   ** an error of some kind.
   87231   */
   87232 abort_due_to_error:
   87233   if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
   87234   assert( rc );
   87235   if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
   87236     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
   87237   }
   87238   p->rc = rc;
   87239   sqlite3SystemError(db, rc);
   87240   testcase( sqlite3GlobalConfig.xLog!=0 );
   87241   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
   87242                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
   87243   sqlite3VdbeHalt(p);
   87244   if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
   87245   rc = SQLITE_ERROR;
   87246   if( resetSchemaOnFault>0 ){
   87247     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
   87248   }
   87249 
   87250   /* This is the only way out of this procedure.  We have to
   87251   ** release the mutexes on btrees that were acquired at the
   87252   ** top. */
   87253 vdbe_return:
   87254   testcase( nVmStep>0 );
   87255   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
   87256   sqlite3VdbeLeave(p);
   87257   assert( rc!=SQLITE_OK || nExtraDelete==0
   87258        || sqlite3_strlike("DELETE%",p->zSql,0)!=0
   87259   );
   87260   return rc;
   87261 
   87262   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
   87263   ** is encountered.
   87264   */
   87265 too_big:
   87266   sqlite3VdbeError(p, "string or blob too big");
   87267   rc = SQLITE_TOOBIG;
   87268   goto abort_due_to_error;
   87269 
   87270   /* Jump to here if a malloc() fails.
   87271   */
   87272 no_mem:
   87273   sqlite3OomFault(db);
   87274   sqlite3VdbeError(p, "out of memory");
   87275   rc = SQLITE_NOMEM_BKPT;
   87276   goto abort_due_to_error;
   87277 
   87278   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
   87279   ** flag.
   87280   */
   87281 abort_due_to_interrupt:
   87282   assert( db->u1.isInterrupted );
   87283   rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
   87284   p->rc = rc;
   87285   sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
   87286   goto abort_due_to_error;
   87287 }
   87288 
   87289 
   87290 /************** End of vdbe.c ************************************************/
   87291 /************** Begin file vdbeblob.c ****************************************/
   87292 /*
   87293 ** 2007 May 1
   87294 **
   87295 ** The author disclaims copyright to this source code.  In place of
   87296 ** a legal notice, here is a blessing:
   87297 **
   87298 **    May you do good and not evil.
   87299 **    May you find forgiveness for yourself and forgive others.
   87300 **    May you share freely, never taking more than you give.
   87301 **
   87302 *************************************************************************
   87303 **
   87304 ** This file contains code used to implement incremental BLOB I/O.
   87305 */
   87306 
   87307 /* #include "sqliteInt.h" */
   87308 /* #include "vdbeInt.h" */
   87309 
   87310 #ifndef SQLITE_OMIT_INCRBLOB
   87311 
   87312 /*
   87313 ** Valid sqlite3_blob* handles point to Incrblob structures.
   87314 */
   87315 typedef struct Incrblob Incrblob;
   87316 struct Incrblob {
   87317   int nByte;              /* Size of open blob, in bytes */
   87318   int iOffset;            /* Byte offset of blob in cursor data */
   87319   u16 iCol;               /* Table column this handle is open on */
   87320   BtCursor *pCsr;         /* Cursor pointing at blob row */
   87321   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
   87322   sqlite3 *db;            /* The associated database */
   87323   char *zDb;              /* Database name */
   87324   Table *pTab;            /* Table object */
   87325 };
   87326 
   87327 
   87328 /*
   87329 ** This function is used by both blob_open() and blob_reopen(). It seeks
   87330 ** the b-tree cursor associated with blob handle p to point to row iRow.
   87331 ** If successful, SQLITE_OK is returned and subsequent calls to
   87332 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
   87333 **
   87334 ** If an error occurs, or if the specified row does not exist or does not
   87335 ** contain a value of type TEXT or BLOB in the column nominated when the
   87336 ** blob handle was opened, then an error code is returned and *pzErr may
   87337 ** be set to point to a buffer containing an error message. It is the
   87338 ** responsibility of the caller to free the error message buffer using
   87339 ** sqlite3DbFree().
   87340 **
   87341 ** If an error does occur, then the b-tree cursor is closed. All subsequent
   87342 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
   87343 ** immediately return SQLITE_ABORT.
   87344 */
   87345 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   87346   int rc;                         /* Error code */
   87347   char *zErr = 0;                 /* Error message */
   87348   Vdbe *v = (Vdbe *)p->pStmt;
   87349 
   87350   /* Set the value of register r[1] in the SQL statement to integer iRow.
   87351   ** This is done directly as a performance optimization
   87352   */
   87353   v->aMem[1].flags = MEM_Int;
   87354   v->aMem[1].u.i = iRow;
   87355 
   87356   /* If the statement has been run before (and is paused at the OP_ResultRow)
   87357   ** then back it up to the point where it does the OP_NotExists.  This could
   87358   ** have been down with an extra OP_Goto, but simply setting the program
   87359   ** counter is faster. */
   87360   if( v->pc>4 ){
   87361     v->pc = 4;
   87362     assert( v->aOp[v->pc].opcode==OP_NotExists );
   87363     rc = sqlite3VdbeExec(v);
   87364   }else{
   87365     rc = sqlite3_step(p->pStmt);
   87366   }
   87367   if( rc==SQLITE_ROW ){
   87368     VdbeCursor *pC = v->apCsr[0];
   87369     u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
   87370     testcase( pC->nHdrParsed==p->iCol );
   87371     testcase( pC->nHdrParsed==p->iCol+1 );
   87372     if( type<12 ){
   87373       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
   87374           type==0?"null": type==7?"real": "integer"
   87375       );
   87376       rc = SQLITE_ERROR;
   87377       sqlite3_finalize(p->pStmt);
   87378       p->pStmt = 0;
   87379     }else{
   87380       p->iOffset = pC->aType[p->iCol + pC->nField];
   87381       p->nByte = sqlite3VdbeSerialTypeLen(type);
   87382       p->pCsr =  pC->uc.pCursor;
   87383       sqlite3BtreeIncrblobCursor(p->pCsr);
   87384     }
   87385   }
   87386 
   87387   if( rc==SQLITE_ROW ){
   87388     rc = SQLITE_OK;
   87389   }else if( p->pStmt ){
   87390     rc = sqlite3_finalize(p->pStmt);
   87391     p->pStmt = 0;
   87392     if( rc==SQLITE_OK ){
   87393       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
   87394       rc = SQLITE_ERROR;
   87395     }else{
   87396       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
   87397     }
   87398   }
   87399 
   87400   assert( rc!=SQLITE_OK || zErr==0 );
   87401   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
   87402 
   87403   *pzErr = zErr;
   87404   return rc;
   87405 }
   87406 
   87407 /*
   87408 ** Open a blob handle.
   87409 */
   87410 SQLITE_API int sqlite3_blob_open(
   87411   sqlite3* db,            /* The database connection */
   87412   const char *zDb,        /* The attached database containing the blob */
   87413   const char *zTable,     /* The table containing the blob */
   87414   const char *zColumn,    /* The column containing the blob */
   87415   sqlite_int64 iRow,      /* The row containing the glob */
   87416   int wrFlag,             /* True -> read/write access, false -> read-only */
   87417   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
   87418 ){
   87419   int nAttempt = 0;
   87420   int iCol;               /* Index of zColumn in row-record */
   87421   int rc = SQLITE_OK;
   87422   char *zErr = 0;
   87423   Table *pTab;
   87424   Incrblob *pBlob = 0;
   87425   Parse sParse;
   87426 
   87427 #ifdef SQLITE_ENABLE_API_ARMOR
   87428   if( ppBlob==0 ){
   87429     return SQLITE_MISUSE_BKPT;
   87430   }
   87431 #endif
   87432   *ppBlob = 0;
   87433 #ifdef SQLITE_ENABLE_API_ARMOR
   87434   if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
   87435     return SQLITE_MISUSE_BKPT;
   87436   }
   87437 #endif
   87438   wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */
   87439 
   87440   sqlite3_mutex_enter(db->mutex);
   87441 
   87442   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
   87443   do {
   87444     memset(&sParse, 0, sizeof(Parse));
   87445     if( !pBlob ) goto blob_open_out;
   87446     sParse.db = db;
   87447     sqlite3DbFree(db, zErr);
   87448     zErr = 0;
   87449 
   87450     sqlite3BtreeEnterAll(db);
   87451     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
   87452     if( pTab && IsVirtual(pTab) ){
   87453       pTab = 0;
   87454       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
   87455     }
   87456     if( pTab && !HasRowid(pTab) ){
   87457       pTab = 0;
   87458       sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
   87459     }
   87460 #ifndef SQLITE_OMIT_VIEW
   87461     if( pTab && pTab->pSelect ){
   87462       pTab = 0;
   87463       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
   87464     }
   87465 #endif
   87466     if( !pTab ){
   87467       if( sParse.zErrMsg ){
   87468         sqlite3DbFree(db, zErr);
   87469         zErr = sParse.zErrMsg;
   87470         sParse.zErrMsg = 0;
   87471       }
   87472       rc = SQLITE_ERROR;
   87473       sqlite3BtreeLeaveAll(db);
   87474       goto blob_open_out;
   87475     }
   87476     pBlob->pTab = pTab;
   87477     pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
   87478 
   87479     /* Now search pTab for the exact column. */
   87480     for(iCol=0; iCol<pTab->nCol; iCol++) {
   87481       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   87482         break;
   87483       }
   87484     }
   87485     if( iCol==pTab->nCol ){
   87486       sqlite3DbFree(db, zErr);
   87487       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
   87488       rc = SQLITE_ERROR;
   87489       sqlite3BtreeLeaveAll(db);
   87490       goto blob_open_out;
   87491     }
   87492 
   87493     /* If the value is being opened for writing, check that the
   87494     ** column is not indexed, and that it is not part of a foreign key.
   87495     */
   87496     if( wrFlag ){
   87497       const char *zFault = 0;
   87498       Index *pIdx;
   87499 #ifndef SQLITE_OMIT_FOREIGN_KEY
   87500       if( db->flags&SQLITE_ForeignKeys ){
   87501         /* Check that the column is not part of an FK child key definition. It
   87502         ** is not necessary to check if it is part of a parent key, as parent
   87503         ** key columns must be indexed. The check below will pick up this
   87504         ** case.  */
   87505         FKey *pFKey;
   87506         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   87507           int j;
   87508           for(j=0; j<pFKey->nCol; j++){
   87509             if( pFKey->aCol[j].iFrom==iCol ){
   87510               zFault = "foreign key";
   87511             }
   87512           }
   87513         }
   87514       }
   87515 #endif
   87516       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   87517         int j;
   87518         for(j=0; j<pIdx->nKeyCol; j++){
   87519           /* FIXME: Be smarter about indexes that use expressions */
   87520           if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
   87521             zFault = "indexed";
   87522           }
   87523         }
   87524       }
   87525       if( zFault ){
   87526         sqlite3DbFree(db, zErr);
   87527         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
   87528         rc = SQLITE_ERROR;
   87529         sqlite3BtreeLeaveAll(db);
   87530         goto blob_open_out;
   87531       }
   87532     }
   87533 
   87534     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
   87535     assert( pBlob->pStmt || db->mallocFailed );
   87536     if( pBlob->pStmt ){
   87537 
   87538       /* This VDBE program seeks a btree cursor to the identified
   87539       ** db/table/row entry. The reason for using a vdbe program instead
   87540       ** of writing code to use the b-tree layer directly is that the
   87541       ** vdbe program will take advantage of the various transaction,
   87542       ** locking and error handling infrastructure built into the vdbe.
   87543       **
   87544       ** After seeking the cursor, the vdbe executes an OP_ResultRow.
   87545       ** Code external to the Vdbe then "borrows" the b-tree cursor and
   87546       ** uses it to implement the blob_read(), blob_write() and
   87547       ** blob_bytes() functions.
   87548       **
   87549       ** The sqlite3_blob_close() function finalizes the vdbe program,
   87550       ** which closes the b-tree cursor and (possibly) commits the
   87551       ** transaction.
   87552       */
   87553       static const int iLn = VDBE_OFFSET_LINENO(2);
   87554       static const VdbeOpList openBlob[] = {
   87555         {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
   87556         {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
   87557         /* blobSeekToRow() will initialize r[1] to the desired rowid */
   87558         {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */
   87559         {OP_Column,         0, 0, 1},  /* 3  */
   87560         {OP_ResultRow,      1, 0, 0},  /* 4  */
   87561         {OP_Halt,           0, 0, 0},  /* 5  */
   87562       };
   87563       Vdbe *v = (Vdbe *)pBlob->pStmt;
   87564       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   87565       VdbeOp *aOp;
   87566 
   87567       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
   87568                            pTab->pSchema->schema_cookie,
   87569                            pTab->pSchema->iGeneration);
   87570       sqlite3VdbeChangeP5(v, 1);
   87571       assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
   87572       aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
   87573 
   87574       /* Make sure a mutex is held on the table to be accessed */
   87575       sqlite3VdbeUsesBtree(v, iDb);
   87576 
   87577       if( db->mallocFailed==0 ){
   87578         assert( aOp!=0 );
   87579         /* Configure the OP_TableLock instruction */
   87580 #ifdef SQLITE_OMIT_SHARED_CACHE
   87581         aOp[0].opcode = OP_Noop;
   87582 #else
   87583         aOp[0].p1 = iDb;
   87584         aOp[0].p2 = pTab->tnum;
   87585         aOp[0].p3 = wrFlag;
   87586         sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
   87587       }
   87588       if( db->mallocFailed==0 ){
   87589 #endif
   87590 
   87591         /* Remove either the OP_OpenWrite or OpenRead. Set the P2
   87592         ** parameter of the other to pTab->tnum.  */
   87593         if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
   87594         aOp[1].p2 = pTab->tnum;
   87595         aOp[1].p3 = iDb;
   87596 
   87597         /* Configure the number of columns. Configure the cursor to
   87598         ** think that the table has one more column than it really
   87599         ** does. An OP_Column to retrieve this imaginary column will
   87600         ** always return an SQL NULL. This is useful because it means
   87601         ** we can invoke OP_Column to fill in the vdbe cursors type
   87602         ** and offset cache without causing any IO.
   87603         */
   87604         aOp[1].p4type = P4_INT32;
   87605         aOp[1].p4.i = pTab->nCol+1;
   87606         aOp[3].p2 = pTab->nCol;
   87607 
   87608         sParse.nVar = 0;
   87609         sParse.nMem = 1;
   87610         sParse.nTab = 1;
   87611         sqlite3VdbeMakeReady(v, &sParse);
   87612       }
   87613     }
   87614 
   87615     pBlob->iCol = iCol;
   87616     pBlob->db = db;
   87617     sqlite3BtreeLeaveAll(db);
   87618     if( db->mallocFailed ){
   87619       goto blob_open_out;
   87620     }
   87621     rc = blobSeekToRow(pBlob, iRow, &zErr);
   87622   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
   87623 
   87624 blob_open_out:
   87625   if( rc==SQLITE_OK && db->mallocFailed==0 ){
   87626     *ppBlob = (sqlite3_blob *)pBlob;
   87627   }else{
   87628     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
   87629     sqlite3DbFree(db, pBlob);
   87630   }
   87631   sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
   87632   sqlite3DbFree(db, zErr);
   87633   sqlite3ParserReset(&sParse);
   87634   rc = sqlite3ApiExit(db, rc);
   87635   sqlite3_mutex_leave(db->mutex);
   87636   return rc;
   87637 }
   87638 
   87639 /*
   87640 ** Close a blob handle that was previously created using
   87641 ** sqlite3_blob_open().
   87642 */
   87643 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
   87644   Incrblob *p = (Incrblob *)pBlob;
   87645   int rc;
   87646   sqlite3 *db;
   87647 
   87648   if( p ){
   87649     db = p->db;
   87650     sqlite3_mutex_enter(db->mutex);
   87651     rc = sqlite3_finalize(p->pStmt);
   87652     sqlite3DbFree(db, p);
   87653     sqlite3_mutex_leave(db->mutex);
   87654   }else{
   87655     rc = SQLITE_OK;
   87656   }
   87657   return rc;
   87658 }
   87659 
   87660 /*
   87661 ** Perform a read or write operation on a blob
   87662 */
   87663 static int blobReadWrite(
   87664   sqlite3_blob *pBlob,
   87665   void *z,
   87666   int n,
   87667   int iOffset,
   87668   int (*xCall)(BtCursor*, u32, u32, void*)
   87669 ){
   87670   int rc;
   87671   Incrblob *p = (Incrblob *)pBlob;
   87672   Vdbe *v;
   87673   sqlite3 *db;
   87674 
   87675   if( p==0 ) return SQLITE_MISUSE_BKPT;
   87676   db = p->db;
   87677   sqlite3_mutex_enter(db->mutex);
   87678   v = (Vdbe*)p->pStmt;
   87679 
   87680   if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
   87681     /* Request is out of range. Return a transient error. */
   87682     rc = SQLITE_ERROR;
   87683   }else if( v==0 ){
   87684     /* If there is no statement handle, then the blob-handle has
   87685     ** already been invalidated. Return SQLITE_ABORT in this case.
   87686     */
   87687     rc = SQLITE_ABORT;
   87688   }else{
   87689     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
   87690     ** returned, clean-up the statement handle.
   87691     */
   87692     assert( db == v->db );
   87693     sqlite3BtreeEnterCursor(p->pCsr);
   87694 
   87695 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   87696     if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
   87697       /* If a pre-update hook is registered and this is a write cursor,
   87698       ** invoke it here.
   87699       **
   87700       ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
   87701       ** operation should really be an SQLITE_UPDATE. This is probably
   87702       ** incorrect, but is convenient because at this point the new.* values
   87703       ** are not easily obtainable. And for the sessions module, an
   87704       ** SQLITE_UPDATE where the PK columns do not change is handled in the
   87705       ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
   87706       ** slightly more efficient). Since you cannot write to a PK column
   87707       ** using the incremental-blob API, this works. For the sessions module
   87708       ** anyhow.
   87709       */
   87710       sqlite3_int64 iKey;
   87711       iKey = sqlite3BtreeIntegerKey(p->pCsr);
   87712       sqlite3VdbePreUpdateHook(
   87713           v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
   87714       );
   87715     }
   87716 #endif
   87717 
   87718     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
   87719     sqlite3BtreeLeaveCursor(p->pCsr);
   87720     if( rc==SQLITE_ABORT ){
   87721       sqlite3VdbeFinalize(v);
   87722       p->pStmt = 0;
   87723     }else{
   87724       v->rc = rc;
   87725     }
   87726   }
   87727   sqlite3Error(db, rc);
   87728   rc = sqlite3ApiExit(db, rc);
   87729   sqlite3_mutex_leave(db->mutex);
   87730   return rc;
   87731 }
   87732 
   87733 /*
   87734 ** Read data from a blob handle.
   87735 */
   87736 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
   87737   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
   87738 }
   87739 
   87740 /*
   87741 ** Write data to a blob handle.
   87742 */
   87743 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
   87744   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
   87745 }
   87746 
   87747 /*
   87748 ** Query a blob handle for the size of the data.
   87749 **
   87750 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
   87751 ** so no mutex is required for access.
   87752 */
   87753 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
   87754   Incrblob *p = (Incrblob *)pBlob;
   87755   return (p && p->pStmt) ? p->nByte : 0;
   87756 }
   87757 
   87758 /*
   87759 ** Move an existing blob handle to point to a different row of the same
   87760 ** database table.
   87761 **
   87762 ** If an error occurs, or if the specified row does not exist or does not
   87763 ** contain a blob or text value, then an error code is returned and the
   87764 ** database handle error code and message set. If this happens, then all
   87765 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
   87766 ** immediately return SQLITE_ABORT.
   87767 */
   87768 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
   87769   int rc;
   87770   Incrblob *p = (Incrblob *)pBlob;
   87771   sqlite3 *db;
   87772 
   87773   if( p==0 ) return SQLITE_MISUSE_BKPT;
   87774   db = p->db;
   87775   sqlite3_mutex_enter(db->mutex);
   87776 
   87777   if( p->pStmt==0 ){
   87778     /* If there is no statement handle, then the blob-handle has
   87779     ** already been invalidated. Return SQLITE_ABORT in this case.
   87780     */
   87781     rc = SQLITE_ABORT;
   87782   }else{
   87783     char *zErr;
   87784     rc = blobSeekToRow(p, iRow, &zErr);
   87785     if( rc!=SQLITE_OK ){
   87786       sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
   87787       sqlite3DbFree(db, zErr);
   87788     }
   87789     assert( rc!=SQLITE_SCHEMA );
   87790   }
   87791 
   87792   rc = sqlite3ApiExit(db, rc);
   87793   assert( rc==SQLITE_OK || p->pStmt==0 );
   87794   sqlite3_mutex_leave(db->mutex);
   87795   return rc;
   87796 }
   87797 
   87798 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
   87799 
   87800 /************** End of vdbeblob.c ********************************************/
   87801 /************** Begin file vdbesort.c ****************************************/
   87802 /*
   87803 ** 2011-07-09
   87804 **
   87805 ** The author disclaims copyright to this source code.  In place of
   87806 ** a legal notice, here is a blessing:
   87807 **
   87808 **    May you do good and not evil.
   87809 **    May you find forgiveness for yourself and forgive others.
   87810 **    May you share freely, never taking more than you give.
   87811 **
   87812 *************************************************************************
   87813 ** This file contains code for the VdbeSorter object, used in concert with
   87814 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
   87815 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
   87816 ** using indexes and without LIMIT clauses.
   87817 **
   87818 ** The VdbeSorter object implements a multi-threaded external merge sort
   87819 ** algorithm that is efficient even if the number of elements being sorted
   87820 ** exceeds the available memory.
   87821 **
   87822 ** Here is the (internal, non-API) interface between this module and the
   87823 ** rest of the SQLite system:
   87824 **
   87825 **    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
   87826 **
   87827 **    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
   87828 **                                  object.  The row is a binary blob in the
   87829 **                                  OP_MakeRecord format that contains both
   87830 **                                  the ORDER BY key columns and result columns
   87831 **                                  in the case of a SELECT w/ ORDER BY, or
   87832 **                                  the complete record for an index entry
   87833 **                                  in the case of a CREATE INDEX.
   87834 **
   87835 **    sqlite3VdbeSorterRewind()     Sort all content previously added.
   87836 **                                  Position the read cursor on the
   87837 **                                  first sorted element.
   87838 **
   87839 **    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
   87840 **                                  element.
   87841 **
   87842 **    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
   87843 **                                  row currently under the read cursor.
   87844 **
   87845 **    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
   87846 **                                  currently under the read cursor against
   87847 **                                  another binary blob X and report if
   87848 **                                  X is strictly less than the read cursor.
   87849 **                                  Used to enforce uniqueness in a
   87850 **                                  CREATE UNIQUE INDEX statement.
   87851 **
   87852 **    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
   87853 **                                  all resources.
   87854 **
   87855 **    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
   87856 **                                  is like Close() followed by Init() only
   87857 **                                  much faster.
   87858 **
   87859 ** The interfaces above must be called in a particular order.  Write() can
   87860 ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
   87861 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
   87862 **
   87863 **   Init()
   87864 **   for each record: Write()
   87865 **   Rewind()
   87866 **     Rowkey()/Compare()
   87867 **   Next()
   87868 **   Close()
   87869 **
   87870 ** Algorithm:
   87871 **
   87872 ** Records passed to the sorter via calls to Write() are initially held
   87873 ** unsorted in main memory. Assuming the amount of memory used never exceeds
   87874 ** a threshold, when Rewind() is called the set of records is sorted using
   87875 ** an in-memory merge sort. In this case, no temporary files are required
   87876 ** and subsequent calls to Rowkey(), Next() and Compare() read records
   87877 ** directly from main memory.
   87878 **
   87879 ** If the amount of space used to store records in main memory exceeds the
   87880 ** threshold, then the set of records currently in memory are sorted and
   87881 ** written to a temporary file in "Packed Memory Array" (PMA) format.
   87882 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
   87883 ** of PMAs may be created by merging existing PMAs together - for example
   87884 ** merging two or more level-0 PMAs together creates a level-1 PMA.
   87885 **
   87886 ** The threshold for the amount of main memory to use before flushing
   87887 ** records to a PMA is roughly the same as the limit configured for the
   87888 ** page-cache of the main database. Specifically, the threshold is set to
   87889 ** the value returned by "PRAGMA main.page_size" multipled by
   87890 ** that returned by "PRAGMA main.cache_size", in bytes.
   87891 **
   87892 ** If the sorter is running in single-threaded mode, then all PMAs generated
   87893 ** are appended to a single temporary file. Or, if the sorter is running in
   87894 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
   87895 ** N is the configured number of worker threads. In this case, instead of
   87896 ** sorting the records and writing the PMA to a temporary file itself, the
   87897 ** calling thread usually launches a worker thread to do so. Except, if
   87898 ** there are already N worker threads running, the main thread does the work
   87899 ** itself.
   87900 **
   87901 ** The sorter is running in multi-threaded mode if (a) the library was built
   87902 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
   87903 ** than zero, and (b) worker threads have been enabled at runtime by calling
   87904 ** "PRAGMA threads=N" with some value of N greater than 0.
   87905 **
   87906 ** When Rewind() is called, any data remaining in memory is flushed to a
   87907 ** final PMA. So at this point the data is stored in some number of sorted
   87908 ** PMAs within temporary files on disk.
   87909 **
   87910 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
   87911 ** sorter is running in single-threaded mode, then these PMAs are merged
   87912 ** incrementally as keys are retreived from the sorter by the VDBE.  The
   87913 ** MergeEngine object, described in further detail below, performs this
   87914 ** merge.
   87915 **
   87916 ** Or, if running in multi-threaded mode, then a background thread is
   87917 ** launched to merge the existing PMAs. Once the background thread has
   87918 ** merged T bytes of data into a single sorted PMA, the main thread
   87919 ** begins reading keys from that PMA while the background thread proceeds
   87920 ** with merging the next T bytes of data. And so on.
   87921 **
   87922 ** Parameter T is set to half the value of the memory threshold used
   87923 ** by Write() above to determine when to create a new PMA.
   87924 **
   87925 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
   87926 ** Rewind() is called, then a hierarchy of incremental-merges is used.
   87927 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
   87928 ** disk are merged together. Then T bytes of data from the second set, and
   87929 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
   87930 ** PMAs at a time. This done is to improve locality.
   87931 **
   87932 ** If running in multi-threaded mode and there are more than
   87933 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
   87934 ** than one background thread may be created. Specifically, there may be
   87935 ** one background thread for each temporary file on disk, and one background
   87936 ** thread to merge the output of each of the others to a single PMA for
   87937 ** the main thread to read from.
   87938 */
   87939 /* #include "sqliteInt.h" */
   87940 /* #include "vdbeInt.h" */
   87941 
   87942 /*
   87943 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
   87944 ** messages to stderr that may be helpful in understanding the performance
   87945 ** characteristics of the sorter in multi-threaded mode.
   87946 */
   87947 #if 0
   87948 # define SQLITE_DEBUG_SORTER_THREADS 1
   87949 #endif
   87950 
   87951 /*
   87952 ** Hard-coded maximum amount of data to accumulate in memory before flushing
   87953 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
   87954 ** overflows. 512MiB.
   87955 */
   87956 #define SQLITE_MAX_PMASZ    (1<<29)
   87957 
   87958 /*
   87959 ** Private objects used by the sorter
   87960 */
   87961 typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
   87962 typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
   87963 typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
   87964 typedef struct SorterRecord SorterRecord;   /* A record being sorted */
   87965 typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
   87966 typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
   87967 typedef struct SorterList SorterList;       /* In-memory list of records */
   87968 typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
   87969 
   87970 /*
   87971 ** A container for a temp file handle and the current amount of data
   87972 ** stored in the file.
   87973 */
   87974 struct SorterFile {
   87975   sqlite3_file *pFd;              /* File handle */
   87976   i64 iEof;                       /* Bytes of data stored in pFd */
   87977 };
   87978 
   87979 /*
   87980 ** An in-memory list of objects to be sorted.
   87981 **
   87982 ** If aMemory==0 then each object is allocated separately and the objects
   87983 ** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
   87984 ** are stored in the aMemory[] bulk memory, one right after the other, and
   87985 ** are connected using SorterRecord.u.iNext.
   87986 */
   87987 struct SorterList {
   87988   SorterRecord *pList;            /* Linked list of records */
   87989   u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
   87990   int szPMA;                      /* Size of pList as PMA in bytes */
   87991 };
   87992 
   87993 /*
   87994 ** The MergeEngine object is used to combine two or more smaller PMAs into
   87995 ** one big PMA using a merge operation.  Separate PMAs all need to be
   87996 ** combined into one big PMA in order to be able to step through the sorted
   87997 ** records in order.
   87998 **
   87999 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
   88000 ** merged.  An aReadr[] object either points to a valid key or else is at EOF.
   88001 ** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
   88002 ** For the purposes of the paragraphs below, we assume that the array is
   88003 ** actually N elements in size, where N is the smallest power of 2 greater
   88004 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
   88005 ** are treated as if they are empty (always at EOF).
   88006 **
   88007 ** The aTree[] array is also N elements in size. The value of N is stored in
   88008 ** the MergeEngine.nTree variable.
   88009 **
   88010 ** The final (N/2) elements of aTree[] contain the results of comparing
   88011 ** pairs of PMA keys together. Element i contains the result of
   88012 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
   88013 ** aTree element is set to the index of it.
   88014 **
   88015 ** For the purposes of this comparison, EOF is considered greater than any
   88016 ** other key value. If the keys are equal (only possible with two EOF
   88017 ** values), it doesn't matter which index is stored.
   88018 **
   88019 ** The (N/4) elements of aTree[] that precede the final (N/2) described
   88020 ** above contains the index of the smallest of each block of 4 PmaReaders
   88021 ** And so on. So that aTree[1] contains the index of the PmaReader that
   88022 ** currently points to the smallest key value. aTree[0] is unused.
   88023 **
   88024 ** Example:
   88025 **
   88026 **     aReadr[0] -> Banana
   88027 **     aReadr[1] -> Feijoa
   88028 **     aReadr[2] -> Elderberry
   88029 **     aReadr[3] -> Currant
   88030 **     aReadr[4] -> Grapefruit
   88031 **     aReadr[5] -> Apple
   88032 **     aReadr[6] -> Durian
   88033 **     aReadr[7] -> EOF
   88034 **
   88035 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
   88036 **
   88037 ** The current element is "Apple" (the value of the key indicated by
   88038 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
   88039 ** be advanced to the next key in its segment. Say the next key is
   88040 ** "Eggplant":
   88041 **
   88042 **     aReadr[5] -> Eggplant
   88043 **
   88044 ** The contents of aTree[] are updated first by comparing the new PmaReader
   88045 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
   88046 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
   88047 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
   88048 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
   88049 ** so the value written into element 1 of the array is 0. As follows:
   88050 **
   88051 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
   88052 **
   88053 ** In other words, each time we advance to the next sorter element, log2(N)
   88054 ** key comparison operations are required, where N is the number of segments
   88055 ** being merged (rounded up to the next power of 2).
   88056 */
   88057 struct MergeEngine {
   88058   int nTree;                 /* Used size of aTree/aReadr (power of 2) */
   88059   SortSubtask *pTask;        /* Used by this thread only */
   88060   int *aTree;                /* Current state of incremental merge */
   88061   PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
   88062 };
   88063 
   88064 /*
   88065 ** This object represents a single thread of control in a sort operation.
   88066 ** Exactly VdbeSorter.nTask instances of this object are allocated
   88067 ** as part of each VdbeSorter object. Instances are never allocated any
   88068 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
   88069 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
   88070 ** single-threaded operation, there is exactly one instance of this object
   88071 ** and for multi-threaded operation there are two or more instances.
   88072 **
   88073 ** Essentially, this structure contains all those fields of the VdbeSorter
   88074 ** structure for which each thread requires a separate instance. For example,
   88075 ** each thread requries its own UnpackedRecord object to unpack records in
   88076 ** as part of comparison operations.
   88077 **
   88078 ** Before a background thread is launched, variable bDone is set to 0. Then,
   88079 ** right before it exits, the thread itself sets bDone to 1. This is used for
   88080 ** two purposes:
   88081 **
   88082 **   1. When flushing the contents of memory to a level-0 PMA on disk, to
   88083 **      attempt to select a SortSubtask for which there is not already an
   88084 **      active background thread (since doing so causes the main thread
   88085 **      to block until it finishes).
   88086 **
   88087 **   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
   88088 **      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
   88089 **      block provoke debugging output.
   88090 **
   88091 ** In both cases, the effects of the main thread seeing (bDone==0) even
   88092 ** after the thread has finished are not dire. So we don't worry about
   88093 ** memory barriers and such here.
   88094 */
   88095 typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
   88096 struct SortSubtask {
   88097   SQLiteThread *pThread;          /* Background thread, if any */
   88098   int bDone;                      /* Set if thread is finished but not joined */
   88099   VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
   88100   UnpackedRecord *pUnpacked;      /* Space to unpack a record */
   88101   SorterList list;                /* List for thread to write to a PMA */
   88102   int nPMA;                       /* Number of PMAs currently in file */
   88103   SorterCompare xCompare;         /* Compare function to use */
   88104   SorterFile file;                /* Temp file for level-0 PMAs */
   88105   SorterFile file2;               /* Space for other PMAs */
   88106 };
   88107 
   88108 
   88109 /*
   88110 ** Main sorter structure. A single instance of this is allocated for each
   88111 ** sorter cursor created by the VDBE.
   88112 **
   88113 ** mxKeysize:
   88114 **   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
   88115 **   this variable is updated so as to be set to the size on disk of the
   88116 **   largest record in the sorter.
   88117 */
   88118 struct VdbeSorter {
   88119   int mnPmaSize;                  /* Minimum PMA size, in bytes */
   88120   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
   88121   int mxKeysize;                  /* Largest serialized key seen so far */
   88122   int pgsz;                       /* Main database page size */
   88123   PmaReader *pReader;             /* Readr data from here after Rewind() */
   88124   MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
   88125   sqlite3 *db;                    /* Database connection */
   88126   KeyInfo *pKeyInfo;              /* How to compare records */
   88127   UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
   88128   SorterList list;                /* List of in-memory records */
   88129   int iMemory;                    /* Offset of free space in list.aMemory */
   88130   int nMemory;                    /* Size of list.aMemory allocation in bytes */
   88131   u8 bUsePMA;                     /* True if one or more PMAs created */
   88132   u8 bUseThreads;                 /* True to use background threads */
   88133   u8 iPrev;                       /* Previous thread used to flush PMA */
   88134   u8 nTask;                       /* Size of aTask[] array */
   88135   u8 typeMask;
   88136   SortSubtask aTask[1];           /* One or more subtasks */
   88137 };
   88138 
   88139 #define SORTER_TYPE_INTEGER 0x01
   88140 #define SORTER_TYPE_TEXT    0x02
   88141 
   88142 /*
   88143 ** An instance of the following object is used to read records out of a
   88144 ** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
   88145 ** aKey might point into aMap or into aBuffer.  If neither of those locations
   88146 ** contain a contiguous representation of the key, then aAlloc is allocated
   88147 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
   88148 **
   88149 ** pFd==0 at EOF.
   88150 */
   88151 struct PmaReader {
   88152   i64 iReadOff;               /* Current read offset */
   88153   i64 iEof;                   /* 1 byte past EOF for this PmaReader */
   88154   int nAlloc;                 /* Bytes of space at aAlloc */
   88155   int nKey;                   /* Number of bytes in key */
   88156   sqlite3_file *pFd;          /* File handle we are reading from */
   88157   u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
   88158   u8 *aKey;                   /* Pointer to current key */
   88159   u8 *aBuffer;                /* Current read buffer */
   88160   int nBuffer;                /* Size of read buffer in bytes */
   88161   u8 *aMap;                   /* Pointer to mapping of entire file */
   88162   IncrMerger *pIncr;          /* Incremental merger */
   88163 };
   88164 
   88165 /*
   88166 ** Normally, a PmaReader object iterates through an existing PMA stored
   88167 ** within a temp file. However, if the PmaReader.pIncr variable points to
   88168 ** an object of the following type, it may be used to iterate/merge through
   88169 ** multiple PMAs simultaneously.
   88170 **
   88171 ** There are two types of IncrMerger object - single (bUseThread==0) and
   88172 ** multi-threaded (bUseThread==1).
   88173 **
   88174 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
   88175 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
   88176 ** size. When the IncrMerger is initialized, it reads enough data from
   88177 ** pMerger to populate aFile[0]. It then sets variables within the
   88178 ** corresponding PmaReader object to read from that file and kicks off
   88179 ** a background thread to populate aFile[1] with the next mxSz bytes of
   88180 ** sorted record data from pMerger.
   88181 **
   88182 ** When the PmaReader reaches the end of aFile[0], it blocks until the
   88183 ** background thread has finished populating aFile[1]. It then exchanges
   88184 ** the contents of the aFile[0] and aFile[1] variables within this structure,
   88185 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
   88186 ** another background thread to populate the new aFile[1]. And so on, until
   88187 ** the contents of pMerger are exhausted.
   88188 **
   88189 ** A single-threaded IncrMerger does not open any temporary files of its
   88190 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
   88191 ** at offset iStartOff of file pTask->file2. And instead of using a
   88192 ** background thread to prepare data for the PmaReader, with a single
   88193 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
   88194 ** keys from pMerger by the calling thread whenever the PmaReader runs out
   88195 ** of data.
   88196 */
   88197 struct IncrMerger {
   88198   SortSubtask *pTask;             /* Task that owns this merger */
   88199   MergeEngine *pMerger;           /* Merge engine thread reads data from */
   88200   i64 iStartOff;                  /* Offset to start writing file at */
   88201   int mxSz;                       /* Maximum bytes of data to store */
   88202   int bEof;                       /* Set to true when merge is finished */
   88203   int bUseThread;                 /* True to use a bg thread for this object */
   88204   SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
   88205 };
   88206 
   88207 /*
   88208 ** An instance of this object is used for writing a PMA.
   88209 **
   88210 ** The PMA is written one record at a time.  Each record is of an arbitrary
   88211 ** size.  But I/O is more efficient if it occurs in page-sized blocks where
   88212 ** each block is aligned on a page boundary.  This object caches writes to
   88213 ** the PMA so that aligned, page-size blocks are written.
   88214 */
   88215 struct PmaWriter {
   88216   int eFWErr;                     /* Non-zero if in an error state */
   88217   u8 *aBuffer;                    /* Pointer to write buffer */
   88218   int nBuffer;                    /* Size of write buffer in bytes */
   88219   int iBufStart;                  /* First byte of buffer to write */
   88220   int iBufEnd;                    /* Last byte of buffer to write */
   88221   i64 iWriteOff;                  /* Offset of start of buffer in file */
   88222   sqlite3_file *pFd;              /* File handle to write to */
   88223 };
   88224 
   88225 /*
   88226 ** This object is the header on a single record while that record is being
   88227 ** held in memory and prior to being written out as part of a PMA.
   88228 **
   88229 ** How the linked list is connected depends on how memory is being managed
   88230 ** by this module. If using a separate allocation for each in-memory record
   88231 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
   88232 ** SorterRecord.u.pNext pointers.
   88233 **
   88234 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
   88235 ** then while records are being accumulated the list is linked using the
   88236 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
   88237 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
   88238 ** has finished passing records to the sorter, or when the in-memory buffer
   88239 ** is full, the list is sorted. As part of the sorting process, it is
   88240 ** converted to use the SorterRecord.u.pNext pointers. See function
   88241 ** vdbeSorterSort() for details.
   88242 */
   88243 struct SorterRecord {
   88244   int nVal;                       /* Size of the record in bytes */
   88245   union {
   88246     SorterRecord *pNext;          /* Pointer to next record in list */
   88247     int iNext;                    /* Offset within aMemory of next record */
   88248   } u;
   88249   /* The data for the record immediately follows this header */
   88250 };
   88251 
   88252 /* Return a pointer to the buffer containing the record data for SorterRecord
   88253 ** object p. Should be used as if:
   88254 **
   88255 **   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
   88256 */
   88257 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
   88258 
   88259 
   88260 /* Maximum number of PMAs that a single MergeEngine can merge */
   88261 #define SORTER_MAX_MERGE_COUNT 16
   88262 
   88263 static int vdbeIncrSwap(IncrMerger*);
   88264 static void vdbeIncrFree(IncrMerger *);
   88265 
   88266 /*
   88267 ** Free all memory belonging to the PmaReader object passed as the
   88268 ** argument. All structure fields are set to zero before returning.
   88269 */
   88270 static void vdbePmaReaderClear(PmaReader *pReadr){
   88271   sqlite3_free(pReadr->aAlloc);
   88272   sqlite3_free(pReadr->aBuffer);
   88273   if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
   88274   vdbeIncrFree(pReadr->pIncr);
   88275   memset(pReadr, 0, sizeof(PmaReader));
   88276 }
   88277 
   88278 /*
   88279 ** Read the next nByte bytes of data from the PMA p.
   88280 ** If successful, set *ppOut to point to a buffer containing the data
   88281 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
   88282 ** error code.
   88283 **
   88284 ** The buffer returned in *ppOut is only valid until the
   88285 ** next call to this function.
   88286 */
   88287 static int vdbePmaReadBlob(
   88288   PmaReader *p,                   /* PmaReader from which to take the blob */
   88289   int nByte,                      /* Bytes of data to read */
   88290   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
   88291 ){
   88292   int iBuf;                       /* Offset within buffer to read from */
   88293   int nAvail;                     /* Bytes of data available in buffer */
   88294 
   88295   if( p->aMap ){
   88296     *ppOut = &p->aMap[p->iReadOff];
   88297     p->iReadOff += nByte;
   88298     return SQLITE_OK;
   88299   }
   88300 
   88301   assert( p->aBuffer );
   88302 
   88303   /* If there is no more data to be read from the buffer, read the next
   88304   ** p->nBuffer bytes of data from the file into it. Or, if there are less
   88305   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
   88306   iBuf = p->iReadOff % p->nBuffer;
   88307   if( iBuf==0 ){
   88308     int nRead;                    /* Bytes to read from disk */
   88309     int rc;                       /* sqlite3OsRead() return code */
   88310 
   88311     /* Determine how many bytes of data to read. */
   88312     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
   88313       nRead = p->nBuffer;
   88314     }else{
   88315       nRead = (int)(p->iEof - p->iReadOff);
   88316     }
   88317     assert( nRead>0 );
   88318 
   88319     /* Readr data from the file. Return early if an error occurs. */
   88320     rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
   88321     assert( rc!=SQLITE_IOERR_SHORT_READ );
   88322     if( rc!=SQLITE_OK ) return rc;
   88323   }
   88324   nAvail = p->nBuffer - iBuf;
   88325 
   88326   if( nByte<=nAvail ){
   88327     /* The requested data is available in the in-memory buffer. In this
   88328     ** case there is no need to make a copy of the data, just return a
   88329     ** pointer into the buffer to the caller.  */
   88330     *ppOut = &p->aBuffer[iBuf];
   88331     p->iReadOff += nByte;
   88332   }else{
   88333     /* The requested data is not all available in the in-memory buffer.
   88334     ** In this case, allocate space at p->aAlloc[] to copy the requested
   88335     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
   88336     int nRem;                     /* Bytes remaining to copy */
   88337 
   88338     /* Extend the p->aAlloc[] allocation if required. */
   88339     if( p->nAlloc<nByte ){
   88340       u8 *aNew;
   88341       int nNew = MAX(128, p->nAlloc*2);
   88342       while( nByte>nNew ) nNew = nNew*2;
   88343       aNew = sqlite3Realloc(p->aAlloc, nNew);
   88344       if( !aNew ) return SQLITE_NOMEM_BKPT;
   88345       p->nAlloc = nNew;
   88346       p->aAlloc = aNew;
   88347     }
   88348 
   88349     /* Copy as much data as is available in the buffer into the start of
   88350     ** p->aAlloc[].  */
   88351     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
   88352     p->iReadOff += nAvail;
   88353     nRem = nByte - nAvail;
   88354 
   88355     /* The following loop copies up to p->nBuffer bytes per iteration into
   88356     ** the p->aAlloc[] buffer.  */
   88357     while( nRem>0 ){
   88358       int rc;                     /* vdbePmaReadBlob() return code */
   88359       int nCopy;                  /* Number of bytes to copy */
   88360       u8 *aNext;                  /* Pointer to buffer to copy data from */
   88361 
   88362       nCopy = nRem;
   88363       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
   88364       rc = vdbePmaReadBlob(p, nCopy, &aNext);
   88365       if( rc!=SQLITE_OK ) return rc;
   88366       assert( aNext!=p->aAlloc );
   88367       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
   88368       nRem -= nCopy;
   88369     }
   88370 
   88371     *ppOut = p->aAlloc;
   88372   }
   88373 
   88374   return SQLITE_OK;
   88375 }
   88376 
   88377 /*
   88378 ** Read a varint from the stream of data accessed by p. Set *pnOut to
   88379 ** the value read.
   88380 */
   88381 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
   88382   int iBuf;
   88383 
   88384   if( p->aMap ){
   88385     p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
   88386   }else{
   88387     iBuf = p->iReadOff % p->nBuffer;
   88388     if( iBuf && (p->nBuffer-iBuf)>=9 ){
   88389       p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
   88390     }else{
   88391       u8 aVarint[16], *a;
   88392       int i = 0, rc;
   88393       do{
   88394         rc = vdbePmaReadBlob(p, 1, &a);
   88395         if( rc ) return rc;
   88396         aVarint[(i++)&0xf] = a[0];
   88397       }while( (a[0]&0x80)!=0 );
   88398       sqlite3GetVarint(aVarint, pnOut);
   88399     }
   88400   }
   88401 
   88402   return SQLITE_OK;
   88403 }
   88404 
   88405 /*
   88406 ** Attempt to memory map file pFile. If successful, set *pp to point to the
   88407 ** new mapping and return SQLITE_OK. If the mapping is not attempted
   88408 ** (because the file is too large or the VFS layer is configured not to use
   88409 ** mmap), return SQLITE_OK and set *pp to NULL.
   88410 **
   88411 ** Or, if an error occurs, return an SQLite error code. The final value of
   88412 ** *pp is undefined in this case.
   88413 */
   88414 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
   88415   int rc = SQLITE_OK;
   88416   if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
   88417     sqlite3_file *pFd = pFile->pFd;
   88418     if( pFd->pMethods->iVersion>=3 ){
   88419       rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
   88420       testcase( rc!=SQLITE_OK );
   88421     }
   88422   }
   88423   return rc;
   88424 }
   88425 
   88426 /*
   88427 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
   88428 ** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
   88429 ** if successful, or an SQLite error code if an error occurs.
   88430 */
   88431 static int vdbePmaReaderSeek(
   88432   SortSubtask *pTask,             /* Task context */
   88433   PmaReader *pReadr,              /* Reader whose cursor is to be moved */
   88434   SorterFile *pFile,              /* Sorter file to read from */
   88435   i64 iOff                        /* Offset in pFile */
   88436 ){
   88437   int rc = SQLITE_OK;
   88438 
   88439   assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
   88440 
   88441   if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
   88442   if( pReadr->aMap ){
   88443     sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
   88444     pReadr->aMap = 0;
   88445   }
   88446   pReadr->iReadOff = iOff;
   88447   pReadr->iEof = pFile->iEof;
   88448   pReadr->pFd = pFile->pFd;
   88449 
   88450   rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
   88451   if( rc==SQLITE_OK && pReadr->aMap==0 ){
   88452     int pgsz = pTask->pSorter->pgsz;
   88453     int iBuf = pReadr->iReadOff % pgsz;
   88454     if( pReadr->aBuffer==0 ){
   88455       pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
   88456       if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
   88457       pReadr->nBuffer = pgsz;
   88458     }
   88459     if( rc==SQLITE_OK && iBuf ){
   88460       int nRead = pgsz - iBuf;
   88461       if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
   88462         nRead = (int)(pReadr->iEof - pReadr->iReadOff);
   88463       }
   88464       rc = sqlite3OsRead(
   88465           pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
   88466       );
   88467       testcase( rc!=SQLITE_OK );
   88468     }
   88469   }
   88470 
   88471   return rc;
   88472 }
   88473 
   88474 /*
   88475 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
   88476 ** no error occurs, or an SQLite error code if one does.
   88477 */
   88478 static int vdbePmaReaderNext(PmaReader *pReadr){
   88479   int rc = SQLITE_OK;             /* Return Code */
   88480   u64 nRec = 0;                   /* Size of record in bytes */
   88481 
   88482 
   88483   if( pReadr->iReadOff>=pReadr->iEof ){
   88484     IncrMerger *pIncr = pReadr->pIncr;
   88485     int bEof = 1;
   88486     if( pIncr ){
   88487       rc = vdbeIncrSwap(pIncr);
   88488       if( rc==SQLITE_OK && pIncr->bEof==0 ){
   88489         rc = vdbePmaReaderSeek(
   88490             pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
   88491         );
   88492         bEof = 0;
   88493       }
   88494     }
   88495 
   88496     if( bEof ){
   88497       /* This is an EOF condition */
   88498       vdbePmaReaderClear(pReadr);
   88499       testcase( rc!=SQLITE_OK );
   88500       return rc;
   88501     }
   88502   }
   88503 
   88504   if( rc==SQLITE_OK ){
   88505     rc = vdbePmaReadVarint(pReadr, &nRec);
   88506   }
   88507   if( rc==SQLITE_OK ){
   88508     pReadr->nKey = (int)nRec;
   88509     rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
   88510     testcase( rc!=SQLITE_OK );
   88511   }
   88512 
   88513   return rc;
   88514 }
   88515 
   88516 /*
   88517 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
   88518 ** starting at offset iStart and ending at offset iEof-1. This function
   88519 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
   88520 ** PMA is empty).
   88521 **
   88522 ** If the pnByte parameter is NULL, then it is assumed that the file
   88523 ** contains a single PMA, and that that PMA omits the initial length varint.
   88524 */
   88525 static int vdbePmaReaderInit(
   88526   SortSubtask *pTask,             /* Task context */
   88527   SorterFile *pFile,              /* Sorter file to read from */
   88528   i64 iStart,                     /* Start offset in pFile */
   88529   PmaReader *pReadr,              /* PmaReader to populate */
   88530   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
   88531 ){
   88532   int rc;
   88533 
   88534   assert( pFile->iEof>iStart );
   88535   assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
   88536   assert( pReadr->aBuffer==0 );
   88537   assert( pReadr->aMap==0 );
   88538 
   88539   rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
   88540   if( rc==SQLITE_OK ){
   88541     u64 nByte = 0;                 /* Size of PMA in bytes */
   88542     rc = vdbePmaReadVarint(pReadr, &nByte);
   88543     pReadr->iEof = pReadr->iReadOff + nByte;
   88544     *pnByte += nByte;
   88545   }
   88546 
   88547   if( rc==SQLITE_OK ){
   88548     rc = vdbePmaReaderNext(pReadr);
   88549   }
   88550   return rc;
   88551 }
   88552 
   88553 /*
   88554 ** A version of vdbeSorterCompare() that assumes that it has already been
   88555 ** determined that the first field of key1 is equal to the first field of
   88556 ** key2.
   88557 */
   88558 static int vdbeSorterCompareTail(
   88559   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
   88560   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
   88561   const void *pKey1, int nKey1,   /* Left side of comparison */
   88562   const void *pKey2, int nKey2    /* Right side of comparison */
   88563 ){
   88564   UnpackedRecord *r2 = pTask->pUnpacked;
   88565   if( *pbKey2Cached==0 ){
   88566     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
   88567     *pbKey2Cached = 1;
   88568   }
   88569   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
   88570 }
   88571 
   88572 /*
   88573 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
   88574 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
   88575 ** used by the comparison. Return the result of the comparison.
   88576 **
   88577 ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
   88578 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
   88579 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
   88580 ** version of key2 and *pbKey2Cached set to true before returning.
   88581 **
   88582 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
   88583 ** to SQLITE_NOMEM.
   88584 */
   88585 static int vdbeSorterCompare(
   88586   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
   88587   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
   88588   const void *pKey1, int nKey1,   /* Left side of comparison */
   88589   const void *pKey2, int nKey2    /* Right side of comparison */
   88590 ){
   88591   UnpackedRecord *r2 = pTask->pUnpacked;
   88592   if( !*pbKey2Cached ){
   88593     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
   88594     *pbKey2Cached = 1;
   88595   }
   88596   return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
   88597 }
   88598 
   88599 /*
   88600 ** A specially optimized version of vdbeSorterCompare() that assumes that
   88601 ** the first field of each key is a TEXT value and that the collation
   88602 ** sequence to compare them with is BINARY.
   88603 */
   88604 static int vdbeSorterCompareText(
   88605   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
   88606   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
   88607   const void *pKey1, int nKey1,   /* Left side of comparison */
   88608   const void *pKey2, int nKey2    /* Right side of comparison */
   88609 ){
   88610   const u8 * const p1 = (const u8 * const)pKey1;
   88611   const u8 * const p2 = (const u8 * const)pKey2;
   88612   const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
   88613   const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
   88614 
   88615   int n1;
   88616   int n2;
   88617   int res;
   88618 
   88619   getVarint32(&p1[1], n1);
   88620   getVarint32(&p2[1], n2);
   88621   res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
   88622   if( res==0 ){
   88623     res = n1 - n2;
   88624   }
   88625 
   88626   if( res==0 ){
   88627     if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
   88628       res = vdbeSorterCompareTail(
   88629           pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
   88630       );
   88631     }
   88632   }else{
   88633     if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
   88634       res = res * -1;
   88635     }
   88636   }
   88637 
   88638   return res;
   88639 }
   88640 
   88641 /*
   88642 ** A specially optimized version of vdbeSorterCompare() that assumes that
   88643 ** the first field of each key is an INTEGER value.
   88644 */
   88645 static int vdbeSorterCompareInt(
   88646   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
   88647   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
   88648   const void *pKey1, int nKey1,   /* Left side of comparison */
   88649   const void *pKey2, int nKey2    /* Right side of comparison */
   88650 ){
   88651   const u8 * const p1 = (const u8 * const)pKey1;
   88652   const u8 * const p2 = (const u8 * const)pKey2;
   88653   const int s1 = p1[1];                 /* Left hand serial type */
   88654   const int s2 = p2[1];                 /* Right hand serial type */
   88655   const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
   88656   const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
   88657   int res;                              /* Return value */
   88658 
   88659   assert( (s1>0 && s1<7) || s1==8 || s1==9 );
   88660   assert( (s2>0 && s2<7) || s2==8 || s2==9 );
   88661 
   88662   if( s1==s2 ){
   88663     /* The two values have the same sign. Compare using memcmp(). */
   88664     static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
   88665     const u8 n = aLen[s1];
   88666     int i;
   88667     res = 0;
   88668     for(i=0; i<n; i++){
   88669       if( (res = v1[i] - v2[i])!=0 ){
   88670         if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
   88671           res = v1[0] & 0x80 ? -1 : +1;
   88672         }
   88673         break;
   88674       }
   88675     }
   88676   }else if( s1>7 && s2>7 ){
   88677     res = s1 - s2;
   88678   }else{
   88679     if( s2>7 ){
   88680       res = +1;
   88681     }else if( s1>7 ){
   88682       res = -1;
   88683     }else{
   88684       res = s1 - s2;
   88685     }
   88686     assert( res!=0 );
   88687 
   88688     if( res>0 ){
   88689       if( *v1 & 0x80 ) res = -1;
   88690     }else{
   88691       if( *v2 & 0x80 ) res = +1;
   88692     }
   88693   }
   88694 
   88695   if( res==0 ){
   88696     if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
   88697       res = vdbeSorterCompareTail(
   88698           pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
   88699       );
   88700     }
   88701   }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
   88702     res = res * -1;
   88703   }
   88704 
   88705   return res;
   88706 }
   88707 
   88708 /*
   88709 ** Initialize the temporary index cursor just opened as a sorter cursor.
   88710 **
   88711 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
   88712 ** to determine the number of fields that should be compared from the
   88713 ** records being sorted. However, if the value passed as argument nField
   88714 ** is non-zero and the sorter is able to guarantee a stable sort, nField
   88715 ** is used instead. This is used when sorting records for a CREATE INDEX
   88716 ** statement. In this case, keys are always delivered to the sorter in
   88717 ** order of the primary key, which happens to be make up the final part
   88718 ** of the records being sorted. So if the sort is stable, there is never
   88719 ** any reason to compare PK fields and they can be ignored for a small
   88720 ** performance boost.
   88721 **
   88722 ** The sorter can guarantee a stable sort when running in single-threaded
   88723 ** mode, but not in multi-threaded mode.
   88724 **
   88725 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
   88726 */
   88727 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
   88728   sqlite3 *db,                    /* Database connection (for malloc()) */
   88729   int nField,                     /* Number of key fields in each record */
   88730   VdbeCursor *pCsr                /* Cursor that holds the new sorter */
   88731 ){
   88732   int pgsz;                       /* Page size of main database */
   88733   int i;                          /* Used to iterate through aTask[] */
   88734   VdbeSorter *pSorter;            /* The new sorter */
   88735   KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
   88736   int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
   88737   int sz;                         /* Size of pSorter in bytes */
   88738   int rc = SQLITE_OK;
   88739 #if SQLITE_MAX_WORKER_THREADS==0
   88740 # define nWorker 0
   88741 #else
   88742   int nWorker;
   88743 #endif
   88744 
   88745   /* Initialize the upper limit on the number of worker threads */
   88746 #if SQLITE_MAX_WORKER_THREADS>0
   88747   if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
   88748     nWorker = 0;
   88749   }else{
   88750     nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
   88751   }
   88752 #endif
   88753 
   88754   /* Do not allow the total number of threads (main thread + all workers)
   88755   ** to exceed the maximum merge count */
   88756 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
   88757   if( nWorker>=SORTER_MAX_MERGE_COUNT ){
   88758     nWorker = SORTER_MAX_MERGE_COUNT-1;
   88759   }
   88760 #endif
   88761 
   88762   assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
   88763   assert( pCsr->eCurType==CURTYPE_SORTER );
   88764   szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
   88765   sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
   88766 
   88767   pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
   88768   pCsr->uc.pSorter = pSorter;
   88769   if( pSorter==0 ){
   88770     rc = SQLITE_NOMEM_BKPT;
   88771   }else{
   88772     pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
   88773     memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
   88774     pKeyInfo->db = 0;
   88775     if( nField && nWorker==0 ){
   88776       pKeyInfo->nKeyField = nField;
   88777     }
   88778     pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   88779     pSorter->nTask = nWorker + 1;
   88780     pSorter->iPrev = (u8)(nWorker - 1);
   88781     pSorter->bUseThreads = (pSorter->nTask>1);
   88782     pSorter->db = db;
   88783     for(i=0; i<pSorter->nTask; i++){
   88784       SortSubtask *pTask = &pSorter->aTask[i];
   88785       pTask->pSorter = pSorter;
   88786     }
   88787 
   88788     if( !sqlite3TempInMemory(db) ){
   88789       i64 mxCache;                /* Cache size in bytes*/
   88790       u32 szPma = sqlite3GlobalConfig.szPma;
   88791       pSorter->mnPmaSize = szPma * pgsz;
   88792 
   88793       mxCache = db->aDb[0].pSchema->cache_size;
   88794       if( mxCache<0 ){
   88795         /* A negative cache-size value C indicates that the cache is abs(C)
   88796         ** KiB in size.  */
   88797         mxCache = mxCache * -1024;
   88798       }else{
   88799         mxCache = mxCache * pgsz;
   88800       }
   88801       mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
   88802       pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
   88803 
   88804       /* Avoid large memory allocations if the application has requested
   88805       ** SQLITE_CONFIG_SMALL_MALLOC. */
   88806       if( sqlite3GlobalConfig.bSmallMalloc==0 ){
   88807         assert( pSorter->iMemory==0 );
   88808         pSorter->nMemory = pgsz;
   88809         pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
   88810         if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
   88811       }
   88812     }
   88813 
   88814     if( pKeyInfo->nAllField<13
   88815      && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
   88816     ){
   88817       pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
   88818     }
   88819   }
   88820 
   88821   return rc;
   88822 }
   88823 #undef nWorker   /* Defined at the top of this function */
   88824 
   88825 /*
   88826 ** Free the list of sorted records starting at pRecord.
   88827 */
   88828 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
   88829   SorterRecord *p;
   88830   SorterRecord *pNext;
   88831   for(p=pRecord; p; p=pNext){
   88832     pNext = p->u.pNext;
   88833     sqlite3DbFree(db, p);
   88834   }
   88835 }
   88836 
   88837 /*
   88838 ** Free all resources owned by the object indicated by argument pTask. All
   88839 ** fields of *pTask are zeroed before returning.
   88840 */
   88841 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
   88842   sqlite3DbFree(db, pTask->pUnpacked);
   88843 #if SQLITE_MAX_WORKER_THREADS>0
   88844   /* pTask->list.aMemory can only be non-zero if it was handed memory
   88845   ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
   88846   if( pTask->list.aMemory ){
   88847     sqlite3_free(pTask->list.aMemory);
   88848   }else
   88849 #endif
   88850   {
   88851     assert( pTask->list.aMemory==0 );
   88852     vdbeSorterRecordFree(0, pTask->list.pList);
   88853   }
   88854   if( pTask->file.pFd ){
   88855     sqlite3OsCloseFree(pTask->file.pFd);
   88856   }
   88857   if( pTask->file2.pFd ){
   88858     sqlite3OsCloseFree(pTask->file2.pFd);
   88859   }
   88860   memset(pTask, 0, sizeof(SortSubtask));
   88861 }
   88862 
   88863 #ifdef SQLITE_DEBUG_SORTER_THREADS
   88864 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
   88865   i64 t;
   88866   int iTask = (pTask - pTask->pSorter->aTask);
   88867   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
   88868   fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
   88869 }
   88870 static void vdbeSorterRewindDebug(const char *zEvent){
   88871   i64 t;
   88872   sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
   88873   fprintf(stderr, "%lld:X %s\n", t, zEvent);
   88874 }
   88875 static void vdbeSorterPopulateDebug(
   88876   SortSubtask *pTask,
   88877   const char *zEvent
   88878 ){
   88879   i64 t;
   88880   int iTask = (pTask - pTask->pSorter->aTask);
   88881   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
   88882   fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
   88883 }
   88884 static void vdbeSorterBlockDebug(
   88885   SortSubtask *pTask,
   88886   int bBlocked,
   88887   const char *zEvent
   88888 ){
   88889   if( bBlocked ){
   88890     i64 t;
   88891     sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
   88892     fprintf(stderr, "%lld:main %s\n", t, zEvent);
   88893   }
   88894 }
   88895 #else
   88896 # define vdbeSorterWorkDebug(x,y)
   88897 # define vdbeSorterRewindDebug(y)
   88898 # define vdbeSorterPopulateDebug(x,y)
   88899 # define vdbeSorterBlockDebug(x,y,z)
   88900 #endif
   88901 
   88902 #if SQLITE_MAX_WORKER_THREADS>0
   88903 /*
   88904 ** Join thread pTask->thread.
   88905 */
   88906 static int vdbeSorterJoinThread(SortSubtask *pTask){
   88907   int rc = SQLITE_OK;
   88908   if( pTask->pThread ){
   88909 #ifdef SQLITE_DEBUG_SORTER_THREADS
   88910     int bDone = pTask->bDone;
   88911 #endif
   88912     void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
   88913     vdbeSorterBlockDebug(pTask, !bDone, "enter");
   88914     (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
   88915     vdbeSorterBlockDebug(pTask, !bDone, "exit");
   88916     rc = SQLITE_PTR_TO_INT(pRet);
   88917     assert( pTask->bDone==1 );
   88918     pTask->bDone = 0;
   88919     pTask->pThread = 0;
   88920   }
   88921   return rc;
   88922 }
   88923 
   88924 /*
   88925 ** Launch a background thread to run xTask(pIn).
   88926 */
   88927 static int vdbeSorterCreateThread(
   88928   SortSubtask *pTask,             /* Thread will use this task object */
   88929   void *(*xTask)(void*),          /* Routine to run in a separate thread */
   88930   void *pIn                       /* Argument passed into xTask() */
   88931 ){
   88932   assert( pTask->pThread==0 && pTask->bDone==0 );
   88933   return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
   88934 }
   88935 
   88936 /*
   88937 ** Join all outstanding threads launched by SorterWrite() to create
   88938 ** level-0 PMAs.
   88939 */
   88940 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
   88941   int rc = rcin;
   88942   int i;
   88943 
   88944   /* This function is always called by the main user thread.
   88945   **
   88946   ** If this function is being called after SorterRewind() has been called,
   88947   ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
   88948   ** is currently attempt to join one of the other threads. To avoid a race
   88949   ** condition where this thread also attempts to join the same object, join
   88950   ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
   88951   for(i=pSorter->nTask-1; i>=0; i--){
   88952     SortSubtask *pTask = &pSorter->aTask[i];
   88953     int rc2 = vdbeSorterJoinThread(pTask);
   88954     if( rc==SQLITE_OK ) rc = rc2;
   88955   }
   88956   return rc;
   88957 }
   88958 #else
   88959 # define vdbeSorterJoinAll(x,rcin) (rcin)
   88960 # define vdbeSorterJoinThread(pTask) SQLITE_OK
   88961 #endif
   88962 
   88963 /*
   88964 ** Allocate a new MergeEngine object capable of handling up to
   88965 ** nReader PmaReader inputs.
   88966 **
   88967 ** nReader is automatically rounded up to the next power of two.
   88968 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
   88969 */
   88970 static MergeEngine *vdbeMergeEngineNew(int nReader){
   88971   int N = 2;                      /* Smallest power of two >= nReader */
   88972   int nByte;                      /* Total bytes of space to allocate */
   88973   MergeEngine *pNew;              /* Pointer to allocated object to return */
   88974 
   88975   assert( nReader<=SORTER_MAX_MERGE_COUNT );
   88976 
   88977   while( N<nReader ) N += N;
   88978   nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
   88979 
   88980   pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
   88981   if( pNew ){
   88982     pNew->nTree = N;
   88983     pNew->pTask = 0;
   88984     pNew->aReadr = (PmaReader*)&pNew[1];
   88985     pNew->aTree = (int*)&pNew->aReadr[N];
   88986   }
   88987   return pNew;
   88988 }
   88989 
   88990 /*
   88991 ** Free the MergeEngine object passed as the only argument.
   88992 */
   88993 static void vdbeMergeEngineFree(MergeEngine *pMerger){
   88994   int i;
   88995   if( pMerger ){
   88996     for(i=0; i<pMerger->nTree; i++){
   88997       vdbePmaReaderClear(&pMerger->aReadr[i]);
   88998     }
   88999   }
   89000   sqlite3_free(pMerger);
   89001 }
   89002 
   89003 /*
   89004 ** Free all resources associated with the IncrMerger object indicated by
   89005 ** the first argument.
   89006 */
   89007 static void vdbeIncrFree(IncrMerger *pIncr){
   89008   if( pIncr ){
   89009 #if SQLITE_MAX_WORKER_THREADS>0
   89010     if( pIncr->bUseThread ){
   89011       vdbeSorterJoinThread(pIncr->pTask);
   89012       if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
   89013       if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
   89014     }
   89015 #endif
   89016     vdbeMergeEngineFree(pIncr->pMerger);
   89017     sqlite3_free(pIncr);
   89018   }
   89019 }
   89020 
   89021 /*
   89022 ** Reset a sorting cursor back to its original empty state.
   89023 */
   89024 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
   89025   int i;
   89026   (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
   89027   assert( pSorter->bUseThreads || pSorter->pReader==0 );
   89028 #if SQLITE_MAX_WORKER_THREADS>0
   89029   if( pSorter->pReader ){
   89030     vdbePmaReaderClear(pSorter->pReader);
   89031     sqlite3DbFree(db, pSorter->pReader);
   89032     pSorter->pReader = 0;
   89033   }
   89034 #endif
   89035   vdbeMergeEngineFree(pSorter->pMerger);
   89036   pSorter->pMerger = 0;
   89037   for(i=0; i<pSorter->nTask; i++){
   89038     SortSubtask *pTask = &pSorter->aTask[i];
   89039     vdbeSortSubtaskCleanup(db, pTask);
   89040     pTask->pSorter = pSorter;
   89041   }
   89042   if( pSorter->list.aMemory==0 ){
   89043     vdbeSorterRecordFree(0, pSorter->list.pList);
   89044   }
   89045   pSorter->list.pList = 0;
   89046   pSorter->list.szPMA = 0;
   89047   pSorter->bUsePMA = 0;
   89048   pSorter->iMemory = 0;
   89049   pSorter->mxKeysize = 0;
   89050   sqlite3DbFree(db, pSorter->pUnpacked);
   89051   pSorter->pUnpacked = 0;
   89052 }
   89053 
   89054 /*
   89055 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
   89056 */
   89057 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
   89058   VdbeSorter *pSorter;
   89059   assert( pCsr->eCurType==CURTYPE_SORTER );
   89060   pSorter = pCsr->uc.pSorter;
   89061   if( pSorter ){
   89062     sqlite3VdbeSorterReset(db, pSorter);
   89063     sqlite3_free(pSorter->list.aMemory);
   89064     sqlite3DbFree(db, pSorter);
   89065     pCsr->uc.pSorter = 0;
   89066   }
   89067 }
   89068 
   89069 #if SQLITE_MAX_MMAP_SIZE>0
   89070 /*
   89071 ** The first argument is a file-handle open on a temporary file. The file
   89072 ** is guaranteed to be nByte bytes or smaller in size. This function
   89073 ** attempts to extend the file to nByte bytes in size and to ensure that
   89074 ** the VFS has memory mapped it.
   89075 **
   89076 ** Whether or not the file does end up memory mapped of course depends on
   89077 ** the specific VFS implementation.
   89078 */
   89079 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
   89080   if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
   89081     void *p = 0;
   89082     int chunksize = 4*1024;
   89083     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
   89084     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
   89085     sqlite3OsFetch(pFd, 0, (int)nByte, &p);
   89086     sqlite3OsUnfetch(pFd, 0, p);
   89087   }
   89088 }
   89089 #else
   89090 # define vdbeSorterExtendFile(x,y,z)
   89091 #endif
   89092 
   89093 /*
   89094 ** Allocate space for a file-handle and open a temporary file. If successful,
   89095 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
   89096 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
   89097 */
   89098 static int vdbeSorterOpenTempFile(
   89099   sqlite3 *db,                    /* Database handle doing sort */
   89100   i64 nExtend,                    /* Attempt to extend file to this size */
   89101   sqlite3_file **ppFd
   89102 ){
   89103   int rc;
   89104   if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
   89105   rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
   89106       SQLITE_OPEN_TEMP_JOURNAL |
   89107       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
   89108       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
   89109   );
   89110   if( rc==SQLITE_OK ){
   89111     i64 max = SQLITE_MAX_MMAP_SIZE;
   89112     sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
   89113     if( nExtend>0 ){
   89114       vdbeSorterExtendFile(db, *ppFd, nExtend);
   89115     }
   89116   }
   89117   return rc;
   89118 }
   89119 
   89120 /*
   89121 ** If it has not already been allocated, allocate the UnpackedRecord
   89122 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
   89123 ** if no allocation was required), or SQLITE_NOMEM otherwise.
   89124 */
   89125 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
   89126   if( pTask->pUnpacked==0 ){
   89127     pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
   89128     if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
   89129     pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
   89130     pTask->pUnpacked->errCode = 0;
   89131   }
   89132   return SQLITE_OK;
   89133 }
   89134 
   89135 
   89136 /*
   89137 ** Merge the two sorted lists p1 and p2 into a single list.
   89138 */
   89139 static SorterRecord *vdbeSorterMerge(
   89140   SortSubtask *pTask,             /* Calling thread context */
   89141   SorterRecord *p1,               /* First list to merge */
   89142   SorterRecord *p2                /* Second list to merge */
   89143 ){
   89144   SorterRecord *pFinal = 0;
   89145   SorterRecord **pp = &pFinal;
   89146   int bCached = 0;
   89147 
   89148   assert( p1!=0 && p2!=0 );
   89149   for(;;){
   89150     int res;
   89151     res = pTask->xCompare(
   89152         pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
   89153     );
   89154 
   89155     if( res<=0 ){
   89156       *pp = p1;
   89157       pp = &p1->u.pNext;
   89158       p1 = p1->u.pNext;
   89159       if( p1==0 ){
   89160         *pp = p2;
   89161         break;
   89162       }
   89163     }else{
   89164       *pp = p2;
   89165       pp = &p2->u.pNext;
   89166       p2 = p2->u.pNext;
   89167       bCached = 0;
   89168       if( p2==0 ){
   89169         *pp = p1;
   89170         break;
   89171       }
   89172     }
   89173   }
   89174   return pFinal;
   89175 }
   89176 
   89177 /*
   89178 ** Return the SorterCompare function to compare values collected by the
   89179 ** sorter object passed as the only argument.
   89180 */
   89181 static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
   89182   if( p->typeMask==SORTER_TYPE_INTEGER ){
   89183     return vdbeSorterCompareInt;
   89184   }else if( p->typeMask==SORTER_TYPE_TEXT ){
   89185     return vdbeSorterCompareText;
   89186   }
   89187   return vdbeSorterCompare;
   89188 }
   89189 
   89190 /*
   89191 ** Sort the linked list of records headed at pTask->pList. Return
   89192 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
   89193 ** an error occurs.
   89194 */
   89195 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
   89196   int i;
   89197   SorterRecord **aSlot;
   89198   SorterRecord *p;
   89199   int rc;
   89200 
   89201   rc = vdbeSortAllocUnpacked(pTask);
   89202   if( rc!=SQLITE_OK ) return rc;
   89203 
   89204   p = pList->pList;
   89205   pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
   89206 
   89207   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
   89208   if( !aSlot ){
   89209     return SQLITE_NOMEM_BKPT;
   89210   }
   89211 
   89212   while( p ){
   89213     SorterRecord *pNext;
   89214     if( pList->aMemory ){
   89215       if( (u8*)p==pList->aMemory ){
   89216         pNext = 0;
   89217       }else{
   89218         assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
   89219         pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
   89220       }
   89221     }else{
   89222       pNext = p->u.pNext;
   89223     }
   89224 
   89225     p->u.pNext = 0;
   89226     for(i=0; aSlot[i]; i++){
   89227       p = vdbeSorterMerge(pTask, p, aSlot[i]);
   89228       aSlot[i] = 0;
   89229     }
   89230     aSlot[i] = p;
   89231     p = pNext;
   89232   }
   89233 
   89234   p = 0;
   89235   for(i=0; i<64; i++){
   89236     if( aSlot[i]==0 ) continue;
   89237     p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
   89238   }
   89239   pList->pList = p;
   89240 
   89241   sqlite3_free(aSlot);
   89242   assert( pTask->pUnpacked->errCode==SQLITE_OK
   89243        || pTask->pUnpacked->errCode==SQLITE_NOMEM
   89244   );
   89245   return pTask->pUnpacked->errCode;
   89246 }
   89247 
   89248 /*
   89249 ** Initialize a PMA-writer object.
   89250 */
   89251 static void vdbePmaWriterInit(
   89252   sqlite3_file *pFd,              /* File handle to write to */
   89253   PmaWriter *p,                   /* Object to populate */
   89254   int nBuf,                       /* Buffer size */
   89255   i64 iStart                      /* Offset of pFd to begin writing at */
   89256 ){
   89257   memset(p, 0, sizeof(PmaWriter));
   89258   p->aBuffer = (u8*)sqlite3Malloc(nBuf);
   89259   if( !p->aBuffer ){
   89260     p->eFWErr = SQLITE_NOMEM_BKPT;
   89261   }else{
   89262     p->iBufEnd = p->iBufStart = (iStart % nBuf);
   89263     p->iWriteOff = iStart - p->iBufStart;
   89264     p->nBuffer = nBuf;
   89265     p->pFd = pFd;
   89266   }
   89267 }
   89268 
   89269 /*
   89270 ** Write nData bytes of data to the PMA. Return SQLITE_OK
   89271 ** if successful, or an SQLite error code if an error occurs.
   89272 */
   89273 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
   89274   int nRem = nData;
   89275   while( nRem>0 && p->eFWErr==0 ){
   89276     int nCopy = nRem;
   89277     if( nCopy>(p->nBuffer - p->iBufEnd) ){
   89278       nCopy = p->nBuffer - p->iBufEnd;
   89279     }
   89280 
   89281     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
   89282     p->iBufEnd += nCopy;
   89283     if( p->iBufEnd==p->nBuffer ){
   89284       p->eFWErr = sqlite3OsWrite(p->pFd,
   89285           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
   89286           p->iWriteOff + p->iBufStart
   89287       );
   89288       p->iBufStart = p->iBufEnd = 0;
   89289       p->iWriteOff += p->nBuffer;
   89290     }
   89291     assert( p->iBufEnd<p->nBuffer );
   89292 
   89293     nRem -= nCopy;
   89294   }
   89295 }
   89296 
   89297 /*
   89298 ** Flush any buffered data to disk and clean up the PMA-writer object.
   89299 ** The results of using the PMA-writer after this call are undefined.
   89300 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
   89301 ** required. Otherwise, return an SQLite error code.
   89302 **
   89303 ** Before returning, set *piEof to the offset immediately following the
   89304 ** last byte written to the file.
   89305 */
   89306 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
   89307   int rc;
   89308   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
   89309     p->eFWErr = sqlite3OsWrite(p->pFd,
   89310         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
   89311         p->iWriteOff + p->iBufStart
   89312     );
   89313   }
   89314   *piEof = (p->iWriteOff + p->iBufEnd);
   89315   sqlite3_free(p->aBuffer);
   89316   rc = p->eFWErr;
   89317   memset(p, 0, sizeof(PmaWriter));
   89318   return rc;
   89319 }
   89320 
   89321 /*
   89322 ** Write value iVal encoded as a varint to the PMA. Return
   89323 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
   89324 */
   89325 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
   89326   int nByte;
   89327   u8 aByte[10];
   89328   nByte = sqlite3PutVarint(aByte, iVal);
   89329   vdbePmaWriteBlob(p, aByte, nByte);
   89330 }
   89331 
   89332 /*
   89333 ** Write the current contents of in-memory linked-list pList to a level-0
   89334 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
   89335 ** successful, or an SQLite error code otherwise.
   89336 **
   89337 ** The format of a PMA is:
   89338 **
   89339 **     * A varint. This varint contains the total number of bytes of content
   89340 **       in the PMA (not including the varint itself).
   89341 **
   89342 **     * One or more records packed end-to-end in order of ascending keys.
   89343 **       Each record consists of a varint followed by a blob of data (the
   89344 **       key). The varint is the number of bytes in the blob of data.
   89345 */
   89346 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
   89347   sqlite3 *db = pTask->pSorter->db;
   89348   int rc = SQLITE_OK;             /* Return code */
   89349   PmaWriter writer;               /* Object used to write to the file */
   89350 
   89351 #ifdef SQLITE_DEBUG
   89352   /* Set iSz to the expected size of file pTask->file after writing the PMA.
   89353   ** This is used by an assert() statement at the end of this function.  */
   89354   i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
   89355 #endif
   89356 
   89357   vdbeSorterWorkDebug(pTask, "enter");
   89358   memset(&writer, 0, sizeof(PmaWriter));
   89359   assert( pList->szPMA>0 );
   89360 
   89361   /* If the first temporary PMA file has not been opened, open it now. */
   89362   if( pTask->file.pFd==0 ){
   89363     rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
   89364     assert( rc!=SQLITE_OK || pTask->file.pFd );
   89365     assert( pTask->file.iEof==0 );
   89366     assert( pTask->nPMA==0 );
   89367   }
   89368 
   89369   /* Try to get the file to memory map */
   89370   if( rc==SQLITE_OK ){
   89371     vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
   89372   }
   89373 
   89374   /* Sort the list */
   89375   if( rc==SQLITE_OK ){
   89376     rc = vdbeSorterSort(pTask, pList);
   89377   }
   89378 
   89379   if( rc==SQLITE_OK ){
   89380     SorterRecord *p;
   89381     SorterRecord *pNext = 0;
   89382 
   89383     vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
   89384                       pTask->file.iEof);
   89385     pTask->nPMA++;
   89386     vdbePmaWriteVarint(&writer, pList->szPMA);
   89387     for(p=pList->pList; p; p=pNext){
   89388       pNext = p->u.pNext;
   89389       vdbePmaWriteVarint(&writer, p->nVal);
   89390       vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
   89391       if( pList->aMemory==0 ) sqlite3_free(p);
   89392     }
   89393     pList->pList = p;
   89394     rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
   89395   }
   89396 
   89397   vdbeSorterWorkDebug(pTask, "exit");
   89398   assert( rc!=SQLITE_OK || pList->pList==0 );
   89399   assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
   89400   return rc;
   89401 }
   89402 
   89403 /*
   89404 ** Advance the MergeEngine to its next entry.
   89405 ** Set *pbEof to true there is no next entry because
   89406 ** the MergeEngine has reached the end of all its inputs.
   89407 **
   89408 ** Return SQLITE_OK if successful or an error code if an error occurs.
   89409 */
   89410 static int vdbeMergeEngineStep(
   89411   MergeEngine *pMerger,      /* The merge engine to advance to the next row */
   89412   int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
   89413 ){
   89414   int rc;
   89415   int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
   89416   SortSubtask *pTask = pMerger->pTask;
   89417 
   89418   /* Advance the current PmaReader */
   89419   rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
   89420 
   89421   /* Update contents of aTree[] */
   89422   if( rc==SQLITE_OK ){
   89423     int i;                      /* Index of aTree[] to recalculate */
   89424     PmaReader *pReadr1;         /* First PmaReader to compare */
   89425     PmaReader *pReadr2;         /* Second PmaReader to compare */
   89426     int bCached = 0;
   89427 
   89428     /* Find the first two PmaReaders to compare. The one that was just
   89429     ** advanced (iPrev) and the one next to it in the array.  */
   89430     pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
   89431     pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
   89432 
   89433     for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
   89434       /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
   89435       int iRes;
   89436       if( pReadr1->pFd==0 ){
   89437         iRes = +1;
   89438       }else if( pReadr2->pFd==0 ){
   89439         iRes = -1;
   89440       }else{
   89441         iRes = pTask->xCompare(pTask, &bCached,
   89442             pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
   89443         );
   89444       }
   89445 
   89446       /* If pReadr1 contained the smaller value, set aTree[i] to its index.
   89447       ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
   89448       ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
   89449       ** pKey2 to point to the record belonging to pReadr2.
   89450       **
   89451       ** Alternatively, if pReadr2 contains the smaller of the two values,
   89452       ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
   89453       ** was actually called above, then pTask->pUnpacked now contains
   89454       ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
   89455       ** vdbeSorterCompare() from decoding pReadr2 again.
   89456       **
   89457       ** If the two values were equal, then the value from the oldest
   89458       ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
   89459       ** is sorted from oldest to newest, so pReadr1 contains older values
   89460       ** than pReadr2 iff (pReadr1<pReadr2).  */
   89461       if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
   89462         pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
   89463         pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
   89464         bCached = 0;
   89465       }else{
   89466         if( pReadr1->pFd ) bCached = 0;
   89467         pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
   89468         pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
   89469       }
   89470     }
   89471     *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
   89472   }
   89473 
   89474   return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
   89475 }
   89476 
   89477 #if SQLITE_MAX_WORKER_THREADS>0
   89478 /*
   89479 ** The main routine for background threads that write level-0 PMAs.
   89480 */
   89481 static void *vdbeSorterFlushThread(void *pCtx){
   89482   SortSubtask *pTask = (SortSubtask*)pCtx;
   89483   int rc;                         /* Return code */
   89484   assert( pTask->bDone==0 );
   89485   rc = vdbeSorterListToPMA(pTask, &pTask->list);
   89486   pTask->bDone = 1;
   89487   return SQLITE_INT_TO_PTR(rc);
   89488 }
   89489 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
   89490 
   89491 /*
   89492 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
   89493 ** using a background thread.
   89494 */
   89495 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
   89496 #if SQLITE_MAX_WORKER_THREADS==0
   89497   pSorter->bUsePMA = 1;
   89498   return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
   89499 #else
   89500   int rc = SQLITE_OK;
   89501   int i;
   89502   SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
   89503   int nWorker = (pSorter->nTask-1);
   89504 
   89505   /* Set the flag to indicate that at least one PMA has been written.
   89506   ** Or will be, anyhow.  */
   89507   pSorter->bUsePMA = 1;
   89508 
   89509   /* Select a sub-task to sort and flush the current list of in-memory
   89510   ** records to disk. If the sorter is running in multi-threaded mode,
   89511   ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
   89512   ** the background thread from a sub-tasks previous turn is still running,
   89513   ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
   89514   ** fall back to using the final sub-task. The first (pSorter->nTask-1)
   89515   ** sub-tasks are prefered as they use background threads - the final
   89516   ** sub-task uses the main thread. */
   89517   for(i=0; i<nWorker; i++){
   89518     int iTest = (pSorter->iPrev + i + 1) % nWorker;
   89519     pTask = &pSorter->aTask[iTest];
   89520     if( pTask->bDone ){
   89521       rc = vdbeSorterJoinThread(pTask);
   89522     }
   89523     if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
   89524   }
   89525 
   89526   if( rc==SQLITE_OK ){
   89527     if( i==nWorker ){
   89528       /* Use the foreground thread for this operation */
   89529       rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
   89530     }else{
   89531       /* Launch a background thread for this operation */
   89532       u8 *aMem = pTask->list.aMemory;
   89533       void *pCtx = (void*)pTask;
   89534 
   89535       assert( pTask->pThread==0 && pTask->bDone==0 );
   89536       assert( pTask->list.pList==0 );
   89537       assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
   89538 
   89539       pSorter->iPrev = (u8)(pTask - pSorter->aTask);
   89540       pTask->list = pSorter->list;
   89541       pSorter->list.pList = 0;
   89542       pSorter->list.szPMA = 0;
   89543       if( aMem ){
   89544         pSorter->list.aMemory = aMem;
   89545         pSorter->nMemory = sqlite3MallocSize(aMem);
   89546       }else if( pSorter->list.aMemory ){
   89547         pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
   89548         if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
   89549       }
   89550 
   89551       rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
   89552     }
   89553   }
   89554 
   89555   return rc;
   89556 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
   89557 }
   89558 
   89559 /*
   89560 ** Add a record to the sorter.
   89561 */
   89562 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
   89563   const VdbeCursor *pCsr,         /* Sorter cursor */
   89564   Mem *pVal                       /* Memory cell containing record */
   89565 ){
   89566   VdbeSorter *pSorter;
   89567   int rc = SQLITE_OK;             /* Return Code */
   89568   SorterRecord *pNew;             /* New list element */
   89569   int bFlush;                     /* True to flush contents of memory to PMA */
   89570   int nReq;                       /* Bytes of memory required */
   89571   int nPMA;                       /* Bytes of PMA space required */
   89572   int t;                          /* serial type of first record field */
   89573 
   89574   assert( pCsr->eCurType==CURTYPE_SORTER );
   89575   pSorter = pCsr->uc.pSorter;
   89576   getVarint32((const u8*)&pVal->z[1], t);
   89577   if( t>0 && t<10 && t!=7 ){
   89578     pSorter->typeMask &= SORTER_TYPE_INTEGER;
   89579   }else if( t>10 && (t & 0x01) ){
   89580     pSorter->typeMask &= SORTER_TYPE_TEXT;
   89581   }else{
   89582     pSorter->typeMask = 0;
   89583   }
   89584 
   89585   assert( pSorter );
   89586 
   89587   /* Figure out whether or not the current contents of memory should be
   89588   ** flushed to a PMA before continuing. If so, do so.
   89589   **
   89590   ** If using the single large allocation mode (pSorter->aMemory!=0), then
   89591   ** flush the contents of memory to a new PMA if (a) at least one value is
   89592   ** already in memory and (b) the new value will not fit in memory.
   89593   **
   89594   ** Or, if using separate allocations for each record, flush the contents
   89595   ** of memory to a PMA if either of the following are true:
   89596   **
   89597   **   * The total memory allocated for the in-memory list is greater
   89598   **     than (page-size * cache-size), or
   89599   **
   89600   **   * The total memory allocated for the in-memory list is greater
   89601   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
   89602   */
   89603   nReq = pVal->n + sizeof(SorterRecord);
   89604   nPMA = pVal->n + sqlite3VarintLen(pVal->n);
   89605   if( pSorter->mxPmaSize ){
   89606     if( pSorter->list.aMemory ){
   89607       bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
   89608     }else{
   89609       bFlush = (
   89610           (pSorter->list.szPMA > pSorter->mxPmaSize)
   89611        || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
   89612       );
   89613     }
   89614     if( bFlush ){
   89615       rc = vdbeSorterFlushPMA(pSorter);
   89616       pSorter->list.szPMA = 0;
   89617       pSorter->iMemory = 0;
   89618       assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
   89619     }
   89620   }
   89621 
   89622   pSorter->list.szPMA += nPMA;
   89623   if( nPMA>pSorter->mxKeysize ){
   89624     pSorter->mxKeysize = nPMA;
   89625   }
   89626 
   89627   if( pSorter->list.aMemory ){
   89628     int nMin = pSorter->iMemory + nReq;
   89629 
   89630     if( nMin>pSorter->nMemory ){
   89631       u8 *aNew;
   89632       int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
   89633       int nNew = pSorter->nMemory * 2;
   89634       while( nNew < nMin ) nNew = nNew*2;
   89635       if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
   89636       if( nNew < nMin ) nNew = nMin;
   89637 
   89638       aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
   89639       if( !aNew ) return SQLITE_NOMEM_BKPT;
   89640       pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
   89641       pSorter->list.aMemory = aNew;
   89642       pSorter->nMemory = nNew;
   89643     }
   89644 
   89645     pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
   89646     pSorter->iMemory += ROUND8(nReq);
   89647     if( pSorter->list.pList ){
   89648       pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
   89649     }
   89650   }else{
   89651     pNew = (SorterRecord *)sqlite3Malloc(nReq);
   89652     if( pNew==0 ){
   89653       return SQLITE_NOMEM_BKPT;
   89654     }
   89655     pNew->u.pNext = pSorter->list.pList;
   89656   }
   89657 
   89658   memcpy(SRVAL(pNew), pVal->z, pVal->n);
   89659   pNew->nVal = pVal->n;
   89660   pSorter->list.pList = pNew;
   89661 
   89662   return rc;
   89663 }
   89664 
   89665 /*
   89666 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
   89667 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
   89668 ** except that the number-of-bytes varint is omitted from the start.
   89669 */
   89670 static int vdbeIncrPopulate(IncrMerger *pIncr){
   89671   int rc = SQLITE_OK;
   89672   int rc2;
   89673   i64 iStart = pIncr->iStartOff;
   89674   SorterFile *pOut = &pIncr->aFile[1];
   89675   SortSubtask *pTask = pIncr->pTask;
   89676   MergeEngine *pMerger = pIncr->pMerger;
   89677   PmaWriter writer;
   89678   assert( pIncr->bEof==0 );
   89679 
   89680   vdbeSorterPopulateDebug(pTask, "enter");
   89681 
   89682   vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
   89683   while( rc==SQLITE_OK ){
   89684     int dummy;
   89685     PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
   89686     int nKey = pReader->nKey;
   89687     i64 iEof = writer.iWriteOff + writer.iBufEnd;
   89688 
   89689     /* Check if the output file is full or if the input has been exhausted.
   89690     ** In either case exit the loop. */
   89691     if( pReader->pFd==0 ) break;
   89692     if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
   89693 
   89694     /* Write the next key to the output. */
   89695     vdbePmaWriteVarint(&writer, nKey);
   89696     vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
   89697     assert( pIncr->pMerger->pTask==pTask );
   89698     rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
   89699   }
   89700 
   89701   rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
   89702   if( rc==SQLITE_OK ) rc = rc2;
   89703   vdbeSorterPopulateDebug(pTask, "exit");
   89704   return rc;
   89705 }
   89706 
   89707 #if SQLITE_MAX_WORKER_THREADS>0
   89708 /*
   89709 ** The main routine for background threads that populate aFile[1] of
   89710 ** multi-threaded IncrMerger objects.
   89711 */
   89712 static void *vdbeIncrPopulateThread(void *pCtx){
   89713   IncrMerger *pIncr = (IncrMerger*)pCtx;
   89714   void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
   89715   pIncr->pTask->bDone = 1;
   89716   return pRet;
   89717 }
   89718 
   89719 /*
   89720 ** Launch a background thread to populate aFile[1] of pIncr.
   89721 */
   89722 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
   89723   void *p = (void*)pIncr;
   89724   assert( pIncr->bUseThread );
   89725   return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
   89726 }
   89727 #endif
   89728 
   89729 /*
   89730 ** This function is called when the PmaReader corresponding to pIncr has
   89731 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
   89732 ** aFile[0] such that the PmaReader should start rereading it from the
   89733 ** beginning.
   89734 **
   89735 ** For single-threaded objects, this is accomplished by literally reading
   89736 ** keys from pIncr->pMerger and repopulating aFile[0].
   89737 **
   89738 ** For multi-threaded objects, all that is required is to wait until the
   89739 ** background thread is finished (if it is not already) and then swap
   89740 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
   89741 ** been exhausted, this function also launches a new background thread
   89742 ** to populate the new aFile[1].
   89743 **
   89744 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
   89745 */
   89746 static int vdbeIncrSwap(IncrMerger *pIncr){
   89747   int rc = SQLITE_OK;
   89748 
   89749 #if SQLITE_MAX_WORKER_THREADS>0
   89750   if( pIncr->bUseThread ){
   89751     rc = vdbeSorterJoinThread(pIncr->pTask);
   89752 
   89753     if( rc==SQLITE_OK ){
   89754       SorterFile f0 = pIncr->aFile[0];
   89755       pIncr->aFile[0] = pIncr->aFile[1];
   89756       pIncr->aFile[1] = f0;
   89757     }
   89758 
   89759     if( rc==SQLITE_OK ){
   89760       if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
   89761         pIncr->bEof = 1;
   89762       }else{
   89763         rc = vdbeIncrBgPopulate(pIncr);
   89764       }
   89765     }
   89766   }else
   89767 #endif
   89768   {
   89769     rc = vdbeIncrPopulate(pIncr);
   89770     pIncr->aFile[0] = pIncr->aFile[1];
   89771     if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
   89772       pIncr->bEof = 1;
   89773     }
   89774   }
   89775 
   89776   return rc;
   89777 }
   89778 
   89779 /*
   89780 ** Allocate and return a new IncrMerger object to read data from pMerger.
   89781 **
   89782 ** If an OOM condition is encountered, return NULL. In this case free the
   89783 ** pMerger argument before returning.
   89784 */
   89785 static int vdbeIncrMergerNew(
   89786   SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
   89787   MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
   89788   IncrMerger **ppOut      /* Write the new IncrMerger here */
   89789 ){
   89790   int rc = SQLITE_OK;
   89791   IncrMerger *pIncr = *ppOut = (IncrMerger*)
   89792        (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
   89793   if( pIncr ){
   89794     pIncr->pMerger = pMerger;
   89795     pIncr->pTask = pTask;
   89796     pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
   89797     pTask->file2.iEof += pIncr->mxSz;
   89798   }else{
   89799     vdbeMergeEngineFree(pMerger);
   89800     rc = SQLITE_NOMEM_BKPT;
   89801   }
   89802   return rc;
   89803 }
   89804 
   89805 #if SQLITE_MAX_WORKER_THREADS>0
   89806 /*
   89807 ** Set the "use-threads" flag on object pIncr.
   89808 */
   89809 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
   89810   pIncr->bUseThread = 1;
   89811   pIncr->pTask->file2.iEof -= pIncr->mxSz;
   89812 }
   89813 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
   89814 
   89815 
   89816 
   89817 /*
   89818 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
   89819 ** two PmaReaders that feed that entry.  Neither of the PmaReaders
   89820 ** are advanced.  This routine merely does the comparison.
   89821 */
   89822 static void vdbeMergeEngineCompare(
   89823   MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
   89824   int iOut               /* Store the result in pMerger->aTree[iOut] */
   89825 ){
   89826   int i1;
   89827   int i2;
   89828   int iRes;
   89829   PmaReader *p1;
   89830   PmaReader *p2;
   89831 
   89832   assert( iOut<pMerger->nTree && iOut>0 );
   89833 
   89834   if( iOut>=(pMerger->nTree/2) ){
   89835     i1 = (iOut - pMerger->nTree/2) * 2;
   89836     i2 = i1 + 1;
   89837   }else{
   89838     i1 = pMerger->aTree[iOut*2];
   89839     i2 = pMerger->aTree[iOut*2+1];
   89840   }
   89841 
   89842   p1 = &pMerger->aReadr[i1];
   89843   p2 = &pMerger->aReadr[i2];
   89844 
   89845   if( p1->pFd==0 ){
   89846     iRes = i2;
   89847   }else if( p2->pFd==0 ){
   89848     iRes = i1;
   89849   }else{
   89850     SortSubtask *pTask = pMerger->pTask;
   89851     int bCached = 0;
   89852     int res;
   89853     assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
   89854     res = pTask->xCompare(
   89855         pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
   89856     );
   89857     if( res<=0 ){
   89858       iRes = i1;
   89859     }else{
   89860       iRes = i2;
   89861     }
   89862   }
   89863 
   89864   pMerger->aTree[iOut] = iRes;
   89865 }
   89866 
   89867 /*
   89868 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
   89869 ** and vdbePmaReaderIncrMergeInit().
   89870 **
   89871 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
   89872 ** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
   89873 ** when there exists one or more separate worker threads.
   89874 */
   89875 #define INCRINIT_NORMAL 0
   89876 #define INCRINIT_TASK   1
   89877 #define INCRINIT_ROOT   2
   89878 
   89879 /*
   89880 ** Forward reference required as the vdbeIncrMergeInit() and
   89881 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
   89882 ** building a merge tree.
   89883 */
   89884 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
   89885 
   89886 /*
   89887 ** Initialize the MergeEngine object passed as the second argument. Once this
   89888 ** function returns, the first key of merged data may be read from the
   89889 ** MergeEngine object in the usual fashion.
   89890 **
   89891 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
   89892 ** objects attached to the PmaReader objects that the merger reads from have
   89893 ** already been populated, but that they have not yet populated aFile[0] and
   89894 ** set the PmaReader objects up to read from it. In this case all that is
   89895 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
   89896 ** its first key.
   89897 **
   89898 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
   89899 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
   89900 ** to pMerger.
   89901 **
   89902 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
   89903 */
   89904 static int vdbeMergeEngineInit(
   89905   SortSubtask *pTask,             /* Thread that will run pMerger */
   89906   MergeEngine *pMerger,           /* MergeEngine to initialize */
   89907   int eMode                       /* One of the INCRINIT_XXX constants */
   89908 ){
   89909   int rc = SQLITE_OK;             /* Return code */
   89910   int i;                          /* For looping over PmaReader objects */
   89911   int nTree = pMerger->nTree;
   89912 
   89913   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
   89914   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
   89915 
   89916   /* Verify that the MergeEngine is assigned to a single thread */
   89917   assert( pMerger->pTask==0 );
   89918   pMerger->pTask = pTask;
   89919 
   89920   for(i=0; i<nTree; i++){
   89921     if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
   89922       /* PmaReaders should be normally initialized in order, as if they are
   89923       ** reading from the same temp file this makes for more linear file IO.
   89924       ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
   89925       ** in use it will block the vdbePmaReaderNext() call while it uses
   89926       ** the main thread to fill its buffer. So calling PmaReaderNext()
   89927       ** on this PmaReader before any of the multi-threaded PmaReaders takes
   89928       ** better advantage of multi-processor hardware. */
   89929       rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
   89930     }else{
   89931       rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
   89932     }
   89933     if( rc!=SQLITE_OK ) return rc;
   89934   }
   89935 
   89936   for(i=pMerger->nTree-1; i>0; i--){
   89937     vdbeMergeEngineCompare(pMerger, i);
   89938   }
   89939   return pTask->pUnpacked->errCode;
   89940 }
   89941 
   89942 /*
   89943 ** The PmaReader passed as the first argument is guaranteed to be an
   89944 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
   89945 ** and/or initialize the temp file related fields of the IncrMerge
   89946 ** object at (pReadr->pIncr).
   89947 **
   89948 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
   89949 ** in the sub-tree headed by pReadr are also initialized. Data is then
   89950 ** loaded into the buffers belonging to pReadr and it is set to point to
   89951 ** the first key in its range.
   89952 **
   89953 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
   89954 ** to be a multi-threaded PmaReader and this function is being called in a
   89955 ** background thread. In this case all PmaReaders in the sub-tree are
   89956 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
   89957 ** pReadr is populated. However, pReadr itself is not set up to point
   89958 ** to its first key. A call to vdbePmaReaderNext() is still required to do
   89959 ** that.
   89960 **
   89961 ** The reason this function does not call vdbePmaReaderNext() immediately
   89962 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
   89963 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
   89964 ** this entire function is being run by thread (pTask->thread), that will
   89965 ** lead to the current background thread attempting to join itself.
   89966 **
   89967 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
   89968 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
   89969 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
   89970 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
   89971 ** the current PmaReader set to point to the first key in its range.
   89972 **
   89973 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
   89974 */
   89975 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
   89976   int rc = SQLITE_OK;
   89977   IncrMerger *pIncr = pReadr->pIncr;
   89978   SortSubtask *pTask = pIncr->pTask;
   89979   sqlite3 *db = pTask->pSorter->db;
   89980 
   89981   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
   89982   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
   89983 
   89984   rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
   89985 
   89986   /* Set up the required files for pIncr. A multi-theaded IncrMerge object
   89987   ** requires two temp files to itself, whereas a single-threaded object
   89988   ** only requires a region of pTask->file2. */
   89989   if( rc==SQLITE_OK ){
   89990     int mxSz = pIncr->mxSz;
   89991 #if SQLITE_MAX_WORKER_THREADS>0
   89992     if( pIncr->bUseThread ){
   89993       rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
   89994       if( rc==SQLITE_OK ){
   89995         rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
   89996       }
   89997     }else
   89998 #endif
   89999     /*if( !pIncr->bUseThread )*/{
   90000       if( pTask->file2.pFd==0 ){
   90001         assert( pTask->file2.iEof>0 );
   90002         rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
   90003         pTask->file2.iEof = 0;
   90004       }
   90005       if( rc==SQLITE_OK ){
   90006         pIncr->aFile[1].pFd = pTask->file2.pFd;
   90007         pIncr->iStartOff = pTask->file2.iEof;
   90008         pTask->file2.iEof += mxSz;
   90009       }
   90010     }
   90011   }
   90012 
   90013 #if SQLITE_MAX_WORKER_THREADS>0
   90014   if( rc==SQLITE_OK && pIncr->bUseThread ){
   90015     /* Use the current thread to populate aFile[1], even though this
   90016     ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
   90017     ** then this function is already running in background thread
   90018     ** pIncr->pTask->thread.
   90019     **
   90020     ** If this is the INCRINIT_ROOT object, then it is running in the
   90021     ** main VDBE thread. But that is Ok, as that thread cannot return
   90022     ** control to the VDBE or proceed with anything useful until the
   90023     ** first results are ready from this merger object anyway.
   90024     */
   90025     assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
   90026     rc = vdbeIncrPopulate(pIncr);
   90027   }
   90028 #endif
   90029 
   90030   if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
   90031     rc = vdbePmaReaderNext(pReadr);
   90032   }
   90033 
   90034   return rc;
   90035 }
   90036 
   90037 #if SQLITE_MAX_WORKER_THREADS>0
   90038 /*
   90039 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
   90040 ** background threads.
   90041 */
   90042 static void *vdbePmaReaderBgIncrInit(void *pCtx){
   90043   PmaReader *pReader = (PmaReader*)pCtx;
   90044   void *pRet = SQLITE_INT_TO_PTR(
   90045                   vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
   90046                );
   90047   pReader->pIncr->pTask->bDone = 1;
   90048   return pRet;
   90049 }
   90050 #endif
   90051 
   90052 /*
   90053 ** If the PmaReader passed as the first argument is not an incremental-reader
   90054 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
   90055 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
   90056 ** this routine to initialize the incremental merge.
   90057 **
   90058 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
   90059 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
   90060 ** Or, if the IncrMerger is single threaded, the same function is called
   90061 ** using the current thread.
   90062 */
   90063 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
   90064   IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
   90065   int rc = SQLITE_OK;                  /* Return code */
   90066   if( pIncr ){
   90067 #if SQLITE_MAX_WORKER_THREADS>0
   90068     assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
   90069     if( pIncr->bUseThread ){
   90070       void *pCtx = (void*)pReadr;
   90071       rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
   90072     }else
   90073 #endif
   90074     {
   90075       rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
   90076     }
   90077   }
   90078   return rc;
   90079 }
   90080 
   90081 /*
   90082 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
   90083 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
   90084 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
   90085 ** to NULL and return an SQLite error code.
   90086 **
   90087 ** When this function is called, *piOffset is set to the offset of the
   90088 ** first PMA to read from pTask->file. Assuming no error occurs, it is
   90089 ** set to the offset immediately following the last byte of the last
   90090 ** PMA before returning. If an error does occur, then the final value of
   90091 ** *piOffset is undefined.
   90092 */
   90093 static int vdbeMergeEngineLevel0(
   90094   SortSubtask *pTask,             /* Sorter task to read from */
   90095   int nPMA,                       /* Number of PMAs to read */
   90096   i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
   90097   MergeEngine **ppOut             /* OUT: New merge-engine */
   90098 ){
   90099   MergeEngine *pNew;              /* Merge engine to return */
   90100   i64 iOff = *piOffset;
   90101   int i;
   90102   int rc = SQLITE_OK;
   90103 
   90104   *ppOut = pNew = vdbeMergeEngineNew(nPMA);
   90105   if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
   90106 
   90107   for(i=0; i<nPMA && rc==SQLITE_OK; i++){
   90108     i64 nDummy = 0;
   90109     PmaReader *pReadr = &pNew->aReadr[i];
   90110     rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
   90111     iOff = pReadr->iEof;
   90112   }
   90113 
   90114   if( rc!=SQLITE_OK ){
   90115     vdbeMergeEngineFree(pNew);
   90116     *ppOut = 0;
   90117   }
   90118   *piOffset = iOff;
   90119   return rc;
   90120 }
   90121 
   90122 /*
   90123 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
   90124 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
   90125 **
   90126 ** i.e.
   90127 **
   90128 **   nPMA<=16    -> TreeDepth() == 0
   90129 **   nPMA<=256   -> TreeDepth() == 1
   90130 **   nPMA<=65536 -> TreeDepth() == 2
   90131 */
   90132 static int vdbeSorterTreeDepth(int nPMA){
   90133   int nDepth = 0;
   90134   i64 nDiv = SORTER_MAX_MERGE_COUNT;
   90135   while( nDiv < (i64)nPMA ){
   90136     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
   90137     nDepth++;
   90138   }
   90139   return nDepth;
   90140 }
   90141 
   90142 /*
   90143 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
   90144 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
   90145 ** tree, counting from zero. This function adds pLeaf to the tree.
   90146 **
   90147 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
   90148 ** code is returned and pLeaf is freed.
   90149 */
   90150 static int vdbeSorterAddToTree(
   90151   SortSubtask *pTask,             /* Task context */
   90152   int nDepth,                     /* Depth of tree according to TreeDepth() */
   90153   int iSeq,                       /* Sequence number of leaf within tree */
   90154   MergeEngine *pRoot,             /* Root of tree */
   90155   MergeEngine *pLeaf              /* Leaf to add to tree */
   90156 ){
   90157   int rc = SQLITE_OK;
   90158   int nDiv = 1;
   90159   int i;
   90160   MergeEngine *p = pRoot;
   90161   IncrMerger *pIncr;
   90162 
   90163   rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
   90164 
   90165   for(i=1; i<nDepth; i++){
   90166     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
   90167   }
   90168 
   90169   for(i=1; i<nDepth && rc==SQLITE_OK; i++){
   90170     int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
   90171     PmaReader *pReadr = &p->aReadr[iIter];
   90172 
   90173     if( pReadr->pIncr==0 ){
   90174       MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
   90175       if( pNew==0 ){
   90176         rc = SQLITE_NOMEM_BKPT;
   90177       }else{
   90178         rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
   90179       }
   90180     }
   90181     if( rc==SQLITE_OK ){
   90182       p = pReadr->pIncr->pMerger;
   90183       nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
   90184     }
   90185   }
   90186 
   90187   if( rc==SQLITE_OK ){
   90188     p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
   90189   }else{
   90190     vdbeIncrFree(pIncr);
   90191   }
   90192   return rc;
   90193 }
   90194 
   90195 /*
   90196 ** This function is called as part of a SorterRewind() operation on a sorter
   90197 ** that has already written two or more level-0 PMAs to one or more temp
   90198 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
   90199 ** can be used to incrementally merge all PMAs on disk.
   90200 **
   90201 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
   90202 ** MergeEngine object at the root of the tree before returning. Or, if an
   90203 ** error occurs, an SQLite error code is returned and the final value
   90204 ** of *ppOut is undefined.
   90205 */
   90206 static int vdbeSorterMergeTreeBuild(
   90207   VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
   90208   MergeEngine **ppOut        /* Write the MergeEngine here */
   90209 ){
   90210   MergeEngine *pMain = 0;
   90211   int rc = SQLITE_OK;
   90212   int iTask;
   90213 
   90214 #if SQLITE_MAX_WORKER_THREADS>0
   90215   /* If the sorter uses more than one task, then create the top-level
   90216   ** MergeEngine here. This MergeEngine will read data from exactly
   90217   ** one PmaReader per sub-task.  */
   90218   assert( pSorter->bUseThreads || pSorter->nTask==1 );
   90219   if( pSorter->nTask>1 ){
   90220     pMain = vdbeMergeEngineNew(pSorter->nTask);
   90221     if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
   90222   }
   90223 #endif
   90224 
   90225   for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
   90226     SortSubtask *pTask = &pSorter->aTask[iTask];
   90227     assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
   90228     if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
   90229       MergeEngine *pRoot = 0;     /* Root node of tree for this task */
   90230       int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
   90231       i64 iReadOff = 0;
   90232 
   90233       if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
   90234         rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
   90235       }else{
   90236         int i;
   90237         int iSeq = 0;
   90238         pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
   90239         if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
   90240         for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
   90241           MergeEngine *pMerger = 0; /* New level-0 PMA merger */
   90242           int nReader;              /* Number of level-0 PMAs to merge */
   90243 
   90244           nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
   90245           rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
   90246           if( rc==SQLITE_OK ){
   90247             rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
   90248           }
   90249         }
   90250       }
   90251 
   90252       if( rc==SQLITE_OK ){
   90253 #if SQLITE_MAX_WORKER_THREADS>0
   90254         if( pMain!=0 ){
   90255           rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
   90256         }else
   90257 #endif
   90258         {
   90259           assert( pMain==0 );
   90260           pMain = pRoot;
   90261         }
   90262       }else{
   90263         vdbeMergeEngineFree(pRoot);
   90264       }
   90265     }
   90266   }
   90267 
   90268   if( rc!=SQLITE_OK ){
   90269     vdbeMergeEngineFree(pMain);
   90270     pMain = 0;
   90271   }
   90272   *ppOut = pMain;
   90273   return rc;
   90274 }
   90275 
   90276 /*
   90277 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
   90278 ** on a sorter that has written two or more PMAs to temporary files. It sets
   90279 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
   90280 ** (for multi-threaded sorters) so that it can be used to iterate through
   90281 ** all records stored in the sorter.
   90282 **
   90283 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
   90284 */
   90285 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
   90286   int rc;                         /* Return code */
   90287   SortSubtask *pTask0 = &pSorter->aTask[0];
   90288   MergeEngine *pMain = 0;
   90289 #if SQLITE_MAX_WORKER_THREADS
   90290   sqlite3 *db = pTask0->pSorter->db;
   90291   int i;
   90292   SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
   90293   for(i=0; i<pSorter->nTask; i++){
   90294     pSorter->aTask[i].xCompare = xCompare;
   90295   }
   90296 #endif
   90297 
   90298   rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
   90299   if( rc==SQLITE_OK ){
   90300 #if SQLITE_MAX_WORKER_THREADS
   90301     assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
   90302     if( pSorter->bUseThreads ){
   90303       int iTask;
   90304       PmaReader *pReadr = 0;
   90305       SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
   90306       rc = vdbeSortAllocUnpacked(pLast);
   90307       if( rc==SQLITE_OK ){
   90308         pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
   90309         pSorter->pReader = pReadr;
   90310         if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
   90311       }
   90312       if( rc==SQLITE_OK ){
   90313         rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
   90314         if( rc==SQLITE_OK ){
   90315           vdbeIncrMergerSetThreads(pReadr->pIncr);
   90316           for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
   90317             IncrMerger *pIncr;
   90318             if( (pIncr = pMain->aReadr[iTask].pIncr) ){
   90319               vdbeIncrMergerSetThreads(pIncr);
   90320               assert( pIncr->pTask!=pLast );
   90321             }
   90322           }
   90323           for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
   90324             /* Check that:
   90325             **
   90326             **   a) The incremental merge object is configured to use the
   90327             **      right task, and
   90328             **   b) If it is using task (nTask-1), it is configured to run
   90329             **      in single-threaded mode. This is important, as the
   90330             **      root merge (INCRINIT_ROOT) will be using the same task
   90331             **      object.
   90332             */
   90333             PmaReader *p = &pMain->aReadr[iTask];
   90334             assert( p->pIncr==0 || (
   90335                 (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
   90336              && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
   90337             ));
   90338             rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
   90339           }
   90340         }
   90341         pMain = 0;
   90342       }
   90343       if( rc==SQLITE_OK ){
   90344         rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
   90345       }
   90346     }else
   90347 #endif
   90348     {
   90349       rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
   90350       pSorter->pMerger = pMain;
   90351       pMain = 0;
   90352     }
   90353   }
   90354 
   90355   if( rc!=SQLITE_OK ){
   90356     vdbeMergeEngineFree(pMain);
   90357   }
   90358   return rc;
   90359 }
   90360 
   90361 
   90362 /*
   90363 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
   90364 ** this function is called to prepare for iterating through the records
   90365 ** in sorted order.
   90366 */
   90367 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
   90368   VdbeSorter *pSorter;
   90369   int rc = SQLITE_OK;             /* Return code */
   90370 
   90371   assert( pCsr->eCurType==CURTYPE_SORTER );
   90372   pSorter = pCsr->uc.pSorter;
   90373   assert( pSorter );
   90374 
   90375   /* If no data has been written to disk, then do not do so now. Instead,
   90376   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
   90377   ** from the in-memory list.  */
   90378   if( pSorter->bUsePMA==0 ){
   90379     if( pSorter->list.pList ){
   90380       *pbEof = 0;
   90381       rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
   90382     }else{
   90383       *pbEof = 1;
   90384     }
   90385     return rc;
   90386   }
   90387 
   90388   /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
   90389   ** function flushes the contents of memory to disk, it immediately always
   90390   ** creates a new list consisting of a single key immediately afterwards.
   90391   ** So the list is never empty at this point.  */
   90392   assert( pSorter->list.pList );
   90393   rc = vdbeSorterFlushPMA(pSorter);
   90394 
   90395   /* Join all threads */
   90396   rc = vdbeSorterJoinAll(pSorter, rc);
   90397 
   90398   vdbeSorterRewindDebug("rewind");
   90399 
   90400   /* Assuming no errors have occurred, set up a merger structure to
   90401   ** incrementally read and merge all remaining PMAs.  */
   90402   assert( pSorter->pReader==0 );
   90403   if( rc==SQLITE_OK ){
   90404     rc = vdbeSorterSetupMerge(pSorter);
   90405     *pbEof = 0;
   90406   }
   90407 
   90408   vdbeSorterRewindDebug("rewinddone");
   90409   return rc;
   90410 }
   90411 
   90412 /*
   90413 ** Advance to the next element in the sorter.  Return value:
   90414 **
   90415 **    SQLITE_OK     success
   90416 **    SQLITE_DONE   end of data
   90417 **    otherwise     some kind of error.
   90418 */
   90419 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
   90420   VdbeSorter *pSorter;
   90421   int rc;                         /* Return code */
   90422 
   90423   assert( pCsr->eCurType==CURTYPE_SORTER );
   90424   pSorter = pCsr->uc.pSorter;
   90425   assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
   90426   if( pSorter->bUsePMA ){
   90427     assert( pSorter->pReader==0 || pSorter->pMerger==0 );
   90428     assert( pSorter->bUseThreads==0 || pSorter->pReader );
   90429     assert( pSorter->bUseThreads==1 || pSorter->pMerger );
   90430 #if SQLITE_MAX_WORKER_THREADS>0
   90431     if( pSorter->bUseThreads ){
   90432       rc = vdbePmaReaderNext(pSorter->pReader);
   90433       if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
   90434     }else
   90435 #endif
   90436     /*if( !pSorter->bUseThreads )*/ {
   90437       int res = 0;
   90438       assert( pSorter->pMerger!=0 );
   90439       assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
   90440       rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
   90441       if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
   90442     }
   90443   }else{
   90444     SorterRecord *pFree = pSorter->list.pList;
   90445     pSorter->list.pList = pFree->u.pNext;
   90446     pFree->u.pNext = 0;
   90447     if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
   90448     rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
   90449   }
   90450   return rc;
   90451 }
   90452 
   90453 /*
   90454 ** Return a pointer to a buffer owned by the sorter that contains the
   90455 ** current key.
   90456 */
   90457 static void *vdbeSorterRowkey(
   90458   const VdbeSorter *pSorter,      /* Sorter object */
   90459   int *pnKey                      /* OUT: Size of current key in bytes */
   90460 ){
   90461   void *pKey;
   90462   if( pSorter->bUsePMA ){
   90463     PmaReader *pReader;
   90464 #if SQLITE_MAX_WORKER_THREADS>0
   90465     if( pSorter->bUseThreads ){
   90466       pReader = pSorter->pReader;
   90467     }else
   90468 #endif
   90469     /*if( !pSorter->bUseThreads )*/{
   90470       pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
   90471     }
   90472     *pnKey = pReader->nKey;
   90473     pKey = pReader->aKey;
   90474   }else{
   90475     *pnKey = pSorter->list.pList->nVal;
   90476     pKey = SRVAL(pSorter->list.pList);
   90477   }
   90478   return pKey;
   90479 }
   90480 
   90481 /*
   90482 ** Copy the current sorter key into the memory cell pOut.
   90483 */
   90484 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
   90485   VdbeSorter *pSorter;
   90486   void *pKey; int nKey;           /* Sorter key to copy into pOut */
   90487 
   90488   assert( pCsr->eCurType==CURTYPE_SORTER );
   90489   pSorter = pCsr->uc.pSorter;
   90490   pKey = vdbeSorterRowkey(pSorter, &nKey);
   90491   if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
   90492     return SQLITE_NOMEM_BKPT;
   90493   }
   90494   pOut->n = nKey;
   90495   MemSetTypeFlag(pOut, MEM_Blob);
   90496   memcpy(pOut->z, pKey, nKey);
   90497 
   90498   return SQLITE_OK;
   90499 }
   90500 
   90501 /*
   90502 ** Compare the key in memory cell pVal with the key that the sorter cursor
   90503 ** passed as the first argument currently points to. For the purposes of
   90504 ** the comparison, ignore the rowid field at the end of each record.
   90505 **
   90506 ** If the sorter cursor key contains any NULL values, consider it to be
   90507 ** less than pVal. Even if pVal also contains NULL values.
   90508 **
   90509 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
   90510 ** Otherwise, set *pRes to a negative, zero or positive value if the
   90511 ** key in pVal is smaller than, equal to or larger than the current sorter
   90512 ** key.
   90513 **
   90514 ** This routine forms the core of the OP_SorterCompare opcode, which in
   90515 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
   90516 */
   90517 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
   90518   const VdbeCursor *pCsr,         /* Sorter cursor */
   90519   Mem *pVal,                      /* Value to compare to current sorter key */
   90520   int nKeyCol,                    /* Compare this many columns */
   90521   int *pRes                       /* OUT: Result of comparison */
   90522 ){
   90523   VdbeSorter *pSorter;
   90524   UnpackedRecord *r2;
   90525   KeyInfo *pKeyInfo;
   90526   int i;
   90527   void *pKey; int nKey;           /* Sorter key to compare pVal with */
   90528 
   90529   assert( pCsr->eCurType==CURTYPE_SORTER );
   90530   pSorter = pCsr->uc.pSorter;
   90531   r2 = pSorter->pUnpacked;
   90532   pKeyInfo = pCsr->pKeyInfo;
   90533   if( r2==0 ){
   90534     r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
   90535     if( r2==0 ) return SQLITE_NOMEM_BKPT;
   90536     r2->nField = nKeyCol;
   90537   }
   90538   assert( r2->nField==nKeyCol );
   90539 
   90540   pKey = vdbeSorterRowkey(pSorter, &nKey);
   90541   sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
   90542   for(i=0; i<nKeyCol; i++){
   90543     if( r2->aMem[i].flags & MEM_Null ){
   90544       *pRes = -1;
   90545       return SQLITE_OK;
   90546     }
   90547   }
   90548 
   90549   *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
   90550   return SQLITE_OK;
   90551 }
   90552 
   90553 /************** End of vdbesort.c ********************************************/
   90554 /************** Begin file memjournal.c **************************************/
   90555 /*
   90556 ** 2008 October 7
   90557 **
   90558 ** The author disclaims copyright to this source code.  In place of
   90559 ** a legal notice, here is a blessing:
   90560 **
   90561 **    May you do good and not evil.
   90562 **    May you find forgiveness for yourself and forgive others.
   90563 **    May you share freely, never taking more than you give.
   90564 **
   90565 *************************************************************************
   90566 **
   90567 ** This file contains code use to implement an in-memory rollback journal.
   90568 ** The in-memory rollback journal is used to journal transactions for
   90569 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
   90570 **
   90571 ** Update:  The in-memory journal is also used to temporarily cache
   90572 ** smaller journals that are not critical for power-loss recovery.
   90573 ** For example, statement journals that are not too big will be held
   90574 ** entirely in memory, thus reducing the number of file I/O calls, and
   90575 ** more importantly, reducing temporary file creation events.  If these
   90576 ** journals become too large for memory, they are spilled to disk.  But
   90577 ** in the common case, they are usually small and no file I/O needs to
   90578 ** occur.
   90579 */
   90580 /* #include "sqliteInt.h" */
   90581 
   90582 /* Forward references to internal structures */
   90583 typedef struct MemJournal MemJournal;
   90584 typedef struct FilePoint FilePoint;
   90585 typedef struct FileChunk FileChunk;
   90586 
   90587 /*
   90588 ** The rollback journal is composed of a linked list of these structures.
   90589 **
   90590 ** The zChunk array is always at least 8 bytes in size - usually much more.
   90591 ** Its actual size is stored in the MemJournal.nChunkSize variable.
   90592 */
   90593 struct FileChunk {
   90594   FileChunk *pNext;               /* Next chunk in the journal */
   90595   u8 zChunk[8];                   /* Content of this chunk */
   90596 };
   90597 
   90598 /*
   90599 ** By default, allocate this many bytes of memory for each FileChunk object.
   90600 */
   90601 #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
   90602 
   90603 /*
   90604 ** For chunk size nChunkSize, return the number of bytes that should
   90605 ** be allocated for each FileChunk structure.
   90606 */
   90607 #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
   90608 
   90609 /*
   90610 ** An instance of this object serves as a cursor into the rollback journal.
   90611 ** The cursor can be either for reading or writing.
   90612 */
   90613 struct FilePoint {
   90614   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
   90615   FileChunk *pChunk;              /* Specific chunk into which cursor points */
   90616 };
   90617 
   90618 /*
   90619 ** This structure is a subclass of sqlite3_file. Each open memory-journal
   90620 ** is an instance of this class.
   90621 */
   90622 struct MemJournal {
   90623   const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
   90624   int nChunkSize;                 /* In-memory chunk-size */
   90625 
   90626   int nSpill;                     /* Bytes of data before flushing */
   90627   int nSize;                      /* Bytes of data currently in memory */
   90628   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   90629   FilePoint endpoint;             /* Pointer to the end of the file */
   90630   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
   90631 
   90632   int flags;                      /* xOpen flags */
   90633   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
   90634   const char *zJournal;           /* Name of the journal file */
   90635 };
   90636 
   90637 /*
   90638 ** Read data from the in-memory journal file.  This is the implementation
   90639 ** of the sqlite3_vfs.xRead method.
   90640 */
   90641 static int memjrnlRead(
   90642   sqlite3_file *pJfd,    /* The journal file from which to read */
   90643   void *zBuf,            /* Put the results here */
   90644   int iAmt,              /* Number of bytes to read */
   90645   sqlite_int64 iOfst     /* Begin reading at this offset */
   90646 ){
   90647   MemJournal *p = (MemJournal *)pJfd;
   90648   u8 *zOut = zBuf;
   90649   int nRead = iAmt;
   90650   int iChunkOffset;
   90651   FileChunk *pChunk;
   90652 
   90653 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
   90654  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   90655   if( (iAmt+iOfst)>p->endpoint.iOffset ){
   90656     return SQLITE_IOERR_SHORT_READ;
   90657   }
   90658 #endif
   90659 
   90660   assert( (iAmt+iOfst)<=p->endpoint.iOffset );
   90661   assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
   90662   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
   90663     sqlite3_int64 iOff = 0;
   90664     for(pChunk=p->pFirst;
   90665         ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
   90666         pChunk=pChunk->pNext
   90667     ){
   90668       iOff += p->nChunkSize;
   90669     }
   90670   }else{
   90671     pChunk = p->readpoint.pChunk;
   90672     assert( pChunk!=0 );
   90673   }
   90674 
   90675   iChunkOffset = (int)(iOfst%p->nChunkSize);
   90676   do {
   90677     int iSpace = p->nChunkSize - iChunkOffset;
   90678     int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
   90679     memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
   90680     zOut += nCopy;
   90681     nRead -= iSpace;
   90682     iChunkOffset = 0;
   90683   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
   90684   p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
   90685   p->readpoint.pChunk = pChunk;
   90686 
   90687   return SQLITE_OK;
   90688 }
   90689 
   90690 /*
   90691 ** Free the list of FileChunk structures headed at MemJournal.pFirst.
   90692 */
   90693 static void memjrnlFreeChunks(MemJournal *p){
   90694   FileChunk *pIter;
   90695   FileChunk *pNext;
   90696   for(pIter=p->pFirst; pIter; pIter=pNext){
   90697     pNext = pIter->pNext;
   90698     sqlite3_free(pIter);
   90699   }
   90700   p->pFirst = 0;
   90701 }
   90702 
   90703 /*
   90704 ** Flush the contents of memory to a real file on disk.
   90705 */
   90706 static int memjrnlCreateFile(MemJournal *p){
   90707   int rc;
   90708   sqlite3_file *pReal = (sqlite3_file*)p;
   90709   MemJournal copy = *p;
   90710 
   90711   memset(p, 0, sizeof(MemJournal));
   90712   rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
   90713   if( rc==SQLITE_OK ){
   90714     int nChunk = copy.nChunkSize;
   90715     i64 iOff = 0;
   90716     FileChunk *pIter;
   90717     for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
   90718       if( iOff + nChunk > copy.endpoint.iOffset ){
   90719         nChunk = copy.endpoint.iOffset - iOff;
   90720       }
   90721       rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
   90722       if( rc ) break;
   90723       iOff += nChunk;
   90724     }
   90725     if( rc==SQLITE_OK ){
   90726       /* No error has occurred. Free the in-memory buffers. */
   90727       memjrnlFreeChunks(&copy);
   90728     }
   90729   }
   90730   if( rc!=SQLITE_OK ){
   90731     /* If an error occurred while creating or writing to the file, restore
   90732     ** the original before returning. This way, SQLite uses the in-memory
   90733     ** journal data to roll back changes made to the internal page-cache
   90734     ** before this function was called.  */
   90735     sqlite3OsClose(pReal);
   90736     *p = copy;
   90737   }
   90738   return rc;
   90739 }
   90740 
   90741 
   90742 /*
   90743 ** Write data to the file.
   90744 */
   90745 static int memjrnlWrite(
   90746   sqlite3_file *pJfd,    /* The journal file into which to write */
   90747   const void *zBuf,      /* Take data to be written from here */
   90748   int iAmt,              /* Number of bytes to write */
   90749   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   90750 ){
   90751   MemJournal *p = (MemJournal *)pJfd;
   90752   int nWrite = iAmt;
   90753   u8 *zWrite = (u8 *)zBuf;
   90754 
   90755   /* If the file should be created now, create it and write the new data
   90756   ** into the file on disk. */
   90757   if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
   90758     int rc = memjrnlCreateFile(p);
   90759     if( rc==SQLITE_OK ){
   90760       rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
   90761     }
   90762     return rc;
   90763   }
   90764 
   90765   /* If the contents of this write should be stored in memory */
   90766   else{
   90767     /* An in-memory journal file should only ever be appended to. Random
   90768     ** access writes are not required. The only exception to this is when
   90769     ** the in-memory journal is being used by a connection using the
   90770     ** atomic-write optimization. In this case the first 28 bytes of the
   90771     ** journal file may be written as part of committing the transaction. */
   90772     assert( iOfst==p->endpoint.iOffset || iOfst==0 );
   90773 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
   90774  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   90775     if( iOfst==0 && p->pFirst ){
   90776       assert( p->nChunkSize>iAmt );
   90777       memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
   90778     }else
   90779 #else
   90780     assert( iOfst>0 || p->pFirst==0 );
   90781 #endif
   90782     {
   90783       while( nWrite>0 ){
   90784         FileChunk *pChunk = p->endpoint.pChunk;
   90785         int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
   90786         int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
   90787 
   90788         if( iChunkOffset==0 ){
   90789           /* New chunk is required to extend the file. */
   90790           FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
   90791           if( !pNew ){
   90792             return SQLITE_IOERR_NOMEM_BKPT;
   90793           }
   90794           pNew->pNext = 0;
   90795           if( pChunk ){
   90796             assert( p->pFirst );
   90797             pChunk->pNext = pNew;
   90798           }else{
   90799             assert( !p->pFirst );
   90800             p->pFirst = pNew;
   90801           }
   90802           p->endpoint.pChunk = pNew;
   90803         }
   90804 
   90805         memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
   90806         zWrite += iSpace;
   90807         nWrite -= iSpace;
   90808         p->endpoint.iOffset += iSpace;
   90809       }
   90810       p->nSize = iAmt + iOfst;
   90811     }
   90812   }
   90813 
   90814   return SQLITE_OK;
   90815 }
   90816 
   90817 /*
   90818 ** Truncate the file.
   90819 **
   90820 ** If the journal file is already on disk, truncate it there. Or, if it
   90821 ** is still in main memory but is being truncated to zero bytes in size,
   90822 ** ignore
   90823 */
   90824 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   90825   MemJournal *p = (MemJournal *)pJfd;
   90826   if( ALWAYS(size==0) ){
   90827     memjrnlFreeChunks(p);
   90828     p->nSize = 0;
   90829     p->endpoint.pChunk = 0;
   90830     p->endpoint.iOffset = 0;
   90831     p->readpoint.pChunk = 0;
   90832     p->readpoint.iOffset = 0;
   90833   }
   90834   return SQLITE_OK;
   90835 }
   90836 
   90837 /*
   90838 ** Close the file.
   90839 */
   90840 static int memjrnlClose(sqlite3_file *pJfd){
   90841   MemJournal *p = (MemJournal *)pJfd;
   90842   memjrnlFreeChunks(p);
   90843   return SQLITE_OK;
   90844 }
   90845 
   90846 /*
   90847 ** Sync the file.
   90848 **
   90849 ** If the real file has been created, call its xSync method. Otherwise,
   90850 ** syncing an in-memory journal is a no-op.
   90851 */
   90852 static int memjrnlSync(sqlite3_file *pJfd, int flags){
   90853   UNUSED_PARAMETER2(pJfd, flags);
   90854   return SQLITE_OK;
   90855 }
   90856 
   90857 /*
   90858 ** Query the size of the file in bytes.
   90859 */
   90860 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   90861   MemJournal *p = (MemJournal *)pJfd;
   90862   *pSize = (sqlite_int64) p->endpoint.iOffset;
   90863   return SQLITE_OK;
   90864 }
   90865 
   90866 /*
   90867 ** Table of methods for MemJournal sqlite3_file object.
   90868 */
   90869 static const struct sqlite3_io_methods MemJournalMethods = {
   90870   1,                /* iVersion */
   90871   memjrnlClose,     /* xClose */
   90872   memjrnlRead,      /* xRead */
   90873   memjrnlWrite,     /* xWrite */
   90874   memjrnlTruncate,  /* xTruncate */
   90875   memjrnlSync,      /* xSync */
   90876   memjrnlFileSize,  /* xFileSize */
   90877   0,                /* xLock */
   90878   0,                /* xUnlock */
   90879   0,                /* xCheckReservedLock */
   90880   0,                /* xFileControl */
   90881   0,                /* xSectorSize */
   90882   0,                /* xDeviceCharacteristics */
   90883   0,                /* xShmMap */
   90884   0,                /* xShmLock */
   90885   0,                /* xShmBarrier */
   90886   0,                /* xShmUnmap */
   90887   0,                /* xFetch */
   90888   0                 /* xUnfetch */
   90889 };
   90890 
   90891 /*
   90892 ** Open a journal file.
   90893 **
   90894 ** The behaviour of the journal file depends on the value of parameter
   90895 ** nSpill. If nSpill is 0, then the journal file is always create and
   90896 ** accessed using the underlying VFS. If nSpill is less than zero, then
   90897 ** all content is always stored in main-memory. Finally, if nSpill is a
   90898 ** positive value, then the journal file is initially created in-memory
   90899 ** but may be flushed to disk later on. In this case the journal file is
   90900 ** flushed to disk either when it grows larger than nSpill bytes in size,
   90901 ** or when sqlite3JournalCreate() is called.
   90902 */
   90903 SQLITE_PRIVATE int sqlite3JournalOpen(
   90904   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
   90905   const char *zName,         /* Name of the journal file */
   90906   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
   90907   int flags,                 /* Opening flags */
   90908   int nSpill                 /* Bytes buffered before opening the file */
   90909 ){
   90910   MemJournal *p = (MemJournal*)pJfd;
   90911 
   90912   /* Zero the file-handle object. If nSpill was passed zero, initialize
   90913   ** it using the sqlite3OsOpen() function of the underlying VFS. In this
   90914   ** case none of the code in this module is executed as a result of calls
   90915   ** made on the journal file-handle.  */
   90916   memset(p, 0, sizeof(MemJournal));
   90917   if( nSpill==0 ){
   90918     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
   90919   }
   90920 
   90921   if( nSpill>0 ){
   90922     p->nChunkSize = nSpill;
   90923   }else{
   90924     p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
   90925     assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
   90926   }
   90927 
   90928   p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
   90929   p->nSpill = nSpill;
   90930   p->flags = flags;
   90931   p->zJournal = zName;
   90932   p->pVfs = pVfs;
   90933   return SQLITE_OK;
   90934 }
   90935 
   90936 /*
   90937 ** Open an in-memory journal file.
   90938 */
   90939 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
   90940   sqlite3JournalOpen(0, 0, pJfd, 0, -1);
   90941 }
   90942 
   90943 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
   90944  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
   90945 /*
   90946 ** If the argument p points to a MemJournal structure that is not an
   90947 ** in-memory-only journal file (i.e. is one that was opened with a +ve
   90948 ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
   90949 ** file has not yet been created, create it now.
   90950 */
   90951 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
   90952   int rc = SQLITE_OK;
   90953   MemJournal *p = (MemJournal*)pJfd;
   90954   if( p->pMethod==&MemJournalMethods && (
   90955 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   90956      p->nSpill>0
   90957 #else
   90958      /* While this appears to not be possible without ATOMIC_WRITE, the
   90959      ** paths are complex, so it seems prudent to leave the test in as
   90960      ** a NEVER(), in case our analysis is subtly flawed. */
   90961      NEVER(p->nSpill>0)
   90962 #endif
   90963 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   90964      || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
   90965 #endif
   90966   )){
   90967     rc = memjrnlCreateFile(p);
   90968   }
   90969   return rc;
   90970 }
   90971 #endif
   90972 
   90973 /*
   90974 ** The file-handle passed as the only argument is open on a journal file.
   90975 ** Return true if this "journal file" is currently stored in heap memory,
   90976 ** or false otherwise.
   90977 */
   90978 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
   90979   return p->pMethods==&MemJournalMethods;
   90980 }
   90981 
   90982 /*
   90983 ** Return the number of bytes required to store a JournalFile that uses vfs
   90984 ** pVfs to create the underlying on-disk files.
   90985 */
   90986 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
   90987   return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
   90988 }
   90989 
   90990 /************** End of memjournal.c ******************************************/
   90991 /************** Begin file walker.c ******************************************/
   90992 /*
   90993 ** 2008 August 16
   90994 **
   90995 ** The author disclaims copyright to this source code.  In place of
   90996 ** a legal notice, here is a blessing:
   90997 **
   90998 **    May you do good and not evil.
   90999 **    May you find forgiveness for yourself and forgive others.
   91000 **    May you share freely, never taking more than you give.
   91001 **
   91002 *************************************************************************
   91003 ** This file contains routines used for walking the parser tree for
   91004 ** an SQL statement.
   91005 */
   91006 /* #include "sqliteInt.h" */
   91007 /* #include <stdlib.h> */
   91008 /* #include <string.h> */
   91009 
   91010 
   91011 /*
   91012 ** Walk an expression tree.  Invoke the callback once for each node
   91013 ** of the expression, while descending.  (In other words, the callback
   91014 ** is invoked before visiting children.)
   91015 **
   91016 ** The return value from the callback should be one of the WRC_*
   91017 ** constants to specify how to proceed with the walk.
   91018 **
   91019 **    WRC_Continue      Continue descending down the tree.
   91020 **
   91021 **    WRC_Prune         Do not descend into child nodes, but allow
   91022 **                      the walk to continue with sibling nodes.
   91023 **
   91024 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
   91025 **                      return from the top-level walk call.
   91026 **
   91027 ** The return value from this routine is WRC_Abort to abandon the tree walk
   91028 ** and WRC_Continue to continue.
   91029 */
   91030 static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
   91031   int rc;
   91032   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
   91033   testcase( ExprHasProperty(pExpr, EP_Reduced) );
   91034   while(1){
   91035     rc = pWalker->xExprCallback(pWalker, pExpr);
   91036     if( rc ) return rc & WRC_Abort;
   91037     if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
   91038       if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
   91039        assert( pExpr->x.pList==0 || pExpr->pRight==0 );
   91040       if( pExpr->pRight ){
   91041         pExpr = pExpr->pRight;
   91042         continue;
   91043       }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   91044         if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
   91045       }else if( pExpr->x.pList ){
   91046         if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
   91047       }
   91048     }
   91049     break;
   91050   }
   91051   return WRC_Continue;
   91052 }
   91053 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
   91054   return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
   91055 }
   91056 
   91057 /*
   91058 ** Call sqlite3WalkExpr() for every expression in list p or until
   91059 ** an abort request is seen.
   91060 */
   91061 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   91062   int i;
   91063   struct ExprList_item *pItem;
   91064   if( p ){
   91065     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
   91066       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
   91067     }
   91068   }
   91069   return WRC_Continue;
   91070 }
   91071 
   91072 /*
   91073 ** Walk all expressions associated with SELECT statement p.  Do
   91074 ** not invoke the SELECT callback on p, but do (of course) invoke
   91075 ** any expr callbacks and SELECT callbacks that come from subqueries.
   91076 ** Return WRC_Abort or WRC_Continue.
   91077 */
   91078 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   91079   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
   91080   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
   91081   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
   91082   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   91083   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   91084   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
   91085   return WRC_Continue;
   91086 }
   91087 
   91088 /*
   91089 ** Walk the parse trees associated with all subqueries in the
   91090 ** FROM clause of SELECT statement p.  Do not invoke the select
   91091 ** callback on p, but do invoke it on each FROM clause subquery
   91092 ** and on any subqueries further down in the tree.  Return
   91093 ** WRC_Abort or WRC_Continue;
   91094 */
   91095 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   91096   SrcList *pSrc;
   91097   int i;
   91098   struct SrcList_item *pItem;
   91099 
   91100   pSrc = p->pSrc;
   91101   assert( pSrc!=0 );
   91102   for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   91103     if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
   91104       return WRC_Abort;
   91105     }
   91106     if( pItem->fg.isTabFunc
   91107      && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
   91108     ){
   91109       return WRC_Abort;
   91110     }
   91111   }
   91112   return WRC_Continue;
   91113 }
   91114 
   91115 /*
   91116 ** Call sqlite3WalkExpr() for every expression in Select statement p.
   91117 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
   91118 ** on the compound select chain, p->pPrior.
   91119 **
   91120 ** If it is not NULL, the xSelectCallback() callback is invoked before
   91121 ** the walk of the expressions and FROM clause. The xSelectCallback2()
   91122 ** method is invoked following the walk of the expressions and FROM clause,
   91123 ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
   91124 ** and if the expressions and FROM clause both return WRC_Continue;
   91125 **
   91126 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
   91127 ** there is an abort request.
   91128 **
   91129 ** If the Walker does not have an xSelectCallback() then this routine
   91130 ** is a no-op returning WRC_Continue.
   91131 */
   91132 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   91133   int rc;
   91134   if( p==0 ) return WRC_Continue;
   91135   if( pWalker->xSelectCallback==0 ) return WRC_Continue;
   91136   do{
   91137     rc = pWalker->xSelectCallback(pWalker, p);
   91138     if( rc ) return rc & WRC_Abort;
   91139     if( sqlite3WalkSelectExpr(pWalker, p)
   91140      || sqlite3WalkSelectFrom(pWalker, p)
   91141     ){
   91142       return WRC_Abort;
   91143     }
   91144     if( pWalker->xSelectCallback2 ){
   91145       pWalker->xSelectCallback2(pWalker, p);
   91146     }
   91147     p = p->pPrior;
   91148   }while( p!=0 );
   91149   return WRC_Continue;
   91150 }
   91151 
   91152 /************** End of walker.c **********************************************/
   91153 /************** Begin file resolve.c *****************************************/
   91154 /*
   91155 ** 2008 August 18
   91156 **
   91157 ** The author disclaims copyright to this source code.  In place of
   91158 ** a legal notice, here is a blessing:
   91159 **
   91160 **    May you do good and not evil.
   91161 **    May you find forgiveness for yourself and forgive others.
   91162 **    May you share freely, never taking more than you give.
   91163 **
   91164 *************************************************************************
   91165 **
   91166 ** This file contains routines used for walking the parser tree and
   91167 ** resolve all identifiers by associating them with a particular
   91168 ** table and column.
   91169 */
   91170 /* #include "sqliteInt.h" */
   91171 
   91172 /*
   91173 ** Walk the expression tree pExpr and increase the aggregate function
   91174 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
   91175 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
   91176 ** outer query into an inner subquery.
   91177 **
   91178 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
   91179 ** is a helper function - a callback for the tree walker.
   91180 */
   91181 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
   91182   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
   91183   return WRC_Continue;
   91184 }
   91185 static void incrAggFunctionDepth(Expr *pExpr, int N){
   91186   if( N>0 ){
   91187     Walker w;
   91188     memset(&w, 0, sizeof(w));
   91189     w.xExprCallback = incrAggDepth;
   91190     w.u.n = N;
   91191     sqlite3WalkExpr(&w, pExpr);
   91192   }
   91193 }
   91194 
   91195 /*
   91196 ** Turn the pExpr expression into an alias for the iCol-th column of the
   91197 ** result set in pEList.
   91198 **
   91199 ** If the reference is followed by a COLLATE operator, then make sure
   91200 ** the COLLATE operator is preserved.  For example:
   91201 **
   91202 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
   91203 **
   91204 ** Should be transformed into:
   91205 **
   91206 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
   91207 **
   91208 ** The nSubquery parameter specifies how many levels of subquery the
   91209 ** alias is removed from the original expression.  The usual value is
   91210 ** zero but it might be more if the alias is contained within a subquery
   91211 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
   91212 ** structures must be increased by the nSubquery amount.
   91213 */
   91214 static void resolveAlias(
   91215   Parse *pParse,         /* Parsing context */
   91216   ExprList *pEList,      /* A result set */
   91217   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   91218   Expr *pExpr,           /* Transform this into an alias to the result set */
   91219   const char *zType,     /* "GROUP" or "ORDER" or "" */
   91220   int nSubquery          /* Number of subqueries that the label is moving */
   91221 ){
   91222   Expr *pOrig;           /* The iCol-th column of the result set */
   91223   Expr *pDup;            /* Copy of pOrig */
   91224   sqlite3 *db;           /* The database connection */
   91225 
   91226   assert( iCol>=0 && iCol<pEList->nExpr );
   91227   pOrig = pEList->a[iCol].pExpr;
   91228   assert( pOrig!=0 );
   91229   db = pParse->db;
   91230   pDup = sqlite3ExprDup(db, pOrig, 0);
   91231   if( pDup==0 ) return;
   91232   if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
   91233   if( pExpr->op==TK_COLLATE ){
   91234     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
   91235   }
   91236   ExprSetProperty(pDup, EP_Alias);
   91237 
   91238   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
   91239   ** prevents ExprDelete() from deleting the Expr structure itself,
   91240   ** allowing it to be repopulated by the memcpy() on the following line.
   91241   ** The pExpr->u.zToken might point into memory that will be freed by the
   91242   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
   91243   ** make a copy of the token before doing the sqlite3DbFree().
   91244   */
   91245   ExprSetProperty(pExpr, EP_Static);
   91246   sqlite3ExprDelete(db, pExpr);
   91247   memcpy(pExpr, pDup, sizeof(*pExpr));
   91248   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
   91249     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
   91250     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
   91251     pExpr->flags |= EP_MemToken;
   91252   }
   91253   sqlite3DbFree(db, pDup);
   91254 }
   91255 
   91256 
   91257 /*
   91258 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
   91259 **
   91260 ** Return FALSE if the USING clause is NULL or if it does not contain
   91261 ** zCol.
   91262 */
   91263 static int nameInUsingClause(IdList *pUsing, const char *zCol){
   91264   if( pUsing ){
   91265     int k;
   91266     for(k=0; k<pUsing->nId; k++){
   91267       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
   91268     }
   91269   }
   91270   return 0;
   91271 }
   91272 
   91273 /*
   91274 ** Subqueries stores the original database, table and column names for their
   91275 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
   91276 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
   91277 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
   91278 ** match anything.
   91279 */
   91280 SQLITE_PRIVATE int sqlite3MatchSpanName(
   91281   const char *zSpan,
   91282   const char *zCol,
   91283   const char *zTab,
   91284   const char *zDb
   91285 ){
   91286   int n;
   91287   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
   91288   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
   91289     return 0;
   91290   }
   91291   zSpan += n+1;
   91292   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
   91293   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
   91294     return 0;
   91295   }
   91296   zSpan += n+1;
   91297   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
   91298     return 0;
   91299   }
   91300   return 1;
   91301 }
   91302 
   91303 /*
   91304 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
   91305 ** that name in the set of source tables in pSrcList and make the pExpr
   91306 ** expression node refer back to that source column.  The following changes
   91307 ** are made to pExpr:
   91308 **
   91309 **    pExpr->iDb           Set the index in db->aDb[] of the database X
   91310 **                         (even if X is implied).
   91311 **    pExpr->iTable        Set to the cursor number for the table obtained
   91312 **                         from pSrcList.
   91313 **    pExpr->pTab          Points to the Table structure of X.Y (even if
   91314 **                         X and/or Y are implied.)
   91315 **    pExpr->iColumn       Set to the column number within the table.
   91316 **    pExpr->op            Set to TK_COLUMN.
   91317 **    pExpr->pLeft         Any expression this points to is deleted
   91318 **    pExpr->pRight        Any expression this points to is deleted.
   91319 **
   91320 ** The zDb variable is the name of the database (the "X").  This value may be
   91321 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
   91322 ** can be used.  The zTable variable is the name of the table (the "Y").  This
   91323 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
   91324 ** means that the form of the name is Z and that columns from any table
   91325 ** can be used.
   91326 **
   91327 ** If the name cannot be resolved unambiguously, leave an error message
   91328 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
   91329 */
   91330 static int lookupName(
   91331   Parse *pParse,       /* The parsing context */
   91332   const char *zDb,     /* Name of the database containing table, or NULL */
   91333   const char *zTab,    /* Name of table containing column, or NULL */
   91334   const char *zCol,    /* Name of the column. */
   91335   NameContext *pNC,    /* The name context used to resolve the name */
   91336   Expr *pExpr          /* Make this EXPR node point to the selected column */
   91337 ){
   91338   int i, j;                         /* Loop counters */
   91339   int cnt = 0;                      /* Number of matching column names */
   91340   int cntTab = 0;                   /* Number of matching table names */
   91341   int nSubquery = 0;                /* How many levels of subquery */
   91342   sqlite3 *db = pParse->db;         /* The database connection */
   91343   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   91344   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   91345   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   91346   Schema *pSchema = 0;              /* Schema of the expression */
   91347   int isTrigger = 0;                /* True if resolved to a trigger column */
   91348   Table *pTab = 0;                  /* Table hold the row */
   91349   Column *pCol;                     /* A column of pTab */
   91350 
   91351   assert( pNC );     /* the name context cannot be NULL. */
   91352   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   91353   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   91354 
   91355   /* Initialize the node to no-match */
   91356   pExpr->iTable = -1;
   91357   pExpr->pTab = 0;
   91358   ExprSetVVAProperty(pExpr, EP_NoReduce);
   91359 
   91360   /* Translate the schema name in zDb into a pointer to the corresponding
   91361   ** schema.  If not found, pSchema will remain NULL and nothing will match
   91362   ** resulting in an appropriate error message toward the end of this routine
   91363   */
   91364   if( zDb ){
   91365     testcase( pNC->ncFlags & NC_PartIdx );
   91366     testcase( pNC->ncFlags & NC_IsCheck );
   91367     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
   91368       /* Silently ignore database qualifiers inside CHECK constraints and
   91369       ** partial indices.  Do not raise errors because that might break
   91370       ** legacy and because it does not hurt anything to just ignore the
   91371       ** database name. */
   91372       zDb = 0;
   91373     }else{
   91374       for(i=0; i<db->nDb; i++){
   91375         assert( db->aDb[i].zDbSName );
   91376         if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
   91377           pSchema = db->aDb[i].pSchema;
   91378           break;
   91379         }
   91380       }
   91381     }
   91382   }
   91383 
   91384   /* Start at the inner-most context and move outward until a match is found */
   91385   assert( pNC && cnt==0 );
   91386   do{
   91387     ExprList *pEList;
   91388     SrcList *pSrcList = pNC->pSrcList;
   91389 
   91390     if( pSrcList ){
   91391       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   91392         pTab = pItem->pTab;
   91393         assert( pTab!=0 && pTab->zName!=0 );
   91394         assert( pTab->nCol>0 );
   91395         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
   91396           int hit = 0;
   91397           pEList = pItem->pSelect->pEList;
   91398           for(j=0; j<pEList->nExpr; j++){
   91399             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
   91400               cnt++;
   91401               cntTab = 2;
   91402               pMatch = pItem;
   91403               pExpr->iColumn = j;
   91404               hit = 1;
   91405             }
   91406           }
   91407           if( hit || zTab==0 ) continue;
   91408         }
   91409         if( zDb && pTab->pSchema!=pSchema ){
   91410           continue;
   91411         }
   91412         if( zTab ){
   91413           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
   91414           assert( zTabName!=0 );
   91415           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
   91416             continue;
   91417           }
   91418         }
   91419         if( 0==(cntTab++) ){
   91420           pMatch = pItem;
   91421         }
   91422         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   91423           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   91424             /* If there has been exactly one prior match and this match
   91425             ** is for the right-hand table of a NATURAL JOIN or is in a
   91426             ** USING clause, then skip this match.
   91427             */
   91428             if( cnt==1 ){
   91429               if( pItem->fg.jointype & JT_NATURAL ) continue;
   91430               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
   91431             }
   91432             cnt++;
   91433             pMatch = pItem;
   91434             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   91435             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
   91436             break;
   91437           }
   91438         }
   91439       }
   91440       if( pMatch ){
   91441         pExpr->iTable = pMatch->iCursor;
   91442         pExpr->pTab = pMatch->pTab;
   91443         /* RIGHT JOIN not (yet) supported */
   91444         assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
   91445         if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
   91446           ExprSetProperty(pExpr, EP_CanBeNull);
   91447         }
   91448         pSchema = pExpr->pTab->pSchema;
   91449       }
   91450     } /* if( pSrcList ) */
   91451 
   91452 #ifndef SQLITE_OMIT_TRIGGER
   91453     /* If we have not already resolved the name, then maybe
   91454     ** it is a new.* or old.* trigger argument reference
   91455     */
   91456     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
   91457       int op = pParse->eTriggerOp;
   91458       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   91459       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   91460         pExpr->iTable = 1;
   91461         pTab = pParse->pTriggerTab;
   91462       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   91463         pExpr->iTable = 0;
   91464         pTab = pParse->pTriggerTab;
   91465       }else{
   91466         pTab = 0;
   91467       }
   91468 
   91469       if( pTab ){
   91470         int iCol;
   91471         pSchema = pTab->pSchema;
   91472         cntTab++;
   91473         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
   91474           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   91475             if( iCol==pTab->iPKey ){
   91476               iCol = -1;
   91477             }
   91478             break;
   91479           }
   91480         }
   91481         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
   91482           /* IMP: R-51414-32910 */
   91483           iCol = -1;
   91484         }
   91485         if( iCol<pTab->nCol ){
   91486           cnt++;
   91487           if( iCol<0 ){
   91488             pExpr->affinity = SQLITE_AFF_INTEGER;
   91489           }else if( pExpr->iTable==0 ){
   91490             testcase( iCol==31 );
   91491             testcase( iCol==32 );
   91492             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   91493           }else{
   91494             testcase( iCol==31 );
   91495             testcase( iCol==32 );
   91496             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   91497           }
   91498           pExpr->iColumn = (i16)iCol;
   91499           pExpr->pTab = pTab;
   91500           isTrigger = 1;
   91501         }
   91502       }
   91503     }
   91504 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   91505 
   91506     /*
   91507     ** Perhaps the name is a reference to the ROWID
   91508     */
   91509     if( cnt==0
   91510      && cntTab==1
   91511      && pMatch
   91512      && (pNC->ncFlags & NC_IdxExpr)==0
   91513      && sqlite3IsRowid(zCol)
   91514      && VisibleRowid(pMatch->pTab)
   91515     ){
   91516       cnt = 1;
   91517       pExpr->iColumn = -1;
   91518       pExpr->affinity = SQLITE_AFF_INTEGER;
   91519     }
   91520 
   91521     /*
   91522     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
   91523     ** might refer to an result-set alias.  This happens, for example, when
   91524     ** we are resolving names in the WHERE clause of the following command:
   91525     **
   91526     **     SELECT a+b AS x FROM table WHERE x<10;
   91527     **
   91528     ** In cases like this, replace pExpr with a copy of the expression that
   91529     ** forms the result set entry ("a+b" in the example) and return immediately.
   91530     ** Note that the expression in the result set should have already been
   91531     ** resolved by the time the WHERE clause is resolved.
   91532     **
   91533     ** The ability to use an output result-set column in the WHERE, GROUP BY,
   91534     ** or HAVING clauses, or as part of a larger expression in the ORDER BY
   91535     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
   91536     ** is supported for backwards compatibility only. Hence, we issue a warning
   91537     ** on sqlite3_log() whenever the capability is used.
   91538     */
   91539     if( (pEList = pNC->pEList)!=0
   91540      && zTab==0
   91541      && cnt==0
   91542     ){
   91543       for(j=0; j<pEList->nExpr; j++){
   91544         char *zAs = pEList->a[j].zName;
   91545         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   91546           Expr *pOrig;
   91547           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   91548           assert( pExpr->x.pList==0 );
   91549           assert( pExpr->x.pSelect==0 );
   91550           pOrig = pEList->a[j].pExpr;
   91551           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
   91552             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
   91553             return WRC_Abort;
   91554           }
   91555           if( sqlite3ExprVectorSize(pOrig)!=1 ){
   91556             sqlite3ErrorMsg(pParse, "row value misused");
   91557             return WRC_Abort;
   91558           }
   91559           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
   91560           cnt = 1;
   91561           pMatch = 0;
   91562           assert( zTab==0 && zDb==0 );
   91563           goto lookupname_end;
   91564         }
   91565       }
   91566     }
   91567 
   91568     /* Advance to the next name context.  The loop will exit when either
   91569     ** we have a match (cnt>0) or when we run out of name contexts.
   91570     */
   91571     if( cnt ) break;
   91572     pNC = pNC->pNext;
   91573     nSubquery++;
   91574   }while( pNC );
   91575 
   91576 
   91577   /*
   91578   ** If X and Y are NULL (in other words if only the column name Z is
   91579   ** supplied) and the value of Z is enclosed in double-quotes, then
   91580   ** Z is a string literal if it doesn't match any column names.  In that
   91581   ** case, we need to return right away and not make any changes to
   91582   ** pExpr.
   91583   **
   91584   ** Because no reference was made to outer contexts, the pNC->nRef
   91585   ** fields are not changed in any context.
   91586   */
   91587   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
   91588     pExpr->op = TK_STRING;
   91589     pExpr->pTab = 0;
   91590     return WRC_Prune;
   91591   }
   91592 
   91593   /*
   91594   ** cnt==0 means there was not match.  cnt>1 means there were two or
   91595   ** more matches.  Either way, we have an error.
   91596   */
   91597   if( cnt!=1 ){
   91598     const char *zErr;
   91599     zErr = cnt==0 ? "no such column" : "ambiguous column name";
   91600     if( zDb ){
   91601       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
   91602     }else if( zTab ){
   91603       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
   91604     }else{
   91605       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
   91606     }
   91607     pParse->checkSchema = 1;
   91608     pTopNC->nErr++;
   91609   }
   91610 
   91611   /* If a column from a table in pSrcList is referenced, then record
   91612   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
   91613   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
   91614   ** column number is greater than the number of bits in the bitmask
   91615   ** then set the high-order bit of the bitmask.
   91616   */
   91617   if( pExpr->iColumn>=0 && pMatch!=0 ){
   91618     int n = pExpr->iColumn;
   91619     testcase( n==BMS-1 );
   91620     if( n>=BMS ){
   91621       n = BMS-1;
   91622     }
   91623     assert( pMatch->iCursor==pExpr->iTable );
   91624     pMatch->colUsed |= ((Bitmask)1)<<n;
   91625   }
   91626 
   91627   /* Clean up and return
   91628   */
   91629   sqlite3ExprDelete(db, pExpr->pLeft);
   91630   pExpr->pLeft = 0;
   91631   sqlite3ExprDelete(db, pExpr->pRight);
   91632   pExpr->pRight = 0;
   91633   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   91634   ExprSetProperty(pExpr, EP_Leaf);
   91635 lookupname_end:
   91636   if( cnt==1 ){
   91637     assert( pNC!=0 );
   91638     if( !ExprHasProperty(pExpr, EP_Alias) ){
   91639       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   91640     }
   91641     /* Increment the nRef value on all name contexts from TopNC up to
   91642     ** the point where the name matched. */
   91643     for(;;){
   91644       assert( pTopNC!=0 );
   91645       pTopNC->nRef++;
   91646       if( pTopNC==pNC ) break;
   91647       pTopNC = pTopNC->pNext;
   91648     }
   91649     return WRC_Prune;
   91650   } else {
   91651     return WRC_Abort;
   91652   }
   91653 }
   91654 
   91655 /*
   91656 ** Allocate and return a pointer to an expression to load the column iCol
   91657 ** from datasource iSrc in SrcList pSrc.
   91658 */
   91659 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   91660   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   91661   if( p ){
   91662     struct SrcList_item *pItem = &pSrc->a[iSrc];
   91663     p->pTab = pItem->pTab;
   91664     p->iTable = pItem->iCursor;
   91665     if( p->pTab->iPKey==iCol ){
   91666       p->iColumn = -1;
   91667     }else{
   91668       p->iColumn = (ynVar)iCol;
   91669       testcase( iCol==BMS );
   91670       testcase( iCol==BMS-1 );
   91671       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   91672     }
   91673   }
   91674   return p;
   91675 }
   91676 
   91677 /*
   91678 ** Report an error that an expression is not valid for some set of
   91679 ** pNC->ncFlags values determined by validMask.
   91680 */
   91681 static void notValid(
   91682   Parse *pParse,       /* Leave error message here */
   91683   NameContext *pNC,    /* The name context */
   91684   const char *zMsg,    /* Type of error */
   91685   int validMask        /* Set of contexts for which prohibited */
   91686 ){
   91687   assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
   91688   if( (pNC->ncFlags & validMask)!=0 ){
   91689     const char *zIn = "partial index WHERE clauses";
   91690     if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
   91691 #ifndef SQLITE_OMIT_CHECK
   91692     else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
   91693 #endif
   91694     sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
   91695   }
   91696 }
   91697 
   91698 /*
   91699 ** Expression p should encode a floating point value between 1.0 and 0.0.
   91700 ** Return 1024 times this value.  Or return -1 if p is not a floating point
   91701 ** value between 1.0 and 0.0.
   91702 */
   91703 static int exprProbability(Expr *p){
   91704   double r = -1.0;
   91705   if( p->op!=TK_FLOAT ) return -1;
   91706   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
   91707   assert( r>=0.0 );
   91708   if( r>1.0 ) return -1;
   91709   return (int)(r*134217728.0);
   91710 }
   91711 
   91712 /*
   91713 ** This routine is callback for sqlite3WalkExpr().
   91714 **
   91715 ** Resolve symbolic names into TK_COLUMN operators for the current
   91716 ** node in the expression tree.  Return 0 to continue the search down
   91717 ** the tree or 2 to abort the tree walk.
   91718 **
   91719 ** This routine also does error checking and name resolution for
   91720 ** function names.  The operator for aggregate functions is changed
   91721 ** to TK_AGG_FUNCTION.
   91722 */
   91723 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
   91724   NameContext *pNC;
   91725   Parse *pParse;
   91726 
   91727   pNC = pWalker->u.pNC;
   91728   assert( pNC!=0 );
   91729   pParse = pNC->pParse;
   91730   assert( pParse==pWalker->pParse );
   91731 
   91732 #ifndef NDEBUG
   91733   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
   91734     SrcList *pSrcList = pNC->pSrcList;
   91735     int i;
   91736     for(i=0; i<pNC->pSrcList->nSrc; i++){
   91737       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
   91738     }
   91739   }
   91740 #endif
   91741   switch( pExpr->op ){
   91742 
   91743 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   91744     /* The special operator TK_ROW means use the rowid for the first
   91745     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
   91746     ** clause processing on UPDATE and DELETE statements.
   91747     */
   91748     case TK_ROW: {
   91749       SrcList *pSrcList = pNC->pSrcList;
   91750       struct SrcList_item *pItem;
   91751       assert( pSrcList && pSrcList->nSrc==1 );
   91752       pItem = pSrcList->a;
   91753       assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
   91754       pExpr->op = TK_COLUMN;
   91755       pExpr->pTab = pItem->pTab;
   91756       pExpr->iTable = pItem->iCursor;
   91757       pExpr->iColumn = -1;
   91758       pExpr->affinity = SQLITE_AFF_INTEGER;
   91759       break;
   91760     }
   91761 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
   91762           && !defined(SQLITE_OMIT_SUBQUERY) */
   91763 
   91764     /* A column name:                    ID
   91765     ** Or table name and column name:    ID.ID
   91766     ** Or a database, table and column:  ID.ID.ID
   91767     **
   91768     ** The TK_ID and TK_OUT cases are combined so that there will only
   91769     ** be one call to lookupName().  Then the compiler will in-line
   91770     ** lookupName() for a size reduction and performance increase.
   91771     */
   91772     case TK_ID:
   91773     case TK_DOT: {
   91774       const char *zColumn;
   91775       const char *zTable;
   91776       const char *zDb;
   91777       Expr *pRight;
   91778 
   91779       if( pExpr->op==TK_ID ){
   91780         zDb = 0;
   91781         zTable = 0;
   91782         zColumn = pExpr->u.zToken;
   91783       }else{
   91784         notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
   91785         pRight = pExpr->pRight;
   91786         if( pRight->op==TK_ID ){
   91787           zDb = 0;
   91788           zTable = pExpr->pLeft->u.zToken;
   91789           zColumn = pRight->u.zToken;
   91790         }else{
   91791           assert( pRight->op==TK_DOT );
   91792           zDb = pExpr->pLeft->u.zToken;
   91793           zTable = pRight->pLeft->u.zToken;
   91794           zColumn = pRight->pRight->u.zToken;
   91795         }
   91796       }
   91797       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
   91798     }
   91799 
   91800     /* Resolve function names
   91801     */
   91802     case TK_FUNCTION: {
   91803       ExprList *pList = pExpr->x.pList;    /* The argument list */
   91804       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
   91805       int no_such_func = 0;       /* True if no such function exists */
   91806       int wrong_num_args = 0;     /* True if wrong number of arguments */
   91807       int is_agg = 0;             /* True if is an aggregate function */
   91808       int nId;                    /* Number of characters in function name */
   91809       const char *zId;            /* The function name. */
   91810       FuncDef *pDef;              /* Information about the function */
   91811       u8 enc = ENC(pParse->db);   /* The database encoding */
   91812 
   91813       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   91814       zId = pExpr->u.zToken;
   91815       nId = sqlite3Strlen30(zId);
   91816       pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
   91817       if( pDef==0 ){
   91818         pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
   91819         if( pDef==0 ){
   91820           no_such_func = 1;
   91821         }else{
   91822           wrong_num_args = 1;
   91823         }
   91824       }else{
   91825         is_agg = pDef->xFinalize!=0;
   91826         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
   91827           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
   91828           if( n==2 ){
   91829             pExpr->iTable = exprProbability(pList->a[1].pExpr);
   91830             if( pExpr->iTable<0 ){
   91831               sqlite3ErrorMsg(pParse,
   91832                 "second argument to likelihood() must be a "
   91833                 "constant between 0.0 and 1.0");
   91834               pNC->nErr++;
   91835             }
   91836           }else{
   91837             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
   91838             ** equivalent to likelihood(X, 0.0625).
   91839             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
   91840             ** short-hand for likelihood(X,0.0625).
   91841             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
   91842             ** for likelihood(X,0.9375).
   91843             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
   91844             ** to likelihood(X,0.9375). */
   91845             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
   91846             pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
   91847           }
   91848         }
   91849 #ifndef SQLITE_OMIT_AUTHORIZATION
   91850         {
   91851           int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
   91852           if( auth!=SQLITE_OK ){
   91853             if( auth==SQLITE_DENY ){
   91854               sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
   91855                                       pDef->zName);
   91856               pNC->nErr++;
   91857             }
   91858             pExpr->op = TK_NULL;
   91859             return WRC_Prune;
   91860           }
   91861         }
   91862 #endif
   91863         if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
   91864           /* For the purposes of the EP_ConstFunc flag, date and time
   91865           ** functions and other functions that change slowly are considered
   91866           ** constant because they are constant for the duration of one query */
   91867           ExprSetProperty(pExpr,EP_ConstFunc);
   91868         }
   91869         if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
   91870           /* Date/time functions that use 'now', and other functions like
   91871           ** sqlite_version() that might change over time cannot be used
   91872           ** in an index. */
   91873           notValid(pParse, pNC, "non-deterministic functions",
   91874                    NC_IdxExpr|NC_PartIdx);
   91875         }
   91876       }
   91877       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
   91878         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
   91879         pNC->nErr++;
   91880         is_agg = 0;
   91881       }else if( no_such_func && pParse->db->init.busy==0
   91882 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
   91883                 && pParse->explain==0
   91884 #endif
   91885       ){
   91886         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
   91887         pNC->nErr++;
   91888       }else if( wrong_num_args ){
   91889         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
   91890              nId, zId);
   91891         pNC->nErr++;
   91892       }
   91893       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
   91894       sqlite3WalkExprList(pWalker, pList);
   91895       if( is_agg ){
   91896         NameContext *pNC2 = pNC;
   91897         pExpr->op = TK_AGG_FUNCTION;
   91898         pExpr->op2 = 0;
   91899         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
   91900           pExpr->op2++;
   91901           pNC2 = pNC2->pNext;
   91902         }
   91903         assert( pDef!=0 );
   91904         if( pNC2 ){
   91905           assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
   91906           testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
   91907           pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
   91908 
   91909         }
   91910         pNC->ncFlags |= NC_AllowAgg;
   91911       }
   91912       /* FIX ME:  Compute pExpr->affinity based on the expected return
   91913       ** type of the function
   91914       */
   91915       return WRC_Prune;
   91916     }
   91917 #ifndef SQLITE_OMIT_SUBQUERY
   91918     case TK_SELECT:
   91919     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   91920 #endif
   91921     case TK_IN: {
   91922       testcase( pExpr->op==TK_IN );
   91923       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   91924         int nRef = pNC->nRef;
   91925         notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
   91926         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   91927         assert( pNC->nRef>=nRef );
   91928         if( nRef!=pNC->nRef ){
   91929           ExprSetProperty(pExpr, EP_VarSelect);
   91930           pNC->ncFlags |= NC_VarSelect;
   91931         }
   91932       }
   91933       break;
   91934     }
   91935     case TK_VARIABLE: {
   91936       notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
   91937       break;
   91938     }
   91939     case TK_BETWEEN:
   91940     case TK_EQ:
   91941     case TK_NE:
   91942     case TK_LT:
   91943     case TK_LE:
   91944     case TK_GT:
   91945     case TK_GE:
   91946     case TK_IS:
   91947     case TK_ISNOT: {
   91948       int nLeft, nRight;
   91949       if( pParse->db->mallocFailed ) break;
   91950       assert( pExpr->pLeft!=0 );
   91951       nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
   91952       if( pExpr->op==TK_BETWEEN ){
   91953         nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
   91954         if( nRight==nLeft ){
   91955           nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
   91956         }
   91957       }else{
   91958         assert( pExpr->pRight!=0 );
   91959         nRight = sqlite3ExprVectorSize(pExpr->pRight);
   91960       }
   91961       if( nLeft!=nRight ){
   91962         testcase( pExpr->op==TK_EQ );
   91963         testcase( pExpr->op==TK_NE );
   91964         testcase( pExpr->op==TK_LT );
   91965         testcase( pExpr->op==TK_LE );
   91966         testcase( pExpr->op==TK_GT );
   91967         testcase( pExpr->op==TK_GE );
   91968         testcase( pExpr->op==TK_IS );
   91969         testcase( pExpr->op==TK_ISNOT );
   91970         testcase( pExpr->op==TK_BETWEEN );
   91971         sqlite3ErrorMsg(pParse, "row value misused");
   91972       }
   91973       break;
   91974     }
   91975   }
   91976   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   91977 }
   91978 
   91979 /*
   91980 ** pEList is a list of expressions which are really the result set of the
   91981 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
   91982 ** This routine checks to see if pE is a simple identifier which corresponds
   91983 ** to the AS-name of one of the terms of the expression list.  If it is,
   91984 ** this routine return an integer between 1 and N where N is the number of
   91985 ** elements in pEList, corresponding to the matching entry.  If there is
   91986 ** no match, or if pE is not a simple identifier, then this routine
   91987 ** return 0.
   91988 **
   91989 ** pEList has been resolved.  pE has not.
   91990 */
   91991 static int resolveAsName(
   91992   Parse *pParse,     /* Parsing context for error messages */
   91993   ExprList *pEList,  /* List of expressions to scan */
   91994   Expr *pE           /* Expression we are trying to match */
   91995 ){
   91996   int i;             /* Loop counter */
   91997 
   91998   UNUSED_PARAMETER(pParse);
   91999 
   92000   if( pE->op==TK_ID ){
   92001     char *zCol = pE->u.zToken;
   92002     for(i=0; i<pEList->nExpr; i++){
   92003       char *zAs = pEList->a[i].zName;
   92004       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   92005         return i+1;
   92006       }
   92007     }
   92008   }
   92009   return 0;
   92010 }
   92011 
   92012 /*
   92013 ** pE is a pointer to an expression which is a single term in the
   92014 ** ORDER BY of a compound SELECT.  The expression has not been
   92015 ** name resolved.
   92016 **
   92017 ** At the point this routine is called, we already know that the
   92018 ** ORDER BY term is not an integer index into the result set.  That
   92019 ** case is handled by the calling routine.
   92020 **
   92021 ** Attempt to match pE against result set columns in the left-most
   92022 ** SELECT statement.  Return the index i of the matching column,
   92023 ** as an indication to the caller that it should sort by the i-th column.
   92024 ** The left-most column is 1.  In other words, the value returned is the
   92025 ** same integer value that would be used in the SQL statement to indicate
   92026 ** the column.
   92027 **
   92028 ** If there is no match, return 0.  Return -1 if an error occurs.
   92029 */
   92030 static int resolveOrderByTermToExprList(
   92031   Parse *pParse,     /* Parsing context for error messages */
   92032   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
   92033   Expr *pE           /* The specific ORDER BY term */
   92034 ){
   92035   int i;             /* Loop counter */
   92036   ExprList *pEList;  /* The columns of the result set */
   92037   NameContext nc;    /* Name context for resolving pE */
   92038   sqlite3 *db;       /* Database connection */
   92039   int rc;            /* Return code from subprocedures */
   92040   u8 savedSuppErr;   /* Saved value of db->suppressErr */
   92041 
   92042   assert( sqlite3ExprIsInteger(pE, &i)==0 );
   92043   pEList = pSelect->pEList;
   92044 
   92045   /* Resolve all names in the ORDER BY term expression
   92046   */
   92047   memset(&nc, 0, sizeof(nc));
   92048   nc.pParse = pParse;
   92049   nc.pSrcList = pSelect->pSrc;
   92050   nc.pEList = pEList;
   92051   nc.ncFlags = NC_AllowAgg;
   92052   nc.nErr = 0;
   92053   db = pParse->db;
   92054   savedSuppErr = db->suppressErr;
   92055   db->suppressErr = 1;
   92056   rc = sqlite3ResolveExprNames(&nc, pE);
   92057   db->suppressErr = savedSuppErr;
   92058   if( rc ) return 0;
   92059 
   92060   /* Try to match the ORDER BY expression against an expression
   92061   ** in the result set.  Return an 1-based index of the matching
   92062   ** result-set entry.
   92063   */
   92064   for(i=0; i<pEList->nExpr; i++){
   92065     if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
   92066       return i+1;
   92067     }
   92068   }
   92069 
   92070   /* If no match, return 0. */
   92071   return 0;
   92072 }
   92073 
   92074 /*
   92075 ** Generate an ORDER BY or GROUP BY term out-of-range error.
   92076 */
   92077 static void resolveOutOfRangeError(
   92078   Parse *pParse,         /* The error context into which to write the error */
   92079   const char *zType,     /* "ORDER" or "GROUP" */
   92080   int i,                 /* The index (1-based) of the term out of range */
   92081   int mx                 /* Largest permissible value of i */
   92082 ){
   92083   sqlite3ErrorMsg(pParse,
   92084     "%r %s BY term out of range - should be "
   92085     "between 1 and %d", i, zType, mx);
   92086 }
   92087 
   92088 /*
   92089 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
   92090 ** each term of the ORDER BY clause is a constant integer between 1
   92091 ** and N where N is the number of columns in the compound SELECT.
   92092 **
   92093 ** ORDER BY terms that are already an integer between 1 and N are
   92094 ** unmodified.  ORDER BY terms that are integers outside the range of
   92095 ** 1 through N generate an error.  ORDER BY terms that are expressions
   92096 ** are matched against result set expressions of compound SELECT
   92097 ** beginning with the left-most SELECT and working toward the right.
   92098 ** At the first match, the ORDER BY expression is transformed into
   92099 ** the integer column number.
   92100 **
   92101 ** Return the number of errors seen.
   92102 */
   92103 static int resolveCompoundOrderBy(
   92104   Parse *pParse,        /* Parsing context.  Leave error messages here */
   92105   Select *pSelect       /* The SELECT statement containing the ORDER BY */
   92106 ){
   92107   int i;
   92108   ExprList *pOrderBy;
   92109   ExprList *pEList;
   92110   sqlite3 *db;
   92111   int moreToDo = 1;
   92112 
   92113   pOrderBy = pSelect->pOrderBy;
   92114   if( pOrderBy==0 ) return 0;
   92115   db = pParse->db;
   92116   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   92117     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
   92118     return 1;
   92119   }
   92120   for(i=0; i<pOrderBy->nExpr; i++){
   92121     pOrderBy->a[i].done = 0;
   92122   }
   92123   pSelect->pNext = 0;
   92124   while( pSelect->pPrior ){
   92125     pSelect->pPrior->pNext = pSelect;
   92126     pSelect = pSelect->pPrior;
   92127   }
   92128   while( pSelect && moreToDo ){
   92129     struct ExprList_item *pItem;
   92130     moreToDo = 0;
   92131     pEList = pSelect->pEList;
   92132     assert( pEList!=0 );
   92133     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   92134       int iCol = -1;
   92135       Expr *pE, *pDup;
   92136       if( pItem->done ) continue;
   92137       pE = sqlite3ExprSkipCollate(pItem->pExpr);
   92138       if( sqlite3ExprIsInteger(pE, &iCol) ){
   92139         if( iCol<=0 || iCol>pEList->nExpr ){
   92140           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
   92141           return 1;
   92142         }
   92143       }else{
   92144         iCol = resolveAsName(pParse, pEList, pE);
   92145         if( iCol==0 ){
   92146           pDup = sqlite3ExprDup(db, pE, 0);
   92147           if( !db->mallocFailed ){
   92148             assert(pDup);
   92149             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
   92150           }
   92151           sqlite3ExprDelete(db, pDup);
   92152         }
   92153       }
   92154       if( iCol>0 ){
   92155         /* Convert the ORDER BY term into an integer column number iCol,
   92156         ** taking care to preserve the COLLATE clause if it exists */
   92157         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   92158         if( pNew==0 ) return 1;
   92159         pNew->flags |= EP_IntValue;
   92160         pNew->u.iValue = iCol;
   92161         if( pItem->pExpr==pE ){
   92162           pItem->pExpr = pNew;
   92163         }else{
   92164           Expr *pParent = pItem->pExpr;
   92165           assert( pParent->op==TK_COLLATE );
   92166           while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
   92167           assert( pParent->pLeft==pE );
   92168           pParent->pLeft = pNew;
   92169         }
   92170         sqlite3ExprDelete(db, pE);
   92171         pItem->u.x.iOrderByCol = (u16)iCol;
   92172         pItem->done = 1;
   92173       }else{
   92174         moreToDo = 1;
   92175       }
   92176     }
   92177     pSelect = pSelect->pNext;
   92178   }
   92179   for(i=0; i<pOrderBy->nExpr; i++){
   92180     if( pOrderBy->a[i].done==0 ){
   92181       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
   92182             "column in the result set", i+1);
   92183       return 1;
   92184     }
   92185   }
   92186   return 0;
   92187 }
   92188 
   92189 /*
   92190 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   92191 ** the SELECT statement pSelect.  If any term is reference to a
   92192 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
   92193 ** field) then convert that term into a copy of the corresponding result set
   92194 ** column.
   92195 **
   92196 ** If any errors are detected, add an error message to pParse and
   92197 ** return non-zero.  Return zero if no errors are seen.
   92198 */
   92199 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   92200   Parse *pParse,        /* Parsing context.  Leave error messages here */
   92201   Select *pSelect,      /* The SELECT statement containing the clause */
   92202   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
   92203   const char *zType     /* "ORDER" or "GROUP" */
   92204 ){
   92205   int i;
   92206   sqlite3 *db = pParse->db;
   92207   ExprList *pEList;
   92208   struct ExprList_item *pItem;
   92209 
   92210   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
   92211   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   92212     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   92213     return 1;
   92214   }
   92215   pEList = pSelect->pEList;
   92216   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   92217   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   92218     if( pItem->u.x.iOrderByCol ){
   92219       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
   92220         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   92221         return 1;
   92222       }
   92223       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
   92224                    zType,0);
   92225     }
   92226   }
   92227   return 0;
   92228 }
   92229 
   92230 /*
   92231 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
   92232 ** The Name context of the SELECT statement is pNC.  zType is either
   92233 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
   92234 **
   92235 ** This routine resolves each term of the clause into an expression.
   92236 ** If the order-by term is an integer I between 1 and N (where N is the
   92237 ** number of columns in the result set of the SELECT) then the expression
   92238 ** in the resolution is a copy of the I-th result-set expression.  If
   92239 ** the order-by term is an identifier that corresponds to the AS-name of
   92240 ** a result-set expression, then the term resolves to a copy of the
   92241 ** result-set expression.  Otherwise, the expression is resolved in
   92242 ** the usual way - using sqlite3ResolveExprNames().
   92243 **
   92244 ** This routine returns the number of errors.  If errors occur, then
   92245 ** an appropriate error message might be left in pParse.  (OOM errors
   92246 ** excepted.)
   92247 */
   92248 static int resolveOrderGroupBy(
   92249   NameContext *pNC,     /* The name context of the SELECT statement */
   92250   Select *pSelect,      /* The SELECT statement holding pOrderBy */
   92251   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
   92252   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
   92253 ){
   92254   int i, j;                      /* Loop counters */
   92255   int iCol;                      /* Column number */
   92256   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
   92257   Parse *pParse;                 /* Parsing context */
   92258   int nResult;                   /* Number of terms in the result set */
   92259 
   92260   if( pOrderBy==0 ) return 0;
   92261   nResult = pSelect->pEList->nExpr;
   92262   pParse = pNC->pParse;
   92263   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   92264     Expr *pE = pItem->pExpr;
   92265     Expr *pE2 = sqlite3ExprSkipCollate(pE);
   92266     if( zType[0]!='G' ){
   92267       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
   92268       if( iCol>0 ){
   92269         /* If an AS-name match is found, mark this ORDER BY column as being
   92270         ** a copy of the iCol-th result-set column.  The subsequent call to
   92271         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   92272         ** copy of the iCol-th result-set expression. */
   92273         pItem->u.x.iOrderByCol = (u16)iCol;
   92274         continue;
   92275       }
   92276     }
   92277     if( sqlite3ExprIsInteger(pE2, &iCol) ){
   92278       /* The ORDER BY term is an integer constant.  Again, set the column
   92279       ** number so that sqlite3ResolveOrderGroupBy() will convert the
   92280       ** order-by term to a copy of the result-set expression */
   92281       if( iCol<1 || iCol>0xffff ){
   92282         resolveOutOfRangeError(pParse, zType, i+1, nResult);
   92283         return 1;
   92284       }
   92285       pItem->u.x.iOrderByCol = (u16)iCol;
   92286       continue;
   92287     }
   92288 
   92289     /* Otherwise, treat the ORDER BY term as an ordinary expression */
   92290     pItem->u.x.iOrderByCol = 0;
   92291     if( sqlite3ResolveExprNames(pNC, pE) ){
   92292       return 1;
   92293     }
   92294     for(j=0; j<pSelect->pEList->nExpr; j++){
   92295       if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
   92296         pItem->u.x.iOrderByCol = j+1;
   92297       }
   92298     }
   92299   }
   92300   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   92301 }
   92302 
   92303 /*
   92304 ** Resolve names in the SELECT statement p and all of its descendants.
   92305 */
   92306 static int resolveSelectStep(Walker *pWalker, Select *p){
   92307   NameContext *pOuterNC;  /* Context that contains this SELECT */
   92308   NameContext sNC;        /* Name context of this SELECT */
   92309   int isCompound;         /* True if p is a compound select */
   92310   int nCompound;          /* Number of compound terms processed so far */
   92311   Parse *pParse;          /* Parsing context */
   92312   int i;                  /* Loop counter */
   92313   ExprList *pGroupBy;     /* The GROUP BY clause */
   92314   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   92315   sqlite3 *db;            /* Database connection */
   92316 
   92317 
   92318   assert( p!=0 );
   92319   if( p->selFlags & SF_Resolved ){
   92320     return WRC_Prune;
   92321   }
   92322   pOuterNC = pWalker->u.pNC;
   92323   pParse = pWalker->pParse;
   92324   db = pParse->db;
   92325 
   92326   /* Normally sqlite3SelectExpand() will be called first and will have
   92327   ** already expanded this SELECT.  However, if this is a subquery within
   92328   ** an expression, sqlite3ResolveExprNames() will be called without a
   92329   ** prior call to sqlite3SelectExpand().  When that happens, let
   92330   ** sqlite3SelectPrep() do all of the processing for this SELECT.
   92331   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
   92332   ** this routine in the correct order.
   92333   */
   92334   if( (p->selFlags & SF_Expanded)==0 ){
   92335     sqlite3SelectPrep(pParse, p, pOuterNC);
   92336     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
   92337   }
   92338 
   92339   isCompound = p->pPrior!=0;
   92340   nCompound = 0;
   92341   pLeftmost = p;
   92342   while( p ){
   92343     assert( (p->selFlags & SF_Expanded)!=0 );
   92344     assert( (p->selFlags & SF_Resolved)==0 );
   92345     p->selFlags |= SF_Resolved;
   92346 
   92347     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
   92348     ** are not allowed to refer to any names, so pass an empty NameContext.
   92349     */
   92350     memset(&sNC, 0, sizeof(sNC));
   92351     sNC.pParse = pParse;
   92352     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
   92353       return WRC_Abort;
   92354     }
   92355 
   92356     /* If the SF_Converted flags is set, then this Select object was
   92357     ** was created by the convertCompoundSelectToSubquery() function.
   92358     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
   92359     ** as if it were part of the sub-query, not the parent. This block
   92360     ** moves the pOrderBy down to the sub-query. It will be moved back
   92361     ** after the names have been resolved.  */
   92362     if( p->selFlags & SF_Converted ){
   92363       Select *pSub = p->pSrc->a[0].pSelect;
   92364       assert( p->pSrc->nSrc==1 && p->pOrderBy );
   92365       assert( pSub->pPrior && pSub->pOrderBy==0 );
   92366       pSub->pOrderBy = p->pOrderBy;
   92367       p->pOrderBy = 0;
   92368     }
   92369 
   92370     /* Recursively resolve names in all subqueries
   92371     */
   92372     for(i=0; i<p->pSrc->nSrc; i++){
   92373       struct SrcList_item *pItem = &p->pSrc->a[i];
   92374       if( pItem->pSelect ){
   92375         NameContext *pNC;         /* Used to iterate name contexts */
   92376         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
   92377         const char *zSavedContext = pParse->zAuthContext;
   92378 
   92379         /* Count the total number of references to pOuterNC and all of its
   92380         ** parent contexts. After resolving references to expressions in
   92381         ** pItem->pSelect, check if this value has changed. If so, then
   92382         ** SELECT statement pItem->pSelect must be correlated. Set the
   92383         ** pItem->fg.isCorrelated flag if this is the case. */
   92384         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
   92385 
   92386         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
   92387         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
   92388         pParse->zAuthContext = zSavedContext;
   92389         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
   92390 
   92391         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
   92392         assert( pItem->fg.isCorrelated==0 && nRef<=0 );
   92393         pItem->fg.isCorrelated = (nRef!=0);
   92394       }
   92395     }
   92396 
   92397     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
   92398     ** resolve the result-set expression list.
   92399     */
   92400     sNC.ncFlags = NC_AllowAgg;
   92401     sNC.pSrcList = p->pSrc;
   92402     sNC.pNext = pOuterNC;
   92403 
   92404     /* Resolve names in the result set. */
   92405     if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
   92406 
   92407     /* If there are no aggregate functions in the result-set, and no GROUP BY
   92408     ** expression, do not allow aggregates in any of the other expressions.
   92409     */
   92410     assert( (p->selFlags & SF_Aggregate)==0 );
   92411     pGroupBy = p->pGroupBy;
   92412     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
   92413       assert( NC_MinMaxAgg==SF_MinMaxAgg );
   92414       p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
   92415     }else{
   92416       sNC.ncFlags &= ~NC_AllowAgg;
   92417     }
   92418 
   92419     /* If a HAVING clause is present, then there must be a GROUP BY clause.
   92420     */
   92421     if( p->pHaving && !pGroupBy ){
   92422       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
   92423       return WRC_Abort;
   92424     }
   92425 
   92426     /* Add the output column list to the name-context before parsing the
   92427     ** other expressions in the SELECT statement. This is so that
   92428     ** expressions in the WHERE clause (etc.) can refer to expressions by
   92429     ** aliases in the result set.
   92430     **
   92431     ** Minor point: If this is the case, then the expression will be
   92432     ** re-evaluated for each reference to it.
   92433     */
   92434     sNC.pEList = p->pEList;
   92435     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
   92436     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
   92437 
   92438     /* Resolve names in table-valued-function arguments */
   92439     for(i=0; i<p->pSrc->nSrc; i++){
   92440       struct SrcList_item *pItem = &p->pSrc->a[i];
   92441       if( pItem->fg.isTabFunc
   92442        && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
   92443       ){
   92444         return WRC_Abort;
   92445       }
   92446     }
   92447 
   92448     /* The ORDER BY and GROUP BY clauses may not refer to terms in
   92449     ** outer queries
   92450     */
   92451     sNC.pNext = 0;
   92452     sNC.ncFlags |= NC_AllowAgg;
   92453 
   92454     /* If this is a converted compound query, move the ORDER BY clause from
   92455     ** the sub-query back to the parent query. At this point each term
   92456     ** within the ORDER BY clause has been transformed to an integer value.
   92457     ** These integers will be replaced by copies of the corresponding result
   92458     ** set expressions by the call to resolveOrderGroupBy() below.  */
   92459     if( p->selFlags & SF_Converted ){
   92460       Select *pSub = p->pSrc->a[0].pSelect;
   92461       p->pOrderBy = pSub->pOrderBy;
   92462       pSub->pOrderBy = 0;
   92463     }
   92464 
   92465     /* Process the ORDER BY clause for singleton SELECT statements.
   92466     ** The ORDER BY clause for compounds SELECT statements is handled
   92467     ** below, after all of the result-sets for all of the elements of
   92468     ** the compound have been resolved.
   92469     **
   92470     ** If there is an ORDER BY clause on a term of a compound-select other
   92471     ** than the right-most term, then that is a syntax error.  But the error
   92472     ** is not detected until much later, and so we need to go ahead and
   92473     ** resolve those symbols on the incorrect ORDER BY for consistency.
   92474     */
   92475     if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
   92476      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
   92477     ){
   92478       return WRC_Abort;
   92479     }
   92480     if( db->mallocFailed ){
   92481       return WRC_Abort;
   92482     }
   92483 
   92484     /* Resolve the GROUP BY clause.  At the same time, make sure
   92485     ** the GROUP BY clause does not contain aggregate functions.
   92486     */
   92487     if( pGroupBy ){
   92488       struct ExprList_item *pItem;
   92489 
   92490       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
   92491         return WRC_Abort;
   92492       }
   92493       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
   92494         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
   92495           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
   92496               "the GROUP BY clause");
   92497           return WRC_Abort;
   92498         }
   92499       }
   92500     }
   92501 
   92502     /* If this is part of a compound SELECT, check that it has the right
   92503     ** number of expressions in the select list. */
   92504     if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
   92505       sqlite3SelectWrongNumTermsError(pParse, p->pNext);
   92506       return WRC_Abort;
   92507     }
   92508 
   92509     /* Advance to the next term of the compound
   92510     */
   92511     p = p->pPrior;
   92512     nCompound++;
   92513   }
   92514 
   92515   /* Resolve the ORDER BY on a compound SELECT after all terms of
   92516   ** the compound have been resolved.
   92517   */
   92518   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
   92519     return WRC_Abort;
   92520   }
   92521 
   92522   return WRC_Prune;
   92523 }
   92524 
   92525 /*
   92526 ** This routine walks an expression tree and resolves references to
   92527 ** table columns and result-set columns.  At the same time, do error
   92528 ** checking on function usage and set a flag if any aggregate functions
   92529 ** are seen.
   92530 **
   92531 ** To resolve table columns references we look for nodes (or subtrees) of the
   92532 ** form X.Y.Z or Y.Z or just Z where
   92533 **
   92534 **      X:   The name of a database.  Ex:  "main" or "temp" or
   92535 **           the symbolic name assigned to an ATTACH-ed database.
   92536 **
   92537 **      Y:   The name of a table in a FROM clause.  Or in a trigger
   92538 **           one of the special names "old" or "new".
   92539 **
   92540 **      Z:   The name of a column in table Y.
   92541 **
   92542 ** The node at the root of the subtree is modified as follows:
   92543 **
   92544 **    Expr.op        Changed to TK_COLUMN
   92545 **    Expr.pTab      Points to the Table object for X.Y
   92546 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
   92547 **    Expr.iTable    The VDBE cursor number for X.Y
   92548 **
   92549 **
   92550 ** To resolve result-set references, look for expression nodes of the
   92551 ** form Z (with no X and Y prefix) where the Z matches the right-hand
   92552 ** size of an AS clause in the result-set of a SELECT.  The Z expression
   92553 ** is replaced by a copy of the left-hand side of the result-set expression.
   92554 ** Table-name and function resolution occurs on the substituted expression
   92555 ** tree.  For example, in:
   92556 **
   92557 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
   92558 **
   92559 ** The "x" term of the order by is replaced by "a+b" to render:
   92560 **
   92561 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
   92562 **
   92563 ** Function calls are checked to make sure that the function is
   92564 ** defined and that the correct number of arguments are specified.
   92565 ** If the function is an aggregate function, then the NC_HasAgg flag is
   92566 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
   92567 ** If an expression contains aggregate functions then the EP_Agg
   92568 ** property on the expression is set.
   92569 **
   92570 ** An error message is left in pParse if anything is amiss.  The number
   92571 ** if errors is returned.
   92572 */
   92573 SQLITE_PRIVATE int sqlite3ResolveExprNames(
   92574   NameContext *pNC,       /* Namespace to resolve expressions in. */
   92575   Expr *pExpr             /* The expression to be analyzed. */
   92576 ){
   92577   u16 savedHasAgg;
   92578   Walker w;
   92579 
   92580   if( pExpr==0 ) return SQLITE_OK;
   92581   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
   92582   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
   92583   w.pParse = pNC->pParse;
   92584   w.xExprCallback = resolveExprStep;
   92585   w.xSelectCallback = resolveSelectStep;
   92586   w.xSelectCallback2 = 0;
   92587   w.u.pNC = pNC;
   92588 #if SQLITE_MAX_EXPR_DEPTH>0
   92589   w.pParse->nHeight += pExpr->nHeight;
   92590   if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
   92591     return SQLITE_ERROR;
   92592   }
   92593 #endif
   92594   sqlite3WalkExpr(&w, pExpr);
   92595 #if SQLITE_MAX_EXPR_DEPTH>0
   92596   w.pParse->nHeight -= pExpr->nHeight;
   92597 #endif
   92598   if( pNC->ncFlags & NC_HasAgg ){
   92599     ExprSetProperty(pExpr, EP_Agg);
   92600   }
   92601   pNC->ncFlags |= savedHasAgg;
   92602   return pNC->nErr>0 || w.pParse->nErr>0;
   92603 }
   92604 
   92605 /*
   92606 ** Resolve all names for all expression in an expression list.  This is
   92607 ** just like sqlite3ResolveExprNames() except that it works for an expression
   92608 ** list rather than a single expression.
   92609 */
   92610 SQLITE_PRIVATE int sqlite3ResolveExprListNames(
   92611   NameContext *pNC,       /* Namespace to resolve expressions in. */
   92612   ExprList *pList         /* The expression list to be analyzed. */
   92613 ){
   92614   int i;
   92615   if( pList ){
   92616     for(i=0; i<pList->nExpr; i++){
   92617       if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
   92618     }
   92619   }
   92620   return WRC_Continue;
   92621 }
   92622 
   92623 /*
   92624 ** Resolve all names in all expressions of a SELECT and in all
   92625 ** decendents of the SELECT, including compounds off of p->pPrior,
   92626 ** subqueries in expressions, and subqueries used as FROM clause
   92627 ** terms.
   92628 **
   92629 ** See sqlite3ResolveExprNames() for a description of the kinds of
   92630 ** transformations that occur.
   92631 **
   92632 ** All SELECT statements should have been expanded using
   92633 ** sqlite3SelectExpand() prior to invoking this routine.
   92634 */
   92635 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
   92636   Parse *pParse,         /* The parser context */
   92637   Select *p,             /* The SELECT statement being coded. */
   92638   NameContext *pOuterNC  /* Name context for parent SELECT statement */
   92639 ){
   92640   Walker w;
   92641 
   92642   assert( p!=0 );
   92643   w.xExprCallback = resolveExprStep;
   92644   w.xSelectCallback = resolveSelectStep;
   92645   w.xSelectCallback2 = 0;
   92646   w.pParse = pParse;
   92647   w.u.pNC = pOuterNC;
   92648   sqlite3WalkSelect(&w, p);
   92649 }
   92650 
   92651 /*
   92652 ** Resolve names in expressions that can only reference a single table:
   92653 **
   92654 **    *   CHECK constraints
   92655 **    *   WHERE clauses on partial indices
   92656 **
   92657 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
   92658 ** is set to -1 and the Expr.iColumn value is set to the column number.
   92659 **
   92660 ** Any errors cause an error message to be set in pParse.
   92661 */
   92662 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
   92663   Parse *pParse,      /* Parsing context */
   92664   Table *pTab,        /* The table being referenced */
   92665   int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
   92666   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
   92667   ExprList *pList     /* Expression list to resolve.  May be NUL. */
   92668 ){
   92669   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   92670   NameContext sNC;                /* Name context for pParse->pNewTable */
   92671 
   92672   assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
   92673   memset(&sNC, 0, sizeof(sNC));
   92674   memset(&sSrc, 0, sizeof(sSrc));
   92675   sSrc.nSrc = 1;
   92676   sSrc.a[0].zName = pTab->zName;
   92677   sSrc.a[0].pTab = pTab;
   92678   sSrc.a[0].iCursor = -1;
   92679   sNC.pParse = pParse;
   92680   sNC.pSrcList = &sSrc;
   92681   sNC.ncFlags = type;
   92682   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
   92683   if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
   92684 }
   92685 
   92686 /************** End of resolve.c *********************************************/
   92687 /************** Begin file expr.c ********************************************/
   92688 /*
   92689 ** 2001 September 15
   92690 **
   92691 ** The author disclaims copyright to this source code.  In place of
   92692 ** a legal notice, here is a blessing:
   92693 **
   92694 **    May you do good and not evil.
   92695 **    May you find forgiveness for yourself and forgive others.
   92696 **    May you share freely, never taking more than you give.
   92697 **
   92698 *************************************************************************
   92699 ** This file contains routines used for analyzing expressions and
   92700 ** for generating VDBE code that evaluates expressions in SQLite.
   92701 */
   92702 /* #include "sqliteInt.h" */
   92703 
   92704 /* Forward declarations */
   92705 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
   92706 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
   92707 
   92708 /*
   92709 ** Return the affinity character for a single column of a table.
   92710 */
   92711 SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
   92712   assert( iCol<pTab->nCol );
   92713   return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
   92714 }
   92715 
   92716 /*
   92717 ** Return the 'affinity' of the expression pExpr if any.
   92718 **
   92719 ** If pExpr is a column, a reference to a column via an 'AS' alias,
   92720 ** or a sub-select with a column as the return value, then the
   92721 ** affinity of that column is returned. Otherwise, 0x00 is returned,
   92722 ** indicating no affinity for the expression.
   92723 **
   92724 ** i.e. the WHERE clause expressions in the following statements all
   92725 ** have an affinity:
   92726 **
   92727 ** CREATE TABLE t1(a);
   92728 ** SELECT * FROM t1 WHERE a;
   92729 ** SELECT a AS b FROM t1 WHERE b;
   92730 ** SELECT * FROM t1 WHERE (select a from t1);
   92731 */
   92732 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
   92733   int op;
   92734   pExpr = sqlite3ExprSkipCollate(pExpr);
   92735   if( pExpr->flags & EP_Generic ) return 0;
   92736   op = pExpr->op;
   92737   if( op==TK_SELECT ){
   92738     assert( pExpr->flags&EP_xIsSelect );
   92739     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   92740   }
   92741   if( op==TK_REGISTER ) op = pExpr->op2;
   92742 #ifndef SQLITE_OMIT_CAST
   92743   if( op==TK_CAST ){
   92744     assert( !ExprHasProperty(pExpr, EP_IntValue) );
   92745     return sqlite3AffinityType(pExpr->u.zToken, 0);
   92746   }
   92747 #endif
   92748   if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
   92749     return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
   92750   }
   92751   if( op==TK_SELECT_COLUMN ){
   92752     assert( pExpr->pLeft->flags&EP_xIsSelect );
   92753     return sqlite3ExprAffinity(
   92754         pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
   92755     );
   92756   }
   92757   return pExpr->affinity;
   92758 }
   92759 
   92760 /*
   92761 ** Set the collating sequence for expression pExpr to be the collating
   92762 ** sequence named by pToken.   Return a pointer to a new Expr node that
   92763 ** implements the COLLATE operator.
   92764 **
   92765 ** If a memory allocation error occurs, that fact is recorded in pParse->db
   92766 ** and the pExpr parameter is returned unchanged.
   92767 */
   92768 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
   92769   Parse *pParse,           /* Parsing context */
   92770   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
   92771   const Token *pCollName,  /* Name of collating sequence */
   92772   int dequote              /* True to dequote pCollName */
   92773 ){
   92774   if( pCollName->n>0 ){
   92775     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
   92776     if( pNew ){
   92777       pNew->pLeft = pExpr;
   92778       pNew->flags |= EP_Collate|EP_Skip;
   92779       pExpr = pNew;
   92780     }
   92781   }
   92782   return pExpr;
   92783 }
   92784 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
   92785   Token s;
   92786   assert( zC!=0 );
   92787   sqlite3TokenInit(&s, (char*)zC);
   92788   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
   92789 }
   92790 
   92791 /*
   92792 ** Skip over any TK_COLLATE operators and any unlikely()
   92793 ** or likelihood() function at the root of an expression.
   92794 */
   92795 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
   92796   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
   92797     if( ExprHasProperty(pExpr, EP_Unlikely) ){
   92798       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   92799       assert( pExpr->x.pList->nExpr>0 );
   92800       assert( pExpr->op==TK_FUNCTION );
   92801       pExpr = pExpr->x.pList->a[0].pExpr;
   92802     }else{
   92803       assert( pExpr->op==TK_COLLATE );
   92804       pExpr = pExpr->pLeft;
   92805     }
   92806   }
   92807   return pExpr;
   92808 }
   92809 
   92810 /*
   92811 ** Return the collation sequence for the expression pExpr. If
   92812 ** there is no defined collating sequence, return NULL.
   92813 **
   92814 ** See also: sqlite3ExprNNCollSeq()
   92815 **
   92816 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
   92817 ** default collation if pExpr has no defined collation.
   92818 **
   92819 ** The collating sequence might be determined by a COLLATE operator
   92820 ** or by the presence of a column with a defined collating sequence.
   92821 ** COLLATE operators take first precedence.  Left operands take
   92822 ** precedence over right operands.
   92823 */
   92824 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
   92825   sqlite3 *db = pParse->db;
   92826   CollSeq *pColl = 0;
   92827   Expr *p = pExpr;
   92828   while( p ){
   92829     int op = p->op;
   92830     if( p->flags & EP_Generic ) break;
   92831     if( op==TK_CAST || op==TK_UPLUS ){
   92832       p = p->pLeft;
   92833       continue;
   92834     }
   92835     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
   92836       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
   92837       break;
   92838     }
   92839     if( (op==TK_AGG_COLUMN || op==TK_COLUMN
   92840           || op==TK_REGISTER || op==TK_TRIGGER)
   92841      && p->pTab!=0
   92842     ){
   92843       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
   92844       ** a TK_COLUMN but was previously evaluated and cached in a register */
   92845       int j = p->iColumn;
   92846       if( j>=0 ){
   92847         const char *zColl = p->pTab->aCol[j].zColl;
   92848         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   92849       }
   92850       break;
   92851     }
   92852     if( p->flags & EP_Collate ){
   92853       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
   92854         p = p->pLeft;
   92855       }else{
   92856         Expr *pNext  = p->pRight;
   92857         /* The Expr.x union is never used at the same time as Expr.pRight */
   92858         assert( p->x.pList==0 || p->pRight==0 );
   92859         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
   92860         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
   92861         ** least one EP_Collate. Thus the following two ALWAYS. */
   92862         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
   92863           int i;
   92864           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
   92865             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
   92866               pNext = p->x.pList->a[i].pExpr;
   92867               break;
   92868             }
   92869           }
   92870         }
   92871         p = pNext;
   92872       }
   92873     }else{
   92874       break;
   92875     }
   92876   }
   92877   if( sqlite3CheckCollSeq(pParse, pColl) ){
   92878     pColl = 0;
   92879   }
   92880   return pColl;
   92881 }
   92882 
   92883 /*
   92884 ** Return the collation sequence for the expression pExpr. If
   92885 ** there is no defined collating sequence, return a pointer to the
   92886 ** defautl collation sequence.
   92887 **
   92888 ** See also: sqlite3ExprCollSeq()
   92889 **
   92890 ** The sqlite3ExprCollSeq() routine works the same except that it
   92891 ** returns NULL if there is no defined collation.
   92892 */
   92893 SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
   92894   CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
   92895   if( p==0 ) p = pParse->db->pDfltColl;
   92896   assert( p!=0 );
   92897   return p;
   92898 }
   92899 
   92900 /*
   92901 ** Return TRUE if the two expressions have equivalent collating sequences.
   92902 */
   92903 SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
   92904   CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
   92905   CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
   92906   return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
   92907 }
   92908 
   92909 /*
   92910 ** pExpr is an operand of a comparison operator.  aff2 is the
   92911 ** type affinity of the other operand.  This routine returns the
   92912 ** type affinity that should be used for the comparison operator.
   92913 */
   92914 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
   92915   char aff1 = sqlite3ExprAffinity(pExpr);
   92916   if( aff1 && aff2 ){
   92917     /* Both sides of the comparison are columns. If one has numeric
   92918     ** affinity, use that. Otherwise use no affinity.
   92919     */
   92920     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
   92921       return SQLITE_AFF_NUMERIC;
   92922     }else{
   92923       return SQLITE_AFF_BLOB;
   92924     }
   92925   }else if( !aff1 && !aff2 ){
   92926     /* Neither side of the comparison is a column.  Compare the
   92927     ** results directly.
   92928     */
   92929     return SQLITE_AFF_BLOB;
   92930   }else{
   92931     /* One side is a column, the other is not. Use the columns affinity. */
   92932     assert( aff1==0 || aff2==0 );
   92933     return (aff1 + aff2);
   92934   }
   92935 }
   92936 
   92937 /*
   92938 ** pExpr is a comparison operator.  Return the type affinity that should
   92939 ** be applied to both operands prior to doing the comparison.
   92940 */
   92941 static char comparisonAffinity(Expr *pExpr){
   92942   char aff;
   92943   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
   92944           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
   92945           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
   92946   assert( pExpr->pLeft );
   92947   aff = sqlite3ExprAffinity(pExpr->pLeft);
   92948   if( pExpr->pRight ){
   92949     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
   92950   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   92951     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   92952   }else if( aff==0 ){
   92953     aff = SQLITE_AFF_BLOB;
   92954   }
   92955   return aff;
   92956 }
   92957 
   92958 /*
   92959 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   92960 ** idx_affinity is the affinity of an indexed column. Return true
   92961 ** if the index with affinity idx_affinity may be used to implement
   92962 ** the comparison in pExpr.
   92963 */
   92964 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   92965   char aff = comparisonAffinity(pExpr);
   92966   switch( aff ){
   92967     case SQLITE_AFF_BLOB:
   92968       return 1;
   92969     case SQLITE_AFF_TEXT:
   92970       return idx_affinity==SQLITE_AFF_TEXT;
   92971     default:
   92972       return sqlite3IsNumericAffinity(idx_affinity);
   92973   }
   92974 }
   92975 
   92976 /*
   92977 ** Return the P5 value that should be used for a binary comparison
   92978 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   92979 */
   92980 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
   92981   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   92982   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   92983   return aff;
   92984 }
   92985 
   92986 /*
   92987 ** Return a pointer to the collation sequence that should be used by
   92988 ** a binary comparison operator comparing pLeft and pRight.
   92989 **
   92990 ** If the left hand expression has a collating sequence type, then it is
   92991 ** used. Otherwise the collation sequence for the right hand expression
   92992 ** is used, or the default (BINARY) if neither expression has a collating
   92993 ** type.
   92994 **
   92995 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
   92996 ** it is not considered.
   92997 */
   92998 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   92999   Parse *pParse,
   93000   Expr *pLeft,
   93001   Expr *pRight
   93002 ){
   93003   CollSeq *pColl;
   93004   assert( pLeft );
   93005   if( pLeft->flags & EP_Collate ){
   93006     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   93007   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
   93008     pColl = sqlite3ExprCollSeq(pParse, pRight);
   93009   }else{
   93010     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   93011     if( !pColl ){
   93012       pColl = sqlite3ExprCollSeq(pParse, pRight);
   93013     }
   93014   }
   93015   return pColl;
   93016 }
   93017 
   93018 /*
   93019 ** Generate code for a comparison operator.
   93020 */
   93021 static int codeCompare(
   93022   Parse *pParse,    /* The parsing (and code generating) context */
   93023   Expr *pLeft,      /* The left operand */
   93024   Expr *pRight,     /* The right operand */
   93025   int opcode,       /* The comparison opcode */
   93026   int in1, int in2, /* Register holding operands */
   93027   int dest,         /* Jump here if true.  */
   93028   int jumpIfNull    /* If true, jump if either operand is NULL */
   93029 ){
   93030   int p5;
   93031   int addr;
   93032   CollSeq *p4;
   93033 
   93034   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
   93035   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   93036   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
   93037                            (void*)p4, P4_COLLSEQ);
   93038   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
   93039   return addr;
   93040 }
   93041 
   93042 /*
   93043 ** Return true if expression pExpr is a vector, or false otherwise.
   93044 **
   93045 ** A vector is defined as any expression that results in two or more
   93046 ** columns of result.  Every TK_VECTOR node is an vector because the
   93047 ** parser will not generate a TK_VECTOR with fewer than two entries.
   93048 ** But a TK_SELECT might be either a vector or a scalar. It is only
   93049 ** considered a vector if it has two or more result columns.
   93050 */
   93051 SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
   93052   return sqlite3ExprVectorSize(pExpr)>1;
   93053 }
   93054 
   93055 /*
   93056 ** If the expression passed as the only argument is of type TK_VECTOR
   93057 ** return the number of expressions in the vector. Or, if the expression
   93058 ** is a sub-select, return the number of columns in the sub-select. For
   93059 ** any other type of expression, return 1.
   93060 */
   93061 SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
   93062   u8 op = pExpr->op;
   93063   if( op==TK_REGISTER ) op = pExpr->op2;
   93064   if( op==TK_VECTOR ){
   93065     return pExpr->x.pList->nExpr;
   93066   }else if( op==TK_SELECT ){
   93067     return pExpr->x.pSelect->pEList->nExpr;
   93068   }else{
   93069     return 1;
   93070   }
   93071 }
   93072 
   93073 /*
   93074 ** Return a pointer to a subexpression of pVector that is the i-th
   93075 ** column of the vector (numbered starting with 0).  The caller must
   93076 ** ensure that i is within range.
   93077 **
   93078 ** If pVector is really a scalar (and "scalar" here includes subqueries
   93079 ** that return a single column!) then return pVector unmodified.
   93080 **
   93081 ** pVector retains ownership of the returned subexpression.
   93082 **
   93083 ** If the vector is a (SELECT ...) then the expression returned is
   93084 ** just the expression for the i-th term of the result set, and may
   93085 ** not be ready for evaluation because the table cursor has not yet
   93086 ** been positioned.
   93087 */
   93088 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
   93089   assert( i<sqlite3ExprVectorSize(pVector) );
   93090   if( sqlite3ExprIsVector(pVector) ){
   93091     assert( pVector->op2==0 || pVector->op==TK_REGISTER );
   93092     if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
   93093       return pVector->x.pSelect->pEList->a[i].pExpr;
   93094     }else{
   93095       return pVector->x.pList->a[i].pExpr;
   93096     }
   93097   }
   93098   return pVector;
   93099 }
   93100 
   93101 /*
   93102 ** Compute and return a new Expr object which when passed to
   93103 ** sqlite3ExprCode() will generate all necessary code to compute
   93104 ** the iField-th column of the vector expression pVector.
   93105 **
   93106 ** It is ok for pVector to be a scalar (as long as iField==0).
   93107 ** In that case, this routine works like sqlite3ExprDup().
   93108 **
   93109 ** The caller owns the returned Expr object and is responsible for
   93110 ** ensuring that the returned value eventually gets freed.
   93111 **
   93112 ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
   93113 ** then the returned object will reference pVector and so pVector must remain
   93114 ** valid for the life of the returned object.  If pVector is a TK_VECTOR
   93115 ** or a scalar expression, then it can be deleted as soon as this routine
   93116 ** returns.
   93117 **
   93118 ** A trick to cause a TK_SELECT pVector to be deleted together with
   93119 ** the returned Expr object is to attach the pVector to the pRight field
   93120 ** of the returned TK_SELECT_COLUMN Expr object.
   93121 */
   93122 SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
   93123   Parse *pParse,       /* Parsing context */
   93124   Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
   93125   int iField           /* Which column of the vector to return */
   93126 ){
   93127   Expr *pRet;
   93128   if( pVector->op==TK_SELECT ){
   93129     assert( pVector->flags & EP_xIsSelect );
   93130     /* The TK_SELECT_COLUMN Expr node:
   93131     **
   93132     ** pLeft:           pVector containing TK_SELECT.  Not deleted.
   93133     ** pRight:          not used.  But recursively deleted.
   93134     ** iColumn:         Index of a column in pVector
   93135     ** iTable:          0 or the number of columns on the LHS of an assignment
   93136     ** pLeft->iTable:   First in an array of register holding result, or 0
   93137     **                  if the result is not yet computed.
   93138     **
   93139     ** sqlite3ExprDelete() specifically skips the recursive delete of
   93140     ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
   93141     ** can be attached to pRight to cause this node to take ownership of
   93142     ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
   93143     ** with the same pLeft pointer to the pVector, but only one of them
   93144     ** will own the pVector.
   93145     */
   93146     pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
   93147     if( pRet ){
   93148       pRet->iColumn = iField;
   93149       pRet->pLeft = pVector;
   93150     }
   93151     assert( pRet==0 || pRet->iTable==0 );
   93152   }else{
   93153     if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
   93154     pRet = sqlite3ExprDup(pParse->db, pVector, 0);
   93155   }
   93156   return pRet;
   93157 }
   93158 
   93159 /*
   93160 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
   93161 ** it. Return the register in which the result is stored (or, if the
   93162 ** sub-select returns more than one column, the first in an array
   93163 ** of registers in which the result is stored).
   93164 **
   93165 ** If pExpr is not a TK_SELECT expression, return 0.
   93166 */
   93167 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
   93168   int reg = 0;
   93169 #ifndef SQLITE_OMIT_SUBQUERY
   93170   if( pExpr->op==TK_SELECT ){
   93171     reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   93172   }
   93173 #endif
   93174   return reg;
   93175 }
   93176 
   93177 /*
   93178 ** Argument pVector points to a vector expression - either a TK_VECTOR
   93179 ** or TK_SELECT that returns more than one column. This function returns
   93180 ** the register number of a register that contains the value of
   93181 ** element iField of the vector.
   93182 **
   93183 ** If pVector is a TK_SELECT expression, then code for it must have
   93184 ** already been generated using the exprCodeSubselect() routine. In this
   93185 ** case parameter regSelect should be the first in an array of registers
   93186 ** containing the results of the sub-select.
   93187 **
   93188 ** If pVector is of type TK_VECTOR, then code for the requested field
   93189 ** is generated. In this case (*pRegFree) may be set to the number of
   93190 ** a temporary register to be freed by the caller before returning.
   93191 **
   93192 ** Before returning, output parameter (*ppExpr) is set to point to the
   93193 ** Expr object corresponding to element iElem of the vector.
   93194 */
   93195 static int exprVectorRegister(
   93196   Parse *pParse,                  /* Parse context */
   93197   Expr *pVector,                  /* Vector to extract element from */
   93198   int iField,                     /* Field to extract from pVector */
   93199   int regSelect,                  /* First in array of registers */
   93200   Expr **ppExpr,                  /* OUT: Expression element */
   93201   int *pRegFree                   /* OUT: Temp register to free */
   93202 ){
   93203   u8 op = pVector->op;
   93204   assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
   93205   if( op==TK_REGISTER ){
   93206     *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
   93207     return pVector->iTable+iField;
   93208   }
   93209   if( op==TK_SELECT ){
   93210     *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
   93211      return regSelect+iField;
   93212   }
   93213   *ppExpr = pVector->x.pList->a[iField].pExpr;
   93214   return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
   93215 }
   93216 
   93217 /*
   93218 ** Expression pExpr is a comparison between two vector values. Compute
   93219 ** the result of the comparison (1, 0, or NULL) and write that
   93220 ** result into register dest.
   93221 **
   93222 ** The caller must satisfy the following preconditions:
   93223 **
   93224 **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
   93225 **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
   93226 **    otherwise:                op==pExpr->op and p5==0
   93227 */
   93228 static void codeVectorCompare(
   93229   Parse *pParse,        /* Code generator context */
   93230   Expr *pExpr,          /* The comparison operation */
   93231   int dest,             /* Write results into this register */
   93232   u8 op,                /* Comparison operator */
   93233   u8 p5                 /* SQLITE_NULLEQ or zero */
   93234 ){
   93235   Vdbe *v = pParse->pVdbe;
   93236   Expr *pLeft = pExpr->pLeft;
   93237   Expr *pRight = pExpr->pRight;
   93238   int nLeft = sqlite3ExprVectorSize(pLeft);
   93239   int i;
   93240   int regLeft = 0;
   93241   int regRight = 0;
   93242   u8 opx = op;
   93243   int addrDone = sqlite3VdbeMakeLabel(v);
   93244 
   93245   if( nLeft!=sqlite3ExprVectorSize(pRight) ){
   93246     sqlite3ErrorMsg(pParse, "row value misused");
   93247     return;
   93248   }
   93249   assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
   93250        || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
   93251        || pExpr->op==TK_LT || pExpr->op==TK_GT
   93252        || pExpr->op==TK_LE || pExpr->op==TK_GE
   93253   );
   93254   assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
   93255             || (pExpr->op==TK_ISNOT && op==TK_NE) );
   93256   assert( p5==0 || pExpr->op!=op );
   93257   assert( p5==SQLITE_NULLEQ || pExpr->op==op );
   93258 
   93259   p5 |= SQLITE_STOREP2;
   93260   if( opx==TK_LE ) opx = TK_LT;
   93261   if( opx==TK_GE ) opx = TK_GT;
   93262 
   93263   regLeft = exprCodeSubselect(pParse, pLeft);
   93264   regRight = exprCodeSubselect(pParse, pRight);
   93265 
   93266   for(i=0; 1 /*Loop exits by "break"*/; i++){
   93267     int regFree1 = 0, regFree2 = 0;
   93268     Expr *pL, *pR;
   93269     int r1, r2;
   93270     assert( i>=0 && i<nLeft );
   93271     if( i>0 ) sqlite3ExprCachePush(pParse);
   93272     r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
   93273     r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
   93274     codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
   93275     testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   93276     testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   93277     testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   93278     testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   93279     testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   93280     testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   93281     sqlite3ReleaseTempReg(pParse, regFree1);
   93282     sqlite3ReleaseTempReg(pParse, regFree2);
   93283     if( i>0 ) sqlite3ExprCachePop(pParse);
   93284     if( i==nLeft-1 ){
   93285       break;
   93286     }
   93287     if( opx==TK_EQ ){
   93288       sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
   93289       p5 |= SQLITE_KEEPNULL;
   93290     }else if( opx==TK_NE ){
   93291       sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
   93292       p5 |= SQLITE_KEEPNULL;
   93293     }else{
   93294       assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
   93295       sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
   93296       VdbeCoverageIf(v, op==TK_LT);
   93297       VdbeCoverageIf(v, op==TK_GT);
   93298       VdbeCoverageIf(v, op==TK_LE);
   93299       VdbeCoverageIf(v, op==TK_GE);
   93300       if( i==nLeft-2 ) opx = op;
   93301     }
   93302   }
   93303   sqlite3VdbeResolveLabel(v, addrDone);
   93304 }
   93305 
   93306 #if SQLITE_MAX_EXPR_DEPTH>0
   93307 /*
   93308 ** Check that argument nHeight is less than or equal to the maximum
   93309 ** expression depth allowed. If it is not, leave an error message in
   93310 ** pParse.
   93311 */
   93312 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   93313   int rc = SQLITE_OK;
   93314   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   93315   if( nHeight>mxHeight ){
   93316     sqlite3ErrorMsg(pParse,
   93317        "Expression tree is too large (maximum depth %d)", mxHeight
   93318     );
   93319     rc = SQLITE_ERROR;
   93320   }
   93321   return rc;
   93322 }
   93323 
   93324 /* The following three functions, heightOfExpr(), heightOfExprList()
   93325 ** and heightOfSelect(), are used to determine the maximum height
   93326 ** of any expression tree referenced by the structure passed as the
   93327 ** first argument.
   93328 **
   93329 ** If this maximum height is greater than the current value pointed
   93330 ** to by pnHeight, the second parameter, then set *pnHeight to that
   93331 ** value.
   93332 */
   93333 static void heightOfExpr(Expr *p, int *pnHeight){
   93334   if( p ){
   93335     if( p->nHeight>*pnHeight ){
   93336       *pnHeight = p->nHeight;
   93337     }
   93338   }
   93339 }
   93340 static void heightOfExprList(ExprList *p, int *pnHeight){
   93341   if( p ){
   93342     int i;
   93343     for(i=0; i<p->nExpr; i++){
   93344       heightOfExpr(p->a[i].pExpr, pnHeight);
   93345     }
   93346   }
   93347 }
   93348 static void heightOfSelect(Select *pSelect, int *pnHeight){
   93349   Select *p;
   93350   for(p=pSelect; p; p=p->pPrior){
   93351     heightOfExpr(p->pWhere, pnHeight);
   93352     heightOfExpr(p->pHaving, pnHeight);
   93353     heightOfExpr(p->pLimit, pnHeight);
   93354     heightOfExprList(p->pEList, pnHeight);
   93355     heightOfExprList(p->pGroupBy, pnHeight);
   93356     heightOfExprList(p->pOrderBy, pnHeight);
   93357   }
   93358 }
   93359 
   93360 /*
   93361 ** Set the Expr.nHeight variable in the structure passed as an
   93362 ** argument. An expression with no children, Expr.pList or
   93363 ** Expr.pSelect member has a height of 1. Any other expression
   93364 ** has a height equal to the maximum height of any other
   93365 ** referenced Expr plus one.
   93366 **
   93367 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
   93368 ** if appropriate.
   93369 */
   93370 static void exprSetHeight(Expr *p){
   93371   int nHeight = 0;
   93372   heightOfExpr(p->pLeft, &nHeight);
   93373   heightOfExpr(p->pRight, &nHeight);
   93374   if( ExprHasProperty(p, EP_xIsSelect) ){
   93375     heightOfSelect(p->x.pSelect, &nHeight);
   93376   }else if( p->x.pList ){
   93377     heightOfExprList(p->x.pList, &nHeight);
   93378     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
   93379   }
   93380   p->nHeight = nHeight + 1;
   93381 }
   93382 
   93383 /*
   93384 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
   93385 ** the height is greater than the maximum allowed expression depth,
   93386 ** leave an error in pParse.
   93387 **
   93388 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
   93389 ** Expr.flags.
   93390 */
   93391 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
   93392   if( pParse->nErr ) return;
   93393   exprSetHeight(p);
   93394   sqlite3ExprCheckHeight(pParse, p->nHeight);
   93395 }
   93396 
   93397 /*
   93398 ** Return the maximum height of any expression tree referenced
   93399 ** by the select statement passed as an argument.
   93400 */
   93401 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
   93402   int nHeight = 0;
   93403   heightOfSelect(p, &nHeight);
   93404   return nHeight;
   93405 }
   93406 #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
   93407 /*
   93408 ** Propagate all EP_Propagate flags from the Expr.x.pList into
   93409 ** Expr.flags.
   93410 */
   93411 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
   93412   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
   93413     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
   93414   }
   93415 }
   93416 #define exprSetHeight(y)
   93417 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
   93418 
   93419 /*
   93420 ** This routine is the core allocator for Expr nodes.
   93421 **
   93422 ** Construct a new expression node and return a pointer to it.  Memory
   93423 ** for this node and for the pToken argument is a single allocation
   93424 ** obtained from sqlite3DbMalloc().  The calling function
   93425 ** is responsible for making sure the node eventually gets freed.
   93426 **
   93427 ** If dequote is true, then the token (if it exists) is dequoted.
   93428 ** If dequote is false, no dequoting is performed.  The deQuote
   93429 ** parameter is ignored if pToken is NULL or if the token does not
   93430 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
   93431 ** then the EP_DblQuoted flag is set on the expression node.
   93432 **
   93433 ** Special case:  If op==TK_INTEGER and pToken points to a string that
   93434 ** can be translated into a 32-bit integer, then the token is not
   93435 ** stored in u.zToken.  Instead, the integer values is written
   93436 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
   93437 ** is allocated to hold the integer text and the dequote flag is ignored.
   93438 */
   93439 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
   93440   sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
   93441   int op,                 /* Expression opcode */
   93442   const Token *pToken,    /* Token argument.  Might be NULL */
   93443   int dequote             /* True to dequote */
   93444 ){
   93445   Expr *pNew;
   93446   int nExtra = 0;
   93447   int iValue = 0;
   93448 
   93449   assert( db!=0 );
   93450   if( pToken ){
   93451     if( op!=TK_INTEGER || pToken->z==0
   93452           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   93453       nExtra = pToken->n+1;
   93454       assert( iValue>=0 );
   93455     }
   93456   }
   93457   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
   93458   if( pNew ){
   93459     memset(pNew, 0, sizeof(Expr));
   93460     pNew->op = (u8)op;
   93461     pNew->iAgg = -1;
   93462     if( pToken ){
   93463       if( nExtra==0 ){
   93464         pNew->flags |= EP_IntValue|EP_Leaf;
   93465         pNew->u.iValue = iValue;
   93466       }else{
   93467         pNew->u.zToken = (char*)&pNew[1];
   93468         assert( pToken->z!=0 || pToken->n==0 );
   93469         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
   93470         pNew->u.zToken[pToken->n] = 0;
   93471         if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
   93472           if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
   93473           sqlite3Dequote(pNew->u.zToken);
   93474         }
   93475       }
   93476     }
   93477 #if SQLITE_MAX_EXPR_DEPTH>0
   93478     pNew->nHeight = 1;
   93479 #endif
   93480   }
   93481   return pNew;
   93482 }
   93483 
   93484 /*
   93485 ** Allocate a new expression node from a zero-terminated token that has
   93486 ** already been dequoted.
   93487 */
   93488 SQLITE_PRIVATE Expr *sqlite3Expr(
   93489   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   93490   int op,                 /* Expression opcode */
   93491   const char *zToken      /* Token argument.  Might be NULL */
   93492 ){
   93493   Token x;
   93494   x.z = zToken;
   93495   x.n = sqlite3Strlen30(zToken);
   93496   return sqlite3ExprAlloc(db, op, &x, 0);
   93497 }
   93498 
   93499 /*
   93500 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
   93501 **
   93502 ** If pRoot==NULL that means that a memory allocation error has occurred.
   93503 ** In that case, delete the subtrees pLeft and pRight.
   93504 */
   93505 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
   93506   sqlite3 *db,
   93507   Expr *pRoot,
   93508   Expr *pLeft,
   93509   Expr *pRight
   93510 ){
   93511   if( pRoot==0 ){
   93512     assert( db->mallocFailed );
   93513     sqlite3ExprDelete(db, pLeft);
   93514     sqlite3ExprDelete(db, pRight);
   93515   }else{
   93516     if( pRight ){
   93517       pRoot->pRight = pRight;
   93518       pRoot->flags |= EP_Propagate & pRight->flags;
   93519     }
   93520     if( pLeft ){
   93521       pRoot->pLeft = pLeft;
   93522       pRoot->flags |= EP_Propagate & pLeft->flags;
   93523     }
   93524     exprSetHeight(pRoot);
   93525   }
   93526 }
   93527 
   93528 /*
   93529 ** Allocate an Expr node which joins as many as two subtrees.
   93530 **
   93531 ** One or both of the subtrees can be NULL.  Return a pointer to the new
   93532 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
   93533 ** free the subtrees and return NULL.
   93534 */
   93535 SQLITE_PRIVATE Expr *sqlite3PExpr(
   93536   Parse *pParse,          /* Parsing context */
   93537   int op,                 /* Expression opcode */
   93538   Expr *pLeft,            /* Left operand */
   93539   Expr *pRight            /* Right operand */
   93540 ){
   93541   Expr *p;
   93542   if( op==TK_AND && pParse->nErr==0 ){
   93543     /* Take advantage of short-circuit false optimization for AND */
   93544     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
   93545   }else{
   93546     p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
   93547     if( p ){
   93548       memset(p, 0, sizeof(Expr));
   93549       p->op = op & TKFLG_MASK;
   93550       p->iAgg = -1;
   93551     }
   93552     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
   93553   }
   93554   if( p ) {
   93555     sqlite3ExprCheckHeight(pParse, p->nHeight);
   93556   }
   93557   return p;
   93558 }
   93559 
   93560 /*
   93561 ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
   93562 ** do a memory allocation failure) then delete the pSelect object.
   93563 */
   93564 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
   93565   if( pExpr ){
   93566     pExpr->x.pSelect = pSelect;
   93567     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
   93568     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
   93569   }else{
   93570     assert( pParse->db->mallocFailed );
   93571     sqlite3SelectDelete(pParse->db, pSelect);
   93572   }
   93573 }
   93574 
   93575 
   93576 /*
   93577 ** If the expression is always either TRUE or FALSE (respectively),
   93578 ** then return 1.  If one cannot determine the truth value of the
   93579 ** expression at compile-time return 0.
   93580 **
   93581 ** This is an optimization.  If is OK to return 0 here even if
   93582 ** the expression really is always false or false (a false negative).
   93583 ** But it is a bug to return 1 if the expression might have different
   93584 ** boolean values in different circumstances (a false positive.)
   93585 **
   93586 ** Note that if the expression is part of conditional for a
   93587 ** LEFT JOIN, then we cannot determine at compile-time whether or not
   93588 ** is it true or false, so always return 0.
   93589 */
   93590 static int exprAlwaysTrue(Expr *p){
   93591   int v = 0;
   93592   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
   93593   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
   93594   return v!=0;
   93595 }
   93596 static int exprAlwaysFalse(Expr *p){
   93597   int v = 0;
   93598   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
   93599   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
   93600   return v==0;
   93601 }
   93602 
   93603 /*
   93604 ** Join two expressions using an AND operator.  If either expression is
   93605 ** NULL, then just return the other expression.
   93606 **
   93607 ** If one side or the other of the AND is known to be false, then instead
   93608 ** of returning an AND expression, just return a constant expression with
   93609 ** a value of false.
   93610 */
   93611 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   93612   if( pLeft==0 ){
   93613     return pRight;
   93614   }else if( pRight==0 ){
   93615     return pLeft;
   93616   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
   93617     sqlite3ExprDelete(db, pLeft);
   93618     sqlite3ExprDelete(db, pRight);
   93619     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
   93620   }else{
   93621     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
   93622     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
   93623     return pNew;
   93624   }
   93625 }
   93626 
   93627 /*
   93628 ** Construct a new expression node for a function with multiple
   93629 ** arguments.
   93630 */
   93631 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
   93632   Expr *pNew;
   93633   sqlite3 *db = pParse->db;
   93634   assert( pToken );
   93635   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
   93636   if( pNew==0 ){
   93637     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
   93638     return 0;
   93639   }
   93640   pNew->x.pList = pList;
   93641   ExprSetProperty(pNew, EP_HasFunc);
   93642   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   93643   sqlite3ExprSetHeightAndFlags(pParse, pNew);
   93644   return pNew;
   93645 }
   93646 
   93647 /*
   93648 ** Assign a variable number to an expression that encodes a wildcard
   93649 ** in the original SQL statement.
   93650 **
   93651 ** Wildcards consisting of a single "?" are assigned the next sequential
   93652 ** variable number.
   93653 **
   93654 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
   93655 ** sure "nnn" is not too big to avoid a denial of service attack when
   93656 ** the SQL statement comes from an external source.
   93657 **
   93658 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
   93659 ** as the previous instance of the same wildcard.  Or if this is the first
   93660 ** instance of the wildcard, the next sequential variable number is
   93661 ** assigned.
   93662 */
   93663 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
   93664   sqlite3 *db = pParse->db;
   93665   const char *z;
   93666   ynVar x;
   93667 
   93668   if( pExpr==0 ) return;
   93669   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
   93670   z = pExpr->u.zToken;
   93671   assert( z!=0 );
   93672   assert( z[0]!=0 );
   93673   assert( n==(u32)sqlite3Strlen30(z) );
   93674   if( z[1]==0 ){
   93675     /* Wildcard of the form "?".  Assign the next variable number */
   93676     assert( z[0]=='?' );
   93677     x = (ynVar)(++pParse->nVar);
   93678   }else{
   93679     int doAdd = 0;
   93680     if( z[0]=='?' ){
   93681       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   93682       ** use it as the variable number */
   93683       i64 i;
   93684       int bOk;
   93685       if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
   93686         i = z[1]-'0';  /* The common case of ?N for a single digit N */
   93687         bOk = 1;
   93688       }else{
   93689         bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
   93690       }
   93691       testcase( i==0 );
   93692       testcase( i==1 );
   93693       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
   93694       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
   93695       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   93696         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   93697             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
   93698         return;
   93699       }
   93700       x = (ynVar)i;
   93701       if( x>pParse->nVar ){
   93702         pParse->nVar = (int)x;
   93703         doAdd = 1;
   93704       }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
   93705         doAdd = 1;
   93706       }
   93707     }else{
   93708       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
   93709       ** number as the prior appearance of the same name, or if the name
   93710       ** has never appeared before, reuse the same variable number
   93711       */
   93712       x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
   93713       if( x==0 ){
   93714         x = (ynVar)(++pParse->nVar);
   93715         doAdd = 1;
   93716       }
   93717     }
   93718     if( doAdd ){
   93719       pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
   93720     }
   93721   }
   93722   pExpr->iColumn = x;
   93723   if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   93724     sqlite3ErrorMsg(pParse, "too many SQL variables");
   93725   }
   93726 }
   93727 
   93728 /*
   93729 ** Recursively delete an expression tree.
   93730 */
   93731 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
   93732   assert( p!=0 );
   93733   /* Sanity check: Assert that the IntValue is non-negative if it exists */
   93734   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
   93735 #ifdef SQLITE_DEBUG
   93736   if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
   93737     assert( p->pLeft==0 );
   93738     assert( p->pRight==0 );
   93739     assert( p->x.pSelect==0 );
   93740   }
   93741 #endif
   93742   if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
   93743     /* The Expr.x union is never used at the same time as Expr.pRight */
   93744     assert( p->x.pList==0 || p->pRight==0 );
   93745     if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
   93746     if( p->pRight ){
   93747       sqlite3ExprDeleteNN(db, p->pRight);
   93748     }else if( ExprHasProperty(p, EP_xIsSelect) ){
   93749       sqlite3SelectDelete(db, p->x.pSelect);
   93750     }else{
   93751       sqlite3ExprListDelete(db, p->x.pList);
   93752     }
   93753   }
   93754   if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
   93755   if( !ExprHasProperty(p, EP_Static) ){
   93756     sqlite3DbFreeNN(db, p);
   93757   }
   93758 }
   93759 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
   93760   if( p ) sqlite3ExprDeleteNN(db, p);
   93761 }
   93762 
   93763 /*
   93764 ** Return the number of bytes allocated for the expression structure
   93765 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
   93766 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
   93767 */
   93768 static int exprStructSize(Expr *p){
   93769   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   93770   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   93771   return EXPR_FULLSIZE;
   93772 }
   93773 
   93774 /*
   93775 ** The dupedExpr*Size() routines each return the number of bytes required
   93776 ** to store a copy of an expression or expression tree.  They differ in
   93777 ** how much of the tree is measured.
   93778 **
   93779 **     dupedExprStructSize()     Size of only the Expr structure
   93780 **     dupedExprNodeSize()       Size of Expr + space for token
   93781 **     dupedExprSize()           Expr + token + subtree components
   93782 **
   93783 ***************************************************************************
   93784 **
   93785 ** The dupedExprStructSize() function returns two values OR-ed together:
   93786 ** (1) the space required for a copy of the Expr structure only and
   93787 ** (2) the EP_xxx flags that indicate what the structure size should be.
   93788 ** The return values is always one of:
   93789 **
   93790 **      EXPR_FULLSIZE
   93791 **      EXPR_REDUCEDSIZE   | EP_Reduced
   93792 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
   93793 **
   93794 ** The size of the structure can be found by masking the return value
   93795 ** of this routine with 0xfff.  The flags can be found by masking the
   93796 ** return value with EP_Reduced|EP_TokenOnly.
   93797 **
   93798 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
   93799 ** (unreduced) Expr objects as they or originally constructed by the parser.
   93800 ** During expression analysis, extra information is computed and moved into
   93801 ** later parts of teh Expr object and that extra information might get chopped
   93802 ** off if the expression is reduced.  Note also that it does not work to
   93803 ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
   93804 ** to reduce a pristine expression tree from the parser.  The implementation
   93805 ** of dupedExprStructSize() contain multiple assert() statements that attempt
   93806 ** to enforce this constraint.
   93807 */
   93808 static int dupedExprStructSize(Expr *p, int flags){
   93809   int nSize;
   93810   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   93811   assert( EXPR_FULLSIZE<=0xfff );
   93812   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
   93813   if( 0==flags || p->op==TK_SELECT_COLUMN ){
   93814     nSize = EXPR_FULLSIZE;
   93815   }else{
   93816     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
   93817     assert( !ExprHasProperty(p, EP_FromJoin) );
   93818     assert( !ExprHasProperty(p, EP_MemToken) );
   93819     assert( !ExprHasProperty(p, EP_NoReduce) );
   93820     if( p->pLeft || p->x.pList ){
   93821       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
   93822     }else{
   93823       assert( p->pRight==0 );
   93824       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
   93825     }
   93826   }
   93827   return nSize;
   93828 }
   93829 
   93830 /*
   93831 ** This function returns the space in bytes required to store the copy
   93832 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
   93833 ** string is defined.)
   93834 */
   93835 static int dupedExprNodeSize(Expr *p, int flags){
   93836   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   93837   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   93838     nByte += sqlite3Strlen30(p->u.zToken)+1;
   93839   }
   93840   return ROUND8(nByte);
   93841 }
   93842 
   93843 /*
   93844 ** Return the number of bytes required to create a duplicate of the
   93845 ** expression passed as the first argument. The second argument is a
   93846 ** mask containing EXPRDUP_XXX flags.
   93847 **
   93848 ** The value returned includes space to create a copy of the Expr struct
   93849 ** itself and the buffer referred to by Expr.u.zToken, if any.
   93850 **
   93851 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
   93852 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
   93853 ** and Expr.pRight variables (but not for any structures pointed to or
   93854 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
   93855 */
   93856 static int dupedExprSize(Expr *p, int flags){
   93857   int nByte = 0;
   93858   if( p ){
   93859     nByte = dupedExprNodeSize(p, flags);
   93860     if( flags&EXPRDUP_REDUCE ){
   93861       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
   93862     }
   93863   }
   93864   return nByte;
   93865 }
   93866 
   93867 /*
   93868 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
   93869 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
   93870 ** to store the copy of expression p, the copies of p->u.zToken
   93871 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   93872 ** if any. Before returning, *pzBuffer is set to the first byte past the
   93873 ** portion of the buffer copied into by this function.
   93874 */
   93875 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
   93876   Expr *pNew;           /* Value to return */
   93877   u8 *zAlloc;           /* Memory space from which to build Expr object */
   93878   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
   93879 
   93880   assert( db!=0 );
   93881   assert( p );
   93882   assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
   93883   assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
   93884 
   93885   /* Figure out where to write the new Expr structure. */
   93886   if( pzBuffer ){
   93887     zAlloc = *pzBuffer;
   93888     staticFlag = EP_Static;
   93889   }else{
   93890     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
   93891     staticFlag = 0;
   93892   }
   93893   pNew = (Expr *)zAlloc;
   93894 
   93895   if( pNew ){
   93896     /* Set nNewSize to the size allocated for the structure pointed to
   93897     ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   93898     ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
   93899     ** by the copy of the p->u.zToken string (if any).
   93900     */
   93901     const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
   93902     const int nNewSize = nStructSize & 0xfff;
   93903     int nToken;
   93904     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   93905       nToken = sqlite3Strlen30(p->u.zToken) + 1;
   93906     }else{
   93907       nToken = 0;
   93908     }
   93909     if( dupFlags ){
   93910       assert( ExprHasProperty(p, EP_Reduced)==0 );
   93911       memcpy(zAlloc, p, nNewSize);
   93912     }else{
   93913       u32 nSize = (u32)exprStructSize(p);
   93914       memcpy(zAlloc, p, nSize);
   93915       if( nSize<EXPR_FULLSIZE ){
   93916         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
   93917       }
   93918     }
   93919 
   93920     /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
   93921     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
   93922     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
   93923     pNew->flags |= staticFlag;
   93924 
   93925     /* Copy the p->u.zToken string, if any. */
   93926     if( nToken ){
   93927       char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
   93928       memcpy(zToken, p->u.zToken, nToken);
   93929     }
   93930 
   93931     if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
   93932       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
   93933       if( ExprHasProperty(p, EP_xIsSelect) ){
   93934         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
   93935       }else{
   93936         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
   93937       }
   93938     }
   93939 
   93940     /* Fill in pNew->pLeft and pNew->pRight. */
   93941     if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
   93942       zAlloc += dupedExprNodeSize(p, dupFlags);
   93943       if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
   93944         pNew->pLeft = p->pLeft ?
   93945                       exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
   93946         pNew->pRight = p->pRight ?
   93947                        exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
   93948       }
   93949       if( pzBuffer ){
   93950         *pzBuffer = zAlloc;
   93951       }
   93952     }else{
   93953       if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
   93954         if( pNew->op==TK_SELECT_COLUMN ){
   93955           pNew->pLeft = p->pLeft;
   93956           assert( p->iColumn==0 || p->pRight==0 );
   93957           assert( p->pRight==0  || p->pRight==p->pLeft );
   93958         }else{
   93959           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
   93960         }
   93961         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
   93962       }
   93963     }
   93964   }
   93965   return pNew;
   93966 }
   93967 
   93968 /*
   93969 ** Create and return a deep copy of the object passed as the second
   93970 ** argument. If an OOM condition is encountered, NULL is returned
   93971 ** and the db->mallocFailed flag set.
   93972 */
   93973 #ifndef SQLITE_OMIT_CTE
   93974 static With *withDup(sqlite3 *db, With *p){
   93975   With *pRet = 0;
   93976   if( p ){
   93977     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
   93978     pRet = sqlite3DbMallocZero(db, nByte);
   93979     if( pRet ){
   93980       int i;
   93981       pRet->nCte = p->nCte;
   93982       for(i=0; i<p->nCte; i++){
   93983         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
   93984         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
   93985         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
   93986       }
   93987     }
   93988   }
   93989   return pRet;
   93990 }
   93991 #else
   93992 # define withDup(x,y) 0
   93993 #endif
   93994 
   93995 /*
   93996 ** The following group of routines make deep copies of expressions,
   93997 ** expression lists, ID lists, and select statements.  The copies can
   93998 ** be deleted (by being passed to their respective ...Delete() routines)
   93999 ** without effecting the originals.
   94000 **
   94001 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
   94002 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
   94003 ** by subsequent calls to sqlite*ListAppend() routines.
   94004 **
   94005 ** Any tables that the SrcList might point to are not duplicated.
   94006 **
   94007 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
   94008 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
   94009 ** truncated version of the usual Expr structure that will be stored as
   94010 ** part of the in-memory representation of the database schema.
   94011 */
   94012 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
   94013   assert( flags==0 || flags==EXPRDUP_REDUCE );
   94014   return p ? exprDup(db, p, flags, 0) : 0;
   94015 }
   94016 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   94017   ExprList *pNew;
   94018   struct ExprList_item *pItem, *pOldItem;
   94019   int i;
   94020   Expr *pPriorSelectCol = 0;
   94021   assert( db!=0 );
   94022   if( p==0 ) return 0;
   94023   pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
   94024   if( pNew==0 ) return 0;
   94025   pNew->nExpr = p->nExpr;
   94026   pItem = pNew->a;
   94027   pOldItem = p->a;
   94028   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   94029     Expr *pOldExpr = pOldItem->pExpr;
   94030     Expr *pNewExpr;
   94031     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   94032     if( pOldExpr
   94033      && pOldExpr->op==TK_SELECT_COLUMN
   94034      && (pNewExpr = pItem->pExpr)!=0
   94035     ){
   94036       assert( pNewExpr->iColumn==0 || i>0 );
   94037       if( pNewExpr->iColumn==0 ){
   94038         assert( pOldExpr->pLeft==pOldExpr->pRight );
   94039         pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
   94040       }else{
   94041         assert( i>0 );
   94042         assert( pItem[-1].pExpr!=0 );
   94043         assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
   94044         assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
   94045         pNewExpr->pLeft = pPriorSelectCol;
   94046       }
   94047     }
   94048     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   94049     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   94050     pItem->sortOrder = pOldItem->sortOrder;
   94051     pItem->done = 0;
   94052     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
   94053     pItem->u = pOldItem->u;
   94054   }
   94055   return pNew;
   94056 }
   94057 
   94058 /*
   94059 ** If cursors, triggers, views and subqueries are all omitted from
   94060 ** the build, then none of the following routines, except for
   94061 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
   94062 ** called with a NULL argument.
   94063 */
   94064 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
   94065  || !defined(SQLITE_OMIT_SUBQUERY)
   94066 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   94067   SrcList *pNew;
   94068   int i;
   94069   int nByte;
   94070   assert( db!=0 );
   94071   if( p==0 ) return 0;
   94072   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
   94073   pNew = sqlite3DbMallocRawNN(db, nByte );
   94074   if( pNew==0 ) return 0;
   94075   pNew->nSrc = pNew->nAlloc = p->nSrc;
   94076   for(i=0; i<p->nSrc; i++){
   94077     struct SrcList_item *pNewItem = &pNew->a[i];
   94078     struct SrcList_item *pOldItem = &p->a[i];
   94079     Table *pTab;
   94080     pNewItem->pSchema = pOldItem->pSchema;
   94081     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
   94082     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   94083     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
   94084     pNewItem->fg = pOldItem->fg;
   94085     pNewItem->iCursor = pOldItem->iCursor;
   94086     pNewItem->addrFillSub = pOldItem->addrFillSub;
   94087     pNewItem->regReturn = pOldItem->regReturn;
   94088     if( pNewItem->fg.isIndexedBy ){
   94089       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
   94090     }
   94091     pNewItem->pIBIndex = pOldItem->pIBIndex;
   94092     if( pNewItem->fg.isTabFunc ){
   94093       pNewItem->u1.pFuncArg =
   94094           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
   94095     }
   94096     pTab = pNewItem->pTab = pOldItem->pTab;
   94097     if( pTab ){
   94098       pTab->nTabRef++;
   94099     }
   94100     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
   94101     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
   94102     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
   94103     pNewItem->colUsed = pOldItem->colUsed;
   94104   }
   94105   return pNew;
   94106 }
   94107 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   94108   IdList *pNew;
   94109   int i;
   94110   assert( db!=0 );
   94111   if( p==0 ) return 0;
   94112   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
   94113   if( pNew==0 ) return 0;
   94114   pNew->nId = p->nId;
   94115   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
   94116   if( pNew->a==0 ){
   94117     sqlite3DbFreeNN(db, pNew);
   94118     return 0;
   94119   }
   94120   /* Note that because the size of the allocation for p->a[] is not
   94121   ** necessarily a power of two, sqlite3IdListAppend() may not be called
   94122   ** on the duplicate created by this function. */
   94123   for(i=0; i<p->nId; i++){
   94124     struct IdList_item *pNewItem = &pNew->a[i];
   94125     struct IdList_item *pOldItem = &p->a[i];
   94126     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   94127     pNewItem->idx = pOldItem->idx;
   94128   }
   94129   return pNew;
   94130 }
   94131 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
   94132   Select *pRet = 0;
   94133   Select *pNext = 0;
   94134   Select **pp = &pRet;
   94135   Select *p;
   94136 
   94137   assert( db!=0 );
   94138   for(p=pDup; p; p=p->pPrior){
   94139     Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
   94140     if( pNew==0 ) break;
   94141     pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   94142     pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   94143     pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   94144     pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   94145     pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   94146     pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   94147     pNew->op = p->op;
   94148     pNew->pNext = pNext;
   94149     pNew->pPrior = 0;
   94150     pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   94151     pNew->iLimit = 0;
   94152     pNew->iOffset = 0;
   94153     pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   94154     pNew->addrOpenEphm[0] = -1;
   94155     pNew->addrOpenEphm[1] = -1;
   94156     pNew->nSelectRow = p->nSelectRow;
   94157     pNew->pWith = withDup(db, p->pWith);
   94158     sqlite3SelectSetName(pNew, p->zSelName);
   94159     *pp = pNew;
   94160     pp = &pNew->pPrior;
   94161     pNext = pNew;
   94162   }
   94163 
   94164   return pRet;
   94165 }
   94166 #else
   94167 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   94168   assert( p==0 );
   94169   return 0;
   94170 }
   94171 #endif
   94172 
   94173 
   94174 /*
   94175 ** Add a new element to the end of an expression list.  If pList is
   94176 ** initially NULL, then create a new expression list.
   94177 **
   94178 ** The pList argument must be either NULL or a pointer to an ExprList
   94179 ** obtained from a prior call to sqlite3ExprListAppend().  This routine
   94180 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
   94181 ** Reason:  This routine assumes that the number of slots in pList->a[]
   94182 ** is a power of two.  That is true for sqlite3ExprListAppend() returns
   94183 ** but is not necessarily true from the return value of sqlite3ExprListDup().
   94184 **
   94185 ** If a memory allocation error occurs, the entire list is freed and
   94186 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
   94187 ** that the new entry was successfully appended.
   94188 */
   94189 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   94190   Parse *pParse,          /* Parsing context */
   94191   ExprList *pList,        /* List to which to append. Might be NULL */
   94192   Expr *pExpr             /* Expression to be appended. Might be NULL */
   94193 ){
   94194   struct ExprList_item *pItem;
   94195   sqlite3 *db = pParse->db;
   94196   assert( db!=0 );
   94197   if( pList==0 ){
   94198     pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
   94199     if( pList==0 ){
   94200       goto no_mem;
   94201     }
   94202     pList->nExpr = 0;
   94203   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
   94204     ExprList *pNew;
   94205     pNew = sqlite3DbRealloc(db, pList,
   94206              sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
   94207     if( pNew==0 ){
   94208       goto no_mem;
   94209     }
   94210     pList = pNew;
   94211   }
   94212   pItem = &pList->a[pList->nExpr++];
   94213   assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
   94214   assert( offsetof(struct ExprList_item,pExpr)==0 );
   94215   memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
   94216   pItem->pExpr = pExpr;
   94217   return pList;
   94218 
   94219 no_mem:
   94220   /* Avoid leaking memory if malloc has failed. */
   94221   sqlite3ExprDelete(db, pExpr);
   94222   sqlite3ExprListDelete(db, pList);
   94223   return 0;
   94224 }
   94225 
   94226 /*
   94227 ** pColumns and pExpr form a vector assignment which is part of the SET
   94228 ** clause of an UPDATE statement.  Like this:
   94229 **
   94230 **        (a,b,c) = (expr1,expr2,expr3)
   94231 ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
   94232 **
   94233 ** For each term of the vector assignment, append new entries to the
   94234 ** expression list pList.  In the case of a subquery on the RHS, append
   94235 ** TK_SELECT_COLUMN expressions.
   94236 */
   94237 SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
   94238   Parse *pParse,         /* Parsing context */
   94239   ExprList *pList,       /* List to which to append. Might be NULL */
   94240   IdList *pColumns,      /* List of names of LHS of the assignment */
   94241   Expr *pExpr            /* Vector expression to be appended. Might be NULL */
   94242 ){
   94243   sqlite3 *db = pParse->db;
   94244   int n;
   94245   int i;
   94246   int iFirst = pList ? pList->nExpr : 0;
   94247   /* pColumns can only be NULL due to an OOM but an OOM will cause an
   94248   ** exit prior to this routine being invoked */
   94249   if( NEVER(pColumns==0) ) goto vector_append_error;
   94250   if( pExpr==0 ) goto vector_append_error;
   94251 
   94252   /* If the RHS is a vector, then we can immediately check to see that
   94253   ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
   94254   ** wildcards ("*") in the result set of the SELECT must be expanded before
   94255   ** we can do the size check, so defer the size check until code generation.
   94256   */
   94257   if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
   94258     sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
   94259                     pColumns->nId, n);
   94260     goto vector_append_error;
   94261   }
   94262 
   94263   for(i=0; i<pColumns->nId; i++){
   94264     Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
   94265     pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
   94266     if( pList ){
   94267       assert( pList->nExpr==iFirst+i+1 );
   94268       pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
   94269       pColumns->a[i].zName = 0;
   94270     }
   94271   }
   94272 
   94273   if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
   94274     Expr *pFirst = pList->a[iFirst].pExpr;
   94275     assert( pFirst!=0 );
   94276     assert( pFirst->op==TK_SELECT_COLUMN );
   94277 
   94278     /* Store the SELECT statement in pRight so it will be deleted when
   94279     ** sqlite3ExprListDelete() is called */
   94280     pFirst->pRight = pExpr;
   94281     pExpr = 0;
   94282 
   94283     /* Remember the size of the LHS in iTable so that we can check that
   94284     ** the RHS and LHS sizes match during code generation. */
   94285     pFirst->iTable = pColumns->nId;
   94286   }
   94287 
   94288 vector_append_error:
   94289   sqlite3ExprDelete(db, pExpr);
   94290   sqlite3IdListDelete(db, pColumns);
   94291   return pList;
   94292 }
   94293 
   94294 /*
   94295 ** Set the sort order for the last element on the given ExprList.
   94296 */
   94297 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
   94298   if( p==0 ) return;
   94299   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
   94300   assert( p->nExpr>0 );
   94301   if( iSortOrder<0 ){
   94302     assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
   94303     return;
   94304   }
   94305   p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
   94306 }
   94307 
   94308 /*
   94309 ** Set the ExprList.a[].zName element of the most recently added item
   94310 ** on the expression list.
   94311 **
   94312 ** pList might be NULL following an OOM error.  But pName should never be
   94313 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   94314 ** is set.
   94315 */
   94316 SQLITE_PRIVATE void sqlite3ExprListSetName(
   94317   Parse *pParse,          /* Parsing context */
   94318   ExprList *pList,        /* List to which to add the span. */
   94319   Token *pName,           /* Name to be added */
   94320   int dequote             /* True to cause the name to be dequoted */
   94321 ){
   94322   assert( pList!=0 || pParse->db->mallocFailed!=0 );
   94323   if( pList ){
   94324     struct ExprList_item *pItem;
   94325     assert( pList->nExpr>0 );
   94326     pItem = &pList->a[pList->nExpr-1];
   94327     assert( pItem->zName==0 );
   94328     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
   94329     if( dequote ) sqlite3Dequote(pItem->zName);
   94330   }
   94331 }
   94332 
   94333 /*
   94334 ** Set the ExprList.a[].zSpan element of the most recently added item
   94335 ** on the expression list.
   94336 **
   94337 ** pList might be NULL following an OOM error.  But pSpan should never be
   94338 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   94339 ** is set.
   94340 */
   94341 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   94342   Parse *pParse,          /* Parsing context */
   94343   ExprList *pList,        /* List to which to add the span. */
   94344   const char *zStart,     /* Start of the span */
   94345   const char *zEnd        /* End of the span */
   94346 ){
   94347   sqlite3 *db = pParse->db;
   94348   assert( pList!=0 || db->mallocFailed!=0 );
   94349   if( pList ){
   94350     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
   94351     assert( pList->nExpr>0 );
   94352     sqlite3DbFree(db, pItem->zSpan);
   94353     pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
   94354   }
   94355 }
   94356 
   94357 /*
   94358 ** If the expression list pEList contains more than iLimit elements,
   94359 ** leave an error message in pParse.
   94360 */
   94361 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
   94362   Parse *pParse,
   94363   ExprList *pEList,
   94364   const char *zObject
   94365 ){
   94366   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
   94367   testcase( pEList && pEList->nExpr==mx );
   94368   testcase( pEList && pEList->nExpr==mx+1 );
   94369   if( pEList && pEList->nExpr>mx ){
   94370     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
   94371   }
   94372 }
   94373 
   94374 /*
   94375 ** Delete an entire expression list.
   94376 */
   94377 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
   94378   int i = pList->nExpr;
   94379   struct ExprList_item *pItem =  pList->a;
   94380   assert( pList->nExpr>0 );
   94381   do{
   94382     sqlite3ExprDelete(db, pItem->pExpr);
   94383     sqlite3DbFree(db, pItem->zName);
   94384     sqlite3DbFree(db, pItem->zSpan);
   94385     pItem++;
   94386   }while( --i>0 );
   94387   sqlite3DbFreeNN(db, pList);
   94388 }
   94389 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
   94390   if( pList ) exprListDeleteNN(db, pList);
   94391 }
   94392 
   94393 /*
   94394 ** Return the bitwise-OR of all Expr.flags fields in the given
   94395 ** ExprList.
   94396 */
   94397 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
   94398   int i;
   94399   u32 m = 0;
   94400   assert( pList!=0 );
   94401   for(i=0; i<pList->nExpr; i++){
   94402      Expr *pExpr = pList->a[i].pExpr;
   94403      assert( pExpr!=0 );
   94404      m |= pExpr->flags;
   94405   }
   94406   return m;
   94407 }
   94408 
   94409 /*
   94410 ** This is a SELECT-node callback for the expression walker that
   94411 ** always "fails".  By "fail" in this case, we mean set
   94412 ** pWalker->eCode to zero and abort.
   94413 **
   94414 ** This callback is used by multiple expression walkers.
   94415 */
   94416 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
   94417   UNUSED_PARAMETER(NotUsed);
   94418   pWalker->eCode = 0;
   94419   return WRC_Abort;
   94420 }
   94421 
   94422 /*
   94423 ** These routines are Walker callbacks used to check expressions to
   94424 ** see if they are "constant" for some definition of constant.  The
   94425 ** Walker.eCode value determines the type of "constant" we are looking
   94426 ** for.
   94427 **
   94428 ** These callback routines are used to implement the following:
   94429 **
   94430 **     sqlite3ExprIsConstant()                  pWalker->eCode==1
   94431 **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
   94432 **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
   94433 **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
   94434 **
   94435 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
   94436 ** is found to not be a constant.
   94437 **
   94438 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
   94439 ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
   94440 ** an existing schema and 4 when processing a new statement.  A bound
   94441 ** parameter raises an error for new statements, but is silently converted
   94442 ** to NULL for existing schemas.  This allows sqlite_master tables that
   94443 ** contain a bound parameter because they were generated by older versions
   94444 ** of SQLite to be parsed by newer versions of SQLite without raising a
   94445 ** malformed schema error.
   94446 */
   94447 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
   94448 
   94449   /* If pWalker->eCode is 2 then any term of the expression that comes from
   94450   ** the ON or USING clauses of a left join disqualifies the expression
   94451   ** from being considered constant. */
   94452   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
   94453     pWalker->eCode = 0;
   94454     return WRC_Abort;
   94455   }
   94456 
   94457   switch( pExpr->op ){
   94458     /* Consider functions to be constant if all their arguments are constant
   94459     ** and either pWalker->eCode==4 or 5 or the function has the
   94460     ** SQLITE_FUNC_CONST flag. */
   94461     case TK_FUNCTION:
   94462       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
   94463         return WRC_Continue;
   94464       }else{
   94465         pWalker->eCode = 0;
   94466         return WRC_Abort;
   94467       }
   94468     case TK_ID:
   94469     case TK_COLUMN:
   94470     case TK_AGG_FUNCTION:
   94471     case TK_AGG_COLUMN:
   94472       testcase( pExpr->op==TK_ID );
   94473       testcase( pExpr->op==TK_COLUMN );
   94474       testcase( pExpr->op==TK_AGG_FUNCTION );
   94475       testcase( pExpr->op==TK_AGG_COLUMN );
   94476       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
   94477         return WRC_Continue;
   94478       }
   94479       /* Fall through */
   94480     case TK_IF_NULL_ROW:
   94481       testcase( pExpr->op==TK_IF_NULL_ROW );
   94482       pWalker->eCode = 0;
   94483       return WRC_Abort;
   94484     case TK_VARIABLE:
   94485       if( pWalker->eCode==5 ){
   94486         /* Silently convert bound parameters that appear inside of CREATE
   94487         ** statements into a NULL when parsing the CREATE statement text out
   94488         ** of the sqlite_master table */
   94489         pExpr->op = TK_NULL;
   94490       }else if( pWalker->eCode==4 ){
   94491         /* A bound parameter in a CREATE statement that originates from
   94492         ** sqlite3_prepare() causes an error */
   94493         pWalker->eCode = 0;
   94494         return WRC_Abort;
   94495       }
   94496       /* Fall through */
   94497     default:
   94498       testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail will disallow */
   94499       testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail will disallow */
   94500       return WRC_Continue;
   94501   }
   94502 }
   94503 static int exprIsConst(Expr *p, int initFlag, int iCur){
   94504   Walker w;
   94505   w.eCode = initFlag;
   94506   w.xExprCallback = exprNodeIsConstant;
   94507   w.xSelectCallback = sqlite3SelectWalkFail;
   94508 #ifdef SQLITE_DEBUG
   94509   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
   94510 #endif
   94511   w.u.iCur = iCur;
   94512   sqlite3WalkExpr(&w, p);
   94513   return w.eCode;
   94514 }
   94515 
   94516 /*
   94517 ** Walk an expression tree.  Return non-zero if the expression is constant
   94518 ** and 0 if it involves variables or function calls.
   94519 **
   94520 ** For the purposes of this function, a double-quoted string (ex: "abc")
   94521 ** is considered a variable but a single-quoted string (ex: 'abc') is
   94522 ** a constant.
   94523 */
   94524 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
   94525   return exprIsConst(p, 1, 0);
   94526 }
   94527 
   94528 /*
   94529 ** Walk an expression tree.  Return non-zero if the expression is constant
   94530 ** that does no originate from the ON or USING clauses of a join.
   94531 ** Return 0 if it involves variables or function calls or terms from
   94532 ** an ON or USING clause.
   94533 */
   94534 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   94535   return exprIsConst(p, 2, 0);
   94536 }
   94537 
   94538 /*
   94539 ** Walk an expression tree.  Return non-zero if the expression is constant
   94540 ** for any single row of the table with cursor iCur.  In other words, the
   94541 ** expression must not refer to any non-deterministic function nor any
   94542 ** table other than iCur.
   94543 */
   94544 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
   94545   return exprIsConst(p, 3, iCur);
   94546 }
   94547 
   94548 
   94549 /*
   94550 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
   94551 */
   94552 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
   94553   ExprList *pGroupBy = pWalker->u.pGroupBy;
   94554   int i;
   94555 
   94556   /* Check if pExpr is identical to any GROUP BY term. If so, consider
   94557   ** it constant.  */
   94558   for(i=0; i<pGroupBy->nExpr; i++){
   94559     Expr *p = pGroupBy->a[i].pExpr;
   94560     if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
   94561       CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
   94562       if( sqlite3_stricmp("BINARY", pColl->zName)==0 ){
   94563         return WRC_Prune;
   94564       }
   94565     }
   94566   }
   94567 
   94568   /* Check if pExpr is a sub-select. If so, consider it variable. */
   94569   if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   94570     pWalker->eCode = 0;
   94571     return WRC_Abort;
   94572   }
   94573 
   94574   return exprNodeIsConstant(pWalker, pExpr);
   94575 }
   94576 
   94577 /*
   94578 ** Walk the expression tree passed as the first argument. Return non-zero
   94579 ** if the expression consists entirely of constants or copies of terms
   94580 ** in pGroupBy that sort with the BINARY collation sequence.
   94581 **
   94582 ** This routine is used to determine if a term of the HAVING clause can
   94583 ** be promoted into the WHERE clause.  In order for such a promotion to work,
   94584 ** the value of the HAVING clause term must be the same for all members of
   94585 ** a "group".  The requirement that the GROUP BY term must be BINARY
   94586 ** assumes that no other collating sequence will have a finer-grained
   94587 ** grouping than binary.  In other words (A=B COLLATE binary) implies
   94588 ** A=B in every other collating sequence.  The requirement that the
   94589 ** GROUP BY be BINARY is stricter than necessary.  It would also work
   94590 ** to promote HAVING clauses that use the same alternative collating
   94591 ** sequence as the GROUP BY term, but that is much harder to check,
   94592 ** alternative collating sequences are uncommon, and this is only an
   94593 ** optimization, so we take the easy way out and simply require the
   94594 ** GROUP BY to use the BINARY collating sequence.
   94595 */
   94596 SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
   94597   Walker w;
   94598   w.eCode = 1;
   94599   w.xExprCallback = exprNodeIsConstantOrGroupBy;
   94600   w.xSelectCallback = 0;
   94601   w.u.pGroupBy = pGroupBy;
   94602   w.pParse = pParse;
   94603   sqlite3WalkExpr(&w, p);
   94604   return w.eCode;
   94605 }
   94606 
   94607 /*
   94608 ** Walk an expression tree.  Return non-zero if the expression is constant
   94609 ** or a function call with constant arguments.  Return and 0 if there
   94610 ** are any variables.
   94611 **
   94612 ** For the purposes of this function, a double-quoted string (ex: "abc")
   94613 ** is considered a variable but a single-quoted string (ex: 'abc') is
   94614 ** a constant.
   94615 */
   94616 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
   94617   assert( isInit==0 || isInit==1 );
   94618   return exprIsConst(p, 4+isInit, 0);
   94619 }
   94620 
   94621 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   94622 /*
   94623 ** Walk an expression tree.  Return 1 if the expression contains a
   94624 ** subquery of some kind.  Return 0 if there are no subqueries.
   94625 */
   94626 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
   94627   Walker w;
   94628   w.eCode = 1;
   94629   w.xExprCallback = sqlite3ExprWalkNoop;
   94630   w.xSelectCallback = sqlite3SelectWalkFail;
   94631 #ifdef SQLITE_DEBUG
   94632   w.xSelectCallback2 = sqlite3SelectWalkAssert2;
   94633 #endif
   94634   sqlite3WalkExpr(&w, p);
   94635   return w.eCode==0;
   94636 }
   94637 #endif
   94638 
   94639 /*
   94640 ** If the expression p codes a constant integer that is small enough
   94641 ** to fit in a 32-bit integer, return 1 and put the value of the integer
   94642 ** in *pValue.  If the expression is not an integer or if it is too big
   94643 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   94644 */
   94645 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
   94646   int rc = 0;
   94647   if( p==0 ) return 0;  /* Can only happen following on OOM */
   94648 
   94649   /* If an expression is an integer literal that fits in a signed 32-bit
   94650   ** integer, then the EP_IntValue flag will have already been set */
   94651   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
   94652            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
   94653 
   94654   if( p->flags & EP_IntValue ){
   94655     *pValue = p->u.iValue;
   94656     return 1;
   94657   }
   94658   switch( p->op ){
   94659     case TK_UPLUS: {
   94660       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
   94661       break;
   94662     }
   94663     case TK_UMINUS: {
   94664       int v;
   94665       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
   94666         assert( v!=(-2147483647-1) );
   94667         *pValue = -v;
   94668         rc = 1;
   94669       }
   94670       break;
   94671     }
   94672     default: break;
   94673   }
   94674   return rc;
   94675 }
   94676 
   94677 /*
   94678 ** Return FALSE if there is no chance that the expression can be NULL.
   94679 **
   94680 ** If the expression might be NULL or if the expression is too complex
   94681 ** to tell return TRUE.
   94682 **
   94683 ** This routine is used as an optimization, to skip OP_IsNull opcodes
   94684 ** when we know that a value cannot be NULL.  Hence, a false positive
   94685 ** (returning TRUE when in fact the expression can never be NULL) might
   94686 ** be a small performance hit but is otherwise harmless.  On the other
   94687 ** hand, a false negative (returning FALSE when the result could be NULL)
   94688 ** will likely result in an incorrect answer.  So when in doubt, return
   94689 ** TRUE.
   94690 */
   94691 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   94692   u8 op;
   94693   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   94694   op = p->op;
   94695   if( op==TK_REGISTER ) op = p->op2;
   94696   switch( op ){
   94697     case TK_INTEGER:
   94698     case TK_STRING:
   94699     case TK_FLOAT:
   94700     case TK_BLOB:
   94701       return 0;
   94702     case TK_COLUMN:
   94703       return ExprHasProperty(p, EP_CanBeNull) ||
   94704              p->pTab==0 ||  /* Reference to column of index on expression */
   94705              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
   94706     default:
   94707       return 1;
   94708   }
   94709 }
   94710 
   94711 /*
   94712 ** Return TRUE if the given expression is a constant which would be
   94713 ** unchanged by OP_Affinity with the affinity given in the second
   94714 ** argument.
   94715 **
   94716 ** This routine is used to determine if the OP_Affinity operation
   94717 ** can be omitted.  When in doubt return FALSE.  A false negative
   94718 ** is harmless.  A false positive, however, can result in the wrong
   94719 ** answer.
   94720 */
   94721 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
   94722   u8 op;
   94723   if( aff==SQLITE_AFF_BLOB ) return 1;
   94724   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   94725   op = p->op;
   94726   if( op==TK_REGISTER ) op = p->op2;
   94727   switch( op ){
   94728     case TK_INTEGER: {
   94729       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
   94730     }
   94731     case TK_FLOAT: {
   94732       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
   94733     }
   94734     case TK_STRING: {
   94735       return aff==SQLITE_AFF_TEXT;
   94736     }
   94737     case TK_BLOB: {
   94738       return 1;
   94739     }
   94740     case TK_COLUMN: {
   94741       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
   94742       return p->iColumn<0
   94743           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
   94744     }
   94745     default: {
   94746       return 0;
   94747     }
   94748   }
   94749 }
   94750 
   94751 /*
   94752 ** Return TRUE if the given string is a row-id column name.
   94753 */
   94754 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
   94755   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
   94756   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
   94757   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
   94758   return 0;
   94759 }
   94760 
   94761 /*
   94762 ** pX is the RHS of an IN operator.  If pX is a SELECT statement
   94763 ** that can be simplified to a direct table access, then return
   94764 ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
   94765 ** or if the SELECT statement needs to be manifested into a transient
   94766 ** table, then return NULL.
   94767 */
   94768 #ifndef SQLITE_OMIT_SUBQUERY
   94769 static Select *isCandidateForInOpt(Expr *pX){
   94770   Select *p;
   94771   SrcList *pSrc;
   94772   ExprList *pEList;
   94773   Table *pTab;
   94774   int i;
   94775   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
   94776   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
   94777   p = pX->x.pSelect;
   94778   if( p->pPrior ) return 0;              /* Not a compound SELECT */
   94779   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   94780     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   94781     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   94782     return 0; /* No DISTINCT keyword and no aggregate functions */
   94783   }
   94784   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
   94785   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
   94786   if( p->pWhere ) return 0;              /* Has no WHERE clause */
   94787   pSrc = p->pSrc;
   94788   assert( pSrc!=0 );
   94789   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
   94790   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   94791   pTab = pSrc->a[0].pTab;
   94792   assert( pTab!=0 );
   94793   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
   94794   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   94795   pEList = p->pEList;
   94796   assert( pEList!=0 );
   94797   /* All SELECT results must be columns. */
   94798   for(i=0; i<pEList->nExpr; i++){
   94799     Expr *pRes = pEList->a[i].pExpr;
   94800     if( pRes->op!=TK_COLUMN ) return 0;
   94801     assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
   94802   }
   94803   return p;
   94804 }
   94805 #endif /* SQLITE_OMIT_SUBQUERY */
   94806 
   94807 #ifndef SQLITE_OMIT_SUBQUERY
   94808 /*
   94809 ** Generate code that checks the left-most column of index table iCur to see if
   94810 ** it contains any NULL entries.  Cause the register at regHasNull to be set
   94811 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
   94812 ** to be set to NULL if iCur contains one or more NULL values.
   94813 */
   94814 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
   94815   int addr1;
   94816   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
   94817   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
   94818   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
   94819   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
   94820   VdbeComment((v, "first_entry_in(%d)", iCur));
   94821   sqlite3VdbeJumpHere(v, addr1);
   94822 }
   94823 #endif
   94824 
   94825 
   94826 #ifndef SQLITE_OMIT_SUBQUERY
   94827 /*
   94828 ** The argument is an IN operator with a list (not a subquery) on the
   94829 ** right-hand side.  Return TRUE if that list is constant.
   94830 */
   94831 static int sqlite3InRhsIsConstant(Expr *pIn){
   94832   Expr *pLHS;
   94833   int res;
   94834   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
   94835   pLHS = pIn->pLeft;
   94836   pIn->pLeft = 0;
   94837   res = sqlite3ExprIsConstant(pIn);
   94838   pIn->pLeft = pLHS;
   94839   return res;
   94840 }
   94841 #endif
   94842 
   94843 /*
   94844 ** This function is used by the implementation of the IN (...) operator.
   94845 ** The pX parameter is the expression on the RHS of the IN operator, which
   94846 ** might be either a list of expressions or a subquery.
   94847 **
   94848 ** The job of this routine is to find or create a b-tree object that can
   94849 ** be used either to test for membership in the RHS set or to iterate through
   94850 ** all members of the RHS set, skipping duplicates.
   94851 **
   94852 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
   94853 ** and pX->iTable is set to the index of that cursor.
   94854 **
   94855 ** The returned value of this function indicates the b-tree type, as follows:
   94856 **
   94857 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
   94858 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
   94859 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
   94860 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
   94861 **                         populated epheremal table.
   94862 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
   94863 **                         implemented as a sequence of comparisons.
   94864 **
   94865 ** An existing b-tree might be used if the RHS expression pX is a simple
   94866 ** subquery such as:
   94867 **
   94868 **     SELECT <column1>, <column2>... FROM <table>
   94869 **
   94870 ** If the RHS of the IN operator is a list or a more complex subquery, then
   94871 ** an ephemeral table might need to be generated from the RHS and then
   94872 ** pX->iTable made to point to the ephemeral table instead of an
   94873 ** existing table.
   94874 **
   94875 ** The inFlags parameter must contain, at a minimum, one of the bits
   94876 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains
   94877 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
   94878 ** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will
   94879 ** be used to loop over all values of the RHS of the IN operator.
   94880 **
   94881 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
   94882 ** through the set members) then the b-tree must not contain duplicates.
   94883 ** An epheremal table will be created unless the selected columns are guaranteed
   94884 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
   94885 ** a UNIQUE constraint or index.
   94886 **
   94887 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
   94888 ** for fast set membership tests) then an epheremal table must
   94889 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
   94890 ** index can be found with the specified <columns> as its left-most.
   94891 **
   94892 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
   94893 ** if the RHS of the IN operator is a list (not a subquery) then this
   94894 ** routine might decide that creating an ephemeral b-tree for membership
   94895 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
   94896 ** calling routine should implement the IN operator using a sequence
   94897 ** of Eq or Ne comparison operations.
   94898 **
   94899 ** When the b-tree is being used for membership tests, the calling function
   94900 ** might need to know whether or not the RHS side of the IN operator
   94901 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
   94902 ** if there is any chance that the (...) might contain a NULL value at
   94903 ** runtime, then a register is allocated and the register number written
   94904 ** to *prRhsHasNull. If there is no chance that the (...) contains a
   94905 ** NULL value, then *prRhsHasNull is left unchanged.
   94906 **
   94907 ** If a register is allocated and its location stored in *prRhsHasNull, then
   94908 ** the value in that register will be NULL if the b-tree contains one or more
   94909 ** NULL values, and it will be some non-NULL value if the b-tree contains no
   94910 ** NULL values.
   94911 **
   94912 ** If the aiMap parameter is not NULL, it must point to an array containing
   94913 ** one element for each column returned by the SELECT statement on the RHS
   94914 ** of the IN(...) operator. The i'th entry of the array is populated with the
   94915 ** offset of the index column that matches the i'th column returned by the
   94916 ** SELECT. For example, if the expression and selected index are:
   94917 **
   94918 **   (?,?,?) IN (SELECT a, b, c FROM t1)
   94919 **   CREATE INDEX i1 ON t1(b, c, a);
   94920 **
   94921 ** then aiMap[] is populated with {2, 0, 1}.
   94922 */
   94923 #ifndef SQLITE_OMIT_SUBQUERY
   94924 SQLITE_PRIVATE int sqlite3FindInIndex(
   94925   Parse *pParse,             /* Parsing context */
   94926   Expr *pX,                  /* The right-hand side (RHS) of the IN operator */
   94927   u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
   94928   int *prRhsHasNull,         /* Register holding NULL status.  See notes */
   94929   int *aiMap                 /* Mapping from Index fields to RHS fields */
   94930 ){
   94931   Select *p;                            /* SELECT to the right of IN operator */
   94932   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
   94933   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
   94934   int mustBeUnique;                     /* True if RHS must be unique */
   94935   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
   94936 
   94937   assert( pX->op==TK_IN );
   94938   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
   94939 
   94940   /* If the RHS of this IN(...) operator is a SELECT, and if it matters
   94941   ** whether or not the SELECT result contains NULL values, check whether
   94942   ** or not NULL is actually possible (it may not be, for example, due
   94943   ** to NOT NULL constraints in the schema). If no NULL values are possible,
   94944   ** set prRhsHasNull to 0 before continuing.  */
   94945   if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
   94946     int i;
   94947     ExprList *pEList = pX->x.pSelect->pEList;
   94948     for(i=0; i<pEList->nExpr; i++){
   94949       if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
   94950     }
   94951     if( i==pEList->nExpr ){
   94952       prRhsHasNull = 0;
   94953     }
   94954   }
   94955 
   94956   /* Check to see if an existing table or index can be used to
   94957   ** satisfy the query.  This is preferable to generating a new
   94958   ** ephemeral table.  */
   94959   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
   94960     sqlite3 *db = pParse->db;              /* Database connection */
   94961     Table *pTab;                           /* Table <table>. */
   94962     i16 iDb;                               /* Database idx for pTab */
   94963     ExprList *pEList = p->pEList;
   94964     int nExpr = pEList->nExpr;
   94965 
   94966     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
   94967     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
   94968     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
   94969     pTab = p->pSrc->a[0].pTab;
   94970 
   94971     /* Code an OP_Transaction and OP_TableLock for <table>. */
   94972     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   94973     sqlite3CodeVerifySchema(pParse, iDb);
   94974     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   94975 
   94976     assert(v);  /* sqlite3GetVdbe() has always been previously called */
   94977     if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
   94978       /* The "x IN (SELECT rowid FROM table)" case */
   94979       int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
   94980       VdbeCoverage(v);
   94981 
   94982       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   94983       eType = IN_INDEX_ROWID;
   94984 
   94985       sqlite3VdbeJumpHere(v, iAddr);
   94986     }else{
   94987       Index *pIdx;                         /* Iterator variable */
   94988       int affinity_ok = 1;
   94989       int i;
   94990 
   94991       /* Check that the affinity that will be used to perform each
   94992       ** comparison is the same as the affinity of each column in table
   94993       ** on the RHS of the IN operator.  If it not, it is not possible to
   94994       ** use any index of the RHS table.  */
   94995       for(i=0; i<nExpr && affinity_ok; i++){
   94996         Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
   94997         int iCol = pEList->a[i].pExpr->iColumn;
   94998         char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
   94999         char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
   95000         testcase( cmpaff==SQLITE_AFF_BLOB );
   95001         testcase( cmpaff==SQLITE_AFF_TEXT );
   95002         switch( cmpaff ){
   95003           case SQLITE_AFF_BLOB:
   95004             break;
   95005           case SQLITE_AFF_TEXT:
   95006             /* sqlite3CompareAffinity() only returns TEXT if one side or the
   95007             ** other has no affinity and the other side is TEXT.  Hence,
   95008             ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
   95009             ** and for the term on the LHS of the IN to have no affinity. */
   95010             assert( idxaff==SQLITE_AFF_TEXT );
   95011             break;
   95012           default:
   95013             affinity_ok = sqlite3IsNumericAffinity(idxaff);
   95014         }
   95015       }
   95016 
   95017       if( affinity_ok ){
   95018         /* Search for an existing index that will work for this IN operator */
   95019         for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
   95020           Bitmask colUsed;      /* Columns of the index used */
   95021           Bitmask mCol;         /* Mask for the current column */
   95022           if( pIdx->nColumn<nExpr ) continue;
   95023           /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
   95024           ** BITMASK(nExpr) without overflowing */
   95025           testcase( pIdx->nColumn==BMS-2 );
   95026           testcase( pIdx->nColumn==BMS-1 );
   95027           if( pIdx->nColumn>=BMS-1 ) continue;
   95028           if( mustBeUnique ){
   95029             if( pIdx->nKeyCol>nExpr
   95030              ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
   95031             ){
   95032               continue;  /* This index is not unique over the IN RHS columns */
   95033             }
   95034           }
   95035 
   95036           colUsed = 0;   /* Columns of index used so far */
   95037           for(i=0; i<nExpr; i++){
   95038             Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
   95039             Expr *pRhs = pEList->a[i].pExpr;
   95040             CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
   95041             int j;
   95042 
   95043             assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
   95044             for(j=0; j<nExpr; j++){
   95045               if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
   95046               assert( pIdx->azColl[j] );
   95047               if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
   95048                 continue;
   95049               }
   95050               break;
   95051             }
   95052             if( j==nExpr ) break;
   95053             mCol = MASKBIT(j);
   95054             if( mCol & colUsed ) break; /* Each column used only once */
   95055             colUsed |= mCol;
   95056             if( aiMap ) aiMap[i] = j;
   95057           }
   95058 
   95059           assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
   95060           if( colUsed==(MASKBIT(nExpr)-1) ){
   95061             /* If we reach this point, that means the index pIdx is usable */
   95062             int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   95063 #ifndef SQLITE_OMIT_EXPLAIN
   95064             sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
   95065               sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
   95066               P4_DYNAMIC);
   95067 #endif
   95068             sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
   95069             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   95070             VdbeComment((v, "%s", pIdx->zName));
   95071             assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
   95072             eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
   95073 
   95074             if( prRhsHasNull ){
   95075 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
   95076               i64 mask = (1<<nExpr)-1;
   95077               sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
   95078                   iTab, 0, 0, (u8*)&mask, P4_INT64);
   95079 #endif
   95080               *prRhsHasNull = ++pParse->nMem;
   95081               if( nExpr==1 ){
   95082                 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
   95083               }
   95084             }
   95085             sqlite3VdbeJumpHere(v, iAddr);
   95086           }
   95087         } /* End loop over indexes */
   95088       } /* End if( affinity_ok ) */
   95089     } /* End if not an rowid index */
   95090   } /* End attempt to optimize using an index */
   95091 
   95092   /* If no preexisting index is available for the IN clause
   95093   ** and IN_INDEX_NOOP is an allowed reply
   95094   ** and the RHS of the IN operator is a list, not a subquery
   95095   ** and the RHS is not constant or has two or fewer terms,
   95096   ** then it is not worth creating an ephemeral table to evaluate
   95097   ** the IN operator so return IN_INDEX_NOOP.
   95098   */
   95099   if( eType==0
   95100    && (inFlags & IN_INDEX_NOOP_OK)
   95101    && !ExprHasProperty(pX, EP_xIsSelect)
   95102    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
   95103   ){
   95104     eType = IN_INDEX_NOOP;
   95105   }
   95106 
   95107   if( eType==0 ){
   95108     /* Could not find an existing table or index to use as the RHS b-tree.
   95109     ** We will have to generate an ephemeral table to do the job.
   95110     */
   95111     u32 savedNQueryLoop = pParse->nQueryLoop;
   95112     int rMayHaveNull = 0;
   95113     eType = IN_INDEX_EPH;
   95114     if( inFlags & IN_INDEX_LOOP ){
   95115       pParse->nQueryLoop = 0;
   95116       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
   95117         eType = IN_INDEX_ROWID;
   95118       }
   95119     }else if( prRhsHasNull ){
   95120       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
   95121     }
   95122     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
   95123     pParse->nQueryLoop = savedNQueryLoop;
   95124   }else{
   95125     pX->iTable = iTab;
   95126   }
   95127 
   95128   if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
   95129     int i, n;
   95130     n = sqlite3ExprVectorSize(pX->pLeft);
   95131     for(i=0; i<n; i++) aiMap[i] = i;
   95132   }
   95133   return eType;
   95134 }
   95135 #endif
   95136 
   95137 #ifndef SQLITE_OMIT_SUBQUERY
   95138 /*
   95139 ** Argument pExpr is an (?, ?...) IN(...) expression. This
   95140 ** function allocates and returns a nul-terminated string containing
   95141 ** the affinities to be used for each column of the comparison.
   95142 **
   95143 ** It is the responsibility of the caller to ensure that the returned
   95144 ** string is eventually freed using sqlite3DbFree().
   95145 */
   95146 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
   95147   Expr *pLeft = pExpr->pLeft;
   95148   int nVal = sqlite3ExprVectorSize(pLeft);
   95149   Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
   95150   char *zRet;
   95151 
   95152   assert( pExpr->op==TK_IN );
   95153   zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
   95154   if( zRet ){
   95155     int i;
   95156     for(i=0; i<nVal; i++){
   95157       Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
   95158       char a = sqlite3ExprAffinity(pA);
   95159       if( pSelect ){
   95160         zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
   95161       }else{
   95162         zRet[i] = a;
   95163       }
   95164     }
   95165     zRet[nVal] = '\0';
   95166   }
   95167   return zRet;
   95168 }
   95169 #endif
   95170 
   95171 #ifndef SQLITE_OMIT_SUBQUERY
   95172 /*
   95173 ** Load the Parse object passed as the first argument with an error
   95174 ** message of the form:
   95175 **
   95176 **   "sub-select returns N columns - expected M"
   95177 */
   95178 SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
   95179   const char *zFmt = "sub-select returns %d columns - expected %d";
   95180   sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
   95181 }
   95182 #endif
   95183 
   95184 /*
   95185 ** Expression pExpr is a vector that has been used in a context where
   95186 ** it is not permitted. If pExpr is a sub-select vector, this routine
   95187 ** loads the Parse object with a message of the form:
   95188 **
   95189 **   "sub-select returns N columns - expected 1"
   95190 **
   95191 ** Or, if it is a regular scalar vector:
   95192 **
   95193 **   "row value misused"
   95194 */
   95195 SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
   95196 #ifndef SQLITE_OMIT_SUBQUERY
   95197   if( pExpr->flags & EP_xIsSelect ){
   95198     sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
   95199   }else
   95200 #endif
   95201   {
   95202     sqlite3ErrorMsg(pParse, "row value misused");
   95203   }
   95204 }
   95205 
   95206 /*
   95207 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
   95208 ** or IN operators.  Examples:
   95209 **
   95210 **     (SELECT a FROM b)          -- subquery
   95211 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
   95212 **     x IN (4,5,11)              -- IN operator with list on right-hand side
   95213 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
   95214 **
   95215 ** The pExpr parameter describes the expression that contains the IN
   95216 ** operator or subquery.
   95217 **
   95218 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
   95219 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
   95220 ** to some integer key column of a table B-Tree. In this case, use an
   95221 ** intkey B-Tree to store the set of IN(...) values instead of the usual
   95222 ** (slower) variable length keys B-Tree.
   95223 **
   95224 ** If rMayHaveNull is non-zero, that means that the operation is an IN
   95225 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
   95226 ** All this routine does is initialize the register given by rMayHaveNull
   95227 ** to NULL.  Calling routines will take care of changing this register
   95228 ** value to non-NULL if the RHS is NULL-free.
   95229 **
   95230 ** For a SELECT or EXISTS operator, return the register that holds the
   95231 ** result.  For a multi-column SELECT, the result is stored in a contiguous
   95232 ** array of registers and the return value is the register of the left-most
   95233 ** result column.  Return 0 for IN operators or if an error occurs.
   95234 */
   95235 #ifndef SQLITE_OMIT_SUBQUERY
   95236 SQLITE_PRIVATE int sqlite3CodeSubselect(
   95237   Parse *pParse,          /* Parsing context */
   95238   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
   95239   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
   95240   int isRowid             /* If true, LHS of IN operator is a rowid */
   95241 ){
   95242   int jmpIfDynamic = -1;                      /* One-time test address */
   95243   int rReg = 0;                           /* Register storing resulting */
   95244   Vdbe *v = sqlite3GetVdbe(pParse);
   95245   if( NEVER(v==0) ) return 0;
   95246   sqlite3ExprCachePush(pParse);
   95247 
   95248   /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
   95249   ** is encountered if any of the following is true:
   95250   **
   95251   **    *  The right-hand side is a correlated subquery
   95252   **    *  The right-hand side is an expression list containing variables
   95253   **    *  We are inside a trigger
   95254   **
   95255   ** If all of the above are false, then we can run this code just once
   95256   ** save the results, and reuse the same result on subsequent invocations.
   95257   */
   95258   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
   95259     jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   95260   }
   95261 
   95262 #ifndef SQLITE_OMIT_EXPLAIN
   95263   if( pParse->explain==2 ){
   95264     char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
   95265         jmpIfDynamic>=0?"":"CORRELATED ",
   95266         pExpr->op==TK_IN?"LIST":"SCALAR",
   95267         pParse->iNextSelectId
   95268     );
   95269     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   95270   }
   95271 #endif
   95272 
   95273   switch( pExpr->op ){
   95274     case TK_IN: {
   95275       int addr;                   /* Address of OP_OpenEphemeral instruction */
   95276       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
   95277       KeyInfo *pKeyInfo = 0;      /* Key information */
   95278       int nVal;                   /* Size of vector pLeft */
   95279 
   95280       nVal = sqlite3ExprVectorSize(pLeft);
   95281       assert( !isRowid || nVal==1 );
   95282 
   95283       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
   95284       ** expression it is handled the same way.  An ephemeral table is
   95285       ** filled with index keys representing the results from the
   95286       ** SELECT or the <exprlist>.
   95287       **
   95288       ** If the 'x' expression is a column value, or the SELECT...
   95289       ** statement returns a column value, then the affinity of that
   95290       ** column is used to build the index keys. If both 'x' and the
   95291       ** SELECT... statement are columns, then numeric affinity is used
   95292       ** if either column has NUMERIC or INTEGER affinity. If neither
   95293       ** 'x' nor the SELECT... statement are columns, then numeric affinity
   95294       ** is used.
   95295       */
   95296       pExpr->iTable = pParse->nTab++;
   95297       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
   95298           pExpr->iTable, (isRowid?0:nVal));
   95299       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
   95300 
   95301       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   95302         /* Case 1:     expr IN (SELECT ...)
   95303         **
   95304         ** Generate code to write the results of the select into the temporary
   95305         ** table allocated and opened above.
   95306         */
   95307         Select *pSelect = pExpr->x.pSelect;
   95308         ExprList *pEList = pSelect->pEList;
   95309 
   95310         assert( !isRowid );
   95311         /* If the LHS and RHS of the IN operator do not match, that
   95312         ** error will have been caught long before we reach this point. */
   95313         if( ALWAYS(pEList->nExpr==nVal) ){
   95314           SelectDest dest;
   95315           int i;
   95316           sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
   95317           dest.zAffSdst = exprINAffinity(pParse, pExpr);
   95318           pSelect->iLimit = 0;
   95319           testcase( pSelect->selFlags & SF_Distinct );
   95320           testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
   95321           if( sqlite3Select(pParse, pSelect, &dest) ){
   95322             sqlite3DbFree(pParse->db, dest.zAffSdst);
   95323             sqlite3KeyInfoUnref(pKeyInfo);
   95324             return 0;
   95325           }
   95326           sqlite3DbFree(pParse->db, dest.zAffSdst);
   95327           assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
   95328           assert( pEList!=0 );
   95329           assert( pEList->nExpr>0 );
   95330           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
   95331           for(i=0; i<nVal; i++){
   95332             Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
   95333             pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
   95334                 pParse, p, pEList->a[i].pExpr
   95335             );
   95336           }
   95337         }
   95338       }else if( ALWAYS(pExpr->x.pList!=0) ){
   95339         /* Case 2:     expr IN (exprlist)
   95340         **
   95341         ** For each expression, build an index key from the evaluation and
   95342         ** store it in the temporary table. If <expr> is a column, then use
   95343         ** that columns affinity when building index keys. If <expr> is not
   95344         ** a column, use numeric affinity.
   95345         */
   95346         char affinity;            /* Affinity of the LHS of the IN */
   95347         int i;
   95348         ExprList *pList = pExpr->x.pList;
   95349         struct ExprList_item *pItem;
   95350         int r1, r2, r3;
   95351 
   95352         affinity = sqlite3ExprAffinity(pLeft);
   95353         if( !affinity ){
   95354           affinity = SQLITE_AFF_BLOB;
   95355         }
   95356         if( pKeyInfo ){
   95357           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
   95358           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   95359         }
   95360 
   95361         /* Loop through each expression in <exprlist>. */
   95362         r1 = sqlite3GetTempReg(pParse);
   95363         r2 = sqlite3GetTempReg(pParse);
   95364         if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
   95365         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
   95366           Expr *pE2 = pItem->pExpr;
   95367           int iValToIns;
   95368 
   95369           /* If the expression is not constant then we will need to
   95370           ** disable the test that was generated above that makes sure
   95371           ** this code only executes once.  Because for a non-constant
   95372           ** expression we need to rerun this code each time.
   95373           */
   95374           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
   95375             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
   95376             jmpIfDynamic = -1;
   95377           }
   95378 
   95379           /* Evaluate the expression and insert it into the temp table */
   95380           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
   95381             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
   95382           }else{
   95383             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
   95384             if( isRowid ){
   95385               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
   95386                                 sqlite3VdbeCurrentAddr(v)+2);
   95387               VdbeCoverage(v);
   95388               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
   95389             }else{
   95390               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
   95391               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
   95392               sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
   95393             }
   95394           }
   95395         }
   95396         sqlite3ReleaseTempReg(pParse, r1);
   95397         sqlite3ReleaseTempReg(pParse, r2);
   95398       }
   95399       if( pKeyInfo ){
   95400         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
   95401       }
   95402       break;
   95403     }
   95404 
   95405     case TK_EXISTS:
   95406     case TK_SELECT:
   95407     default: {
   95408       /* Case 3:    (SELECT ... FROM ...)
   95409       **     or:    EXISTS(SELECT ... FROM ...)
   95410       **
   95411       ** For a SELECT, generate code to put the values for all columns of
   95412       ** the first row into an array of registers and return the index of
   95413       ** the first register.
   95414       **
   95415       ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
   95416       ** into a register and return that register number.
   95417       **
   95418       ** In both cases, the query is augmented with "LIMIT 1".  Any
   95419       ** preexisting limit is discarded in place of the new LIMIT 1.
   95420       */
   95421       Select *pSel;                         /* SELECT statement to encode */
   95422       SelectDest dest;                      /* How to deal with SELECT result */
   95423       int nReg;                             /* Registers to allocate */
   95424       Expr *pLimit;                         /* New limit expression */
   95425 
   95426       testcase( pExpr->op==TK_EXISTS );
   95427       testcase( pExpr->op==TK_SELECT );
   95428       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
   95429       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   95430 
   95431       pSel = pExpr->x.pSelect;
   95432       nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
   95433       sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
   95434       pParse->nMem += nReg;
   95435       if( pExpr->op==TK_SELECT ){
   95436         dest.eDest = SRT_Mem;
   95437         dest.iSdst = dest.iSDParm;
   95438         dest.nSdst = nReg;
   95439         sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
   95440         VdbeComment((v, "Init subquery result"));
   95441       }else{
   95442         dest.eDest = SRT_Exists;
   95443         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
   95444         VdbeComment((v, "Init EXISTS result"));
   95445       }
   95446       pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
   95447       if( pSel->pLimit ){
   95448         sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
   95449         pSel->pLimit->pLeft = pLimit;
   95450       }else{
   95451         pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
   95452       }
   95453       pSel->iLimit = 0;
   95454       if( sqlite3Select(pParse, pSel, &dest) ){
   95455         return 0;
   95456       }
   95457       rReg = dest.iSDParm;
   95458       ExprSetVVAProperty(pExpr, EP_NoReduce);
   95459       break;
   95460     }
   95461   }
   95462 
   95463   if( rHasNullFlag ){
   95464     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
   95465   }
   95466 
   95467   if( jmpIfDynamic>=0 ){
   95468     sqlite3VdbeJumpHere(v, jmpIfDynamic);
   95469   }
   95470   sqlite3ExprCachePop(pParse);
   95471 
   95472   return rReg;
   95473 }
   95474 #endif /* SQLITE_OMIT_SUBQUERY */
   95475 
   95476 #ifndef SQLITE_OMIT_SUBQUERY
   95477 /*
   95478 ** Expr pIn is an IN(...) expression. This function checks that the
   95479 ** sub-select on the RHS of the IN() operator has the same number of
   95480 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
   95481 ** a sub-query, that the LHS is a vector of size 1.
   95482 */
   95483 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
   95484   int nVector = sqlite3ExprVectorSize(pIn->pLeft);
   95485   if( (pIn->flags & EP_xIsSelect) ){
   95486     if( nVector!=pIn->x.pSelect->pEList->nExpr ){
   95487       sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
   95488       return 1;
   95489     }
   95490   }else if( nVector!=1 ){
   95491     sqlite3VectorErrorMsg(pParse, pIn->pLeft);
   95492     return 1;
   95493   }
   95494   return 0;
   95495 }
   95496 #endif
   95497 
   95498 #ifndef SQLITE_OMIT_SUBQUERY
   95499 /*
   95500 ** Generate code for an IN expression.
   95501 **
   95502 **      x IN (SELECT ...)
   95503 **      x IN (value, value, ...)
   95504 **
   95505 ** The left-hand side (LHS) is a scalar or vector expression.  The
   95506 ** right-hand side (RHS) is an array of zero or more scalar values, or a
   95507 ** subquery.  If the RHS is a subquery, the number of result columns must
   95508 ** match the number of columns in the vector on the LHS.  If the RHS is
   95509 ** a list of values, the LHS must be a scalar.
   95510 **
   95511 ** The IN operator is true if the LHS value is contained within the RHS.
   95512 ** The result is false if the LHS is definitely not in the RHS.  The
   95513 ** result is NULL if the presence of the LHS in the RHS cannot be
   95514 ** determined due to NULLs.
   95515 **
   95516 ** This routine generates code that jumps to destIfFalse if the LHS is not
   95517 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
   95518 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
   95519 ** within the RHS then fall through.
   95520 **
   95521 ** See the separate in-operator.md documentation file in the canonical
   95522 ** SQLite source tree for additional information.
   95523 */
   95524 static void sqlite3ExprCodeIN(
   95525   Parse *pParse,        /* Parsing and code generating context */
   95526   Expr *pExpr,          /* The IN expression */
   95527   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
   95528   int destIfNull        /* Jump here if the results are unknown due to NULLs */
   95529 ){
   95530   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
   95531   int eType;            /* Type of the RHS */
   95532   int rLhs;             /* Register(s) holding the LHS values */
   95533   int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
   95534   Vdbe *v;              /* Statement under construction */
   95535   int *aiMap = 0;       /* Map from vector field to index column */
   95536   char *zAff = 0;       /* Affinity string for comparisons */
   95537   int nVector;          /* Size of vectors for this IN operator */
   95538   int iDummy;           /* Dummy parameter to exprCodeVector() */
   95539   Expr *pLeft;          /* The LHS of the IN operator */
   95540   int i;                /* loop counter */
   95541   int destStep2;        /* Where to jump when NULLs seen in step 2 */
   95542   int destStep6 = 0;    /* Start of code for Step 6 */
   95543   int addrTruthOp;      /* Address of opcode that determines the IN is true */
   95544   int destNotNull;      /* Jump here if a comparison is not true in step 6 */
   95545   int addrTop;          /* Top of the step-6 loop */
   95546 
   95547   pLeft = pExpr->pLeft;
   95548   if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
   95549   zAff = exprINAffinity(pParse, pExpr);
   95550   nVector = sqlite3ExprVectorSize(pExpr->pLeft);
   95551   aiMap = (int*)sqlite3DbMallocZero(
   95552       pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
   95553   );
   95554   if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
   95555 
   95556   /* Attempt to compute the RHS. After this step, if anything other than
   95557   ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
   95558   ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
   95559   ** the RHS has not yet been coded.  */
   95560   v = pParse->pVdbe;
   95561   assert( v!=0 );       /* OOM detected prior to this routine */
   95562   VdbeNoopComment((v, "begin IN expr"));
   95563   eType = sqlite3FindInIndex(pParse, pExpr,
   95564                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
   95565                              destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
   95566 
   95567   assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
   95568        || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
   95569   );
   95570 #ifdef SQLITE_DEBUG
   95571   /* Confirm that aiMap[] contains nVector integer values between 0 and
   95572   ** nVector-1. */
   95573   for(i=0; i<nVector; i++){
   95574     int j, cnt;
   95575     for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
   95576     assert( cnt==1 );
   95577   }
   95578 #endif
   95579 
   95580   /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
   95581   ** vector, then it is stored in an array of nVector registers starting
   95582   ** at r1.
   95583   **
   95584   ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
   95585   ** so that the fields are in the same order as an existing index.   The
   95586   ** aiMap[] array contains a mapping from the original LHS field order to
   95587   ** the field order that matches the RHS index.
   95588   */
   95589   sqlite3ExprCachePush(pParse);
   95590   rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
   95591   for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
   95592   if( i==nVector ){
   95593     /* LHS fields are not reordered */
   95594     rLhs = rLhsOrig;
   95595   }else{
   95596     /* Need to reorder the LHS fields according to aiMap */
   95597     rLhs = sqlite3GetTempRange(pParse, nVector);
   95598     for(i=0; i<nVector; i++){
   95599       sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
   95600     }
   95601   }
   95602 
   95603   /* If sqlite3FindInIndex() did not find or create an index that is
   95604   ** suitable for evaluating the IN operator, then evaluate using a
   95605   ** sequence of comparisons.
   95606   **
   95607   ** This is step (1) in the in-operator.md optimized algorithm.
   95608   */
   95609   if( eType==IN_INDEX_NOOP ){
   95610     ExprList *pList = pExpr->x.pList;
   95611     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   95612     int labelOk = sqlite3VdbeMakeLabel(v);
   95613     int r2, regToFree;
   95614     int regCkNull = 0;
   95615     int ii;
   95616     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   95617     if( destIfNull!=destIfFalse ){
   95618       regCkNull = sqlite3GetTempReg(pParse);
   95619       sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
   95620     }
   95621     for(ii=0; ii<pList->nExpr; ii++){
   95622       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
   95623       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
   95624         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
   95625       }
   95626       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
   95627         sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
   95628                           (void*)pColl, P4_COLLSEQ);
   95629         VdbeCoverageIf(v, ii<pList->nExpr-1);
   95630         VdbeCoverageIf(v, ii==pList->nExpr-1);
   95631         sqlite3VdbeChangeP5(v, zAff[0]);
   95632       }else{
   95633         assert( destIfNull==destIfFalse );
   95634         sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
   95635                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
   95636         sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
   95637       }
   95638       sqlite3ReleaseTempReg(pParse, regToFree);
   95639     }
   95640     if( regCkNull ){
   95641       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
   95642       sqlite3VdbeGoto(v, destIfFalse);
   95643     }
   95644     sqlite3VdbeResolveLabel(v, labelOk);
   95645     sqlite3ReleaseTempReg(pParse, regCkNull);
   95646     goto sqlite3ExprCodeIN_finished;
   95647   }
   95648 
   95649   /* Step 2: Check to see if the LHS contains any NULL columns.  If the
   95650   ** LHS does contain NULLs then the result must be either FALSE or NULL.
   95651   ** We will then skip the binary search of the RHS.
   95652   */
   95653   if( destIfNull==destIfFalse ){
   95654     destStep2 = destIfFalse;
   95655   }else{
   95656     destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
   95657   }
   95658   for(i=0; i<nVector; i++){
   95659     Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
   95660     if( sqlite3ExprCanBeNull(p) ){
   95661       sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
   95662       VdbeCoverage(v);
   95663     }
   95664   }
   95665 
   95666   /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
   95667   ** of the RHS using the LHS as a probe.  If found, the result is
   95668   ** true.
   95669   */
   95670   if( eType==IN_INDEX_ROWID ){
   95671     /* In this case, the RHS is the ROWID of table b-tree and so we also
   95672     ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
   95673     ** into a single opcode. */
   95674     sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
   95675     VdbeCoverage(v);
   95676     addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
   95677   }else{
   95678     sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
   95679     if( destIfFalse==destIfNull ){
   95680       /* Combine Step 3 and Step 5 into a single opcode */
   95681       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
   95682                            rLhs, nVector); VdbeCoverage(v);
   95683       goto sqlite3ExprCodeIN_finished;
   95684     }
   95685     /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
   95686     addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
   95687                                       rLhs, nVector); VdbeCoverage(v);
   95688   }
   95689 
   95690   /* Step 4.  If the RHS is known to be non-NULL and we did not find
   95691   ** an match on the search above, then the result must be FALSE.
   95692   */
   95693   if( rRhsHasNull && nVector==1 ){
   95694     sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
   95695     VdbeCoverage(v);
   95696   }
   95697 
   95698   /* Step 5.  If we do not care about the difference between NULL and
   95699   ** FALSE, then just return false.
   95700   */
   95701   if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
   95702 
   95703   /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
   95704   ** If any comparison is NULL, then the result is NULL.  If all
   95705   ** comparisons are FALSE then the final result is FALSE.
   95706   **
   95707   ** For a scalar LHS, it is sufficient to check just the first row
   95708   ** of the RHS.
   95709   */
   95710   if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
   95711   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
   95712   VdbeCoverage(v);
   95713   if( nVector>1 ){
   95714     destNotNull = sqlite3VdbeMakeLabel(v);
   95715   }else{
   95716     /* For nVector==1, combine steps 6 and 7 by immediately returning
   95717     ** FALSE if the first comparison is not NULL */
   95718     destNotNull = destIfFalse;
   95719   }
   95720   for(i=0; i<nVector; i++){
   95721     Expr *p;
   95722     CollSeq *pColl;
   95723     int r3 = sqlite3GetTempReg(pParse);
   95724     p = sqlite3VectorFieldSubexpr(pLeft, i);
   95725     pColl = sqlite3ExprCollSeq(pParse, p);
   95726     sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
   95727     sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
   95728                       (void*)pColl, P4_COLLSEQ);
   95729     VdbeCoverage(v);
   95730     sqlite3ReleaseTempReg(pParse, r3);
   95731   }
   95732   sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
   95733   if( nVector>1 ){
   95734     sqlite3VdbeResolveLabel(v, destNotNull);
   95735     sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
   95736     VdbeCoverage(v);
   95737 
   95738     /* Step 7:  If we reach this point, we know that the result must
   95739     ** be false. */
   95740     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   95741   }
   95742 
   95743   /* Jumps here in order to return true. */
   95744   sqlite3VdbeJumpHere(v, addrTruthOp);
   95745 
   95746 sqlite3ExprCodeIN_finished:
   95747   if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
   95748   sqlite3ExprCachePop(pParse);
   95749   VdbeComment((v, "end IN expr"));
   95750 sqlite3ExprCodeIN_oom_error:
   95751   sqlite3DbFree(pParse->db, aiMap);
   95752   sqlite3DbFree(pParse->db, zAff);
   95753 }
   95754 #endif /* SQLITE_OMIT_SUBQUERY */
   95755 
   95756 #ifndef SQLITE_OMIT_FLOATING_POINT
   95757 /*
   95758 ** Generate an instruction that will put the floating point
   95759 ** value described by z[0..n-1] into register iMem.
   95760 **
   95761 ** The z[] string will probably not be zero-terminated.  But the
   95762 ** z[n] character is guaranteed to be something that does not look
   95763 ** like the continuation of the number.
   95764 */
   95765 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
   95766   if( ALWAYS(z!=0) ){
   95767     double value;
   95768     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   95769     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
   95770     if( negateFlag ) value = -value;
   95771     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
   95772   }
   95773 }
   95774 #endif
   95775 
   95776 
   95777 /*
   95778 ** Generate an instruction that will put the integer describe by
   95779 ** text z[0..n-1] into register iMem.
   95780 **
   95781 ** Expr.u.zToken is always UTF8 and zero-terminated.
   95782 */
   95783 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
   95784   Vdbe *v = pParse->pVdbe;
   95785   if( pExpr->flags & EP_IntValue ){
   95786     int i = pExpr->u.iValue;
   95787     assert( i>=0 );
   95788     if( negFlag ) i = -i;
   95789     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
   95790   }else{
   95791     int c;
   95792     i64 value;
   95793     const char *z = pExpr->u.zToken;
   95794     assert( z!=0 );
   95795     c = sqlite3DecOrHexToI64(z, &value);
   95796     if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
   95797 #ifdef SQLITE_OMIT_FLOATING_POINT
   95798       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
   95799 #else
   95800 #ifndef SQLITE_OMIT_HEX_INTEGER
   95801       if( sqlite3_strnicmp(z,"0x",2)==0 ){
   95802         sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
   95803       }else
   95804 #endif
   95805       {
   95806         codeReal(v, z, negFlag, iMem);
   95807       }
   95808 #endif
   95809     }else{
   95810       if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
   95811       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
   95812     }
   95813   }
   95814 }
   95815 
   95816 /*
   95817 ** Erase column-cache entry number i
   95818 */
   95819 static void cacheEntryClear(Parse *pParse, int i){
   95820   if( pParse->aColCache[i].tempReg ){
   95821     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   95822       pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
   95823     }
   95824   }
   95825   pParse->nColCache--;
   95826   if( i<pParse->nColCache ){
   95827     pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
   95828   }
   95829 }
   95830 
   95831 
   95832 /*
   95833 ** Record in the column cache that a particular column from a
   95834 ** particular table is stored in a particular register.
   95835 */
   95836 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
   95837   int i;
   95838   int minLru;
   95839   int idxLru;
   95840   struct yColCache *p;
   95841 
   95842   /* Unless an error has occurred, register numbers are always positive. */
   95843   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
   95844   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
   95845 
   95846   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
   95847   ** for testing only - to verify that SQLite always gets the same answer
   95848   ** with and without the column cache.
   95849   */
   95850   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
   95851 
   95852   /* First replace any existing entry.
   95853   **
   95854   ** Actually, the way the column cache is currently used, we are guaranteed
   95855   ** that the object will never already be in cache.  Verify this guarantee.
   95856   */
   95857 #ifndef NDEBUG
   95858   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
   95859     assert( p->iTable!=iTab || p->iColumn!=iCol );
   95860   }
   95861 #endif
   95862 
   95863   /* If the cache is already full, delete the least recently used entry */
   95864   if( pParse->nColCache>=SQLITE_N_COLCACHE ){
   95865     minLru = 0x7fffffff;
   95866     idxLru = -1;
   95867     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   95868       if( p->lru<minLru ){
   95869         idxLru = i;
   95870         minLru = p->lru;
   95871       }
   95872     }
   95873     p = &pParse->aColCache[idxLru];
   95874   }else{
   95875     p = &pParse->aColCache[pParse->nColCache++];
   95876   }
   95877 
   95878   /* Add the new entry to the end of the cache */
   95879   p->iLevel = pParse->iCacheLevel;
   95880   p->iTable = iTab;
   95881   p->iColumn = iCol;
   95882   p->iReg = iReg;
   95883   p->tempReg = 0;
   95884   p->lru = pParse->iCacheCnt++;
   95885 }
   95886 
   95887 /*
   95888 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
   95889 ** Purge the range of registers from the column cache.
   95890 */
   95891 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
   95892   int i = 0;
   95893   while( i<pParse->nColCache ){
   95894     struct yColCache *p = &pParse->aColCache[i];
   95895     if( p->iReg >= iReg && p->iReg < iReg+nReg ){
   95896       cacheEntryClear(pParse, i);
   95897     }else{
   95898       i++;
   95899     }
   95900   }
   95901 }
   95902 
   95903 /*
   95904 ** Remember the current column cache context.  Any new entries added
   95905 ** added to the column cache after this call are removed when the
   95906 ** corresponding pop occurs.
   95907 */
   95908 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
   95909   pParse->iCacheLevel++;
   95910 #ifdef SQLITE_DEBUG
   95911   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   95912     printf("PUSH to %d\n", pParse->iCacheLevel);
   95913   }
   95914 #endif
   95915 }
   95916 
   95917 /*
   95918 ** Remove from the column cache any entries that were added since the
   95919 ** the previous sqlite3ExprCachePush operation.  In other words, restore
   95920 ** the cache to the state it was in prior the most recent Push.
   95921 */
   95922 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
   95923   int i = 0;
   95924   assert( pParse->iCacheLevel>=1 );
   95925   pParse->iCacheLevel--;
   95926 #ifdef SQLITE_DEBUG
   95927   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   95928     printf("POP  to %d\n", pParse->iCacheLevel);
   95929   }
   95930 #endif
   95931   while( i<pParse->nColCache ){
   95932     if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
   95933       cacheEntryClear(pParse, i);
   95934     }else{
   95935       i++;
   95936     }
   95937   }
   95938 }
   95939 
   95940 /*
   95941 ** When a cached column is reused, make sure that its register is
   95942 ** no longer available as a temp register.  ticket #3879:  that same
   95943 ** register might be in the cache in multiple places, so be sure to
   95944 ** get them all.
   95945 */
   95946 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
   95947   int i;
   95948   struct yColCache *p;
   95949   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
   95950     if( p->iReg==iReg ){
   95951       p->tempReg = 0;
   95952     }
   95953   }
   95954 }
   95955 
   95956 /* Generate code that will load into register regOut a value that is
   95957 ** appropriate for the iIdxCol-th column of index pIdx.
   95958 */
   95959 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
   95960   Parse *pParse,  /* The parsing context */
   95961   Index *pIdx,    /* The index whose column is to be loaded */
   95962   int iTabCur,    /* Cursor pointing to a table row */
   95963   int iIdxCol,    /* The column of the index to be loaded */
   95964   int regOut      /* Store the index column value in this register */
   95965 ){
   95966   i16 iTabCol = pIdx->aiColumn[iIdxCol];
   95967   if( iTabCol==XN_EXPR ){
   95968     assert( pIdx->aColExpr );
   95969     assert( pIdx->aColExpr->nExpr>iIdxCol );
   95970     pParse->iSelfTab = iTabCur + 1;
   95971     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
   95972     pParse->iSelfTab = 0;
   95973   }else{
   95974     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
   95975                                     iTabCol, regOut);
   95976   }
   95977 }
   95978 
   95979 /*
   95980 ** Generate code to extract the value of the iCol-th column of a table.
   95981 */
   95982 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
   95983   Vdbe *v,        /* The VDBE under construction */
   95984   Table *pTab,    /* The table containing the value */
   95985   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
   95986   int iCol,       /* Index of the column to extract */
   95987   int regOut      /* Extract the value into this register */
   95988 ){
   95989   if( pTab==0 ){
   95990     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
   95991     return;
   95992   }
   95993   if( iCol<0 || iCol==pTab->iPKey ){
   95994     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
   95995   }else{
   95996     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
   95997     int x = iCol;
   95998     if( !HasRowid(pTab) && !IsVirtual(pTab) ){
   95999       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
   96000     }
   96001     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
   96002   }
   96003   if( iCol>=0 ){
   96004     sqlite3ColumnDefault(v, pTab, iCol, regOut);
   96005   }
   96006 }
   96007 
   96008 /*
   96009 ** Generate code that will extract the iColumn-th column from
   96010 ** table pTab and store the column value in a register.
   96011 **
   96012 ** An effort is made to store the column value in register iReg.  This
   96013 ** is not garanteeed for GetColumn() - the result can be stored in
   96014 ** any register.  But the result is guaranteed to land in register iReg
   96015 ** for GetColumnToReg().
   96016 **
   96017 ** There must be an open cursor to pTab in iTable when this routine
   96018 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
   96019 */
   96020 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   96021   Parse *pParse,   /* Parsing and code generating context */
   96022   Table *pTab,     /* Description of the table we are reading from */
   96023   int iColumn,     /* Index of the table column */
   96024   int iTable,      /* The cursor pointing to the table */
   96025   int iReg,        /* Store results here */
   96026   u8 p5            /* P5 value for OP_Column + FLAGS */
   96027 ){
   96028   Vdbe *v = pParse->pVdbe;
   96029   int i;
   96030   struct yColCache *p;
   96031 
   96032   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
   96033     if( p->iTable==iTable && p->iColumn==iColumn ){
   96034       p->lru = pParse->iCacheCnt++;
   96035       sqlite3ExprCachePinRegister(pParse, p->iReg);
   96036       return p->iReg;
   96037     }
   96038   }
   96039   assert( v!=0 );
   96040   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
   96041   if( p5 ){
   96042     sqlite3VdbeChangeP5(v, p5);
   96043   }else{
   96044     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
   96045   }
   96046   return iReg;
   96047 }
   96048 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
   96049   Parse *pParse,   /* Parsing and code generating context */
   96050   Table *pTab,     /* Description of the table we are reading from */
   96051   int iColumn,     /* Index of the table column */
   96052   int iTable,      /* The cursor pointing to the table */
   96053   int iReg         /* Store results here */
   96054 ){
   96055   int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
   96056   if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
   96057 }
   96058 
   96059 
   96060 /*
   96061 ** Clear all column cache entries.
   96062 */
   96063 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
   96064   int i;
   96065 
   96066 #ifdef SQLITE_DEBUG
   96067   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
   96068     printf("CLEAR\n");
   96069   }
   96070 #endif
   96071   for(i=0; i<pParse->nColCache; i++){
   96072     if( pParse->aColCache[i].tempReg
   96073      && pParse->nTempReg<ArraySize(pParse->aTempReg)
   96074     ){
   96075        pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
   96076     }
   96077   }
   96078   pParse->nColCache = 0;
   96079 }
   96080 
   96081 /*
   96082 ** Record the fact that an affinity change has occurred on iCount
   96083 ** registers starting with iStart.
   96084 */
   96085 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
   96086   sqlite3ExprCacheRemove(pParse, iStart, iCount);
   96087 }
   96088 
   96089 /*
   96090 ** Generate code to move content from registers iFrom...iFrom+nReg-1
   96091 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
   96092 */
   96093 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
   96094   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
   96095   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
   96096   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
   96097 }
   96098 
   96099 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   96100 /*
   96101 ** Return true if any register in the range iFrom..iTo (inclusive)
   96102 ** is used as part of the column cache.
   96103 **
   96104 ** This routine is used within assert() and testcase() macros only
   96105 ** and does not appear in a normal build.
   96106 */
   96107 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
   96108   int i;
   96109   struct yColCache *p;
   96110   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
   96111     int r = p->iReg;
   96112     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
   96113   }
   96114   return 0;
   96115 }
   96116 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
   96117 
   96118 
   96119 /*
   96120 ** Convert a scalar expression node to a TK_REGISTER referencing
   96121 ** register iReg.  The caller must ensure that iReg already contains
   96122 ** the correct value for the expression.
   96123 */
   96124 static void exprToRegister(Expr *p, int iReg){
   96125   p->op2 = p->op;
   96126   p->op = TK_REGISTER;
   96127   p->iTable = iReg;
   96128   ExprClearProperty(p, EP_Skip);
   96129 }
   96130 
   96131 /*
   96132 ** Evaluate an expression (either a vector or a scalar expression) and store
   96133 ** the result in continguous temporary registers.  Return the index of
   96134 ** the first register used to store the result.
   96135 **
   96136 ** If the returned result register is a temporary scalar, then also write
   96137 ** that register number into *piFreeable.  If the returned result register
   96138 ** is not a temporary or if the expression is a vector set *piFreeable
   96139 ** to 0.
   96140 */
   96141 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
   96142   int iResult;
   96143   int nResult = sqlite3ExprVectorSize(p);
   96144   if( nResult==1 ){
   96145     iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
   96146   }else{
   96147     *piFreeable = 0;
   96148     if( p->op==TK_SELECT ){
   96149 #if SQLITE_OMIT_SUBQUERY
   96150       iResult = 0;
   96151 #else
   96152       iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
   96153 #endif
   96154     }else{
   96155       int i;
   96156       iResult = pParse->nMem+1;
   96157       pParse->nMem += nResult;
   96158       for(i=0; i<nResult; i++){
   96159         sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
   96160       }
   96161     }
   96162   }
   96163   return iResult;
   96164 }
   96165 
   96166 
   96167 /*
   96168 ** Generate code into the current Vdbe to evaluate the given
   96169 ** expression.  Attempt to store the results in register "target".
   96170 ** Return the register where results are stored.
   96171 **
   96172 ** With this routine, there is no guarantee that results will
   96173 ** be stored in target.  The result might be stored in some other
   96174 ** register if it is convenient to do so.  The calling function
   96175 ** must check the return code and move the results to the desired
   96176 ** register.
   96177 */
   96178 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
   96179   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
   96180   int op;                   /* The opcode being coded */
   96181   int inReg = target;       /* Results stored in register inReg */
   96182   int regFree1 = 0;         /* If non-zero free this temporary register */
   96183   int regFree2 = 0;         /* If non-zero free this temporary register */
   96184   int r1, r2;               /* Various register numbers */
   96185   Expr tempX;               /* Temporary expression node */
   96186   int p5 = 0;
   96187 
   96188   assert( target>0 && target<=pParse->nMem );
   96189   if( v==0 ){
   96190     assert( pParse->db->mallocFailed );
   96191     return 0;
   96192   }
   96193 
   96194   if( pExpr==0 ){
   96195     op = TK_NULL;
   96196   }else{
   96197     op = pExpr->op;
   96198   }
   96199   switch( op ){
   96200     case TK_AGG_COLUMN: {
   96201       AggInfo *pAggInfo = pExpr->pAggInfo;
   96202       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
   96203       if( !pAggInfo->directMode ){
   96204         assert( pCol->iMem>0 );
   96205         return pCol->iMem;
   96206       }else if( pAggInfo->useSortingIdx ){
   96207         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
   96208                               pCol->iSorterColumn, target);
   96209         return target;
   96210       }
   96211       /* Otherwise, fall thru into the TK_COLUMN case */
   96212     }
   96213     case TK_COLUMN: {
   96214       int iTab = pExpr->iTable;
   96215       if( iTab<0 ){
   96216         if( pParse->iSelfTab<0 ){
   96217           /* Generating CHECK constraints or inserting into partial index */
   96218           return pExpr->iColumn - pParse->iSelfTab;
   96219         }else{
   96220           /* Coding an expression that is part of an index where column names
   96221           ** in the index refer to the table to which the index belongs */
   96222           iTab = pParse->iSelfTab - 1;
   96223         }
   96224       }
   96225       return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
   96226                                pExpr->iColumn, iTab, target,
   96227                                pExpr->op2);
   96228     }
   96229     case TK_INTEGER: {
   96230       codeInteger(pParse, pExpr, 0, target);
   96231       return target;
   96232     }
   96233 #ifndef SQLITE_OMIT_FLOATING_POINT
   96234     case TK_FLOAT: {
   96235       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96236       codeReal(v, pExpr->u.zToken, 0, target);
   96237       return target;
   96238     }
   96239 #endif
   96240     case TK_STRING: {
   96241       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96242       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
   96243       return target;
   96244     }
   96245     case TK_NULL: {
   96246       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   96247       return target;
   96248     }
   96249 #ifndef SQLITE_OMIT_BLOB_LITERAL
   96250     case TK_BLOB: {
   96251       int n;
   96252       const char *z;
   96253       char *zBlob;
   96254       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96255       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   96256       assert( pExpr->u.zToken[1]=='\'' );
   96257       z = &pExpr->u.zToken[2];
   96258       n = sqlite3Strlen30(z) - 1;
   96259       assert( z[n]=='\'' );
   96260       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
   96261       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
   96262       return target;
   96263     }
   96264 #endif
   96265     case TK_VARIABLE: {
   96266       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96267       assert( pExpr->u.zToken!=0 );
   96268       assert( pExpr->u.zToken[0]!=0 );
   96269       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
   96270       if( pExpr->u.zToken[1]!=0 ){
   96271         const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
   96272         assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
   96273         pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
   96274         sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
   96275       }
   96276       return target;
   96277     }
   96278     case TK_REGISTER: {
   96279       return pExpr->iTable;
   96280     }
   96281 #ifndef SQLITE_OMIT_CAST
   96282     case TK_CAST: {
   96283       /* Expressions of the form:   CAST(pLeft AS token) */
   96284       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   96285       if( inReg!=target ){
   96286         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
   96287         inReg = target;
   96288       }
   96289       sqlite3VdbeAddOp2(v, OP_Cast, target,
   96290                         sqlite3AffinityType(pExpr->u.zToken, 0));
   96291       testcase( usedAsColumnCache(pParse, inReg, inReg) );
   96292       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
   96293       return inReg;
   96294     }
   96295 #endif /* SQLITE_OMIT_CAST */
   96296     case TK_IS:
   96297     case TK_ISNOT:
   96298       op = (op==TK_IS) ? TK_EQ : TK_NE;
   96299       p5 = SQLITE_NULLEQ;
   96300       /* fall-through */
   96301     case TK_LT:
   96302     case TK_LE:
   96303     case TK_GT:
   96304     case TK_GE:
   96305     case TK_NE:
   96306     case TK_EQ: {
   96307       Expr *pLeft = pExpr->pLeft;
   96308       if( sqlite3ExprIsVector(pLeft) ){
   96309         codeVectorCompare(pParse, pExpr, target, op, p5);
   96310       }else{
   96311         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
   96312         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   96313         codeCompare(pParse, pLeft, pExpr->pRight, op,
   96314             r1, r2, inReg, SQLITE_STOREP2 | p5);
   96315         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   96316         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   96317         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   96318         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   96319         assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
   96320         assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
   96321         testcase( regFree1==0 );
   96322         testcase( regFree2==0 );
   96323       }
   96324       break;
   96325     }
   96326     case TK_AND:
   96327     case TK_OR:
   96328     case TK_PLUS:
   96329     case TK_STAR:
   96330     case TK_MINUS:
   96331     case TK_REM:
   96332     case TK_BITAND:
   96333     case TK_BITOR:
   96334     case TK_SLASH:
   96335     case TK_LSHIFT:
   96336     case TK_RSHIFT:
   96337     case TK_CONCAT: {
   96338       assert( TK_AND==OP_And );            testcase( op==TK_AND );
   96339       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
   96340       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
   96341       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
   96342       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
   96343       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
   96344       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
   96345       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
   96346       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
   96347       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
   96348       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
   96349       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   96350       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   96351       sqlite3VdbeAddOp3(v, op, r2, r1, target);
   96352       testcase( regFree1==0 );
   96353       testcase( regFree2==0 );
   96354       break;
   96355     }
   96356     case TK_UMINUS: {
   96357       Expr *pLeft = pExpr->pLeft;
   96358       assert( pLeft );
   96359       if( pLeft->op==TK_INTEGER ){
   96360         codeInteger(pParse, pLeft, 1, target);
   96361         return target;
   96362 #ifndef SQLITE_OMIT_FLOATING_POINT
   96363       }else if( pLeft->op==TK_FLOAT ){
   96364         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96365         codeReal(v, pLeft->u.zToken, 1, target);
   96366         return target;
   96367 #endif
   96368       }else{
   96369         tempX.op = TK_INTEGER;
   96370         tempX.flags = EP_IntValue|EP_TokenOnly;
   96371         tempX.u.iValue = 0;
   96372         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
   96373         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
   96374         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
   96375         testcase( regFree2==0 );
   96376       }
   96377       break;
   96378     }
   96379     case TK_BITNOT:
   96380     case TK_NOT: {
   96381       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
   96382       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
   96383       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   96384       testcase( regFree1==0 );
   96385       sqlite3VdbeAddOp2(v, op, r1, inReg);
   96386       break;
   96387     }
   96388     case TK_ISNULL:
   96389     case TK_NOTNULL: {
   96390       int addr;
   96391       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
   96392       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
   96393       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   96394       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   96395       testcase( regFree1==0 );
   96396       addr = sqlite3VdbeAddOp1(v, op, r1);
   96397       VdbeCoverageIf(v, op==TK_ISNULL);
   96398       VdbeCoverageIf(v, op==TK_NOTNULL);
   96399       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
   96400       sqlite3VdbeJumpHere(v, addr);
   96401       break;
   96402     }
   96403     case TK_AGG_FUNCTION: {
   96404       AggInfo *pInfo = pExpr->pAggInfo;
   96405       if( pInfo==0 ){
   96406         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96407         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
   96408       }else{
   96409         return pInfo->aFunc[pExpr->iAgg].iMem;
   96410       }
   96411       break;
   96412     }
   96413     case TK_FUNCTION: {
   96414       ExprList *pFarg;       /* List of function arguments */
   96415       int nFarg;             /* Number of function arguments */
   96416       FuncDef *pDef;         /* The function definition object */
   96417       const char *zId;       /* The function name */
   96418       u32 constMask = 0;     /* Mask of function arguments that are constant */
   96419       int i;                 /* Loop counter */
   96420       sqlite3 *db = pParse->db;  /* The database connection */
   96421       u8 enc = ENC(db);      /* The text encoding used by this database */
   96422       CollSeq *pColl = 0;    /* A collating sequence */
   96423 
   96424       if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
   96425         /* SQL functions can be expensive. So try to move constant functions
   96426         ** out of the inner loop, even if that means an extra OP_Copy. */
   96427         return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
   96428       }
   96429       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   96430       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
   96431         pFarg = 0;
   96432       }else{
   96433         pFarg = pExpr->x.pList;
   96434       }
   96435       nFarg = pFarg ? pFarg->nExpr : 0;
   96436       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96437       zId = pExpr->u.zToken;
   96438       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
   96439 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
   96440       if( pDef==0 && pParse->explain ){
   96441         pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
   96442       }
   96443 #endif
   96444       if( pDef==0 || pDef->xFinalize!=0 ){
   96445         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
   96446         break;
   96447       }
   96448 
   96449       /* Attempt a direct implementation of the built-in COALESCE() and
   96450       ** IFNULL() functions.  This avoids unnecessary evaluation of
   96451       ** arguments past the first non-NULL argument.
   96452       */
   96453       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
   96454         int endCoalesce = sqlite3VdbeMakeLabel(v);
   96455         assert( nFarg>=2 );
   96456         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   96457         for(i=1; i<nFarg; i++){
   96458           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
   96459           VdbeCoverage(v);
   96460           sqlite3ExprCacheRemove(pParse, target, 1);
   96461           sqlite3ExprCachePush(pParse);
   96462           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
   96463           sqlite3ExprCachePop(pParse);
   96464         }
   96465         sqlite3VdbeResolveLabel(v, endCoalesce);
   96466         break;
   96467       }
   96468 
   96469       /* The UNLIKELY() function is a no-op.  The result is the value
   96470       ** of the first argument.
   96471       */
   96472       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
   96473         assert( nFarg>=1 );
   96474         return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
   96475       }
   96476 
   96477 #ifdef SQLITE_DEBUG
   96478       /* The AFFINITY() function evaluates to a string that describes
   96479       ** the type affinity of the argument.  This is used for testing of
   96480       ** the SQLite type logic.
   96481       */
   96482       if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
   96483         const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
   96484         char aff;
   96485         assert( nFarg==1 );
   96486         aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
   96487         sqlite3VdbeLoadString(v, target,
   96488                               aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
   96489         return target;
   96490       }
   96491 #endif
   96492 
   96493       for(i=0; i<nFarg; i++){
   96494         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
   96495           testcase( i==31 );
   96496           constMask |= MASKBIT32(i);
   96497         }
   96498         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
   96499           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
   96500         }
   96501       }
   96502       if( pFarg ){
   96503         if( constMask ){
   96504           r1 = pParse->nMem+1;
   96505           pParse->nMem += nFarg;
   96506         }else{
   96507           r1 = sqlite3GetTempRange(pParse, nFarg);
   96508         }
   96509 
   96510         /* For length() and typeof() functions with a column argument,
   96511         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
   96512         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
   96513         ** loading.
   96514         */
   96515         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
   96516           u8 exprOp;
   96517           assert( nFarg==1 );
   96518           assert( pFarg->a[0].pExpr!=0 );
   96519           exprOp = pFarg->a[0].pExpr->op;
   96520           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
   96521             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
   96522             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
   96523             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
   96524             pFarg->a[0].pExpr->op2 =
   96525                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
   96526           }
   96527         }
   96528 
   96529         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
   96530         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
   96531                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
   96532         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
   96533       }else{
   96534         r1 = 0;
   96535       }
   96536 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96537       /* Possibly overload the function if the first argument is
   96538       ** a virtual table column.
   96539       **
   96540       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
   96541       ** second argument, not the first, as the argument to test to
   96542       ** see if it is a column in a virtual table.  This is done because
   96543       ** the left operand of infix functions (the operand we want to
   96544       ** control overloading) ends up as the second argument to the
   96545       ** function.  The expression "A glob B" is equivalent to
   96546       ** "glob(B,A).  We want to use the A in "A glob B" to test
   96547       ** for function overloading.  But we use the B term in "glob(B,A)".
   96548       */
   96549       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
   96550         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
   96551       }else if( nFarg>0 ){
   96552         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
   96553       }
   96554 #endif
   96555       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   96556         if( !pColl ) pColl = db->pDfltColl;
   96557         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   96558       }
   96559 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
   96560       if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
   96561         Expr *pArg = pFarg->a[0].pExpr;
   96562         if( pArg->op==TK_COLUMN ){
   96563           sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
   96564         }else{
   96565           sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   96566         }
   96567       }else
   96568 #endif
   96569       {
   96570         sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
   96571                           constMask, r1, target, (char*)pDef, P4_FUNCDEF);
   96572         sqlite3VdbeChangeP5(v, (u8)nFarg);
   96573       }
   96574       if( nFarg && constMask==0 ){
   96575         sqlite3ReleaseTempRange(pParse, r1, nFarg);
   96576       }
   96577       return target;
   96578     }
   96579 #ifndef SQLITE_OMIT_SUBQUERY
   96580     case TK_EXISTS:
   96581     case TK_SELECT: {
   96582       int nCol;
   96583       testcase( op==TK_EXISTS );
   96584       testcase( op==TK_SELECT );
   96585       if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
   96586         sqlite3SubselectError(pParse, nCol, 1);
   96587       }else{
   96588         return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   96589       }
   96590       break;
   96591     }
   96592     case TK_SELECT_COLUMN: {
   96593       int n;
   96594       if( pExpr->pLeft->iTable==0 ){
   96595         pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
   96596       }
   96597       assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
   96598       if( pExpr->iTable
   96599        && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
   96600       ){
   96601         sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
   96602                                 pExpr->iTable, n);
   96603       }
   96604       return pExpr->pLeft->iTable + pExpr->iColumn;
   96605     }
   96606     case TK_IN: {
   96607       int destIfFalse = sqlite3VdbeMakeLabel(v);
   96608       int destIfNull = sqlite3VdbeMakeLabel(v);
   96609       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   96610       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   96611       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   96612       sqlite3VdbeResolveLabel(v, destIfFalse);
   96613       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
   96614       sqlite3VdbeResolveLabel(v, destIfNull);
   96615       return target;
   96616     }
   96617 #endif /* SQLITE_OMIT_SUBQUERY */
   96618 
   96619 
   96620     /*
   96621     **    x BETWEEN y AND z
   96622     **
   96623     ** This is equivalent to
   96624     **
   96625     **    x>=y AND x<=z
   96626     **
   96627     ** X is stored in pExpr->pLeft.
   96628     ** Y is stored in pExpr->pList->a[0].pExpr.
   96629     ** Z is stored in pExpr->pList->a[1].pExpr.
   96630     */
   96631     case TK_BETWEEN: {
   96632       exprCodeBetween(pParse, pExpr, target, 0, 0);
   96633       return target;
   96634     }
   96635     case TK_SPAN:
   96636     case TK_COLLATE:
   96637     case TK_UPLUS: {
   96638       return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   96639     }
   96640 
   96641     case TK_TRIGGER: {
   96642       /* If the opcode is TK_TRIGGER, then the expression is a reference
   96643       ** to a column in the new.* or old.* pseudo-tables available to
   96644       ** trigger programs. In this case Expr.iTable is set to 1 for the
   96645       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   96646       ** is set to the column of the pseudo-table to read, or to -1 to
   96647       ** read the rowid field.
   96648       **
   96649       ** The expression is implemented using an OP_Param opcode. The p1
   96650       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
   96651       ** to reference another column of the old.* pseudo-table, where
   96652       ** i is the index of the column. For a new.rowid reference, p1 is
   96653       ** set to (n+1), where n is the number of columns in each pseudo-table.
   96654       ** For a reference to any other column in the new.* pseudo-table, p1
   96655       ** is set to (n+2+i), where n and i are as defined previously. For
   96656       ** example, if the table on which triggers are being fired is
   96657       ** declared as:
   96658       **
   96659       **   CREATE TABLE t1(a, b);
   96660       **
   96661       ** Then p1 is interpreted as follows:
   96662       **
   96663       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
   96664       **   p1==1   ->    old.a         p1==4   ->    new.a
   96665       **   p1==2   ->    old.b         p1==5   ->    new.b
   96666       */
   96667       Table *pTab = pExpr->pTab;
   96668       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
   96669 
   96670       assert( pExpr->iTable==0 || pExpr->iTable==1 );
   96671       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
   96672       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
   96673       assert( p1>=0 && p1<(pTab->nCol*2+2) );
   96674 
   96675       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
   96676       VdbeComment((v, "%s.%s -> $%d",
   96677         (pExpr->iTable ? "new" : "old"),
   96678         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
   96679         target
   96680       ));
   96681 
   96682 #ifndef SQLITE_OMIT_FLOATING_POINT
   96683       /* If the column has REAL affinity, it may currently be stored as an
   96684       ** integer. Use OP_RealAffinity to make sure it is really real.
   96685       **
   96686       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
   96687       ** floating point when extracting it from the record.  */
   96688       if( pExpr->iColumn>=0
   96689        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
   96690       ){
   96691         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
   96692       }
   96693 #endif
   96694       break;
   96695     }
   96696 
   96697     case TK_VECTOR: {
   96698       sqlite3ErrorMsg(pParse, "row value misused");
   96699       break;
   96700     }
   96701 
   96702     case TK_IF_NULL_ROW: {
   96703       int addrINR;
   96704       addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
   96705       sqlite3ExprCachePush(pParse);
   96706       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   96707       sqlite3ExprCachePop(pParse);
   96708       sqlite3VdbeJumpHere(v, addrINR);
   96709       sqlite3VdbeChangeP3(v, addrINR, inReg);
   96710       break;
   96711     }
   96712 
   96713     /*
   96714     ** Form A:
   96715     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   96716     **
   96717     ** Form B:
   96718     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   96719     **
   96720     ** Form A is can be transformed into the equivalent form B as follows:
   96721     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
   96722     **        WHEN x=eN THEN rN ELSE y END
   96723     **
   96724     ** X (if it exists) is in pExpr->pLeft.
   96725     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
   96726     ** odd.  The Y is also optional.  If the number of elements in x.pList
   96727     ** is even, then Y is omitted and the "otherwise" result is NULL.
   96728     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
   96729     **
   96730     ** The result of the expression is the Ri for the first matching Ei,
   96731     ** or if there is no matching Ei, the ELSE term Y, or if there is
   96732     ** no ELSE term, NULL.
   96733     */
   96734     default: assert( op==TK_CASE ); {
   96735       int endLabel;                     /* GOTO label for end of CASE stmt */
   96736       int nextCase;                     /* GOTO label for next WHEN clause */
   96737       int nExpr;                        /* 2x number of WHEN terms */
   96738       int i;                            /* Loop counter */
   96739       ExprList *pEList;                 /* List of WHEN terms */
   96740       struct ExprList_item *aListelem;  /* Array of WHEN terms */
   96741       Expr opCompare;                   /* The X==Ei expression */
   96742       Expr *pX;                         /* The X expression */
   96743       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
   96744       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
   96745 
   96746       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
   96747       assert(pExpr->x.pList->nExpr > 0);
   96748       pEList = pExpr->x.pList;
   96749       aListelem = pEList->a;
   96750       nExpr = pEList->nExpr;
   96751       endLabel = sqlite3VdbeMakeLabel(v);
   96752       if( (pX = pExpr->pLeft)!=0 ){
   96753         tempX = *pX;
   96754         testcase( pX->op==TK_COLUMN );
   96755         exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
   96756         testcase( regFree1==0 );
   96757         memset(&opCompare, 0, sizeof(opCompare));
   96758         opCompare.op = TK_EQ;
   96759         opCompare.pLeft = &tempX;
   96760         pTest = &opCompare;
   96761         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
   96762         ** The value in regFree1 might get SCopy-ed into the file result.
   96763         ** So make sure that the regFree1 register is not reused for other
   96764         ** purposes and possibly overwritten.  */
   96765         regFree1 = 0;
   96766       }
   96767       for(i=0; i<nExpr-1; i=i+2){
   96768         sqlite3ExprCachePush(pParse);
   96769         if( pX ){
   96770           assert( pTest!=0 );
   96771           opCompare.pRight = aListelem[i].pExpr;
   96772         }else{
   96773           pTest = aListelem[i].pExpr;
   96774         }
   96775         nextCase = sqlite3VdbeMakeLabel(v);
   96776         testcase( pTest->op==TK_COLUMN );
   96777         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
   96778         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
   96779         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
   96780         sqlite3VdbeGoto(v, endLabel);
   96781         sqlite3ExprCachePop(pParse);
   96782         sqlite3VdbeResolveLabel(v, nextCase);
   96783       }
   96784       if( (nExpr&1)!=0 ){
   96785         sqlite3ExprCachePush(pParse);
   96786         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
   96787         sqlite3ExprCachePop(pParse);
   96788       }else{
   96789         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   96790       }
   96791       assert( pParse->db->mallocFailed || pParse->nErr>0
   96792            || pParse->iCacheLevel==iCacheLevel );
   96793       sqlite3VdbeResolveLabel(v, endLabel);
   96794       break;
   96795     }
   96796 #ifndef SQLITE_OMIT_TRIGGER
   96797     case TK_RAISE: {
   96798       assert( pExpr->affinity==OE_Rollback
   96799            || pExpr->affinity==OE_Abort
   96800            || pExpr->affinity==OE_Fail
   96801            || pExpr->affinity==OE_Ignore
   96802       );
   96803       if( !pParse->pTriggerTab ){
   96804         sqlite3ErrorMsg(pParse,
   96805                        "RAISE() may only be used within a trigger-program");
   96806         return 0;
   96807       }
   96808       if( pExpr->affinity==OE_Abort ){
   96809         sqlite3MayAbort(pParse);
   96810       }
   96811       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   96812       if( pExpr->affinity==OE_Ignore ){
   96813         sqlite3VdbeAddOp4(
   96814             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
   96815         VdbeCoverage(v);
   96816       }else{
   96817         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
   96818                               pExpr->affinity, pExpr->u.zToken, 0, 0);
   96819       }
   96820 
   96821       break;
   96822     }
   96823 #endif
   96824   }
   96825   sqlite3ReleaseTempReg(pParse, regFree1);
   96826   sqlite3ReleaseTempReg(pParse, regFree2);
   96827   return inReg;
   96828 }
   96829 
   96830 /*
   96831 ** Factor out the code of the given expression to initialization time.
   96832 **
   96833 ** If regDest>=0 then the result is always stored in that register and the
   96834 ** result is not reusable.  If regDest<0 then this routine is free to
   96835 ** store the value whereever it wants.  The register where the expression
   96836 ** is stored is returned.  When regDest<0, two identical expressions will
   96837 ** code to the same register.
   96838 */
   96839 SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
   96840   Parse *pParse,    /* Parsing context */
   96841   Expr *pExpr,      /* The expression to code when the VDBE initializes */
   96842   int regDest       /* Store the value in this register */
   96843 ){
   96844   ExprList *p;
   96845   assert( ConstFactorOk(pParse) );
   96846   p = pParse->pConstExpr;
   96847   if( regDest<0 && p ){
   96848     struct ExprList_item *pItem;
   96849     int i;
   96850     for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
   96851       if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
   96852         return pItem->u.iConstExprReg;
   96853       }
   96854     }
   96855   }
   96856   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
   96857   p = sqlite3ExprListAppend(pParse, p, pExpr);
   96858   if( p ){
   96859      struct ExprList_item *pItem = &p->a[p->nExpr-1];
   96860      pItem->reusable = regDest<0;
   96861      if( regDest<0 ) regDest = ++pParse->nMem;
   96862      pItem->u.iConstExprReg = regDest;
   96863   }
   96864   pParse->pConstExpr = p;
   96865   return regDest;
   96866 }
   96867 
   96868 /*
   96869 ** Generate code to evaluate an expression and store the results
   96870 ** into a register.  Return the register number where the results
   96871 ** are stored.
   96872 **
   96873 ** If the register is a temporary register that can be deallocated,
   96874 ** then write its number into *pReg.  If the result register is not
   96875 ** a temporary, then set *pReg to zero.
   96876 **
   96877 ** If pExpr is a constant, then this routine might generate this
   96878 ** code to fill the register in the initialization section of the
   96879 ** VDBE program, in order to factor it out of the evaluation loop.
   96880 */
   96881 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   96882   int r2;
   96883   pExpr = sqlite3ExprSkipCollate(pExpr);
   96884   if( ConstFactorOk(pParse)
   96885    && pExpr->op!=TK_REGISTER
   96886    && sqlite3ExprIsConstantNotJoin(pExpr)
   96887   ){
   96888     *pReg  = 0;
   96889     r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
   96890   }else{
   96891     int r1 = sqlite3GetTempReg(pParse);
   96892     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   96893     if( r2==r1 ){
   96894       *pReg = r1;
   96895     }else{
   96896       sqlite3ReleaseTempReg(pParse, r1);
   96897       *pReg = 0;
   96898     }
   96899   }
   96900   return r2;
   96901 }
   96902 
   96903 /*
   96904 ** Generate code that will evaluate expression pExpr and store the
   96905 ** results in register target.  The results are guaranteed to appear
   96906 ** in register target.
   96907 */
   96908 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   96909   int inReg;
   96910 
   96911   assert( target>0 && target<=pParse->nMem );
   96912   if( pExpr && pExpr->op==TK_REGISTER ){
   96913     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
   96914   }else{
   96915     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   96916     assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
   96917     if( inReg!=target && pParse->pVdbe ){
   96918       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
   96919     }
   96920   }
   96921 }
   96922 
   96923 /*
   96924 ** Make a transient copy of expression pExpr and then code it using
   96925 ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
   96926 ** except that the input expression is guaranteed to be unchanged.
   96927 */
   96928 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
   96929   sqlite3 *db = pParse->db;
   96930   pExpr = sqlite3ExprDup(db, pExpr, 0);
   96931   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
   96932   sqlite3ExprDelete(db, pExpr);
   96933 }
   96934 
   96935 /*
   96936 ** Generate code that will evaluate expression pExpr and store the
   96937 ** results in register target.  The results are guaranteed to appear
   96938 ** in register target.  If the expression is constant, then this routine
   96939 ** might choose to code the expression at initialization time.
   96940 */
   96941 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
   96942   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
   96943     sqlite3ExprCodeAtInit(pParse, pExpr, target);
   96944   }else{
   96945     sqlite3ExprCode(pParse, pExpr, target);
   96946   }
   96947 }
   96948 
   96949 /*
   96950 ** Generate code that evaluates the given expression and puts the result
   96951 ** in register target.
   96952 **
   96953 ** Also make a copy of the expression results into another "cache" register
   96954 ** and modify the expression so that the next time it is evaluated,
   96955 ** the result is a copy of the cache register.
   96956 **
   96957 ** This routine is used for expressions that are used multiple
   96958 ** times.  They are evaluated once and the results of the expression
   96959 ** are reused.
   96960 */
   96961 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
   96962   Vdbe *v = pParse->pVdbe;
   96963   int iMem;
   96964 
   96965   assert( target>0 );
   96966   assert( pExpr->op!=TK_REGISTER );
   96967   sqlite3ExprCode(pParse, pExpr, target);
   96968   iMem = ++pParse->nMem;
   96969   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
   96970   exprToRegister(pExpr, iMem);
   96971 }
   96972 
   96973 /*
   96974 ** Generate code that pushes the value of every element of the given
   96975 ** expression list into a sequence of registers beginning at target.
   96976 **
   96977 ** Return the number of elements evaluated.  The number returned will
   96978 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
   96979 ** is defined.
   96980 **
   96981 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
   96982 ** filled using OP_SCopy.  OP_Copy must be used instead.
   96983 **
   96984 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
   96985 ** factored out into initialization code.
   96986 **
   96987 ** The SQLITE_ECEL_REF flag means that expressions in the list with
   96988 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
   96989 ** in registers at srcReg, and so the value can be copied from there.
   96990 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
   96991 ** are simply omitted rather than being copied from srcReg.
   96992 */
   96993 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
   96994   Parse *pParse,     /* Parsing context */
   96995   ExprList *pList,   /* The expression list to be coded */
   96996   int target,        /* Where to write results */
   96997   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
   96998   u8 flags           /* SQLITE_ECEL_* flags */
   96999 ){
   97000   struct ExprList_item *pItem;
   97001   int i, j, n;
   97002   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
   97003   Vdbe *v = pParse->pVdbe;
   97004   assert( pList!=0 );
   97005   assert( target>0 );
   97006   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
   97007   n = pList->nExpr;
   97008   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
   97009   for(pItem=pList->a, i=0; i<n; i++, pItem++){
   97010     Expr *pExpr = pItem->pExpr;
   97011     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
   97012       if( flags & SQLITE_ECEL_OMITREF ){
   97013         i--;
   97014         n--;
   97015       }else{
   97016         sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
   97017       }
   97018     }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
   97019       sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
   97020     }else{
   97021       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
   97022       if( inReg!=target+i ){
   97023         VdbeOp *pOp;
   97024         if( copyOp==OP_Copy
   97025          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
   97026          && pOp->p1+pOp->p3+1==inReg
   97027          && pOp->p2+pOp->p3+1==target+i
   97028         ){
   97029           pOp->p3++;
   97030         }else{
   97031           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
   97032         }
   97033       }
   97034     }
   97035   }
   97036   return n;
   97037 }
   97038 
   97039 /*
   97040 ** Generate code for a BETWEEN operator.
   97041 **
   97042 **    x BETWEEN y AND z
   97043 **
   97044 ** The above is equivalent to
   97045 **
   97046 **    x>=y AND x<=z
   97047 **
   97048 ** Code it as such, taking care to do the common subexpression
   97049 ** elimination of x.
   97050 **
   97051 ** The xJumpIf parameter determines details:
   97052 **
   97053 **    NULL:                   Store the boolean result in reg[dest]
   97054 **    sqlite3ExprIfTrue:      Jump to dest if true
   97055 **    sqlite3ExprIfFalse:     Jump to dest if false
   97056 **
   97057 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
   97058 */
   97059 static void exprCodeBetween(
   97060   Parse *pParse,    /* Parsing and code generating context */
   97061   Expr *pExpr,      /* The BETWEEN expression */
   97062   int dest,         /* Jump destination or storage location */
   97063   void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
   97064   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
   97065 ){
   97066  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
   97067   Expr compLeft;    /* The  x>=y  term */
   97068   Expr compRight;   /* The  x<=z  term */
   97069   Expr exprX;       /* The  x  subexpression */
   97070   int regFree1 = 0; /* Temporary use register */
   97071 
   97072 
   97073   memset(&compLeft, 0, sizeof(Expr));
   97074   memset(&compRight, 0, sizeof(Expr));
   97075   memset(&exprAnd, 0, sizeof(Expr));
   97076 
   97077   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   97078   exprX = *pExpr->pLeft;
   97079   exprAnd.op = TK_AND;
   97080   exprAnd.pLeft = &compLeft;
   97081   exprAnd.pRight = &compRight;
   97082   compLeft.op = TK_GE;
   97083   compLeft.pLeft = &exprX;
   97084   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
   97085   compRight.op = TK_LE;
   97086   compRight.pLeft = &exprX;
   97087   compRight.pRight = pExpr->x.pList->a[1].pExpr;
   97088   exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
   97089   if( xJump ){
   97090     xJump(pParse, &exprAnd, dest, jumpIfNull);
   97091   }else{
   97092     /* Mark the expression is being from the ON or USING clause of a join
   97093     ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
   97094     ** it into the Parse.pConstExpr list.  We should use a new bit for this,
   97095     ** for clarity, but we are out of bits in the Expr.flags field so we
   97096     ** have to reuse the EP_FromJoin bit.  Bummer. */
   97097     exprX.flags |= EP_FromJoin;
   97098     sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
   97099   }
   97100   sqlite3ReleaseTempReg(pParse, regFree1);
   97101 
   97102   /* Ensure adequate test coverage */
   97103   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
   97104   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
   97105   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
   97106   testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
   97107   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
   97108   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
   97109   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
   97110   testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
   97111   testcase( xJump==0 );
   97112 }
   97113 
   97114 /*
   97115 ** Generate code for a boolean expression such that a jump is made
   97116 ** to the label "dest" if the expression is true but execution
   97117 ** continues straight thru if the expression is false.
   97118 **
   97119 ** If the expression evaluates to NULL (neither true nor false), then
   97120 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
   97121 **
   97122 ** This code depends on the fact that certain token values (ex: TK_EQ)
   97123 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
   97124 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
   97125 ** the make process cause these values to align.  Assert()s in the code
   97126 ** below verify that the numbers are aligned correctly.
   97127 */
   97128 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   97129   Vdbe *v = pParse->pVdbe;
   97130   int op = 0;
   97131   int regFree1 = 0;
   97132   int regFree2 = 0;
   97133   int r1, r2;
   97134 
   97135   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   97136   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
   97137   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
   97138   op = pExpr->op;
   97139   switch( op ){
   97140     case TK_AND: {
   97141       int d2 = sqlite3VdbeMakeLabel(v);
   97142       testcase( jumpIfNull==0 );
   97143       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
   97144       sqlite3ExprCachePush(pParse);
   97145       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   97146       sqlite3VdbeResolveLabel(v, d2);
   97147       sqlite3ExprCachePop(pParse);
   97148       break;
   97149     }
   97150     case TK_OR: {
   97151       testcase( jumpIfNull==0 );
   97152       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   97153       sqlite3ExprCachePush(pParse);
   97154       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   97155       sqlite3ExprCachePop(pParse);
   97156       break;
   97157     }
   97158     case TK_NOT: {
   97159       testcase( jumpIfNull==0 );
   97160       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   97161       break;
   97162     }
   97163     case TK_IS:
   97164     case TK_ISNOT:
   97165       testcase( op==TK_IS );
   97166       testcase( op==TK_ISNOT );
   97167       op = (op==TK_IS) ? TK_EQ : TK_NE;
   97168       jumpIfNull = SQLITE_NULLEQ;
   97169       /* Fall thru */
   97170     case TK_LT:
   97171     case TK_LE:
   97172     case TK_GT:
   97173     case TK_GE:
   97174     case TK_NE:
   97175     case TK_EQ: {
   97176       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
   97177       testcase( jumpIfNull==0 );
   97178       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   97179       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   97180       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   97181                   r1, r2, dest, jumpIfNull);
   97182       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   97183       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   97184       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   97185       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   97186       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
   97187       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
   97188       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
   97189       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
   97190       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
   97191       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
   97192       testcase( regFree1==0 );
   97193       testcase( regFree2==0 );
   97194       break;
   97195     }
   97196     case TK_ISNULL:
   97197     case TK_NOTNULL: {
   97198       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
   97199       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
   97200       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   97201       sqlite3VdbeAddOp2(v, op, r1, dest);
   97202       VdbeCoverageIf(v, op==TK_ISNULL);
   97203       VdbeCoverageIf(v, op==TK_NOTNULL);
   97204       testcase( regFree1==0 );
   97205       break;
   97206     }
   97207     case TK_BETWEEN: {
   97208       testcase( jumpIfNull==0 );
   97209       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
   97210       break;
   97211     }
   97212 #ifndef SQLITE_OMIT_SUBQUERY
   97213     case TK_IN: {
   97214       int destIfFalse = sqlite3VdbeMakeLabel(v);
   97215       int destIfNull = jumpIfNull ? dest : destIfFalse;
   97216       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   97217       sqlite3VdbeGoto(v, dest);
   97218       sqlite3VdbeResolveLabel(v, destIfFalse);
   97219       break;
   97220     }
   97221 #endif
   97222     default: {
   97223     default_expr:
   97224       if( exprAlwaysTrue(pExpr) ){
   97225         sqlite3VdbeGoto(v, dest);
   97226       }else if( exprAlwaysFalse(pExpr) ){
   97227         /* No-op */
   97228       }else{
   97229         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   97230         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
   97231         VdbeCoverage(v);
   97232         testcase( regFree1==0 );
   97233         testcase( jumpIfNull==0 );
   97234       }
   97235       break;
   97236     }
   97237   }
   97238   sqlite3ReleaseTempReg(pParse, regFree1);
   97239   sqlite3ReleaseTempReg(pParse, regFree2);
   97240 }
   97241 
   97242 /*
   97243 ** Generate code for a boolean expression such that a jump is made
   97244 ** to the label "dest" if the expression is false but execution
   97245 ** continues straight thru if the expression is true.
   97246 **
   97247 ** If the expression evaluates to NULL (neither true nor false) then
   97248 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
   97249 ** is 0.
   97250 */
   97251 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   97252   Vdbe *v = pParse->pVdbe;
   97253   int op = 0;
   97254   int regFree1 = 0;
   97255   int regFree2 = 0;
   97256   int r1, r2;
   97257 
   97258   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   97259   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
   97260   if( pExpr==0 )    return;
   97261 
   97262   /* The value of pExpr->op and op are related as follows:
   97263   **
   97264   **       pExpr->op            op
   97265   **       ---------          ----------
   97266   **       TK_ISNULL          OP_NotNull
   97267   **       TK_NOTNULL         OP_IsNull
   97268   **       TK_NE              OP_Eq
   97269   **       TK_EQ              OP_Ne
   97270   **       TK_GT              OP_Le
   97271   **       TK_LE              OP_Gt
   97272   **       TK_GE              OP_Lt
   97273   **       TK_LT              OP_Ge
   97274   **
   97275   ** For other values of pExpr->op, op is undefined and unused.
   97276   ** The value of TK_ and OP_ constants are arranged such that we
   97277   ** can compute the mapping above using the following expression.
   97278   ** Assert()s verify that the computation is correct.
   97279   */
   97280   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
   97281 
   97282   /* Verify correct alignment of TK_ and OP_ constants
   97283   */
   97284   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
   97285   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
   97286   assert( pExpr->op!=TK_NE || op==OP_Eq );
   97287   assert( pExpr->op!=TK_EQ || op==OP_Ne );
   97288   assert( pExpr->op!=TK_LT || op==OP_Ge );
   97289   assert( pExpr->op!=TK_LE || op==OP_Gt );
   97290   assert( pExpr->op!=TK_GT || op==OP_Le );
   97291   assert( pExpr->op!=TK_GE || op==OP_Lt );
   97292 
   97293   switch( pExpr->op ){
   97294     case TK_AND: {
   97295       testcase( jumpIfNull==0 );
   97296       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   97297       sqlite3ExprCachePush(pParse);
   97298       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   97299       sqlite3ExprCachePop(pParse);
   97300       break;
   97301     }
   97302     case TK_OR: {
   97303       int d2 = sqlite3VdbeMakeLabel(v);
   97304       testcase( jumpIfNull==0 );
   97305       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
   97306       sqlite3ExprCachePush(pParse);
   97307       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   97308       sqlite3VdbeResolveLabel(v, d2);
   97309       sqlite3ExprCachePop(pParse);
   97310       break;
   97311     }
   97312     case TK_NOT: {
   97313       testcase( jumpIfNull==0 );
   97314       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   97315       break;
   97316     }
   97317     case TK_IS:
   97318     case TK_ISNOT:
   97319       testcase( pExpr->op==TK_IS );
   97320       testcase( pExpr->op==TK_ISNOT );
   97321       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
   97322       jumpIfNull = SQLITE_NULLEQ;
   97323       /* Fall thru */
   97324     case TK_LT:
   97325     case TK_LE:
   97326     case TK_GT:
   97327     case TK_GE:
   97328     case TK_NE:
   97329     case TK_EQ: {
   97330       if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
   97331       testcase( jumpIfNull==0 );
   97332       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   97333       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   97334       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   97335                   r1, r2, dest, jumpIfNull);
   97336       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
   97337       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
   97338       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
   97339       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
   97340       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
   97341       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
   97342       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
   97343       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
   97344       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
   97345       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
   97346       testcase( regFree1==0 );
   97347       testcase( regFree2==0 );
   97348       break;
   97349     }
   97350     case TK_ISNULL:
   97351     case TK_NOTNULL: {
   97352       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   97353       sqlite3VdbeAddOp2(v, op, r1, dest);
   97354       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
   97355       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
   97356       testcase( regFree1==0 );
   97357       break;
   97358     }
   97359     case TK_BETWEEN: {
   97360       testcase( jumpIfNull==0 );
   97361       exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
   97362       break;
   97363     }
   97364 #ifndef SQLITE_OMIT_SUBQUERY
   97365     case TK_IN: {
   97366       if( jumpIfNull ){
   97367         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
   97368       }else{
   97369         int destIfNull = sqlite3VdbeMakeLabel(v);
   97370         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
   97371         sqlite3VdbeResolveLabel(v, destIfNull);
   97372       }
   97373       break;
   97374     }
   97375 #endif
   97376     default: {
   97377     default_expr:
   97378       if( exprAlwaysFalse(pExpr) ){
   97379         sqlite3VdbeGoto(v, dest);
   97380       }else if( exprAlwaysTrue(pExpr) ){
   97381         /* no-op */
   97382       }else{
   97383         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   97384         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
   97385         VdbeCoverage(v);
   97386         testcase( regFree1==0 );
   97387         testcase( jumpIfNull==0 );
   97388       }
   97389       break;
   97390     }
   97391   }
   97392   sqlite3ReleaseTempReg(pParse, regFree1);
   97393   sqlite3ReleaseTempReg(pParse, regFree2);
   97394 }
   97395 
   97396 /*
   97397 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
   97398 ** code generation, and that copy is deleted after code generation. This
   97399 ** ensures that the original pExpr is unchanged.
   97400 */
   97401 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
   97402   sqlite3 *db = pParse->db;
   97403   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
   97404   if( db->mallocFailed==0 ){
   97405     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
   97406   }
   97407   sqlite3ExprDelete(db, pCopy);
   97408 }
   97409 
   97410 /*
   97411 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
   97412 ** type of expression.
   97413 **
   97414 ** If pExpr is a simple SQL value - an integer, real, string, blob
   97415 ** or NULL value - then the VDBE currently being prepared is configured
   97416 ** to re-prepare each time a new value is bound to variable pVar.
   97417 **
   97418 ** Additionally, if pExpr is a simple SQL value and the value is the
   97419 ** same as that currently bound to variable pVar, non-zero is returned.
   97420 ** Otherwise, if the values are not the same or if pExpr is not a simple
   97421 ** SQL value, zero is returned.
   97422 */
   97423 static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
   97424   int res = 0;
   97425   int iVar;
   97426   sqlite3_value *pL, *pR = 0;
   97427 
   97428   sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
   97429   if( pR ){
   97430     iVar = pVar->iColumn;
   97431     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
   97432     pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
   97433     if( pL ){
   97434       if( sqlite3_value_type(pL)==SQLITE_TEXT ){
   97435         sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
   97436       }
   97437       res =  0==sqlite3MemCompare(pL, pR, 0);
   97438     }
   97439     sqlite3ValueFree(pR);
   97440     sqlite3ValueFree(pL);
   97441   }
   97442 
   97443   return res;
   97444 }
   97445 
   97446 /*
   97447 ** Do a deep comparison of two expression trees.  Return 0 if the two
   97448 ** expressions are completely identical.  Return 1 if they differ only
   97449 ** by a COLLATE operator at the top level.  Return 2 if there are differences
   97450 ** other than the top-level COLLATE operator.
   97451 **
   97452 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
   97453 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
   97454 **
   97455 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
   97456 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
   97457 **
   97458 ** Sometimes this routine will return 2 even if the two expressions
   97459 ** really are equivalent.  If we cannot prove that the expressions are
   97460 ** identical, we return 2 just to be safe.  So if this routine
   97461 ** returns 2, then you do not really know for certain if the two
   97462 ** expressions are the same.  But if you get a 0 or 1 return, then you
   97463 ** can be sure the expressions are the same.  In the places where
   97464 ** this routine is used, it does not hurt to get an extra 2 - that
   97465 ** just might result in some slightly slower code.  But returning
   97466 ** an incorrect 0 or 1 could lead to a malfunction.
   97467 **
   97468 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
   97469 ** pParse->pReprepare can be matched against literals in pB.  The
   97470 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
   97471 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
   97472 ** Argument pParse should normally be NULL. If it is not NULL and pA or
   97473 ** pB causes a return value of 2.
   97474 */
   97475 SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
   97476   u32 combinedFlags;
   97477   if( pA==0 || pB==0 ){
   97478     return pB==pA ? 0 : 2;
   97479   }
   97480   if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
   97481     return 0;
   97482   }
   97483   combinedFlags = pA->flags | pB->flags;
   97484   if( combinedFlags & EP_IntValue ){
   97485     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
   97486       return 0;
   97487     }
   97488     return 2;
   97489   }
   97490   if( pA->op!=pB->op ){
   97491     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
   97492       return 1;
   97493     }
   97494     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
   97495       return 1;
   97496     }
   97497     return 2;
   97498   }
   97499   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
   97500     if( pA->op==TK_FUNCTION ){
   97501       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
   97502     }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
   97503       return pA->op==TK_COLLATE ? 1 : 2;
   97504     }
   97505   }
   97506   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
   97507   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
   97508     if( combinedFlags & EP_xIsSelect ) return 2;
   97509     if( sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
   97510     if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
   97511     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
   97512     if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
   97513       if( pA->iColumn!=pB->iColumn ) return 2;
   97514       if( pA->iTable!=pB->iTable
   97515        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
   97516     }
   97517   }
   97518   return 0;
   97519 }
   97520 
   97521 /*
   97522 ** Compare two ExprList objects.  Return 0 if they are identical and
   97523 ** non-zero if they differ in any way.
   97524 **
   97525 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
   97526 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
   97527 **
   97528 ** This routine might return non-zero for equivalent ExprLists.  The
   97529 ** only consequence will be disabled optimizations.  But this routine
   97530 ** must never return 0 if the two ExprList objects are different, or
   97531 ** a malfunction will result.
   97532 **
   97533 ** Two NULL pointers are considered to be the same.  But a NULL pointer
   97534 ** always differs from a non-NULL pointer.
   97535 */
   97536 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
   97537   int i;
   97538   if( pA==0 && pB==0 ) return 0;
   97539   if( pA==0 || pB==0 ) return 1;
   97540   if( pA->nExpr!=pB->nExpr ) return 1;
   97541   for(i=0; i<pA->nExpr; i++){
   97542     Expr *pExprA = pA->a[i].pExpr;
   97543     Expr *pExprB = pB->a[i].pExpr;
   97544     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
   97545     if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
   97546   }
   97547   return 0;
   97548 }
   97549 
   97550 /*
   97551 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
   97552 ** are ignored.
   97553 */
   97554 SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
   97555   return sqlite3ExprCompare(0,
   97556              sqlite3ExprSkipCollate(pA),
   97557              sqlite3ExprSkipCollate(pB),
   97558              iTab);
   97559 }
   97560 
   97561 /*
   97562 ** Return true if we can prove the pE2 will always be true if pE1 is
   97563 ** true.  Return false if we cannot complete the proof or if pE2 might
   97564 ** be false.  Examples:
   97565 **
   97566 **     pE1: x==5       pE2: x==5             Result: true
   97567 **     pE1: x>0        pE2: x==5             Result: false
   97568 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
   97569 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
   97570 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
   97571 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
   97572 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
   97573 **
   97574 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
   97575 ** Expr.iTable<0 then assume a table number given by iTab.
   97576 **
   97577 ** If pParse is not NULL, then the values of bound variables in pE1 are
   97578 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
   97579 ** modified to record which bound variables are referenced.  If pParse
   97580 ** is NULL, then false will be returned if pE1 contains any bound variables.
   97581 **
   97582 ** When in doubt, return false.  Returning true might give a performance
   97583 ** improvement.  Returning false might cause a performance reduction, but
   97584 ** it will always give the correct answer and is hence always safe.
   97585 */
   97586 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
   97587   if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
   97588     return 1;
   97589   }
   97590   if( pE2->op==TK_OR
   97591    && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
   97592              || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
   97593   ){
   97594     return 1;
   97595   }
   97596   if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
   97597     Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
   97598     testcase( pX!=pE1->pLeft );
   97599     if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
   97600   }
   97601   return 0;
   97602 }
   97603 
   97604 /*
   97605 ** An instance of the following structure is used by the tree walker
   97606 ** to determine if an expression can be evaluated by reference to the
   97607 ** index only, without having to do a search for the corresponding
   97608 ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
   97609 ** is the cursor for the table.
   97610 */
   97611 struct IdxCover {
   97612   Index *pIdx;     /* The index to be tested for coverage */
   97613   int iCur;        /* Cursor number for the table corresponding to the index */
   97614 };
   97615 
   97616 /*
   97617 ** Check to see if there are references to columns in table
   97618 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
   97619 ** pWalker->u.pIdxCover->pIdx.
   97620 */
   97621 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
   97622   if( pExpr->op==TK_COLUMN
   97623    && pExpr->iTable==pWalker->u.pIdxCover->iCur
   97624    && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
   97625   ){
   97626     pWalker->eCode = 1;
   97627     return WRC_Abort;
   97628   }
   97629   return WRC_Continue;
   97630 }
   97631 
   97632 /*
   97633 ** Determine if an index pIdx on table with cursor iCur contains will
   97634 ** the expression pExpr.  Return true if the index does cover the
   97635 ** expression and false if the pExpr expression references table columns
   97636 ** that are not found in the index pIdx.
   97637 **
   97638 ** An index covering an expression means that the expression can be
   97639 ** evaluated using only the index and without having to lookup the
   97640 ** corresponding table entry.
   97641 */
   97642 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
   97643   Expr *pExpr,        /* The index to be tested */
   97644   int iCur,           /* The cursor number for the corresponding table */
   97645   Index *pIdx         /* The index that might be used for coverage */
   97646 ){
   97647   Walker w;
   97648   struct IdxCover xcov;
   97649   memset(&w, 0, sizeof(w));
   97650   xcov.iCur = iCur;
   97651   xcov.pIdx = pIdx;
   97652   w.xExprCallback = exprIdxCover;
   97653   w.u.pIdxCover = &xcov;
   97654   sqlite3WalkExpr(&w, pExpr);
   97655   return !w.eCode;
   97656 }
   97657 
   97658 
   97659 /*
   97660 ** An instance of the following structure is used by the tree walker
   97661 ** to count references to table columns in the arguments of an
   97662 ** aggregate function, in order to implement the
   97663 ** sqlite3FunctionThisSrc() routine.
   97664 */
   97665 struct SrcCount {
   97666   SrcList *pSrc;   /* One particular FROM clause in a nested query */
   97667   int nThis;       /* Number of references to columns in pSrcList */
   97668   int nOther;      /* Number of references to columns in other FROM clauses */
   97669 };
   97670 
   97671 /*
   97672 ** Count the number of references to columns.
   97673 */
   97674 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
   97675   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
   97676   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
   97677   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
   97678   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
   97679   ** NEVER() will need to be removed. */
   97680   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
   97681     int i;
   97682     struct SrcCount *p = pWalker->u.pSrcCount;
   97683     SrcList *pSrc = p->pSrc;
   97684     int nSrc = pSrc ? pSrc->nSrc : 0;
   97685     for(i=0; i<nSrc; i++){
   97686       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
   97687     }
   97688     if( i<nSrc ){
   97689       p->nThis++;
   97690     }else{
   97691       p->nOther++;
   97692     }
   97693   }
   97694   return WRC_Continue;
   97695 }
   97696 
   97697 /*
   97698 ** Determine if any of the arguments to the pExpr Function reference
   97699 ** pSrcList.  Return true if they do.  Also return true if the function
   97700 ** has no arguments or has only constant arguments.  Return false if pExpr
   97701 ** references columns but not columns of tables found in pSrcList.
   97702 */
   97703 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
   97704   Walker w;
   97705   struct SrcCount cnt;
   97706   assert( pExpr->op==TK_AGG_FUNCTION );
   97707   w.xExprCallback = exprSrcCount;
   97708   w.xSelectCallback = 0;
   97709   w.u.pSrcCount = &cnt;
   97710   cnt.pSrc = pSrcList;
   97711   cnt.nThis = 0;
   97712   cnt.nOther = 0;
   97713   sqlite3WalkExprList(&w, pExpr->x.pList);
   97714   return cnt.nThis>0 || cnt.nOther==0;
   97715 }
   97716 
   97717 /*
   97718 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
   97719 ** the new element.  Return a negative number if malloc fails.
   97720 */
   97721 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
   97722   int i;
   97723   pInfo->aCol = sqlite3ArrayAllocate(
   97724        db,
   97725        pInfo->aCol,
   97726        sizeof(pInfo->aCol[0]),
   97727        &pInfo->nColumn,
   97728        &i
   97729   );
   97730   return i;
   97731 }
   97732 
   97733 /*
   97734 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
   97735 ** the new element.  Return a negative number if malloc fails.
   97736 */
   97737 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   97738   int i;
   97739   pInfo->aFunc = sqlite3ArrayAllocate(
   97740        db,
   97741        pInfo->aFunc,
   97742        sizeof(pInfo->aFunc[0]),
   97743        &pInfo->nFunc,
   97744        &i
   97745   );
   97746   return i;
   97747 }
   97748 
   97749 /*
   97750 ** This is the xExprCallback for a tree walker.  It is used to
   97751 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
   97752 ** for additional information.
   97753 */
   97754 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   97755   int i;
   97756   NameContext *pNC = pWalker->u.pNC;
   97757   Parse *pParse = pNC->pParse;
   97758   SrcList *pSrcList = pNC->pSrcList;
   97759   AggInfo *pAggInfo = pNC->pAggInfo;
   97760 
   97761   switch( pExpr->op ){
   97762     case TK_AGG_COLUMN:
   97763     case TK_COLUMN: {
   97764       testcase( pExpr->op==TK_AGG_COLUMN );
   97765       testcase( pExpr->op==TK_COLUMN );
   97766       /* Check to see if the column is in one of the tables in the FROM
   97767       ** clause of the aggregate query */
   97768       if( ALWAYS(pSrcList!=0) ){
   97769         struct SrcList_item *pItem = pSrcList->a;
   97770         for(i=0; i<pSrcList->nSrc; i++, pItem++){
   97771           struct AggInfo_col *pCol;
   97772           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   97773           if( pExpr->iTable==pItem->iCursor ){
   97774             /* If we reach this point, it means that pExpr refers to a table
   97775             ** that is in the FROM clause of the aggregate query.
   97776             **
   97777             ** Make an entry for the column in pAggInfo->aCol[] if there
   97778             ** is not an entry there already.
   97779             */
   97780             int k;
   97781             pCol = pAggInfo->aCol;
   97782             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
   97783               if( pCol->iTable==pExpr->iTable &&
   97784                   pCol->iColumn==pExpr->iColumn ){
   97785                 break;
   97786               }
   97787             }
   97788             if( (k>=pAggInfo->nColumn)
   97789              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
   97790             ){
   97791               pCol = &pAggInfo->aCol[k];
   97792               pCol->pTab = pExpr->pTab;
   97793               pCol->iTable = pExpr->iTable;
   97794               pCol->iColumn = pExpr->iColumn;
   97795               pCol->iMem = ++pParse->nMem;
   97796               pCol->iSorterColumn = -1;
   97797               pCol->pExpr = pExpr;
   97798               if( pAggInfo->pGroupBy ){
   97799                 int j, n;
   97800                 ExprList *pGB = pAggInfo->pGroupBy;
   97801                 struct ExprList_item *pTerm = pGB->a;
   97802                 n = pGB->nExpr;
   97803                 for(j=0; j<n; j++, pTerm++){
   97804                   Expr *pE = pTerm->pExpr;
   97805                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
   97806                       pE->iColumn==pExpr->iColumn ){
   97807                     pCol->iSorterColumn = j;
   97808                     break;
   97809                   }
   97810                 }
   97811               }
   97812               if( pCol->iSorterColumn<0 ){
   97813                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
   97814               }
   97815             }
   97816             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
   97817             ** because it was there before or because we just created it).
   97818             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
   97819             ** pAggInfo->aCol[] entry.
   97820             */
   97821             ExprSetVVAProperty(pExpr, EP_NoReduce);
   97822             pExpr->pAggInfo = pAggInfo;
   97823             pExpr->op = TK_AGG_COLUMN;
   97824             pExpr->iAgg = (i16)k;
   97825             break;
   97826           } /* endif pExpr->iTable==pItem->iCursor */
   97827         } /* end loop over pSrcList */
   97828       }
   97829       return WRC_Prune;
   97830     }
   97831     case TK_AGG_FUNCTION: {
   97832       if( (pNC->ncFlags & NC_InAggFunc)==0
   97833        && pWalker->walkerDepth==pExpr->op2
   97834       ){
   97835         /* Check to see if pExpr is a duplicate of another aggregate
   97836         ** function that is already in the pAggInfo structure
   97837         */
   97838         struct AggInfo_func *pItem = pAggInfo->aFunc;
   97839         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
   97840           if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
   97841             break;
   97842           }
   97843         }
   97844         if( i>=pAggInfo->nFunc ){
   97845           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
   97846           */
   97847           u8 enc = ENC(pParse->db);
   97848           i = addAggInfoFunc(pParse->db, pAggInfo);
   97849           if( i>=0 ){
   97850             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   97851             pItem = &pAggInfo->aFunc[i];
   97852             pItem->pExpr = pExpr;
   97853             pItem->iMem = ++pParse->nMem;
   97854             assert( !ExprHasProperty(pExpr, EP_IntValue) );
   97855             pItem->pFunc = sqlite3FindFunction(pParse->db,
   97856                    pExpr->u.zToken,
   97857                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
   97858             if( pExpr->flags & EP_Distinct ){
   97859               pItem->iDistinct = pParse->nTab++;
   97860             }else{
   97861               pItem->iDistinct = -1;
   97862             }
   97863           }
   97864         }
   97865         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
   97866         */
   97867         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   97868         ExprSetVVAProperty(pExpr, EP_NoReduce);
   97869         pExpr->iAgg = (i16)i;
   97870         pExpr->pAggInfo = pAggInfo;
   97871         return WRC_Prune;
   97872       }else{
   97873         return WRC_Continue;
   97874       }
   97875     }
   97876   }
   97877   return WRC_Continue;
   97878 }
   97879 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
   97880   UNUSED_PARAMETER(pSelect);
   97881   pWalker->walkerDepth++;
   97882   return WRC_Continue;
   97883 }
   97884 static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
   97885   UNUSED_PARAMETER(pSelect);
   97886   pWalker->walkerDepth--;
   97887 }
   97888 
   97889 /*
   97890 ** Analyze the pExpr expression looking for aggregate functions and
   97891 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
   97892 ** points to.  Additional entries are made on the AggInfo object as
   97893 ** necessary.
   97894 **
   97895 ** This routine should only be called after the expression has been
   97896 ** analyzed by sqlite3ResolveExprNames().
   97897 */
   97898 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   97899   Walker w;
   97900   w.xExprCallback = analyzeAggregate;
   97901   w.xSelectCallback = analyzeAggregatesInSelect;
   97902   w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
   97903   w.walkerDepth = 0;
   97904   w.u.pNC = pNC;
   97905   assert( pNC->pSrcList!=0 );
   97906   sqlite3WalkExpr(&w, pExpr);
   97907 }
   97908 
   97909 /*
   97910 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
   97911 ** expression list.  Return the number of errors.
   97912 **
   97913 ** If an error is found, the analysis is cut short.
   97914 */
   97915 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
   97916   struct ExprList_item *pItem;
   97917   int i;
   97918   if( pList ){
   97919     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   97920       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
   97921     }
   97922   }
   97923 }
   97924 
   97925 /*
   97926 ** Allocate a single new register for use to hold some intermediate result.
   97927 */
   97928 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
   97929   if( pParse->nTempReg==0 ){
   97930     return ++pParse->nMem;
   97931   }
   97932   return pParse->aTempReg[--pParse->nTempReg];
   97933 }
   97934 
   97935 /*
   97936 ** Deallocate a register, making available for reuse for some other
   97937 ** purpose.
   97938 **
   97939 ** If a register is currently being used by the column cache, then
   97940 ** the deallocation is deferred until the column cache line that uses
   97941 ** the register becomes stale.
   97942 */
   97943 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
   97944   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   97945     int i;
   97946     struct yColCache *p;
   97947     for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
   97948       if( p->iReg==iReg ){
   97949         p->tempReg = 1;
   97950         return;
   97951       }
   97952     }
   97953     pParse->aTempReg[pParse->nTempReg++] = iReg;
   97954   }
   97955 }
   97956 
   97957 /*
   97958 ** Allocate or deallocate a block of nReg consecutive registers.
   97959 */
   97960 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
   97961   int i, n;
   97962   if( nReg==1 ) return sqlite3GetTempReg(pParse);
   97963   i = pParse->iRangeReg;
   97964   n = pParse->nRangeReg;
   97965   if( nReg<=n ){
   97966     assert( !usedAsColumnCache(pParse, i, i+n-1) );
   97967     pParse->iRangeReg += nReg;
   97968     pParse->nRangeReg -= nReg;
   97969   }else{
   97970     i = pParse->nMem+1;
   97971     pParse->nMem += nReg;
   97972   }
   97973   return i;
   97974 }
   97975 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
   97976   if( nReg==1 ){
   97977     sqlite3ReleaseTempReg(pParse, iReg);
   97978     return;
   97979   }
   97980   sqlite3ExprCacheRemove(pParse, iReg, nReg);
   97981   if( nReg>pParse->nRangeReg ){
   97982     pParse->nRangeReg = nReg;
   97983     pParse->iRangeReg = iReg;
   97984   }
   97985 }
   97986 
   97987 /*
   97988 ** Mark all temporary registers as being unavailable for reuse.
   97989 */
   97990 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
   97991   pParse->nTempReg = 0;
   97992   pParse->nRangeReg = 0;
   97993 }
   97994 
   97995 /*
   97996 ** Validate that no temporary register falls within the range of
   97997 ** iFirst..iLast, inclusive.  This routine is only call from within assert()
   97998 ** statements.
   97999 */
   98000 #ifdef SQLITE_DEBUG
   98001 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
   98002   int i;
   98003   if( pParse->nRangeReg>0
   98004    && pParse->iRangeReg+pParse->nRangeReg > iFirst
   98005    && pParse->iRangeReg <= iLast
   98006   ){
   98007      return 0;
   98008   }
   98009   for(i=0; i<pParse->nTempReg; i++){
   98010     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
   98011       return 0;
   98012     }
   98013   }
   98014   return 1;
   98015 }
   98016 #endif /* SQLITE_DEBUG */
   98017 
   98018 /************** End of expr.c ************************************************/
   98019 /************** Begin file alter.c *******************************************/
   98020 /*
   98021 ** 2005 February 15
   98022 **
   98023 ** The author disclaims copyright to this source code.  In place of
   98024 ** a legal notice, here is a blessing:
   98025 **
   98026 **    May you do good and not evil.
   98027 **    May you find forgiveness for yourself and forgive others.
   98028 **    May you share freely, never taking more than you give.
   98029 **
   98030 *************************************************************************
   98031 ** This file contains C code routines that used to generate VDBE code
   98032 ** that implements the ALTER TABLE command.
   98033 */
   98034 /* #include "sqliteInt.h" */
   98035 
   98036 /*
   98037 ** The code in this file only exists if we are not omitting the
   98038 ** ALTER TABLE logic from the build.
   98039 */
   98040 #ifndef SQLITE_OMIT_ALTERTABLE
   98041 
   98042 
   98043 /*
   98044 ** This function is used by SQL generated to implement the
   98045 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
   98046 ** CREATE INDEX command. The second is a table name. The table name in
   98047 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
   98048 ** argument and the result returned. Examples:
   98049 **
   98050 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
   98051 **     -> 'CREATE TABLE def(a, b, c)'
   98052 **
   98053 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
   98054 **     -> 'CREATE INDEX i ON def(a, b, c)'
   98055 */
   98056 static void renameTableFunc(
   98057   sqlite3_context *context,
   98058   int NotUsed,
   98059   sqlite3_value **argv
   98060 ){
   98061   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   98062   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   98063 
   98064   int token;
   98065   Token tname;
   98066   unsigned char const *zCsr = zSql;
   98067   int len = 0;
   98068   char *zRet;
   98069 
   98070   sqlite3 *db = sqlite3_context_db_handle(context);
   98071 
   98072   UNUSED_PARAMETER(NotUsed);
   98073 
   98074   /* The principle used to locate the table name in the CREATE TABLE
   98075   ** statement is that the table name is the first non-space token that
   98076   ** is immediately followed by a TK_LP or TK_USING token.
   98077   */
   98078   if( zSql ){
   98079     do {
   98080       if( !*zCsr ){
   98081         /* Ran out of input before finding an opening bracket. Return NULL. */
   98082         return;
   98083       }
   98084 
   98085       /* Store the token that zCsr points to in tname. */
   98086       tname.z = (char*)zCsr;
   98087       tname.n = len;
   98088 
   98089       /* Advance zCsr to the next token. Store that token type in 'token',
   98090       ** and its length in 'len' (to be used next iteration of this loop).
   98091       */
   98092       do {
   98093         zCsr += len;
   98094         len = sqlite3GetToken(zCsr, &token);
   98095       } while( token==TK_SPACE );
   98096       assert( len>0 );
   98097     } while( token!=TK_LP && token!=TK_USING );
   98098 
   98099     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
   98100        zSql, zTableName, tname.z+tname.n);
   98101     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   98102   }
   98103 }
   98104 
   98105 /*
   98106 ** This C function implements an SQL user function that is used by SQL code
   98107 ** generated by the ALTER TABLE ... RENAME command to modify the definition
   98108 ** of any foreign key constraints that use the table being renamed as the
   98109 ** parent table. It is passed three arguments:
   98110 **
   98111 **   1) The complete text of the CREATE TABLE statement being modified,
   98112 **   2) The old name of the table being renamed, and
   98113 **   3) The new name of the table being renamed.
   98114 **
   98115 ** It returns the new CREATE TABLE statement. For example:
   98116 **
   98117 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
   98118 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
   98119 */
   98120 #ifndef SQLITE_OMIT_FOREIGN_KEY
   98121 static void renameParentFunc(
   98122   sqlite3_context *context,
   98123   int NotUsed,
   98124   sqlite3_value **argv
   98125 ){
   98126   sqlite3 *db = sqlite3_context_db_handle(context);
   98127   char *zOutput = 0;
   98128   char *zResult;
   98129   unsigned char const *zInput = sqlite3_value_text(argv[0]);
   98130   unsigned char const *zOld = sqlite3_value_text(argv[1]);
   98131   unsigned char const *zNew = sqlite3_value_text(argv[2]);
   98132 
   98133   unsigned const char *z;         /* Pointer to token */
   98134   int n;                          /* Length of token z */
   98135   int token;                      /* Type of token */
   98136 
   98137   UNUSED_PARAMETER(NotUsed);
   98138   if( zInput==0 || zOld==0 ) return;
   98139   for(z=zInput; *z; z=z+n){
   98140     n = sqlite3GetToken(z, &token);
   98141     if( token==TK_REFERENCES ){
   98142       char *zParent;
   98143       do {
   98144         z += n;
   98145         n = sqlite3GetToken(z, &token);
   98146       }while( token==TK_SPACE );
   98147 
   98148       if( token==TK_ILLEGAL ) break;
   98149       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   98150       if( zParent==0 ) break;
   98151       sqlite3Dequote(zParent);
   98152       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   98153         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
   98154             (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
   98155         );
   98156         sqlite3DbFree(db, zOutput);
   98157         zOutput = zOut;
   98158         zInput = &z[n];
   98159       }
   98160       sqlite3DbFree(db, zParent);
   98161     }
   98162   }
   98163 
   98164   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
   98165   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
   98166   sqlite3DbFree(db, zOutput);
   98167 }
   98168 #endif
   98169 
   98170 #ifndef SQLITE_OMIT_TRIGGER
   98171 /* This function is used by SQL generated to implement the
   98172 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
   98173 ** statement. The second is a table name. The table name in the CREATE
   98174 ** TRIGGER statement is replaced with the third argument and the result
   98175 ** returned. This is analagous to renameTableFunc() above, except for CREATE
   98176 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
   98177 */
   98178 static void renameTriggerFunc(
   98179   sqlite3_context *context,
   98180   int NotUsed,
   98181   sqlite3_value **argv
   98182 ){
   98183   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   98184   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   98185 
   98186   int token;
   98187   Token tname;
   98188   int dist = 3;
   98189   unsigned char const *zCsr = zSql;
   98190   int len = 0;
   98191   char *zRet;
   98192   sqlite3 *db = sqlite3_context_db_handle(context);
   98193 
   98194   UNUSED_PARAMETER(NotUsed);
   98195 
   98196   /* The principle used to locate the table name in the CREATE TRIGGER
   98197   ** statement is that the table name is the first token that is immediately
   98198   ** preceded by either TK_ON or TK_DOT and immediately followed by one
   98199   ** of TK_WHEN, TK_BEGIN or TK_FOR.
   98200   */
   98201   if( zSql ){
   98202     do {
   98203 
   98204       if( !*zCsr ){
   98205         /* Ran out of input before finding the table name. Return NULL. */
   98206         return;
   98207       }
   98208 
   98209       /* Store the token that zCsr points to in tname. */
   98210       tname.z = (char*)zCsr;
   98211       tname.n = len;
   98212 
   98213       /* Advance zCsr to the next token. Store that token type in 'token',
   98214       ** and its length in 'len' (to be used next iteration of this loop).
   98215       */
   98216       do {
   98217         zCsr += len;
   98218         len = sqlite3GetToken(zCsr, &token);
   98219       }while( token==TK_SPACE );
   98220       assert( len>0 );
   98221 
   98222       /* Variable 'dist' stores the number of tokens read since the most
   98223       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
   98224       ** token is read and 'dist' equals 2, the condition stated above
   98225       ** to be met.
   98226       **
   98227       ** Note that ON cannot be a database, table or column name, so
   98228       ** there is no need to worry about syntax like
   98229       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
   98230       */
   98231       dist++;
   98232       if( token==TK_DOT || token==TK_ON ){
   98233         dist = 0;
   98234       }
   98235     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   98236 
   98237     /* Variable tname now contains the token that is the old table-name
   98238     ** in the CREATE TRIGGER statement.
   98239     */
   98240     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
   98241        zSql, zTableName, tname.z+tname.n);
   98242     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   98243   }
   98244 }
   98245 #endif   /* !SQLITE_OMIT_TRIGGER */
   98246 
   98247 /*
   98248 ** Register built-in functions used to help implement ALTER TABLE
   98249 */
   98250 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
   98251   static FuncDef aAlterTableFuncs[] = {
   98252     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
   98253 #ifndef SQLITE_OMIT_TRIGGER
   98254     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
   98255 #endif
   98256 #ifndef SQLITE_OMIT_FOREIGN_KEY
   98257     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
   98258 #endif
   98259   };
   98260   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
   98261 }
   98262 
   98263 /*
   98264 ** This function is used to create the text of expressions of the form:
   98265 **
   98266 **   name=<constant1> OR name=<constant2> OR ...
   98267 **
   98268 ** If argument zWhere is NULL, then a pointer string containing the text
   98269 ** "name=<constant>" is returned, where <constant> is the quoted version
   98270 ** of the string passed as argument zConstant. The returned buffer is
   98271 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
   98272 ** caller to ensure that it is eventually freed.
   98273 **
   98274 ** If argument zWhere is not NULL, then the string returned is
   98275 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
   98276 ** In this case zWhere is passed to sqlite3DbFree() before returning.
   98277 **
   98278 */
   98279 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
   98280   char *zNew;
   98281   if( !zWhere ){
   98282     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
   98283   }else{
   98284     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
   98285     sqlite3DbFree(db, zWhere);
   98286   }
   98287   return zNew;
   98288 }
   98289 
   98290 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98291 /*
   98292 ** Generate the text of a WHERE expression which can be used to select all
   98293 ** tables that have foreign key constraints that refer to table pTab (i.e.
   98294 ** constraints for which pTab is the parent table) from the sqlite_master
   98295 ** table.
   98296 */
   98297 static char *whereForeignKeys(Parse *pParse, Table *pTab){
   98298   FKey *p;
   98299   char *zWhere = 0;
   98300   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   98301     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
   98302   }
   98303   return zWhere;
   98304 }
   98305 #endif
   98306 
   98307 /*
   98308 ** Generate the text of a WHERE expression which can be used to select all
   98309 ** temporary triggers on table pTab from the sqlite_temp_master table. If
   98310 ** table pTab has no temporary triggers, or is itself stored in the
   98311 ** temporary database, NULL is returned.
   98312 */
   98313 static char *whereTempTriggers(Parse *pParse, Table *pTab){
   98314   Trigger *pTrig;
   98315   char *zWhere = 0;
   98316   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
   98317 
   98318   /* If the table is not located in the temp-db (in which case NULL is
   98319   ** returned, loop through the tables list of triggers. For each trigger
   98320   ** that is not part of the temp-db schema, add a clause to the WHERE
   98321   ** expression being built up in zWhere.
   98322   */
   98323   if( pTab->pSchema!=pTempSchema ){
   98324     sqlite3 *db = pParse->db;
   98325     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   98326       if( pTrig->pSchema==pTempSchema ){
   98327         zWhere = whereOrName(db, zWhere, pTrig->zName);
   98328       }
   98329     }
   98330   }
   98331   if( zWhere ){
   98332     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
   98333     sqlite3DbFree(pParse->db, zWhere);
   98334     zWhere = zNew;
   98335   }
   98336   return zWhere;
   98337 }
   98338 
   98339 /*
   98340 ** Generate code to drop and reload the internal representation of table
   98341 ** pTab from the database, including triggers and temporary triggers.
   98342 ** Argument zName is the name of the table in the database schema at
   98343 ** the time the generated code is executed. This can be different from
   98344 ** pTab->zName if this function is being called to code part of an
   98345 ** "ALTER TABLE RENAME TO" statement.
   98346 */
   98347 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   98348   Vdbe *v;
   98349   char *zWhere;
   98350   int iDb;                   /* Index of database containing pTab */
   98351 #ifndef SQLITE_OMIT_TRIGGER
   98352   Trigger *pTrig;
   98353 #endif
   98354 
   98355   v = sqlite3GetVdbe(pParse);
   98356   if( NEVER(v==0) ) return;
   98357   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   98358   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   98359   assert( iDb>=0 );
   98360 
   98361 #ifndef SQLITE_OMIT_TRIGGER
   98362   /* Drop any table triggers from the internal schema. */
   98363   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   98364     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   98365     assert( iTrigDb==iDb || iTrigDb==1 );
   98366     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   98367   }
   98368 #endif
   98369 
   98370   /* Drop the table and index from the internal schema.  */
   98371   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   98372 
   98373   /* Reload the table, index and permanent trigger schemas. */
   98374   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
   98375   if( !zWhere ) return;
   98376   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   98377 
   98378 #ifndef SQLITE_OMIT_TRIGGER
   98379   /* Now, if the table is not stored in the temp database, reload any temp
   98380   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
   98381   */
   98382   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   98383     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
   98384   }
   98385 #endif
   98386 }
   98387 
   98388 /*
   98389 ** Parameter zName is the name of a table that is about to be altered
   98390 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
   98391 ** If the table is a system table, this function leaves an error message
   98392 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
   98393 **
   98394 ** Or, if zName is not a system table, zero is returned.
   98395 */
   98396 static int isSystemTable(Parse *pParse, const char *zName){
   98397   if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   98398     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
   98399     return 1;
   98400   }
   98401   return 0;
   98402 }
   98403 
   98404 /*
   98405 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
   98406 ** command.
   98407 */
   98408 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   98409   Parse *pParse,            /* Parser context. */
   98410   SrcList *pSrc,            /* The table to rename. */
   98411   Token *pName              /* The new table name. */
   98412 ){
   98413   int iDb;                  /* Database that contains the table */
   98414   char *zDb;                /* Name of database iDb */
   98415   Table *pTab;              /* Table being renamed */
   98416   char *zName = 0;          /* NULL-terminated version of pName */
   98417   sqlite3 *db = pParse->db; /* Database connection */
   98418   int nTabName;             /* Number of UTF-8 characters in zTabName */
   98419   const char *zTabName;     /* Original name of the table */
   98420   Vdbe *v;
   98421 #ifndef SQLITE_OMIT_TRIGGER
   98422   char *zWhere = 0;         /* Where clause to locate temp triggers */
   98423 #endif
   98424   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   98425   u32 savedDbFlags;         /* Saved value of db->mDbFlags */
   98426 
   98427   savedDbFlags = db->mDbFlags;
   98428   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   98429   assert( pSrc->nSrc==1 );
   98430   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   98431 
   98432   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
   98433   if( !pTab ) goto exit_rename_table;
   98434   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   98435   zDb = db->aDb[iDb].zDbSName;
   98436   db->mDbFlags |= DBFLAG_PreferBuiltin;
   98437 
   98438   /* Get a NULL terminated version of the new table name. */
   98439   zName = sqlite3NameFromToken(db, pName);
   98440   if( !zName ) goto exit_rename_table;
   98441 
   98442   /* Check that a table or index named 'zName' does not already exist
   98443   ** in database iDb. If so, this is an error.
   98444   */
   98445   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
   98446     sqlite3ErrorMsg(pParse,
   98447         "there is already another table or index with this name: %s", zName);
   98448     goto exit_rename_table;
   98449   }
   98450 
   98451   /* Make sure it is not a system table being altered, or a reserved name
   98452   ** that the table is being renamed to.
   98453   */
   98454   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   98455     goto exit_rename_table;
   98456   }
   98457   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
   98458     exit_rename_table;
   98459   }
   98460 
   98461 #ifndef SQLITE_OMIT_VIEW
   98462   if( pTab->pSelect ){
   98463     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
   98464     goto exit_rename_table;
   98465   }
   98466 #endif
   98467 
   98468 #ifndef SQLITE_OMIT_AUTHORIZATION
   98469   /* Invoke the authorization callback. */
   98470   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   98471     goto exit_rename_table;
   98472   }
   98473 #endif
   98474 
   98475 #ifndef SQLITE_OMIT_VIRTUALTABLE
   98476   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   98477     goto exit_rename_table;
   98478   }
   98479   if( IsVirtual(pTab) ){
   98480     pVTab = sqlite3GetVTable(db, pTab);
   98481     if( pVTab->pVtab->pModule->xRename==0 ){
   98482       pVTab = 0;
   98483     }
   98484   }
   98485 #endif
   98486 
   98487   /* Begin a transaction for database iDb.
   98488   ** Then modify the schema cookie (since the ALTER TABLE modifies the
   98489   ** schema). Open a statement transaction if the table is a virtual
   98490   ** table.
   98491   */
   98492   v = sqlite3GetVdbe(pParse);
   98493   if( v==0 ){
   98494     goto exit_rename_table;
   98495   }
   98496   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
   98497   sqlite3ChangeCookie(pParse, iDb);
   98498 
   98499   /* If this is a virtual table, invoke the xRename() function if
   98500   ** one is defined. The xRename() callback will modify the names
   98501   ** of any resources used by the v-table implementation (including other
   98502   ** SQLite tables) that are identified by the name of the virtual table.
   98503   */
   98504 #ifndef SQLITE_OMIT_VIRTUALTABLE
   98505   if( pVTab ){
   98506     int i = ++pParse->nMem;
   98507     sqlite3VdbeLoadString(v, i, zName);
   98508     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
   98509     sqlite3MayAbort(pParse);
   98510   }
   98511 #endif
   98512 
   98513   /* figure out how many UTF-8 characters are in zName */
   98514   zTabName = pTab->zName;
   98515   nTabName = sqlite3Utf8CharLen(zTabName, -1);
   98516 
   98517 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98518   if( db->flags&SQLITE_ForeignKeys ){
   98519     /* If foreign-key support is enabled, rewrite the CREATE TABLE
   98520     ** statements corresponding to all child tables of foreign key constraints
   98521     ** for which the renamed table is the parent table.  */
   98522     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
   98523       sqlite3NestedParse(pParse,
   98524           "UPDATE \"%w\".%s SET "
   98525               "sql = sqlite_rename_parent(sql, %Q, %Q) "
   98526               "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
   98527       sqlite3DbFree(db, zWhere);
   98528     }
   98529   }
   98530 #endif
   98531 
   98532   /* Modify the sqlite_master table to use the new table name. */
   98533   sqlite3NestedParse(pParse,
   98534       "UPDATE %Q.%s SET "
   98535 #ifdef SQLITE_OMIT_TRIGGER
   98536           "sql = sqlite_rename_table(sql, %Q), "
   98537 #else
   98538           "sql = CASE "
   98539             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
   98540             "ELSE sqlite_rename_table(sql, %Q) END, "
   98541 #endif
   98542           "tbl_name = %Q, "
   98543           "name = CASE "
   98544             "WHEN type='table' THEN %Q "
   98545             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
   98546              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
   98547             "ELSE name END "
   98548       "WHERE tbl_name=%Q COLLATE nocase AND "
   98549           "(type='table' OR type='index' OR type='trigger');",
   98550       zDb, MASTER_NAME, zName, zName, zName,
   98551 #ifndef SQLITE_OMIT_TRIGGER
   98552       zName,
   98553 #endif
   98554       zName, nTabName, zTabName
   98555   );
   98556 
   98557 #ifndef SQLITE_OMIT_AUTOINCREMENT
   98558   /* If the sqlite_sequence table exists in this database, then update
   98559   ** it with the new table name.
   98560   */
   98561   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
   98562     sqlite3NestedParse(pParse,
   98563         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
   98564         zDb, zName, pTab->zName);
   98565   }
   98566 #endif
   98567 
   98568 #ifndef SQLITE_OMIT_TRIGGER
   98569   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   98570   ** table. Don't do this if the table being ALTERed is itself located in
   98571   ** the temp database.
   98572   */
   98573   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   98574     sqlite3NestedParse(pParse,
   98575         "UPDATE sqlite_temp_master SET "
   98576             "sql = sqlite_rename_trigger(sql, %Q), "
   98577             "tbl_name = %Q "
   98578             "WHERE %s;", zName, zName, zWhere);
   98579     sqlite3DbFree(db, zWhere);
   98580   }
   98581 #endif
   98582 
   98583 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   98584   if( db->flags&SQLITE_ForeignKeys ){
   98585     FKey *p;
   98586     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   98587       Table *pFrom = p->pFrom;
   98588       if( pFrom!=pTab ){
   98589         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
   98590       }
   98591     }
   98592   }
   98593 #endif
   98594 
   98595   /* Drop and reload the internal table schema. */
   98596   reloadTableSchema(pParse, pTab, zName);
   98597 
   98598 exit_rename_table:
   98599   sqlite3SrcListDelete(db, pSrc);
   98600   sqlite3DbFree(db, zName);
   98601   db->mDbFlags = savedDbFlags;
   98602 }
   98603 
   98604 /*
   98605 ** This function is called after an "ALTER TABLE ... ADD" statement
   98606 ** has been parsed. Argument pColDef contains the text of the new
   98607 ** column definition.
   98608 **
   98609 ** The Table structure pParse->pNewTable was extended to include
   98610 ** the new column during parsing.
   98611 */
   98612 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   98613   Table *pNew;              /* Copy of pParse->pNewTable */
   98614   Table *pTab;              /* Table being altered */
   98615   int iDb;                  /* Database number */
   98616   const char *zDb;          /* Database name */
   98617   const char *zTab;         /* Table name */
   98618   char *zCol;               /* Null-terminated column definition */
   98619   Column *pCol;             /* The new column */
   98620   Expr *pDflt;              /* Default value for the new column */
   98621   sqlite3 *db;              /* The database connection; */
   98622   Vdbe *v = pParse->pVdbe;  /* The prepared statement under construction */
   98623   int r1;                   /* Temporary registers */
   98624 
   98625   db = pParse->db;
   98626   if( pParse->nErr || db->mallocFailed ) return;
   98627   assert( v!=0 );
   98628   pNew = pParse->pNewTable;
   98629   assert( pNew );
   98630 
   98631   assert( sqlite3BtreeHoldsAllMutexes(db) );
   98632   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   98633   zDb = db->aDb[iDb].zDbSName;
   98634   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   98635   pCol = &pNew->aCol[pNew->nCol-1];
   98636   pDflt = pCol->pDflt;
   98637   pTab = sqlite3FindTable(db, zTab, zDb);
   98638   assert( pTab );
   98639 
   98640 #ifndef SQLITE_OMIT_AUTHORIZATION
   98641   /* Invoke the authorization callback. */
   98642   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   98643     return;
   98644   }
   98645 #endif
   98646 
   98647   /* If the default value for the new column was specified with a
   98648   ** literal NULL, then set pDflt to 0. This simplifies checking
   98649   ** for an SQL NULL default below.
   98650   */
   98651   assert( pDflt==0 || pDflt->op==TK_SPAN );
   98652   if( pDflt && pDflt->pLeft->op==TK_NULL ){
   98653     pDflt = 0;
   98654   }
   98655 
   98656   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   98657   ** If there is a NOT NULL constraint, then the default value for the
   98658   ** column must not be NULL.
   98659   */
   98660   if( pCol->colFlags & COLFLAG_PRIMKEY ){
   98661     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
   98662     return;
   98663   }
   98664   if( pNew->pIndex ){
   98665     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
   98666     return;
   98667   }
   98668   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
   98669     sqlite3ErrorMsg(pParse,
   98670         "Cannot add a REFERENCES column with non-NULL default value");
   98671     return;
   98672   }
   98673   if( pCol->notNull && !pDflt ){
   98674     sqlite3ErrorMsg(pParse,
   98675         "Cannot add a NOT NULL column with default value NULL");
   98676     return;
   98677   }
   98678 
   98679   /* Ensure the default expression is something that sqlite3ValueFromExpr()
   98680   ** can handle (i.e. not CURRENT_TIME etc.)
   98681   */
   98682   if( pDflt ){
   98683     sqlite3_value *pVal = 0;
   98684     int rc;
   98685     rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
   98686     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   98687     if( rc!=SQLITE_OK ){
   98688       assert( db->mallocFailed == 1 );
   98689       return;
   98690     }
   98691     if( !pVal ){
   98692       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   98693       return;
   98694     }
   98695     sqlite3ValueFree(pVal);
   98696   }
   98697 
   98698   /* Modify the CREATE TABLE statement. */
   98699   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   98700   if( zCol ){
   98701     char *zEnd = &zCol[pColDef->n-1];
   98702     u32 savedDbFlags = db->mDbFlags;
   98703     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
   98704       *zEnd-- = '\0';
   98705     }
   98706     db->mDbFlags |= DBFLAG_PreferBuiltin;
   98707     sqlite3NestedParse(pParse,
   98708         "UPDATE \"%w\".%s SET "
   98709           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
   98710         "WHERE type = 'table' AND name = %Q",
   98711       zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
   98712       zTab
   98713     );
   98714     sqlite3DbFree(db, zCol);
   98715     db->mDbFlags = savedDbFlags;
   98716   }
   98717 
   98718   /* Make sure the schema version is at least 3.  But do not upgrade
   98719   ** from less than 3 to 4, as that will corrupt any preexisting DESC
   98720   ** index.
   98721   */
   98722   r1 = sqlite3GetTempReg(pParse);
   98723   sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   98724   sqlite3VdbeUsesBtree(v, iDb);
   98725   sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
   98726   sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
   98727   VdbeCoverage(v);
   98728   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
   98729   sqlite3ReleaseTempReg(pParse, r1);
   98730 
   98731   /* Reload the schema of the modified table. */
   98732   reloadTableSchema(pParse, pTab, pTab->zName);
   98733 }
   98734 
   98735 /*
   98736 ** This function is called by the parser after the table-name in
   98737 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
   98738 ** pSrc is the full-name of the table being altered.
   98739 **
   98740 ** This routine makes a (partial) copy of the Table structure
   98741 ** for the table being altered and sets Parse.pNewTable to point
   98742 ** to it. Routines called by the parser as the column definition
   98743 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
   98744 ** the copy. The copy of the Table structure is deleted by tokenize.c
   98745 ** after parsing is finished.
   98746 **
   98747 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
   98748 ** coding the "ALTER TABLE ... ADD" statement.
   98749 */
   98750 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   98751   Table *pNew;
   98752   Table *pTab;
   98753   Vdbe *v;
   98754   int iDb;
   98755   int i;
   98756   int nAlloc;
   98757   sqlite3 *db = pParse->db;
   98758 
   98759   /* Look up the table being altered. */
   98760   assert( pParse->pNewTable==0 );
   98761   assert( sqlite3BtreeHoldsAllMutexes(db) );
   98762   if( db->mallocFailed ) goto exit_begin_add_column;
   98763   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
   98764   if( !pTab ) goto exit_begin_add_column;
   98765 
   98766 #ifndef SQLITE_OMIT_VIRTUALTABLE
   98767   if( IsVirtual(pTab) ){
   98768     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
   98769     goto exit_begin_add_column;
   98770   }
   98771 #endif
   98772 
   98773   /* Make sure this is not an attempt to ALTER a view. */
   98774   if( pTab->pSelect ){
   98775     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   98776     goto exit_begin_add_column;
   98777   }
   98778   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   98779     goto exit_begin_add_column;
   98780   }
   98781 
   98782   assert( pTab->addColOffset>0 );
   98783   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   98784 
   98785   /* Put a copy of the Table struct in Parse.pNewTable for the
   98786   ** sqlite3AddColumn() function and friends to modify.  But modify
   98787   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
   98788   ** prefix, we insure that the name will not collide with an existing
   98789   ** table because user table are not allowed to have the "sqlite_"
   98790   ** prefix on their name.
   98791   */
   98792   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
   98793   if( !pNew ) goto exit_begin_add_column;
   98794   pParse->pNewTable = pNew;
   98795   pNew->nTabRef = 1;
   98796   pNew->nCol = pTab->nCol;
   98797   assert( pNew->nCol>0 );
   98798   nAlloc = (((pNew->nCol-1)/8)*8)+8;
   98799   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
   98800   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
   98801   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
   98802   if( !pNew->aCol || !pNew->zName ){
   98803     assert( db->mallocFailed );
   98804     goto exit_begin_add_column;
   98805   }
   98806   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   98807   for(i=0; i<pNew->nCol; i++){
   98808     Column *pCol = &pNew->aCol[i];
   98809     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
   98810     pCol->zColl = 0;
   98811     pCol->pDflt = 0;
   98812   }
   98813   pNew->pSchema = db->aDb[iDb].pSchema;
   98814   pNew->addColOffset = pTab->addColOffset;
   98815   pNew->nTabRef = 1;
   98816 
   98817   /* Begin a transaction and increment the schema cookie.  */
   98818   sqlite3BeginWriteOperation(pParse, 0, iDb);
   98819   v = sqlite3GetVdbe(pParse);
   98820   if( !v ) goto exit_begin_add_column;
   98821   sqlite3ChangeCookie(pParse, iDb);
   98822 
   98823 exit_begin_add_column:
   98824   sqlite3SrcListDelete(db, pSrc);
   98825   return;
   98826 }
   98827 #endif  /* SQLITE_ALTER_TABLE */
   98828 
   98829 /************** End of alter.c ***********************************************/
   98830 /************** Begin file analyze.c *****************************************/
   98831 /*
   98832 ** 2005-07-08
   98833 **
   98834 ** The author disclaims copyright to this source code.  In place of
   98835 ** a legal notice, here is a blessing:
   98836 **
   98837 **    May you do good and not evil.
   98838 **    May you find forgiveness for yourself and forgive others.
   98839 **    May you share freely, never taking more than you give.
   98840 **
   98841 *************************************************************************
   98842 ** This file contains code associated with the ANALYZE command.
   98843 **
   98844 ** The ANALYZE command gather statistics about the content of tables
   98845 ** and indices.  These statistics are made available to the query planner
   98846 ** to help it make better decisions about how to perform queries.
   98847 **
   98848 ** The following system tables are or have been supported:
   98849 **
   98850 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
   98851 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
   98852 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
   98853 **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
   98854 **
   98855 ** Additional tables might be added in future releases of SQLite.
   98856 ** The sqlite_stat2 table is not created or used unless the SQLite version
   98857 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
   98858 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
   98859 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
   98860 ** created and used by SQLite versions 3.7.9 and later and with
   98861 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
   98862 ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
   98863 ** version of sqlite_stat3 and is only available when compiled with
   98864 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
   98865 ** not possible to enable both STAT3 and STAT4 at the same time.  If they
   98866 ** are both enabled, then STAT4 takes precedence.
   98867 **
   98868 ** For most applications, sqlite_stat1 provides all the statistics required
   98869 ** for the query planner to make good choices.
   98870 **
   98871 ** Format of sqlite_stat1:
   98872 **
   98873 ** There is normally one row per index, with the index identified by the
   98874 ** name in the idx column.  The tbl column is the name of the table to
   98875 ** which the index belongs.  In each such row, the stat column will be
   98876 ** a string consisting of a list of integers.  The first integer in this
   98877 ** list is the number of rows in the index.  (This is the same as the
   98878 ** number of rows in the table, except for partial indices.)  The second
   98879 ** integer is the average number of rows in the index that have the same
   98880 ** value in the first column of the index.  The third integer is the average
   98881 ** number of rows in the index that have the same value for the first two
   98882 ** columns.  The N-th integer (for N>1) is the average number of rows in
   98883 ** the index which have the same value for the first N-1 columns.  For
   98884 ** a K-column index, there will be K+1 integers in the stat column.  If
   98885 ** the index is unique, then the last integer will be 1.
   98886 **
   98887 ** The list of integers in the stat column can optionally be followed
   98888 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
   98889 ** must be separated from the last integer by a single space.  If the
   98890 ** "unordered" keyword is present, then the query planner assumes that
   98891 ** the index is unordered and will not use the index for a range query.
   98892 **
   98893 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
   98894 ** column contains a single integer which is the (estimated) number of
   98895 ** rows in the table identified by sqlite_stat1.tbl.
   98896 **
   98897 ** Format of sqlite_stat2:
   98898 **
   98899 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
   98900 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
   98901 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
   98902 ** about the distribution of keys within an index.  The index is identified by
   98903 ** the "idx" column and the "tbl" column is the name of the table to which
   98904 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
   98905 ** table for each index.
   98906 **
   98907 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
   98908 ** inclusive are samples of the left-most key value in the index taken at
   98909 ** evenly spaced points along the index.  Let the number of samples be S
   98910 ** (10 in the standard build) and let C be the number of rows in the index.
   98911 ** Then the sampled rows are given by:
   98912 **
   98913 **     rownumber = (i*C*2 + C)/(S*2)
   98914 **
   98915 ** For i between 0 and S-1.  Conceptually, the index space is divided into
   98916 ** S uniform buckets and the samples are the middle row from each bucket.
   98917 **
   98918 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
   98919 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
   98920 ** writes the sqlite_stat2 table.  This version of SQLite only supports
   98921 ** sqlite_stat3.
   98922 **
   98923 ** Format for sqlite_stat3:
   98924 **
   98925 ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
   98926 ** sqlite_stat4 format will be described first.  Further information
   98927 ** about sqlite_stat3 follows the sqlite_stat4 description.
   98928 **
   98929 ** Format for sqlite_stat4:
   98930 **
   98931 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
   98932 ** to aid the query planner in choosing good indices based on the values
   98933 ** that indexed columns are compared against in the WHERE clauses of
   98934 ** queries.
   98935 **
   98936 ** The sqlite_stat4 table contains multiple entries for each index.
   98937 ** The idx column names the index and the tbl column is the table of the
   98938 ** index.  If the idx and tbl columns are the same, then the sample is
   98939 ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
   98940 ** binary encoding of a key from the index.  The nEq column is a
   98941 ** list of integers.  The first integer is the approximate number
   98942 ** of entries in the index whose left-most column exactly matches
   98943 ** the left-most column of the sample.  The second integer in nEq
   98944 ** is the approximate number of entries in the index where the
   98945 ** first two columns match the first two columns of the sample.
   98946 ** And so forth.  nLt is another list of integers that show the approximate
   98947 ** number of entries that are strictly less than the sample.  The first
   98948 ** integer in nLt contains the number of entries in the index where the
   98949 ** left-most column is less than the left-most column of the sample.
   98950 ** The K-th integer in the nLt entry is the number of index entries
   98951 ** where the first K columns are less than the first K columns of the
   98952 ** sample.  The nDLt column is like nLt except that it contains the
   98953 ** number of distinct entries in the index that are less than the
   98954 ** sample.
   98955 **
   98956 ** There can be an arbitrary number of sqlite_stat4 entries per index.
   98957 ** The ANALYZE command will typically generate sqlite_stat4 tables
   98958 ** that contain between 10 and 40 samples which are distributed across
   98959 ** the key space, though not uniformly, and which include samples with
   98960 ** large nEq values.
   98961 **
   98962 ** Format for sqlite_stat3 redux:
   98963 **
   98964 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
   98965 ** looks at the left-most column of the index.  The sqlite_stat3.sample
   98966 ** column contains the actual value of the left-most column instead
   98967 ** of a blob encoding of the complete index key as is found in
   98968 ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
   98969 ** all contain just a single integer which is the same as the first
   98970 ** integer in the equivalent columns in sqlite_stat4.
   98971 */
   98972 #ifndef SQLITE_OMIT_ANALYZE
   98973 /* #include "sqliteInt.h" */
   98974 
   98975 #if defined(SQLITE_ENABLE_STAT4)
   98976 # define IsStat4     1
   98977 # define IsStat3     0
   98978 #elif defined(SQLITE_ENABLE_STAT3)
   98979 # define IsStat4     0
   98980 # define IsStat3     1
   98981 #else
   98982 # define IsStat4     0
   98983 # define IsStat3     0
   98984 # undef SQLITE_STAT4_SAMPLES
   98985 # define SQLITE_STAT4_SAMPLES 1
   98986 #endif
   98987 #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
   98988 
   98989 /*
   98990 ** This routine generates code that opens the sqlite_statN tables.
   98991 ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
   98992 ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
   98993 ** appropriate compile-time options are provided.
   98994 **
   98995 ** If the sqlite_statN tables do not previously exist, it is created.
   98996 **
   98997 ** Argument zWhere may be a pointer to a buffer containing a table name,
   98998 ** or it may be a NULL pointer. If it is not NULL, then all entries in
   98999 ** the sqlite_statN tables associated with the named table are deleted.
   99000 ** If zWhere==0, then code is generated to delete all stat table entries.
   99001 */
   99002 static void openStatTable(
   99003   Parse *pParse,          /* Parsing context */
   99004   int iDb,                /* The database we are looking in */
   99005   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
   99006   const char *zWhere,     /* Delete entries for this table or index */
   99007   const char *zWhereType  /* Either "tbl" or "idx" */
   99008 ){
   99009   static const struct {
   99010     const char *zName;
   99011     const char *zCols;
   99012   } aTable[] = {
   99013     { "sqlite_stat1", "tbl,idx,stat" },
   99014 #if defined(SQLITE_ENABLE_STAT4)
   99015     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
   99016     { "sqlite_stat3", 0 },
   99017 #elif defined(SQLITE_ENABLE_STAT3)
   99018     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
   99019     { "sqlite_stat4", 0 },
   99020 #else
   99021     { "sqlite_stat3", 0 },
   99022     { "sqlite_stat4", 0 },
   99023 #endif
   99024   };
   99025   int i;
   99026   sqlite3 *db = pParse->db;
   99027   Db *pDb;
   99028   Vdbe *v = sqlite3GetVdbe(pParse);
   99029   int aRoot[ArraySize(aTable)];
   99030   u8 aCreateTbl[ArraySize(aTable)];
   99031 
   99032   if( v==0 ) return;
   99033   assert( sqlite3BtreeHoldsAllMutexes(db) );
   99034   assert( sqlite3VdbeDb(v)==db );
   99035   pDb = &db->aDb[iDb];
   99036 
   99037   /* Create new statistic tables if they do not exist, or clear them
   99038   ** if they do already exist.
   99039   */
   99040   for(i=0; i<ArraySize(aTable); i++){
   99041     const char *zTab = aTable[i].zName;
   99042     Table *pStat;
   99043     if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
   99044       if( aTable[i].zCols ){
   99045         /* The sqlite_statN table does not exist. Create it. Note that a
   99046         ** side-effect of the CREATE TABLE statement is to leave the rootpage
   99047         ** of the new table in register pParse->regRoot. This is important
   99048         ** because the OpenWrite opcode below will be needing it. */
   99049         sqlite3NestedParse(pParse,
   99050             "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
   99051         );
   99052         aRoot[i] = pParse->regRoot;
   99053         aCreateTbl[i] = OPFLAG_P2ISREG;
   99054       }
   99055     }else{
   99056       /* The table already exists. If zWhere is not NULL, delete all entries
   99057       ** associated with the table zWhere. If zWhere is NULL, delete the
   99058       ** entire contents of the table. */
   99059       aRoot[i] = pStat->tnum;
   99060       aCreateTbl[i] = 0;
   99061       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   99062       if( zWhere ){
   99063         sqlite3NestedParse(pParse,
   99064            "DELETE FROM %Q.%s WHERE %s=%Q",
   99065            pDb->zDbSName, zTab, zWhereType, zWhere
   99066         );
   99067 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   99068       }else if( db->xPreUpdateCallback ){
   99069         sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
   99070 #endif
   99071       }else{
   99072         /* The sqlite_stat[134] table already exists.  Delete all rows. */
   99073         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   99074       }
   99075     }
   99076   }
   99077 
   99078   /* Open the sqlite_stat[134] tables for writing. */
   99079   for(i=0; aTable[i].zCols; i++){
   99080     assert( i<ArraySize(aTable) );
   99081     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
   99082     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
   99083     VdbeComment((v, aTable[i].zName));
   99084   }
   99085 }
   99086 
   99087 /*
   99088 ** Recommended number of samples for sqlite_stat4
   99089 */
   99090 #ifndef SQLITE_STAT4_SAMPLES
   99091 # define SQLITE_STAT4_SAMPLES 24
   99092 #endif
   99093 
   99094 /*
   99095 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
   99096 ** share an instance of the following structure to hold their state
   99097 ** information.
   99098 */
   99099 typedef struct Stat4Accum Stat4Accum;
   99100 typedef struct Stat4Sample Stat4Sample;
   99101 struct Stat4Sample {
   99102   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
   99103   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
   99104 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99105   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
   99106   union {
   99107     i64 iRowid;                     /* Rowid in main table of the key */
   99108     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
   99109   } u;
   99110   u32 nRowid;                     /* Sizeof aRowid[] */
   99111   u8 isPSample;                   /* True if a periodic sample */
   99112   int iCol;                       /* If !isPSample, the reason for inclusion */
   99113   u32 iHash;                      /* Tiebreaker hash */
   99114 #endif
   99115 };
   99116 struct Stat4Accum {
   99117   tRowcnt nRow;             /* Number of rows in the entire table */
   99118   tRowcnt nPSample;         /* How often to do a periodic sample */
   99119   int nCol;                 /* Number of columns in index + pk/rowid */
   99120   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
   99121   int mxSample;             /* Maximum number of samples to accumulate */
   99122   Stat4Sample current;      /* Current row as a Stat4Sample */
   99123   u32 iPrn;                 /* Pseudo-random number used for sampling */
   99124   Stat4Sample *aBest;       /* Array of nCol best samples */
   99125   int iMin;                 /* Index in a[] of entry with minimum score */
   99126   int nSample;              /* Current number of samples */
   99127   int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
   99128   int iGet;                 /* Index of current sample accessed by stat_get() */
   99129   Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
   99130   sqlite3 *db;              /* Database connection, for malloc() */
   99131 };
   99132 
   99133 /* Reclaim memory used by a Stat4Sample
   99134 */
   99135 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99136 static void sampleClear(sqlite3 *db, Stat4Sample *p){
   99137   assert( db!=0 );
   99138   if( p->nRowid ){
   99139     sqlite3DbFree(db, p->u.aRowid);
   99140     p->nRowid = 0;
   99141   }
   99142 }
   99143 #endif
   99144 
   99145 /* Initialize the BLOB value of a ROWID
   99146 */
   99147 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99148 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
   99149   assert( db!=0 );
   99150   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   99151   p->u.aRowid = sqlite3DbMallocRawNN(db, n);
   99152   if( p->u.aRowid ){
   99153     p->nRowid = n;
   99154     memcpy(p->u.aRowid, pData, n);
   99155   }else{
   99156     p->nRowid = 0;
   99157   }
   99158 }
   99159 #endif
   99160 
   99161 /* Initialize the INTEGER value of a ROWID.
   99162 */
   99163 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99164 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
   99165   assert( db!=0 );
   99166   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   99167   p->nRowid = 0;
   99168   p->u.iRowid = iRowid;
   99169 }
   99170 #endif
   99171 
   99172 
   99173 /*
   99174 ** Copy the contents of object (*pFrom) into (*pTo).
   99175 */
   99176 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99177 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
   99178   pTo->isPSample = pFrom->isPSample;
   99179   pTo->iCol = pFrom->iCol;
   99180   pTo->iHash = pFrom->iHash;
   99181   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
   99182   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
   99183   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
   99184   if( pFrom->nRowid ){
   99185     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
   99186   }else{
   99187     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
   99188   }
   99189 }
   99190 #endif
   99191 
   99192 /*
   99193 ** Reclaim all memory of a Stat4Accum structure.
   99194 */
   99195 static void stat4Destructor(void *pOld){
   99196   Stat4Accum *p = (Stat4Accum*)pOld;
   99197 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99198   int i;
   99199   for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
   99200   for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
   99201   sampleClear(p->db, &p->current);
   99202 #endif
   99203   sqlite3DbFree(p->db, p);
   99204 }
   99205 
   99206 /*
   99207 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
   99208 ** are:
   99209 **     N:    The number of columns in the index including the rowid/pk (note 1)
   99210 **     K:    The number of columns in the index excluding the rowid/pk.
   99211 **     C:    The number of rows in the index (note 2)
   99212 **
   99213 ** Note 1:  In the special case of the covering index that implements a
   99214 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
   99215 ** total number of columns in the table.
   99216 **
   99217 ** Note 2:  C is only used for STAT3 and STAT4.
   99218 **
   99219 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
   99220 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
   99221 ** PRIMARY KEY of the table.  The covering index that implements the
   99222 ** original WITHOUT ROWID table as N==K as a special case.
   99223 **
   99224 ** This routine allocates the Stat4Accum object in heap memory. The return
   99225 ** value is a pointer to the Stat4Accum object.  The datatype of the
   99226 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
   99227 ** object.
   99228 */
   99229 static void statInit(
   99230   sqlite3_context *context,
   99231   int argc,
   99232   sqlite3_value **argv
   99233 ){
   99234   Stat4Accum *p;
   99235   int nCol;                       /* Number of columns in index being sampled */
   99236   int nKeyCol;                    /* Number of key columns */
   99237   int nColUp;                     /* nCol rounded up for alignment */
   99238   int n;                          /* Bytes of space to allocate */
   99239   sqlite3 *db;                    /* Database connection */
   99240 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99241   int mxSample = SQLITE_STAT4_SAMPLES;
   99242 #endif
   99243 
   99244   /* Decode the three function arguments */
   99245   UNUSED_PARAMETER(argc);
   99246   nCol = sqlite3_value_int(argv[0]);
   99247   assert( nCol>0 );
   99248   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
   99249   nKeyCol = sqlite3_value_int(argv[1]);
   99250   assert( nKeyCol<=nCol );
   99251   assert( nKeyCol>0 );
   99252 
   99253   /* Allocate the space required for the Stat4Accum object */
   99254   n = sizeof(*p)
   99255     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
   99256     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
   99257 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99258     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
   99259     + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
   99260     + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
   99261 #endif
   99262   ;
   99263   db = sqlite3_context_db_handle(context);
   99264   p = sqlite3DbMallocZero(db, n);
   99265   if( p==0 ){
   99266     sqlite3_result_error_nomem(context);
   99267     return;
   99268   }
   99269 
   99270   p->db = db;
   99271   p->nRow = 0;
   99272   p->nCol = nCol;
   99273   p->nKeyCol = nKeyCol;
   99274   p->current.anDLt = (tRowcnt*)&p[1];
   99275   p->current.anEq = &p->current.anDLt[nColUp];
   99276 
   99277 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99278   {
   99279     u8 *pSpace;                     /* Allocated space not yet assigned */
   99280     int i;                          /* Used to iterate through p->aSample[] */
   99281 
   99282     p->iGet = -1;
   99283     p->mxSample = mxSample;
   99284     p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
   99285     p->current.anLt = &p->current.anEq[nColUp];
   99286     p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
   99287 
   99288     /* Set up the Stat4Accum.a[] and aBest[] arrays */
   99289     p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
   99290     p->aBest = &p->a[mxSample];
   99291     pSpace = (u8*)(&p->a[mxSample+nCol]);
   99292     for(i=0; i<(mxSample+nCol); i++){
   99293       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   99294       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   99295       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
   99296     }
   99297     assert( (pSpace - (u8*)p)==n );
   99298 
   99299     for(i=0; i<nCol; i++){
   99300       p->aBest[i].iCol = i;
   99301     }
   99302   }
   99303 #endif
   99304 
   99305   /* Return a pointer to the allocated object to the caller.  Note that
   99306   ** only the pointer (the 2nd parameter) matters.  The size of the object
   99307   ** (given by the 3rd parameter) is never used and can be any positive
   99308   ** value. */
   99309   sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
   99310 }
   99311 static const FuncDef statInitFuncdef = {
   99312   2+IsStat34,      /* nArg */
   99313   SQLITE_UTF8,     /* funcFlags */
   99314   0,               /* pUserData */
   99315   0,               /* pNext */
   99316   statInit,        /* xSFunc */
   99317   0,               /* xFinalize */
   99318   "stat_init",     /* zName */
   99319   {0}
   99320 };
   99321 
   99322 #ifdef SQLITE_ENABLE_STAT4
   99323 /*
   99324 ** pNew and pOld are both candidate non-periodic samples selected for
   99325 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
   99326 ** considering only any trailing columns and the sample hash value, this
   99327 ** function returns true if sample pNew is to be preferred over pOld.
   99328 ** In other words, if we assume that the cardinalities of the selected
   99329 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
   99330 **
   99331 ** This function assumes that for each argument sample, the contents of
   99332 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
   99333 */
   99334 static int sampleIsBetterPost(
   99335   Stat4Accum *pAccum,
   99336   Stat4Sample *pNew,
   99337   Stat4Sample *pOld
   99338 ){
   99339   int nCol = pAccum->nCol;
   99340   int i;
   99341   assert( pNew->iCol==pOld->iCol );
   99342   for(i=pNew->iCol+1; i<nCol; i++){
   99343     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
   99344     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
   99345   }
   99346   if( pNew->iHash>pOld->iHash ) return 1;
   99347   return 0;
   99348 }
   99349 #endif
   99350 
   99351 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99352 /*
   99353 ** Return true if pNew is to be preferred over pOld.
   99354 **
   99355 ** This function assumes that for each argument sample, the contents of
   99356 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
   99357 */
   99358 static int sampleIsBetter(
   99359   Stat4Accum *pAccum,
   99360   Stat4Sample *pNew,
   99361   Stat4Sample *pOld
   99362 ){
   99363   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
   99364   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
   99365 
   99366   assert( pOld->isPSample==0 && pNew->isPSample==0 );
   99367   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
   99368 
   99369   if( (nEqNew>nEqOld) ) return 1;
   99370 #ifdef SQLITE_ENABLE_STAT4
   99371   if( nEqNew==nEqOld ){
   99372     if( pNew->iCol<pOld->iCol ) return 1;
   99373     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
   99374   }
   99375   return 0;
   99376 #else
   99377   return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
   99378 #endif
   99379 }
   99380 
   99381 /*
   99382 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
   99383 ** remove the least desirable sample from p->a[] to make room.
   99384 */
   99385 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
   99386   Stat4Sample *pSample = 0;
   99387   int i;
   99388 
   99389   assert( IsStat4 || nEqZero==0 );
   99390 
   99391 #ifdef SQLITE_ENABLE_STAT4
   99392   /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
   99393   ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
   99394   ** other words, if nMaxEqZero is n, then it is guaranteed that there
   99395   ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
   99396   if( nEqZero>p->nMaxEqZero ){
   99397     p->nMaxEqZero = nEqZero;
   99398   }
   99399   if( pNew->isPSample==0 ){
   99400     Stat4Sample *pUpgrade = 0;
   99401     assert( pNew->anEq[pNew->iCol]>0 );
   99402 
   99403     /* This sample is being added because the prefix that ends in column
   99404     ** iCol occurs many times in the table. However, if we have already
   99405     ** added a sample that shares this prefix, there is no need to add
   99406     ** this one. Instead, upgrade the priority of the highest priority
   99407     ** existing sample that shares this prefix.  */
   99408     for(i=p->nSample-1; i>=0; i--){
   99409       Stat4Sample *pOld = &p->a[i];
   99410       if( pOld->anEq[pNew->iCol]==0 ){
   99411         if( pOld->isPSample ) return;
   99412         assert( pOld->iCol>pNew->iCol );
   99413         assert( sampleIsBetter(p, pNew, pOld) );
   99414         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
   99415           pUpgrade = pOld;
   99416         }
   99417       }
   99418     }
   99419     if( pUpgrade ){
   99420       pUpgrade->iCol = pNew->iCol;
   99421       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
   99422       goto find_new_min;
   99423     }
   99424   }
   99425 #endif
   99426 
   99427   /* If necessary, remove sample iMin to make room for the new sample. */
   99428   if( p->nSample>=p->mxSample ){
   99429     Stat4Sample *pMin = &p->a[p->iMin];
   99430     tRowcnt *anEq = pMin->anEq;
   99431     tRowcnt *anLt = pMin->anLt;
   99432     tRowcnt *anDLt = pMin->anDLt;
   99433     sampleClear(p->db, pMin);
   99434     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
   99435     pSample = &p->a[p->nSample-1];
   99436     pSample->nRowid = 0;
   99437     pSample->anEq = anEq;
   99438     pSample->anDLt = anDLt;
   99439     pSample->anLt = anLt;
   99440     p->nSample = p->mxSample-1;
   99441   }
   99442 
   99443   /* The "rows less-than" for the rowid column must be greater than that
   99444   ** for the last sample in the p->a[] array. Otherwise, the samples would
   99445   ** be out of order. */
   99446 #ifdef SQLITE_ENABLE_STAT4
   99447   assert( p->nSample==0
   99448        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
   99449 #endif
   99450 
   99451   /* Insert the new sample */
   99452   pSample = &p->a[p->nSample];
   99453   sampleCopy(p, pSample, pNew);
   99454   p->nSample++;
   99455 
   99456   /* Zero the first nEqZero entries in the anEq[] array. */
   99457   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
   99458 
   99459 #ifdef SQLITE_ENABLE_STAT4
   99460  find_new_min:
   99461 #endif
   99462   if( p->nSample>=p->mxSample ){
   99463     int iMin = -1;
   99464     for(i=0; i<p->mxSample; i++){
   99465       if( p->a[i].isPSample ) continue;
   99466       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
   99467         iMin = i;
   99468       }
   99469     }
   99470     assert( iMin>=0 );
   99471     p->iMin = iMin;
   99472   }
   99473 }
   99474 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   99475 
   99476 /*
   99477 ** Field iChng of the index being scanned has changed. So at this point
   99478 ** p->current contains a sample that reflects the previous row of the
   99479 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
   99480 ** correct at this point.
   99481 */
   99482 static void samplePushPrevious(Stat4Accum *p, int iChng){
   99483 #ifdef SQLITE_ENABLE_STAT4
   99484   int i;
   99485 
   99486   /* Check if any samples from the aBest[] array should be pushed
   99487   ** into IndexSample.a[] at this point.  */
   99488   for(i=(p->nCol-2); i>=iChng; i--){
   99489     Stat4Sample *pBest = &p->aBest[i];
   99490     pBest->anEq[i] = p->current.anEq[i];
   99491     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
   99492       sampleInsert(p, pBest, i);
   99493     }
   99494   }
   99495 
   99496   /* Check that no sample contains an anEq[] entry with an index of
   99497   ** p->nMaxEqZero or greater set to zero. */
   99498   for(i=p->nSample-1; i>=0; i--){
   99499     int j;
   99500     for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
   99501   }
   99502 
   99503   /* Update the anEq[] fields of any samples already collected. */
   99504   if( iChng<p->nMaxEqZero ){
   99505     for(i=p->nSample-1; i>=0; i--){
   99506       int j;
   99507       for(j=iChng; j<p->nCol; j++){
   99508         if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
   99509       }
   99510     }
   99511     p->nMaxEqZero = iChng;
   99512   }
   99513 #endif
   99514 
   99515 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
   99516   if( iChng==0 ){
   99517     tRowcnt nLt = p->current.anLt[0];
   99518     tRowcnt nEq = p->current.anEq[0];
   99519 
   99520     /* Check if this is to be a periodic sample. If so, add it. */
   99521     if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
   99522       p->current.isPSample = 1;
   99523       sampleInsert(p, &p->current, 0);
   99524       p->current.isPSample = 0;
   99525     }else
   99526 
   99527     /* Or if it is a non-periodic sample. Add it in this case too. */
   99528     if( p->nSample<p->mxSample
   99529      || sampleIsBetter(p, &p->current, &p->a[p->iMin])
   99530     ){
   99531       sampleInsert(p, &p->current, 0);
   99532     }
   99533   }
   99534 #endif
   99535 
   99536 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
   99537   UNUSED_PARAMETER( p );
   99538   UNUSED_PARAMETER( iChng );
   99539 #endif
   99540 }
   99541 
   99542 /*
   99543 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
   99544 ** Arguments:
   99545 **
   99546 **    P     Pointer to the Stat4Accum object created by stat_init()
   99547 **    C     Index of left-most column to differ from previous row
   99548 **    R     Rowid for the current row.  Might be a key record for
   99549 **          WITHOUT ROWID tables.
   99550 **
   99551 ** This SQL function always returns NULL.  It's purpose it to accumulate
   99552 ** statistical data and/or samples in the Stat4Accum object about the
   99553 ** index being analyzed.  The stat_get() SQL function will later be used to
   99554 ** extract relevant information for constructing the sqlite_statN tables.
   99555 **
   99556 ** The R parameter is only used for STAT3 and STAT4
   99557 */
   99558 static void statPush(
   99559   sqlite3_context *context,
   99560   int argc,
   99561   sqlite3_value **argv
   99562 ){
   99563   int i;
   99564 
   99565   /* The three function arguments */
   99566   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
   99567   int iChng = sqlite3_value_int(argv[1]);
   99568 
   99569   UNUSED_PARAMETER( argc );
   99570   UNUSED_PARAMETER( context );
   99571   assert( p->nCol>0 );
   99572   assert( iChng<p->nCol );
   99573 
   99574   if( p->nRow==0 ){
   99575     /* This is the first call to this function. Do initialization. */
   99576     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
   99577   }else{
   99578     /* Second and subsequent calls get processed here */
   99579     samplePushPrevious(p, iChng);
   99580 
   99581     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
   99582     ** to the current row of the index. */
   99583     for(i=0; i<iChng; i++){
   99584       p->current.anEq[i]++;
   99585     }
   99586     for(i=iChng; i<p->nCol; i++){
   99587       p->current.anDLt[i]++;
   99588 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99589       p->current.anLt[i] += p->current.anEq[i];
   99590 #endif
   99591       p->current.anEq[i] = 1;
   99592     }
   99593   }
   99594   p->nRow++;
   99595 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99596   if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
   99597     sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
   99598   }else{
   99599     sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
   99600                                        sqlite3_value_blob(argv[2]));
   99601   }
   99602   p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
   99603 #endif
   99604 
   99605 #ifdef SQLITE_ENABLE_STAT4
   99606   {
   99607     tRowcnt nLt = p->current.anLt[p->nCol-1];
   99608 
   99609     /* Check if this is to be a periodic sample. If so, add it. */
   99610     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
   99611       p->current.isPSample = 1;
   99612       p->current.iCol = 0;
   99613       sampleInsert(p, &p->current, p->nCol-1);
   99614       p->current.isPSample = 0;
   99615     }
   99616 
   99617     /* Update the aBest[] array. */
   99618     for(i=0; i<(p->nCol-1); i++){
   99619       p->current.iCol = i;
   99620       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
   99621         sampleCopy(p, &p->aBest[i], &p->current);
   99622       }
   99623     }
   99624   }
   99625 #endif
   99626 }
   99627 static const FuncDef statPushFuncdef = {
   99628   2+IsStat34,      /* nArg */
   99629   SQLITE_UTF8,     /* funcFlags */
   99630   0,               /* pUserData */
   99631   0,               /* pNext */
   99632   statPush,        /* xSFunc */
   99633   0,               /* xFinalize */
   99634   "stat_push",     /* zName */
   99635   {0}
   99636 };
   99637 
   99638 #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
   99639 #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
   99640 #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
   99641 #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
   99642 #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
   99643 
   99644 /*
   99645 ** Implementation of the stat_get(P,J) SQL function.  This routine is
   99646 ** used to query statistical information that has been gathered into
   99647 ** the Stat4Accum object by prior calls to stat_push().  The P parameter
   99648 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
   99649 ** The content to returned is determined by the parameter J
   99650 ** which is one of the STAT_GET_xxxx values defined above.
   99651 **
   99652 ** The stat_get(P,J) function is not available to generic SQL.  It is
   99653 ** inserted as part of a manually constructed bytecode program.  (See
   99654 ** the callStatGet() routine below.)  It is guaranteed that the P
   99655 ** parameter will always be a poiner to a Stat4Accum object, never a
   99656 ** NULL.
   99657 **
   99658 ** If neither STAT3 nor STAT4 are enabled, then J is always
   99659 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
   99660 ** a one-parameter function, stat_get(P), that always returns the
   99661 ** stat1 table entry information.
   99662 */
   99663 static void statGet(
   99664   sqlite3_context *context,
   99665   int argc,
   99666   sqlite3_value **argv
   99667 ){
   99668   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
   99669 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99670   /* STAT3 and STAT4 have a parameter on this routine. */
   99671   int eCall = sqlite3_value_int(argv[1]);
   99672   assert( argc==2 );
   99673   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
   99674        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
   99675        || eCall==STAT_GET_NDLT
   99676   );
   99677   if( eCall==STAT_GET_STAT1 )
   99678 #else
   99679   assert( argc==1 );
   99680 #endif
   99681   {
   99682     /* Return the value to store in the "stat" column of the sqlite_stat1
   99683     ** table for this index.
   99684     **
   99685     ** The value is a string composed of a list of integers describing
   99686     ** the index. The first integer in the list is the total number of
   99687     ** entries in the index. There is one additional integer in the list
   99688     ** for each indexed column. This additional integer is an estimate of
   99689     ** the number of rows matched by a stabbing query on the index using
   99690     ** a key with the corresponding number of fields. In other words,
   99691     ** if the index is on columns (a,b) and the sqlite_stat1 value is
   99692     ** "100 10 2", then SQLite estimates that:
   99693     **
   99694     **   * the index contains 100 rows,
   99695     **   * "WHERE a=?" matches 10 rows, and
   99696     **   * "WHERE a=? AND b=?" matches 2 rows.
   99697     **
   99698     ** If D is the count of distinct values and K is the total number of
   99699     ** rows, then each estimate is computed as:
   99700     **
   99701     **        I = (K+D-1)/D
   99702     */
   99703     char *z;
   99704     int i;
   99705 
   99706     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
   99707     if( zRet==0 ){
   99708       sqlite3_result_error_nomem(context);
   99709       return;
   99710     }
   99711 
   99712     sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
   99713     z = zRet + sqlite3Strlen30(zRet);
   99714     for(i=0; i<p->nKeyCol; i++){
   99715       u64 nDistinct = p->current.anDLt[i] + 1;
   99716       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
   99717       sqlite3_snprintf(24, z, " %llu", iVal);
   99718       z += sqlite3Strlen30(z);
   99719       assert( p->current.anEq[i] );
   99720     }
   99721     assert( z[0]=='\0' && z>zRet );
   99722 
   99723     sqlite3_result_text(context, zRet, -1, sqlite3_free);
   99724   }
   99725 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99726   else if( eCall==STAT_GET_ROWID ){
   99727     if( p->iGet<0 ){
   99728       samplePushPrevious(p, 0);
   99729       p->iGet = 0;
   99730     }
   99731     if( p->iGet<p->nSample ){
   99732       Stat4Sample *pS = p->a + p->iGet;
   99733       if( pS->nRowid==0 ){
   99734         sqlite3_result_int64(context, pS->u.iRowid);
   99735       }else{
   99736         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
   99737                             SQLITE_TRANSIENT);
   99738       }
   99739     }
   99740   }else{
   99741     tRowcnt *aCnt = 0;
   99742 
   99743     assert( p->iGet<p->nSample );
   99744     switch( eCall ){
   99745       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
   99746       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
   99747       default: {
   99748         aCnt = p->a[p->iGet].anDLt;
   99749         p->iGet++;
   99750         break;
   99751       }
   99752     }
   99753 
   99754     if( IsStat3 ){
   99755       sqlite3_result_int64(context, (i64)aCnt[0]);
   99756     }else{
   99757       char *zRet = sqlite3MallocZero(p->nCol * 25);
   99758       if( zRet==0 ){
   99759         sqlite3_result_error_nomem(context);
   99760       }else{
   99761         int i;
   99762         char *z = zRet;
   99763         for(i=0; i<p->nCol; i++){
   99764           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
   99765           z += sqlite3Strlen30(z);
   99766         }
   99767         assert( z[0]=='\0' && z>zRet );
   99768         z[-1] = '\0';
   99769         sqlite3_result_text(context, zRet, -1, sqlite3_free);
   99770       }
   99771     }
   99772   }
   99773 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   99774 #ifndef SQLITE_DEBUG
   99775   UNUSED_PARAMETER( argc );
   99776 #endif
   99777 }
   99778 static const FuncDef statGetFuncdef = {
   99779   1+IsStat34,      /* nArg */
   99780   SQLITE_UTF8,     /* funcFlags */
   99781   0,               /* pUserData */
   99782   0,               /* pNext */
   99783   statGet,         /* xSFunc */
   99784   0,               /* xFinalize */
   99785   "stat_get",      /* zName */
   99786   {0}
   99787 };
   99788 
   99789 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
   99790   assert( regOut!=regStat4 && regOut!=regStat4+1 );
   99791 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99792   sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
   99793 #elif SQLITE_DEBUG
   99794   assert( iParam==STAT_GET_STAT1 );
   99795 #else
   99796   UNUSED_PARAMETER( iParam );
   99797 #endif
   99798   sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
   99799                     (char*)&statGetFuncdef, P4_FUNCDEF);
   99800   sqlite3VdbeChangeP5(v, 1 + IsStat34);
   99801 }
   99802 
   99803 /*
   99804 ** Generate code to do an analysis of all indices associated with
   99805 ** a single table.
   99806 */
   99807 static void analyzeOneTable(
   99808   Parse *pParse,   /* Parser context */
   99809   Table *pTab,     /* Table whose indices are to be analyzed */
   99810   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
   99811   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
   99812   int iMem,        /* Available memory locations begin here */
   99813   int iTab         /* Next available cursor */
   99814 ){
   99815   sqlite3 *db = pParse->db;    /* Database handle */
   99816   Index *pIdx;                 /* An index to being analyzed */
   99817   int iIdxCur;                 /* Cursor open on index being analyzed */
   99818   int iTabCur;                 /* Table cursor */
   99819   Vdbe *v;                     /* The virtual machine being built up */
   99820   int i;                       /* Loop counter */
   99821   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
   99822   int iDb;                     /* Index of database containing pTab */
   99823   u8 needTableCnt = 1;         /* True to count the table */
   99824   int regNewRowid = iMem++;    /* Rowid for the inserted record */
   99825   int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
   99826   int regChng = iMem++;        /* Index of changed index field */
   99827 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99828   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
   99829 #endif
   99830   int regTemp = iMem++;        /* Temporary use register */
   99831   int regTabname = iMem++;     /* Register containing table name */
   99832   int regIdxname = iMem++;     /* Register containing index name */
   99833   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
   99834   int regPrev = iMem;          /* MUST BE LAST (see below) */
   99835 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   99836   Table *pStat1 = 0;
   99837 #endif
   99838 
   99839   pParse->nMem = MAX(pParse->nMem, iMem);
   99840   v = sqlite3GetVdbe(pParse);
   99841   if( v==0 || NEVER(pTab==0) ){
   99842     return;
   99843   }
   99844   if( pTab->tnum==0 ){
   99845     /* Do not gather statistics on views or virtual tables */
   99846     return;
   99847   }
   99848   if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
   99849     /* Do not gather statistics on system tables */
   99850     return;
   99851   }
   99852   assert( sqlite3BtreeHoldsAllMutexes(db) );
   99853   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   99854   assert( iDb>=0 );
   99855   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99856 #ifndef SQLITE_OMIT_AUTHORIZATION
   99857   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   99858       db->aDb[iDb].zDbSName ) ){
   99859     return;
   99860   }
   99861 #endif
   99862 
   99863 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   99864   if( db->xPreUpdateCallback ){
   99865     pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
   99866     if( pStat1==0 ) return;
   99867     pStat1->zName = (char*)&pStat1[1];
   99868     memcpy(pStat1->zName, "sqlite_stat1", 13);
   99869     pStat1->nCol = 3;
   99870     pStat1->iPKey = -1;
   99871     sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
   99872   }
   99873 #endif
   99874 
   99875   /* Establish a read-lock on the table at the shared-cache level.
   99876   ** Open a read-only cursor on the table. Also allocate a cursor number
   99877   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
   99878   ** this time though.  */
   99879   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   99880   iTabCur = iTab++;
   99881   iIdxCur = iTab++;
   99882   pParse->nTab = MAX(pParse->nTab, iTab);
   99883   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
   99884   sqlite3VdbeLoadString(v, regTabname, pTab->zName);
   99885 
   99886   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   99887     int nCol;                     /* Number of columns in pIdx. "N" */
   99888     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
   99889     int addrNextRow;              /* Address of "next_row:" */
   99890     const char *zIdxName;         /* Name of the index */
   99891     int nColTest;                 /* Number of columns to test for changes */
   99892 
   99893     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
   99894     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
   99895     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
   99896       nCol = pIdx->nKeyCol;
   99897       zIdxName = pTab->zName;
   99898       nColTest = nCol - 1;
   99899     }else{
   99900       nCol = pIdx->nColumn;
   99901       zIdxName = pIdx->zName;
   99902       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
   99903     }
   99904 
   99905     /* Populate the register containing the index name. */
   99906     sqlite3VdbeLoadString(v, regIdxname, zIdxName);
   99907     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
   99908 
   99909     /*
   99910     ** Pseudo-code for loop that calls stat_push():
   99911     **
   99912     **   Rewind csr
   99913     **   if eof(csr) goto end_of_scan;
   99914     **   regChng = 0
   99915     **   goto chng_addr_0;
   99916     **
   99917     **  next_row:
   99918     **   regChng = 0
   99919     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
   99920     **   regChng = 1
   99921     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
   99922     **   ...
   99923     **   regChng = N
   99924     **   goto chng_addr_N
   99925     **
   99926     **  chng_addr_0:
   99927     **   regPrev(0) = idx(0)
   99928     **  chng_addr_1:
   99929     **   regPrev(1) = idx(1)
   99930     **  ...
   99931     **
   99932     **  endDistinctTest:
   99933     **   regRowid = idx(rowid)
   99934     **   stat_push(P, regChng, regRowid)
   99935     **   Next csr
   99936     **   if !eof(csr) goto next_row;
   99937     **
   99938     **  end_of_scan:
   99939     */
   99940 
   99941     /* Make sure there are enough memory cells allocated to accommodate
   99942     ** the regPrev array and a trailing rowid (the rowid slot is required
   99943     ** when building a record to insert into the sample column of
   99944     ** the sqlite_stat4 table.  */
   99945     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
   99946 
   99947     /* Open a read-only cursor on the index being analyzed. */
   99948     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
   99949     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
   99950     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   99951     VdbeComment((v, "%s", pIdx->zName));
   99952 
   99953     /* Invoke the stat_init() function. The arguments are:
   99954     **
   99955     **    (1) the number of columns in the index including the rowid
   99956     **        (or for a WITHOUT ROWID table, the number of PK columns),
   99957     **    (2) the number of columns in the key without the rowid/pk
   99958     **    (3) the number of rows in the index,
   99959     **
   99960     **
   99961     ** The third argument is only used for STAT3 and STAT4
   99962     */
   99963 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   99964     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
   99965 #endif
   99966     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
   99967     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
   99968     sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
   99969                      (char*)&statInitFuncdef, P4_FUNCDEF);
   99970     sqlite3VdbeChangeP5(v, 2+IsStat34);
   99971 
   99972     /* Implementation of the following:
   99973     **
   99974     **   Rewind csr
   99975     **   if eof(csr) goto end_of_scan;
   99976     **   regChng = 0
   99977     **   goto next_push_0;
   99978     **
   99979     */
   99980     addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
   99981     VdbeCoverage(v);
   99982     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
   99983     addrNextRow = sqlite3VdbeCurrentAddr(v);
   99984 
   99985     if( nColTest>0 ){
   99986       int endDistinctTest = sqlite3VdbeMakeLabel(v);
   99987       int *aGotoChng;               /* Array of jump instruction addresses */
   99988       aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
   99989       if( aGotoChng==0 ) continue;
   99990 
   99991       /*
   99992       **  next_row:
   99993       **   regChng = 0
   99994       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
   99995       **   regChng = 1
   99996       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
   99997       **   ...
   99998       **   regChng = N
   99999       **   goto endDistinctTest
   100000       */
   100001       sqlite3VdbeAddOp0(v, OP_Goto);
   100002       addrNextRow = sqlite3VdbeCurrentAddr(v);
   100003       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
   100004         /* For a single-column UNIQUE index, once we have found a non-NULL
   100005         ** row, we know that all the rest will be distinct, so skip
   100006         ** subsequent distinctness tests. */
   100007         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
   100008         VdbeCoverage(v);
   100009       }
   100010       for(i=0; i<nColTest; i++){
   100011         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
   100012         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
   100013         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
   100014         aGotoChng[i] =
   100015         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
   100016         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   100017         VdbeCoverage(v);
   100018       }
   100019       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
   100020       sqlite3VdbeGoto(v, endDistinctTest);
   100021 
   100022 
   100023       /*
   100024       **  chng_addr_0:
   100025       **   regPrev(0) = idx(0)
   100026       **  chng_addr_1:
   100027       **   regPrev(1) = idx(1)
   100028       **  ...
   100029       */
   100030       sqlite3VdbeJumpHere(v, addrNextRow-1);
   100031       for(i=0; i<nColTest; i++){
   100032         sqlite3VdbeJumpHere(v, aGotoChng[i]);
   100033         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
   100034       }
   100035       sqlite3VdbeResolveLabel(v, endDistinctTest);
   100036       sqlite3DbFree(db, aGotoChng);
   100037     }
   100038 
   100039     /*
   100040     **  chng_addr_N:
   100041     **   regRowid = idx(rowid)            // STAT34 only
   100042     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
   100043     **   Next csr
   100044     **   if !eof(csr) goto next_row;
   100045     */
   100046 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100047     assert( regRowid==(regStat4+2) );
   100048     if( HasRowid(pTab) ){
   100049       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
   100050     }else{
   100051       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
   100052       int j, k, regKey;
   100053       regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
   100054       for(j=0; j<pPk->nKeyCol; j++){
   100055         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
   100056         assert( k>=0 && k<pIdx->nColumn );
   100057         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
   100058         VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
   100059       }
   100060       sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
   100061       sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
   100062     }
   100063 #endif
   100064     assert( regChng==(regStat4+1) );
   100065     sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
   100066                      (char*)&statPushFuncdef, P4_FUNCDEF);
   100067     sqlite3VdbeChangeP5(v, 2+IsStat34);
   100068     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
   100069 
   100070     /* Add the entry to the stat1 table. */
   100071     callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
   100072     assert( "BBB"[0]==SQLITE_AFF_TEXT );
   100073     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
   100074     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   100075     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
   100076 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   100077     sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
   100078 #endif
   100079     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   100080 
   100081     /* Add the entries to the stat3 or stat4 table. */
   100082 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100083     {
   100084       int regEq = regStat1;
   100085       int regLt = regStat1+1;
   100086       int regDLt = regStat1+2;
   100087       int regSample = regStat1+3;
   100088       int regCol = regStat1+4;
   100089       int regSampleRowid = regCol + nCol;
   100090       int addrNext;
   100091       int addrIsNull;
   100092       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
   100093 
   100094       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
   100095 
   100096       addrNext = sqlite3VdbeCurrentAddr(v);
   100097       callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
   100098       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
   100099       VdbeCoverage(v);
   100100       callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
   100101       callStatGet(v, regStat4, STAT_GET_NLT, regLt);
   100102       callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
   100103       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
   100104       /* We know that the regSampleRowid row exists because it was read by
   100105       ** the previous loop.  Thus the not-found jump of seekOp will never
   100106       ** be taken */
   100107       VdbeCoverageNeverTaken(v);
   100108 #ifdef SQLITE_ENABLE_STAT3
   100109       sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
   100110 #else
   100111       for(i=0; i<nCol; i++){
   100112         sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
   100113       }
   100114       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
   100115 #endif
   100116       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
   100117       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
   100118       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
   100119       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
   100120       sqlite3VdbeJumpHere(v, addrIsNull);
   100121     }
   100122 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   100123 
   100124     /* End of analysis */
   100125     sqlite3VdbeJumpHere(v, addrRewind);
   100126   }
   100127 
   100128 
   100129   /* Create a single sqlite_stat1 entry containing NULL as the index
   100130   ** name and the row count as the content.
   100131   */
   100132   if( pOnlyIdx==0 && needTableCnt ){
   100133     VdbeComment((v, "%s", pTab->zName));
   100134     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
   100135     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
   100136     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
   100137     assert( "BBB"[0]==SQLITE_AFF_TEXT );
   100138     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
   100139     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   100140     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
   100141     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   100142 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   100143     sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
   100144 #endif
   100145     sqlite3VdbeJumpHere(v, jZeroRows);
   100146   }
   100147 }
   100148 
   100149 
   100150 /*
   100151 ** Generate code that will cause the most recent index analysis to
   100152 ** be loaded into internal hash tables where is can be used.
   100153 */
   100154 static void loadAnalysis(Parse *pParse, int iDb){
   100155   Vdbe *v = sqlite3GetVdbe(pParse);
   100156   if( v ){
   100157     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
   100158   }
   100159 }
   100160 
   100161 /*
   100162 ** Generate code that will do an analysis of an entire database
   100163 */
   100164 static void analyzeDatabase(Parse *pParse, int iDb){
   100165   sqlite3 *db = pParse->db;
   100166   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   100167   HashElem *k;
   100168   int iStatCur;
   100169   int iMem;
   100170   int iTab;
   100171 
   100172   sqlite3BeginWriteOperation(pParse, 0, iDb);
   100173   iStatCur = pParse->nTab;
   100174   pParse->nTab += 3;
   100175   openStatTable(pParse, iDb, iStatCur, 0, 0);
   100176   iMem = pParse->nMem+1;
   100177   iTab = pParse->nTab;
   100178   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   100179   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   100180     Table *pTab = (Table*)sqliteHashData(k);
   100181     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
   100182   }
   100183   loadAnalysis(pParse, iDb);
   100184 }
   100185 
   100186 /*
   100187 ** Generate code that will do an analysis of a single table in
   100188 ** a database.  If pOnlyIdx is not NULL then it is a single index
   100189 ** in pTab that should be analyzed.
   100190 */
   100191 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
   100192   int iDb;
   100193   int iStatCur;
   100194 
   100195   assert( pTab!=0 );
   100196   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   100197   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   100198   sqlite3BeginWriteOperation(pParse, 0, iDb);
   100199   iStatCur = pParse->nTab;
   100200   pParse->nTab += 3;
   100201   if( pOnlyIdx ){
   100202     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
   100203   }else{
   100204     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
   100205   }
   100206   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
   100207   loadAnalysis(pParse, iDb);
   100208 }
   100209 
   100210 /*
   100211 ** Generate code for the ANALYZE command.  The parser calls this routine
   100212 ** when it recognizes an ANALYZE command.
   100213 **
   100214 **        ANALYZE                            -- 1
   100215 **        ANALYZE  <database>                -- 2
   100216 **        ANALYZE  ?<database>.?<tablename>  -- 3
   100217 **
   100218 ** Form 1 causes all indices in all attached databases to be analyzed.
   100219 ** Form 2 analyzes all indices the single database named.
   100220 ** Form 3 analyzes all indices associated with the named table.
   100221 */
   100222 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
   100223   sqlite3 *db = pParse->db;
   100224   int iDb;
   100225   int i;
   100226   char *z, *zDb;
   100227   Table *pTab;
   100228   Index *pIdx;
   100229   Token *pTableName;
   100230   Vdbe *v;
   100231 
   100232   /* Read the database schema. If an error occurs, leave an error message
   100233   ** and code in pParse and return NULL. */
   100234   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   100235   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   100236     return;
   100237   }
   100238 
   100239   assert( pName2!=0 || pName1==0 );
   100240   if( pName1==0 ){
   100241     /* Form 1:  Analyze everything */
   100242     for(i=0; i<db->nDb; i++){
   100243       if( i==1 ) continue;  /* Do not analyze the TEMP database */
   100244       analyzeDatabase(pParse, i);
   100245     }
   100246   }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
   100247     /* Analyze the schema named as the argument */
   100248     analyzeDatabase(pParse, iDb);
   100249   }else{
   100250     /* Form 3: Analyze the table or index named as an argument */
   100251     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
   100252     if( iDb>=0 ){
   100253       zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
   100254       z = sqlite3NameFromToken(db, pTableName);
   100255       if( z ){
   100256         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
   100257           analyzeTable(pParse, pIdx->pTable, pIdx);
   100258         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
   100259           analyzeTable(pParse, pTab, 0);
   100260         }
   100261         sqlite3DbFree(db, z);
   100262       }
   100263     }
   100264   }
   100265   if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
   100266     sqlite3VdbeAddOp0(v, OP_Expire);
   100267   }
   100268 }
   100269 
   100270 /*
   100271 ** Used to pass information from the analyzer reader through to the
   100272 ** callback routine.
   100273 */
   100274 typedef struct analysisInfo analysisInfo;
   100275 struct analysisInfo {
   100276   sqlite3 *db;
   100277   const char *zDatabase;
   100278 };
   100279 
   100280 /*
   100281 ** The first argument points to a nul-terminated string containing a
   100282 ** list of space separated integers. Read the first nOut of these into
   100283 ** the array aOut[].
   100284 */
   100285 static void decodeIntArray(
   100286   char *zIntArray,       /* String containing int array to decode */
   100287   int nOut,              /* Number of slots in aOut[] */
   100288   tRowcnt *aOut,         /* Store integers here */
   100289   LogEst *aLog,          /* Or, if aOut==0, here */
   100290   Index *pIndex          /* Handle extra flags for this index, if not NULL */
   100291 ){
   100292   char *z = zIntArray;
   100293   int c;
   100294   int i;
   100295   tRowcnt v;
   100296 
   100297 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100298   if( z==0 ) z = "";
   100299 #else
   100300   assert( z!=0 );
   100301 #endif
   100302   for(i=0; *z && i<nOut; i++){
   100303     v = 0;
   100304     while( (c=z[0])>='0' && c<='9' ){
   100305       v = v*10 + c - '0';
   100306       z++;
   100307     }
   100308 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100309     if( aOut ) aOut[i] = v;
   100310     if( aLog ) aLog[i] = sqlite3LogEst(v);
   100311 #else
   100312     assert( aOut==0 );
   100313     UNUSED_PARAMETER(aOut);
   100314     assert( aLog!=0 );
   100315     aLog[i] = sqlite3LogEst(v);
   100316 #endif
   100317     if( *z==' ' ) z++;
   100318   }
   100319 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
   100320   assert( pIndex!=0 ); {
   100321 #else
   100322   if( pIndex ){
   100323 #endif
   100324     pIndex->bUnordered = 0;
   100325     pIndex->noSkipScan = 0;
   100326     while( z[0] ){
   100327       if( sqlite3_strglob("unordered*", z)==0 ){
   100328         pIndex->bUnordered = 1;
   100329       }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
   100330         pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
   100331       }else if( sqlite3_strglob("noskipscan*", z)==0 ){
   100332         pIndex->noSkipScan = 1;
   100333       }
   100334 #ifdef SQLITE_ENABLE_COSTMULT
   100335       else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
   100336         pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
   100337       }
   100338 #endif
   100339       while( z[0]!=0 && z[0]!=' ' ) z++;
   100340       while( z[0]==' ' ) z++;
   100341     }
   100342   }
   100343 }
   100344 
   100345 /*
   100346 ** This callback is invoked once for each index when reading the
   100347 ** sqlite_stat1 table.
   100348 **
   100349 **     argv[0] = name of the table
   100350 **     argv[1] = name of the index (might be NULL)
   100351 **     argv[2] = results of analysis - on integer for each column
   100352 **
   100353 ** Entries for which argv[1]==NULL simply record the number of rows in
   100354 ** the table.
   100355 */
   100356 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
   100357   analysisInfo *pInfo = (analysisInfo*)pData;
   100358   Index *pIndex;
   100359   Table *pTable;
   100360   const char *z;
   100361 
   100362   assert( argc==3 );
   100363   UNUSED_PARAMETER2(NotUsed, argc);
   100364 
   100365   if( argv==0 || argv[0]==0 || argv[2]==0 ){
   100366     return 0;
   100367   }
   100368   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
   100369   if( pTable==0 ){
   100370     return 0;
   100371   }
   100372   if( argv[1]==0 ){
   100373     pIndex = 0;
   100374   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
   100375     pIndex = sqlite3PrimaryKeyIndex(pTable);
   100376   }else{
   100377     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
   100378   }
   100379   z = argv[2];
   100380 
   100381   if( pIndex ){
   100382     tRowcnt *aiRowEst = 0;
   100383     int nCol = pIndex->nKeyCol+1;
   100384 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100385     /* Index.aiRowEst may already be set here if there are duplicate
   100386     ** sqlite_stat1 entries for this index. In that case just clobber
   100387     ** the old data with the new instead of allocating a new array.  */
   100388     if( pIndex->aiRowEst==0 ){
   100389       pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
   100390       if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
   100391     }
   100392     aiRowEst = pIndex->aiRowEst;
   100393 #endif
   100394     pIndex->bUnordered = 0;
   100395     decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
   100396     pIndex->hasStat1 = 1;
   100397     if( pIndex->pPartIdxWhere==0 ){
   100398       pTable->nRowLogEst = pIndex->aiRowLogEst[0];
   100399       pTable->tabFlags |= TF_HasStat1;
   100400     }
   100401   }else{
   100402     Index fakeIdx;
   100403     fakeIdx.szIdxRow = pTable->szTabRow;
   100404 #ifdef SQLITE_ENABLE_COSTMULT
   100405     fakeIdx.pTable = pTable;
   100406 #endif
   100407     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
   100408     pTable->szTabRow = fakeIdx.szIdxRow;
   100409     pTable->tabFlags |= TF_HasStat1;
   100410   }
   100411 
   100412   return 0;
   100413 }
   100414 
   100415 /*
   100416 ** If the Index.aSample variable is not NULL, delete the aSample[] array
   100417 ** and its contents.
   100418 */
   100419 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
   100420 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100421   if( pIdx->aSample ){
   100422     int j;
   100423     for(j=0; j<pIdx->nSample; j++){
   100424       IndexSample *p = &pIdx->aSample[j];
   100425       sqlite3DbFree(db, p->p);
   100426     }
   100427     sqlite3DbFree(db, pIdx->aSample);
   100428   }
   100429   if( db && db->pnBytesFreed==0 ){
   100430     pIdx->nSample = 0;
   100431     pIdx->aSample = 0;
   100432   }
   100433 #else
   100434   UNUSED_PARAMETER(db);
   100435   UNUSED_PARAMETER(pIdx);
   100436 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   100437 }
   100438 
   100439 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100440 /*
   100441 ** Populate the pIdx->aAvgEq[] array based on the samples currently
   100442 ** stored in pIdx->aSample[].
   100443 */
   100444 static void initAvgEq(Index *pIdx){
   100445   if( pIdx ){
   100446     IndexSample *aSample = pIdx->aSample;
   100447     IndexSample *pFinal = &aSample[pIdx->nSample-1];
   100448     int iCol;
   100449     int nCol = 1;
   100450     if( pIdx->nSampleCol>1 ){
   100451       /* If this is stat4 data, then calculate aAvgEq[] values for all
   100452       ** sample columns except the last. The last is always set to 1, as
   100453       ** once the trailing PK fields are considered all index keys are
   100454       ** unique.  */
   100455       nCol = pIdx->nSampleCol-1;
   100456       pIdx->aAvgEq[nCol] = 1;
   100457     }
   100458     for(iCol=0; iCol<nCol; iCol++){
   100459       int nSample = pIdx->nSample;
   100460       int i;                    /* Used to iterate through samples */
   100461       tRowcnt sumEq = 0;        /* Sum of the nEq values */
   100462       tRowcnt avgEq = 0;
   100463       tRowcnt nRow;             /* Number of rows in index */
   100464       i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
   100465       i64 nDist100;             /* Number of distinct values in index */
   100466 
   100467       if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
   100468         nRow = pFinal->anLt[iCol];
   100469         nDist100 = (i64)100 * pFinal->anDLt[iCol];
   100470         nSample--;
   100471       }else{
   100472         nRow = pIdx->aiRowEst[0];
   100473         nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
   100474       }
   100475       pIdx->nRowEst0 = nRow;
   100476 
   100477       /* Set nSum to the number of distinct (iCol+1) field prefixes that
   100478       ** occur in the stat4 table for this index. Set sumEq to the sum of
   100479       ** the nEq values for column iCol for the same set (adding the value
   100480       ** only once where there exist duplicate prefixes).  */
   100481       for(i=0; i<nSample; i++){
   100482         if( i==(pIdx->nSample-1)
   100483          || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
   100484         ){
   100485           sumEq += aSample[i].anEq[iCol];
   100486           nSum100 += 100;
   100487         }
   100488       }
   100489 
   100490       if( nDist100>nSum100 && sumEq<nRow ){
   100491         avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
   100492       }
   100493       if( avgEq==0 ) avgEq = 1;
   100494       pIdx->aAvgEq[iCol] = avgEq;
   100495     }
   100496   }
   100497 }
   100498 
   100499 /*
   100500 ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
   100501 ** is supplied instead, find the PRIMARY KEY index for that table.
   100502 */
   100503 static Index *findIndexOrPrimaryKey(
   100504   sqlite3 *db,
   100505   const char *zName,
   100506   const char *zDb
   100507 ){
   100508   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
   100509   if( pIdx==0 ){
   100510     Table *pTab = sqlite3FindTable(db, zName, zDb);
   100511     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
   100512   }
   100513   return pIdx;
   100514 }
   100515 
   100516 /*
   100517 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
   100518 ** into the relevant Index.aSample[] arrays.
   100519 **
   100520 ** Arguments zSql1 and zSql2 must point to SQL statements that return
   100521 ** data equivalent to the following (statements are different for stat3,
   100522 ** see the caller of this function for details):
   100523 **
   100524 **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
   100525 **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
   100526 **
   100527 ** where %Q is replaced with the database name before the SQL is executed.
   100528 */
   100529 static int loadStatTbl(
   100530   sqlite3 *db,                  /* Database handle */
   100531   int bStat3,                   /* Assume single column records only */
   100532   const char *zSql1,            /* SQL statement 1 (see above) */
   100533   const char *zSql2,            /* SQL statement 2 (see above) */
   100534   const char *zDb               /* Database name (e.g. "main") */
   100535 ){
   100536   int rc;                       /* Result codes from subroutines */
   100537   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
   100538   char *zSql;                   /* Text of the SQL statement */
   100539   Index *pPrevIdx = 0;          /* Previous index in the loop */
   100540   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
   100541 
   100542   assert( db->lookaside.bDisable );
   100543   zSql = sqlite3MPrintf(db, zSql1, zDb);
   100544   if( !zSql ){
   100545     return SQLITE_NOMEM_BKPT;
   100546   }
   100547   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   100548   sqlite3DbFree(db, zSql);
   100549   if( rc ) return rc;
   100550 
   100551   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   100552     int nIdxCol = 1;              /* Number of columns in stat4 records */
   100553 
   100554     char *zIndex;   /* Index name */
   100555     Index *pIdx;    /* Pointer to the index object */
   100556     int nSample;    /* Number of samples */
   100557     int nByte;      /* Bytes of space required */
   100558     int i;          /* Bytes of space required */
   100559     tRowcnt *pSpace;
   100560 
   100561     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   100562     if( zIndex==0 ) continue;
   100563     nSample = sqlite3_column_int(pStmt, 1);
   100564     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
   100565     assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
   100566     /* Index.nSample is non-zero at this point if data has already been
   100567     ** loaded from the stat4 table. In this case ignore stat3 data.  */
   100568     if( pIdx==0 || pIdx->nSample ) continue;
   100569     if( bStat3==0 ){
   100570       assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
   100571       if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
   100572         nIdxCol = pIdx->nKeyCol;
   100573       }else{
   100574         nIdxCol = pIdx->nColumn;
   100575       }
   100576     }
   100577     pIdx->nSampleCol = nIdxCol;
   100578     nByte = sizeof(IndexSample) * nSample;
   100579     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
   100580     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
   100581 
   100582     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
   100583     if( pIdx->aSample==0 ){
   100584       sqlite3_finalize(pStmt);
   100585       return SQLITE_NOMEM_BKPT;
   100586     }
   100587     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
   100588     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
   100589     for(i=0; i<nSample; i++){
   100590       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
   100591       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
   100592       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
   100593     }
   100594     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
   100595   }
   100596   rc = sqlite3_finalize(pStmt);
   100597   if( rc ) return rc;
   100598 
   100599   zSql = sqlite3MPrintf(db, zSql2, zDb);
   100600   if( !zSql ){
   100601     return SQLITE_NOMEM_BKPT;
   100602   }
   100603   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   100604   sqlite3DbFree(db, zSql);
   100605   if( rc ) return rc;
   100606 
   100607   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   100608     char *zIndex;                 /* Index name */
   100609     Index *pIdx;                  /* Pointer to the index object */
   100610     int nCol = 1;                 /* Number of columns in index */
   100611 
   100612     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   100613     if( zIndex==0 ) continue;
   100614     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
   100615     if( pIdx==0 ) continue;
   100616     /* This next condition is true if data has already been loaded from
   100617     ** the sqlite_stat4 table. In this case ignore stat3 data.  */
   100618     nCol = pIdx->nSampleCol;
   100619     if( bStat3 && nCol>1 ) continue;
   100620     if( pIdx!=pPrevIdx ){
   100621       initAvgEq(pPrevIdx);
   100622       pPrevIdx = pIdx;
   100623     }
   100624     pSample = &pIdx->aSample[pIdx->nSample];
   100625     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
   100626     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
   100627     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
   100628 
   100629     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
   100630     ** This is in case the sample record is corrupted. In that case, the
   100631     ** sqlite3VdbeRecordCompare() may read up to two varints past the
   100632     ** end of the allocated buffer before it realizes it is dealing with
   100633     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
   100634     ** a buffer overread.  */
   100635     pSample->n = sqlite3_column_bytes(pStmt, 4);
   100636     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
   100637     if( pSample->p==0 ){
   100638       sqlite3_finalize(pStmt);
   100639       return SQLITE_NOMEM_BKPT;
   100640     }
   100641     if( pSample->n ){
   100642       memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
   100643     }
   100644     pIdx->nSample++;
   100645   }
   100646   rc = sqlite3_finalize(pStmt);
   100647   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
   100648   return rc;
   100649 }
   100650 
   100651 /*
   100652 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
   100653 ** the Index.aSample[] arrays of all indices.
   100654 */
   100655 static int loadStat4(sqlite3 *db, const char *zDb){
   100656   int rc = SQLITE_OK;             /* Result codes from subroutines */
   100657 
   100658   assert( db->lookaside.bDisable );
   100659   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
   100660     rc = loadStatTbl(db, 0,
   100661       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
   100662       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
   100663       zDb
   100664     );
   100665   }
   100666 
   100667   if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
   100668     rc = loadStatTbl(db, 1,
   100669       "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
   100670       "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
   100671       zDb
   100672     );
   100673   }
   100674 
   100675   return rc;
   100676 }
   100677 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   100678 
   100679 /*
   100680 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
   100681 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
   100682 ** arrays. The contents of sqlite_stat3/4 are used to populate the
   100683 ** Index.aSample[] arrays.
   100684 **
   100685 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
   100686 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
   100687 ** during compilation and the sqlite_stat3/4 table is present, no data is
   100688 ** read from it.
   100689 **
   100690 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
   100691 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
   100692 ** returned. However, in this case, data is read from the sqlite_stat1
   100693 ** table (if it is present) before returning.
   100694 **
   100695 ** If an OOM error occurs, this function always sets db->mallocFailed.
   100696 ** This means if the caller does not care about other errors, the return
   100697 ** code may be ignored.
   100698 */
   100699 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   100700   analysisInfo sInfo;
   100701   HashElem *i;
   100702   char *zSql;
   100703   int rc = SQLITE_OK;
   100704   Schema *pSchema = db->aDb[iDb].pSchema;
   100705 
   100706   assert( iDb>=0 && iDb<db->nDb );
   100707   assert( db->aDb[iDb].pBt!=0 );
   100708 
   100709   /* Clear any prior statistics */
   100710   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   100711   for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
   100712     Table *pTab = sqliteHashData(i);
   100713     pTab->tabFlags &= ~TF_HasStat1;
   100714   }
   100715   for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
   100716     Index *pIdx = sqliteHashData(i);
   100717     pIdx->hasStat1 = 0;
   100718 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100719     sqlite3DeleteIndexSamples(db, pIdx);
   100720     pIdx->aSample = 0;
   100721 #endif
   100722   }
   100723 
   100724   /* Load new statistics out of the sqlite_stat1 table */
   100725   sInfo.db = db;
   100726   sInfo.zDatabase = db->aDb[iDb].zDbSName;
   100727   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
   100728     zSql = sqlite3MPrintf(db,
   100729         "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
   100730     if( zSql==0 ){
   100731       rc = SQLITE_NOMEM_BKPT;
   100732     }else{
   100733       rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
   100734       sqlite3DbFree(db, zSql);
   100735     }
   100736   }
   100737 
   100738   /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
   100739   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   100740   for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
   100741     Index *pIdx = sqliteHashData(i);
   100742     if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
   100743   }
   100744 
   100745   /* Load the statistics from the sqlite_stat4 table. */
   100746 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   100747   if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
   100748     db->lookaside.bDisable++;
   100749     rc = loadStat4(db, sInfo.zDatabase);
   100750     db->lookaside.bDisable--;
   100751   }
   100752   for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
   100753     Index *pIdx = sqliteHashData(i);
   100754     sqlite3_free(pIdx->aiRowEst);
   100755     pIdx->aiRowEst = 0;
   100756   }
   100757 #endif
   100758 
   100759   if( rc==SQLITE_NOMEM ){
   100760     sqlite3OomFault(db);
   100761   }
   100762   return rc;
   100763 }
   100764 
   100765 
   100766 #endif /* SQLITE_OMIT_ANALYZE */
   100767 
   100768 /************** End of analyze.c *********************************************/
   100769 /************** Begin file attach.c ******************************************/
   100770 /*
   100771 ** 2003 April 6
   100772 **
   100773 ** The author disclaims copyright to this source code.  In place of
   100774 ** a legal notice, here is a blessing:
   100775 **
   100776 **    May you do good and not evil.
   100777 **    May you find forgiveness for yourself and forgive others.
   100778 **    May you share freely, never taking more than you give.
   100779 **
   100780 *************************************************************************
   100781 ** This file contains code used to implement the ATTACH and DETACH commands.
   100782 */
   100783 /* #include "sqliteInt.h" */
   100784 
   100785 #ifndef SQLITE_OMIT_ATTACH
   100786 /*
   100787 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
   100788 ** is slightly different from resolving a normal SQL expression, because simple
   100789 ** identifiers are treated as strings, not possible column names or aliases.
   100790 **
   100791 ** i.e. if the parser sees:
   100792 **
   100793 **     ATTACH DATABASE abc AS def
   100794 **
   100795 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
   100796 ** looking for columns of the same name.
   100797 **
   100798 ** This only applies to the root node of pExpr, so the statement:
   100799 **
   100800 **     ATTACH DATABASE abc||def AS 'db2'
   100801 **
   100802 ** will fail because neither abc or def can be resolved.
   100803 */
   100804 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
   100805 {
   100806   int rc = SQLITE_OK;
   100807   if( pExpr ){
   100808     if( pExpr->op!=TK_ID ){
   100809       rc = sqlite3ResolveExprNames(pName, pExpr);
   100810     }else{
   100811       pExpr->op = TK_STRING;
   100812     }
   100813   }
   100814   return rc;
   100815 }
   100816 
   100817 /*
   100818 ** An SQL user-function registered to do the work of an ATTACH statement. The
   100819 ** three arguments to the function come directly from an attach statement:
   100820 **
   100821 **     ATTACH DATABASE x AS y KEY z
   100822 **
   100823 **     SELECT sqlite_attach(x, y, z)
   100824 **
   100825 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
   100826 ** third argument.
   100827 */
   100828 static void attachFunc(
   100829   sqlite3_context *context,
   100830   int NotUsed,
   100831   sqlite3_value **argv
   100832 ){
   100833   int i;
   100834   int rc = 0;
   100835   sqlite3 *db = sqlite3_context_db_handle(context);
   100836   const char *zName;
   100837   const char *zFile;
   100838   char *zPath = 0;
   100839   char *zErr = 0;
   100840   unsigned int flags;
   100841   Db *aNew;                 /* New array of Db pointers */
   100842   Db *pNew;                 /* Db object for the newly attached database */
   100843   char *zErrDyn = 0;
   100844   sqlite3_vfs *pVfs;
   100845 
   100846   UNUSED_PARAMETER(NotUsed);
   100847 
   100848   zFile = (const char *)sqlite3_value_text(argv[0]);
   100849   zName = (const char *)sqlite3_value_text(argv[1]);
   100850   if( zFile==0 ) zFile = "";
   100851   if( zName==0 ) zName = "";
   100852 
   100853   /* Check for the following errors:
   100854   **
   100855   **     * Too many attached databases,
   100856   **     * Transaction currently open
   100857   **     * Specified database name already being used.
   100858   */
   100859   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
   100860     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
   100861       db->aLimit[SQLITE_LIMIT_ATTACHED]
   100862     );
   100863     goto attach_error;
   100864   }
   100865   for(i=0; i<db->nDb; i++){
   100866     char *z = db->aDb[i].zDbSName;
   100867     assert( z && zName );
   100868     if( sqlite3StrICmp(z, zName)==0 ){
   100869       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   100870       goto attach_error;
   100871     }
   100872   }
   100873 
   100874   /* Allocate the new entry in the db->aDb[] array and initialize the schema
   100875   ** hash tables.
   100876   */
   100877   if( db->aDb==db->aDbStatic ){
   100878     aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
   100879     if( aNew==0 ) return;
   100880     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   100881   }else{
   100882     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   100883     if( aNew==0 ) return;
   100884   }
   100885   db->aDb = aNew;
   100886   pNew = &db->aDb[db->nDb];
   100887   memset(pNew, 0, sizeof(*pNew));
   100888 
   100889   /* Open the database file. If the btree is successfully opened, use
   100890   ** it to obtain the database schema. At this point the schema may
   100891   ** or may not be initialized.
   100892   */
   100893   flags = db->openFlags;
   100894   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
   100895   if( rc!=SQLITE_OK ){
   100896     if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
   100897     sqlite3_result_error(context, zErr, -1);
   100898     sqlite3_free(zErr);
   100899     return;
   100900   }
   100901   assert( pVfs );
   100902   flags |= SQLITE_OPEN_MAIN_DB;
   100903   rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
   100904   sqlite3_free( zPath );
   100905   db->nDb++;
   100906   db->skipBtreeMutex = 0;
   100907   if( rc==SQLITE_CONSTRAINT ){
   100908     rc = SQLITE_ERROR;
   100909     zErrDyn = sqlite3MPrintf(db, "database is already attached");
   100910   }else if( rc==SQLITE_OK ){
   100911     Pager *pPager;
   100912     pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
   100913     if( !pNew->pSchema ){
   100914       rc = SQLITE_NOMEM_BKPT;
   100915     }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
   100916       zErrDyn = sqlite3MPrintf(db,
   100917         "attached databases must use the same text encoding as main database");
   100918       rc = SQLITE_ERROR;
   100919     }
   100920     sqlite3BtreeEnter(pNew->pBt);
   100921     pPager = sqlite3BtreePager(pNew->pBt);
   100922     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
   100923     sqlite3BtreeSecureDelete(pNew->pBt,
   100924                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
   100925 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   100926     sqlite3BtreeSetPagerFlags(pNew->pBt,
   100927                       PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
   100928 #endif
   100929     sqlite3BtreeLeave(pNew->pBt);
   100930   }
   100931   pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
   100932   pNew->zDbSName = sqlite3DbStrDup(db, zName);
   100933   if( rc==SQLITE_OK && pNew->zDbSName==0 ){
   100934     rc = SQLITE_NOMEM_BKPT;
   100935   }
   100936 
   100937 
   100938 #ifdef SQLITE_HAS_CODEC
   100939   if( rc==SQLITE_OK ){
   100940     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
   100941     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   100942     int nKey;
   100943     char *zKey;
   100944     int t = sqlite3_value_type(argv[2]);
   100945     switch( t ){
   100946       case SQLITE_INTEGER:
   100947       case SQLITE_FLOAT:
   100948         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
   100949         rc = SQLITE_ERROR;
   100950         break;
   100951 
   100952       case SQLITE_TEXT:
   100953       case SQLITE_BLOB:
   100954         nKey = sqlite3_value_bytes(argv[2]);
   100955         zKey = (char *)sqlite3_value_blob(argv[2]);
   100956         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   100957         break;
   100958 
   100959       case SQLITE_NULL:
   100960         /* No key specified.  Use the key from the main database */
   100961         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   100962         if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
   100963           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   100964         }
   100965         break;
   100966     }
   100967   }
   100968 #endif
   100969 
   100970   /* If the file was opened successfully, read the schema for the new database.
   100971   ** If this fails, or if opening the file failed, then close the file and
   100972   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
   100973   ** we found it.
   100974   */
   100975   if( rc==SQLITE_OK ){
   100976     sqlite3BtreeEnterAll(db);
   100977     rc = sqlite3Init(db, &zErrDyn);
   100978     sqlite3BtreeLeaveAll(db);
   100979   }
   100980 #ifdef SQLITE_USER_AUTHENTICATION
   100981   if( rc==SQLITE_OK ){
   100982     u8 newAuth = 0;
   100983     rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
   100984     if( newAuth<db->auth.authLevel ){
   100985       rc = SQLITE_AUTH_USER;
   100986     }
   100987   }
   100988 #endif
   100989   if( rc ){
   100990     int iDb = db->nDb - 1;
   100991     assert( iDb>=2 );
   100992     if( db->aDb[iDb].pBt ){
   100993       sqlite3BtreeClose(db->aDb[iDb].pBt);
   100994       db->aDb[iDb].pBt = 0;
   100995       db->aDb[iDb].pSchema = 0;
   100996     }
   100997     sqlite3ResetAllSchemasOfConnection(db);
   100998     db->nDb = iDb;
   100999     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   101000       sqlite3OomFault(db);
   101001       sqlite3DbFree(db, zErrDyn);
   101002       zErrDyn = sqlite3MPrintf(db, "out of memory");
   101003     }else if( zErrDyn==0 ){
   101004       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   101005     }
   101006     goto attach_error;
   101007   }
   101008 
   101009   return;
   101010 
   101011 attach_error:
   101012   /* Return an error if we get here */
   101013   if( zErrDyn ){
   101014     sqlite3_result_error(context, zErrDyn, -1);
   101015     sqlite3DbFree(db, zErrDyn);
   101016   }
   101017   if( rc ) sqlite3_result_error_code(context, rc);
   101018 }
   101019 
   101020 /*
   101021 ** An SQL user-function registered to do the work of an DETACH statement. The
   101022 ** three arguments to the function come directly from a detach statement:
   101023 **
   101024 **     DETACH DATABASE x
   101025 **
   101026 **     SELECT sqlite_detach(x)
   101027 */
   101028 static void detachFunc(
   101029   sqlite3_context *context,
   101030   int NotUsed,
   101031   sqlite3_value **argv
   101032 ){
   101033   const char *zName = (const char *)sqlite3_value_text(argv[0]);
   101034   sqlite3 *db = sqlite3_context_db_handle(context);
   101035   int i;
   101036   Db *pDb = 0;
   101037   char zErr[128];
   101038 
   101039   UNUSED_PARAMETER(NotUsed);
   101040 
   101041   if( zName==0 ) zName = "";
   101042   for(i=0; i<db->nDb; i++){
   101043     pDb = &db->aDb[i];
   101044     if( pDb->pBt==0 ) continue;
   101045     if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
   101046   }
   101047 
   101048   if( i>=db->nDb ){
   101049     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   101050     goto detach_error;
   101051   }
   101052   if( i<2 ){
   101053     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
   101054     goto detach_error;
   101055   }
   101056   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
   101057     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
   101058     goto detach_error;
   101059   }
   101060 
   101061   sqlite3BtreeClose(pDb->pBt);
   101062   pDb->pBt = 0;
   101063   pDb->pSchema = 0;
   101064   sqlite3CollapseDatabaseArray(db);
   101065   return;
   101066 
   101067 detach_error:
   101068   sqlite3_result_error(context, zErr, -1);
   101069 }
   101070 
   101071 /*
   101072 ** This procedure generates VDBE code for a single invocation of either the
   101073 ** sqlite_detach() or sqlite_attach() SQL user functions.
   101074 */
   101075 static void codeAttach(
   101076   Parse *pParse,       /* The parser context */
   101077   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
   101078   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
   101079   Expr *pAuthArg,      /* Expression to pass to authorization callback */
   101080   Expr *pFilename,     /* Name of database file */
   101081   Expr *pDbname,       /* Name of the database to use internally */
   101082   Expr *pKey           /* Database key for encryption extension */
   101083 ){
   101084   int rc;
   101085   NameContext sName;
   101086   Vdbe *v;
   101087   sqlite3* db = pParse->db;
   101088   int regArgs;
   101089 
   101090   if( pParse->nErr ) goto attach_end;
   101091   memset(&sName, 0, sizeof(NameContext));
   101092   sName.pParse = pParse;
   101093 
   101094   if(
   101095       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
   101096       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
   101097       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
   101098   ){
   101099     goto attach_end;
   101100   }
   101101 
   101102 #ifndef SQLITE_OMIT_AUTHORIZATION
   101103   if( pAuthArg ){
   101104     char *zAuthArg;
   101105     if( pAuthArg->op==TK_STRING ){
   101106       zAuthArg = pAuthArg->u.zToken;
   101107     }else{
   101108       zAuthArg = 0;
   101109     }
   101110     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
   101111     if(rc!=SQLITE_OK ){
   101112       goto attach_end;
   101113     }
   101114   }
   101115 #endif /* SQLITE_OMIT_AUTHORIZATION */
   101116 
   101117 
   101118   v = sqlite3GetVdbe(pParse);
   101119   regArgs = sqlite3GetTempRange(pParse, 4);
   101120   sqlite3ExprCode(pParse, pFilename, regArgs);
   101121   sqlite3ExprCode(pParse, pDbname, regArgs+1);
   101122   sqlite3ExprCode(pParse, pKey, regArgs+2);
   101123 
   101124   assert( v || db->mallocFailed );
   101125   if( v ){
   101126     sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
   101127                       (char *)pFunc, P4_FUNCDEF);
   101128     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
   101129     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
   101130 
   101131     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
   101132     ** statement only). For DETACH, set it to false (expire all existing
   101133     ** statements).
   101134     */
   101135     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   101136   }
   101137 
   101138 attach_end:
   101139   sqlite3ExprDelete(db, pFilename);
   101140   sqlite3ExprDelete(db, pDbname);
   101141   sqlite3ExprDelete(db, pKey);
   101142 }
   101143 
   101144 /*
   101145 ** Called by the parser to compile a DETACH statement.
   101146 **
   101147 **     DETACH pDbname
   101148 */
   101149 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
   101150   static const FuncDef detach_func = {
   101151     1,                /* nArg */
   101152     SQLITE_UTF8,      /* funcFlags */
   101153     0,                /* pUserData */
   101154     0,                /* pNext */
   101155     detachFunc,       /* xSFunc */
   101156     0,                /* xFinalize */
   101157     "sqlite_detach",  /* zName */
   101158     {0}
   101159   };
   101160   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
   101161 }
   101162 
   101163 /*
   101164 ** Called by the parser to compile an ATTACH statement.
   101165 **
   101166 **     ATTACH p AS pDbname KEY pKey
   101167 */
   101168 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
   101169   static const FuncDef attach_func = {
   101170     3,                /* nArg */
   101171     SQLITE_UTF8,      /* funcFlags */
   101172     0,                /* pUserData */
   101173     0,                /* pNext */
   101174     attachFunc,       /* xSFunc */
   101175     0,                /* xFinalize */
   101176     "sqlite_attach",  /* zName */
   101177     {0}
   101178   };
   101179   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
   101180 }
   101181 #endif /* SQLITE_OMIT_ATTACH */
   101182 
   101183 /*
   101184 ** Initialize a DbFixer structure.  This routine must be called prior
   101185 ** to passing the structure to one of the sqliteFixAAAA() routines below.
   101186 */
   101187 SQLITE_PRIVATE void sqlite3FixInit(
   101188   DbFixer *pFix,      /* The fixer to be initialized */
   101189   Parse *pParse,      /* Error messages will be written here */
   101190   int iDb,            /* This is the database that must be used */
   101191   const char *zType,  /* "view", "trigger", or "index" */
   101192   const Token *pName  /* Name of the view, trigger, or index */
   101193 ){
   101194   sqlite3 *db;
   101195 
   101196   db = pParse->db;
   101197   assert( db->nDb>iDb );
   101198   pFix->pParse = pParse;
   101199   pFix->zDb = db->aDb[iDb].zDbSName;
   101200   pFix->pSchema = db->aDb[iDb].pSchema;
   101201   pFix->zType = zType;
   101202   pFix->pName = pName;
   101203   pFix->bVarOnly = (iDb==1);
   101204 }
   101205 
   101206 /*
   101207 ** The following set of routines walk through the parse tree and assign
   101208 ** a specific database to all table references where the database name
   101209 ** was left unspecified in the original SQL statement.  The pFix structure
   101210 ** must have been initialized by a prior call to sqlite3FixInit().
   101211 **
   101212 ** These routines are used to make sure that an index, trigger, or
   101213 ** view in one database does not refer to objects in a different database.
   101214 ** (Exception: indices, triggers, and views in the TEMP database are
   101215 ** allowed to refer to anything.)  If a reference is explicitly made
   101216 ** to an object in a different database, an error message is added to
   101217 ** pParse->zErrMsg and these routines return non-zero.  If everything
   101218 ** checks out, these routines return 0.
   101219 */
   101220 SQLITE_PRIVATE int sqlite3FixSrcList(
   101221   DbFixer *pFix,       /* Context of the fixation */
   101222   SrcList *pList       /* The Source list to check and modify */
   101223 ){
   101224   int i;
   101225   const char *zDb;
   101226   struct SrcList_item *pItem;
   101227 
   101228   if( NEVER(pList==0) ) return 0;
   101229   zDb = pFix->zDb;
   101230   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   101231     if( pFix->bVarOnly==0 ){
   101232       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
   101233         sqlite3ErrorMsg(pFix->pParse,
   101234             "%s %T cannot reference objects in database %s",
   101235             pFix->zType, pFix->pName, pItem->zDatabase);
   101236         return 1;
   101237       }
   101238       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
   101239       pItem->zDatabase = 0;
   101240       pItem->pSchema = pFix->pSchema;
   101241     }
   101242 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   101243     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
   101244     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
   101245 #endif
   101246   }
   101247   return 0;
   101248 }
   101249 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   101250 SQLITE_PRIVATE int sqlite3FixSelect(
   101251   DbFixer *pFix,       /* Context of the fixation */
   101252   Select *pSelect      /* The SELECT statement to be fixed to one database */
   101253 ){
   101254   while( pSelect ){
   101255     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
   101256       return 1;
   101257     }
   101258     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
   101259       return 1;
   101260     }
   101261     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
   101262       return 1;
   101263     }
   101264     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
   101265       return 1;
   101266     }
   101267     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
   101268       return 1;
   101269     }
   101270     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
   101271       return 1;
   101272     }
   101273     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
   101274       return 1;
   101275     }
   101276     pSelect = pSelect->pPrior;
   101277   }
   101278   return 0;
   101279 }
   101280 SQLITE_PRIVATE int sqlite3FixExpr(
   101281   DbFixer *pFix,     /* Context of the fixation */
   101282   Expr *pExpr        /* The expression to be fixed to one database */
   101283 ){
   101284   while( pExpr ){
   101285     if( pExpr->op==TK_VARIABLE ){
   101286       if( pFix->pParse->db->init.busy ){
   101287         pExpr->op = TK_NULL;
   101288       }else{
   101289         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
   101290         return 1;
   101291       }
   101292     }
   101293     if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
   101294     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   101295       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
   101296     }else{
   101297       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
   101298     }
   101299     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
   101300       return 1;
   101301     }
   101302     pExpr = pExpr->pLeft;
   101303   }
   101304   return 0;
   101305 }
   101306 SQLITE_PRIVATE int sqlite3FixExprList(
   101307   DbFixer *pFix,     /* Context of the fixation */
   101308   ExprList *pList    /* The expression to be fixed to one database */
   101309 ){
   101310   int i;
   101311   struct ExprList_item *pItem;
   101312   if( pList==0 ) return 0;
   101313   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
   101314     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
   101315       return 1;
   101316     }
   101317   }
   101318   return 0;
   101319 }
   101320 #endif
   101321 
   101322 #ifndef SQLITE_OMIT_TRIGGER
   101323 SQLITE_PRIVATE int sqlite3FixTriggerStep(
   101324   DbFixer *pFix,     /* Context of the fixation */
   101325   TriggerStep *pStep /* The trigger step be fixed to one database */
   101326 ){
   101327   while( pStep ){
   101328     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
   101329       return 1;
   101330     }
   101331     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
   101332       return 1;
   101333     }
   101334     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
   101335       return 1;
   101336     }
   101337     pStep = pStep->pNext;
   101338   }
   101339   return 0;
   101340 }
   101341 #endif
   101342 
   101343 /************** End of attach.c **********************************************/
   101344 /************** Begin file auth.c ********************************************/
   101345 /*
   101346 ** 2003 January 11
   101347 **
   101348 ** The author disclaims copyright to this source code.  In place of
   101349 ** a legal notice, here is a blessing:
   101350 **
   101351 **    May you do good and not evil.
   101352 **    May you find forgiveness for yourself and forgive others.
   101353 **    May you share freely, never taking more than you give.
   101354 **
   101355 *************************************************************************
   101356 ** This file contains code used to implement the sqlite3_set_authorizer()
   101357 ** API.  This facility is an optional feature of the library.  Embedded
   101358 ** systems that do not need this facility may omit it by recompiling
   101359 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
   101360 */
   101361 /* #include "sqliteInt.h" */
   101362 
   101363 /*
   101364 ** All of the code in this file may be omitted by defining a single
   101365 ** macro.
   101366 */
   101367 #ifndef SQLITE_OMIT_AUTHORIZATION
   101368 
   101369 /*
   101370 ** Set or clear the access authorization function.
   101371 **
   101372 ** The access authorization function is be called during the compilation
   101373 ** phase to verify that the user has read and/or write access permission on
   101374 ** various fields of the database.  The first argument to the auth function
   101375 ** is a copy of the 3rd argument to this routine.  The second argument
   101376 ** to the auth function is one of these constants:
   101377 **
   101378 **       SQLITE_CREATE_INDEX
   101379 **       SQLITE_CREATE_TABLE
   101380 **       SQLITE_CREATE_TEMP_INDEX
   101381 **       SQLITE_CREATE_TEMP_TABLE
   101382 **       SQLITE_CREATE_TEMP_TRIGGER
   101383 **       SQLITE_CREATE_TEMP_VIEW
   101384 **       SQLITE_CREATE_TRIGGER
   101385 **       SQLITE_CREATE_VIEW
   101386 **       SQLITE_DELETE
   101387 **       SQLITE_DROP_INDEX
   101388 **       SQLITE_DROP_TABLE
   101389 **       SQLITE_DROP_TEMP_INDEX
   101390 **       SQLITE_DROP_TEMP_TABLE
   101391 **       SQLITE_DROP_TEMP_TRIGGER
   101392 **       SQLITE_DROP_TEMP_VIEW
   101393 **       SQLITE_DROP_TRIGGER
   101394 **       SQLITE_DROP_VIEW
   101395 **       SQLITE_INSERT
   101396 **       SQLITE_PRAGMA
   101397 **       SQLITE_READ
   101398 **       SQLITE_SELECT
   101399 **       SQLITE_TRANSACTION
   101400 **       SQLITE_UPDATE
   101401 **
   101402 ** The third and fourth arguments to the auth function are the name of
   101403 ** the table and the column that are being accessed.  The auth function
   101404 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
   101405 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
   101406 ** means that the SQL statement will never-run - the sqlite3_exec() call
   101407 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
   101408 ** should run but attempts to read the specified column will return NULL
   101409 ** and attempts to write the column will be ignored.
   101410 **
   101411 ** Setting the auth function to NULL disables this hook.  The default
   101412 ** setting of the auth function is NULL.
   101413 */
   101414 SQLITE_API int sqlite3_set_authorizer(
   101415   sqlite3 *db,
   101416   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   101417   void *pArg
   101418 ){
   101419 #ifdef SQLITE_ENABLE_API_ARMOR
   101420   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   101421 #endif
   101422   sqlite3_mutex_enter(db->mutex);
   101423   db->xAuth = (sqlite3_xauth)xAuth;
   101424   db->pAuthArg = pArg;
   101425   sqlite3ExpirePreparedStatements(db);
   101426   sqlite3_mutex_leave(db->mutex);
   101427   return SQLITE_OK;
   101428 }
   101429 
   101430 /*
   101431 ** Write an error message into pParse->zErrMsg that explains that the
   101432 ** user-supplied authorization function returned an illegal value.
   101433 */
   101434 static void sqliteAuthBadReturnCode(Parse *pParse){
   101435   sqlite3ErrorMsg(pParse, "authorizer malfunction");
   101436   pParse->rc = SQLITE_ERROR;
   101437 }
   101438 
   101439 /*
   101440 ** Invoke the authorization callback for permission to read column zCol from
   101441 ** table zTab in database zDb. This function assumes that an authorization
   101442 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
   101443 **
   101444 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
   101445 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
   101446 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
   101447 */
   101448 SQLITE_PRIVATE int sqlite3AuthReadCol(
   101449   Parse *pParse,                  /* The parser context */
   101450   const char *zTab,               /* Table name */
   101451   const char *zCol,               /* Column name */
   101452   int iDb                         /* Index of containing database. */
   101453 ){
   101454   sqlite3 *db = pParse->db;          /* Database handle */
   101455   char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
   101456   int rc;                            /* Auth callback return code */
   101457 
   101458   if( db->init.busy ) return SQLITE_OK;
   101459   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
   101460 #ifdef SQLITE_USER_AUTHENTICATION
   101461                  ,db->auth.zAuthUser
   101462 #endif
   101463                 );
   101464   if( rc==SQLITE_DENY ){
   101465     char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
   101466     if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
   101467     sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
   101468     pParse->rc = SQLITE_AUTH;
   101469   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
   101470     sqliteAuthBadReturnCode(pParse);
   101471   }
   101472   return rc;
   101473 }
   101474 
   101475 /*
   101476 ** The pExpr should be a TK_COLUMN expression.  The table referred to
   101477 ** is in pTabList or else it is the NEW or OLD table of a trigger.
   101478 ** Check to see if it is OK to read this particular column.
   101479 **
   101480 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
   101481 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
   101482 ** then generate an error.
   101483 */
   101484 SQLITE_PRIVATE void sqlite3AuthRead(
   101485   Parse *pParse,        /* The parser context */
   101486   Expr *pExpr,          /* The expression to check authorization on */
   101487   Schema *pSchema,      /* The schema of the expression */
   101488   SrcList *pTabList     /* All table that pExpr might refer to */
   101489 ){
   101490   sqlite3 *db = pParse->db;
   101491   Table *pTab = 0;      /* The table being read */
   101492   const char *zCol;     /* Name of the column of the table */
   101493   int iSrc;             /* Index in pTabList->a[] of table being read */
   101494   int iDb;              /* The index of the database the expression refers to */
   101495   int iCol;             /* Index of column in table */
   101496 
   101497   if( db->xAuth==0 ) return;
   101498   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   101499   if( iDb<0 ){
   101500     /* An attempt to read a column out of a subquery or other
   101501     ** temporary table. */
   101502     return;
   101503   }
   101504 
   101505   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
   101506   if( pExpr->op==TK_TRIGGER ){
   101507     pTab = pParse->pTriggerTab;
   101508   }else{
   101509     assert( pTabList );
   101510     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
   101511       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   101512         pTab = pTabList->a[iSrc].pTab;
   101513         break;
   101514       }
   101515     }
   101516   }
   101517   iCol = pExpr->iColumn;
   101518   if( NEVER(pTab==0) ) return;
   101519 
   101520   if( iCol>=0 ){
   101521     assert( iCol<pTab->nCol );
   101522     zCol = pTab->aCol[iCol].zName;
   101523   }else if( pTab->iPKey>=0 ){
   101524     assert( pTab->iPKey<pTab->nCol );
   101525     zCol = pTab->aCol[pTab->iPKey].zName;
   101526   }else{
   101527     zCol = "ROWID";
   101528   }
   101529   assert( iDb>=0 && iDb<db->nDb );
   101530   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
   101531     pExpr->op = TK_NULL;
   101532   }
   101533 }
   101534 
   101535 /*
   101536 ** Do an authorization check using the code and arguments given.  Return
   101537 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
   101538 ** is returned, then the error count and error message in pParse are
   101539 ** modified appropriately.
   101540 */
   101541 SQLITE_PRIVATE int sqlite3AuthCheck(
   101542   Parse *pParse,
   101543   int code,
   101544   const char *zArg1,
   101545   const char *zArg2,
   101546   const char *zArg3
   101547 ){
   101548   sqlite3 *db = pParse->db;
   101549   int rc;
   101550 
   101551   /* Don't do any authorization checks if the database is initialising
   101552   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   101553   */
   101554   if( db->init.busy || IN_DECLARE_VTAB ){
   101555     return SQLITE_OK;
   101556   }
   101557 
   101558   if( db->xAuth==0 ){
   101559     return SQLITE_OK;
   101560   }
   101561 
   101562   /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
   101563   ** callback are either NULL pointers or zero-terminated strings that
   101564   ** contain additional details about the action to be authorized.
   101565   **
   101566   ** The following testcase() macros show that any of the 3rd through 6th
   101567   ** parameters can be either NULL or a string. */
   101568   testcase( zArg1==0 );
   101569   testcase( zArg2==0 );
   101570   testcase( zArg3==0 );
   101571   testcase( pParse->zAuthContext==0 );
   101572 
   101573   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
   101574 #ifdef SQLITE_USER_AUTHENTICATION
   101575                  ,db->auth.zAuthUser
   101576 #endif
   101577                 );
   101578   if( rc==SQLITE_DENY ){
   101579     sqlite3ErrorMsg(pParse, "not authorized");
   101580     pParse->rc = SQLITE_AUTH;
   101581   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
   101582     rc = SQLITE_DENY;
   101583     sqliteAuthBadReturnCode(pParse);
   101584   }
   101585   return rc;
   101586 }
   101587 
   101588 /*
   101589 ** Push an authorization context.  After this routine is called, the
   101590 ** zArg3 argument to authorization callbacks will be zContext until
   101591 ** popped.  Or if pParse==0, this routine is a no-op.
   101592 */
   101593 SQLITE_PRIVATE void sqlite3AuthContextPush(
   101594   Parse *pParse,
   101595   AuthContext *pContext,
   101596   const char *zContext
   101597 ){
   101598   assert( pParse );
   101599   pContext->pParse = pParse;
   101600   pContext->zAuthContext = pParse->zAuthContext;
   101601   pParse->zAuthContext = zContext;
   101602 }
   101603 
   101604 /*
   101605 ** Pop an authorization context that was previously pushed
   101606 ** by sqlite3AuthContextPush
   101607 */
   101608 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
   101609   if( pContext->pParse ){
   101610     pContext->pParse->zAuthContext = pContext->zAuthContext;
   101611     pContext->pParse = 0;
   101612   }
   101613 }
   101614 
   101615 #endif /* SQLITE_OMIT_AUTHORIZATION */
   101616 
   101617 /************** End of auth.c ************************************************/
   101618 /************** Begin file build.c *******************************************/
   101619 /*
   101620 ** 2001 September 15
   101621 **
   101622 ** The author disclaims copyright to this source code.  In place of
   101623 ** a legal notice, here is a blessing:
   101624 **
   101625 **    May you do good and not evil.
   101626 **    May you find forgiveness for yourself and forgive others.
   101627 **    May you share freely, never taking more than you give.
   101628 **
   101629 *************************************************************************
   101630 ** This file contains C code routines that are called by the SQLite parser
   101631 ** when syntax rules are reduced.  The routines in this file handle the
   101632 ** following kinds of SQL syntax:
   101633 **
   101634 **     CREATE TABLE
   101635 **     DROP TABLE
   101636 **     CREATE INDEX
   101637 **     DROP INDEX
   101638 **     creating ID lists
   101639 **     BEGIN TRANSACTION
   101640 **     COMMIT
   101641 **     ROLLBACK
   101642 */
   101643 /* #include "sqliteInt.h" */
   101644 
   101645 #ifndef SQLITE_OMIT_SHARED_CACHE
   101646 /*
   101647 ** The TableLock structure is only used by the sqlite3TableLock() and
   101648 ** codeTableLocks() functions.
   101649 */
   101650 struct TableLock {
   101651   int iDb;               /* The database containing the table to be locked */
   101652   int iTab;              /* The root page of the table to be locked */
   101653   u8 isWriteLock;        /* True for write lock.  False for a read lock */
   101654   const char *zLockName; /* Name of the table */
   101655 };
   101656 
   101657 /*
   101658 ** Record the fact that we want to lock a table at run-time.
   101659 **
   101660 ** The table to be locked has root page iTab and is found in database iDb.
   101661 ** A read or a write lock can be taken depending on isWritelock.
   101662 **
   101663 ** This routine just records the fact that the lock is desired.  The
   101664 ** code to make the lock occur is generated by a later call to
   101665 ** codeTableLocks() which occurs during sqlite3FinishCoding().
   101666 */
   101667 SQLITE_PRIVATE void sqlite3TableLock(
   101668   Parse *pParse,     /* Parsing context */
   101669   int iDb,           /* Index of the database containing the table to lock */
   101670   int iTab,          /* Root page number of the table to be locked */
   101671   u8 isWriteLock,    /* True for a write lock */
   101672   const char *zName  /* Name of the table to be locked */
   101673 ){
   101674   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   101675   int i;
   101676   int nBytes;
   101677   TableLock *p;
   101678   assert( iDb>=0 );
   101679 
   101680   if( iDb==1 ) return;
   101681   if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
   101682   for(i=0; i<pToplevel->nTableLock; i++){
   101683     p = &pToplevel->aTableLock[i];
   101684     if( p->iDb==iDb && p->iTab==iTab ){
   101685       p->isWriteLock = (p->isWriteLock || isWriteLock);
   101686       return;
   101687     }
   101688   }
   101689 
   101690   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
   101691   pToplevel->aTableLock =
   101692       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
   101693   if( pToplevel->aTableLock ){
   101694     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
   101695     p->iDb = iDb;
   101696     p->iTab = iTab;
   101697     p->isWriteLock = isWriteLock;
   101698     p->zLockName = zName;
   101699   }else{
   101700     pToplevel->nTableLock = 0;
   101701     sqlite3OomFault(pToplevel->db);
   101702   }
   101703 }
   101704 
   101705 /*
   101706 ** Code an OP_TableLock instruction for each table locked by the
   101707 ** statement (configured by calls to sqlite3TableLock()).
   101708 */
   101709 static void codeTableLocks(Parse *pParse){
   101710   int i;
   101711   Vdbe *pVdbe;
   101712 
   101713   pVdbe = sqlite3GetVdbe(pParse);
   101714   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   101715 
   101716   for(i=0; i<pParse->nTableLock; i++){
   101717     TableLock *p = &pParse->aTableLock[i];
   101718     int p1 = p->iDb;
   101719     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   101720                       p->zLockName, P4_STATIC);
   101721   }
   101722 }
   101723 #else
   101724   #define codeTableLocks(x)
   101725 #endif
   101726 
   101727 /*
   101728 ** Return TRUE if the given yDbMask object is empty - if it contains no
   101729 ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
   101730 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
   101731 */
   101732 #if SQLITE_MAX_ATTACHED>30
   101733 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
   101734   int i;
   101735   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
   101736   return 1;
   101737 }
   101738 #endif
   101739 
   101740 /*
   101741 ** This routine is called after a single SQL statement has been
   101742 ** parsed and a VDBE program to execute that statement has been
   101743 ** prepared.  This routine puts the finishing touches on the
   101744 ** VDBE program and resets the pParse structure for the next
   101745 ** parse.
   101746 **
   101747 ** Note that if an error occurred, it might be the case that
   101748 ** no VDBE code was generated.
   101749 */
   101750 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   101751   sqlite3 *db;
   101752   Vdbe *v;
   101753 
   101754   assert( pParse->pToplevel==0 );
   101755   db = pParse->db;
   101756   if( pParse->nested ) return;
   101757   if( db->mallocFailed || pParse->nErr ){
   101758     if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
   101759     return;
   101760   }
   101761 
   101762   /* Begin by generating some termination code at the end of the
   101763   ** vdbe program
   101764   */
   101765   v = sqlite3GetVdbe(pParse);
   101766   assert( !pParse->isMultiWrite
   101767        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   101768   if( v ){
   101769     sqlite3VdbeAddOp0(v, OP_Halt);
   101770 
   101771 #if SQLITE_USER_AUTHENTICATION
   101772     if( pParse->nTableLock>0 && db->init.busy==0 ){
   101773       sqlite3UserAuthInit(db);
   101774       if( db->auth.authLevel<UAUTH_User ){
   101775         sqlite3ErrorMsg(pParse, "user not authenticated");
   101776         pParse->rc = SQLITE_AUTH_USER;
   101777         return;
   101778       }
   101779     }
   101780 #endif
   101781 
   101782     /* The cookie mask contains one bit for each database file open.
   101783     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   101784     ** set for each database that is used.  Generate code to start a
   101785     ** transaction on each used database and to verify the schema cookie
   101786     ** on each used database.
   101787     */
   101788     if( db->mallocFailed==0
   101789      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
   101790     ){
   101791       int iDb, i;
   101792       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
   101793       sqlite3VdbeJumpHere(v, 0);
   101794       for(iDb=0; iDb<db->nDb; iDb++){
   101795         Schema *pSchema;
   101796         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
   101797         sqlite3VdbeUsesBtree(v, iDb);
   101798         pSchema = db->aDb[iDb].pSchema;
   101799         sqlite3VdbeAddOp4Int(v,
   101800           OP_Transaction,                    /* Opcode */
   101801           iDb,                               /* P1 */
   101802           DbMaskTest(pParse->writeMask,iDb), /* P2 */
   101803           pSchema->schema_cookie,            /* P3 */
   101804           pSchema->iGeneration               /* P4 */
   101805         );
   101806         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
   101807         VdbeComment((v,
   101808               "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
   101809       }
   101810 #ifndef SQLITE_OMIT_VIRTUALTABLE
   101811       for(i=0; i<pParse->nVtabLock; i++){
   101812         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   101813         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   101814       }
   101815       pParse->nVtabLock = 0;
   101816 #endif
   101817 
   101818       /* Once all the cookies have been verified and transactions opened,
   101819       ** obtain the required table-locks. This is a no-op unless the
   101820       ** shared-cache feature is enabled.
   101821       */
   101822       codeTableLocks(pParse);
   101823 
   101824       /* Initialize any AUTOINCREMENT data structures required.
   101825       */
   101826       sqlite3AutoincrementBegin(pParse);
   101827 
   101828       /* Code constant expressions that where factored out of inner loops */
   101829       if( pParse->pConstExpr ){
   101830         ExprList *pEL = pParse->pConstExpr;
   101831         pParse->okConstFactor = 0;
   101832         for(i=0; i<pEL->nExpr; i++){
   101833           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
   101834         }
   101835       }
   101836 
   101837       /* Finally, jump back to the beginning of the executable code. */
   101838       sqlite3VdbeGoto(v, 1);
   101839     }
   101840   }
   101841 
   101842 
   101843   /* Get the VDBE program ready for execution
   101844   */
   101845   if( v && pParse->nErr==0 && !db->mallocFailed ){
   101846     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   101847     /* A minimum of one cursor is required if autoincrement is used
   101848     *  See ticket [a696379c1f08866] */
   101849     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   101850     sqlite3VdbeMakeReady(v, pParse);
   101851     pParse->rc = SQLITE_DONE;
   101852   }else{
   101853     pParse->rc = SQLITE_ERROR;
   101854   }
   101855 }
   101856 
   101857 /*
   101858 ** Run the parser and code generator recursively in order to generate
   101859 ** code for the SQL statement given onto the end of the pParse context
   101860 ** currently under construction.  When the parser is run recursively
   101861 ** this way, the final OP_Halt is not appended and other initialization
   101862 ** and finalization steps are omitted because those are handling by the
   101863 ** outermost parser.
   101864 **
   101865 ** Not everything is nestable.  This facility is designed to permit
   101866 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   101867 ** care if you decide to try to use this routine for some other purposes.
   101868 */
   101869 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   101870   va_list ap;
   101871   char *zSql;
   101872   char *zErrMsg = 0;
   101873   sqlite3 *db = pParse->db;
   101874   char saveBuf[PARSE_TAIL_SZ];
   101875 
   101876   if( pParse->nErr ) return;
   101877   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   101878   va_start(ap, zFormat);
   101879   zSql = sqlite3VMPrintf(db, zFormat, ap);
   101880   va_end(ap);
   101881   if( zSql==0 ){
   101882     return;   /* A malloc must have failed */
   101883   }
   101884   pParse->nested++;
   101885   memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
   101886   memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
   101887   sqlite3RunParser(pParse, zSql, &zErrMsg);
   101888   sqlite3DbFree(db, zErrMsg);
   101889   sqlite3DbFree(db, zSql);
   101890   memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
   101891   pParse->nested--;
   101892 }
   101893 
   101894 #if SQLITE_USER_AUTHENTICATION
   101895 /*
   101896 ** Return TRUE if zTable is the name of the system table that stores the
   101897 ** list of users and their access credentials.
   101898 */
   101899 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
   101900   return sqlite3_stricmp(zTable, "sqlite_user")==0;
   101901 }
   101902 #endif
   101903 
   101904 /*
   101905 ** Locate the in-memory structure that describes a particular database
   101906 ** table given the name of that table and (optionally) the name of the
   101907 ** database containing the table.  Return NULL if not found.
   101908 **
   101909 ** If zDatabase is 0, all databases are searched for the table and the
   101910 ** first matching table is returned.  (No checking for duplicate table
   101911 ** names is done.)  The search order is TEMP first, then MAIN, then any
   101912 ** auxiliary databases added using the ATTACH command.
   101913 **
   101914 ** See also sqlite3LocateTable().
   101915 */
   101916 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   101917   Table *p = 0;
   101918   int i;
   101919 
   101920   /* All mutexes are required for schema access.  Make sure we hold them. */
   101921   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   101922 #if SQLITE_USER_AUTHENTICATION
   101923   /* Only the admin user is allowed to know that the sqlite_user table
   101924   ** exists */
   101925   if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
   101926     return 0;
   101927   }
   101928 #endif
   101929   while(1){
   101930     for(i=OMIT_TEMPDB; i<db->nDb; i++){
   101931       int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   101932       if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
   101933         assert( sqlite3SchemaMutexHeld(db, j, 0) );
   101934         p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
   101935         if( p ) return p;
   101936       }
   101937     }
   101938     /* Not found.  If the name we were looking for was temp.sqlite_master
   101939     ** then change the name to sqlite_temp_master and try again. */
   101940     if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
   101941     if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
   101942     zName = TEMP_MASTER_NAME;
   101943   }
   101944   return 0;
   101945 }
   101946 
   101947 /*
   101948 ** Locate the in-memory structure that describes a particular database
   101949 ** table given the name of that table and (optionally) the name of the
   101950 ** database containing the table.  Return NULL if not found.  Also leave an
   101951 ** error message in pParse->zErrMsg.
   101952 **
   101953 ** The difference between this routine and sqlite3FindTable() is that this
   101954 ** routine leaves an error message in pParse->zErrMsg where
   101955 ** sqlite3FindTable() does not.
   101956 */
   101957 SQLITE_PRIVATE Table *sqlite3LocateTable(
   101958   Parse *pParse,         /* context in which to report errors */
   101959   u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
   101960   const char *zName,     /* Name of the table we are looking for */
   101961   const char *zDbase     /* Name of the database.  Might be NULL */
   101962 ){
   101963   Table *p;
   101964 
   101965   /* Read the database schema. If an error occurs, leave an error message
   101966   ** and code in pParse and return NULL. */
   101967   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   101968     return 0;
   101969   }
   101970 
   101971   p = sqlite3FindTable(pParse->db, zName, zDbase);
   101972   if( p==0 ){
   101973     const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
   101974 #ifndef SQLITE_OMIT_VIRTUALTABLE
   101975     if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
   101976       /* If zName is the not the name of a table in the schema created using
   101977       ** CREATE, then check to see if it is the name of an virtual table that
   101978       ** can be an eponymous virtual table. */
   101979       Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
   101980       if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
   101981         pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
   101982       }
   101983       if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
   101984         return pMod->pEpoTab;
   101985       }
   101986     }
   101987 #endif
   101988     if( (flags & LOCATE_NOERR)==0 ){
   101989       if( zDbase ){
   101990         sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   101991       }else{
   101992         sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   101993       }
   101994       pParse->checkSchema = 1;
   101995     }
   101996   }
   101997 
   101998   return p;
   101999 }
   102000 
   102001 /*
   102002 ** Locate the table identified by *p.
   102003 **
   102004 ** This is a wrapper around sqlite3LocateTable(). The difference between
   102005 ** sqlite3LocateTable() and this function is that this function restricts
   102006 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
   102007 ** non-NULL if it is part of a view or trigger program definition. See
   102008 ** sqlite3FixSrcList() for details.
   102009 */
   102010 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
   102011   Parse *pParse,
   102012   u32 flags,
   102013   struct SrcList_item *p
   102014 ){
   102015   const char *zDb;
   102016   assert( p->pSchema==0 || p->zDatabase==0 );
   102017   if( p->pSchema ){
   102018     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
   102019     zDb = pParse->db->aDb[iDb].zDbSName;
   102020   }else{
   102021     zDb = p->zDatabase;
   102022   }
   102023   return sqlite3LocateTable(pParse, flags, p->zName, zDb);
   102024 }
   102025 
   102026 /*
   102027 ** Locate the in-memory structure that describes
   102028 ** a particular index given the name of that index
   102029 ** and the name of the database that contains the index.
   102030 ** Return NULL if not found.
   102031 **
   102032 ** If zDatabase is 0, all databases are searched for the
   102033 ** table and the first matching index is returned.  (No checking
   102034 ** for duplicate index names is done.)  The search order is
   102035 ** TEMP first, then MAIN, then any auxiliary databases added
   102036 ** using the ATTACH command.
   102037 */
   102038 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   102039   Index *p = 0;
   102040   int i;
   102041   /* All mutexes are required for schema access.  Make sure we hold them. */
   102042   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   102043   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   102044     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   102045     Schema *pSchema = db->aDb[j].pSchema;
   102046     assert( pSchema );
   102047     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
   102048     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   102049     p = sqlite3HashFind(&pSchema->idxHash, zName);
   102050     if( p ) break;
   102051   }
   102052   return p;
   102053 }
   102054 
   102055 /*
   102056 ** Reclaim the memory used by an index
   102057 */
   102058 static void freeIndex(sqlite3 *db, Index *p){
   102059 #ifndef SQLITE_OMIT_ANALYZE
   102060   sqlite3DeleteIndexSamples(db, p);
   102061 #endif
   102062   sqlite3ExprDelete(db, p->pPartIdxWhere);
   102063   sqlite3ExprListDelete(db, p->aColExpr);
   102064   sqlite3DbFree(db, p->zColAff);
   102065   if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
   102066 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   102067   sqlite3_free(p->aiRowEst);
   102068 #endif
   102069   sqlite3DbFree(db, p);
   102070 }
   102071 
   102072 /*
   102073 ** For the index called zIdxName which is found in the database iDb,
   102074 ** unlike that index from its Table then remove the index from
   102075 ** the index hash table and free all memory structures associated
   102076 ** with the index.
   102077 */
   102078 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   102079   Index *pIndex;
   102080   Hash *pHash;
   102081 
   102082   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   102083   pHash = &db->aDb[iDb].pSchema->idxHash;
   102084   pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
   102085   if( ALWAYS(pIndex) ){
   102086     if( pIndex->pTable->pIndex==pIndex ){
   102087       pIndex->pTable->pIndex = pIndex->pNext;
   102088     }else{
   102089       Index *p;
   102090       /* Justification of ALWAYS();  The index must be on the list of
   102091       ** indices. */
   102092       p = pIndex->pTable->pIndex;
   102093       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   102094       if( ALWAYS(p && p->pNext==pIndex) ){
   102095         p->pNext = pIndex->pNext;
   102096       }
   102097     }
   102098     freeIndex(db, pIndex);
   102099   }
   102100   db->mDbFlags |= DBFLAG_SchemaChange;
   102101 }
   102102 
   102103 /*
   102104 ** Look through the list of open database files in db->aDb[] and if
   102105 ** any have been closed, remove them from the list.  Reallocate the
   102106 ** db->aDb[] structure to a smaller size, if possible.
   102107 **
   102108 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
   102109 ** are never candidates for being collapsed.
   102110 */
   102111 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
   102112   int i, j;
   102113   for(i=j=2; i<db->nDb; i++){
   102114     struct Db *pDb = &db->aDb[i];
   102115     if( pDb->pBt==0 ){
   102116       sqlite3DbFree(db, pDb->zDbSName);
   102117       pDb->zDbSName = 0;
   102118       continue;
   102119     }
   102120     if( j<i ){
   102121       db->aDb[j] = db->aDb[i];
   102122     }
   102123     j++;
   102124   }
   102125   db->nDb = j;
   102126   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   102127     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   102128     sqlite3DbFree(db, db->aDb);
   102129     db->aDb = db->aDbStatic;
   102130   }
   102131 }
   102132 
   102133 /*
   102134 ** Reset the schema for the database at index iDb.  Also reset the
   102135 ** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
   102136 ** Deferred resets may be run by calling with iDb<0.
   102137 */
   102138 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
   102139   int i;
   102140   assert( iDb<db->nDb );
   102141 
   102142   if( iDb>=0 ){
   102143     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   102144     DbSetProperty(db, iDb, DB_ResetWanted);
   102145     DbSetProperty(db, 1, DB_ResetWanted);
   102146   }
   102147 
   102148   if( db->nSchemaLock==0 ){
   102149     for(i=0; i<db->nDb; i++){
   102150       if( DbHasProperty(db, i, DB_ResetWanted) ){
   102151         sqlite3SchemaClear(db->aDb[i].pSchema);
   102152       }
   102153     }
   102154   }
   102155 }
   102156 
   102157 /*
   102158 ** Erase all schema information from all attached databases (including
   102159 ** "main" and "temp") for a single database connection.
   102160 */
   102161 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
   102162   int i;
   102163   sqlite3BtreeEnterAll(db);
   102164   assert( db->nSchemaLock==0 );
   102165   for(i=0; i<db->nDb; i++){
   102166     Db *pDb = &db->aDb[i];
   102167     if( pDb->pSchema ){
   102168       sqlite3SchemaClear(pDb->pSchema);
   102169     }
   102170   }
   102171   db->mDbFlags &= ~DBFLAG_SchemaChange;
   102172   sqlite3VtabUnlockList(db);
   102173   sqlite3BtreeLeaveAll(db);
   102174   sqlite3CollapseDatabaseArray(db);
   102175 }
   102176 
   102177 /*
   102178 ** This routine is called when a commit occurs.
   102179 */
   102180 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   102181   db->mDbFlags &= ~DBFLAG_SchemaChange;
   102182 }
   102183 
   102184 /*
   102185 ** Delete memory allocated for the column names of a table or view (the
   102186 ** Table.aCol[] array).
   102187 */
   102188 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
   102189   int i;
   102190   Column *pCol;
   102191   assert( pTable!=0 );
   102192   if( (pCol = pTable->aCol)!=0 ){
   102193     for(i=0; i<pTable->nCol; i++, pCol++){
   102194       sqlite3DbFree(db, pCol->zName);
   102195       sqlite3ExprDelete(db, pCol->pDflt);
   102196       sqlite3DbFree(db, pCol->zColl);
   102197     }
   102198     sqlite3DbFree(db, pTable->aCol);
   102199   }
   102200 }
   102201 
   102202 /*
   102203 ** Remove the memory data structures associated with the given
   102204 ** Table.  No changes are made to disk by this routine.
   102205 **
   102206 ** This routine just deletes the data structure.  It does not unlink
   102207 ** the table data structure from the hash table.  But it does destroy
   102208 ** memory structures of the indices and foreign keys associated with
   102209 ** the table.
   102210 **
   102211 ** The db parameter is optional.  It is needed if the Table object
   102212 ** contains lookaside memory.  (Table objects in the schema do not use
   102213 ** lookaside memory, but some ephemeral Table objects do.)  Or the
   102214 ** db parameter can be used with db->pnBytesFreed to measure the memory
   102215 ** used by the Table object.
   102216 */
   102217 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
   102218   Index *pIndex, *pNext;
   102219 
   102220 #ifdef SQLITE_DEBUG
   102221   /* Record the number of outstanding lookaside allocations in schema Tables
   102222   ** prior to doing any free() operations.  Since schema Tables do not use
   102223   ** lookaside, this number should not change. */
   102224   int nLookaside = 0;
   102225   if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
   102226     nLookaside = sqlite3LookasideUsed(db, 0);
   102227   }
   102228 #endif
   102229 
   102230   /* Delete all indices associated with this table. */
   102231   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   102232     pNext = pIndex->pNext;
   102233     assert( pIndex->pSchema==pTable->pSchema
   102234          || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
   102235     if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
   102236       char *zName = pIndex->zName;
   102237       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
   102238          &pIndex->pSchema->idxHash, zName, 0
   102239       );
   102240       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   102241       assert( pOld==pIndex || pOld==0 );
   102242     }
   102243     freeIndex(db, pIndex);
   102244   }
   102245 
   102246   /* Delete any foreign keys attached to this table. */
   102247   sqlite3FkDelete(db, pTable);
   102248 
   102249   /* Delete the Table structure itself.
   102250   */
   102251   sqlite3DeleteColumnNames(db, pTable);
   102252   sqlite3DbFree(db, pTable->zName);
   102253   sqlite3DbFree(db, pTable->zColAff);
   102254   sqlite3SelectDelete(db, pTable->pSelect);
   102255   sqlite3ExprListDelete(db, pTable->pCheck);
   102256 #ifndef SQLITE_OMIT_VIRTUALTABLE
   102257   sqlite3VtabClear(db, pTable);
   102258 #endif
   102259   sqlite3DbFree(db, pTable);
   102260 
   102261   /* Verify that no lookaside memory was used by schema tables */
   102262   assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
   102263 }
   102264 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   102265   /* Do not delete the table until the reference count reaches zero. */
   102266   if( !pTable ) return;
   102267   if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
   102268   deleteTable(db, pTable);
   102269 }
   102270 
   102271 
   102272 /*
   102273 ** Unlink the given table from the hash tables and the delete the
   102274 ** table structure with all its indices and foreign keys.
   102275 */
   102276 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   102277   Table *p;
   102278   Db *pDb;
   102279 
   102280   assert( db!=0 );
   102281   assert( iDb>=0 && iDb<db->nDb );
   102282   assert( zTabName );
   102283   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   102284   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   102285   pDb = &db->aDb[iDb];
   102286   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
   102287   sqlite3DeleteTable(db, p);
   102288   db->mDbFlags |= DBFLAG_SchemaChange;
   102289 }
   102290 
   102291 /*
   102292 ** Given a token, return a string that consists of the text of that
   102293 ** token.  Space to hold the returned string
   102294 ** is obtained from sqliteMalloc() and must be freed by the calling
   102295 ** function.
   102296 **
   102297 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   102298 ** surround the body of the token are removed.
   102299 **
   102300 ** Tokens are often just pointers into the original SQL text and so
   102301 ** are not \000 terminated and are not persistent.  The returned string
   102302 ** is \000 terminated and is persistent.
   102303 */
   102304 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   102305   char *zName;
   102306   if( pName ){
   102307     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   102308     sqlite3Dequote(zName);
   102309   }else{
   102310     zName = 0;
   102311   }
   102312   return zName;
   102313 }
   102314 
   102315 /*
   102316 ** Open the sqlite_master table stored in database number iDb for
   102317 ** writing. The table is opened using cursor 0.
   102318 */
   102319 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
   102320   Vdbe *v = sqlite3GetVdbe(p);
   102321   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
   102322   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
   102323   if( p->nTab==0 ){
   102324     p->nTab = 1;
   102325   }
   102326 }
   102327 
   102328 /*
   102329 ** Parameter zName points to a nul-terminated buffer containing the name
   102330 ** of a database ("main", "temp" or the name of an attached db). This
   102331 ** function returns the index of the named database in db->aDb[], or
   102332 ** -1 if the named db cannot be found.
   102333 */
   102334 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
   102335   int i = -1;         /* Database number */
   102336   if( zName ){
   102337     Db *pDb;
   102338     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   102339       if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
   102340       /* "main" is always an acceptable alias for the primary database
   102341       ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
   102342       if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
   102343     }
   102344   }
   102345   return i;
   102346 }
   102347 
   102348 /*
   102349 ** The token *pName contains the name of a database (either "main" or
   102350 ** "temp" or the name of an attached db). This routine returns the
   102351 ** index of the named database in db->aDb[], or -1 if the named db
   102352 ** does not exist.
   102353 */
   102354 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
   102355   int i;                               /* Database number */
   102356   char *zName;                         /* Name we are searching for */
   102357   zName = sqlite3NameFromToken(db, pName);
   102358   i = sqlite3FindDbName(db, zName);
   102359   sqlite3DbFree(db, zName);
   102360   return i;
   102361 }
   102362 
   102363 /* The table or view or trigger name is passed to this routine via tokens
   102364 ** pName1 and pName2. If the table name was fully qualified, for example:
   102365 **
   102366 ** CREATE TABLE xxx.yyy (...);
   102367 **
   102368 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   102369 ** the table name is not fully qualified, i.e.:
   102370 **
   102371 ** CREATE TABLE yyy(...);
   102372 **
   102373 ** Then pName1 is set to "yyy" and pName2 is "".
   102374 **
   102375 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   102376 ** pName2) that stores the unqualified table name.  The index of the
   102377 ** database "xxx" is returned.
   102378 */
   102379 SQLITE_PRIVATE int sqlite3TwoPartName(
   102380   Parse *pParse,      /* Parsing and code generating context */
   102381   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   102382   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   102383   Token **pUnqual     /* Write the unqualified object name here */
   102384 ){
   102385   int iDb;                    /* Database holding the object */
   102386   sqlite3 *db = pParse->db;
   102387 
   102388   assert( pName2!=0 );
   102389   if( pName2->n>0 ){
   102390     if( db->init.busy ) {
   102391       sqlite3ErrorMsg(pParse, "corrupt database");
   102392       return -1;
   102393     }
   102394     *pUnqual = pName2;
   102395     iDb = sqlite3FindDb(db, pName1);
   102396     if( iDb<0 ){
   102397       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   102398       return -1;
   102399     }
   102400   }else{
   102401     assert( db->init.iDb==0 || db->init.busy
   102402              || (db->mDbFlags & DBFLAG_Vacuum)!=0);
   102403     iDb = db->init.iDb;
   102404     *pUnqual = pName1;
   102405   }
   102406   return iDb;
   102407 }
   102408 
   102409 /*
   102410 ** This routine is used to check if the UTF-8 string zName is a legal
   102411 ** unqualified name for a new schema object (table, index, view or
   102412 ** trigger). All names are legal except those that begin with the string
   102413 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   102414 ** is reserved for internal use.
   102415 */
   102416 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   102417   if( !pParse->db->init.busy && pParse->nested==0
   102418           && (pParse->db->flags & SQLITE_WriteSchema)==0
   102419           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   102420     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   102421     return SQLITE_ERROR;
   102422   }
   102423   return SQLITE_OK;
   102424 }
   102425 
   102426 /*
   102427 ** Return the PRIMARY KEY index of a table
   102428 */
   102429 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
   102430   Index *p;
   102431   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
   102432   return p;
   102433 }
   102434 
   102435 /*
   102436 ** Return the column of index pIdx that corresponds to table
   102437 ** column iCol.  Return -1 if not found.
   102438 */
   102439 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
   102440   int i;
   102441   for(i=0; i<pIdx->nColumn; i++){
   102442     if( iCol==pIdx->aiColumn[i] ) return i;
   102443   }
   102444   return -1;
   102445 }
   102446 
   102447 /*
   102448 ** Begin constructing a new table representation in memory.  This is
   102449 ** the first of several action routines that get called in response
   102450 ** to a CREATE TABLE statement.  In particular, this routine is called
   102451 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   102452 ** flag is true if the table should be stored in the auxiliary database
   102453 ** file instead of in the main database file.  This is normally the case
   102454 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   102455 ** CREATE and TABLE.
   102456 **
   102457 ** The new table record is initialized and put in pParse->pNewTable.
   102458 ** As more of the CREATE TABLE statement is parsed, additional action
   102459 ** routines will be called to add more information to this record.
   102460 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   102461 ** is called to complete the construction of the new table record.
   102462 */
   102463 SQLITE_PRIVATE void sqlite3StartTable(
   102464   Parse *pParse,   /* Parser context */
   102465   Token *pName1,   /* First part of the name of the table or view */
   102466   Token *pName2,   /* Second part of the name of the table or view */
   102467   int isTemp,      /* True if this is a TEMP table */
   102468   int isView,      /* True if this is a VIEW */
   102469   int isVirtual,   /* True if this is a VIRTUAL table */
   102470   int noErr        /* Do nothing if table already exists */
   102471 ){
   102472   Table *pTable;
   102473   char *zName = 0; /* The name of the new table */
   102474   sqlite3 *db = pParse->db;
   102475   Vdbe *v;
   102476   int iDb;         /* Database number to create the table in */
   102477   Token *pName;    /* Unqualified name of the table to create */
   102478 
   102479   if( db->init.busy && db->init.newTnum==1 ){
   102480     /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
   102481     iDb = db->init.iDb;
   102482     zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
   102483     pName = pName1;
   102484   }else{
   102485     /* The common case */
   102486     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   102487     if( iDb<0 ) return;
   102488     if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
   102489       /* If creating a temp table, the name may not be qualified. Unless
   102490       ** the database name is "temp" anyway.  */
   102491       sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   102492       return;
   102493     }
   102494     if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   102495     zName = sqlite3NameFromToken(db, pName);
   102496   }
   102497   pParse->sNameToken = *pName;
   102498   if( zName==0 ) return;
   102499   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   102500     goto begin_table_error;
   102501   }
   102502   if( db->init.iDb==1 ) isTemp = 1;
   102503 #ifndef SQLITE_OMIT_AUTHORIZATION
   102504   assert( isTemp==0 || isTemp==1 );
   102505   assert( isView==0 || isView==1 );
   102506   {
   102507     static const u8 aCode[] = {
   102508        SQLITE_CREATE_TABLE,
   102509        SQLITE_CREATE_TEMP_TABLE,
   102510        SQLITE_CREATE_VIEW,
   102511        SQLITE_CREATE_TEMP_VIEW
   102512     };
   102513     char *zDb = db->aDb[iDb].zDbSName;
   102514     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   102515       goto begin_table_error;
   102516     }
   102517     if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
   102518                                        zName, 0, zDb) ){
   102519       goto begin_table_error;
   102520     }
   102521   }
   102522 #endif
   102523 
   102524   /* Make sure the new table name does not collide with an existing
   102525   ** index or table name in the same database.  Issue an error message if
   102526   ** it does. The exception is if the statement being parsed was passed
   102527   ** to an sqlite3_declare_vtab() call. In that case only the column names
   102528   ** and types will be used, so there is no need to test for namespace
   102529   ** collisions.
   102530   */
   102531   if( !IN_DECLARE_VTAB ){
   102532     char *zDb = db->aDb[iDb].zDbSName;
   102533     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   102534       goto begin_table_error;
   102535     }
   102536     pTable = sqlite3FindTable(db, zName, zDb);
   102537     if( pTable ){
   102538       if( !noErr ){
   102539         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   102540       }else{
   102541         assert( !db->init.busy || CORRUPT_DB );
   102542         sqlite3CodeVerifySchema(pParse, iDb);
   102543       }
   102544       goto begin_table_error;
   102545     }
   102546     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
   102547       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   102548       goto begin_table_error;
   102549     }
   102550   }
   102551 
   102552   pTable = sqlite3DbMallocZero(db, sizeof(Table));
   102553   if( pTable==0 ){
   102554     assert( db->mallocFailed );
   102555     pParse->rc = SQLITE_NOMEM_BKPT;
   102556     pParse->nErr++;
   102557     goto begin_table_error;
   102558   }
   102559   pTable->zName = zName;
   102560   pTable->iPKey = -1;
   102561   pTable->pSchema = db->aDb[iDb].pSchema;
   102562   pTable->nTabRef = 1;
   102563 #ifdef SQLITE_DEFAULT_ROWEST
   102564   pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
   102565 #else
   102566   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   102567 #endif
   102568   assert( pParse->pNewTable==0 );
   102569   pParse->pNewTable = pTable;
   102570 
   102571   /* If this is the magic sqlite_sequence table used by autoincrement,
   102572   ** then record a pointer to this table in the main database structure
   102573   ** so that INSERT can find the table easily.
   102574   */
   102575 #ifndef SQLITE_OMIT_AUTOINCREMENT
   102576   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   102577     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   102578     pTable->pSchema->pSeqTab = pTable;
   102579   }
   102580 #endif
   102581 
   102582   /* Begin generating the code that will insert the table record into
   102583   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   102584   ** and allocate the record number for the table entry now.  Before any
   102585   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   102586   ** indices to be created and the table record must come before the
   102587   ** indices.  Hence, the record number for the table must be allocated
   102588   ** now.
   102589   */
   102590   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   102591     int addr1;
   102592     int fileFormat;
   102593     int reg1, reg2, reg3;
   102594     /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
   102595     static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
   102596     sqlite3BeginWriteOperation(pParse, 1, iDb);
   102597 
   102598 #ifndef SQLITE_OMIT_VIRTUALTABLE
   102599     if( isVirtual ){
   102600       sqlite3VdbeAddOp0(v, OP_VBegin);
   102601     }
   102602 #endif
   102603 
   102604     /* If the file format and encoding in the database have not been set,
   102605     ** set them now.
   102606     */
   102607     reg1 = pParse->regRowid = ++pParse->nMem;
   102608     reg2 = pParse->regRoot = ++pParse->nMem;
   102609     reg3 = ++pParse->nMem;
   102610     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   102611     sqlite3VdbeUsesBtree(v, iDb);
   102612     addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
   102613     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   102614                   1 : SQLITE_MAX_FILE_FORMAT;
   102615     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
   102616     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
   102617     sqlite3VdbeJumpHere(v, addr1);
   102618 
   102619     /* This just creates a place-holder record in the sqlite_master table.
   102620     ** The record created does not contain anything yet.  It will be replaced
   102621     ** by the real entry in code generated at sqlite3EndTable().
   102622     **
   102623     ** The rowid for the new entry is left in register pParse->regRowid.
   102624     ** The root page number of the new table is left in reg pParse->regRoot.
   102625     ** The rowid and root page number values are needed by the code that
   102626     ** sqlite3EndTable will generate.
   102627     */
   102628 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   102629     if( isView || isVirtual ){
   102630       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   102631     }else
   102632 #endif
   102633     {
   102634       pParse->addrCrTab =
   102635          sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
   102636     }
   102637     sqlite3OpenMasterTable(pParse, iDb);
   102638     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   102639     sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
   102640     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   102641     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   102642     sqlite3VdbeAddOp0(v, OP_Close);
   102643   }
   102644 
   102645   /* Normal (non-error) return. */
   102646   return;
   102647 
   102648   /* If an error occurs, we jump here */
   102649 begin_table_error:
   102650   sqlite3DbFree(db, zName);
   102651   return;
   102652 }
   102653 
   102654 /* Set properties of a table column based on the (magical)
   102655 ** name of the column.
   102656 */
   102657 #if SQLITE_ENABLE_HIDDEN_COLUMNS
   102658 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
   102659   if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
   102660     pCol->colFlags |= COLFLAG_HIDDEN;
   102661   }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
   102662     pTab->tabFlags |= TF_OOOHidden;
   102663   }
   102664 }
   102665 #endif
   102666 
   102667 
   102668 /*
   102669 ** Add a new column to the table currently being constructed.
   102670 **
   102671 ** The parser calls this routine once for each column declaration
   102672 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   102673 ** first to get things going.  Then this routine is called for each
   102674 ** column.
   102675 */
   102676 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
   102677   Table *p;
   102678   int i;
   102679   char *z;
   102680   char *zType;
   102681   Column *pCol;
   102682   sqlite3 *db = pParse->db;
   102683   if( (p = pParse->pNewTable)==0 ) return;
   102684   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   102685     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   102686     return;
   102687   }
   102688   z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
   102689   if( z==0 ) return;
   102690   memcpy(z, pName->z, pName->n);
   102691   z[pName->n] = 0;
   102692   sqlite3Dequote(z);
   102693   for(i=0; i<p->nCol; i++){
   102694     if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
   102695       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   102696       sqlite3DbFree(db, z);
   102697       return;
   102698     }
   102699   }
   102700   if( (p->nCol & 0x7)==0 ){
   102701     Column *aNew;
   102702     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   102703     if( aNew==0 ){
   102704       sqlite3DbFree(db, z);
   102705       return;
   102706     }
   102707     p->aCol = aNew;
   102708   }
   102709   pCol = &p->aCol[p->nCol];
   102710   memset(pCol, 0, sizeof(p->aCol[0]));
   102711   pCol->zName = z;
   102712   sqlite3ColumnPropertiesFromName(p, pCol);
   102713 
   102714   if( pType->n==0 ){
   102715     /* If there is no type specified, columns have the default affinity
   102716     ** 'BLOB'. */
   102717     pCol->affinity = SQLITE_AFF_BLOB;
   102718     pCol->szEst = 1;
   102719   }else{
   102720     zType = z + sqlite3Strlen30(z) + 1;
   102721     memcpy(zType, pType->z, pType->n);
   102722     zType[pType->n] = 0;
   102723     sqlite3Dequote(zType);
   102724     pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
   102725     pCol->colFlags |= COLFLAG_HASTYPE;
   102726   }
   102727   p->nCol++;
   102728   pParse->constraintName.n = 0;
   102729 }
   102730 
   102731 /*
   102732 ** This routine is called by the parser while in the middle of
   102733 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   102734 ** been seen on a column.  This routine sets the notNull flag on
   102735 ** the column currently under construction.
   102736 */
   102737 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
   102738   Table *p;
   102739   p = pParse->pNewTable;
   102740   if( p==0 || NEVER(p->nCol<1) ) return;
   102741   p->aCol[p->nCol-1].notNull = (u8)onError;
   102742   p->tabFlags |= TF_HasNotNull;
   102743 }
   102744 
   102745 /*
   102746 ** Scan the column type name zType (length nType) and return the
   102747 ** associated affinity type.
   102748 **
   102749 ** This routine does a case-independent search of zType for the
   102750 ** substrings in the following table. If one of the substrings is
   102751 ** found, the corresponding affinity is returned. If zType contains
   102752 ** more than one of the substrings, entries toward the top of
   102753 ** the table take priority. For example, if zType is 'BLOBINT',
   102754 ** SQLITE_AFF_INTEGER is returned.
   102755 **
   102756 ** Substring     | Affinity
   102757 ** --------------------------------
   102758 ** 'INT'         | SQLITE_AFF_INTEGER
   102759 ** 'CHAR'        | SQLITE_AFF_TEXT
   102760 ** 'CLOB'        | SQLITE_AFF_TEXT
   102761 ** 'TEXT'        | SQLITE_AFF_TEXT
   102762 ** 'BLOB'        | SQLITE_AFF_BLOB
   102763 ** 'REAL'        | SQLITE_AFF_REAL
   102764 ** 'FLOA'        | SQLITE_AFF_REAL
   102765 ** 'DOUB'        | SQLITE_AFF_REAL
   102766 **
   102767 ** If none of the substrings in the above table are found,
   102768 ** SQLITE_AFF_NUMERIC is returned.
   102769 */
   102770 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
   102771   u32 h = 0;
   102772   char aff = SQLITE_AFF_NUMERIC;
   102773   const char *zChar = 0;
   102774 
   102775   assert( zIn!=0 );
   102776   while( zIn[0] ){
   102777     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
   102778     zIn++;
   102779     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   102780       aff = SQLITE_AFF_TEXT;
   102781       zChar = zIn;
   102782     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   102783       aff = SQLITE_AFF_TEXT;
   102784     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   102785       aff = SQLITE_AFF_TEXT;
   102786     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   102787         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   102788       aff = SQLITE_AFF_BLOB;
   102789       if( zIn[0]=='(' ) zChar = zIn;
   102790 #ifndef SQLITE_OMIT_FLOATING_POINT
   102791     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
   102792         && aff==SQLITE_AFF_NUMERIC ){
   102793       aff = SQLITE_AFF_REAL;
   102794     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
   102795         && aff==SQLITE_AFF_NUMERIC ){
   102796       aff = SQLITE_AFF_REAL;
   102797     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
   102798         && aff==SQLITE_AFF_NUMERIC ){
   102799       aff = SQLITE_AFF_REAL;
   102800 #endif
   102801     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   102802       aff = SQLITE_AFF_INTEGER;
   102803       break;
   102804     }
   102805   }
   102806 
   102807   /* If pszEst is not NULL, store an estimate of the field size.  The
   102808   ** estimate is scaled so that the size of an integer is 1.  */
   102809   if( pszEst ){
   102810     *pszEst = 1;   /* default size is approx 4 bytes */
   102811     if( aff<SQLITE_AFF_NUMERIC ){
   102812       if( zChar ){
   102813         while( zChar[0] ){
   102814           if( sqlite3Isdigit(zChar[0]) ){
   102815             int v = 0;
   102816             sqlite3GetInt32(zChar, &v);
   102817             v = v/4 + 1;
   102818             if( v>255 ) v = 255;
   102819             *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
   102820             break;
   102821           }
   102822           zChar++;
   102823         }
   102824       }else{
   102825         *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
   102826       }
   102827     }
   102828   }
   102829   return aff;
   102830 }
   102831 
   102832 /*
   102833 ** The expression is the default value for the most recently added column
   102834 ** of the table currently under construction.
   102835 **
   102836 ** Default value expressions must be constant.  Raise an exception if this
   102837 ** is not the case.
   102838 **
   102839 ** This routine is called by the parser while in the middle of
   102840 ** parsing a CREATE TABLE statement.
   102841 */
   102842 SQLITE_PRIVATE void sqlite3AddDefaultValue(
   102843   Parse *pParse,           /* Parsing context */
   102844   Expr *pExpr,             /* The parsed expression of the default value */
   102845   const char *zStart,      /* Start of the default value text */
   102846   const char *zEnd         /* First character past end of defaut value text */
   102847 ){
   102848   Table *p;
   102849   Column *pCol;
   102850   sqlite3 *db = pParse->db;
   102851   p = pParse->pNewTable;
   102852   if( p!=0 ){
   102853     pCol = &(p->aCol[p->nCol-1]);
   102854     if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
   102855       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   102856           pCol->zName);
   102857     }else{
   102858       /* A copy of pExpr is used instead of the original, as pExpr contains
   102859       ** tokens that point to volatile memory.
   102860       */
   102861       Expr x;
   102862       sqlite3ExprDelete(db, pCol->pDflt);
   102863       memset(&x, 0, sizeof(x));
   102864       x.op = TK_SPAN;
   102865       x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
   102866       x.pLeft = pExpr;
   102867       x.flags = EP_Skip;
   102868       pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
   102869       sqlite3DbFree(db, x.u.zToken);
   102870     }
   102871   }
   102872   sqlite3ExprDelete(db, pExpr);
   102873 }
   102874 
   102875 /*
   102876 ** Backwards Compatibility Hack:
   102877 **
   102878 ** Historical versions of SQLite accepted strings as column names in
   102879 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
   102880 **
   102881 **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
   102882 **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
   102883 **
   102884 ** This is goofy.  But to preserve backwards compatibility we continue to
   102885 ** accept it.  This routine does the necessary conversion.  It converts
   102886 ** the expression given in its argument from a TK_STRING into a TK_ID
   102887 ** if the expression is just a TK_STRING with an optional COLLATE clause.
   102888 ** If the epxression is anything other than TK_STRING, the expression is
   102889 ** unchanged.
   102890 */
   102891 static void sqlite3StringToId(Expr *p){
   102892   if( p->op==TK_STRING ){
   102893     p->op = TK_ID;
   102894   }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
   102895     p->pLeft->op = TK_ID;
   102896   }
   102897 }
   102898 
   102899 /*
   102900 ** Designate the PRIMARY KEY for the table.  pList is a list of names
   102901 ** of columns that form the primary key.  If pList is NULL, then the
   102902 ** most recently added column of the table is the primary key.
   102903 **
   102904 ** A table can have at most one primary key.  If the table already has
   102905 ** a primary key (and this is the second primary key) then create an
   102906 ** error.
   102907 **
   102908 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
   102909 ** then we will try to use that column as the rowid.  Set the Table.iPKey
   102910 ** field of the table under construction to be the index of the
   102911 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
   102912 ** no INTEGER PRIMARY KEY.
   102913 **
   102914 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   102915 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   102916 */
   102917 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   102918   Parse *pParse,    /* Parsing context */
   102919   ExprList *pList,  /* List of field names to be indexed */
   102920   int onError,      /* What to do with a uniqueness conflict */
   102921   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
   102922   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   102923 ){
   102924   Table *pTab = pParse->pNewTable;
   102925   Column *pCol = 0;
   102926   int iCol = -1, i;
   102927   int nTerm;
   102928   if( pTab==0 ) goto primary_key_exit;
   102929   if( pTab->tabFlags & TF_HasPrimaryKey ){
   102930     sqlite3ErrorMsg(pParse,
   102931       "table \"%s\" has more than one primary key", pTab->zName);
   102932     goto primary_key_exit;
   102933   }
   102934   pTab->tabFlags |= TF_HasPrimaryKey;
   102935   if( pList==0 ){
   102936     iCol = pTab->nCol - 1;
   102937     pCol = &pTab->aCol[iCol];
   102938     pCol->colFlags |= COLFLAG_PRIMKEY;
   102939     nTerm = 1;
   102940   }else{
   102941     nTerm = pList->nExpr;
   102942     for(i=0; i<nTerm; i++){
   102943       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
   102944       assert( pCExpr!=0 );
   102945       sqlite3StringToId(pCExpr);
   102946       if( pCExpr->op==TK_ID ){
   102947         const char *zCName = pCExpr->u.zToken;
   102948         for(iCol=0; iCol<pTab->nCol; iCol++){
   102949           if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
   102950             pCol = &pTab->aCol[iCol];
   102951             pCol->colFlags |= COLFLAG_PRIMKEY;
   102952             break;
   102953           }
   102954         }
   102955       }
   102956     }
   102957   }
   102958   if( nTerm==1
   102959    && pCol
   102960    && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
   102961    && sortOrder!=SQLITE_SO_DESC
   102962   ){
   102963     pTab->iPKey = iCol;
   102964     pTab->keyConf = (u8)onError;
   102965     assert( autoInc==0 || autoInc==1 );
   102966     pTab->tabFlags |= autoInc*TF_Autoincrement;
   102967     if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
   102968   }else if( autoInc ){
   102969 #ifndef SQLITE_OMIT_AUTOINCREMENT
   102970     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
   102971        "INTEGER PRIMARY KEY");
   102972 #endif
   102973   }else{
   102974     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
   102975                            0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
   102976     pList = 0;
   102977   }
   102978 
   102979 primary_key_exit:
   102980   sqlite3ExprListDelete(pParse->db, pList);
   102981   return;
   102982 }
   102983 
   102984 /*
   102985 ** Add a new CHECK constraint to the table currently under construction.
   102986 */
   102987 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
   102988   Parse *pParse,    /* Parsing context */
   102989   Expr *pCheckExpr  /* The check expression */
   102990 ){
   102991 #ifndef SQLITE_OMIT_CHECK
   102992   Table *pTab = pParse->pNewTable;
   102993   sqlite3 *db = pParse->db;
   102994   if( pTab && !IN_DECLARE_VTAB
   102995    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
   102996   ){
   102997     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
   102998     if( pParse->constraintName.n ){
   102999       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
   103000     }
   103001   }else
   103002 #endif
   103003   {
   103004     sqlite3ExprDelete(pParse->db, pCheckExpr);
   103005   }
   103006 }
   103007 
   103008 /*
   103009 ** Set the collation function of the most recently parsed table column
   103010 ** to the CollSeq given.
   103011 */
   103012 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   103013   Table *p;
   103014   int i;
   103015   char *zColl;              /* Dequoted name of collation sequence */
   103016   sqlite3 *db;
   103017 
   103018   if( (p = pParse->pNewTable)==0 ) return;
   103019   i = p->nCol-1;
   103020   db = pParse->db;
   103021   zColl = sqlite3NameFromToken(db, pToken);
   103022   if( !zColl ) return;
   103023 
   103024   if( sqlite3LocateCollSeq(pParse, zColl) ){
   103025     Index *pIdx;
   103026     sqlite3DbFree(db, p->aCol[i].zColl);
   103027     p->aCol[i].zColl = zColl;
   103028 
   103029     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
   103030     ** then an index may have been created on this column before the
   103031     ** collation type was added. Correct this if it is the case.
   103032     */
   103033     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   103034       assert( pIdx->nKeyCol==1 );
   103035       if( pIdx->aiColumn[0]==i ){
   103036         pIdx->azColl[0] = p->aCol[i].zColl;
   103037       }
   103038     }
   103039   }else{
   103040     sqlite3DbFree(db, zColl);
   103041   }
   103042 }
   103043 
   103044 /*
   103045 ** This function returns the collation sequence for database native text
   103046 ** encoding identified by the string zName, length nName.
   103047 **
   103048 ** If the requested collation sequence is not available, or not available
   103049 ** in the database native encoding, the collation factory is invoked to
   103050 ** request it. If the collation factory does not supply such a sequence,
   103051 ** and the sequence is available in another text encoding, then that is
   103052 ** returned instead.
   103053 **
   103054 ** If no versions of the requested collations sequence are available, or
   103055 ** another error occurs, NULL is returned and an error message written into
   103056 ** pParse.
   103057 **
   103058 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
   103059 ** invokes the collation factory if the named collation cannot be found
   103060 ** and generates an error message.
   103061 **
   103062 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
   103063 */
   103064 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
   103065   sqlite3 *db = pParse->db;
   103066   u8 enc = ENC(db);
   103067   u8 initbusy = db->init.busy;
   103068   CollSeq *pColl;
   103069 
   103070   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
   103071   if( !initbusy && (!pColl || !pColl->xCmp) ){
   103072     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
   103073   }
   103074 
   103075   return pColl;
   103076 }
   103077 
   103078 
   103079 /*
   103080 ** Generate code that will increment the schema cookie.
   103081 **
   103082 ** The schema cookie is used to determine when the schema for the
   103083 ** database changes.  After each schema change, the cookie value
   103084 ** changes.  When a process first reads the schema it records the
   103085 ** cookie.  Thereafter, whenever it goes to access the database,
   103086 ** it checks the cookie to make sure the schema has not changed
   103087 ** since it was last read.
   103088 **
   103089 ** This plan is not completely bullet-proof.  It is possible for
   103090 ** the schema to change multiple times and for the cookie to be
   103091 ** set back to prior value.  But schema changes are infrequent
   103092 ** and the probability of hitting the same cookie value is only
   103093 ** 1 chance in 2^32.  So we're safe enough.
   103094 **
   103095 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
   103096 ** the schema-version whenever the schema changes.
   103097 */
   103098 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   103099   sqlite3 *db = pParse->db;
   103100   Vdbe *v = pParse->pVdbe;
   103101   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   103102   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
   103103                     db->aDb[iDb].pSchema->schema_cookie+1);
   103104 }
   103105 
   103106 /*
   103107 ** Measure the number of characters needed to output the given
   103108 ** identifier.  The number returned includes any quotes used
   103109 ** but does not include the null terminator.
   103110 **
   103111 ** The estimate is conservative.  It might be larger that what is
   103112 ** really needed.
   103113 */
   103114 static int identLength(const char *z){
   103115   int n;
   103116   for(n=0; *z; n++, z++){
   103117     if( *z=='"' ){ n++; }
   103118   }
   103119   return n + 2;
   103120 }
   103121 
   103122 /*
   103123 ** The first parameter is a pointer to an output buffer. The second
   103124 ** parameter is a pointer to an integer that contains the offset at
   103125 ** which to write into the output buffer. This function copies the
   103126 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
   103127 ** to the specified offset in the buffer and updates *pIdx to refer
   103128 ** to the first byte after the last byte written before returning.
   103129 **
   103130 ** If the string zSignedIdent consists entirely of alpha-numeric
   103131 ** characters, does not begin with a digit and is not an SQL keyword,
   103132 ** then it is copied to the output buffer exactly as it is. Otherwise,
   103133 ** it is quoted using double-quotes.
   103134 */
   103135 static void identPut(char *z, int *pIdx, char *zSignedIdent){
   103136   unsigned char *zIdent = (unsigned char*)zSignedIdent;
   103137   int i, j, needQuote;
   103138   i = *pIdx;
   103139 
   103140   for(j=0; zIdent[j]; j++){
   103141     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
   103142   }
   103143   needQuote = sqlite3Isdigit(zIdent[0])
   103144             || sqlite3KeywordCode(zIdent, j)!=TK_ID
   103145             || zIdent[j]!=0
   103146             || j==0;
   103147 
   103148   if( needQuote ) z[i++] = '"';
   103149   for(j=0; zIdent[j]; j++){
   103150     z[i++] = zIdent[j];
   103151     if( zIdent[j]=='"' ) z[i++] = '"';
   103152   }
   103153   if( needQuote ) z[i++] = '"';
   103154   z[i] = 0;
   103155   *pIdx = i;
   103156 }
   103157 
   103158 /*
   103159 ** Generate a CREATE TABLE statement appropriate for the given
   103160 ** table.  Memory to hold the text of the statement is obtained
   103161 ** from sqliteMalloc() and must be freed by the calling function.
   103162 */
   103163 static char *createTableStmt(sqlite3 *db, Table *p){
   103164   int i, k, n;
   103165   char *zStmt;
   103166   char *zSep, *zSep2, *zEnd;
   103167   Column *pCol;
   103168   n = 0;
   103169   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
   103170     n += identLength(pCol->zName) + 5;
   103171   }
   103172   n += identLength(p->zName);
   103173   if( n<50 ){
   103174     zSep = "";
   103175     zSep2 = ",";
   103176     zEnd = ")";
   103177   }else{
   103178     zSep = "\n  ";
   103179     zSep2 = ",\n  ";
   103180     zEnd = "\n)";
   103181   }
   103182   n += 35 + 6*p->nCol;
   103183   zStmt = sqlite3DbMallocRaw(0, n);
   103184   if( zStmt==0 ){
   103185     sqlite3OomFault(db);
   103186     return 0;
   103187   }
   103188   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
   103189   k = sqlite3Strlen30(zStmt);
   103190   identPut(zStmt, &k, p->zName);
   103191   zStmt[k++] = '(';
   103192   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
   103193     static const char * const azType[] = {
   103194         /* SQLITE_AFF_BLOB    */ "",
   103195         /* SQLITE_AFF_TEXT    */ " TEXT",
   103196         /* SQLITE_AFF_NUMERIC */ " NUM",
   103197         /* SQLITE_AFF_INTEGER */ " INT",
   103198         /* SQLITE_AFF_REAL    */ " REAL"
   103199     };
   103200     int len;
   103201     const char *zType;
   103202 
   103203     sqlite3_snprintf(n-k, &zStmt[k], zSep);
   103204     k += sqlite3Strlen30(&zStmt[k]);
   103205     zSep = zSep2;
   103206     identPut(zStmt, &k, pCol->zName);
   103207     assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
   103208     assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
   103209     testcase( pCol->affinity==SQLITE_AFF_BLOB );
   103210     testcase( pCol->affinity==SQLITE_AFF_TEXT );
   103211     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
   103212     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
   103213     testcase( pCol->affinity==SQLITE_AFF_REAL );
   103214 
   103215     zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
   103216     len = sqlite3Strlen30(zType);
   103217     assert( pCol->affinity==SQLITE_AFF_BLOB
   103218             || pCol->affinity==sqlite3AffinityType(zType, 0) );
   103219     memcpy(&zStmt[k], zType, len);
   103220     k += len;
   103221     assert( k<=n );
   103222   }
   103223   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
   103224   return zStmt;
   103225 }
   103226 
   103227 /*
   103228 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
   103229 ** on success and SQLITE_NOMEM on an OOM error.
   103230 */
   103231 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
   103232   char *zExtra;
   103233   int nByte;
   103234   if( pIdx->nColumn>=N ) return SQLITE_OK;
   103235   assert( pIdx->isResized==0 );
   103236   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
   103237   zExtra = sqlite3DbMallocZero(db, nByte);
   103238   if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
   103239   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
   103240   pIdx->azColl = (const char**)zExtra;
   103241   zExtra += sizeof(char*)*N;
   103242   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
   103243   pIdx->aiColumn = (i16*)zExtra;
   103244   zExtra += sizeof(i16)*N;
   103245   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
   103246   pIdx->aSortOrder = (u8*)zExtra;
   103247   pIdx->nColumn = N;
   103248   pIdx->isResized = 1;
   103249   return SQLITE_OK;
   103250 }
   103251 
   103252 /*
   103253 ** Estimate the total row width for a table.
   103254 */
   103255 static void estimateTableWidth(Table *pTab){
   103256   unsigned wTable = 0;
   103257   const Column *pTabCol;
   103258   int i;
   103259   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
   103260     wTable += pTabCol->szEst;
   103261   }
   103262   if( pTab->iPKey<0 ) wTable++;
   103263   pTab->szTabRow = sqlite3LogEst(wTable*4);
   103264 }
   103265 
   103266 /*
   103267 ** Estimate the average size of a row for an index.
   103268 */
   103269 static void estimateIndexWidth(Index *pIdx){
   103270   unsigned wIndex = 0;
   103271   int i;
   103272   const Column *aCol = pIdx->pTable->aCol;
   103273   for(i=0; i<pIdx->nColumn; i++){
   103274     i16 x = pIdx->aiColumn[i];
   103275     assert( x<pIdx->pTable->nCol );
   103276     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
   103277   }
   103278   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
   103279 }
   103280 
   103281 /* Return true if value x is found any of the first nCol entries of aiCol[]
   103282 */
   103283 static int hasColumn(const i16 *aiCol, int nCol, int x){
   103284   while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
   103285   return 0;
   103286 }
   103287 
   103288 /*
   103289 ** This routine runs at the end of parsing a CREATE TABLE statement that
   103290 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
   103291 ** internal schema data structures and the generated VDBE code so that they
   103292 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
   103293 ** Changes include:
   103294 **
   103295 **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
   103296 **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
   103297 **          into BTREE_BLOBKEY.
   103298 **     (3)  Bypass the creation of the sqlite_master table entry
   103299 **          for the PRIMARY KEY as the primary key index is now
   103300 **          identified by the sqlite_master table entry of the table itself.
   103301 **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
   103302 **          schema to the rootpage from the main table.
   103303 **     (5)  Add all table columns to the PRIMARY KEY Index object
   103304 **          so that the PRIMARY KEY is a covering index.  The surplus
   103305 **          columns are part of KeyInfo.nAllField and are not used for
   103306 **          sorting or lookup or uniqueness checks.
   103307 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
   103308 **          indices with the PRIMARY KEY columns.
   103309 **
   103310 ** For virtual tables, only (1) is performed.
   103311 */
   103312 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   103313   Index *pIdx;
   103314   Index *pPk;
   103315   int nPk;
   103316   int i, j;
   103317   sqlite3 *db = pParse->db;
   103318   Vdbe *v = pParse->pVdbe;
   103319 
   103320   /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
   103321   */
   103322   if( !db->init.imposterTable ){
   103323     for(i=0; i<pTab->nCol; i++){
   103324       if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
   103325         pTab->aCol[i].notNull = OE_Abort;
   103326       }
   103327     }
   103328   }
   103329 
   103330   /* The remaining transformations only apply to b-tree tables, not to
   103331   ** virtual tables */
   103332   if( IN_DECLARE_VTAB ) return;
   103333 
   103334   /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
   103335   ** into BTREE_BLOBKEY.
   103336   */
   103337   if( pParse->addrCrTab ){
   103338     assert( v );
   103339     sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
   103340   }
   103341 
   103342   /* Locate the PRIMARY KEY index.  Or, if this table was originally
   103343   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
   103344   */
   103345   if( pTab->iPKey>=0 ){
   103346     ExprList *pList;
   103347     Token ipkToken;
   103348     sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
   103349     pList = sqlite3ExprListAppend(pParse, 0,
   103350                   sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
   103351     if( pList==0 ) return;
   103352     pList->a[0].sortOrder = pParse->iPkSortOrder;
   103353     assert( pParse->pNewTable==pTab );
   103354     sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
   103355                        SQLITE_IDXTYPE_PRIMARYKEY);
   103356     if( db->mallocFailed ) return;
   103357     pPk = sqlite3PrimaryKeyIndex(pTab);
   103358     pTab->iPKey = -1;
   103359   }else{
   103360     pPk = sqlite3PrimaryKeyIndex(pTab);
   103361 
   103362     /*
   103363     ** Remove all redundant columns from the PRIMARY KEY.  For example, change
   103364     ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
   103365     ** code assumes the PRIMARY KEY contains no repeated columns.
   103366     */
   103367     for(i=j=1; i<pPk->nKeyCol; i++){
   103368       if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
   103369         pPk->nColumn--;
   103370       }else{
   103371         pPk->aiColumn[j++] = pPk->aiColumn[i];
   103372       }
   103373     }
   103374     pPk->nKeyCol = j;
   103375   }
   103376   assert( pPk!=0 );
   103377   pPk->isCovering = 1;
   103378   if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
   103379   nPk = pPk->nKeyCol;
   103380 
   103381   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
   103382   ** table entry. This is only required if currently generating VDBE
   103383   ** code for a CREATE TABLE (not when parsing one as part of reading
   103384   ** a database schema).  */
   103385   if( v && pPk->tnum>0 ){
   103386     assert( db->init.busy==0 );
   103387     sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
   103388   }
   103389 
   103390   /* The root page of the PRIMARY KEY is the table root page */
   103391   pPk->tnum = pTab->tnum;
   103392 
   103393   /* Update the in-memory representation of all UNIQUE indices by converting
   103394   ** the final rowid column into one or more columns of the PRIMARY KEY.
   103395   */
   103396   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   103397     int n;
   103398     if( IsPrimaryKeyIndex(pIdx) ) continue;
   103399     for(i=n=0; i<nPk; i++){
   103400       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
   103401     }
   103402     if( n==0 ){
   103403       /* This index is a superset of the primary key */
   103404       pIdx->nColumn = pIdx->nKeyCol;
   103405       continue;
   103406     }
   103407     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
   103408     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
   103409       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
   103410         pIdx->aiColumn[j] = pPk->aiColumn[i];
   103411         pIdx->azColl[j] = pPk->azColl[i];
   103412         j++;
   103413       }
   103414     }
   103415     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
   103416     assert( pIdx->nColumn>=j );
   103417   }
   103418 
   103419   /* Add all table columns to the PRIMARY KEY index
   103420   */
   103421   if( nPk<pTab->nCol ){
   103422     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
   103423     for(i=0, j=nPk; i<pTab->nCol; i++){
   103424       if( !hasColumn(pPk->aiColumn, j, i) ){
   103425         assert( j<pPk->nColumn );
   103426         pPk->aiColumn[j] = i;
   103427         pPk->azColl[j] = sqlite3StrBINARY;
   103428         j++;
   103429       }
   103430     }
   103431     assert( pPk->nColumn==j );
   103432     assert( pTab->nCol==j );
   103433   }else{
   103434     pPk->nColumn = pTab->nCol;
   103435   }
   103436 }
   103437 
   103438 /*
   103439 ** This routine is called to report the final ")" that terminates
   103440 ** a CREATE TABLE statement.
   103441 **
   103442 ** The table structure that other action routines have been building
   103443 ** is added to the internal hash tables, assuming no errors have
   103444 ** occurred.
   103445 **
   103446 ** An entry for the table is made in the master table on disk, unless
   103447 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
   103448 ** it means we are reading the sqlite_master table because we just
   103449 ** connected to the database or because the sqlite_master table has
   103450 ** recently changed, so the entry for this table already exists in
   103451 ** the sqlite_master table.  We do not want to create it again.
   103452 **
   103453 ** If the pSelect argument is not NULL, it means that this routine
   103454 ** was called to create a table generated from a
   103455 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
   103456 ** the new table will match the result set of the SELECT.
   103457 */
   103458 SQLITE_PRIVATE void sqlite3EndTable(
   103459   Parse *pParse,          /* Parse context */
   103460   Token *pCons,           /* The ',' token after the last column defn. */
   103461   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
   103462   u8 tabOpts,             /* Extra table options. Usually 0. */
   103463   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
   103464 ){
   103465   Table *p;                 /* The new table */
   103466   sqlite3 *db = pParse->db; /* The database connection */
   103467   int iDb;                  /* Database in which the table lives */
   103468   Index *pIdx;              /* An implied index of the table */
   103469 
   103470   if( pEnd==0 && pSelect==0 ){
   103471     return;
   103472   }
   103473   assert( !db->mallocFailed );
   103474   p = pParse->pNewTable;
   103475   if( p==0 ) return;
   103476 
   103477   assert( !db->init.busy || !pSelect );
   103478 
   103479   /* If the db->init.busy is 1 it means we are reading the SQL off the
   103480   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
   103481   ** So do not write to the disk again.  Extract the root page number
   103482   ** for the table from the db->init.newTnum field.  (The page number
   103483   ** should have been put there by the sqliteOpenCb routine.)
   103484   **
   103485   ** If the root page number is 1, that means this is the sqlite_master
   103486   ** table itself.  So mark it read-only.
   103487   */
   103488   if( db->init.busy ){
   103489     p->tnum = db->init.newTnum;
   103490     if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
   103491   }
   103492 
   103493   /* Special processing for WITHOUT ROWID Tables */
   103494   if( tabOpts & TF_WithoutRowid ){
   103495     if( (p->tabFlags & TF_Autoincrement) ){
   103496       sqlite3ErrorMsg(pParse,
   103497           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
   103498       return;
   103499     }
   103500     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
   103501       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
   103502     }else{
   103503       p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
   103504       convertToWithoutRowidTable(pParse, p);
   103505     }
   103506   }
   103507 
   103508   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   103509 
   103510 #ifndef SQLITE_OMIT_CHECK
   103511   /* Resolve names in all CHECK constraint expressions.
   103512   */
   103513   if( p->pCheck ){
   103514     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
   103515   }
   103516 #endif /* !defined(SQLITE_OMIT_CHECK) */
   103517 
   103518   /* Estimate the average row size for the table and for all implied indices */
   103519   estimateTableWidth(p);
   103520   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   103521     estimateIndexWidth(pIdx);
   103522   }
   103523 
   103524   /* If not initializing, then create a record for the new table
   103525   ** in the SQLITE_MASTER table of the database.
   103526   **
   103527   ** If this is a TEMPORARY table, write the entry into the auxiliary
   103528   ** file instead of into the main database file.
   103529   */
   103530   if( !db->init.busy ){
   103531     int n;
   103532     Vdbe *v;
   103533     char *zType;    /* "view" or "table" */
   103534     char *zType2;   /* "VIEW" or "TABLE" */
   103535     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
   103536 
   103537     v = sqlite3GetVdbe(pParse);
   103538     if( NEVER(v==0) ) return;
   103539 
   103540     sqlite3VdbeAddOp1(v, OP_Close, 0);
   103541 
   103542     /*
   103543     ** Initialize zType for the new view or table.
   103544     */
   103545     if( p->pSelect==0 ){
   103546       /* A regular table */
   103547       zType = "table";
   103548       zType2 = "TABLE";
   103549 #ifndef SQLITE_OMIT_VIEW
   103550     }else{
   103551       /* A view */
   103552       zType = "view";
   103553       zType2 = "VIEW";
   103554 #endif
   103555     }
   103556 
   103557     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
   103558     ** statement to populate the new table. The root-page number for the
   103559     ** new table is in register pParse->regRoot.
   103560     **
   103561     ** Once the SELECT has been coded by sqlite3Select(), it is in a
   103562     ** suitable state to query for the column names and types to be used
   103563     ** by the new table.
   103564     **
   103565     ** A shared-cache write-lock is not required to write to the new table,
   103566     ** as a schema-lock must have already been obtained to create it. Since
   103567     ** a schema-lock excludes all other database users, the write-lock would
   103568     ** be redundant.
   103569     */
   103570     if( pSelect ){
   103571       SelectDest dest;    /* Where the SELECT should store results */
   103572       int regYield;       /* Register holding co-routine entry-point */
   103573       int addrTop;        /* Top of the co-routine */
   103574       int regRec;         /* A record to be insert into the new table */
   103575       int regRowid;       /* Rowid of the next row to insert */
   103576       int addrInsLoop;    /* Top of the loop for inserting rows */
   103577       Table *pSelTab;     /* A table that describes the SELECT results */
   103578 
   103579       regYield = ++pParse->nMem;
   103580       regRec = ++pParse->nMem;
   103581       regRowid = ++pParse->nMem;
   103582       assert(pParse->nTab==1);
   103583       sqlite3MayAbort(pParse);
   103584       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
   103585       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
   103586       pParse->nTab = 2;
   103587       addrTop = sqlite3VdbeCurrentAddr(v) + 1;
   103588       sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
   103589       if( pParse->nErr ) return;
   103590       pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
   103591       if( pSelTab==0 ) return;
   103592       assert( p->aCol==0 );
   103593       p->nCol = pSelTab->nCol;
   103594       p->aCol = pSelTab->aCol;
   103595       pSelTab->nCol = 0;
   103596       pSelTab->aCol = 0;
   103597       sqlite3DeleteTable(db, pSelTab);
   103598       sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
   103599       sqlite3Select(pParse, pSelect, &dest);
   103600       if( pParse->nErr ) return;
   103601       sqlite3VdbeEndCoroutine(v, regYield);
   103602       sqlite3VdbeJumpHere(v, addrTop - 1);
   103603       addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
   103604       VdbeCoverage(v);
   103605       sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
   103606       sqlite3TableAffinity(v, p, 0);
   103607       sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
   103608       sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
   103609       sqlite3VdbeGoto(v, addrInsLoop);
   103610       sqlite3VdbeJumpHere(v, addrInsLoop);
   103611       sqlite3VdbeAddOp1(v, OP_Close, 1);
   103612     }
   103613 
   103614     /* Compute the complete text of the CREATE statement */
   103615     if( pSelect ){
   103616       zStmt = createTableStmt(db, p);
   103617     }else{
   103618       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
   103619       n = (int)(pEnd2->z - pParse->sNameToken.z);
   103620       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
   103621       zStmt = sqlite3MPrintf(db,
   103622           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
   103623       );
   103624     }
   103625 
   103626     /* A slot for the record has already been allocated in the
   103627     ** SQLITE_MASTER table.  We just need to update that slot with all
   103628     ** the information we've collected.
   103629     */
   103630     sqlite3NestedParse(pParse,
   103631       "UPDATE %Q.%s "
   103632          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
   103633        "WHERE rowid=#%d",
   103634       db->aDb[iDb].zDbSName, MASTER_NAME,
   103635       zType,
   103636       p->zName,
   103637       p->zName,
   103638       pParse->regRoot,
   103639       zStmt,
   103640       pParse->regRowid
   103641     );
   103642     sqlite3DbFree(db, zStmt);
   103643     sqlite3ChangeCookie(pParse, iDb);
   103644 
   103645 #ifndef SQLITE_OMIT_AUTOINCREMENT
   103646     /* Check to see if we need to create an sqlite_sequence table for
   103647     ** keeping track of autoincrement keys.
   103648     */
   103649     if( (p->tabFlags & TF_Autoincrement)!=0 ){
   103650       Db *pDb = &db->aDb[iDb];
   103651       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   103652       if( pDb->pSchema->pSeqTab==0 ){
   103653         sqlite3NestedParse(pParse,
   103654           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
   103655           pDb->zDbSName
   103656         );
   103657       }
   103658     }
   103659 #endif
   103660 
   103661     /* Reparse everything to update our internal data structures */
   103662     sqlite3VdbeAddParseSchemaOp(v, iDb,
   103663            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
   103664   }
   103665 
   103666 
   103667   /* Add the table to the in-memory representation of the database.
   103668   */
   103669   if( db->init.busy ){
   103670     Table *pOld;
   103671     Schema *pSchema = p->pSchema;
   103672     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   103673     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
   103674     if( pOld ){
   103675       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
   103676       sqlite3OomFault(db);
   103677       return;
   103678     }
   103679     pParse->pNewTable = 0;
   103680     db->mDbFlags |= DBFLAG_SchemaChange;
   103681 
   103682 #ifndef SQLITE_OMIT_ALTERTABLE
   103683     if( !p->pSelect ){
   103684       const char *zName = (const char *)pParse->sNameToken.z;
   103685       int nName;
   103686       assert( !pSelect && pCons && pEnd );
   103687       if( pCons->z==0 ){
   103688         pCons = pEnd;
   103689       }
   103690       nName = (int)((const char *)pCons->z - zName);
   103691       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
   103692     }
   103693 #endif
   103694   }
   103695 }
   103696 
   103697 #ifndef SQLITE_OMIT_VIEW
   103698 /*
   103699 ** The parser calls this routine in order to create a new VIEW
   103700 */
   103701 SQLITE_PRIVATE void sqlite3CreateView(
   103702   Parse *pParse,     /* The parsing context */
   103703   Token *pBegin,     /* The CREATE token that begins the statement */
   103704   Token *pName1,     /* The token that holds the name of the view */
   103705   Token *pName2,     /* The token that holds the name of the view */
   103706   ExprList *pCNames, /* Optional list of view column names */
   103707   Select *pSelect,   /* A SELECT statement that will become the new view */
   103708   int isTemp,        /* TRUE for a TEMPORARY view */
   103709   int noErr          /* Suppress error messages if VIEW already exists */
   103710 ){
   103711   Table *p;
   103712   int n;
   103713   const char *z;
   103714   Token sEnd;
   103715   DbFixer sFix;
   103716   Token *pName = 0;
   103717   int iDb;
   103718   sqlite3 *db = pParse->db;
   103719 
   103720   if( pParse->nVar>0 ){
   103721     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
   103722     goto create_view_fail;
   103723   }
   103724   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   103725   p = pParse->pNewTable;
   103726   if( p==0 || pParse->nErr ) goto create_view_fail;
   103727   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   103728   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   103729   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
   103730   if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
   103731 
   103732   /* Make a copy of the entire SELECT statement that defines the view.
   103733   ** This will force all the Expr.token.z values to be dynamically
   103734   ** allocated rather than point to the input string - which means that
   103735   ** they will persist after the current sqlite3_exec() call returns.
   103736   */
   103737   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   103738   p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
   103739   if( db->mallocFailed ) goto create_view_fail;
   103740 
   103741   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
   103742   ** the end.
   103743   */
   103744   sEnd = pParse->sLastToken;
   103745   assert( sEnd.z[0]!=0 || sEnd.n==0 );
   103746   if( sEnd.z[0]!=';' ){
   103747     sEnd.z += sEnd.n;
   103748   }
   103749   sEnd.n = 0;
   103750   n = (int)(sEnd.z - pBegin->z);
   103751   assert( n>0 );
   103752   z = pBegin->z;
   103753   while( sqlite3Isspace(z[n-1]) ){ n--; }
   103754   sEnd.z = &z[n-1];
   103755   sEnd.n = 1;
   103756 
   103757   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
   103758   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
   103759 
   103760 create_view_fail:
   103761   sqlite3SelectDelete(db, pSelect);
   103762   sqlite3ExprListDelete(db, pCNames);
   103763   return;
   103764 }
   103765 #endif /* SQLITE_OMIT_VIEW */
   103766 
   103767 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   103768 /*
   103769 ** The Table structure pTable is really a VIEW.  Fill in the names of
   103770 ** the columns of the view in the pTable structure.  Return the number
   103771 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
   103772 */
   103773 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   103774   Table *pSelTab;   /* A fake table from which we get the result set */
   103775   Select *pSel;     /* Copy of the SELECT that implements the view */
   103776   int nErr = 0;     /* Number of errors encountered */
   103777   int n;            /* Temporarily holds the number of cursors assigned */
   103778   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
   103779 #ifndef SQLITE_OMIT_VIRTUALTABLE
   103780   int rc;
   103781 #endif
   103782 #ifndef SQLITE_OMIT_AUTHORIZATION
   103783   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
   103784 #endif
   103785 
   103786   assert( pTable );
   103787 
   103788 #ifndef SQLITE_OMIT_VIRTUALTABLE
   103789   db->nSchemaLock++;
   103790   rc = sqlite3VtabCallConnect(pParse, pTable);
   103791   db->nSchemaLock--;
   103792   if( rc ){
   103793     return 1;
   103794   }
   103795   if( IsVirtual(pTable) ) return 0;
   103796 #endif
   103797 
   103798 #ifndef SQLITE_OMIT_VIEW
   103799   /* A positive nCol means the columns names for this view are
   103800   ** already known.
   103801   */
   103802   if( pTable->nCol>0 ) return 0;
   103803 
   103804   /* A negative nCol is a special marker meaning that we are currently
   103805   ** trying to compute the column names.  If we enter this routine with
   103806   ** a negative nCol, it means two or more views form a loop, like this:
   103807   **
   103808   **     CREATE VIEW one AS SELECT * FROM two;
   103809   **     CREATE VIEW two AS SELECT * FROM one;
   103810   **
   103811   ** Actually, the error above is now caught prior to reaching this point.
   103812   ** But the following test is still important as it does come up
   103813   ** in the following:
   103814   **
   103815   **     CREATE TABLE main.ex1(a);
   103816   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   103817   **     SELECT * FROM temp.ex1;
   103818   */
   103819   if( pTable->nCol<0 ){
   103820     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
   103821     return 1;
   103822   }
   103823   assert( pTable->nCol>=0 );
   103824 
   103825   /* If we get this far, it means we need to compute the table names.
   103826   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
   103827   ** "*" elements in the results set of the view and will assign cursors
   103828   ** to the elements of the FROM clause.  But we do not want these changes
   103829   ** to be permanent.  So the computation is done on a copy of the SELECT
   103830   ** statement that defines the view.
   103831   */
   103832   assert( pTable->pSelect );
   103833   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   103834   if( pSel ){
   103835     n = pParse->nTab;
   103836     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
   103837     pTable->nCol = -1;
   103838     db->lookaside.bDisable++;
   103839 #ifndef SQLITE_OMIT_AUTHORIZATION
   103840     xAuth = db->xAuth;
   103841     db->xAuth = 0;
   103842     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   103843     db->xAuth = xAuth;
   103844 #else
   103845     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   103846 #endif
   103847     pParse->nTab = n;
   103848     if( pTable->pCheck ){
   103849       /* CREATE VIEW name(arglist) AS ...
   103850       ** The names of the columns in the table are taken from
   103851       ** arglist which is stored in pTable->pCheck.  The pCheck field
   103852       ** normally holds CHECK constraints on an ordinary table, but for
   103853       ** a VIEW it holds the list of column names.
   103854       */
   103855       sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
   103856                                  &pTable->nCol, &pTable->aCol);
   103857       if( db->mallocFailed==0
   103858        && pParse->nErr==0
   103859        && pTable->nCol==pSel->pEList->nExpr
   103860       ){
   103861         sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
   103862       }
   103863     }else if( pSelTab ){
   103864       /* CREATE VIEW name AS...  without an argument list.  Construct
   103865       ** the column names from the SELECT statement that defines the view.
   103866       */
   103867       assert( pTable->aCol==0 );
   103868       pTable->nCol = pSelTab->nCol;
   103869       pTable->aCol = pSelTab->aCol;
   103870       pSelTab->nCol = 0;
   103871       pSelTab->aCol = 0;
   103872       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
   103873     }else{
   103874       pTable->nCol = 0;
   103875       nErr++;
   103876     }
   103877     sqlite3DeleteTable(db, pSelTab);
   103878     sqlite3SelectDelete(db, pSel);
   103879     db->lookaside.bDisable--;
   103880   } else {
   103881     nErr++;
   103882   }
   103883   pTable->pSchema->schemaFlags |= DB_UnresetViews;
   103884 #endif /* SQLITE_OMIT_VIEW */
   103885   return nErr;
   103886 }
   103887 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
   103888 
   103889 #ifndef SQLITE_OMIT_VIEW
   103890 /*
   103891 ** Clear the column names from every VIEW in database idx.
   103892 */
   103893 static void sqliteViewResetAll(sqlite3 *db, int idx){
   103894   HashElem *i;
   103895   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
   103896   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   103897   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
   103898     Table *pTab = sqliteHashData(i);
   103899     if( pTab->pSelect ){
   103900       sqlite3DeleteColumnNames(db, pTab);
   103901       pTab->aCol = 0;
   103902       pTab->nCol = 0;
   103903     }
   103904   }
   103905   DbClearProperty(db, idx, DB_UnresetViews);
   103906 }
   103907 #else
   103908 # define sqliteViewResetAll(A,B)
   103909 #endif /* SQLITE_OMIT_VIEW */
   103910 
   103911 /*
   103912 ** This function is called by the VDBE to adjust the internal schema
   103913 ** used by SQLite when the btree layer moves a table root page. The
   103914 ** root-page of a table or index in database iDb has changed from iFrom
   103915 ** to iTo.
   103916 **
   103917 ** Ticket #1728:  The symbol table might still contain information
   103918 ** on tables and/or indices that are the process of being deleted.
   103919 ** If you are unlucky, one of those deleted indices or tables might
   103920 ** have the same rootpage number as the real table or index that is
   103921 ** being moved.  So we cannot stop searching after the first match
   103922 ** because the first match might be for one of the deleted indices
   103923 ** or tables and not the table/index that is actually being moved.
   103924 ** We must continue looping until all tables and indices with
   103925 ** rootpage==iFrom have been converted to have a rootpage of iTo
   103926 ** in order to be certain that we got the right one.
   103927 */
   103928 #ifndef SQLITE_OMIT_AUTOVACUUM
   103929 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
   103930   HashElem *pElem;
   103931   Hash *pHash;
   103932   Db *pDb;
   103933 
   103934   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   103935   pDb = &db->aDb[iDb];
   103936   pHash = &pDb->pSchema->tblHash;
   103937   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   103938     Table *pTab = sqliteHashData(pElem);
   103939     if( pTab->tnum==iFrom ){
   103940       pTab->tnum = iTo;
   103941     }
   103942   }
   103943   pHash = &pDb->pSchema->idxHash;
   103944   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   103945     Index *pIdx = sqliteHashData(pElem);
   103946     if( pIdx->tnum==iFrom ){
   103947       pIdx->tnum = iTo;
   103948     }
   103949   }
   103950 }
   103951 #endif
   103952 
   103953 /*
   103954 ** Write code to erase the table with root-page iTable from database iDb.
   103955 ** Also write code to modify the sqlite_master table and internal schema
   103956 ** if a root-page of another table is moved by the btree-layer whilst
   103957 ** erasing iTable (this can happen with an auto-vacuum database).
   103958 */
   103959 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   103960   Vdbe *v = sqlite3GetVdbe(pParse);
   103961   int r1 = sqlite3GetTempReg(pParse);
   103962   assert( iTable>1 );
   103963   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
   103964   sqlite3MayAbort(pParse);
   103965 #ifndef SQLITE_OMIT_AUTOVACUUM
   103966   /* OP_Destroy stores an in integer r1. If this integer
   103967   ** is non-zero, then it is the root page number of a table moved to
   103968   ** location iTable. The following code modifies the sqlite_master table to
   103969   ** reflect this.
   103970   **
   103971   ** The "#NNN" in the SQL is a special constant that means whatever value
   103972   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   103973   ** token for additional information.
   103974   */
   103975   sqlite3NestedParse(pParse,
   103976      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
   103977      pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
   103978 #endif
   103979   sqlite3ReleaseTempReg(pParse, r1);
   103980 }
   103981 
   103982 /*
   103983 ** Write VDBE code to erase table pTab and all associated indices on disk.
   103984 ** Code to update the sqlite_master tables and internal schema definitions
   103985 ** in case a root-page belonging to another table is moved by the btree layer
   103986 ** is also added (this can happen with an auto-vacuum database).
   103987 */
   103988 static void destroyTable(Parse *pParse, Table *pTab){
   103989   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   103990   ** is not defined), then it is important to call OP_Destroy on the
   103991   ** table and index root-pages in order, starting with the numerically
   103992   ** largest root-page number. This guarantees that none of the root-pages
   103993   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   103994   ** following were coded:
   103995   **
   103996   ** OP_Destroy 4 0
   103997   ** ...
   103998   ** OP_Destroy 5 0
   103999   **
   104000   ** and root page 5 happened to be the largest root-page number in the
   104001   ** database, then root page 5 would be moved to page 4 by the
   104002   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   104003   ** a free-list page.
   104004   */
   104005   int iTab = pTab->tnum;
   104006   int iDestroyed = 0;
   104007 
   104008   while( 1 ){
   104009     Index *pIdx;
   104010     int iLargest = 0;
   104011 
   104012     if( iDestroyed==0 || iTab<iDestroyed ){
   104013       iLargest = iTab;
   104014     }
   104015     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   104016       int iIdx = pIdx->tnum;
   104017       assert( pIdx->pSchema==pTab->pSchema );
   104018       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
   104019         iLargest = iIdx;
   104020       }
   104021     }
   104022     if( iLargest==0 ){
   104023       return;
   104024     }else{
   104025       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   104026       assert( iDb>=0 && iDb<pParse->db->nDb );
   104027       destroyRootPage(pParse, iLargest, iDb);
   104028       iDestroyed = iLargest;
   104029     }
   104030   }
   104031 }
   104032 
   104033 /*
   104034 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
   104035 ** after a DROP INDEX or DROP TABLE command.
   104036 */
   104037 static void sqlite3ClearStatTables(
   104038   Parse *pParse,         /* The parsing context */
   104039   int iDb,               /* The database number */
   104040   const char *zType,     /* "idx" or "tbl" */
   104041   const char *zName      /* Name of index or table */
   104042 ){
   104043   int i;
   104044   const char *zDbName = pParse->db->aDb[iDb].zDbSName;
   104045   for(i=1; i<=4; i++){
   104046     char zTab[24];
   104047     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
   104048     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
   104049       sqlite3NestedParse(pParse,
   104050         "DELETE FROM %Q.%s WHERE %s=%Q",
   104051         zDbName, zTab, zType, zName
   104052       );
   104053     }
   104054   }
   104055 }
   104056 
   104057 /*
   104058 ** Generate code to drop a table.
   104059 */
   104060 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
   104061   Vdbe *v;
   104062   sqlite3 *db = pParse->db;
   104063   Trigger *pTrigger;
   104064   Db *pDb = &db->aDb[iDb];
   104065 
   104066   v = sqlite3GetVdbe(pParse);
   104067   assert( v!=0 );
   104068   sqlite3BeginWriteOperation(pParse, 1, iDb);
   104069 
   104070 #ifndef SQLITE_OMIT_VIRTUALTABLE
   104071   if( IsVirtual(pTab) ){
   104072     sqlite3VdbeAddOp0(v, OP_VBegin);
   104073   }
   104074 #endif
   104075 
   104076   /* Drop all triggers associated with the table being dropped. Code
   104077   ** is generated to remove entries from sqlite_master and/or
   104078   ** sqlite_temp_master if required.
   104079   */
   104080   pTrigger = sqlite3TriggerList(pParse, pTab);
   104081   while( pTrigger ){
   104082     assert( pTrigger->pSchema==pTab->pSchema ||
   104083         pTrigger->pSchema==db->aDb[1].pSchema );
   104084     sqlite3DropTriggerPtr(pParse, pTrigger);
   104085     pTrigger = pTrigger->pNext;
   104086   }
   104087 
   104088 #ifndef SQLITE_OMIT_AUTOINCREMENT
   104089   /* Remove any entries of the sqlite_sequence table associated with
   104090   ** the table being dropped. This is done before the table is dropped
   104091   ** at the btree level, in case the sqlite_sequence table needs to
   104092   ** move as a result of the drop (can happen in auto-vacuum mode).
   104093   */
   104094   if( pTab->tabFlags & TF_Autoincrement ){
   104095     sqlite3NestedParse(pParse,
   104096       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
   104097       pDb->zDbSName, pTab->zName
   104098     );
   104099   }
   104100 #endif
   104101 
   104102   /* Drop all SQLITE_MASTER table and index entries that refer to the
   104103   ** table. The program name loops through the master table and deletes
   104104   ** every row that refers to a table of the same name as the one being
   104105   ** dropped. Triggers are handled separately because a trigger can be
   104106   ** created in the temp database that refers to a table in another
   104107   ** database.
   104108   */
   104109   sqlite3NestedParse(pParse,
   104110       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
   104111       pDb->zDbSName, MASTER_NAME, pTab->zName);
   104112   if( !isView && !IsVirtual(pTab) ){
   104113     destroyTable(pParse, pTab);
   104114   }
   104115 
   104116   /* Remove the table entry from SQLite's internal schema and modify
   104117   ** the schema cookie.
   104118   */
   104119   if( IsVirtual(pTab) ){
   104120     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
   104121   }
   104122   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   104123   sqlite3ChangeCookie(pParse, iDb);
   104124   sqliteViewResetAll(db, iDb);
   104125 }
   104126 
   104127 /*
   104128 ** This routine is called to do the work of a DROP TABLE statement.
   104129 ** pName is the name of the table to be dropped.
   104130 */
   104131 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
   104132   Table *pTab;
   104133   Vdbe *v;
   104134   sqlite3 *db = pParse->db;
   104135   int iDb;
   104136 
   104137   if( db->mallocFailed ){
   104138     goto exit_drop_table;
   104139   }
   104140   assert( pParse->nErr==0 );
   104141   assert( pName->nSrc==1 );
   104142   if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
   104143   if( noErr ) db->suppressErr++;
   104144   assert( isView==0 || isView==LOCATE_VIEW );
   104145   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
   104146   if( noErr ) db->suppressErr--;
   104147 
   104148   if( pTab==0 ){
   104149     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   104150     goto exit_drop_table;
   104151   }
   104152   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   104153   assert( iDb>=0 && iDb<db->nDb );
   104154 
   104155   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
   104156   ** it is initialized.
   104157   */
   104158   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
   104159     goto exit_drop_table;
   104160   }
   104161 #ifndef SQLITE_OMIT_AUTHORIZATION
   104162   {
   104163     int code;
   104164     const char *zTab = SCHEMA_TABLE(iDb);
   104165     const char *zDb = db->aDb[iDb].zDbSName;
   104166     const char *zArg2 = 0;
   104167     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
   104168       goto exit_drop_table;
   104169     }
   104170     if( isView ){
   104171       if( !OMIT_TEMPDB && iDb==1 ){
   104172         code = SQLITE_DROP_TEMP_VIEW;
   104173       }else{
   104174         code = SQLITE_DROP_VIEW;
   104175       }
   104176 #ifndef SQLITE_OMIT_VIRTUALTABLE
   104177     }else if( IsVirtual(pTab) ){
   104178       code = SQLITE_DROP_VTABLE;
   104179       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
   104180 #endif
   104181     }else{
   104182       if( !OMIT_TEMPDB && iDb==1 ){
   104183         code = SQLITE_DROP_TEMP_TABLE;
   104184       }else{
   104185         code = SQLITE_DROP_TABLE;
   104186       }
   104187     }
   104188     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
   104189       goto exit_drop_table;
   104190     }
   104191     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   104192       goto exit_drop_table;
   104193     }
   104194   }
   104195 #endif
   104196   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   104197     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
   104198     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
   104199     goto exit_drop_table;
   104200   }
   104201 
   104202 #ifndef SQLITE_OMIT_VIEW
   104203   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   104204   ** on a table.
   104205   */
   104206   if( isView && pTab->pSelect==0 ){
   104207     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
   104208     goto exit_drop_table;
   104209   }
   104210   if( !isView && pTab->pSelect ){
   104211     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
   104212     goto exit_drop_table;
   104213   }
   104214 #endif
   104215 
   104216   /* Generate code to remove the table from the master table
   104217   ** on disk.
   104218   */
   104219   v = sqlite3GetVdbe(pParse);
   104220   if( v ){
   104221     sqlite3BeginWriteOperation(pParse, 1, iDb);
   104222     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
   104223     sqlite3FkDropTable(pParse, pName, pTab);
   104224     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
   104225   }
   104226 
   104227 exit_drop_table:
   104228   sqlite3SrcListDelete(db, pName);
   104229 }
   104230 
   104231 /*
   104232 ** This routine is called to create a new foreign key on the table
   104233 ** currently under construction.  pFromCol determines which columns
   104234 ** in the current table point to the foreign key.  If pFromCol==0 then
   104235 ** connect the key to the last column inserted.  pTo is the name of
   104236 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
   104237 ** of tables in the parent pTo table.  flags contains all
   104238 ** information about the conflict resolution algorithms specified
   104239 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
   104240 **
   104241 ** An FKey structure is created and added to the table currently
   104242 ** under construction in the pParse->pNewTable field.
   104243 **
   104244 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
   104245 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
   104246 */
   104247 SQLITE_PRIVATE void sqlite3CreateForeignKey(
   104248   Parse *pParse,       /* Parsing context */
   104249   ExprList *pFromCol,  /* Columns in this table that point to other table */
   104250   Token *pTo,          /* Name of the other table */
   104251   ExprList *pToCol,    /* Columns in the other table */
   104252   int flags            /* Conflict resolution algorithms. */
   104253 ){
   104254   sqlite3 *db = pParse->db;
   104255 #ifndef SQLITE_OMIT_FOREIGN_KEY
   104256   FKey *pFKey = 0;
   104257   FKey *pNextTo;
   104258   Table *p = pParse->pNewTable;
   104259   int nByte;
   104260   int i;
   104261   int nCol;
   104262   char *z;
   104263 
   104264   assert( pTo!=0 );
   104265   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
   104266   if( pFromCol==0 ){
   104267     int iCol = p->nCol-1;
   104268     if( NEVER(iCol<0) ) goto fk_end;
   104269     if( pToCol && pToCol->nExpr!=1 ){
   104270       sqlite3ErrorMsg(pParse, "foreign key on %s"
   104271          " should reference only one column of table %T",
   104272          p->aCol[iCol].zName, pTo);
   104273       goto fk_end;
   104274     }
   104275     nCol = 1;
   104276   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
   104277     sqlite3ErrorMsg(pParse,
   104278         "number of columns in foreign key does not match the number of "
   104279         "columns in the referenced table");
   104280     goto fk_end;
   104281   }else{
   104282     nCol = pFromCol->nExpr;
   104283   }
   104284   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   104285   if( pToCol ){
   104286     for(i=0; i<pToCol->nExpr; i++){
   104287       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
   104288     }
   104289   }
   104290   pFKey = sqlite3DbMallocZero(db, nByte );
   104291   if( pFKey==0 ){
   104292     goto fk_end;
   104293   }
   104294   pFKey->pFrom = p;
   104295   pFKey->pNextFrom = p->pFKey;
   104296   z = (char*)&pFKey->aCol[nCol];
   104297   pFKey->zTo = z;
   104298   memcpy(z, pTo->z, pTo->n);
   104299   z[pTo->n] = 0;
   104300   sqlite3Dequote(z);
   104301   z += pTo->n+1;
   104302   pFKey->nCol = nCol;
   104303   if( pFromCol==0 ){
   104304     pFKey->aCol[0].iFrom = p->nCol-1;
   104305   }else{
   104306     for(i=0; i<nCol; i++){
   104307       int j;
   104308       for(j=0; j<p->nCol; j++){
   104309         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
   104310           pFKey->aCol[i].iFrom = j;
   104311           break;
   104312         }
   104313       }
   104314       if( j>=p->nCol ){
   104315         sqlite3ErrorMsg(pParse,
   104316           "unknown column \"%s\" in foreign key definition",
   104317           pFromCol->a[i].zName);
   104318         goto fk_end;
   104319       }
   104320     }
   104321   }
   104322   if( pToCol ){
   104323     for(i=0; i<nCol; i++){
   104324       int n = sqlite3Strlen30(pToCol->a[i].zName);
   104325       pFKey->aCol[i].zCol = z;
   104326       memcpy(z, pToCol->a[i].zName, n);
   104327       z[n] = 0;
   104328       z += n+1;
   104329     }
   104330   }
   104331   pFKey->isDeferred = 0;
   104332   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
   104333   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
   104334 
   104335   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   104336   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
   104337       pFKey->zTo, (void *)pFKey
   104338   );
   104339   if( pNextTo==pFKey ){
   104340     sqlite3OomFault(db);
   104341     goto fk_end;
   104342   }
   104343   if( pNextTo ){
   104344     assert( pNextTo->pPrevTo==0 );
   104345     pFKey->pNextTo = pNextTo;
   104346     pNextTo->pPrevTo = pFKey;
   104347   }
   104348 
   104349   /* Link the foreign key to the table as the last step.
   104350   */
   104351   p->pFKey = pFKey;
   104352   pFKey = 0;
   104353 
   104354 fk_end:
   104355   sqlite3DbFree(db, pFKey);
   104356 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   104357   sqlite3ExprListDelete(db, pFromCol);
   104358   sqlite3ExprListDelete(db, pToCol);
   104359 }
   104360 
   104361 /*
   104362 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
   104363 ** clause is seen as part of a foreign key definition.  The isDeferred
   104364 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
   104365 ** The behavior of the most recently created foreign key is adjusted
   104366 ** accordingly.
   104367 */
   104368 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
   104369 #ifndef SQLITE_OMIT_FOREIGN_KEY
   104370   Table *pTab;
   104371   FKey *pFKey;
   104372   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
   104373   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   104374   pFKey->isDeferred = (u8)isDeferred;
   104375 #endif
   104376 }
   104377 
   104378 /*
   104379 ** Generate code that will erase and refill index *pIdx.  This is
   104380 ** used to initialize a newly created index or to recompute the
   104381 ** content of an index in response to a REINDEX command.
   104382 **
   104383 ** if memRootPage is not negative, it means that the index is newly
   104384 ** created.  The register specified by memRootPage contains the
   104385 ** root page number of the index.  If memRootPage is negative, then
   104386 ** the index already exists and must be cleared before being refilled and
   104387 ** the root page number of the index is taken from pIndex->tnum.
   104388 */
   104389 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   104390   Table *pTab = pIndex->pTable;  /* The table that is indexed */
   104391   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
   104392   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
   104393   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
   104394   int addr1;                     /* Address of top of loop */
   104395   int addr2;                     /* Address to jump to for next iteration */
   104396   int tnum;                      /* Root page of index */
   104397   int iPartIdxLabel;             /* Jump to this label to skip a row */
   104398   Vdbe *v;                       /* Generate code into this virtual machine */
   104399   KeyInfo *pKey;                 /* KeyInfo for index */
   104400   int regRecord;                 /* Register holding assembled index record */
   104401   sqlite3 *db = pParse->db;      /* The database connection */
   104402   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   104403 
   104404 #ifndef SQLITE_OMIT_AUTHORIZATION
   104405   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
   104406       db->aDb[iDb].zDbSName ) ){
   104407     return;
   104408   }
   104409 #endif
   104410 
   104411   /* Require a write-lock on the table to perform this operation */
   104412   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   104413 
   104414   v = sqlite3GetVdbe(pParse);
   104415   if( v==0 ) return;
   104416   if( memRootPage>=0 ){
   104417     tnum = memRootPage;
   104418   }else{
   104419     tnum = pIndex->tnum;
   104420   }
   104421   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
   104422   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
   104423 
   104424   /* Open the sorter cursor if we are to use one. */
   104425   iSorter = pParse->nTab++;
   104426   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
   104427                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
   104428 
   104429   /* Open the table. Loop through all rows of the table, inserting index
   104430   ** records into the sorter. */
   104431   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   104432   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
   104433   regRecord = sqlite3GetTempReg(pParse);
   104434 
   104435   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
   104436   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
   104437   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
   104438   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
   104439   sqlite3VdbeJumpHere(v, addr1);
   104440   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
   104441   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
   104442                     (char *)pKey, P4_KEYINFO);
   104443   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
   104444 
   104445   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
   104446   if( IsUniqueIndex(pIndex) ){
   104447     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
   104448     sqlite3VdbeGoto(v, j2);
   104449     addr2 = sqlite3VdbeCurrentAddr(v);
   104450     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
   104451                          pIndex->nKeyCol); VdbeCoverage(v);
   104452     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
   104453   }else{
   104454     addr2 = sqlite3VdbeCurrentAddr(v);
   104455   }
   104456   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
   104457   sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
   104458   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
   104459   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   104460   sqlite3ReleaseTempReg(pParse, regRecord);
   104461   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
   104462   sqlite3VdbeJumpHere(v, addr1);
   104463 
   104464   sqlite3VdbeAddOp1(v, OP_Close, iTab);
   104465   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
   104466   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
   104467 }
   104468 
   104469 /*
   104470 ** Allocate heap space to hold an Index object with nCol columns.
   104471 **
   104472 ** Increase the allocation size to provide an extra nExtra bytes
   104473 ** of 8-byte aligned space after the Index object and return a
   104474 ** pointer to this extra space in *ppExtra.
   104475 */
   104476 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
   104477   sqlite3 *db,         /* Database connection */
   104478   i16 nCol,            /* Total number of columns in the index */
   104479   int nExtra,          /* Number of bytes of extra space to alloc */
   104480   char **ppExtra       /* Pointer to the "extra" space */
   104481 ){
   104482   Index *p;            /* Allocated index object */
   104483   int nByte;           /* Bytes of space for Index object + arrays */
   104484 
   104485   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
   104486           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
   104487           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
   104488                  sizeof(i16)*nCol +            /* Index.aiColumn   */
   104489                  sizeof(u8)*nCol);             /* Index.aSortOrder */
   104490   p = sqlite3DbMallocZero(db, nByte + nExtra);
   104491   if( p ){
   104492     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
   104493     p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
   104494     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
   104495     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
   104496     p->aSortOrder = (u8*)pExtra;
   104497     p->nColumn = nCol;
   104498     p->nKeyCol = nCol - 1;
   104499     *ppExtra = ((char*)p) + nByte;
   104500   }
   104501   return p;
   104502 }
   104503 
   104504 /*
   104505 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
   104506 ** and pTblList is the name of the table that is to be indexed.  Both will
   104507 ** be NULL for a primary key or an index that is created to satisfy a
   104508 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
   104509 ** as the table to be indexed.  pParse->pNewTable is a table that is
   104510 ** currently being constructed by a CREATE TABLE statement.
   104511 **
   104512 ** pList is a list of columns to be indexed.  pList will be NULL if this
   104513 ** is a primary key or unique-constraint on the most recent column added
   104514 ** to the table currently under construction.
   104515 */
   104516 SQLITE_PRIVATE void sqlite3CreateIndex(
   104517   Parse *pParse,     /* All information about this parse */
   104518   Token *pName1,     /* First part of index name. May be NULL */
   104519   Token *pName2,     /* Second part of index name. May be NULL */
   104520   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
   104521   ExprList *pList,   /* A list of columns to be indexed */
   104522   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   104523   Token *pStart,     /* The CREATE token that begins this statement */
   104524   Expr *pPIWhere,    /* WHERE clause for partial indices */
   104525   int sortOrder,     /* Sort order of primary key when pList==NULL */
   104526   int ifNotExist,    /* Omit error if index already exists */
   104527   u8 idxType         /* The index type */
   104528 ){
   104529   Table *pTab = 0;     /* Table to be indexed */
   104530   Index *pIndex = 0;   /* The index to be created */
   104531   char *zName = 0;     /* Name of the index */
   104532   int nName;           /* Number of characters in zName */
   104533   int i, j;
   104534   DbFixer sFix;        /* For assigning database names to pTable */
   104535   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
   104536   sqlite3 *db = pParse->db;
   104537   Db *pDb;             /* The specific table containing the indexed database */
   104538   int iDb;             /* Index of the database that is being written */
   104539   Token *pName = 0;    /* Unqualified name of the index to create */
   104540   struct ExprList_item *pListItem; /* For looping over pList */
   104541   int nExtra = 0;                  /* Space allocated for zExtra[] */
   104542   int nExtraCol;                   /* Number of extra columns needed */
   104543   char *zExtra = 0;                /* Extra space after the Index object */
   104544   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
   104545 
   104546   if( db->mallocFailed || pParse->nErr>0 ){
   104547     goto exit_create_index;
   104548   }
   104549   if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
   104550     goto exit_create_index;
   104551   }
   104552   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   104553     goto exit_create_index;
   104554   }
   104555 
   104556   /*
   104557   ** Find the table that is to be indexed.  Return early if not found.
   104558   */
   104559   if( pTblName!=0 ){
   104560 
   104561     /* Use the two-part index name to determine the database
   104562     ** to search for the table. 'Fix' the table name to this db
   104563     ** before looking up the table.
   104564     */
   104565     assert( pName1 && pName2 );
   104566     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   104567     if( iDb<0 ) goto exit_create_index;
   104568     assert( pName && pName->z );
   104569 
   104570 #ifndef SQLITE_OMIT_TEMPDB
   104571     /* If the index name was unqualified, check if the table
   104572     ** is a temp table. If so, set the database to 1. Do not do this
   104573     ** if initialising a database schema.
   104574     */
   104575     if( !db->init.busy ){
   104576       pTab = sqlite3SrcListLookup(pParse, pTblName);
   104577       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   104578         iDb = 1;
   104579       }
   104580     }
   104581 #endif
   104582 
   104583     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
   104584     if( sqlite3FixSrcList(&sFix, pTblName) ){
   104585       /* Because the parser constructs pTblName from a single identifier,
   104586       ** sqlite3FixSrcList can never fail. */
   104587       assert(0);
   104588     }
   104589     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
   104590     assert( db->mallocFailed==0 || pTab==0 );
   104591     if( pTab==0 ) goto exit_create_index;
   104592     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
   104593       sqlite3ErrorMsg(pParse,
   104594            "cannot create a TEMP index on non-TEMP table \"%s\"",
   104595            pTab->zName);
   104596       goto exit_create_index;
   104597     }
   104598     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
   104599   }else{
   104600     assert( pName==0 );
   104601     assert( pStart==0 );
   104602     pTab = pParse->pNewTable;
   104603     if( !pTab ) goto exit_create_index;
   104604     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   104605   }
   104606   pDb = &db->aDb[iDb];
   104607 
   104608   assert( pTab!=0 );
   104609   assert( pParse->nErr==0 );
   104610   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   104611        && db->init.busy==0
   104612 #if SQLITE_USER_AUTHENTICATION
   104613        && sqlite3UserAuthTable(pTab->zName)==0
   104614 #endif
   104615        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
   104616     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
   104617     goto exit_create_index;
   104618   }
   104619 #ifndef SQLITE_OMIT_VIEW
   104620   if( pTab->pSelect ){
   104621     sqlite3ErrorMsg(pParse, "views may not be indexed");
   104622     goto exit_create_index;
   104623   }
   104624 #endif
   104625 #ifndef SQLITE_OMIT_VIRTUALTABLE
   104626   if( IsVirtual(pTab) ){
   104627     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
   104628     goto exit_create_index;
   104629   }
   104630 #endif
   104631 
   104632   /*
   104633   ** Find the name of the index.  Make sure there is not already another
   104634   ** index or table with the same name.
   104635   **
   104636   ** Exception:  If we are reading the names of permanent indices from the
   104637   ** sqlite_master table (because some other process changed the schema) and
   104638   ** one of the index names collides with the name of a temporary table or
   104639   ** index, then we will continue to process this index.
   104640   **
   104641   ** If pName==0 it means that we are
   104642   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
   104643   ** own name.
   104644   */
   104645   if( pName ){
   104646     zName = sqlite3NameFromToken(db, pName);
   104647     if( zName==0 ) goto exit_create_index;
   104648     assert( pName->z!=0 );
   104649     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   104650       goto exit_create_index;
   104651     }
   104652     if( !db->init.busy ){
   104653       if( sqlite3FindTable(db, zName, 0)!=0 ){
   104654         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
   104655         goto exit_create_index;
   104656       }
   104657     }
   104658     if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
   104659       if( !ifNotExist ){
   104660         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
   104661       }else{
   104662         assert( !db->init.busy );
   104663         sqlite3CodeVerifySchema(pParse, iDb);
   104664       }
   104665       goto exit_create_index;
   104666     }
   104667   }else{
   104668     int n;
   104669     Index *pLoop;
   104670     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
   104671     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
   104672     if( zName==0 ){
   104673       goto exit_create_index;
   104674     }
   104675 
   104676     /* Automatic index names generated from within sqlite3_declare_vtab()
   104677     ** must have names that are distinct from normal automatic index names.
   104678     ** The following statement converts "sqlite3_autoindex..." into
   104679     ** "sqlite3_butoindex..." in order to make the names distinct.
   104680     ** The "vtab_err.test" test demonstrates the need of this statement. */
   104681     if( IN_DECLARE_VTAB ) zName[7]++;
   104682   }
   104683 
   104684   /* Check for authorization to create an index.
   104685   */
   104686 #ifndef SQLITE_OMIT_AUTHORIZATION
   104687   {
   104688     const char *zDb = pDb->zDbSName;
   104689     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
   104690       goto exit_create_index;
   104691     }
   104692     i = SQLITE_CREATE_INDEX;
   104693     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
   104694     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
   104695       goto exit_create_index;
   104696     }
   104697   }
   104698 #endif
   104699 
   104700   /* If pList==0, it means this routine was called to make a primary
   104701   ** key out of the last column added to the table under construction.
   104702   ** So create a fake list to simulate this.
   104703   */
   104704   if( pList==0 ){
   104705     Token prevCol;
   104706     sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
   104707     pList = sqlite3ExprListAppend(pParse, 0,
   104708               sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
   104709     if( pList==0 ) goto exit_create_index;
   104710     assert( pList->nExpr==1 );
   104711     sqlite3ExprListSetSortOrder(pList, sortOrder);
   104712   }else{
   104713     sqlite3ExprListCheckLength(pParse, pList, "index");
   104714   }
   104715 
   104716   /* Figure out how many bytes of space are required to store explicitly
   104717   ** specified collation sequence names.
   104718   */
   104719   for(i=0; i<pList->nExpr; i++){
   104720     Expr *pExpr = pList->a[i].pExpr;
   104721     assert( pExpr!=0 );
   104722     if( pExpr->op==TK_COLLATE ){
   104723       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
   104724     }
   104725   }
   104726 
   104727   /*
   104728   ** Allocate the index structure.
   104729   */
   104730   nName = sqlite3Strlen30(zName);
   104731   nExtraCol = pPk ? pPk->nKeyCol : 1;
   104732   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
   104733                                       nName + nExtra + 1, &zExtra);
   104734   if( db->mallocFailed ){
   104735     goto exit_create_index;
   104736   }
   104737   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
   104738   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
   104739   pIndex->zName = zExtra;
   104740   zExtra += nName + 1;
   104741   memcpy(pIndex->zName, zName, nName+1);
   104742   pIndex->pTable = pTab;
   104743   pIndex->onError = (u8)onError;
   104744   pIndex->uniqNotNull = onError!=OE_None;
   104745   pIndex->idxType = idxType;
   104746   pIndex->pSchema = db->aDb[iDb].pSchema;
   104747   pIndex->nKeyCol = pList->nExpr;
   104748   if( pPIWhere ){
   104749     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
   104750     pIndex->pPartIdxWhere = pPIWhere;
   104751     pPIWhere = 0;
   104752   }
   104753   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   104754 
   104755   /* Check to see if we should honor DESC requests on index columns
   104756   */
   104757   if( pDb->pSchema->file_format>=4 ){
   104758     sortOrderMask = -1;   /* Honor DESC */
   104759   }else{
   104760     sortOrderMask = 0;    /* Ignore DESC */
   104761   }
   104762 
   104763   /* Analyze the list of expressions that form the terms of the index and
   104764   ** report any errors.  In the common case where the expression is exactly
   104765   ** a table column, store that column in aiColumn[].  For general expressions,
   104766   ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
   104767   **
   104768   ** TODO: Issue a warning if two or more columns of the index are identical.
   104769   ** TODO: Issue a warning if the table primary key is used as part of the
   104770   ** index key.
   104771   */
   104772   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
   104773     Expr *pCExpr;                  /* The i-th index expression */
   104774     int requestedSortOrder;        /* ASC or DESC on the i-th expression */
   104775     const char *zColl;             /* Collation sequence name */
   104776 
   104777     sqlite3StringToId(pListItem->pExpr);
   104778     sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
   104779     if( pParse->nErr ) goto exit_create_index;
   104780     pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
   104781     if( pCExpr->op!=TK_COLUMN ){
   104782       if( pTab==pParse->pNewTable ){
   104783         sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
   104784                                 "UNIQUE constraints");
   104785         goto exit_create_index;
   104786       }
   104787       if( pIndex->aColExpr==0 ){
   104788         ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
   104789         pIndex->aColExpr = pCopy;
   104790         if( !db->mallocFailed ){
   104791           assert( pCopy!=0 );
   104792           pListItem = &pCopy->a[i];
   104793         }
   104794       }
   104795       j = XN_EXPR;
   104796       pIndex->aiColumn[i] = XN_EXPR;
   104797       pIndex->uniqNotNull = 0;
   104798     }else{
   104799       j = pCExpr->iColumn;
   104800       assert( j<=0x7fff );
   104801       if( j<0 ){
   104802         j = pTab->iPKey;
   104803       }else if( pTab->aCol[j].notNull==0 ){
   104804         pIndex->uniqNotNull = 0;
   104805       }
   104806       pIndex->aiColumn[i] = (i16)j;
   104807     }
   104808     zColl = 0;
   104809     if( pListItem->pExpr->op==TK_COLLATE ){
   104810       int nColl;
   104811       zColl = pListItem->pExpr->u.zToken;
   104812       nColl = sqlite3Strlen30(zColl) + 1;
   104813       assert( nExtra>=nColl );
   104814       memcpy(zExtra, zColl, nColl);
   104815       zColl = zExtra;
   104816       zExtra += nColl;
   104817       nExtra -= nColl;
   104818     }else if( j>=0 ){
   104819       zColl = pTab->aCol[j].zColl;
   104820     }
   104821     if( !zColl ) zColl = sqlite3StrBINARY;
   104822     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
   104823       goto exit_create_index;
   104824     }
   104825     pIndex->azColl[i] = zColl;
   104826     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
   104827     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
   104828   }
   104829 
   104830   /* Append the table key to the end of the index.  For WITHOUT ROWID
   104831   ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
   104832   ** normal tables (when pPk==0) this will be the rowid.
   104833   */
   104834   if( pPk ){
   104835     for(j=0; j<pPk->nKeyCol; j++){
   104836       int x = pPk->aiColumn[j];
   104837       assert( x>=0 );
   104838       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
   104839         pIndex->nColumn--;
   104840       }else{
   104841         pIndex->aiColumn[i] = x;
   104842         pIndex->azColl[i] = pPk->azColl[j];
   104843         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
   104844         i++;
   104845       }
   104846     }
   104847     assert( i==pIndex->nColumn );
   104848   }else{
   104849     pIndex->aiColumn[i] = XN_ROWID;
   104850     pIndex->azColl[i] = sqlite3StrBINARY;
   104851   }
   104852   sqlite3DefaultRowEst(pIndex);
   104853   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
   104854 
   104855   /* If this index contains every column of its table, then mark
   104856   ** it as a covering index */
   104857   assert( HasRowid(pTab)
   104858       || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
   104859   if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
   104860     pIndex->isCovering = 1;
   104861     for(j=0; j<pTab->nCol; j++){
   104862       if( j==pTab->iPKey ) continue;
   104863       if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
   104864       pIndex->isCovering = 0;
   104865       break;
   104866     }
   104867   }
   104868 
   104869   if( pTab==pParse->pNewTable ){
   104870     /* This routine has been called to create an automatic index as a
   104871     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
   104872     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
   104873     ** i.e. one of:
   104874     **
   104875     ** CREATE TABLE t(x PRIMARY KEY, y);
   104876     ** CREATE TABLE t(x, y, UNIQUE(x, y));
   104877     **
   104878     ** Either way, check to see if the table already has such an index. If
   104879     ** so, don't bother creating this one. This only applies to
   104880     ** automatically created indices. Users can do as they wish with
   104881     ** explicit indices.
   104882     **
   104883     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
   104884     ** (and thus suppressing the second one) even if they have different
   104885     ** sort orders.
   104886     **
   104887     ** If there are different collating sequences or if the columns of
   104888     ** the constraint occur in different orders, then the constraints are
   104889     ** considered distinct and both result in separate indices.
   104890     */
   104891     Index *pIdx;
   104892     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   104893       int k;
   104894       assert( IsUniqueIndex(pIdx) );
   104895       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
   104896       assert( IsUniqueIndex(pIndex) );
   104897 
   104898       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
   104899       for(k=0; k<pIdx->nKeyCol; k++){
   104900         const char *z1;
   104901         const char *z2;
   104902         assert( pIdx->aiColumn[k]>=0 );
   104903         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
   104904         z1 = pIdx->azColl[k];
   104905         z2 = pIndex->azColl[k];
   104906         if( sqlite3StrICmp(z1, z2) ) break;
   104907       }
   104908       if( k==pIdx->nKeyCol ){
   104909         if( pIdx->onError!=pIndex->onError ){
   104910           /* This constraint creates the same index as a previous
   104911           ** constraint specified somewhere in the CREATE TABLE statement.
   104912           ** However the ON CONFLICT clauses are different. If both this
   104913           ** constraint and the previous equivalent constraint have explicit
   104914           ** ON CONFLICT clauses this is an error. Otherwise, use the
   104915           ** explicitly specified behavior for the index.
   104916           */
   104917           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
   104918             sqlite3ErrorMsg(pParse,
   104919                 "conflicting ON CONFLICT clauses specified", 0);
   104920           }
   104921           if( pIdx->onError==OE_Default ){
   104922             pIdx->onError = pIndex->onError;
   104923           }
   104924         }
   104925         if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
   104926         goto exit_create_index;
   104927       }
   104928     }
   104929   }
   104930 
   104931   /* Link the new Index structure to its table and to the other
   104932   ** in-memory database structures.
   104933   */
   104934   assert( pParse->nErr==0 );
   104935   if( db->init.busy ){
   104936     Index *p;
   104937     assert( !IN_DECLARE_VTAB );
   104938     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   104939     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
   104940                           pIndex->zName, pIndex);
   104941     if( p ){
   104942       assert( p==pIndex );  /* Malloc must have failed */
   104943       sqlite3OomFault(db);
   104944       goto exit_create_index;
   104945     }
   104946     db->mDbFlags |= DBFLAG_SchemaChange;
   104947     if( pTblName!=0 ){
   104948       pIndex->tnum = db->init.newTnum;
   104949     }
   104950   }
   104951 
   104952   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
   104953   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
   104954   ** emit code to allocate the index rootpage on disk and make an entry for
   104955   ** the index in the sqlite_master table and populate the index with
   104956   ** content.  But, do not do this if we are simply reading the sqlite_master
   104957   ** table to parse the schema, or if this index is the PRIMARY KEY index
   104958   ** of a WITHOUT ROWID table.
   104959   **
   104960   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
   104961   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
   104962   ** has just been created, it contains no data and the index initialization
   104963   ** step can be skipped.
   104964   */
   104965   else if( HasRowid(pTab) || pTblName!=0 ){
   104966     Vdbe *v;
   104967     char *zStmt;
   104968     int iMem = ++pParse->nMem;
   104969 
   104970     v = sqlite3GetVdbe(pParse);
   104971     if( v==0 ) goto exit_create_index;
   104972 
   104973     sqlite3BeginWriteOperation(pParse, 1, iDb);
   104974 
   104975     /* Create the rootpage for the index using CreateIndex. But before
   104976     ** doing so, code a Noop instruction and store its address in
   104977     ** Index.tnum. This is required in case this index is actually a
   104978     ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
   104979     ** that case the convertToWithoutRowidTable() routine will replace
   104980     ** the Noop with a Goto to jump over the VDBE code generated below. */
   104981     pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
   104982     sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
   104983 
   104984     /* Gather the complete text of the CREATE INDEX statement into
   104985     ** the zStmt variable
   104986     */
   104987     if( pStart ){
   104988       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
   104989       if( pName->z[n-1]==';' ) n--;
   104990       /* A named index with an explicit CREATE INDEX statement */
   104991       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
   104992         onError==OE_None ? "" : " UNIQUE", n, pName->z);
   104993     }else{
   104994       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
   104995       /* zStmt = sqlite3MPrintf(""); */
   104996       zStmt = 0;
   104997     }
   104998 
   104999     /* Add an entry in sqlite_master for this index
   105000     */
   105001     sqlite3NestedParse(pParse,
   105002         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
   105003         db->aDb[iDb].zDbSName, MASTER_NAME,
   105004         pIndex->zName,
   105005         pTab->zName,
   105006         iMem,
   105007         zStmt
   105008     );
   105009     sqlite3DbFree(db, zStmt);
   105010 
   105011     /* Fill the index with data and reparse the schema. Code an OP_Expire
   105012     ** to invalidate all pre-compiled statements.
   105013     */
   105014     if( pTblName ){
   105015       sqlite3RefillIndex(pParse, pIndex, iMem);
   105016       sqlite3ChangeCookie(pParse, iDb);
   105017       sqlite3VdbeAddParseSchemaOp(v, iDb,
   105018          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
   105019       sqlite3VdbeAddOp0(v, OP_Expire);
   105020     }
   105021 
   105022     sqlite3VdbeJumpHere(v, pIndex->tnum);
   105023   }
   105024 
   105025   /* When adding an index to the list of indices for a table, make
   105026   ** sure all indices labeled OE_Replace come after all those labeled
   105027   ** OE_Ignore.  This is necessary for the correct constraint check
   105028   ** processing (in sqlite3GenerateConstraintChecks()) as part of
   105029   ** UPDATE and INSERT statements.
   105030   */
   105031   if( db->init.busy || pTblName==0 ){
   105032     if( onError!=OE_Replace || pTab->pIndex==0
   105033          || pTab->pIndex->onError==OE_Replace){
   105034       pIndex->pNext = pTab->pIndex;
   105035       pTab->pIndex = pIndex;
   105036     }else{
   105037       Index *pOther = pTab->pIndex;
   105038       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
   105039         pOther = pOther->pNext;
   105040       }
   105041       pIndex->pNext = pOther->pNext;
   105042       pOther->pNext = pIndex;
   105043     }
   105044     pIndex = 0;
   105045   }
   105046 
   105047   /* Clean up before exiting */
   105048 exit_create_index:
   105049   if( pIndex ) freeIndex(db, pIndex);
   105050   sqlite3ExprDelete(db, pPIWhere);
   105051   sqlite3ExprListDelete(db, pList);
   105052   sqlite3SrcListDelete(db, pTblName);
   105053   sqlite3DbFree(db, zName);
   105054 }
   105055 
   105056 /*
   105057 ** Fill the Index.aiRowEst[] array with default information - information
   105058 ** to be used when we have not run the ANALYZE command.
   105059 **
   105060 ** aiRowEst[0] is supposed to contain the number of elements in the index.
   105061 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
   105062 ** number of rows in the table that match any particular value of the
   105063 ** first column of the index.  aiRowEst[2] is an estimate of the number
   105064 ** of rows that match any particular combination of the first 2 columns
   105065 ** of the index.  And so forth.  It must always be the case that
   105066 *
   105067 **           aiRowEst[N]<=aiRowEst[N-1]
   105068 **           aiRowEst[N]>=1
   105069 **
   105070 ** Apart from that, we have little to go on besides intuition as to
   105071 ** how aiRowEst[] should be initialized.  The numbers generated here
   105072 ** are based on typical values found in actual indices.
   105073 */
   105074 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   105075   /*                10,  9,  8,  7,  6 */
   105076   LogEst aVal[] = { 33, 32, 30, 28, 26 };
   105077   LogEst *a = pIdx->aiRowLogEst;
   105078   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
   105079   int i;
   105080 
   105081   /* Indexes with default row estimates should not have stat1 data */
   105082   assert( !pIdx->hasStat1 );
   105083 
   105084   /* Set the first entry (number of rows in the index) to the estimated
   105085   ** number of rows in the table, or half the number of rows in the table
   105086   ** for a partial index.   But do not let the estimate drop below 10. */
   105087   a[0] = pIdx->pTable->nRowLogEst;
   105088   if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
   105089   if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
   105090 
   105091   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
   105092   ** 6 and each subsequent value (if any) is 5.  */
   105093   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
   105094   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
   105095     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
   105096   }
   105097 
   105098   assert( 0==sqlite3LogEst(1) );
   105099   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
   105100 }
   105101 
   105102 /*
   105103 ** This routine will drop an existing named index.  This routine
   105104 ** implements the DROP INDEX statement.
   105105 */
   105106 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
   105107   Index *pIndex;
   105108   Vdbe *v;
   105109   sqlite3 *db = pParse->db;
   105110   int iDb;
   105111 
   105112   assert( pParse->nErr==0 );   /* Never called with prior errors */
   105113   if( db->mallocFailed ){
   105114     goto exit_drop_index;
   105115   }
   105116   assert( pName->nSrc==1 );
   105117   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   105118     goto exit_drop_index;
   105119   }
   105120   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   105121   if( pIndex==0 ){
   105122     if( !ifExists ){
   105123       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
   105124     }else{
   105125       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   105126     }
   105127     pParse->checkSchema = 1;
   105128     goto exit_drop_index;
   105129   }
   105130   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
   105131     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
   105132       "or PRIMARY KEY constraint cannot be dropped", 0);
   105133     goto exit_drop_index;
   105134   }
   105135   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   105136 #ifndef SQLITE_OMIT_AUTHORIZATION
   105137   {
   105138     int code = SQLITE_DROP_INDEX;
   105139     Table *pTab = pIndex->pTable;
   105140     const char *zDb = db->aDb[iDb].zDbSName;
   105141     const char *zTab = SCHEMA_TABLE(iDb);
   105142     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   105143       goto exit_drop_index;
   105144     }
   105145     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
   105146     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
   105147       goto exit_drop_index;
   105148     }
   105149   }
   105150 #endif
   105151 
   105152   /* Generate code to remove the index and from the master table */
   105153   v = sqlite3GetVdbe(pParse);
   105154   if( v ){
   105155     sqlite3BeginWriteOperation(pParse, 1, iDb);
   105156     sqlite3NestedParse(pParse,
   105157        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
   105158        db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
   105159     );
   105160     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
   105161     sqlite3ChangeCookie(pParse, iDb);
   105162     destroyRootPage(pParse, pIndex->tnum, iDb);
   105163     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
   105164   }
   105165 
   105166 exit_drop_index:
   105167   sqlite3SrcListDelete(db, pName);
   105168 }
   105169 
   105170 /*
   105171 ** pArray is a pointer to an array of objects. Each object in the
   105172 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
   105173 ** to extend the array so that there is space for a new object at the end.
   105174 **
   105175 ** When this function is called, *pnEntry contains the current size of
   105176 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
   105177 ** in total).
   105178 **
   105179 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
   105180 ** space allocated for the new object is zeroed, *pnEntry updated to
   105181 ** reflect the new size of the array and a pointer to the new allocation
   105182 ** returned. *pIdx is set to the index of the new array entry in this case.
   105183 **
   105184 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
   105185 ** unchanged and a copy of pArray returned.
   105186 */
   105187 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
   105188   sqlite3 *db,      /* Connection to notify of malloc failures */
   105189   void *pArray,     /* Array of objects.  Might be reallocated */
   105190   int szEntry,      /* Size of each object in the array */
   105191   int *pnEntry,     /* Number of objects currently in use */
   105192   int *pIdx         /* Write the index of a new slot here */
   105193 ){
   105194   char *z;
   105195   int n = *pnEntry;
   105196   if( (n & (n-1))==0 ){
   105197     int sz = (n==0) ? 1 : 2*n;
   105198     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
   105199     if( pNew==0 ){
   105200       *pIdx = -1;
   105201       return pArray;
   105202     }
   105203     pArray = pNew;
   105204   }
   105205   z = (char*)pArray;
   105206   memset(&z[n * szEntry], 0, szEntry);
   105207   *pIdx = n;
   105208   ++*pnEntry;
   105209   return pArray;
   105210 }
   105211 
   105212 /*
   105213 ** Append a new element to the given IdList.  Create a new IdList if
   105214 ** need be.
   105215 **
   105216 ** A new IdList is returned, or NULL if malloc() fails.
   105217 */
   105218 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
   105219   int i;
   105220   if( pList==0 ){
   105221     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
   105222     if( pList==0 ) return 0;
   105223   }
   105224   pList->a = sqlite3ArrayAllocate(
   105225       db,
   105226       pList->a,
   105227       sizeof(pList->a[0]),
   105228       &pList->nId,
   105229       &i
   105230   );
   105231   if( i<0 ){
   105232     sqlite3IdListDelete(db, pList);
   105233     return 0;
   105234   }
   105235   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
   105236   return pList;
   105237 }
   105238 
   105239 /*
   105240 ** Delete an IdList.
   105241 */
   105242 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
   105243   int i;
   105244   if( pList==0 ) return;
   105245   for(i=0; i<pList->nId; i++){
   105246     sqlite3DbFree(db, pList->a[i].zName);
   105247   }
   105248   sqlite3DbFree(db, pList->a);
   105249   sqlite3DbFreeNN(db, pList);
   105250 }
   105251 
   105252 /*
   105253 ** Return the index in pList of the identifier named zId.  Return -1
   105254 ** if not found.
   105255 */
   105256 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
   105257   int i;
   105258   if( pList==0 ) return -1;
   105259   for(i=0; i<pList->nId; i++){
   105260     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
   105261   }
   105262   return -1;
   105263 }
   105264 
   105265 /*
   105266 ** Expand the space allocated for the given SrcList object by
   105267 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
   105268 ** New slots are zeroed.
   105269 **
   105270 ** For example, suppose a SrcList initially contains two entries: A,B.
   105271 ** To append 3 new entries onto the end, do this:
   105272 **
   105273 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
   105274 **
   105275 ** After the call above it would contain:  A, B, nil, nil, nil.
   105276 ** If the iStart argument had been 1 instead of 2, then the result
   105277 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
   105278 ** the iStart value would be 0.  The result then would
   105279 ** be: nil, nil, nil, A, B.
   105280 **
   105281 ** If a memory allocation fails the SrcList is unchanged.  The
   105282 ** db->mallocFailed flag will be set to true.
   105283 */
   105284 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
   105285   sqlite3 *db,       /* Database connection to notify of OOM errors */
   105286   SrcList *pSrc,     /* The SrcList to be enlarged */
   105287   int nExtra,        /* Number of new slots to add to pSrc->a[] */
   105288   int iStart         /* Index in pSrc->a[] of first new slot */
   105289 ){
   105290   int i;
   105291 
   105292   /* Sanity checking on calling parameters */
   105293   assert( iStart>=0 );
   105294   assert( nExtra>=1 );
   105295   assert( pSrc!=0 );
   105296   assert( iStart<=pSrc->nSrc );
   105297 
   105298   /* Allocate additional space if needed */
   105299   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
   105300     SrcList *pNew;
   105301     int nAlloc = pSrc->nSrc*2+nExtra;
   105302     int nGot;
   105303     pNew = sqlite3DbRealloc(db, pSrc,
   105304                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
   105305     if( pNew==0 ){
   105306       assert( db->mallocFailed );
   105307       return pSrc;
   105308     }
   105309     pSrc = pNew;
   105310     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
   105311     pSrc->nAlloc = nGot;
   105312   }
   105313 
   105314   /* Move existing slots that come after the newly inserted slots
   105315   ** out of the way */
   105316   for(i=pSrc->nSrc-1; i>=iStart; i--){
   105317     pSrc->a[i+nExtra] = pSrc->a[i];
   105318   }
   105319   pSrc->nSrc += nExtra;
   105320 
   105321   /* Zero the newly allocated slots */
   105322   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
   105323   for(i=iStart; i<iStart+nExtra; i++){
   105324     pSrc->a[i].iCursor = -1;
   105325   }
   105326 
   105327   /* Return a pointer to the enlarged SrcList */
   105328   return pSrc;
   105329 }
   105330 
   105331 
   105332 /*
   105333 ** Append a new table name to the given SrcList.  Create a new SrcList if
   105334 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
   105335 **
   105336 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
   105337 ** SrcList might be the same as the SrcList that was input or it might be
   105338 ** a new one.  If an OOM error does occurs, then the prior value of pList
   105339 ** that is input to this routine is automatically freed.
   105340 **
   105341 ** If pDatabase is not null, it means that the table has an optional
   105342 ** database name prefix.  Like this:  "database.table".  The pDatabase
   105343 ** points to the table name and the pTable points to the database name.
   105344 ** The SrcList.a[].zName field is filled with the table name which might
   105345 ** come from pTable (if pDatabase is NULL) or from pDatabase.
   105346 ** SrcList.a[].zDatabase is filled with the database name from pTable,
   105347 ** or with NULL if no database is specified.
   105348 **
   105349 ** In other words, if call like this:
   105350 **
   105351 **         sqlite3SrcListAppend(D,A,B,0);
   105352 **
   105353 ** Then B is a table name and the database name is unspecified.  If called
   105354 ** like this:
   105355 **
   105356 **         sqlite3SrcListAppend(D,A,B,C);
   105357 **
   105358 ** Then C is the table name and B is the database name.  If C is defined
   105359 ** then so is B.  In other words, we never have a case where:
   105360 **
   105361 **         sqlite3SrcListAppend(D,A,0,C);
   105362 **
   105363 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
   105364 ** before being added to the SrcList.
   105365 */
   105366 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
   105367   sqlite3 *db,        /* Connection to notify of malloc failures */
   105368   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
   105369   Token *pTable,      /* Table to append */
   105370   Token *pDatabase    /* Database of the table */
   105371 ){
   105372   struct SrcList_item *pItem;
   105373   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   105374   assert( db!=0 );
   105375   if( pList==0 ){
   105376     pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
   105377     if( pList==0 ) return 0;
   105378     pList->nAlloc = 1;
   105379     pList->nSrc = 1;
   105380     memset(&pList->a[0], 0, sizeof(pList->a[0]));
   105381     pList->a[0].iCursor = -1;
   105382   }else{
   105383     pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
   105384   }
   105385   if( db->mallocFailed ){
   105386     sqlite3SrcListDelete(db, pList);
   105387     return 0;
   105388   }
   105389   pItem = &pList->a[pList->nSrc-1];
   105390   if( pDatabase && pDatabase->z==0 ){
   105391     pDatabase = 0;
   105392   }
   105393   if( pDatabase ){
   105394     pItem->zName = sqlite3NameFromToken(db, pDatabase);
   105395     pItem->zDatabase = sqlite3NameFromToken(db, pTable);
   105396   }else{
   105397     pItem->zName = sqlite3NameFromToken(db, pTable);
   105398     pItem->zDatabase = 0;
   105399   }
   105400   return pList;
   105401 }
   105402 
   105403 /*
   105404 ** Assign VdbeCursor index numbers to all tables in a SrcList
   105405 */
   105406 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   105407   int i;
   105408   struct SrcList_item *pItem;
   105409   assert(pList || pParse->db->mallocFailed );
   105410   if( pList ){
   105411     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   105412       if( pItem->iCursor>=0 ) break;
   105413       pItem->iCursor = pParse->nTab++;
   105414       if( pItem->pSelect ){
   105415         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
   105416       }
   105417     }
   105418   }
   105419 }
   105420 
   105421 /*
   105422 ** Delete an entire SrcList including all its substructure.
   105423 */
   105424 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   105425   int i;
   105426   struct SrcList_item *pItem;
   105427   if( pList==0 ) return;
   105428   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
   105429     sqlite3DbFree(db, pItem->zDatabase);
   105430     sqlite3DbFree(db, pItem->zName);
   105431     sqlite3DbFree(db, pItem->zAlias);
   105432     if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
   105433     if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
   105434     sqlite3DeleteTable(db, pItem->pTab);
   105435     sqlite3SelectDelete(db, pItem->pSelect);
   105436     sqlite3ExprDelete(db, pItem->pOn);
   105437     sqlite3IdListDelete(db, pItem->pUsing);
   105438   }
   105439   sqlite3DbFreeNN(db, pList);
   105440 }
   105441 
   105442 /*
   105443 ** This routine is called by the parser to add a new term to the
   105444 ** end of a growing FROM clause.  The "p" parameter is the part of
   105445 ** the FROM clause that has already been constructed.  "p" is NULL
   105446 ** if this is the first term of the FROM clause.  pTable and pDatabase
   105447 ** are the name of the table and database named in the FROM clause term.
   105448 ** pDatabase is NULL if the database name qualifier is missing - the
   105449 ** usual case.  If the term has an alias, then pAlias points to the
   105450 ** alias token.  If the term is a subquery, then pSubquery is the
   105451 ** SELECT statement that the subquery encodes.  The pTable and
   105452 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
   105453 ** parameters are the content of the ON and USING clauses.
   105454 **
   105455 ** Return a new SrcList which encodes is the FROM with the new
   105456 ** term added.
   105457 */
   105458 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   105459   Parse *pParse,          /* Parsing context */
   105460   SrcList *p,             /* The left part of the FROM clause already seen */
   105461   Token *pTable,          /* Name of the table to add to the FROM clause */
   105462   Token *pDatabase,       /* Name of the database containing pTable */
   105463   Token *pAlias,          /* The right-hand side of the AS subexpression */
   105464   Select *pSubquery,      /* A subquery used in place of a table name */
   105465   Expr *pOn,              /* The ON clause of a join */
   105466   IdList *pUsing          /* The USING clause of a join */
   105467 ){
   105468   struct SrcList_item *pItem;
   105469   sqlite3 *db = pParse->db;
   105470   if( !p && (pOn || pUsing) ){
   105471     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
   105472       (pOn ? "ON" : "USING")
   105473     );
   105474     goto append_from_error;
   105475   }
   105476   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
   105477   if( p==0 ){
   105478     goto append_from_error;
   105479   }
   105480   assert( p->nSrc>0 );
   105481   pItem = &p->a[p->nSrc-1];
   105482   assert( pAlias!=0 );
   105483   if( pAlias->n ){
   105484     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
   105485   }
   105486   pItem->pSelect = pSubquery;
   105487   pItem->pOn = pOn;
   105488   pItem->pUsing = pUsing;
   105489   return p;
   105490 
   105491  append_from_error:
   105492   assert( p==0 );
   105493   sqlite3ExprDelete(db, pOn);
   105494   sqlite3IdListDelete(db, pUsing);
   105495   sqlite3SelectDelete(db, pSubquery);
   105496   return 0;
   105497 }
   105498 
   105499 /*
   105500 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
   105501 ** element of the source-list passed as the second argument.
   105502 */
   105503 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   105504   assert( pIndexedBy!=0 );
   105505   if( p && pIndexedBy->n>0 ){
   105506     struct SrcList_item *pItem;
   105507     assert( p->nSrc>0 );
   105508     pItem = &p->a[p->nSrc-1];
   105509     assert( pItem->fg.notIndexed==0 );
   105510     assert( pItem->fg.isIndexedBy==0 );
   105511     assert( pItem->fg.isTabFunc==0 );
   105512     if( pIndexedBy->n==1 && !pIndexedBy->z ){
   105513       /* A "NOT INDEXED" clause was supplied. See parse.y
   105514       ** construct "indexed_opt" for details. */
   105515       pItem->fg.notIndexed = 1;
   105516     }else{
   105517       pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
   105518       pItem->fg.isIndexedBy = 1;
   105519     }
   105520   }
   105521 }
   105522 
   105523 /*
   105524 ** Add the list of function arguments to the SrcList entry for a
   105525 ** table-valued-function.
   105526 */
   105527 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
   105528   if( p ){
   105529     struct SrcList_item *pItem = &p->a[p->nSrc-1];
   105530     assert( pItem->fg.notIndexed==0 );
   105531     assert( pItem->fg.isIndexedBy==0 );
   105532     assert( pItem->fg.isTabFunc==0 );
   105533     pItem->u1.pFuncArg = pList;
   105534     pItem->fg.isTabFunc = 1;
   105535   }else{
   105536     sqlite3ExprListDelete(pParse->db, pList);
   105537   }
   105538 }
   105539 
   105540 /*
   105541 ** When building up a FROM clause in the parser, the join operator
   105542 ** is initially attached to the left operand.  But the code generator
   105543 ** expects the join operator to be on the right operand.  This routine
   105544 ** Shifts all join operators from left to right for an entire FROM
   105545 ** clause.
   105546 **
   105547 ** Example: Suppose the join is like this:
   105548 **
   105549 **           A natural cross join B
   105550 **
   105551 ** The operator is "natural cross join".  The A and B operands are stored
   105552 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
   105553 ** operator with A.  This routine shifts that operator over to B.
   105554 */
   105555 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
   105556   if( p ){
   105557     int i;
   105558     for(i=p->nSrc-1; i>0; i--){
   105559       p->a[i].fg.jointype = p->a[i-1].fg.jointype;
   105560     }
   105561     p->a[0].fg.jointype = 0;
   105562   }
   105563 }
   105564 
   105565 /*
   105566 ** Generate VDBE code for a BEGIN statement.
   105567 */
   105568 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   105569   sqlite3 *db;
   105570   Vdbe *v;
   105571   int i;
   105572 
   105573   assert( pParse!=0 );
   105574   db = pParse->db;
   105575   assert( db!=0 );
   105576   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
   105577     return;
   105578   }
   105579   v = sqlite3GetVdbe(pParse);
   105580   if( !v ) return;
   105581   if( type!=TK_DEFERRED ){
   105582     for(i=0; i<db->nDb; i++){
   105583       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
   105584       sqlite3VdbeUsesBtree(v, i);
   105585     }
   105586   }
   105587   sqlite3VdbeAddOp0(v, OP_AutoCommit);
   105588 }
   105589 
   105590 /*
   105591 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
   105592 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
   105593 ** code is generated for a COMMIT.
   105594 */
   105595 SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
   105596   Vdbe *v;
   105597   int isRollback;
   105598 
   105599   assert( pParse!=0 );
   105600   assert( pParse->db!=0 );
   105601   assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
   105602   isRollback = eType==TK_ROLLBACK;
   105603   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
   105604        isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
   105605     return;
   105606   }
   105607   v = sqlite3GetVdbe(pParse);
   105608   if( v ){
   105609     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
   105610   }
   105611 }
   105612 
   105613 /*
   105614 ** This function is called by the parser when it parses a command to create,
   105615 ** release or rollback an SQL savepoint.
   105616 */
   105617 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   105618   char *zName = sqlite3NameFromToken(pParse->db, pName);
   105619   if( zName ){
   105620     Vdbe *v = sqlite3GetVdbe(pParse);
   105621 #ifndef SQLITE_OMIT_AUTHORIZATION
   105622     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
   105623     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
   105624 #endif
   105625     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
   105626       sqlite3DbFree(pParse->db, zName);
   105627       return;
   105628     }
   105629     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
   105630   }
   105631 }
   105632 
   105633 /*
   105634 ** Make sure the TEMP database is open and available for use.  Return
   105635 ** the number of errors.  Leave any error messages in the pParse structure.
   105636 */
   105637 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   105638   sqlite3 *db = pParse->db;
   105639   if( db->aDb[1].pBt==0 && !pParse->explain ){
   105640     int rc;
   105641     Btree *pBt;
   105642     static const int flags =
   105643           SQLITE_OPEN_READWRITE |
   105644           SQLITE_OPEN_CREATE |
   105645           SQLITE_OPEN_EXCLUSIVE |
   105646           SQLITE_OPEN_DELETEONCLOSE |
   105647           SQLITE_OPEN_TEMP_DB;
   105648 
   105649     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
   105650     if( rc!=SQLITE_OK ){
   105651       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
   105652         "file for storing temporary tables");
   105653       pParse->rc = rc;
   105654       return 1;
   105655     }
   105656     db->aDb[1].pBt = pBt;
   105657     assert( db->aDb[1].pSchema );
   105658     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   105659       sqlite3OomFault(db);
   105660       return 1;
   105661     }
   105662   }
   105663   return 0;
   105664 }
   105665 
   105666 /*
   105667 ** Record the fact that the schema cookie will need to be verified
   105668 ** for database iDb.  The code to actually verify the schema cookie
   105669 ** will occur at the end of the top-level VDBE and will be generated
   105670 ** later, by sqlite3FinishCoding().
   105671 */
   105672 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
   105673   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   105674 
   105675   assert( iDb>=0 && iDb<pParse->db->nDb );
   105676   assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
   105677   assert( iDb<SQLITE_MAX_ATTACHED+2 );
   105678   assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
   105679   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
   105680     DbMaskSet(pToplevel->cookieMask, iDb);
   105681     if( !OMIT_TEMPDB && iDb==1 ){
   105682       sqlite3OpenTempDatabase(pToplevel);
   105683     }
   105684   }
   105685 }
   105686 
   105687 /*
   105688 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
   105689 ** attached database. Otherwise, invoke it for the database named zDb only.
   105690 */
   105691 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
   105692   sqlite3 *db = pParse->db;
   105693   int i;
   105694   for(i=0; i<db->nDb; i++){
   105695     Db *pDb = &db->aDb[i];
   105696     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
   105697       sqlite3CodeVerifySchema(pParse, i);
   105698     }
   105699   }
   105700 }
   105701 
   105702 /*
   105703 ** Generate VDBE code that prepares for doing an operation that
   105704 ** might change the database.
   105705 **
   105706 ** This routine starts a new transaction if we are not already within
   105707 ** a transaction.  If we are already within a transaction, then a checkpoint
   105708 ** is set if the setStatement parameter is true.  A checkpoint should
   105709 ** be set for operations that might fail (due to a constraint) part of
   105710 ** the way through and which will need to undo some writes without having to
   105711 ** rollback the whole transaction.  For operations where all constraints
   105712 ** can be checked before any changes are made to the database, it is never
   105713 ** necessary to undo a write and the checkpoint should not be set.
   105714 */
   105715 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   105716   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   105717   sqlite3CodeVerifySchema(pParse, iDb);
   105718   DbMaskSet(pToplevel->writeMask, iDb);
   105719   pToplevel->isMultiWrite |= setStatement;
   105720 }
   105721 
   105722 /*
   105723 ** Indicate that the statement currently under construction might write
   105724 ** more than one entry (example: deleting one row then inserting another,
   105725 ** inserting multiple rows in a table, or inserting a row and index entries.)
   105726 ** If an abort occurs after some of these writes have completed, then it will
   105727 ** be necessary to undo the completed writes.
   105728 */
   105729 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   105730   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   105731   pToplevel->isMultiWrite = 1;
   105732 }
   105733 
   105734 /*
   105735 ** The code generator calls this routine if is discovers that it is
   105736 ** possible to abort a statement prior to completion.  In order to
   105737 ** perform this abort without corrupting the database, we need to make
   105738 ** sure that the statement is protected by a statement transaction.
   105739 **
   105740 ** Technically, we only need to set the mayAbort flag if the
   105741 ** isMultiWrite flag was previously set.  There is a time dependency
   105742 ** such that the abort must occur after the multiwrite.  This makes
   105743 ** some statements involving the REPLACE conflict resolution algorithm
   105744 ** go a little faster.  But taking advantage of this time dependency
   105745 ** makes it more difficult to prove that the code is correct (in
   105746 ** particular, it prevents us from writing an effective
   105747 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
   105748 ** to take the safe route and skip the optimization.
   105749 */
   105750 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
   105751   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   105752   pToplevel->mayAbort = 1;
   105753 }
   105754 
   105755 /*
   105756 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
   105757 ** error. The onError parameter determines which (if any) of the statement
   105758 ** and/or current transaction is rolled back.
   105759 */
   105760 SQLITE_PRIVATE void sqlite3HaltConstraint(
   105761   Parse *pParse,    /* Parsing context */
   105762   int errCode,      /* extended error code */
   105763   int onError,      /* Constraint type */
   105764   char *p4,         /* Error message */
   105765   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
   105766   u8 p5Errmsg       /* P5_ErrMsg type */
   105767 ){
   105768   Vdbe *v = sqlite3GetVdbe(pParse);
   105769   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
   105770   if( onError==OE_Abort ){
   105771     sqlite3MayAbort(pParse);
   105772   }
   105773   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
   105774   sqlite3VdbeChangeP5(v, p5Errmsg);
   105775 }
   105776 
   105777 /*
   105778 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
   105779 */
   105780 SQLITE_PRIVATE void sqlite3UniqueConstraint(
   105781   Parse *pParse,    /* Parsing context */
   105782   int onError,      /* Constraint type */
   105783   Index *pIdx       /* The index that triggers the constraint */
   105784 ){
   105785   char *zErr;
   105786   int j;
   105787   StrAccum errMsg;
   105788   Table *pTab = pIdx->pTable;
   105789 
   105790   sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
   105791   if( pIdx->aColExpr ){
   105792     sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
   105793   }else{
   105794     for(j=0; j<pIdx->nKeyCol; j++){
   105795       char *zCol;
   105796       assert( pIdx->aiColumn[j]>=0 );
   105797       zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
   105798       if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
   105799       sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
   105800       sqlite3StrAccumAppend(&errMsg, ".", 1);
   105801       sqlite3StrAccumAppendAll(&errMsg, zCol);
   105802     }
   105803   }
   105804   zErr = sqlite3StrAccumFinish(&errMsg);
   105805   sqlite3HaltConstraint(pParse,
   105806     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
   105807                             : SQLITE_CONSTRAINT_UNIQUE,
   105808     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
   105809 }
   105810 
   105811 
   105812 /*
   105813 ** Code an OP_Halt due to non-unique rowid.
   105814 */
   105815 SQLITE_PRIVATE void sqlite3RowidConstraint(
   105816   Parse *pParse,    /* Parsing context */
   105817   int onError,      /* Conflict resolution algorithm */
   105818   Table *pTab       /* The table with the non-unique rowid */
   105819 ){
   105820   char *zMsg;
   105821   int rc;
   105822   if( pTab->iPKey>=0 ){
   105823     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
   105824                           pTab->aCol[pTab->iPKey].zName);
   105825     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
   105826   }else{
   105827     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
   105828     rc = SQLITE_CONSTRAINT_ROWID;
   105829   }
   105830   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
   105831                         P5_ConstraintUnique);
   105832 }
   105833 
   105834 /*
   105835 ** Check to see if pIndex uses the collating sequence pColl.  Return
   105836 ** true if it does and false if it does not.
   105837 */
   105838 #ifndef SQLITE_OMIT_REINDEX
   105839 static int collationMatch(const char *zColl, Index *pIndex){
   105840   int i;
   105841   assert( zColl!=0 );
   105842   for(i=0; i<pIndex->nColumn; i++){
   105843     const char *z = pIndex->azColl[i];
   105844     assert( z!=0 || pIndex->aiColumn[i]<0 );
   105845     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
   105846       return 1;
   105847     }
   105848   }
   105849   return 0;
   105850 }
   105851 #endif
   105852 
   105853 /*
   105854 ** Recompute all indices of pTab that use the collating sequence pColl.
   105855 ** If pColl==0 then recompute all indices of pTab.
   105856 */
   105857 #ifndef SQLITE_OMIT_REINDEX
   105858 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
   105859   Index *pIndex;              /* An index associated with pTab */
   105860 
   105861   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   105862     if( zColl==0 || collationMatch(zColl, pIndex) ){
   105863       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   105864       sqlite3BeginWriteOperation(pParse, 0, iDb);
   105865       sqlite3RefillIndex(pParse, pIndex, -1);
   105866     }
   105867   }
   105868 }
   105869 #endif
   105870 
   105871 /*
   105872 ** Recompute all indices of all tables in all databases where the
   105873 ** indices use the collating sequence pColl.  If pColl==0 then recompute
   105874 ** all indices everywhere.
   105875 */
   105876 #ifndef SQLITE_OMIT_REINDEX
   105877 static void reindexDatabases(Parse *pParse, char const *zColl){
   105878   Db *pDb;                    /* A single database */
   105879   int iDb;                    /* The database index number */
   105880   sqlite3 *db = pParse->db;   /* The database connection */
   105881   HashElem *k;                /* For looping over tables in pDb */
   105882   Table *pTab;                /* A table in the database */
   105883 
   105884   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
   105885   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   105886     assert( pDb!=0 );
   105887     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   105888       pTab = (Table*)sqliteHashData(k);
   105889       reindexTable(pParse, pTab, zColl);
   105890     }
   105891   }
   105892 }
   105893 #endif
   105894 
   105895 /*
   105896 ** Generate code for the REINDEX command.
   105897 **
   105898 **        REINDEX                            -- 1
   105899 **        REINDEX  <collation>               -- 2
   105900 **        REINDEX  ?<database>.?<tablename>  -- 3
   105901 **        REINDEX  ?<database>.?<indexname>  -- 4
   105902 **
   105903 ** Form 1 causes all indices in all attached databases to be rebuilt.
   105904 ** Form 2 rebuilds all indices in all databases that use the named
   105905 ** collating function.  Forms 3 and 4 rebuild the named index or all
   105906 ** indices associated with the named table.
   105907 */
   105908 #ifndef SQLITE_OMIT_REINDEX
   105909 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
   105910   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
   105911   char *z;                    /* Name of a table or index */
   105912   const char *zDb;            /* Name of the database */
   105913   Table *pTab;                /* A table in the database */
   105914   Index *pIndex;              /* An index associated with pTab */
   105915   int iDb;                    /* The database index number */
   105916   sqlite3 *db = pParse->db;   /* The database connection */
   105917   Token *pObjName;            /* Name of the table or index to be reindexed */
   105918 
   105919   /* Read the database schema. If an error occurs, leave an error message
   105920   ** and code in pParse and return NULL. */
   105921   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   105922     return;
   105923   }
   105924 
   105925   if( pName1==0 ){
   105926     reindexDatabases(pParse, 0);
   105927     return;
   105928   }else if( NEVER(pName2==0) || pName2->z==0 ){
   105929     char *zColl;
   105930     assert( pName1->z );
   105931     zColl = sqlite3NameFromToken(pParse->db, pName1);
   105932     if( !zColl ) return;
   105933     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   105934     if( pColl ){
   105935       reindexDatabases(pParse, zColl);
   105936       sqlite3DbFree(db, zColl);
   105937       return;
   105938     }
   105939     sqlite3DbFree(db, zColl);
   105940   }
   105941   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
   105942   if( iDb<0 ) return;
   105943   z = sqlite3NameFromToken(db, pObjName);
   105944   if( z==0 ) return;
   105945   zDb = db->aDb[iDb].zDbSName;
   105946   pTab = sqlite3FindTable(db, z, zDb);
   105947   if( pTab ){
   105948     reindexTable(pParse, pTab, 0);
   105949     sqlite3DbFree(db, z);
   105950     return;
   105951   }
   105952   pIndex = sqlite3FindIndex(db, z, zDb);
   105953   sqlite3DbFree(db, z);
   105954   if( pIndex ){
   105955     sqlite3BeginWriteOperation(pParse, 0, iDb);
   105956     sqlite3RefillIndex(pParse, pIndex, -1);
   105957     return;
   105958   }
   105959   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
   105960 }
   105961 #endif
   105962 
   105963 /*
   105964 ** Return a KeyInfo structure that is appropriate for the given Index.
   105965 **
   105966 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
   105967 ** when it has finished using it.
   105968 */
   105969 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
   105970   int i;
   105971   int nCol = pIdx->nColumn;
   105972   int nKey = pIdx->nKeyCol;
   105973   KeyInfo *pKey;
   105974   if( pParse->nErr ) return 0;
   105975   if( pIdx->uniqNotNull ){
   105976     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
   105977   }else{
   105978     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
   105979   }
   105980   if( pKey ){
   105981     assert( sqlite3KeyInfoIsWriteable(pKey) );
   105982     for(i=0; i<nCol; i++){
   105983       const char *zColl = pIdx->azColl[i];
   105984       pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
   105985                         sqlite3LocateCollSeq(pParse, zColl);
   105986       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
   105987     }
   105988     if( pParse->nErr ){
   105989       assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
   105990       if( pIdx->bNoQuery==0 ){
   105991         /* Deactivate the index because it contains an unknown collating
   105992         ** sequence.  The only way to reactive the index is to reload the
   105993         ** schema.  Adding the missing collating sequence later does not
   105994         ** reactive the index.  The application had the chance to register
   105995         ** the missing index using the collation-needed callback.  For
   105996         ** simplicity, SQLite will not give the application a second chance.
   105997         */
   105998         pIdx->bNoQuery = 1;
   105999         pParse->rc = SQLITE_ERROR_RETRY;
   106000       }
   106001       sqlite3KeyInfoUnref(pKey);
   106002       pKey = 0;
   106003     }
   106004   }
   106005   return pKey;
   106006 }
   106007 
   106008 #ifndef SQLITE_OMIT_CTE
   106009 /*
   106010 ** This routine is invoked once per CTE by the parser while parsing a
   106011 ** WITH clause.
   106012 */
   106013 SQLITE_PRIVATE With *sqlite3WithAdd(
   106014   Parse *pParse,          /* Parsing context */
   106015   With *pWith,            /* Existing WITH clause, or NULL */
   106016   Token *pName,           /* Name of the common-table */
   106017   ExprList *pArglist,     /* Optional column name list for the table */
   106018   Select *pQuery          /* Query used to initialize the table */
   106019 ){
   106020   sqlite3 *db = pParse->db;
   106021   With *pNew;
   106022   char *zName;
   106023 
   106024   /* Check that the CTE name is unique within this WITH clause. If
   106025   ** not, store an error in the Parse structure. */
   106026   zName = sqlite3NameFromToken(pParse->db, pName);
   106027   if( zName && pWith ){
   106028     int i;
   106029     for(i=0; i<pWith->nCte; i++){
   106030       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
   106031         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
   106032       }
   106033     }
   106034   }
   106035 
   106036   if( pWith ){
   106037     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
   106038     pNew = sqlite3DbRealloc(db, pWith, nByte);
   106039   }else{
   106040     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
   106041   }
   106042   assert( (pNew!=0 && zName!=0) || db->mallocFailed );
   106043 
   106044   if( db->mallocFailed ){
   106045     sqlite3ExprListDelete(db, pArglist);
   106046     sqlite3SelectDelete(db, pQuery);
   106047     sqlite3DbFree(db, zName);
   106048     pNew = pWith;
   106049   }else{
   106050     pNew->a[pNew->nCte].pSelect = pQuery;
   106051     pNew->a[pNew->nCte].pCols = pArglist;
   106052     pNew->a[pNew->nCte].zName = zName;
   106053     pNew->a[pNew->nCte].zCteErr = 0;
   106054     pNew->nCte++;
   106055   }
   106056 
   106057   return pNew;
   106058 }
   106059 
   106060 /*
   106061 ** Free the contents of the With object passed as the second argument.
   106062 */
   106063 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
   106064   if( pWith ){
   106065     int i;
   106066     for(i=0; i<pWith->nCte; i++){
   106067       struct Cte *pCte = &pWith->a[i];
   106068       sqlite3ExprListDelete(db, pCte->pCols);
   106069       sqlite3SelectDelete(db, pCte->pSelect);
   106070       sqlite3DbFree(db, pCte->zName);
   106071     }
   106072     sqlite3DbFree(db, pWith);
   106073   }
   106074 }
   106075 #endif /* !defined(SQLITE_OMIT_CTE) */
   106076 
   106077 /************** End of build.c ***********************************************/
   106078 /************** Begin file callback.c ****************************************/
   106079 /*
   106080 ** 2005 May 23
   106081 **
   106082 ** The author disclaims copyright to this source code.  In place of
   106083 ** a legal notice, here is a blessing:
   106084 **
   106085 **    May you do good and not evil.
   106086 **    May you find forgiveness for yourself and forgive others.
   106087 **    May you share freely, never taking more than you give.
   106088 **
   106089 *************************************************************************
   106090 **
   106091 ** This file contains functions used to access the internal hash tables
   106092 ** of user defined functions and collation sequences.
   106093 */
   106094 
   106095 /* #include "sqliteInt.h" */
   106096 
   106097 /*
   106098 ** Invoke the 'collation needed' callback to request a collation sequence
   106099 ** in the encoding enc of name zName, length nName.
   106100 */
   106101 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
   106102   assert( !db->xCollNeeded || !db->xCollNeeded16 );
   106103   if( db->xCollNeeded ){
   106104     char *zExternal = sqlite3DbStrDup(db, zName);
   106105     if( !zExternal ) return;
   106106     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
   106107     sqlite3DbFree(db, zExternal);
   106108   }
   106109 #ifndef SQLITE_OMIT_UTF16
   106110   if( db->xCollNeeded16 ){
   106111     char const *zExternal;
   106112     sqlite3_value *pTmp = sqlite3ValueNew(db);
   106113     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
   106114     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
   106115     if( zExternal ){
   106116       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
   106117     }
   106118     sqlite3ValueFree(pTmp);
   106119   }
   106120 #endif
   106121 }
   106122 
   106123 /*
   106124 ** This routine is called if the collation factory fails to deliver a
   106125 ** collation function in the best encoding but there may be other versions
   106126 ** of this collation function (for other text encodings) available. Use one
   106127 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
   106128 ** possible.
   106129 */
   106130 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
   106131   CollSeq *pColl2;
   106132   char *z = pColl->zName;
   106133   int i;
   106134   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
   106135   for(i=0; i<3; i++){
   106136     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
   106137     if( pColl2->xCmp!=0 ){
   106138       memcpy(pColl, pColl2, sizeof(CollSeq));
   106139       pColl->xDel = 0;         /* Do not copy the destructor */
   106140       return SQLITE_OK;
   106141     }
   106142   }
   106143   return SQLITE_ERROR;
   106144 }
   106145 
   106146 /*
   106147 ** This function is responsible for invoking the collation factory callback
   106148 ** or substituting a collation sequence of a different encoding when the
   106149 ** requested collation sequence is not available in the desired encoding.
   106150 **
   106151 ** If it is not NULL, then pColl must point to the database native encoding
   106152 ** collation sequence with name zName, length nName.
   106153 **
   106154 ** The return value is either the collation sequence to be used in database
   106155 ** db for collation type name zName, length nName, or NULL, if no collation
   106156 ** sequence can be found.  If no collation is found, leave an error message.
   106157 **
   106158 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
   106159 */
   106160 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
   106161   Parse *pParse,        /* Parsing context */
   106162   u8 enc,               /* The desired encoding for the collating sequence */
   106163   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
   106164   const char *zName     /* Collating sequence name */
   106165 ){
   106166   CollSeq *p;
   106167   sqlite3 *db = pParse->db;
   106168 
   106169   p = pColl;
   106170   if( !p ){
   106171     p = sqlite3FindCollSeq(db, enc, zName, 0);
   106172   }
   106173   if( !p || !p->xCmp ){
   106174     /* No collation sequence of this type for this encoding is registered.
   106175     ** Call the collation factory to see if it can supply us with one.
   106176     */
   106177     callCollNeeded(db, enc, zName);
   106178     p = sqlite3FindCollSeq(db, enc, zName, 0);
   106179   }
   106180   if( p && !p->xCmp && synthCollSeq(db, p) ){
   106181     p = 0;
   106182   }
   106183   assert( !p || p->xCmp );
   106184   if( p==0 ){
   106185     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   106186     pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
   106187   }
   106188   return p;
   106189 }
   106190 
   106191 /*
   106192 ** This routine is called on a collation sequence before it is used to
   106193 ** check that it is defined. An undefined collation sequence exists when
   106194 ** a database is loaded that contains references to collation sequences
   106195 ** that have not been defined by sqlite3_create_collation() etc.
   106196 **
   106197 ** If required, this routine calls the 'collation needed' callback to
   106198 ** request a definition of the collating sequence. If this doesn't work,
   106199 ** an equivalent collating sequence that uses a text encoding different
   106200 ** from the main database is substituted, if one is available.
   106201 */
   106202 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
   106203   if( pColl && pColl->xCmp==0 ){
   106204     const char *zName = pColl->zName;
   106205     sqlite3 *db = pParse->db;
   106206     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
   106207     if( !p ){
   106208       return SQLITE_ERROR;
   106209     }
   106210     assert( p==pColl );
   106211   }
   106212   return SQLITE_OK;
   106213 }
   106214 
   106215 
   106216 
   106217 /*
   106218 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
   106219 ** specified by zName and nName is not found and parameter 'create' is
   106220 ** true, then create a new entry. Otherwise return NULL.
   106221 **
   106222 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
   106223 ** array of three CollSeq structures. The first is the collation sequence
   106224 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
   106225 **
   106226 ** Stored immediately after the three collation sequences is a copy of
   106227 ** the collation sequence name. A pointer to this string is stored in
   106228 ** each collation sequence structure.
   106229 */
   106230 static CollSeq *findCollSeqEntry(
   106231   sqlite3 *db,          /* Database connection */
   106232   const char *zName,    /* Name of the collating sequence */
   106233   int create            /* Create a new entry if true */
   106234 ){
   106235   CollSeq *pColl;
   106236   pColl = sqlite3HashFind(&db->aCollSeq, zName);
   106237 
   106238   if( 0==pColl && create ){
   106239     int nName = sqlite3Strlen30(zName) + 1;
   106240     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
   106241     if( pColl ){
   106242       CollSeq *pDel = 0;
   106243       pColl[0].zName = (char*)&pColl[3];
   106244       pColl[0].enc = SQLITE_UTF8;
   106245       pColl[1].zName = (char*)&pColl[3];
   106246       pColl[1].enc = SQLITE_UTF16LE;
   106247       pColl[2].zName = (char*)&pColl[3];
   106248       pColl[2].enc = SQLITE_UTF16BE;
   106249       memcpy(pColl[0].zName, zName, nName);
   106250       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
   106251 
   106252       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
   106253       ** return the pColl pointer to be deleted (because it wasn't added
   106254       ** to the hash table).
   106255       */
   106256       assert( pDel==0 || pDel==pColl );
   106257       if( pDel!=0 ){
   106258         sqlite3OomFault(db);
   106259         sqlite3DbFree(db, pDel);
   106260         pColl = 0;
   106261       }
   106262     }
   106263   }
   106264   return pColl;
   106265 }
   106266 
   106267 /*
   106268 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
   106269 ** Return the CollSeq* pointer for the collation sequence named zName
   106270 ** for the encoding 'enc' from the database 'db'.
   106271 **
   106272 ** If the entry specified is not found and 'create' is true, then create a
   106273 ** new entry.  Otherwise return NULL.
   106274 **
   106275 ** A separate function sqlite3LocateCollSeq() is a wrapper around
   106276 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
   106277 ** if necessary and generates an error message if the collating sequence
   106278 ** cannot be found.
   106279 **
   106280 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
   106281 */
   106282 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
   106283   sqlite3 *db,
   106284   u8 enc,
   106285   const char *zName,
   106286   int create
   106287 ){
   106288   CollSeq *pColl;
   106289   if( zName ){
   106290     pColl = findCollSeqEntry(db, zName, create);
   106291   }else{
   106292     pColl = db->pDfltColl;
   106293   }
   106294   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   106295   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   106296   if( pColl ) pColl += enc-1;
   106297   return pColl;
   106298 }
   106299 
   106300 /* During the search for the best function definition, this procedure
   106301 ** is called to test how well the function passed as the first argument
   106302 ** matches the request for a function with nArg arguments in a system
   106303 ** that uses encoding enc. The value returned indicates how well the
   106304 ** request is matched. A higher value indicates a better match.
   106305 **
   106306 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
   106307 ** is also -1.  In other words, we are searching for a function that
   106308 ** takes a variable number of arguments.
   106309 **
   106310 ** If nArg is -2 that means that we are searching for any function
   106311 ** regardless of the number of arguments it uses, so return a positive
   106312 ** match score for any
   106313 **
   106314 ** The returned value is always between 0 and 6, as follows:
   106315 **
   106316 ** 0: Not a match.
   106317 ** 1: UTF8/16 conversion required and function takes any number of arguments.
   106318 ** 2: UTF16 byte order change required and function takes any number of args.
   106319 ** 3: encoding matches and function takes any number of arguments
   106320 ** 4: UTF8/16 conversion required - argument count matches exactly
   106321 ** 5: UTF16 byte order conversion required - argument count matches exactly
   106322 ** 6: Perfect match:  encoding and argument count match exactly.
   106323 **
   106324 ** If nArg==(-2) then any function with a non-null xSFunc is
   106325 ** a perfect match and any function with xSFunc NULL is
   106326 ** a non-match.
   106327 */
   106328 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
   106329 static int matchQuality(
   106330   FuncDef *p,     /* The function we are evaluating for match quality */
   106331   int nArg,       /* Desired number of arguments.  (-1)==any */
   106332   u8 enc          /* Desired text encoding */
   106333 ){
   106334   int match;
   106335 
   106336   /* nArg of -2 is a special case */
   106337   if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
   106338 
   106339   /* Wrong number of arguments means "no match" */
   106340   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
   106341 
   106342   /* Give a better score to a function with a specific number of arguments
   106343   ** than to function that accepts any number of arguments. */
   106344   if( p->nArg==nArg ){
   106345     match = 4;
   106346   }else{
   106347     match = 1;
   106348   }
   106349 
   106350   /* Bonus points if the text encoding matches */
   106351   if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
   106352     match += 2;  /* Exact encoding match */
   106353   }else if( (enc & p->funcFlags & 2)!=0 ){
   106354     match += 1;  /* Both are UTF16, but with different byte orders */
   106355   }
   106356 
   106357   return match;
   106358 }
   106359 
   106360 /*
   106361 ** Search a FuncDefHash for a function with the given name.  Return
   106362 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
   106363 */
   106364 static FuncDef *functionSearch(
   106365   int h,               /* Hash of the name */
   106366   const char *zFunc    /* Name of function */
   106367 ){
   106368   FuncDef *p;
   106369   for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
   106370     if( sqlite3StrICmp(p->zName, zFunc)==0 ){
   106371       return p;
   106372     }
   106373   }
   106374   return 0;
   106375 }
   106376 
   106377 /*
   106378 ** Insert a new FuncDef into a FuncDefHash hash table.
   106379 */
   106380 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
   106381   FuncDef *aDef,      /* List of global functions to be inserted */
   106382   int nDef            /* Length of the apDef[] list */
   106383 ){
   106384   int i;
   106385   for(i=0; i<nDef; i++){
   106386     FuncDef *pOther;
   106387     const char *zName = aDef[i].zName;
   106388     int nName = sqlite3Strlen30(zName);
   106389     int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
   106390     assert( zName[0]>='a' && zName[0]<='z' );
   106391     pOther = functionSearch(h, zName);
   106392     if( pOther ){
   106393       assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
   106394       aDef[i].pNext = pOther->pNext;
   106395       pOther->pNext = &aDef[i];
   106396     }else{
   106397       aDef[i].pNext = 0;
   106398       aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
   106399       sqlite3BuiltinFunctions.a[h] = &aDef[i];
   106400     }
   106401   }
   106402 }
   106403 
   106404 
   106405 
   106406 /*
   106407 ** Locate a user function given a name, a number of arguments and a flag
   106408 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
   106409 ** pointer to the FuncDef structure that defines that function, or return
   106410 ** NULL if the function does not exist.
   106411 **
   106412 ** If the createFlag argument is true, then a new (blank) FuncDef
   106413 ** structure is created and liked into the "db" structure if a
   106414 ** no matching function previously existed.
   106415 **
   106416 ** If nArg is -2, then the first valid function found is returned.  A
   106417 ** function is valid if xSFunc is non-zero.  The nArg==(-2)
   106418 ** case is used to see if zName is a valid function name for some number
   106419 ** of arguments.  If nArg is -2, then createFlag must be 0.
   106420 **
   106421 ** If createFlag is false, then a function with the required name and
   106422 ** number of arguments may be returned even if the eTextRep flag does not
   106423 ** match that requested.
   106424 */
   106425 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   106426   sqlite3 *db,       /* An open database */
   106427   const char *zName, /* Name of the function.  zero-terminated */
   106428   int nArg,          /* Number of arguments.  -1 means any number */
   106429   u8 enc,            /* Preferred text encoding */
   106430   u8 createFlag      /* Create new entry if true and does not otherwise exist */
   106431 ){
   106432   FuncDef *p;         /* Iterator variable */
   106433   FuncDef *pBest = 0; /* Best match found so far */
   106434   int bestScore = 0;  /* Score of best match */
   106435   int h;              /* Hash value */
   106436   int nName;          /* Length of the name */
   106437 
   106438   assert( nArg>=(-2) );
   106439   assert( nArg>=(-1) || createFlag==0 );
   106440   nName = sqlite3Strlen30(zName);
   106441 
   106442   /* First search for a match amongst the application-defined functions.
   106443   */
   106444   p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
   106445   while( p ){
   106446     int score = matchQuality(p, nArg, enc);
   106447     if( score>bestScore ){
   106448       pBest = p;
   106449       bestScore = score;
   106450     }
   106451     p = p->pNext;
   106452   }
   106453 
   106454   /* If no match is found, search the built-in functions.
   106455   **
   106456   ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
   106457   ** functions even if a prior app-defined function was found.  And give
   106458   ** priority to built-in functions.
   106459   **
   106460   ** Except, if createFlag is true, that means that we are trying to
   106461   ** install a new function.  Whatever FuncDef structure is returned it will
   106462   ** have fields overwritten with new information appropriate for the
   106463   ** new function.  But the FuncDefs for built-in functions are read-only.
   106464   ** So we must not search for built-ins when creating a new function.
   106465   */
   106466   if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
   106467     bestScore = 0;
   106468     h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
   106469     p = functionSearch(h, zName);
   106470     while( p ){
   106471       int score = matchQuality(p, nArg, enc);
   106472       if( score>bestScore ){
   106473         pBest = p;
   106474         bestScore = score;
   106475       }
   106476       p = p->pNext;
   106477     }
   106478   }
   106479 
   106480   /* If the createFlag parameter is true and the search did not reveal an
   106481   ** exact match for the name, number of arguments and encoding, then add a
   106482   ** new entry to the hash table and return it.
   106483   */
   106484   if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
   106485       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
   106486     FuncDef *pOther;
   106487     pBest->zName = (const char*)&pBest[1];
   106488     pBest->nArg = (u16)nArg;
   106489     pBest->funcFlags = enc;
   106490     memcpy((char*)&pBest[1], zName, nName+1);
   106491     pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
   106492     if( pOther==pBest ){
   106493       sqlite3DbFree(db, pBest);
   106494       sqlite3OomFault(db);
   106495       return 0;
   106496     }else{
   106497       pBest->pNext = pOther;
   106498     }
   106499   }
   106500 
   106501   if( pBest && (pBest->xSFunc || createFlag) ){
   106502     return pBest;
   106503   }
   106504   return 0;
   106505 }
   106506 
   106507 /*
   106508 ** Free all resources held by the schema structure. The void* argument points
   106509 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
   106510 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
   106511 ** of the schema hash tables).
   106512 **
   106513 ** The Schema.cache_size variable is not cleared.
   106514 */
   106515 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
   106516   Hash temp1;
   106517   Hash temp2;
   106518   HashElem *pElem;
   106519   Schema *pSchema = (Schema *)p;
   106520 
   106521   temp1 = pSchema->tblHash;
   106522   temp2 = pSchema->trigHash;
   106523   sqlite3HashInit(&pSchema->trigHash);
   106524   sqlite3HashClear(&pSchema->idxHash);
   106525   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   106526     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
   106527   }
   106528   sqlite3HashClear(&temp2);
   106529   sqlite3HashInit(&pSchema->tblHash);
   106530   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   106531     Table *pTab = sqliteHashData(pElem);
   106532     sqlite3DeleteTable(0, pTab);
   106533   }
   106534   sqlite3HashClear(&temp1);
   106535   sqlite3HashClear(&pSchema->fkeyHash);
   106536   pSchema->pSeqTab = 0;
   106537   if( pSchema->schemaFlags & DB_SchemaLoaded ){
   106538     pSchema->iGeneration++;
   106539   }
   106540   pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
   106541 }
   106542 
   106543 /*
   106544 ** Find and return the schema associated with a BTree.  Create
   106545 ** a new one if necessary.
   106546 */
   106547 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   106548   Schema * p;
   106549   if( pBt ){
   106550     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
   106551   }else{
   106552     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
   106553   }
   106554   if( !p ){
   106555     sqlite3OomFault(db);
   106556   }else if ( 0==p->file_format ){
   106557     sqlite3HashInit(&p->tblHash);
   106558     sqlite3HashInit(&p->idxHash);
   106559     sqlite3HashInit(&p->trigHash);
   106560     sqlite3HashInit(&p->fkeyHash);
   106561     p->enc = SQLITE_UTF8;
   106562   }
   106563   return p;
   106564 }
   106565 
   106566 /************** End of callback.c ********************************************/
   106567 /************** Begin file delete.c ******************************************/
   106568 /*
   106569 ** 2001 September 15
   106570 **
   106571 ** The author disclaims copyright to this source code.  In place of
   106572 ** a legal notice, here is a blessing:
   106573 **
   106574 **    May you do good and not evil.
   106575 **    May you find forgiveness for yourself and forgive others.
   106576 **    May you share freely, never taking more than you give.
   106577 **
   106578 *************************************************************************
   106579 ** This file contains C code routines that are called by the parser
   106580 ** in order to generate code for DELETE FROM statements.
   106581 */
   106582 /* #include "sqliteInt.h" */
   106583 
   106584 /*
   106585 ** While a SrcList can in general represent multiple tables and subqueries
   106586 ** (as in the FROM clause of a SELECT statement) in this case it contains
   106587 ** the name of a single table, as one might find in an INSERT, DELETE,
   106588 ** or UPDATE statement.  Look up that table in the symbol table and
   106589 ** return a pointer.  Set an error message and return NULL if the table
   106590 ** name is not found or if any other error occurs.
   106591 **
   106592 ** The following fields are initialized appropriate in pSrc:
   106593 **
   106594 **    pSrc->a[0].pTab       Pointer to the Table object
   106595 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
   106596 **
   106597 */
   106598 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   106599   struct SrcList_item *pItem = pSrc->a;
   106600   Table *pTab;
   106601   assert( pItem && pSrc->nSrc==1 );
   106602   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
   106603   sqlite3DeleteTable(pParse->db, pItem->pTab);
   106604   pItem->pTab = pTab;
   106605   if( pTab ){
   106606     pTab->nTabRef++;
   106607   }
   106608   if( sqlite3IndexedByLookup(pParse, pItem) ){
   106609     pTab = 0;
   106610   }
   106611   return pTab;
   106612 }
   106613 
   106614 /*
   106615 ** Check to make sure the given table is writable.  If it is not
   106616 ** writable, generate an error message and return 1.  If it is
   106617 ** writable return 0;
   106618 */
   106619 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
   106620   /* A table is not writable under the following circumstances:
   106621   **
   106622   **   1) It is a virtual table and no implementation of the xUpdate method
   106623   **      has been provided, or
   106624   **   2) It is a system table (i.e. sqlite_master), this call is not
   106625   **      part of a nested parse and writable_schema pragma has not
   106626   **      been specified.
   106627   **
   106628   ** In either case leave an error message in pParse and return non-zero.
   106629   */
   106630   if( ( IsVirtual(pTab)
   106631      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   106632    || ( (pTab->tabFlags & TF_Readonly)!=0
   106633      && (pParse->db->flags & SQLITE_WriteSchema)==0
   106634      && pParse->nested==0 )
   106635   ){
   106636     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
   106637     return 1;
   106638   }
   106639 
   106640 #ifndef SQLITE_OMIT_VIEW
   106641   if( !viewOk && pTab->pSelect ){
   106642     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
   106643     return 1;
   106644   }
   106645 #endif
   106646   return 0;
   106647 }
   106648 
   106649 
   106650 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   106651 /*
   106652 ** Evaluate a view and store its result in an ephemeral table.  The
   106653 ** pWhere argument is an optional WHERE clause that restricts the
   106654 ** set of rows in the view that are to be added to the ephemeral table.
   106655 */
   106656 SQLITE_PRIVATE void sqlite3MaterializeView(
   106657   Parse *pParse,       /* Parsing context */
   106658   Table *pView,        /* View definition */
   106659   Expr *pWhere,        /* Optional WHERE clause to be added */
   106660   ExprList *pOrderBy,  /* Optional ORDER BY clause */
   106661   Expr *pLimit,        /* Optional LIMIT clause */
   106662   int iCur             /* Cursor number for ephemeral table */
   106663 ){
   106664   SelectDest dest;
   106665   Select *pSel;
   106666   SrcList *pFrom;
   106667   sqlite3 *db = pParse->db;
   106668   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
   106669   pWhere = sqlite3ExprDup(db, pWhere, 0);
   106670   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   106671   if( pFrom ){
   106672     assert( pFrom->nSrc==1 );
   106673     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
   106674     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
   106675     assert( pFrom->a[0].pOn==0 );
   106676     assert( pFrom->a[0].pUsing==0 );
   106677   }
   106678   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
   106679                           SF_IncludeHidden, pLimit);
   106680   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   106681   sqlite3Select(pParse, pSel, &dest);
   106682   sqlite3SelectDelete(db, pSel);
   106683 }
   106684 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
   106685 
   106686 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   106687 /*
   106688 ** Generate an expression tree to implement the WHERE, ORDER BY,
   106689 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
   106690 **
   106691 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
   106692 **                            \__________________________/
   106693 **                               pLimitWhere (pInClause)
   106694 */
   106695 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   106696   Parse *pParse,               /* The parser context */
   106697   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
   106698   Expr *pWhere,                /* The WHERE clause.  May be null */
   106699   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
   106700   Expr *pLimit,                /* The LIMIT clause.  May be null */
   106701   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
   106702 ){
   106703   sqlite3 *db = pParse->db;
   106704   Expr *pLhs = NULL;           /* LHS of IN(SELECT...) operator */
   106705   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
   106706   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
   106707   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   106708   Select *pSelect = NULL;      /* Complete SELECT tree */
   106709   Table *pTab;
   106710 
   106711   /* Check that there isn't an ORDER BY without a LIMIT clause.
   106712   */
   106713   if( pOrderBy && pLimit==0 ) {
   106714     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   106715     sqlite3ExprDelete(pParse->db, pWhere);
   106716     sqlite3ExprListDelete(pParse->db, pOrderBy);
   106717     return 0;
   106718   }
   106719 
   106720   /* We only need to generate a select expression if there
   106721   ** is a limit/offset term to enforce.
   106722   */
   106723   if( pLimit == 0 ) {
   106724     return pWhere;
   106725   }
   106726 
   106727   /* Generate a select expression tree to enforce the limit/offset
   106728   ** term for the DELETE or UPDATE statement.  For example:
   106729   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   106730   ** becomes:
   106731   **   DELETE FROM table_a WHERE rowid IN (
   106732   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   106733   **   );
   106734   */
   106735 
   106736   pTab = pSrc->a[0].pTab;
   106737   if( HasRowid(pTab) ){
   106738     pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
   106739     pEList = sqlite3ExprListAppend(
   106740         pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
   106741     );
   106742   }else{
   106743     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   106744     if( pPk->nKeyCol==1 ){
   106745       const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
   106746       pLhs = sqlite3Expr(db, TK_ID, zName);
   106747       pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
   106748     }else{
   106749       int i;
   106750       for(i=0; i<pPk->nKeyCol; i++){
   106751         Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
   106752         pEList = sqlite3ExprListAppend(pParse, pEList, p);
   106753       }
   106754       pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
   106755       if( pLhs ){
   106756         pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
   106757       }
   106758     }
   106759   }
   106760 
   106761   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   106762   ** and the SELECT subtree. */
   106763   pSrc->a[0].pTab = 0;
   106764   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
   106765   pSrc->a[0].pTab = pTab;
   106766   pSrc->a[0].pIBIndex = 0;
   106767 
   106768   /* generate the SELECT expression tree. */
   106769   pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
   106770       pOrderBy,0,pLimit
   106771   );
   106772 
   106773   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
   106774   pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
   106775   sqlite3PExprAddSelect(pParse, pInClause, pSelect);
   106776   return pInClause;
   106777 }
   106778 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
   106779        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
   106780 
   106781 /*
   106782 ** Generate code for a DELETE FROM statement.
   106783 **
   106784 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
   106785 **                 \________/       \________________/
   106786 **                  pTabList              pWhere
   106787 */
   106788 SQLITE_PRIVATE void sqlite3DeleteFrom(
   106789   Parse *pParse,         /* The parser context */
   106790   SrcList *pTabList,     /* The table from which we should delete things */
   106791   Expr *pWhere,          /* The WHERE clause.  May be null */
   106792   ExprList *pOrderBy,    /* ORDER BY clause. May be null */
   106793   Expr *pLimit           /* LIMIT clause. May be null */
   106794 ){
   106795   Vdbe *v;               /* The virtual database engine */
   106796   Table *pTab;           /* The table from which records will be deleted */
   106797   int i;                 /* Loop counter */
   106798   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   106799   Index *pIdx;           /* For looping over indices of the table */
   106800   int iTabCur;           /* Cursor number for the table */
   106801   int iDataCur = 0;      /* VDBE cursor for the canonical data source */
   106802   int iIdxCur = 0;       /* Cursor number of the first index */
   106803   int nIdx;              /* Number of indices */
   106804   sqlite3 *db;           /* Main database structure */
   106805   AuthContext sContext;  /* Authorization context */
   106806   NameContext sNC;       /* Name context to resolve expressions in */
   106807   int iDb;               /* Database number */
   106808   int memCnt = -1;       /* Memory cell used for change counting */
   106809   int rcauth;            /* Value returned by authorization callback */
   106810   int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
   106811   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
   106812   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
   106813   Index *pPk;            /* The PRIMARY KEY index on the table */
   106814   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
   106815   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
   106816   int iKey;              /* Memory cell holding key of row to be deleted */
   106817   i16 nKey;              /* Number of memory cells in the row key */
   106818   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
   106819   int iRowSet = 0;       /* Register for rowset of rows to delete */
   106820   int addrBypass = 0;    /* Address of jump over the delete logic */
   106821   int addrLoop = 0;      /* Top of the delete loop */
   106822   int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
   106823   int bComplex;          /* True if there are triggers or FKs or
   106824                          ** subqueries in the WHERE clause */
   106825 
   106826 #ifndef SQLITE_OMIT_TRIGGER
   106827   int isView;                  /* True if attempting to delete from a view */
   106828   Trigger *pTrigger;           /* List of table triggers, if required */
   106829 #endif
   106830 
   106831   memset(&sContext, 0, sizeof(sContext));
   106832   db = pParse->db;
   106833   if( pParse->nErr || db->mallocFailed ){
   106834     goto delete_from_cleanup;
   106835   }
   106836   assert( pTabList->nSrc==1 );
   106837 
   106838 
   106839   /* Locate the table which we want to delete.  This table has to be
   106840   ** put in an SrcList structure because some of the subroutines we
   106841   ** will be calling are designed to work with multiple tables and expect
   106842   ** an SrcList* parameter instead of just a Table* parameter.
   106843   */
   106844   pTab = sqlite3SrcListLookup(pParse, pTabList);
   106845   if( pTab==0 )  goto delete_from_cleanup;
   106846 
   106847   /* Figure out if we have any triggers and if the table being
   106848   ** deleted from is a view
   106849   */
   106850 #ifndef SQLITE_OMIT_TRIGGER
   106851   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   106852   isView = pTab->pSelect!=0;
   106853 #else
   106854 # define pTrigger 0
   106855 # define isView 0
   106856 #endif
   106857   bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
   106858 #ifdef SQLITE_OMIT_VIEW
   106859 # undef isView
   106860 # define isView 0
   106861 #endif
   106862 
   106863 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
   106864   if( !isView ){
   106865     pWhere = sqlite3LimitWhere(
   106866         pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
   106867     );
   106868     pOrderBy = 0;
   106869     pLimit = 0;
   106870   }
   106871 #endif
   106872 
   106873   /* If pTab is really a view, make sure it has been initialized.
   106874   */
   106875   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   106876     goto delete_from_cleanup;
   106877   }
   106878 
   106879   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   106880     goto delete_from_cleanup;
   106881   }
   106882   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   106883   assert( iDb<db->nDb );
   106884   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
   106885                             db->aDb[iDb].zDbSName);
   106886   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   106887   if( rcauth==SQLITE_DENY ){
   106888     goto delete_from_cleanup;
   106889   }
   106890   assert(!isView || pTrigger);
   106891 
   106892   /* Assign cursor numbers to the table and all its indices.
   106893   */
   106894   assert( pTabList->nSrc==1 );
   106895   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
   106896   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
   106897     pParse->nTab++;
   106898   }
   106899 
   106900   /* Start the view context
   106901   */
   106902   if( isView ){
   106903     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   106904   }
   106905 
   106906   /* Begin generating code.
   106907   */
   106908   v = sqlite3GetVdbe(pParse);
   106909   if( v==0 ){
   106910     goto delete_from_cleanup;
   106911   }
   106912   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   106913   sqlite3BeginWriteOperation(pParse, 1, iDb);
   106914 
   106915   /* If we are trying to delete from a view, realize that view into
   106916   ** an ephemeral table.
   106917   */
   106918 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   106919   if( isView ){
   106920     sqlite3MaterializeView(pParse, pTab,
   106921         pWhere, pOrderBy, pLimit, iTabCur
   106922     );
   106923     iDataCur = iIdxCur = iTabCur;
   106924     pOrderBy = 0;
   106925     pLimit = 0;
   106926   }
   106927 #endif
   106928 
   106929   /* Resolve the column names in the WHERE clause.
   106930   */
   106931   memset(&sNC, 0, sizeof(sNC));
   106932   sNC.pParse = pParse;
   106933   sNC.pSrcList = pTabList;
   106934   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   106935     goto delete_from_cleanup;
   106936   }
   106937 
   106938   /* Initialize the counter of the number of rows deleted, if
   106939   ** we are counting rows.
   106940   */
   106941   if( db->flags & SQLITE_CountRows ){
   106942     memCnt = ++pParse->nMem;
   106943     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
   106944   }
   106945 
   106946 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   106947   /* Special case: A DELETE without a WHERE clause deletes everything.
   106948   ** It is easier just to erase the whole table. Prior to version 3.6.5,
   106949   ** this optimization caused the row change count (the value returned by
   106950   ** API function sqlite3_count_changes) to be set incorrectly.
   106951   **
   106952   ** The "rcauth==SQLITE_OK" terms is the
   106953   ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
   106954   ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
   106955   ** the truncate optimization is disabled and all rows are deleted
   106956   ** individually.
   106957   */
   106958   if( rcauth==SQLITE_OK
   106959    && pWhere==0
   106960    && !bComplex
   106961    && !IsVirtual(pTab)
   106962 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   106963    && db->xPreUpdateCallback==0
   106964 #endif
   106965   ){
   106966     assert( !isView );
   106967     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   106968     if( HasRowid(pTab) ){
   106969       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
   106970                         pTab->zName, P4_STATIC);
   106971     }
   106972     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   106973       assert( pIdx->pSchema==pTab->pSchema );
   106974       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
   106975     }
   106976   }else
   106977 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   106978   {
   106979     u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
   106980     if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
   106981     wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
   106982     if( HasRowid(pTab) ){
   106983       /* For a rowid table, initialize the RowSet to an empty set */
   106984       pPk = 0;
   106985       nPk = 1;
   106986       iRowSet = ++pParse->nMem;
   106987       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   106988     }else{
   106989       /* For a WITHOUT ROWID table, create an ephemeral table used to
   106990       ** hold all primary keys for rows to be deleted. */
   106991       pPk = sqlite3PrimaryKeyIndex(pTab);
   106992       assert( pPk!=0 );
   106993       nPk = pPk->nKeyCol;
   106994       iPk = pParse->nMem+1;
   106995       pParse->nMem += nPk;
   106996       iEphCur = pParse->nTab++;
   106997       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
   106998       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   106999     }
   107000 
   107001     /* Construct a query to find the rowid or primary key for every row
   107002     ** to be deleted, based on the WHERE clause. Set variable eOnePass
   107003     ** to indicate the strategy used to implement this delete:
   107004     **
   107005     **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
   107006     **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
   107007     **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
   107008     */
   107009     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
   107010     if( pWInfo==0 ) goto delete_from_cleanup;
   107011     eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   107012     assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
   107013     assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
   107014 
   107015     /* Keep track of the number of rows to be deleted */
   107016     if( db->flags & SQLITE_CountRows ){
   107017       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   107018     }
   107019 
   107020     /* Extract the rowid or primary key for the current row */
   107021     if( pPk ){
   107022       for(i=0; i<nPk; i++){
   107023         assert( pPk->aiColumn[i]>=0 );
   107024         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
   107025                                         pPk->aiColumn[i], iPk+i);
   107026       }
   107027       iKey = iPk;
   107028     }else{
   107029       iKey = pParse->nMem + 1;
   107030       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
   107031       if( iKey>pParse->nMem ) pParse->nMem = iKey;
   107032     }
   107033 
   107034     if( eOnePass!=ONEPASS_OFF ){
   107035       /* For ONEPASS, no need to store the rowid/primary-key. There is only
   107036       ** one, so just keep it in its register(s) and fall through to the
   107037       ** delete code.  */
   107038       nKey = nPk; /* OP_Found will use an unpacked key */
   107039       aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
   107040       if( aToOpen==0 ){
   107041         sqlite3WhereEnd(pWInfo);
   107042         goto delete_from_cleanup;
   107043       }
   107044       memset(aToOpen, 1, nIdx+1);
   107045       aToOpen[nIdx+1] = 0;
   107046       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
   107047       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
   107048       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
   107049     }else{
   107050       if( pPk ){
   107051         /* Add the PK key for this row to the temporary table */
   107052         iKey = ++pParse->nMem;
   107053         nKey = 0;   /* Zero tells OP_Found to use a composite key */
   107054         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
   107055             sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
   107056         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
   107057       }else{
   107058         /* Add the rowid of the row to be deleted to the RowSet */
   107059         nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
   107060         sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
   107061       }
   107062     }
   107063 
   107064     /* If this DELETE cannot use the ONEPASS strategy, this is the
   107065     ** end of the WHERE loop */
   107066     if( eOnePass!=ONEPASS_OFF ){
   107067       addrBypass = sqlite3VdbeMakeLabel(v);
   107068     }else{
   107069       sqlite3WhereEnd(pWInfo);
   107070     }
   107071 
   107072     /* Unless this is a view, open cursors for the table we are
   107073     ** deleting from and all its indices. If this is a view, then the
   107074     ** only effect this statement has is to fire the INSTEAD OF
   107075     ** triggers.
   107076     */
   107077     if( !isView ){
   107078       int iAddrOnce = 0;
   107079       if( eOnePass==ONEPASS_MULTI ){
   107080         iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   107081       }
   107082       testcase( IsVirtual(pTab) );
   107083       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
   107084                                  iTabCur, aToOpen, &iDataCur, &iIdxCur);
   107085       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
   107086       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
   107087       if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
   107088     }
   107089 
   107090     /* Set up a loop over the rowids/primary-keys that were found in the
   107091     ** where-clause loop above.
   107092     */
   107093     if( eOnePass!=ONEPASS_OFF ){
   107094       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
   107095       if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
   107096         assert( pPk!=0 || pTab->pSelect!=0 );
   107097         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
   107098         VdbeCoverage(v);
   107099       }
   107100     }else if( pPk ){
   107101       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
   107102       if( IsVirtual(pTab) ){
   107103         sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
   107104       }else{
   107105         sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
   107106       }
   107107       assert( nKey==0 );  /* OP_Found will use a composite key */
   107108     }else{
   107109       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
   107110       VdbeCoverage(v);
   107111       assert( nKey==1 );
   107112     }
   107113 
   107114     /* Delete the row */
   107115 #ifndef SQLITE_OMIT_VIRTUALTABLE
   107116     if( IsVirtual(pTab) ){
   107117       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   107118       sqlite3VtabMakeWritable(pParse, pTab);
   107119       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
   107120       sqlite3VdbeChangeP5(v, OE_Abort);
   107121       assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
   107122       sqlite3MayAbort(pParse);
   107123       if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
   107124         pParse->isMultiWrite = 0;
   107125       }
   107126     }else
   107127 #endif
   107128     {
   107129       int count = (pParse->nested==0);    /* True to count changes */
   107130       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   107131           iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
   107132     }
   107133 
   107134     /* End of the loop over all rowids/primary-keys. */
   107135     if( eOnePass!=ONEPASS_OFF ){
   107136       sqlite3VdbeResolveLabel(v, addrBypass);
   107137       sqlite3WhereEnd(pWInfo);
   107138     }else if( pPk ){
   107139       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
   107140       sqlite3VdbeJumpHere(v, addrLoop);
   107141     }else{
   107142       sqlite3VdbeGoto(v, addrLoop);
   107143       sqlite3VdbeJumpHere(v, addrLoop);
   107144     }
   107145   } /* End non-truncate path */
   107146 
   107147   /* Update the sqlite_sequence table by storing the content of the
   107148   ** maximum rowid counter values recorded while inserting into
   107149   ** autoincrement tables.
   107150   */
   107151   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   107152     sqlite3AutoincrementEnd(pParse);
   107153   }
   107154 
   107155   /* Return the number of rows that were deleted. If this routine is
   107156   ** generating code because of a call to sqlite3NestedParse(), do not
   107157   ** invoke the callback function.
   107158   */
   107159   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   107160     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   107161     sqlite3VdbeSetNumCols(v, 1);
   107162     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   107163   }
   107164 
   107165 delete_from_cleanup:
   107166   sqlite3AuthContextPop(&sContext);
   107167   sqlite3SrcListDelete(db, pTabList);
   107168   sqlite3ExprDelete(db, pWhere);
   107169 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
   107170   sqlite3ExprListDelete(db, pOrderBy);
   107171   sqlite3ExprDelete(db, pLimit);
   107172 #endif
   107173   sqlite3DbFree(db, aToOpen);
   107174   return;
   107175 }
   107176 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   107177 ** they may interfere with compilation of other functions in this file
   107178 ** (or in another file, if this file becomes part of the amalgamation).  */
   107179 #ifdef isView
   107180  #undef isView
   107181 #endif
   107182 #ifdef pTrigger
   107183  #undef pTrigger
   107184 #endif
   107185 
   107186 /*
   107187 ** This routine generates VDBE code that causes a single row of a
   107188 ** single table to be deleted.  Both the original table entry and
   107189 ** all indices are removed.
   107190 **
   107191 ** Preconditions:
   107192 **
   107193 **   1.  iDataCur is an open cursor on the btree that is the canonical data
   107194 **       store for the table.  (This will be either the table itself,
   107195 **       in the case of a rowid table, or the PRIMARY KEY index in the case
   107196 **       of a WITHOUT ROWID table.)
   107197 **
   107198 **   2.  Read/write cursors for all indices of pTab must be open as
   107199 **       cursor number iIdxCur+i for the i-th index.
   107200 **
   107201 **   3.  The primary key for the row to be deleted must be stored in a
   107202 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
   107203 **       that a search record formed from OP_MakeRecord is contained in the
   107204 **       single memory location iPk.
   107205 **
   107206 ** eMode:
   107207 **   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
   107208 **   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
   107209 **   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
   107210 **   then this function must seek iDataCur to the entry identified by iPk
   107211 **   and nPk before reading from it.
   107212 **
   107213 **   If eMode is ONEPASS_MULTI, then this call is being made as part
   107214 **   of a ONEPASS delete that affects multiple rows. In this case, if
   107215 **   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
   107216 **   iDataCur, then its position should be preserved following the delete
   107217 **   operation. Or, if iIdxNoSeek is not a valid cursor number, the
   107218 **   position of iDataCur should be preserved instead.
   107219 **
   107220 ** iIdxNoSeek:
   107221 **   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
   107222 **   then it identifies an index cursor (from within array of cursors
   107223 **   starting at iIdxCur) that already points to the index entry to be deleted.
   107224 **   Except, this optimization is disabled if there are BEFORE triggers since
   107225 **   the trigger body might have moved the cursor.
   107226 */
   107227 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   107228   Parse *pParse,     /* Parsing context */
   107229   Table *pTab,       /* Table containing the row to be deleted */
   107230   Trigger *pTrigger, /* List of triggers to (potentially) fire */
   107231   int iDataCur,      /* Cursor from which column data is extracted */
   107232   int iIdxCur,       /* First index cursor */
   107233   int iPk,           /* First memory cell containing the PRIMARY KEY */
   107234   i16 nPk,           /* Number of PRIMARY KEY memory cells */
   107235   u8 count,          /* If non-zero, increment the row change counter */
   107236   u8 onconf,         /* Default ON CONFLICT policy for triggers */
   107237   u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
   107238   int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
   107239 ){
   107240   Vdbe *v = pParse->pVdbe;        /* Vdbe */
   107241   int iOld = 0;                   /* First register in OLD.* array */
   107242   int iLabel;                     /* Label resolved to end of generated code */
   107243   u8 opSeek;                      /* Seek opcode */
   107244 
   107245   /* Vdbe is guaranteed to have been allocated by this stage. */
   107246   assert( v );
   107247   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
   107248                          iDataCur, iIdxCur, iPk, (int)nPk));
   107249 
   107250   /* Seek cursor iCur to the row to delete. If this row no longer exists
   107251   ** (this can happen if a trigger program has already deleted it), do
   107252   ** not attempt to delete it or fire any DELETE triggers.  */
   107253   iLabel = sqlite3VdbeMakeLabel(v);
   107254   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
   107255   if( eMode==ONEPASS_OFF ){
   107256     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
   107257     VdbeCoverageIf(v, opSeek==OP_NotExists);
   107258     VdbeCoverageIf(v, opSeek==OP_NotFound);
   107259   }
   107260 
   107261   /* If there are any triggers to fire, allocate a range of registers to
   107262   ** use for the old.* references in the triggers.  */
   107263   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   107264     u32 mask;                     /* Mask of OLD.* columns in use */
   107265     int iCol;                     /* Iterator used while populating OLD.* */
   107266     int addrStart;                /* Start of BEFORE trigger programs */
   107267 
   107268     /* TODO: Could use temporary registers here. Also could attempt to
   107269     ** avoid copying the contents of the rowid register.  */
   107270     mask = sqlite3TriggerColmask(
   107271         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
   107272     );
   107273     mask |= sqlite3FkOldmask(pParse, pTab);
   107274     iOld = pParse->nMem+1;
   107275     pParse->nMem += (1 + pTab->nCol);
   107276 
   107277     /* Populate the OLD.* pseudo-table register array. These values will be
   107278     ** used by any BEFORE and AFTER triggers that exist.  */
   107279     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
   107280     for(iCol=0; iCol<pTab->nCol; iCol++){
   107281       testcase( mask!=0xffffffff && iCol==31 );
   107282       testcase( mask!=0xffffffff && iCol==32 );
   107283       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
   107284         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
   107285       }
   107286     }
   107287 
   107288     /* Invoke BEFORE DELETE trigger programs. */
   107289     addrStart = sqlite3VdbeCurrentAddr(v);
   107290     sqlite3CodeRowTrigger(pParse, pTrigger,
   107291         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
   107292     );
   107293 
   107294     /* If any BEFORE triggers were coded, then seek the cursor to the
   107295     ** row to be deleted again. It may be that the BEFORE triggers moved
   107296     ** the cursor or already deleted the row that the cursor was
   107297     ** pointing to.
   107298     **
   107299     ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
   107300     ** may have moved that cursor.
   107301     */
   107302     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
   107303       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
   107304       VdbeCoverageIf(v, opSeek==OP_NotExists);
   107305       VdbeCoverageIf(v, opSeek==OP_NotFound);
   107306       testcase( iIdxNoSeek>=0 );
   107307       iIdxNoSeek = -1;
   107308     }
   107309 
   107310     /* Do FK processing. This call checks that any FK constraints that
   107311     ** refer to this table (i.e. constraints attached to other tables)
   107312     ** are not violated by deleting this row.  */
   107313     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
   107314   }
   107315 
   107316   /* Delete the index and table entries. Skip this step if pTab is really
   107317   ** a view (in which case the only effect of the DELETE statement is to
   107318   ** fire the INSTEAD OF triggers).
   107319   **
   107320   ** If variable 'count' is non-zero, then this OP_Delete instruction should
   107321   ** invoke the update-hook. The pre-update-hook, on the other hand should
   107322   ** be invoked unless table pTab is a system table. The difference is that
   107323   ** the update-hook is not invoked for rows removed by REPLACE, but the
   107324   ** pre-update-hook is.
   107325   */
   107326   if( pTab->pSelect==0 ){
   107327     u8 p5 = 0;
   107328     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
   107329     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
   107330     if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
   107331       sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
   107332     }
   107333     if( eMode!=ONEPASS_OFF ){
   107334       sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
   107335     }
   107336     if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
   107337       sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
   107338     }
   107339     if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
   107340     sqlite3VdbeChangeP5(v, p5);
   107341   }
   107342 
   107343   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   107344   ** handle rows (possibly in other tables) that refer via a foreign key
   107345   ** to the row just deleted. */
   107346   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
   107347 
   107348   /* Invoke AFTER DELETE trigger programs. */
   107349   sqlite3CodeRowTrigger(pParse, pTrigger,
   107350       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   107351   );
   107352 
   107353   /* Jump here if the row had already been deleted before any BEFORE
   107354   ** trigger programs were invoked. Or if a trigger program throws a
   107355   ** RAISE(IGNORE) exception.  */
   107356   sqlite3VdbeResolveLabel(v, iLabel);
   107357   VdbeModuleComment((v, "END: GenRowDel()"));
   107358 }
   107359 
   107360 /*
   107361 ** This routine generates VDBE code that causes the deletion of all
   107362 ** index entries associated with a single row of a single table, pTab
   107363 **
   107364 ** Preconditions:
   107365 **
   107366 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
   107367 **       btree for the table pTab.  (This will be either the table itself
   107368 **       for rowid tables or to the primary key index for WITHOUT ROWID
   107369 **       tables.)
   107370 **
   107371 **   2.  Read/write cursors for all indices of pTab must be open as
   107372 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
   107373 **       index is the 0-th index.)
   107374 **
   107375 **   3.  The "iDataCur" cursor must be already be positioned on the row
   107376 **       that is to be deleted.
   107377 */
   107378 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
   107379   Parse *pParse,     /* Parsing and code generating context */
   107380   Table *pTab,       /* Table containing the row to be deleted */
   107381   int iDataCur,      /* Cursor of table holding data. */
   107382   int iIdxCur,       /* First index cursor */
   107383   int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   107384   int iIdxNoSeek     /* Do not delete from this cursor */
   107385 ){
   107386   int i;             /* Index loop counter */
   107387   int r1 = -1;       /* Register holding an index key */
   107388   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
   107389   Index *pIdx;       /* Current index */
   107390   Index *pPrior = 0; /* Prior index */
   107391   Vdbe *v;           /* The prepared statement under construction */
   107392   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
   107393 
   107394   v = pParse->pVdbe;
   107395   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   107396   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   107397     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
   107398     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
   107399     if( pIdx==pPk ) continue;
   107400     if( iIdxCur+i==iIdxNoSeek ) continue;
   107401     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
   107402     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
   107403         &iPartIdxLabel, pPrior, r1);
   107404     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
   107405         pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
   107406     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
   107407     pPrior = pIdx;
   107408   }
   107409 }
   107410 
   107411 /*
   107412 ** Generate code that will assemble an index key and stores it in register
   107413 ** regOut.  The key with be for index pIdx which is an index on pTab.
   107414 ** iCur is the index of a cursor open on the pTab table and pointing to
   107415 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
   107416 ** iCur must be the cursor of the PRIMARY KEY index.
   107417 **
   107418 ** Return a register number which is the first in a block of
   107419 ** registers that holds the elements of the index key.  The
   107420 ** block of registers has already been deallocated by the time
   107421 ** this routine returns.
   107422 **
   107423 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
   107424 ** to that label if pIdx is a partial index that should be skipped.
   107425 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
   107426 ** A partial index should be skipped if its WHERE clause evaluates
   107427 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
   107428 ** will be set to zero which is an empty label that is ignored by
   107429 ** sqlite3ResolvePartIdxLabel().
   107430 **
   107431 ** The pPrior and regPrior parameters are used to implement a cache to
   107432 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
   107433 ** a pointer to a different index for which an index key has just been
   107434 ** computed into register regPrior.  If the current pIdx index is generating
   107435 ** its key into the same sequence of registers and if pPrior and pIdx share
   107436 ** a column in common, then the register corresponding to that column already
   107437 ** holds the correct value and the loading of that register is skipped.
   107438 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
   107439 ** on a table with multiple indices, and especially with the ROWID or
   107440 ** PRIMARY KEY columns of the index.
   107441 */
   107442 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   107443   Parse *pParse,       /* Parsing context */
   107444   Index *pIdx,         /* The index for which to generate a key */
   107445   int iDataCur,        /* Cursor number from which to take column data */
   107446   int regOut,          /* Put the new key into this register if not 0 */
   107447   int prefixOnly,      /* Compute only a unique prefix of the key */
   107448   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
   107449   Index *pPrior,       /* Previously generated index key */
   107450   int regPrior         /* Register holding previous generated key */
   107451 ){
   107452   Vdbe *v = pParse->pVdbe;
   107453   int j;
   107454   int regBase;
   107455   int nCol;
   107456 
   107457   if( piPartIdxLabel ){
   107458     if( pIdx->pPartIdxWhere ){
   107459       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
   107460       pParse->iSelfTab = iDataCur + 1;
   107461       sqlite3ExprCachePush(pParse);
   107462       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
   107463                             SQLITE_JUMPIFNULL);
   107464       pParse->iSelfTab = 0;
   107465     }else{
   107466       *piPartIdxLabel = 0;
   107467     }
   107468   }
   107469   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
   107470   regBase = sqlite3GetTempRange(pParse, nCol);
   107471   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
   107472   for(j=0; j<nCol; j++){
   107473     if( pPrior
   107474      && pPrior->aiColumn[j]==pIdx->aiColumn[j]
   107475      && pPrior->aiColumn[j]!=XN_EXPR
   107476     ){
   107477       /* This column was already computed by the previous index */
   107478       continue;
   107479     }
   107480     sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
   107481     /* If the column affinity is REAL but the number is an integer, then it
   107482     ** might be stored in the table as an integer (using a compact
   107483     ** representation) then converted to REAL by an OP_RealAffinity opcode.
   107484     ** But we are getting ready to store this value back into an index, where
   107485     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
   107486     ** opcode if it is present */
   107487     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
   107488   }
   107489   if( regOut ){
   107490     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
   107491     if( pIdx->pTable->pSelect ){
   107492       const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
   107493       sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
   107494     }
   107495   }
   107496   sqlite3ReleaseTempRange(pParse, regBase, nCol);
   107497   return regBase;
   107498 }
   107499 
   107500 /*
   107501 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
   107502 ** because it was a partial index, then this routine should be called to
   107503 ** resolve that label.
   107504 */
   107505 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
   107506   if( iLabel ){
   107507     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
   107508     sqlite3ExprCachePop(pParse);
   107509   }
   107510 }
   107511 
   107512 /************** End of delete.c **********************************************/
   107513 /************** Begin file func.c ********************************************/
   107514 /*
   107515 ** 2002 February 23
   107516 **
   107517 ** The author disclaims copyright to this source code.  In place of
   107518 ** a legal notice, here is a blessing:
   107519 **
   107520 **    May you do good and not evil.
   107521 **    May you find forgiveness for yourself and forgive others.
   107522 **    May you share freely, never taking more than you give.
   107523 **
   107524 *************************************************************************
   107525 ** This file contains the C-language implementations for many of the SQL
   107526 ** functions of SQLite.  (Some function, and in particular the date and
   107527 ** time functions, are implemented separately.)
   107528 */
   107529 /* #include "sqliteInt.h" */
   107530 /* #include <stdlib.h> */
   107531 /* #include <assert.h> */
   107532 /* #include "vdbeInt.h" */
   107533 
   107534 /*
   107535 ** Return the collating function associated with a function.
   107536 */
   107537 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
   107538   VdbeOp *pOp;
   107539   assert( context->pVdbe!=0 );
   107540   pOp = &context->pVdbe->aOp[context->iOp-1];
   107541   assert( pOp->opcode==OP_CollSeq );
   107542   assert( pOp->p4type==P4_COLLSEQ );
   107543   return pOp->p4.pColl;
   107544 }
   107545 
   107546 /*
   107547 ** Indicate that the accumulator load should be skipped on this
   107548 ** iteration of the aggregate loop.
   107549 */
   107550 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
   107551   context->skipFlag = 1;
   107552 }
   107553 
   107554 /*
   107555 ** Implementation of the non-aggregate min() and max() functions
   107556 */
   107557 static void minmaxFunc(
   107558   sqlite3_context *context,
   107559   int argc,
   107560   sqlite3_value **argv
   107561 ){
   107562   int i;
   107563   int mask;    /* 0 for min() or 0xffffffff for max() */
   107564   int iBest;
   107565   CollSeq *pColl;
   107566 
   107567   assert( argc>1 );
   107568   mask = sqlite3_user_data(context)==0 ? 0 : -1;
   107569   pColl = sqlite3GetFuncCollSeq(context);
   107570   assert( pColl );
   107571   assert( mask==-1 || mask==0 );
   107572   iBest = 0;
   107573   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   107574   for(i=1; i<argc; i++){
   107575     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
   107576     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
   107577       testcase( mask==0 );
   107578       iBest = i;
   107579     }
   107580   }
   107581   sqlite3_result_value(context, argv[iBest]);
   107582 }
   107583 
   107584 /*
   107585 ** Return the type of the argument.
   107586 */
   107587 static void typeofFunc(
   107588   sqlite3_context *context,
   107589   int NotUsed,
   107590   sqlite3_value **argv
   107591 ){
   107592   static const char *azType[] = { "integer", "real", "text", "blob", "null" };
   107593   int i = sqlite3_value_type(argv[0]) - 1;
   107594   UNUSED_PARAMETER(NotUsed);
   107595   assert( i>=0 && i<ArraySize(azType) );
   107596   assert( SQLITE_INTEGER==1 );
   107597   assert( SQLITE_FLOAT==2 );
   107598   assert( SQLITE_TEXT==3 );
   107599   assert( SQLITE_BLOB==4 );
   107600   assert( SQLITE_NULL==5 );
   107601   /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
   107602   ** the datatype code for the initial datatype of the sqlite3_value object
   107603   ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
   107604   ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
   107605   sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
   107606 }
   107607 
   107608 
   107609 /*
   107610 ** Implementation of the length() function
   107611 */
   107612 static void lengthFunc(
   107613   sqlite3_context *context,
   107614   int argc,
   107615   sqlite3_value **argv
   107616 ){
   107617   int len;
   107618 
   107619   assert( argc==1 );
   107620   UNUSED_PARAMETER(argc);
   107621   switch( sqlite3_value_type(argv[0]) ){
   107622     case SQLITE_BLOB:
   107623     case SQLITE_INTEGER:
   107624     case SQLITE_FLOAT: {
   107625       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   107626       break;
   107627     }
   107628     case SQLITE_TEXT: {
   107629       const unsigned char *z = sqlite3_value_text(argv[0]);
   107630       if( z==0 ) return;
   107631       len = 0;
   107632       while( *z ){
   107633         len++;
   107634         SQLITE_SKIP_UTF8(z);
   107635       }
   107636       sqlite3_result_int(context, len);
   107637       break;
   107638     }
   107639     default: {
   107640       sqlite3_result_null(context);
   107641       break;
   107642     }
   107643   }
   107644 }
   107645 
   107646 /*
   107647 ** Implementation of the abs() function.
   107648 **
   107649 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
   107650 ** the numeric argument X.
   107651 */
   107652 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   107653   assert( argc==1 );
   107654   UNUSED_PARAMETER(argc);
   107655   switch( sqlite3_value_type(argv[0]) ){
   107656     case SQLITE_INTEGER: {
   107657       i64 iVal = sqlite3_value_int64(argv[0]);
   107658       if( iVal<0 ){
   107659         if( iVal==SMALLEST_INT64 ){
   107660           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
   107661           ** then abs(X) throws an integer overflow error since there is no
   107662           ** equivalent positive 64-bit two complement value. */
   107663           sqlite3_result_error(context, "integer overflow", -1);
   107664           return;
   107665         }
   107666         iVal = -iVal;
   107667       }
   107668       sqlite3_result_int64(context, iVal);
   107669       break;
   107670     }
   107671     case SQLITE_NULL: {
   107672       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
   107673       sqlite3_result_null(context);
   107674       break;
   107675     }
   107676     default: {
   107677       /* Because sqlite3_value_double() returns 0.0 if the argument is not
   107678       ** something that can be converted into a number, we have:
   107679       ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
   107680       ** that cannot be converted to a numeric value.
   107681       */
   107682       double rVal = sqlite3_value_double(argv[0]);
   107683       if( rVal<0 ) rVal = -rVal;
   107684       sqlite3_result_double(context, rVal);
   107685       break;
   107686     }
   107687   }
   107688 }
   107689 
   107690 /*
   107691 ** Implementation of the instr() function.
   107692 **
   107693 ** instr(haystack,needle) finds the first occurrence of needle
   107694 ** in haystack and returns the number of previous characters plus 1,
   107695 ** or 0 if needle does not occur within haystack.
   107696 **
   107697 ** If both haystack and needle are BLOBs, then the result is one more than
   107698 ** the number of bytes in haystack prior to the first occurrence of needle,
   107699 ** or 0 if needle never occurs in haystack.
   107700 */
   107701 static void instrFunc(
   107702   sqlite3_context *context,
   107703   int argc,
   107704   sqlite3_value **argv
   107705 ){
   107706   const unsigned char *zHaystack;
   107707   const unsigned char *zNeedle;
   107708   int nHaystack;
   107709   int nNeedle;
   107710   int typeHaystack, typeNeedle;
   107711   int N = 1;
   107712   int isText;
   107713 
   107714   UNUSED_PARAMETER(argc);
   107715   typeHaystack = sqlite3_value_type(argv[0]);
   107716   typeNeedle = sqlite3_value_type(argv[1]);
   107717   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
   107718   nHaystack = sqlite3_value_bytes(argv[0]);
   107719   nNeedle = sqlite3_value_bytes(argv[1]);
   107720   if( nNeedle>0 ){
   107721     if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
   107722       zHaystack = sqlite3_value_blob(argv[0]);
   107723       zNeedle = sqlite3_value_blob(argv[1]);
   107724       isText = 0;
   107725     }else{
   107726       zHaystack = sqlite3_value_text(argv[0]);
   107727       zNeedle = sqlite3_value_text(argv[1]);
   107728       isText = 1;
   107729     }
   107730     if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
   107731     while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
   107732       N++;
   107733       do{
   107734         nHaystack--;
   107735         zHaystack++;
   107736       }while( isText && (zHaystack[0]&0xc0)==0x80 );
   107737     }
   107738     if( nNeedle>nHaystack ) N = 0;
   107739   }
   107740   sqlite3_result_int(context, N);
   107741 }
   107742 
   107743 /*
   107744 ** Implementation of the printf() function.
   107745 */
   107746 static void printfFunc(
   107747   sqlite3_context *context,
   107748   int argc,
   107749   sqlite3_value **argv
   107750 ){
   107751   PrintfArguments x;
   107752   StrAccum str;
   107753   const char *zFormat;
   107754   int n;
   107755   sqlite3 *db = sqlite3_context_db_handle(context);
   107756 
   107757   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   107758     x.nArg = argc-1;
   107759     x.nUsed = 0;
   107760     x.apArg = argv+1;
   107761     sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
   107762     str.printfFlags = SQLITE_PRINTF_SQLFUNC;
   107763     sqlite3XPrintf(&str, zFormat, &x);
   107764     n = str.nChar;
   107765     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
   107766                         SQLITE_DYNAMIC);
   107767   }
   107768 }
   107769 
   107770 /*
   107771 ** Implementation of the substr() function.
   107772 **
   107773 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   107774 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   107775 ** of x.  If x is text, then we actually count UTF-8 characters.
   107776 ** If x is a blob, then we count bytes.
   107777 **
   107778 ** If p1 is negative, then we begin abs(p1) from the end of x[].
   107779 **
   107780 ** If p2 is negative, return the p2 characters preceding p1.
   107781 */
   107782 static void substrFunc(
   107783   sqlite3_context *context,
   107784   int argc,
   107785   sqlite3_value **argv
   107786 ){
   107787   const unsigned char *z;
   107788   const unsigned char *z2;
   107789   int len;
   107790   int p0type;
   107791   i64 p1, p2;
   107792   int negP2 = 0;
   107793 
   107794   assert( argc==3 || argc==2 );
   107795   if( sqlite3_value_type(argv[1])==SQLITE_NULL
   107796    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
   107797   ){
   107798     return;
   107799   }
   107800   p0type = sqlite3_value_type(argv[0]);
   107801   p1 = sqlite3_value_int(argv[1]);
   107802   if( p0type==SQLITE_BLOB ){
   107803     len = sqlite3_value_bytes(argv[0]);
   107804     z = sqlite3_value_blob(argv[0]);
   107805     if( z==0 ) return;
   107806     assert( len==sqlite3_value_bytes(argv[0]) );
   107807   }else{
   107808     z = sqlite3_value_text(argv[0]);
   107809     if( z==0 ) return;
   107810     len = 0;
   107811     if( p1<0 ){
   107812       for(z2=z; *z2; len++){
   107813         SQLITE_SKIP_UTF8(z2);
   107814       }
   107815     }
   107816   }
   107817 #ifdef SQLITE_SUBSTR_COMPATIBILITY
   107818   /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
   107819   ** as substr(X,1,N) - it returns the first N characters of X.  This
   107820   ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
   107821   ** from 2009-02-02 for compatibility of applications that exploited the
   107822   ** old buggy behavior. */
   107823   if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
   107824 #endif
   107825   if( argc==3 ){
   107826     p2 = sqlite3_value_int(argv[2]);
   107827     if( p2<0 ){
   107828       p2 = -p2;
   107829       negP2 = 1;
   107830     }
   107831   }else{
   107832     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   107833   }
   107834   if( p1<0 ){
   107835     p1 += len;
   107836     if( p1<0 ){
   107837       p2 += p1;
   107838       if( p2<0 ) p2 = 0;
   107839       p1 = 0;
   107840     }
   107841   }else if( p1>0 ){
   107842     p1--;
   107843   }else if( p2>0 ){
   107844     p2--;
   107845   }
   107846   if( negP2 ){
   107847     p1 -= p2;
   107848     if( p1<0 ){
   107849       p2 += p1;
   107850       p1 = 0;
   107851     }
   107852   }
   107853   assert( p1>=0 && p2>=0 );
   107854   if( p0type!=SQLITE_BLOB ){
   107855     while( *z && p1 ){
   107856       SQLITE_SKIP_UTF8(z);
   107857       p1--;
   107858     }
   107859     for(z2=z; *z2 && p2; p2--){
   107860       SQLITE_SKIP_UTF8(z2);
   107861     }
   107862     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
   107863                           SQLITE_UTF8);
   107864   }else{
   107865     if( p1+p2>len ){
   107866       p2 = len-p1;
   107867       if( p2<0 ) p2 = 0;
   107868     }
   107869     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
   107870   }
   107871 }
   107872 
   107873 /*
   107874 ** Implementation of the round() function
   107875 */
   107876 #ifndef SQLITE_OMIT_FLOATING_POINT
   107877 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   107878   int n = 0;
   107879   double r;
   107880   char *zBuf;
   107881   assert( argc==1 || argc==2 );
   107882   if( argc==2 ){
   107883     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   107884     n = sqlite3_value_int(argv[1]);
   107885     if( n>30 ) n = 30;
   107886     if( n<0 ) n = 0;
   107887   }
   107888   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   107889   r = sqlite3_value_double(argv[0]);
   107890   /* If Y==0 and X will fit in a 64-bit int,
   107891   ** handle the rounding directly,
   107892   ** otherwise use printf.
   107893   */
   107894   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
   107895     r = (double)((sqlite_int64)(r+0.5));
   107896   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
   107897     r = -(double)((sqlite_int64)((-r)+0.5));
   107898   }else{
   107899     zBuf = sqlite3_mprintf("%.*f",n,r);
   107900     if( zBuf==0 ){
   107901       sqlite3_result_error_nomem(context);
   107902       return;
   107903     }
   107904     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
   107905     sqlite3_free(zBuf);
   107906   }
   107907   sqlite3_result_double(context, r);
   107908 }
   107909 #endif
   107910 
   107911 /*
   107912 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
   107913 ** allocation fails, call sqlite3_result_error_nomem() to notify
   107914 ** the database handle that malloc() has failed and return NULL.
   107915 ** If nByte is larger than the maximum string or blob length, then
   107916 ** raise an SQLITE_TOOBIG exception and return NULL.
   107917 */
   107918 static void *contextMalloc(sqlite3_context *context, i64 nByte){
   107919   char *z;
   107920   sqlite3 *db = sqlite3_context_db_handle(context);
   107921   assert( nByte>0 );
   107922   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
   107923   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   107924   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   107925     sqlite3_result_error_toobig(context);
   107926     z = 0;
   107927   }else{
   107928     z = sqlite3Malloc(nByte);
   107929     if( !z ){
   107930       sqlite3_result_error_nomem(context);
   107931     }
   107932   }
   107933   return z;
   107934 }
   107935 
   107936 /*
   107937 ** Implementation of the upper() and lower() SQL functions.
   107938 */
   107939 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   107940   char *z1;
   107941   const char *z2;
   107942   int i, n;
   107943   UNUSED_PARAMETER(argc);
   107944   z2 = (char*)sqlite3_value_text(argv[0]);
   107945   n = sqlite3_value_bytes(argv[0]);
   107946   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   107947   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   107948   if( z2 ){
   107949     z1 = contextMalloc(context, ((i64)n)+1);
   107950     if( z1 ){
   107951       for(i=0; i<n; i++){
   107952         z1[i] = (char)sqlite3Toupper(z2[i]);
   107953       }
   107954       sqlite3_result_text(context, z1, n, sqlite3_free);
   107955     }
   107956   }
   107957 }
   107958 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   107959   char *z1;
   107960   const char *z2;
   107961   int i, n;
   107962   UNUSED_PARAMETER(argc);
   107963   z2 = (char*)sqlite3_value_text(argv[0]);
   107964   n = sqlite3_value_bytes(argv[0]);
   107965   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   107966   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   107967   if( z2 ){
   107968     z1 = contextMalloc(context, ((i64)n)+1);
   107969     if( z1 ){
   107970       for(i=0; i<n; i++){
   107971         z1[i] = sqlite3Tolower(z2[i]);
   107972       }
   107973       sqlite3_result_text(context, z1, n, sqlite3_free);
   107974     }
   107975   }
   107976 }
   107977 
   107978 /*
   107979 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
   107980 ** as VDBE code so that unused argument values do not have to be computed.
   107981 ** However, we still need some kind of function implementation for this
   107982 ** routines in the function table.  The noopFunc macro provides this.
   107983 ** noopFunc will never be called so it doesn't matter what the implementation
   107984 ** is.  We might as well use the "version()" function as a substitute.
   107985 */
   107986 #define noopFunc versionFunc   /* Substitute function - never called */
   107987 
   107988 /*
   107989 ** Implementation of random().  Return a random integer.
   107990 */
   107991 static void randomFunc(
   107992   sqlite3_context *context,
   107993   int NotUsed,
   107994   sqlite3_value **NotUsed2
   107995 ){
   107996   sqlite_int64 r;
   107997   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   107998   sqlite3_randomness(sizeof(r), &r);
   107999   if( r<0 ){
   108000     /* We need to prevent a random number of 0x8000000000000000
   108001     ** (or -9223372036854775808) since when you do abs() of that
   108002     ** number of you get the same value back again.  To do this
   108003     ** in a way that is testable, mask the sign bit off of negative
   108004     ** values, resulting in a positive value.  Then take the
   108005     ** 2s complement of that positive value.  The end result can
   108006     ** therefore be no less than -9223372036854775807.
   108007     */
   108008     r = -(r & LARGEST_INT64);
   108009   }
   108010   sqlite3_result_int64(context, r);
   108011 }
   108012 
   108013 /*
   108014 ** Implementation of randomblob(N).  Return a random blob
   108015 ** that is N bytes long.
   108016 */
   108017 static void randomBlob(
   108018   sqlite3_context *context,
   108019   int argc,
   108020   sqlite3_value **argv
   108021 ){
   108022   int n;
   108023   unsigned char *p;
   108024   assert( argc==1 );
   108025   UNUSED_PARAMETER(argc);
   108026   n = sqlite3_value_int(argv[0]);
   108027   if( n<1 ){
   108028     n = 1;
   108029   }
   108030   p = contextMalloc(context, n);
   108031   if( p ){
   108032     sqlite3_randomness(n, p);
   108033     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   108034   }
   108035 }
   108036 
   108037 /*
   108038 ** Implementation of the last_insert_rowid() SQL function.  The return
   108039 ** value is the same as the sqlite3_last_insert_rowid() API function.
   108040 */
   108041 static void last_insert_rowid(
   108042   sqlite3_context *context,
   108043   int NotUsed,
   108044   sqlite3_value **NotUsed2
   108045 ){
   108046   sqlite3 *db = sqlite3_context_db_handle(context);
   108047   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   108048   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
   108049   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
   108050   ** function. */
   108051   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   108052 }
   108053 
   108054 /*
   108055 ** Implementation of the changes() SQL function.
   108056 **
   108057 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
   108058 ** around the sqlite3_changes() C/C++ function and hence follows the same
   108059 ** rules for counting changes.
   108060 */
   108061 static void changes(
   108062   sqlite3_context *context,
   108063   int NotUsed,
   108064   sqlite3_value **NotUsed2
   108065 ){
   108066   sqlite3 *db = sqlite3_context_db_handle(context);
   108067   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   108068   sqlite3_result_int(context, sqlite3_changes(db));
   108069 }
   108070 
   108071 /*
   108072 ** Implementation of the total_changes() SQL function.  The return value is
   108073 ** the same as the sqlite3_total_changes() API function.
   108074 */
   108075 static void total_changes(
   108076   sqlite3_context *context,
   108077   int NotUsed,
   108078   sqlite3_value **NotUsed2
   108079 ){
   108080   sqlite3 *db = sqlite3_context_db_handle(context);
   108081   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   108082   /* IMP: R-52756-41993 This function is a wrapper around the
   108083   ** sqlite3_total_changes() C/C++ interface. */
   108084   sqlite3_result_int(context, sqlite3_total_changes(db));
   108085 }
   108086 
   108087 /*
   108088 ** A structure defining how to do GLOB-style comparisons.
   108089 */
   108090 struct compareInfo {
   108091   u8 matchAll;          /* "*" or "%" */
   108092   u8 matchOne;          /* "?" or "_" */
   108093   u8 matchSet;          /* "[" or 0 */
   108094   u8 noCase;            /* true to ignore case differences */
   108095 };
   108096 
   108097 /*
   108098 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   108099 ** character is exactly one byte in size.  Also, provde the Utf8Read()
   108100 ** macro for fast reading of the next character in the common case where
   108101 ** the next character is ASCII.
   108102 */
   108103 #if defined(SQLITE_EBCDIC)
   108104 # define sqlite3Utf8Read(A)        (*((*A)++))
   108105 # define Utf8Read(A)               (*(A++))
   108106 #else
   108107 # define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
   108108 #endif
   108109 
   108110 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   108111 /* The correct SQL-92 behavior is for the LIKE operator to ignore
   108112 ** case.  Thus  'a' LIKE 'A' would be true. */
   108113 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   108114 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   108115 ** is case sensitive causing 'a' LIKE 'A' to be false */
   108116 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   108117 
   108118 /*
   108119 ** Possible error returns from patternMatch()
   108120 */
   108121 #define SQLITE_MATCH             0
   108122 #define SQLITE_NOMATCH           1
   108123 #define SQLITE_NOWILDCARDMATCH   2
   108124 
   108125 /*
   108126 ** Compare two UTF-8 strings for equality where the first string is
   108127 ** a GLOB or LIKE expression.  Return values:
   108128 **
   108129 **    SQLITE_MATCH:            Match
   108130 **    SQLITE_NOMATCH:          No match
   108131 **    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
   108132 **
   108133 ** Globbing rules:
   108134 **
   108135 **      '*'       Matches any sequence of zero or more characters.
   108136 **
   108137 **      '?'       Matches exactly one character.
   108138 **
   108139 **     [...]      Matches one character from the enclosed list of
   108140 **                characters.
   108141 **
   108142 **     [^...]     Matches one character not in the enclosed list.
   108143 **
   108144 ** With the [...] and [^...] matching, a ']' character can be included
   108145 ** in the list by making it the first character after '[' or '^'.  A
   108146 ** range of characters can be specified using '-'.  Example:
   108147 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   108148 ** it the last character in the list.
   108149 **
   108150 ** Like matching rules:
   108151 **
   108152 **      '%'       Matches any sequence of zero or more characters
   108153 **
   108154 ***     '_'       Matches any one character
   108155 **
   108156 **      Ec        Where E is the "esc" character and c is any other
   108157 **                character, including '%', '_', and esc, match exactly c.
   108158 **
   108159 ** The comments within this routine usually assume glob matching.
   108160 **
   108161 ** This routine is usually quick, but can be N**2 in the worst case.
   108162 */
   108163 static int patternCompare(
   108164   const u8 *zPattern,              /* The glob pattern */
   108165   const u8 *zString,               /* The string to compare against the glob */
   108166   const struct compareInfo *pInfo, /* Information about how to do the compare */
   108167   u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
   108168 ){
   108169   u32 c, c2;                       /* Next pattern and input string chars */
   108170   u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
   108171   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
   108172   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
   108173   const u8 *zEscaped = 0;          /* One past the last escaped input char */
   108174 
   108175   while( (c = Utf8Read(zPattern))!=0 ){
   108176     if( c==matchAll ){  /* Match "*" */
   108177       /* Skip over multiple "*" characters in the pattern.  If there
   108178       ** are also "?" characters, skip those as well, but consume a
   108179       ** single character of the input string for each "?" skipped */
   108180       while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
   108181         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
   108182           return SQLITE_NOWILDCARDMATCH;
   108183         }
   108184       }
   108185       if( c==0 ){
   108186         return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
   108187       }else if( c==matchOther ){
   108188         if( pInfo->matchSet==0 ){
   108189           c = sqlite3Utf8Read(&zPattern);
   108190           if( c==0 ) return SQLITE_NOWILDCARDMATCH;
   108191         }else{
   108192           /* "[...]" immediately follows the "*".  We have to do a slow
   108193           ** recursive search in this case, but it is an unusual case. */
   108194           assert( matchOther<0x80 );  /* '[' is a single-byte character */
   108195           while( *zString ){
   108196             int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
   108197             if( bMatch!=SQLITE_NOMATCH ) return bMatch;
   108198             SQLITE_SKIP_UTF8(zString);
   108199           }
   108200           return SQLITE_NOWILDCARDMATCH;
   108201         }
   108202       }
   108203 
   108204       /* At this point variable c contains the first character of the
   108205       ** pattern string past the "*".  Search in the input string for the
   108206       ** first matching character and recursively continue the match from
   108207       ** that point.
   108208       **
   108209       ** For a case-insensitive search, set variable cx to be the same as
   108210       ** c but in the other case and search the input string for either
   108211       ** c or cx.
   108212       */
   108213       if( c<=0x80 ){
   108214         char zStop[3];
   108215         int bMatch;
   108216         if( noCase ){
   108217           zStop[0] = sqlite3Toupper(c);
   108218           zStop[1] = sqlite3Tolower(c);
   108219           zStop[2] = 0;
   108220         }else{
   108221           zStop[0] = c;
   108222           zStop[1] = 0;
   108223         }
   108224         while(1){
   108225           zString += strcspn((const char*)zString, zStop);
   108226           if( zString[0]==0 ) break;
   108227           zString++;
   108228           bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
   108229           if( bMatch!=SQLITE_NOMATCH ) return bMatch;
   108230         }
   108231       }else{
   108232         int bMatch;
   108233         while( (c2 = Utf8Read(zString))!=0 ){
   108234           if( c2!=c ) continue;
   108235           bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
   108236           if( bMatch!=SQLITE_NOMATCH ) return bMatch;
   108237         }
   108238       }
   108239       return SQLITE_NOWILDCARDMATCH;
   108240     }
   108241     if( c==matchOther ){
   108242       if( pInfo->matchSet==0 ){
   108243         c = sqlite3Utf8Read(&zPattern);
   108244         if( c==0 ) return SQLITE_NOMATCH;
   108245         zEscaped = zPattern;
   108246       }else{
   108247         u32 prior_c = 0;
   108248         int seen = 0;
   108249         int invert = 0;
   108250         c = sqlite3Utf8Read(&zString);
   108251         if( c==0 ) return SQLITE_NOMATCH;
   108252         c2 = sqlite3Utf8Read(&zPattern);
   108253         if( c2=='^' ){
   108254           invert = 1;
   108255           c2 = sqlite3Utf8Read(&zPattern);
   108256         }
   108257         if( c2==']' ){
   108258           if( c==']' ) seen = 1;
   108259           c2 = sqlite3Utf8Read(&zPattern);
   108260         }
   108261         while( c2 && c2!=']' ){
   108262           if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   108263             c2 = sqlite3Utf8Read(&zPattern);
   108264             if( c>=prior_c && c<=c2 ) seen = 1;
   108265             prior_c = 0;
   108266           }else{
   108267             if( c==c2 ){
   108268               seen = 1;
   108269             }
   108270             prior_c = c2;
   108271           }
   108272           c2 = sqlite3Utf8Read(&zPattern);
   108273         }
   108274         if( c2==0 || (seen ^ invert)==0 ){
   108275           return SQLITE_NOMATCH;
   108276         }
   108277         continue;
   108278       }
   108279     }
   108280     c2 = Utf8Read(zString);
   108281     if( c==c2 ) continue;
   108282     if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
   108283       continue;
   108284     }
   108285     if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
   108286     return SQLITE_NOMATCH;
   108287   }
   108288   return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
   108289 }
   108290 
   108291 /*
   108292 ** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
   108293 ** non-zero if there is no match.
   108294 */
   108295 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
   108296   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
   108297 }
   108298 
   108299 /*
   108300 ** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
   108301 ** a miss - like strcmp().
   108302 */
   108303 SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
   108304   return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
   108305 }
   108306 
   108307 /*
   108308 ** Count the number of times that the LIKE operator (or GLOB which is
   108309 ** just a variation of LIKE) gets called.  This is used for testing
   108310 ** only.
   108311 */
   108312 #ifdef SQLITE_TEST
   108313 SQLITE_API int sqlite3_like_count = 0;
   108314 #endif
   108315 
   108316 
   108317 /*
   108318 ** Implementation of the like() SQL function.  This function implements
   108319 ** the build-in LIKE operator.  The first argument to the function is the
   108320 ** pattern and the second argument is the string.  So, the SQL statements:
   108321 **
   108322 **       A LIKE B
   108323 **
   108324 ** is implemented as like(B,A).
   108325 **
   108326 ** This same function (with a different compareInfo structure) computes
   108327 ** the GLOB operator.
   108328 */
   108329 static void likeFunc(
   108330   sqlite3_context *context,
   108331   int argc,
   108332   sqlite3_value **argv
   108333 ){
   108334   const unsigned char *zA, *zB;
   108335   u32 escape;
   108336   int nPat;
   108337   sqlite3 *db = sqlite3_context_db_handle(context);
   108338   struct compareInfo *pInfo = sqlite3_user_data(context);
   108339 
   108340 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   108341   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
   108342    || sqlite3_value_type(argv[1])==SQLITE_BLOB
   108343   ){
   108344 #ifdef SQLITE_TEST
   108345     sqlite3_like_count++;
   108346 #endif
   108347     sqlite3_result_int(context, 0);
   108348     return;
   108349   }
   108350 #endif
   108351   zB = sqlite3_value_text(argv[0]);
   108352   zA = sqlite3_value_text(argv[1]);
   108353 
   108354   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   108355   ** of deep recursion and N*N behavior in patternCompare().
   108356   */
   108357   nPat = sqlite3_value_bytes(argv[0]);
   108358   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
   108359   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
   108360   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   108361     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   108362     return;
   108363   }
   108364   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   108365 
   108366   if( argc==3 ){
   108367     /* The escape character string must consist of a single UTF-8 character.
   108368     ** Otherwise, return an error.
   108369     */
   108370     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   108371     if( zEsc==0 ) return;
   108372     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   108373       sqlite3_result_error(context,
   108374           "ESCAPE expression must be a single character", -1);
   108375       return;
   108376     }
   108377     escape = sqlite3Utf8Read(&zEsc);
   108378   }else{
   108379     escape = pInfo->matchSet;
   108380   }
   108381   if( zA && zB ){
   108382 #ifdef SQLITE_TEST
   108383     sqlite3_like_count++;
   108384 #endif
   108385     sqlite3_result_int(context,
   108386                       patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
   108387   }
   108388 }
   108389 
   108390 /*
   108391 ** Implementation of the NULLIF(x,y) function.  The result is the first
   108392 ** argument if the arguments are different.  The result is NULL if the
   108393 ** arguments are equal to each other.
   108394 */
   108395 static void nullifFunc(
   108396   sqlite3_context *context,
   108397   int NotUsed,
   108398   sqlite3_value **argv
   108399 ){
   108400   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   108401   UNUSED_PARAMETER(NotUsed);
   108402   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   108403     sqlite3_result_value(context, argv[0]);
   108404   }
   108405 }
   108406 
   108407 /*
   108408 ** Implementation of the sqlite_version() function.  The result is the version
   108409 ** of the SQLite library that is running.
   108410 */
   108411 static void versionFunc(
   108412   sqlite3_context *context,
   108413   int NotUsed,
   108414   sqlite3_value **NotUsed2
   108415 ){
   108416   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   108417   /* IMP: R-48699-48617 This function is an SQL wrapper around the
   108418   ** sqlite3_libversion() C-interface. */
   108419   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
   108420 }
   108421 
   108422 /*
   108423 ** Implementation of the sqlite_source_id() function. The result is a string
   108424 ** that identifies the particular version of the source code used to build
   108425 ** SQLite.
   108426 */
   108427 static void sourceidFunc(
   108428   sqlite3_context *context,
   108429   int NotUsed,
   108430   sqlite3_value **NotUsed2
   108431 ){
   108432   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   108433   /* IMP: R-24470-31136 This function is an SQL wrapper around the
   108434   ** sqlite3_sourceid() C interface. */
   108435   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
   108436 }
   108437 
   108438 /*
   108439 ** Implementation of the sqlite_log() function.  This is a wrapper around
   108440 ** sqlite3_log().  The return value is NULL.  The function exists purely for
   108441 ** its side-effects.
   108442 */
   108443 static void errlogFunc(
   108444   sqlite3_context *context,
   108445   int argc,
   108446   sqlite3_value **argv
   108447 ){
   108448   UNUSED_PARAMETER(argc);
   108449   UNUSED_PARAMETER(context);
   108450   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
   108451 }
   108452 
   108453 /*
   108454 ** Implementation of the sqlite_compileoption_used() function.
   108455 ** The result is an integer that identifies if the compiler option
   108456 ** was used to build SQLite.
   108457 */
   108458 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   108459 static void compileoptionusedFunc(
   108460   sqlite3_context *context,
   108461   int argc,
   108462   sqlite3_value **argv
   108463 ){
   108464   const char *zOptName;
   108465   assert( argc==1 );
   108466   UNUSED_PARAMETER(argc);
   108467   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
   108468   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
   108469   ** function.
   108470   */
   108471   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   108472     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
   108473   }
   108474 }
   108475 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   108476 
   108477 /*
   108478 ** Implementation of the sqlite_compileoption_get() function.
   108479 ** The result is a string that identifies the compiler options
   108480 ** used to build SQLite.
   108481 */
   108482 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   108483 static void compileoptiongetFunc(
   108484   sqlite3_context *context,
   108485   int argc,
   108486   sqlite3_value **argv
   108487 ){
   108488   int n;
   108489   assert( argc==1 );
   108490   UNUSED_PARAMETER(argc);
   108491   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
   108492   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
   108493   */
   108494   n = sqlite3_value_int(argv[0]);
   108495   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
   108496 }
   108497 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   108498 
   108499 /* Array for converting from half-bytes (nybbles) into ASCII hex
   108500 ** digits. */
   108501 static const char hexdigits[] = {
   108502   '0', '1', '2', '3', '4', '5', '6', '7',
   108503   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   108504 };
   108505 
   108506 /*
   108507 ** Implementation of the QUOTE() function.  This function takes a single
   108508 ** argument.  If the argument is numeric, the return value is the same as
   108509 ** the argument.  If the argument is NULL, the return value is the string
   108510 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
   108511 ** single-quote escapes.
   108512 */
   108513 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   108514   assert( argc==1 );
   108515   UNUSED_PARAMETER(argc);
   108516   switch( sqlite3_value_type(argv[0]) ){
   108517     case SQLITE_FLOAT: {
   108518       double r1, r2;
   108519       char zBuf[50];
   108520       r1 = sqlite3_value_double(argv[0]);
   108521       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
   108522       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
   108523       if( r1!=r2 ){
   108524         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
   108525       }
   108526       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   108527       break;
   108528     }
   108529     case SQLITE_INTEGER: {
   108530       sqlite3_result_value(context, argv[0]);
   108531       break;
   108532     }
   108533     case SQLITE_BLOB: {
   108534       char *zText = 0;
   108535       char const *zBlob = sqlite3_value_blob(argv[0]);
   108536       int nBlob = sqlite3_value_bytes(argv[0]);
   108537       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   108538       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
   108539       if( zText ){
   108540         int i;
   108541         for(i=0; i<nBlob; i++){
   108542           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   108543           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   108544         }
   108545         zText[(nBlob*2)+2] = '\'';
   108546         zText[(nBlob*2)+3] = '\0';
   108547         zText[0] = 'X';
   108548         zText[1] = '\'';
   108549         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   108550         sqlite3_free(zText);
   108551       }
   108552       break;
   108553     }
   108554     case SQLITE_TEXT: {
   108555       int i,j;
   108556       u64 n;
   108557       const unsigned char *zArg = sqlite3_value_text(argv[0]);
   108558       char *z;
   108559 
   108560       if( zArg==0 ) return;
   108561       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   108562       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   108563       if( z ){
   108564         z[0] = '\'';
   108565         for(i=0, j=1; zArg[i]; i++){
   108566           z[j++] = zArg[i];
   108567           if( zArg[i]=='\'' ){
   108568             z[j++] = '\'';
   108569           }
   108570         }
   108571         z[j++] = '\'';
   108572         z[j] = 0;
   108573         sqlite3_result_text(context, z, j, sqlite3_free);
   108574       }
   108575       break;
   108576     }
   108577     default: {
   108578       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
   108579       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   108580       break;
   108581     }
   108582   }
   108583 }
   108584 
   108585 /*
   108586 ** The unicode() function.  Return the integer unicode code-point value
   108587 ** for the first character of the input string.
   108588 */
   108589 static void unicodeFunc(
   108590   sqlite3_context *context,
   108591   int argc,
   108592   sqlite3_value **argv
   108593 ){
   108594   const unsigned char *z = sqlite3_value_text(argv[0]);
   108595   (void)argc;
   108596   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
   108597 }
   108598 
   108599 /*
   108600 ** The char() function takes zero or more arguments, each of which is
   108601 ** an integer.  It constructs a string where each character of the string
   108602 ** is the unicode character for the corresponding integer argument.
   108603 */
   108604 static void charFunc(
   108605   sqlite3_context *context,
   108606   int argc,
   108607   sqlite3_value **argv
   108608 ){
   108609   unsigned char *z, *zOut;
   108610   int i;
   108611   zOut = z = sqlite3_malloc64( argc*4+1 );
   108612   if( z==0 ){
   108613     sqlite3_result_error_nomem(context);
   108614     return;
   108615   }
   108616   for(i=0; i<argc; i++){
   108617     sqlite3_int64 x;
   108618     unsigned c;
   108619     x = sqlite3_value_int64(argv[i]);
   108620     if( x<0 || x>0x10ffff ) x = 0xfffd;
   108621     c = (unsigned)(x & 0x1fffff);
   108622     if( c<0x00080 ){
   108623       *zOut++ = (u8)(c&0xFF);
   108624     }else if( c<0x00800 ){
   108625       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
   108626       *zOut++ = 0x80 + (u8)(c & 0x3F);
   108627     }else if( c<0x10000 ){
   108628       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
   108629       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
   108630       *zOut++ = 0x80 + (u8)(c & 0x3F);
   108631     }else{
   108632       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
   108633       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
   108634       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
   108635       *zOut++ = 0x80 + (u8)(c & 0x3F);
   108636     }                                                    \
   108637   }
   108638   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
   108639 }
   108640 
   108641 /*
   108642 ** The hex() function.  Interpret the argument as a blob.  Return
   108643 ** a hexadecimal rendering as text.
   108644 */
   108645 static void hexFunc(
   108646   sqlite3_context *context,
   108647   int argc,
   108648   sqlite3_value **argv
   108649 ){
   108650   int i, n;
   108651   const unsigned char *pBlob;
   108652   char *zHex, *z;
   108653   assert( argc==1 );
   108654   UNUSED_PARAMETER(argc);
   108655   pBlob = sqlite3_value_blob(argv[0]);
   108656   n = sqlite3_value_bytes(argv[0]);
   108657   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   108658   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   108659   if( zHex ){
   108660     for(i=0; i<n; i++, pBlob++){
   108661       unsigned char c = *pBlob;
   108662       *(z++) = hexdigits[(c>>4)&0xf];
   108663       *(z++) = hexdigits[c&0xf];
   108664     }
   108665     *z = 0;
   108666     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   108667   }
   108668 }
   108669 
   108670 /*
   108671 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   108672 */
   108673 static void zeroblobFunc(
   108674   sqlite3_context *context,
   108675   int argc,
   108676   sqlite3_value **argv
   108677 ){
   108678   i64 n;
   108679   int rc;
   108680   assert( argc==1 );
   108681   UNUSED_PARAMETER(argc);
   108682   n = sqlite3_value_int64(argv[0]);
   108683   if( n<0 ) n = 0;
   108684   rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
   108685   if( rc ){
   108686     sqlite3_result_error_code(context, rc);
   108687   }
   108688 }
   108689 
   108690 /*
   108691 ** The replace() function.  Three arguments are all strings: call
   108692 ** them A, B, and C. The result is also a string which is derived
   108693 ** from A by replacing every occurrence of B with C.  The match
   108694 ** must be exact.  Collating sequences are not used.
   108695 */
   108696 static void replaceFunc(
   108697   sqlite3_context *context,
   108698   int argc,
   108699   sqlite3_value **argv
   108700 ){
   108701   const unsigned char *zStr;        /* The input string A */
   108702   const unsigned char *zPattern;    /* The pattern string B */
   108703   const unsigned char *zRep;        /* The replacement string C */
   108704   unsigned char *zOut;              /* The output */
   108705   int nStr;                /* Size of zStr */
   108706   int nPattern;            /* Size of zPattern */
   108707   int nRep;                /* Size of zRep */
   108708   i64 nOut;                /* Maximum size of zOut */
   108709   int loopLimit;           /* Last zStr[] that might match zPattern[] */
   108710   int i, j;                /* Loop counters */
   108711 
   108712   assert( argc==3 );
   108713   UNUSED_PARAMETER(argc);
   108714   zStr = sqlite3_value_text(argv[0]);
   108715   if( zStr==0 ) return;
   108716   nStr = sqlite3_value_bytes(argv[0]);
   108717   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   108718   zPattern = sqlite3_value_text(argv[1]);
   108719   if( zPattern==0 ){
   108720     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
   108721             || sqlite3_context_db_handle(context)->mallocFailed );
   108722     return;
   108723   }
   108724   if( zPattern[0]==0 ){
   108725     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
   108726     sqlite3_result_value(context, argv[0]);
   108727     return;
   108728   }
   108729   nPattern = sqlite3_value_bytes(argv[1]);
   108730   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   108731   zRep = sqlite3_value_text(argv[2]);
   108732   if( zRep==0 ) return;
   108733   nRep = sqlite3_value_bytes(argv[2]);
   108734   assert( zRep==sqlite3_value_text(argv[2]) );
   108735   nOut = nStr + 1;
   108736   assert( nOut<SQLITE_MAX_LENGTH );
   108737   zOut = contextMalloc(context, (i64)nOut);
   108738   if( zOut==0 ){
   108739     return;
   108740   }
   108741   loopLimit = nStr - nPattern;
   108742   for(i=j=0; i<=loopLimit; i++){
   108743     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   108744       zOut[j++] = zStr[i];
   108745     }else{
   108746       u8 *zOld;
   108747       sqlite3 *db = sqlite3_context_db_handle(context);
   108748       nOut += nRep - nPattern;
   108749       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
   108750       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
   108751       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   108752         sqlite3_result_error_toobig(context);
   108753         sqlite3_free(zOut);
   108754         return;
   108755       }
   108756       zOld = zOut;
   108757       zOut = sqlite3_realloc64(zOut, (int)nOut);
   108758       if( zOut==0 ){
   108759         sqlite3_result_error_nomem(context);
   108760         sqlite3_free(zOld);
   108761         return;
   108762       }
   108763       memcpy(&zOut[j], zRep, nRep);
   108764       j += nRep;
   108765       i += nPattern-1;
   108766     }
   108767   }
   108768   assert( j+nStr-i+1==nOut );
   108769   memcpy(&zOut[j], &zStr[i], nStr-i);
   108770   j += nStr - i;
   108771   assert( j<=nOut );
   108772   zOut[j] = 0;
   108773   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   108774 }
   108775 
   108776 /*
   108777 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   108778 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   108779 */
   108780 static void trimFunc(
   108781   sqlite3_context *context,
   108782   int argc,
   108783   sqlite3_value **argv
   108784 ){
   108785   const unsigned char *zIn;         /* Input string */
   108786   const unsigned char *zCharSet;    /* Set of characters to trim */
   108787   int nIn;                          /* Number of bytes in input */
   108788   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   108789   int i;                            /* Loop counter */
   108790   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
   108791   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   108792   int nChar;                        /* Number of characters in zCharSet */
   108793 
   108794   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   108795     return;
   108796   }
   108797   zIn = sqlite3_value_text(argv[0]);
   108798   if( zIn==0 ) return;
   108799   nIn = sqlite3_value_bytes(argv[0]);
   108800   assert( zIn==sqlite3_value_text(argv[0]) );
   108801   if( argc==1 ){
   108802     static const unsigned char lenOne[] = { 1 };
   108803     static unsigned char * const azOne[] = { (u8*)" " };
   108804     nChar = 1;
   108805     aLen = (u8*)lenOne;
   108806     azChar = (unsigned char **)azOne;
   108807     zCharSet = 0;
   108808   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   108809     return;
   108810   }else{
   108811     const unsigned char *z;
   108812     for(z=zCharSet, nChar=0; *z; nChar++){
   108813       SQLITE_SKIP_UTF8(z);
   108814     }
   108815     if( nChar>0 ){
   108816       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   108817       if( azChar==0 ){
   108818         return;
   108819       }
   108820       aLen = (unsigned char*)&azChar[nChar];
   108821       for(z=zCharSet, nChar=0; *z; nChar++){
   108822         azChar[nChar] = (unsigned char *)z;
   108823         SQLITE_SKIP_UTF8(z);
   108824         aLen[nChar] = (u8)(z - azChar[nChar]);
   108825       }
   108826     }
   108827   }
   108828   if( nChar>0 ){
   108829     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   108830     if( flags & 1 ){
   108831       while( nIn>0 ){
   108832         int len = 0;
   108833         for(i=0; i<nChar; i++){
   108834           len = aLen[i];
   108835           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
   108836         }
   108837         if( i>=nChar ) break;
   108838         zIn += len;
   108839         nIn -= len;
   108840       }
   108841     }
   108842     if( flags & 2 ){
   108843       while( nIn>0 ){
   108844         int len = 0;
   108845         for(i=0; i<nChar; i++){
   108846           len = aLen[i];
   108847           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   108848         }
   108849         if( i>=nChar ) break;
   108850         nIn -= len;
   108851       }
   108852     }
   108853     if( zCharSet ){
   108854       sqlite3_free(azChar);
   108855     }
   108856   }
   108857   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   108858 }
   108859 
   108860 
   108861 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
   108862 /*
   108863 ** The "unknown" function is automatically substituted in place of
   108864 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
   108865 ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
   108866 ** When the "sqlite3" command-line shell is built using this functionality,
   108867 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
   108868 ** involving application-defined functions to be examined in a generic
   108869 ** sqlite3 shell.
   108870 */
   108871 static void unknownFunc(
   108872   sqlite3_context *context,
   108873   int argc,
   108874   sqlite3_value **argv
   108875 ){
   108876   /* no-op */
   108877 }
   108878 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
   108879 
   108880 
   108881 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
   108882 ** is only available if the SQLITE_SOUNDEX compile-time option is used
   108883 ** when SQLite is built.
   108884 */
   108885 #ifdef SQLITE_SOUNDEX
   108886 /*
   108887 ** Compute the soundex encoding of a word.
   108888 **
   108889 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
   108890 ** soundex encoding of the string X.
   108891 */
   108892 static void soundexFunc(
   108893   sqlite3_context *context,
   108894   int argc,
   108895   sqlite3_value **argv
   108896 ){
   108897   char zResult[8];
   108898   const u8 *zIn;
   108899   int i, j;
   108900   static const unsigned char iCode[] = {
   108901     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   108902     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   108903     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   108904     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   108905     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   108906     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   108907     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   108908     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   108909   };
   108910   assert( argc==1 );
   108911   zIn = (u8*)sqlite3_value_text(argv[0]);
   108912   if( zIn==0 ) zIn = (u8*)"";
   108913   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
   108914   if( zIn[i] ){
   108915     u8 prevcode = iCode[zIn[i]&0x7f];
   108916     zResult[0] = sqlite3Toupper(zIn[i]);
   108917     for(j=1; j<4 && zIn[i]; i++){
   108918       int code = iCode[zIn[i]&0x7f];
   108919       if( code>0 ){
   108920         if( code!=prevcode ){
   108921           prevcode = code;
   108922           zResult[j++] = code + '0';
   108923         }
   108924       }else{
   108925         prevcode = 0;
   108926       }
   108927     }
   108928     while( j<4 ){
   108929       zResult[j++] = '0';
   108930     }
   108931     zResult[j] = 0;
   108932     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   108933   }else{
   108934     /* IMP: R-64894-50321 The string "?000" is returned if the argument
   108935     ** is NULL or contains no ASCII alphabetic characters. */
   108936     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   108937   }
   108938 }
   108939 #endif /* SQLITE_SOUNDEX */
   108940 
   108941 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   108942 /*
   108943 ** A function that loads a shared-library extension then returns NULL.
   108944 */
   108945 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
   108946   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
   108947   const char *zProc;
   108948   sqlite3 *db = sqlite3_context_db_handle(context);
   108949   char *zErrMsg = 0;
   108950 
   108951   /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
   108952   ** flag is set.  See the sqlite3_enable_load_extension() API.
   108953   */
   108954   if( (db->flags & SQLITE_LoadExtFunc)==0 ){
   108955     sqlite3_result_error(context, "not authorized", -1);
   108956     return;
   108957   }
   108958 
   108959   if( argc==2 ){
   108960     zProc = (const char *)sqlite3_value_text(argv[1]);
   108961   }else{
   108962     zProc = 0;
   108963   }
   108964   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
   108965     sqlite3_result_error(context, zErrMsg, -1);
   108966     sqlite3_free(zErrMsg);
   108967   }
   108968 }
   108969 #endif
   108970 
   108971 
   108972 /*
   108973 ** An instance of the following structure holds the context of a
   108974 ** sum() or avg() aggregate computation.
   108975 */
   108976 typedef struct SumCtx SumCtx;
   108977 struct SumCtx {
   108978   double rSum;      /* Floating point sum */
   108979   i64 iSum;         /* Integer sum */
   108980   i64 cnt;          /* Number of elements summed */
   108981   u8 overflow;      /* True if integer overflow seen */
   108982   u8 approx;        /* True if non-integer value was input to the sum */
   108983 };
   108984 
   108985 /*
   108986 ** Routines used to compute the sum, average, and total.
   108987 **
   108988 ** The SUM() function follows the (broken) SQL standard which means
   108989 ** that it returns NULL if it sums over no inputs.  TOTAL returns
   108990 ** 0.0 in that case.  In addition, TOTAL always returns a float where
   108991 ** SUM might return an integer if it never encounters a floating point
   108992 ** value.  TOTAL never fails, but SUM might through an exception if
   108993 ** it overflows an integer.
   108994 */
   108995 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   108996   SumCtx *p;
   108997   int type;
   108998   assert( argc==1 );
   108999   UNUSED_PARAMETER(argc);
   109000   p = sqlite3_aggregate_context(context, sizeof(*p));
   109001   type = sqlite3_value_numeric_type(argv[0]);
   109002   if( p && type!=SQLITE_NULL ){
   109003     p->cnt++;
   109004     if( type==SQLITE_INTEGER ){
   109005       i64 v = sqlite3_value_int64(argv[0]);
   109006       p->rSum += v;
   109007       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
   109008         p->overflow = 1;
   109009       }
   109010     }else{
   109011       p->rSum += sqlite3_value_double(argv[0]);
   109012       p->approx = 1;
   109013     }
   109014   }
   109015 }
   109016 static void sumFinalize(sqlite3_context *context){
   109017   SumCtx *p;
   109018   p = sqlite3_aggregate_context(context, 0);
   109019   if( p && p->cnt>0 ){
   109020     if( p->overflow ){
   109021       sqlite3_result_error(context,"integer overflow",-1);
   109022     }else if( p->approx ){
   109023       sqlite3_result_double(context, p->rSum);
   109024     }else{
   109025       sqlite3_result_int64(context, p->iSum);
   109026     }
   109027   }
   109028 }
   109029 static void avgFinalize(sqlite3_context *context){
   109030   SumCtx *p;
   109031   p = sqlite3_aggregate_context(context, 0);
   109032   if( p && p->cnt>0 ){
   109033     sqlite3_result_double(context, p->rSum/(double)p->cnt);
   109034   }
   109035 }
   109036 static void totalFinalize(sqlite3_context *context){
   109037   SumCtx *p;
   109038   p = sqlite3_aggregate_context(context, 0);
   109039   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   109040   sqlite3_result_double(context, p ? p->rSum : (double)0);
   109041 }
   109042 
   109043 /*
   109044 ** The following structure keeps track of state information for the
   109045 ** count() aggregate function.
   109046 */
   109047 typedef struct CountCtx CountCtx;
   109048 struct CountCtx {
   109049   i64 n;
   109050 };
   109051 
   109052 /*
   109053 ** Routines to implement the count() aggregate function.
   109054 */
   109055 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   109056   CountCtx *p;
   109057   p = sqlite3_aggregate_context(context, sizeof(*p));
   109058   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
   109059     p->n++;
   109060   }
   109061 
   109062 #ifndef SQLITE_OMIT_DEPRECATED
   109063   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
   109064   ** sure it still operates correctly, verify that its count agrees with our
   109065   ** internal count when using count(*) and when the total count can be
   109066   ** expressed as a 32-bit integer. */
   109067   assert( argc==1 || p==0 || p->n>0x7fffffff
   109068           || p->n==sqlite3_aggregate_count(context) );
   109069 #endif
   109070 }
   109071 static void countFinalize(sqlite3_context *context){
   109072   CountCtx *p;
   109073   p = sqlite3_aggregate_context(context, 0);
   109074   sqlite3_result_int64(context, p ? p->n : 0);
   109075 }
   109076 
   109077 /*
   109078 ** Routines to implement min() and max() aggregate functions.
   109079 */
   109080 static void minmaxStep(
   109081   sqlite3_context *context,
   109082   int NotUsed,
   109083   sqlite3_value **argv
   109084 ){
   109085   Mem *pArg  = (Mem *)argv[0];
   109086   Mem *pBest;
   109087   UNUSED_PARAMETER(NotUsed);
   109088 
   109089   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
   109090   if( !pBest ) return;
   109091 
   109092   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   109093     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
   109094   }else if( pBest->flags ){
   109095     int max;
   109096     int cmp;
   109097     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   109098     /* This step function is used for both the min() and max() aggregates,
   109099     ** the only difference between the two being that the sense of the
   109100     ** comparison is inverted. For the max() aggregate, the
   109101     ** sqlite3_user_data() function returns (void *)-1. For min() it
   109102     ** returns (void *)db, where db is the sqlite3* database pointer.
   109103     ** Therefore the next statement sets variable 'max' to 1 for the max()
   109104     ** aggregate, or 0 for min().
   109105     */
   109106     max = sqlite3_user_data(context)!=0;
   109107     cmp = sqlite3MemCompare(pBest, pArg, pColl);
   109108     if( (max && cmp<0) || (!max && cmp>0) ){
   109109       sqlite3VdbeMemCopy(pBest, pArg);
   109110     }else{
   109111       sqlite3SkipAccumulatorLoad(context);
   109112     }
   109113   }else{
   109114     pBest->db = sqlite3_context_db_handle(context);
   109115     sqlite3VdbeMemCopy(pBest, pArg);
   109116   }
   109117 }
   109118 static void minMaxFinalize(sqlite3_context *context){
   109119   sqlite3_value *pRes;
   109120   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
   109121   if( pRes ){
   109122     if( pRes->flags ){
   109123       sqlite3_result_value(context, pRes);
   109124     }
   109125     sqlite3VdbeMemRelease(pRes);
   109126   }
   109127 }
   109128 
   109129 /*
   109130 ** group_concat(EXPR, ?SEPARATOR?)
   109131 */
   109132 static void groupConcatStep(
   109133   sqlite3_context *context,
   109134   int argc,
   109135   sqlite3_value **argv
   109136 ){
   109137   const char *zVal;
   109138   StrAccum *pAccum;
   109139   const char *zSep;
   109140   int nVal, nSep;
   109141   assert( argc==1 || argc==2 );
   109142   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   109143   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
   109144 
   109145   if( pAccum ){
   109146     sqlite3 *db = sqlite3_context_db_handle(context);
   109147     int firstTerm = pAccum->mxAlloc==0;
   109148     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
   109149     if( !firstTerm ){
   109150       if( argc==2 ){
   109151         zSep = (char*)sqlite3_value_text(argv[1]);
   109152         nSep = sqlite3_value_bytes(argv[1]);
   109153       }else{
   109154         zSep = ",";
   109155         nSep = 1;
   109156       }
   109157       if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
   109158     }
   109159     zVal = (char*)sqlite3_value_text(argv[0]);
   109160     nVal = sqlite3_value_bytes(argv[0]);
   109161     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
   109162   }
   109163 }
   109164 static void groupConcatFinalize(sqlite3_context *context){
   109165   StrAccum *pAccum;
   109166   pAccum = sqlite3_aggregate_context(context, 0);
   109167   if( pAccum ){
   109168     if( pAccum->accError==STRACCUM_TOOBIG ){
   109169       sqlite3_result_error_toobig(context);
   109170     }else if( pAccum->accError==STRACCUM_NOMEM ){
   109171       sqlite3_result_error_nomem(context);
   109172     }else{
   109173       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
   109174                           sqlite3_free);
   109175     }
   109176   }
   109177 }
   109178 
   109179 /*
   109180 ** This routine does per-connection function registration.  Most
   109181 ** of the built-in functions above are part of the global function set.
   109182 ** This routine only deals with those that are not global.
   109183 */
   109184 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
   109185   int rc = sqlite3_overload_function(db, "MATCH", 2);
   109186   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   109187   if( rc==SQLITE_NOMEM ){
   109188     sqlite3OomFault(db);
   109189   }
   109190 }
   109191 
   109192 /*
   109193 ** Set the LIKEOPT flag on the 2-argument function with the given name.
   109194 */
   109195 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
   109196   FuncDef *pDef;
   109197   pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
   109198   if( ALWAYS(pDef) ){
   109199     pDef->funcFlags |= flagVal;
   109200   }
   109201 }
   109202 
   109203 /*
   109204 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
   109205 ** parameter determines whether or not the LIKE operator is case
   109206 ** sensitive.  GLOB is always case sensitive.
   109207 */
   109208 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
   109209   struct compareInfo *pInfo;
   109210   if( caseSensitive ){
   109211     pInfo = (struct compareInfo*)&likeInfoAlt;
   109212   }else{
   109213     pInfo = (struct compareInfo*)&likeInfoNorm;
   109214   }
   109215   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   109216   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   109217   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
   109218       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
   109219   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
   109220   setLikeOptFlag(db, "like",
   109221       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
   109222 }
   109223 
   109224 /*
   109225 ** pExpr points to an expression which implements a function.  If
   109226 ** it is appropriate to apply the LIKE optimization to that function
   109227 ** then set aWc[0] through aWc[2] to the wildcard characters and the
   109228 ** escape character and then return TRUE.  If the function is not a
   109229 ** LIKE-style function then return FALSE.
   109230 **
   109231 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
   109232 ** operator if c is a string literal that is exactly one byte in length.
   109233 ** That one byte is stored in aWc[3].  aWc[3] is set to zero if there is
   109234 ** no ESCAPE clause.
   109235 **
   109236 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
   109237 ** the function (default for LIKE).  If the function makes the distinction
   109238 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
   109239 ** false.
   109240 */
   109241 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   109242   FuncDef *pDef;
   109243   int nExpr;
   109244   if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
   109245     return 0;
   109246   }
   109247   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   109248   nExpr = pExpr->x.pList->nExpr;
   109249   pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
   109250   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
   109251     return 0;
   109252   }
   109253   if( nExpr<3 ){
   109254     aWc[3] = 0;
   109255   }else{
   109256     Expr *pEscape = pExpr->x.pList->a[2].pExpr;
   109257     char *zEscape;
   109258     if( pEscape->op!=TK_STRING ) return 0;
   109259     zEscape = pEscape->u.zToken;
   109260     if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
   109261     aWc[3] = zEscape[0];
   109262   }
   109263 
   109264   /* The memcpy() statement assumes that the wildcard characters are
   109265   ** the first three statements in the compareInfo structure.  The
   109266   ** asserts() that follow verify that assumption
   109267   */
   109268   memcpy(aWc, pDef->pUserData, 3);
   109269   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
   109270   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
   109271   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   109272   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
   109273   return 1;
   109274 }
   109275 
   109276 /*
   109277 ** All of the FuncDef structures in the aBuiltinFunc[] array above
   109278 ** to the global function hash table.  This occurs at start-time (as
   109279 ** a consequence of calling sqlite3_initialize()).
   109280 **
   109281 ** After this routine runs
   109282 */
   109283 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
   109284   /*
   109285   ** The following array holds FuncDef structures for all of the functions
   109286   ** defined in this file.
   109287   **
   109288   ** The array cannot be constant since changes are made to the
   109289   ** FuncDef.pHash elements at start-time.  The elements of this array
   109290   ** are read-only after initialization is complete.
   109291   **
   109292   ** For peak efficiency, put the most frequently used function last.
   109293   */
   109294   static FuncDef aBuiltinFunc[] = {
   109295 #ifdef SQLITE_SOUNDEX
   109296     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
   109297 #endif
   109298 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   109299     VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
   109300     VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
   109301 #endif
   109302 #if SQLITE_USER_AUTHENTICATION
   109303     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
   109304 #endif
   109305 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   109306     DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
   109307     DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
   109308 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   109309     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   109310     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   109311     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
   109312 #ifdef SQLITE_DEBUG
   109313     FUNCTION2(affinity,          1, 0, 0, noopFunc,  SQLITE_FUNC_AFFINITY),
   109314 #endif
   109315 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
   109316     FUNCTION2(sqlite_offset,     1, 0, 0, noopFunc,  SQLITE_FUNC_OFFSET|
   109317                                                      SQLITE_FUNC_TYPEOF),
   109318 #endif
   109319     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
   109320     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
   109321     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
   109322     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
   109323     FUNCTION(trim,               1, 3, 0, trimFunc         ),
   109324     FUNCTION(trim,               2, 3, 0, trimFunc         ),
   109325     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
   109326     FUNCTION(min,                0, 0, 1, 0                ),
   109327     AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
   109328                                           SQLITE_FUNC_MINMAX ),
   109329     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
   109330     FUNCTION(max,                0, 1, 1, 0                ),
   109331     AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
   109332                                           SQLITE_FUNC_MINMAX ),
   109333     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
   109334     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
   109335     FUNCTION(instr,              2, 0, 0, instrFunc        ),
   109336     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
   109337     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
   109338     FUNCTION(char,              -1, 0, 0, charFunc         ),
   109339     FUNCTION(abs,                1, 0, 0, absFunc          ),
   109340 #ifndef SQLITE_OMIT_FLOATING_POINT
   109341     FUNCTION(round,              1, 0, 0, roundFunc        ),
   109342     FUNCTION(round,              2, 0, 0, roundFunc        ),
   109343 #endif
   109344     FUNCTION(upper,              1, 0, 0, upperFunc        ),
   109345     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
   109346     FUNCTION(hex,                1, 0, 0, hexFunc          ),
   109347     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
   109348     VFUNCTION(random,            0, 0, 0, randomFunc       ),
   109349     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
   109350     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
   109351     DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
   109352     DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
   109353     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
   109354     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
   109355     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
   109356     VFUNCTION(changes,           0, 0, 0, changes          ),
   109357     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
   109358     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
   109359     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
   109360     FUNCTION(substr,             2, 0, 0, substrFunc       ),
   109361     FUNCTION(substr,             3, 0, 0, substrFunc       ),
   109362     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
   109363     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
   109364     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
   109365     AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
   109366                SQLITE_FUNC_COUNT  ),
   109367     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
   109368     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
   109369     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
   109370 
   109371     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   109372 #ifdef SQLITE_CASE_SENSITIVE_LIKE
   109373     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   109374     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   109375 #else
   109376     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
   109377     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
   109378 #endif
   109379 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
   109380     FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
   109381 #endif
   109382     FUNCTION(coalesce,           1, 0, 0, 0                ),
   109383     FUNCTION(coalesce,           0, 0, 0, 0                ),
   109384     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
   109385   };
   109386 #ifndef SQLITE_OMIT_ALTERTABLE
   109387   sqlite3AlterFunctions();
   109388 #endif
   109389 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
   109390   sqlite3AnalyzeFunctions();
   109391 #endif
   109392   sqlite3RegisterDateTimeFunctions();
   109393   sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
   109394 
   109395 #if 0  /* Enable to print out how the built-in functions are hashed */
   109396   {
   109397     int i;
   109398     FuncDef *p;
   109399     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
   109400       printf("FUNC-HASH %02d:", i);
   109401       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
   109402         int n = sqlite3Strlen30(p->zName);
   109403         int h = p->zName[0] + n;
   109404         printf(" %s(%d)", p->zName, h);
   109405       }
   109406       printf("\n");
   109407     }
   109408   }
   109409 #endif
   109410 }
   109411 
   109412 /************** End of func.c ************************************************/
   109413 /************** Begin file fkey.c ********************************************/
   109414 /*
   109415 **
   109416 ** The author disclaims copyright to this source code.  In place of
   109417 ** a legal notice, here is a blessing:
   109418 **
   109419 **    May you do good and not evil.
   109420 **    May you find forgiveness for yourself and forgive others.
   109421 **    May you share freely, never taking more than you give.
   109422 **
   109423 *************************************************************************
   109424 ** This file contains code used by the compiler to add foreign key
   109425 ** support to compiled SQL statements.
   109426 */
   109427 /* #include "sqliteInt.h" */
   109428 
   109429 #ifndef SQLITE_OMIT_FOREIGN_KEY
   109430 #ifndef SQLITE_OMIT_TRIGGER
   109431 
   109432 /*
   109433 ** Deferred and Immediate FKs
   109434 ** --------------------------
   109435 **
   109436 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
   109437 ** If an immediate foreign key constraint is violated,
   109438 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
   109439 ** statement transaction rolled back. If a
   109440 ** deferred foreign key constraint is violated, no action is taken
   109441 ** immediately. However if the application attempts to commit the
   109442 ** transaction before fixing the constraint violation, the attempt fails.
   109443 **
   109444 ** Deferred constraints are implemented using a simple counter associated
   109445 ** with the database handle. The counter is set to zero each time a
   109446 ** database transaction is opened. Each time a statement is executed
   109447 ** that causes a foreign key violation, the counter is incremented. Each
   109448 ** time a statement is executed that removes an existing violation from
   109449 ** the database, the counter is decremented. When the transaction is
   109450 ** committed, the commit fails if the current value of the counter is
   109451 ** greater than zero. This scheme has two big drawbacks:
   109452 **
   109453 **   * When a commit fails due to a deferred foreign key constraint,
   109454 **     there is no way to tell which foreign constraint is not satisfied,
   109455 **     or which row it is not satisfied for.
   109456 **
   109457 **   * If the database contains foreign key violations when the
   109458 **     transaction is opened, this may cause the mechanism to malfunction.
   109459 **
   109460 ** Despite these problems, this approach is adopted as it seems simpler
   109461 ** than the alternatives.
   109462 **
   109463 ** INSERT operations:
   109464 **
   109465 **   I.1) For each FK for which the table is the child table, search
   109466 **        the parent table for a match. If none is found increment the
   109467 **        constraint counter.
   109468 **
   109469 **   I.2) For each FK for which the table is the parent table,
   109470 **        search the child table for rows that correspond to the new
   109471 **        row in the parent table. Decrement the counter for each row
   109472 **        found (as the constraint is now satisfied).
   109473 **
   109474 ** DELETE operations:
   109475 **
   109476 **   D.1) For each FK for which the table is the child table,
   109477 **        search the parent table for a row that corresponds to the
   109478 **        deleted row in the child table. If such a row is not found,
   109479 **        decrement the counter.
   109480 **
   109481 **   D.2) For each FK for which the table is the parent table, search
   109482 **        the child table for rows that correspond to the deleted row
   109483 **        in the parent table. For each found increment the counter.
   109484 **
   109485 ** UPDATE operations:
   109486 **
   109487 **   An UPDATE command requires that all 4 steps above are taken, but only
   109488 **   for FK constraints for which the affected columns are actually
   109489 **   modified (values must be compared at runtime).
   109490 **
   109491 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
   109492 ** This simplifies the implementation a bit.
   109493 **
   109494 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
   109495 ** resolution is considered to delete rows before the new row is inserted.
   109496 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
   109497 ** is thrown, even if the FK constraint would be satisfied after the new
   109498 ** row is inserted.
   109499 **
   109500 ** Immediate constraints are usually handled similarly. The only difference
   109501 ** is that the counter used is stored as part of each individual statement
   109502 ** object (struct Vdbe). If, after the statement has run, its immediate
   109503 ** constraint counter is greater than zero,
   109504 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
   109505 ** and the statement transaction is rolled back. An exception is an INSERT
   109506 ** statement that inserts a single row only (no triggers). In this case,
   109507 ** instead of using a counter, an exception is thrown immediately if the
   109508 ** INSERT violates a foreign key constraint. This is necessary as such
   109509 ** an INSERT does not open a statement transaction.
   109510 **
   109511 ** TODO: How should dropping a table be handled? How should renaming a
   109512 ** table be handled?
   109513 **
   109514 **
   109515 ** Query API Notes
   109516 ** ---------------
   109517 **
   109518 ** Before coding an UPDATE or DELETE row operation, the code-generator
   109519 ** for those two operations needs to know whether or not the operation
   109520 ** requires any FK processing and, if so, which columns of the original
   109521 ** row are required by the FK processing VDBE code (i.e. if FKs were
   109522 ** implemented using triggers, which of the old.* columns would be
   109523 ** accessed). No information is required by the code-generator before
   109524 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
   109525 ** generation code to query for this information are:
   109526 **
   109527 **   sqlite3FkRequired() - Test to see if FK processing is required.
   109528 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
   109529 **
   109530 **
   109531 ** Externally accessible module functions
   109532 ** --------------------------------------
   109533 **
   109534 **   sqlite3FkCheck()    - Check for foreign key violations.
   109535 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
   109536 **   sqlite3FkDelete()   - Delete an FKey structure.
   109537 */
   109538 
   109539 /*
   109540 ** VDBE Calling Convention
   109541 ** -----------------------
   109542 **
   109543 ** Example:
   109544 **
   109545 **   For the following INSERT statement:
   109546 **
   109547 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
   109548 **     INSERT INTO t1 VALUES(1, 2, 3.1);
   109549 **
   109550 **   Register (x):        2    (type integer)
   109551 **   Register (x+1):      1    (type integer)
   109552 **   Register (x+2):      NULL (type NULL)
   109553 **   Register (x+3):      3.1  (type real)
   109554 */
   109555 
   109556 /*
   109557 ** A foreign key constraint requires that the key columns in the parent
   109558 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
   109559 ** Given that pParent is the parent table for foreign key constraint pFKey,
   109560 ** search the schema for a unique index on the parent key columns.
   109561 **
   109562 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
   109563 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
   109564 ** is set to point to the unique index.
   109565 **
   109566 ** If the parent key consists of a single column (the foreign key constraint
   109567 ** is not a composite foreign key), output variable *paiCol is set to NULL.
   109568 ** Otherwise, it is set to point to an allocated array of size N, where
   109569 ** N is the number of columns in the parent key. The first element of the
   109570 ** array is the index of the child table column that is mapped by the FK
   109571 ** constraint to the parent table column stored in the left-most column
   109572 ** of index *ppIdx. The second element of the array is the index of the
   109573 ** child table column that corresponds to the second left-most column of
   109574 ** *ppIdx, and so on.
   109575 **
   109576 ** If the required index cannot be found, either because:
   109577 **
   109578 **   1) The named parent key columns do not exist, or
   109579 **
   109580 **   2) The named parent key columns do exist, but are not subject to a
   109581 **      UNIQUE or PRIMARY KEY constraint, or
   109582 **
   109583 **   3) No parent key columns were provided explicitly as part of the
   109584 **      foreign key definition, and the parent table does not have a
   109585 **      PRIMARY KEY, or
   109586 **
   109587 **   4) No parent key columns were provided explicitly as part of the
   109588 **      foreign key definition, and the PRIMARY KEY of the parent table
   109589 **      consists of a different number of columns to the child key in
   109590 **      the child table.
   109591 **
   109592 ** then non-zero is returned, and a "foreign key mismatch" error loaded
   109593 ** into pParse. If an OOM error occurs, non-zero is returned and the
   109594 ** pParse->db->mallocFailed flag is set.
   109595 */
   109596 SQLITE_PRIVATE int sqlite3FkLocateIndex(
   109597   Parse *pParse,                  /* Parse context to store any error in */
   109598   Table *pParent,                 /* Parent table of FK constraint pFKey */
   109599   FKey *pFKey,                    /* Foreign key to find index for */
   109600   Index **ppIdx,                  /* OUT: Unique index on parent table */
   109601   int **paiCol                    /* OUT: Map of index columns in pFKey */
   109602 ){
   109603   Index *pIdx = 0;                    /* Value to return via *ppIdx */
   109604   int *aiCol = 0;                     /* Value to return via *paiCol */
   109605   int nCol = pFKey->nCol;             /* Number of columns in parent key */
   109606   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
   109607 
   109608   /* The caller is responsible for zeroing output parameters. */
   109609   assert( ppIdx && *ppIdx==0 );
   109610   assert( !paiCol || *paiCol==0 );
   109611   assert( pParse );
   109612 
   109613   /* If this is a non-composite (single column) foreign key, check if it
   109614   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
   109615   ** and *paiCol set to zero and return early.
   109616   **
   109617   ** Otherwise, for a composite foreign key (more than one column), allocate
   109618   ** space for the aiCol array (returned via output parameter *paiCol).
   109619   ** Non-composite foreign keys do not require the aiCol array.
   109620   */
   109621   if( nCol==1 ){
   109622     /* The FK maps to the IPK if any of the following are true:
   109623     **
   109624     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
   109625     **      mapped to the primary key of table pParent, or
   109626     **   2) The FK is explicitly mapped to a column declared as INTEGER
   109627     **      PRIMARY KEY.
   109628     */
   109629     if( pParent->iPKey>=0 ){
   109630       if( !zKey ) return 0;
   109631       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   109632     }
   109633   }else if( paiCol ){
   109634     assert( nCol>1 );
   109635     aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
   109636     if( !aiCol ) return 1;
   109637     *paiCol = aiCol;
   109638   }
   109639 
   109640   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   109641     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
   109642       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
   109643       ** of columns. If each indexed column corresponds to a foreign key
   109644       ** column of pFKey, then this index is a winner.  */
   109645 
   109646       if( zKey==0 ){
   109647         /* If zKey is NULL, then this foreign key is implicitly mapped to
   109648         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
   109649         ** identified by the test.  */
   109650         if( IsPrimaryKeyIndex(pIdx) ){
   109651           if( aiCol ){
   109652             int i;
   109653             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
   109654           }
   109655           break;
   109656         }
   109657       }else{
   109658         /* If zKey is non-NULL, then this foreign key was declared to
   109659         ** map to an explicit list of columns in table pParent. Check if this
   109660         ** index matches those columns. Also, check that the index uses
   109661         ** the default collation sequences for each column. */
   109662         int i, j;
   109663         for(i=0; i<nCol; i++){
   109664           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
   109665           const char *zDfltColl;            /* Def. collation for column */
   109666           char *zIdxCol;                    /* Name of indexed column */
   109667 
   109668           if( iCol<0 ) break; /* No foreign keys against expression indexes */
   109669 
   109670           /* If the index uses a collation sequence that is different from
   109671           ** the default collation sequence for the column, this index is
   109672           ** unusable. Bail out early in this case.  */
   109673           zDfltColl = pParent->aCol[iCol].zColl;
   109674           if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
   109675           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
   109676 
   109677           zIdxCol = pParent->aCol[iCol].zName;
   109678           for(j=0; j<nCol; j++){
   109679             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
   109680               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
   109681               break;
   109682             }
   109683           }
   109684           if( j==nCol ) break;
   109685         }
   109686         if( i==nCol ) break;      /* pIdx is usable */
   109687       }
   109688     }
   109689   }
   109690 
   109691   if( !pIdx ){
   109692     if( !pParse->disableTriggers ){
   109693       sqlite3ErrorMsg(pParse,
   109694            "foreign key mismatch - \"%w\" referencing \"%w\"",
   109695            pFKey->pFrom->zName, pFKey->zTo);
   109696     }
   109697     sqlite3DbFree(pParse->db, aiCol);
   109698     return 1;
   109699   }
   109700 
   109701   *ppIdx = pIdx;
   109702   return 0;
   109703 }
   109704 
   109705 /*
   109706 ** This function is called when a row is inserted into or deleted from the
   109707 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
   109708 ** on the child table of pFKey, this function is invoked twice for each row
   109709 ** affected - once to "delete" the old row, and then again to "insert" the
   109710 ** new row.
   109711 **
   109712 ** Each time it is called, this function generates VDBE code to locate the
   109713 ** row in the parent table that corresponds to the row being inserted into
   109714 ** or deleted from the child table. If the parent row can be found, no
   109715 ** special action is taken. Otherwise, if the parent row can *not* be
   109716 ** found in the parent table:
   109717 **
   109718 **   Operation | FK type   | Action taken
   109719 **   --------------------------------------------------------------------------
   109720 **   INSERT      immediate   Increment the "immediate constraint counter".
   109721 **
   109722 **   DELETE      immediate   Decrement the "immediate constraint counter".
   109723 **
   109724 **   INSERT      deferred    Increment the "deferred constraint counter".
   109725 **
   109726 **   DELETE      deferred    Decrement the "deferred constraint counter".
   109727 **
   109728 ** These operations are identified in the comment at the top of this file
   109729 ** (fkey.c) as "I.1" and "D.1".
   109730 */
   109731 static void fkLookupParent(
   109732   Parse *pParse,        /* Parse context */
   109733   int iDb,              /* Index of database housing pTab */
   109734   Table *pTab,          /* Parent table of FK pFKey */
   109735   Index *pIdx,          /* Unique index on parent key columns in pTab */
   109736   FKey *pFKey,          /* Foreign key constraint */
   109737   int *aiCol,           /* Map from parent key columns to child table columns */
   109738   int regData,          /* Address of array containing child table row */
   109739   int nIncr,            /* Increment constraint counter by this */
   109740   int isIgnore          /* If true, pretend pTab contains all NULL values */
   109741 ){
   109742   int i;                                    /* Iterator variable */
   109743   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
   109744   int iCur = pParse->nTab - 1;              /* Cursor number to use */
   109745   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
   109746 
   109747   /* If nIncr is less than zero, then check at runtime if there are any
   109748   ** outstanding constraints to resolve. If there are not, there is no need
   109749   ** to check if deleting this row resolves any outstanding violations.
   109750   **
   109751   ** Check if any of the key columns in the child table row are NULL. If
   109752   ** any are, then the constraint is considered satisfied. No need to
   109753   ** search for a matching row in the parent table.  */
   109754   if( nIncr<0 ){
   109755     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
   109756     VdbeCoverage(v);
   109757   }
   109758   for(i=0; i<pFKey->nCol; i++){
   109759     int iReg = aiCol[i] + regData + 1;
   109760     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
   109761   }
   109762 
   109763   if( isIgnore==0 ){
   109764     if( pIdx==0 ){
   109765       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   109766       ** column of the parent table (table pTab).  */
   109767       int iMustBeInt;               /* Address of MustBeInt instruction */
   109768       int regTemp = sqlite3GetTempReg(pParse);
   109769 
   109770       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
   109771       ** apply the affinity of the parent key). If this fails, then there
   109772       ** is no matching parent key. Before using MustBeInt, make a copy of
   109773       ** the value. Otherwise, the value inserted into the child key column
   109774       ** will have INTEGER affinity applied to it, which may not be correct.  */
   109775       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   109776       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
   109777       VdbeCoverage(v);
   109778 
   109779       /* If the parent table is the same as the child table, and we are about
   109780       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   109781       ** then check if the row being inserted matches itself. If so, do not
   109782       ** increment the constraint-counter.  */
   109783       if( pTab==pFKey->pFrom && nIncr==1 ){
   109784         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
   109785         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   109786       }
   109787 
   109788       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   109789       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
   109790       sqlite3VdbeGoto(v, iOk);
   109791       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   109792       sqlite3VdbeJumpHere(v, iMustBeInt);
   109793       sqlite3ReleaseTempReg(pParse, regTemp);
   109794     }else{
   109795       int nCol = pFKey->nCol;
   109796       int regTemp = sqlite3GetTempRange(pParse, nCol);
   109797       int regRec = sqlite3GetTempReg(pParse);
   109798 
   109799       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
   109800       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   109801       for(i=0; i<nCol; i++){
   109802         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
   109803       }
   109804 
   109805       /* If the parent table is the same as the child table, and we are about
   109806       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   109807       ** then check if the row being inserted matches itself. If so, do not
   109808       ** increment the constraint-counter.
   109809       **
   109810       ** If any of the parent-key values are NULL, then the row cannot match
   109811       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
   109812       ** of the parent-key values are NULL (at this point it is known that
   109813       ** none of the child key values are).
   109814       */
   109815       if( pTab==pFKey->pFrom && nIncr==1 ){
   109816         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
   109817         for(i=0; i<nCol; i++){
   109818           int iChild = aiCol[i]+1+regData;
   109819           int iParent = pIdx->aiColumn[i]+1+regData;
   109820           assert( pIdx->aiColumn[i]>=0 );
   109821           assert( aiCol[i]!=pTab->iPKey );
   109822           if( pIdx->aiColumn[i]==pTab->iPKey ){
   109823             /* The parent key is a composite key that includes the IPK column */
   109824             iParent = regData;
   109825           }
   109826           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
   109827           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   109828         }
   109829         sqlite3VdbeGoto(v, iOk);
   109830       }
   109831 
   109832       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
   109833                         sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
   109834       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
   109835 
   109836       sqlite3ReleaseTempReg(pParse, regRec);
   109837       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   109838     }
   109839   }
   109840 
   109841   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
   109842    && !pParse->pToplevel
   109843    && !pParse->isMultiWrite
   109844   ){
   109845     /* Special case: If this is an INSERT statement that will insert exactly
   109846     ** one row into the table, raise a constraint immediately instead of
   109847     ** incrementing a counter. This is necessary as the VM code is being
   109848     ** generated for will not open a statement transaction.  */
   109849     assert( nIncr==1 );
   109850     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
   109851         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
   109852   }else{
   109853     if( nIncr>0 && pFKey->isDeferred==0 ){
   109854       sqlite3MayAbort(pParse);
   109855     }
   109856     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   109857   }
   109858 
   109859   sqlite3VdbeResolveLabel(v, iOk);
   109860   sqlite3VdbeAddOp1(v, OP_Close, iCur);
   109861 }
   109862 
   109863 
   109864 /*
   109865 ** Return an Expr object that refers to a memory register corresponding
   109866 ** to column iCol of table pTab.
   109867 **
   109868 ** regBase is the first of an array of register that contains the data
   109869 ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
   109870 ** column.  regBase+2 holds the second column, and so forth.
   109871 */
   109872 static Expr *exprTableRegister(
   109873   Parse *pParse,     /* Parsing and code generating context */
   109874   Table *pTab,       /* The table whose content is at r[regBase]... */
   109875   int regBase,       /* Contents of table pTab */
   109876   i16 iCol           /* Which column of pTab is desired */
   109877 ){
   109878   Expr *pExpr;
   109879   Column *pCol;
   109880   const char *zColl;
   109881   sqlite3 *db = pParse->db;
   109882 
   109883   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
   109884   if( pExpr ){
   109885     if( iCol>=0 && iCol!=pTab->iPKey ){
   109886       pCol = &pTab->aCol[iCol];
   109887       pExpr->iTable = regBase + iCol + 1;
   109888       pExpr->affinity = pCol->affinity;
   109889       zColl = pCol->zColl;
   109890       if( zColl==0 ) zColl = db->pDfltColl->zName;
   109891       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
   109892     }else{
   109893       pExpr->iTable = regBase;
   109894       pExpr->affinity = SQLITE_AFF_INTEGER;
   109895     }
   109896   }
   109897   return pExpr;
   109898 }
   109899 
   109900 /*
   109901 ** Return an Expr object that refers to column iCol of table pTab which
   109902 ** has cursor iCur.
   109903 */
   109904 static Expr *exprTableColumn(
   109905   sqlite3 *db,      /* The database connection */
   109906   Table *pTab,      /* The table whose column is desired */
   109907   int iCursor,      /* The open cursor on the table */
   109908   i16 iCol          /* The column that is wanted */
   109909 ){
   109910   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
   109911   if( pExpr ){
   109912     pExpr->pTab = pTab;
   109913     pExpr->iTable = iCursor;
   109914     pExpr->iColumn = iCol;
   109915   }
   109916   return pExpr;
   109917 }
   109918 
   109919 /*
   109920 ** This function is called to generate code executed when a row is deleted
   109921 ** from the parent table of foreign key constraint pFKey and, if pFKey is
   109922 ** deferred, when a row is inserted into the same table. When generating
   109923 ** code for an SQL UPDATE operation, this function may be called twice -
   109924 ** once to "delete" the old row and once to "insert" the new row.
   109925 **
   109926 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
   109927 ** the number of FK violations in the db) or +1 when deleting one (as this
   109928 ** may increase the number of FK constraint problems).
   109929 **
   109930 ** The code generated by this function scans through the rows in the child
   109931 ** table that correspond to the parent table row being deleted or inserted.
   109932 ** For each child row found, one of the following actions is taken:
   109933 **
   109934 **   Operation | FK type   | Action taken
   109935 **   --------------------------------------------------------------------------
   109936 **   DELETE      immediate   Increment the "immediate constraint counter".
   109937 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   109938 **                           throw a "FOREIGN KEY constraint failed" exception.
   109939 **
   109940 **   INSERT      immediate   Decrement the "immediate constraint counter".
   109941 **
   109942 **   DELETE      deferred    Increment the "deferred constraint counter".
   109943 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   109944 **                           throw a "FOREIGN KEY constraint failed" exception.
   109945 **
   109946 **   INSERT      deferred    Decrement the "deferred constraint counter".
   109947 **
   109948 ** These operations are identified in the comment at the top of this file
   109949 ** (fkey.c) as "I.2" and "D.2".
   109950 */
   109951 static void fkScanChildren(
   109952   Parse *pParse,                  /* Parse context */
   109953   SrcList *pSrc,                  /* The child table to be scanned */
   109954   Table *pTab,                    /* The parent table */
   109955   Index *pIdx,                    /* Index on parent covering the foreign key */
   109956   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
   109957   int *aiCol,                     /* Map from pIdx cols to child table cols */
   109958   int regData,                    /* Parent row data starts here */
   109959   int nIncr                       /* Amount to increment deferred counter by */
   109960 ){
   109961   sqlite3 *db = pParse->db;       /* Database handle */
   109962   int i;                          /* Iterator variable */
   109963   Expr *pWhere = 0;               /* WHERE clause to scan with */
   109964   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   109965   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
   109966   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
   109967   Vdbe *v = sqlite3GetVdbe(pParse);
   109968 
   109969   assert( pIdx==0 || pIdx->pTable==pTab );
   109970   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
   109971   assert( pIdx!=0 || pFKey->nCol==1 );
   109972   assert( pIdx!=0 || HasRowid(pTab) );
   109973 
   109974   if( nIncr<0 ){
   109975     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
   109976     VdbeCoverage(v);
   109977   }
   109978 
   109979   /* Create an Expr object representing an SQL expression like:
   109980   **
   109981   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   109982   **
   109983   ** The collation sequence used for the comparison should be that of
   109984   ** the parent key columns. The affinity of the parent key column should
   109985   ** be applied to each child key value before the comparison takes place.
   109986   */
   109987   for(i=0; i<pFKey->nCol; i++){
   109988     Expr *pLeft;                  /* Value from parent table row */
   109989     Expr *pRight;                 /* Column ref to child table */
   109990     Expr *pEq;                    /* Expression (pLeft = pRight) */
   109991     i16 iCol;                     /* Index of column in child table */
   109992     const char *zCol;             /* Name of column in child table */
   109993 
   109994     iCol = pIdx ? pIdx->aiColumn[i] : -1;
   109995     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
   109996     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   109997     assert( iCol>=0 );
   109998     zCol = pFKey->pFrom->aCol[iCol].zName;
   109999     pRight = sqlite3Expr(db, TK_ID, zCol);
   110000     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
   110001     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   110002   }
   110003 
   110004   /* If the child table is the same as the parent table, then add terms
   110005   ** to the WHERE clause that prevent this entry from being scanned.
   110006   ** The added WHERE clause terms are like this:
   110007   **
   110008   **     $current_rowid!=rowid
   110009   **     NOT( $current_a==a AND $current_b==b AND ... )
   110010   **
   110011   ** The first form is used for rowid tables.  The second form is used
   110012   ** for WITHOUT ROWID tables.  In the second form, the primary key is
   110013   ** (a,b,...)
   110014   */
   110015   if( pTab==pFKey->pFrom && nIncr>0 ){
   110016     Expr *pNe;                    /* Expression (pLeft != pRight) */
   110017     Expr *pLeft;                  /* Value from parent table row */
   110018     Expr *pRight;                 /* Column ref to child table */
   110019     if( HasRowid(pTab) ){
   110020       pLeft = exprTableRegister(pParse, pTab, regData, -1);
   110021       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
   110022       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
   110023     }else{
   110024       Expr *pEq, *pAll = 0;
   110025       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   110026       assert( pIdx!=0 );
   110027       for(i=0; i<pPk->nKeyCol; i++){
   110028         i16 iCol = pIdx->aiColumn[i];
   110029         assert( iCol>=0 );
   110030         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
   110031         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
   110032         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
   110033         pAll = sqlite3ExprAnd(db, pAll, pEq);
   110034       }
   110035       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
   110036     }
   110037     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
   110038   }
   110039 
   110040   /* Resolve the references in the WHERE clause. */
   110041   memset(&sNameContext, 0, sizeof(NameContext));
   110042   sNameContext.pSrcList = pSrc;
   110043   sNameContext.pParse = pParse;
   110044   sqlite3ResolveExprNames(&sNameContext, pWhere);
   110045 
   110046   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   110047   ** clause. For each row found, increment either the deferred or immediate
   110048   ** foreign key constraint counter. */
   110049   if( pParse->nErr==0 ){
   110050     pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
   110051     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   110052     if( pWInfo ){
   110053       sqlite3WhereEnd(pWInfo);
   110054     }
   110055   }
   110056 
   110057   /* Clean up the WHERE clause constructed above. */
   110058   sqlite3ExprDelete(db, pWhere);
   110059   if( iFkIfZero ){
   110060     sqlite3VdbeJumpHere(v, iFkIfZero);
   110061   }
   110062 }
   110063 
   110064 /*
   110065 ** This function returns a linked list of FKey objects (connected by
   110066 ** FKey.pNextTo) holding all children of table pTab.  For example,
   110067 ** given the following schema:
   110068 **
   110069 **   CREATE TABLE t1(a PRIMARY KEY);
   110070 **   CREATE TABLE t2(b REFERENCES t1(a);
   110071 **
   110072 ** Calling this function with table "t1" as an argument returns a pointer
   110073 ** to the FKey structure representing the foreign key constraint on table
   110074 ** "t2". Calling this function with "t2" as the argument would return a
   110075 ** NULL pointer (as there are no FK constraints for which t2 is the parent
   110076 ** table).
   110077 */
   110078 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
   110079   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
   110080 }
   110081 
   110082 /*
   110083 ** The second argument is a Trigger structure allocated by the
   110084 ** fkActionTrigger() routine. This function deletes the Trigger structure
   110085 ** and all of its sub-components.
   110086 **
   110087 ** The Trigger structure or any of its sub-components may be allocated from
   110088 ** the lookaside buffer belonging to database handle dbMem.
   110089 */
   110090 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   110091   if( p ){
   110092     TriggerStep *pStep = p->step_list;
   110093     sqlite3ExprDelete(dbMem, pStep->pWhere);
   110094     sqlite3ExprListDelete(dbMem, pStep->pExprList);
   110095     sqlite3SelectDelete(dbMem, pStep->pSelect);
   110096     sqlite3ExprDelete(dbMem, p->pWhen);
   110097     sqlite3DbFree(dbMem, p);
   110098   }
   110099 }
   110100 
   110101 /*
   110102 ** This function is called to generate code that runs when table pTab is
   110103 ** being dropped from the database. The SrcList passed as the second argument
   110104 ** to this function contains a single entry guaranteed to resolve to
   110105 ** table pTab.
   110106 **
   110107 ** Normally, no code is required. However, if either
   110108 **
   110109 **   (a) The table is the parent table of a FK constraint, or
   110110 **   (b) The table is the child table of a deferred FK constraint and it is
   110111 **       determined at runtime that there are outstanding deferred FK
   110112 **       constraint violations in the database,
   110113 **
   110114 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
   110115 ** the table from the database. Triggers are disabled while running this
   110116 ** DELETE, but foreign key actions are not.
   110117 */
   110118 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   110119   sqlite3 *db = pParse->db;
   110120   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
   110121     int iSkip = 0;
   110122     Vdbe *v = sqlite3GetVdbe(pParse);
   110123 
   110124     assert( v );                  /* VDBE has already been allocated */
   110125     if( sqlite3FkReferences(pTab)==0 ){
   110126       /* Search for a deferred foreign key constraint for which this table
   110127       ** is the child table. If one cannot be found, return without
   110128       ** generating any VDBE code. If one can be found, then jump over
   110129       ** the entire DELETE if there are no outstanding deferred constraints
   110130       ** when this statement is run.  */
   110131       FKey *p;
   110132       for(p=pTab->pFKey; p; p=p->pNextFrom){
   110133         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
   110134       }
   110135       if( !p ) return;
   110136       iSkip = sqlite3VdbeMakeLabel(v);
   110137       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
   110138     }
   110139 
   110140     pParse->disableTriggers = 1;
   110141     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
   110142     pParse->disableTriggers = 0;
   110143 
   110144     /* If the DELETE has generated immediate foreign key constraint
   110145     ** violations, halt the VDBE and return an error at this point, before
   110146     ** any modifications to the schema are made. This is because statement
   110147     ** transactions are not able to rollback schema changes.
   110148     **
   110149     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
   110150     ** the statement transaction will not be rolled back even if FK
   110151     ** constraints are violated.
   110152     */
   110153     if( (db->flags & SQLITE_DeferFKs)==0 ){
   110154       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
   110155       VdbeCoverage(v);
   110156       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
   110157           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
   110158     }
   110159 
   110160     if( iSkip ){
   110161       sqlite3VdbeResolveLabel(v, iSkip);
   110162     }
   110163   }
   110164 }
   110165 
   110166 
   110167 /*
   110168 ** The second argument points to an FKey object representing a foreign key
   110169 ** for which pTab is the child table. An UPDATE statement against pTab
   110170 ** is currently being processed. For each column of the table that is
   110171 ** actually updated, the corresponding element in the aChange[] array
   110172 ** is zero or greater (if a column is unmodified the corresponding element
   110173 ** is set to -1). If the rowid column is modified by the UPDATE statement
   110174 ** the bChngRowid argument is non-zero.
   110175 **
   110176 ** This function returns true if any of the columns that are part of the
   110177 ** child key for FK constraint *p are modified.
   110178 */
   110179 static int fkChildIsModified(
   110180   Table *pTab,                    /* Table being updated */
   110181   FKey *p,                        /* Foreign key for which pTab is the child */
   110182   int *aChange,                   /* Array indicating modified columns */
   110183   int bChngRowid                  /* True if rowid is modified by this update */
   110184 ){
   110185   int i;
   110186   for(i=0; i<p->nCol; i++){
   110187     int iChildKey = p->aCol[i].iFrom;
   110188     if( aChange[iChildKey]>=0 ) return 1;
   110189     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
   110190   }
   110191   return 0;
   110192 }
   110193 
   110194 /*
   110195 ** The second argument points to an FKey object representing a foreign key
   110196 ** for which pTab is the parent table. An UPDATE statement against pTab
   110197 ** is currently being processed. For each column of the table that is
   110198 ** actually updated, the corresponding element in the aChange[] array
   110199 ** is zero or greater (if a column is unmodified the corresponding element
   110200 ** is set to -1). If the rowid column is modified by the UPDATE statement
   110201 ** the bChngRowid argument is non-zero.
   110202 **
   110203 ** This function returns true if any of the columns that are part of the
   110204 ** parent key for FK constraint *p are modified.
   110205 */
   110206 static int fkParentIsModified(
   110207   Table *pTab,
   110208   FKey *p,
   110209   int *aChange,
   110210   int bChngRowid
   110211 ){
   110212   int i;
   110213   for(i=0; i<p->nCol; i++){
   110214     char *zKey = p->aCol[i].zCol;
   110215     int iKey;
   110216     for(iKey=0; iKey<pTab->nCol; iKey++){
   110217       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
   110218         Column *pCol = &pTab->aCol[iKey];
   110219         if( zKey ){
   110220           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
   110221         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
   110222           return 1;
   110223         }
   110224       }
   110225     }
   110226   }
   110227   return 0;
   110228 }
   110229 
   110230 /*
   110231 ** Return true if the parser passed as the first argument is being
   110232 ** used to code a trigger that is really a "SET NULL" action belonging
   110233 ** to trigger pFKey.
   110234 */
   110235 static int isSetNullAction(Parse *pParse, FKey *pFKey){
   110236   Parse *pTop = sqlite3ParseToplevel(pParse);
   110237   if( pTop->pTriggerPrg ){
   110238     Trigger *p = pTop->pTriggerPrg->pTrigger;
   110239     if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
   110240      || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
   110241     ){
   110242       return 1;
   110243     }
   110244   }
   110245   return 0;
   110246 }
   110247 
   110248 /*
   110249 ** This function is called when inserting, deleting or updating a row of
   110250 ** table pTab to generate VDBE code to perform foreign key constraint
   110251 ** processing for the operation.
   110252 **
   110253 ** For a DELETE operation, parameter regOld is passed the index of the
   110254 ** first register in an array of (pTab->nCol+1) registers containing the
   110255 ** rowid of the row being deleted, followed by each of the column values
   110256 ** of the row being deleted, from left to right. Parameter regNew is passed
   110257 ** zero in this case.
   110258 **
   110259 ** For an INSERT operation, regOld is passed zero and regNew is passed the
   110260 ** first register of an array of (pTab->nCol+1) registers containing the new
   110261 ** row data.
   110262 **
   110263 ** For an UPDATE operation, this function is called twice. Once before
   110264 ** the original record is deleted from the table using the calling convention
   110265 ** described for DELETE. Then again after the original record is deleted
   110266 ** but before the new record is inserted using the INSERT convention.
   110267 */
   110268 SQLITE_PRIVATE void sqlite3FkCheck(
   110269   Parse *pParse,                  /* Parse context */
   110270   Table *pTab,                    /* Row is being deleted from this table */
   110271   int regOld,                     /* Previous row data is stored here */
   110272   int regNew,                     /* New row data is stored here */
   110273   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
   110274   int bChngRowid                  /* True if rowid is UPDATEd */
   110275 ){
   110276   sqlite3 *db = pParse->db;       /* Database handle */
   110277   FKey *pFKey;                    /* Used to iterate through FKs */
   110278   int iDb;                        /* Index of database containing pTab */
   110279   const char *zDb;                /* Name of database containing pTab */
   110280   int isIgnoreErrors = pParse->disableTriggers;
   110281 
   110282   /* Exactly one of regOld and regNew should be non-zero. */
   110283   assert( (regOld==0)!=(regNew==0) );
   110284 
   110285   /* If foreign-keys are disabled, this function is a no-op. */
   110286   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   110287 
   110288   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   110289   zDb = db->aDb[iDb].zDbSName;
   110290 
   110291   /* Loop through all the foreign key constraints for which pTab is the
   110292   ** child table (the table that the foreign key definition is part of).  */
   110293   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   110294     Table *pTo;                   /* Parent table of foreign key pFKey */
   110295     Index *pIdx = 0;              /* Index on key columns in pTo */
   110296     int *aiFree = 0;
   110297     int *aiCol;
   110298     int iCol;
   110299     int i;
   110300     int bIgnore = 0;
   110301 
   110302     if( aChange
   110303      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
   110304      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
   110305     ){
   110306       continue;
   110307     }
   110308 
   110309     /* Find the parent table of this foreign key. Also find a unique index
   110310     ** on the parent key columns in the parent table. If either of these
   110311     ** schema items cannot be located, set an error in pParse and return
   110312     ** early.  */
   110313     if( pParse->disableTriggers ){
   110314       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
   110315     }else{
   110316       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
   110317     }
   110318     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
   110319       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
   110320       if( !isIgnoreErrors || db->mallocFailed ) return;
   110321       if( pTo==0 ){
   110322         /* If isIgnoreErrors is true, then a table is being dropped. In this
   110323         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
   110324         ** before actually dropping it in order to check FK constraints.
   110325         ** If the parent table of an FK constraint on the current table is
   110326         ** missing, behave as if it is empty. i.e. decrement the relevant
   110327         ** FK counter for each row of the current table with non-NULL keys.
   110328         */
   110329         Vdbe *v = sqlite3GetVdbe(pParse);
   110330         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
   110331         for(i=0; i<pFKey->nCol; i++){
   110332           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
   110333           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
   110334         }
   110335         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
   110336       }
   110337       continue;
   110338     }
   110339     assert( pFKey->nCol==1 || (aiFree && pIdx) );
   110340 
   110341     if( aiFree ){
   110342       aiCol = aiFree;
   110343     }else{
   110344       iCol = pFKey->aCol[0].iFrom;
   110345       aiCol = &iCol;
   110346     }
   110347     for(i=0; i<pFKey->nCol; i++){
   110348       if( aiCol[i]==pTab->iPKey ){
   110349         aiCol[i] = -1;
   110350       }
   110351       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
   110352 #ifndef SQLITE_OMIT_AUTHORIZATION
   110353       /* Request permission to read the parent key columns. If the
   110354       ** authorization callback returns SQLITE_IGNORE, behave as if any
   110355       ** values read from the parent table are NULL. */
   110356       if( db->xAuth ){
   110357         int rcauth;
   110358         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
   110359         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
   110360         bIgnore = (rcauth==SQLITE_IGNORE);
   110361       }
   110362 #endif
   110363     }
   110364 
   110365     /* Take a shared-cache advisory read-lock on the parent table. Allocate
   110366     ** a cursor to use to search the unique index on the parent key columns
   110367     ** in the parent table.  */
   110368     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
   110369     pParse->nTab++;
   110370 
   110371     if( regOld!=0 ){
   110372       /* A row is being removed from the child table. Search for the parent.
   110373       ** If the parent does not exist, removing the child row resolves an
   110374       ** outstanding foreign key constraint violation. */
   110375       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
   110376     }
   110377     if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
   110378       /* A row is being added to the child table. If a parent row cannot
   110379       ** be found, adding the child row has violated the FK constraint.
   110380       **
   110381       ** If this operation is being performed as part of a trigger program
   110382       ** that is actually a "SET NULL" action belonging to this very
   110383       ** foreign key, then omit this scan altogether. As all child key
   110384       ** values are guaranteed to be NULL, it is not possible for adding
   110385       ** this row to cause an FK violation.  */
   110386       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
   110387     }
   110388 
   110389     sqlite3DbFree(db, aiFree);
   110390   }
   110391 
   110392   /* Loop through all the foreign key constraints that refer to this table.
   110393   ** (the "child" constraints) */
   110394   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   110395     Index *pIdx = 0;              /* Foreign key index for pFKey */
   110396     SrcList *pSrc;
   110397     int *aiCol = 0;
   110398 
   110399     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
   110400       continue;
   110401     }
   110402 
   110403     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
   110404      && !pParse->pToplevel && !pParse->isMultiWrite
   110405     ){
   110406       assert( regOld==0 && regNew!=0 );
   110407       /* Inserting a single row into a parent table cannot cause (or fix)
   110408       ** an immediate foreign key violation. So do nothing in this case.  */
   110409       continue;
   110410     }
   110411 
   110412     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
   110413       if( !isIgnoreErrors || db->mallocFailed ) return;
   110414       continue;
   110415     }
   110416     assert( aiCol || pFKey->nCol==1 );
   110417 
   110418     /* Create a SrcList structure containing the child table.  We need the
   110419     ** child table as a SrcList for sqlite3WhereBegin() */
   110420     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   110421     if( pSrc ){
   110422       struct SrcList_item *pItem = pSrc->a;
   110423       pItem->pTab = pFKey->pFrom;
   110424       pItem->zName = pFKey->pFrom->zName;
   110425       pItem->pTab->nTabRef++;
   110426       pItem->iCursor = pParse->nTab++;
   110427 
   110428       if( regNew!=0 ){
   110429         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
   110430       }
   110431       if( regOld!=0 ){
   110432         int eAction = pFKey->aAction[aChange!=0];
   110433         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
   110434         /* If this is a deferred FK constraint, or a CASCADE or SET NULL
   110435         ** action applies, then any foreign key violations caused by
   110436         ** removing the parent key will be rectified by the action trigger.
   110437         ** So do not set the "may-abort" flag in this case.
   110438         **
   110439         ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
   110440         ** may-abort flag will eventually be set on this statement anyway
   110441         ** (when this function is called as part of processing the UPDATE
   110442         ** within the action trigger).
   110443         **
   110444         ** Note 2: At first glance it may seem like SQLite could simply omit
   110445         ** all OP_FkCounter related scans when either CASCADE or SET NULL
   110446         ** applies. The trouble starts if the CASCADE or SET NULL action
   110447         ** trigger causes other triggers or action rules attached to the
   110448         ** child table to fire. In these cases the fk constraint counters
   110449         ** might be set incorrectly if any OP_FkCounter related scans are
   110450         ** omitted.  */
   110451         if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
   110452           sqlite3MayAbort(pParse);
   110453         }
   110454       }
   110455       pItem->zName = 0;
   110456       sqlite3SrcListDelete(db, pSrc);
   110457     }
   110458     sqlite3DbFree(db, aiCol);
   110459   }
   110460 }
   110461 
   110462 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
   110463 
   110464 /*
   110465 ** This function is called before generating code to update or delete a
   110466 ** row contained in table pTab.
   110467 */
   110468 SQLITE_PRIVATE u32 sqlite3FkOldmask(
   110469   Parse *pParse,                  /* Parse context */
   110470   Table *pTab                     /* Table being modified */
   110471 ){
   110472   u32 mask = 0;
   110473   if( pParse->db->flags&SQLITE_ForeignKeys ){
   110474     FKey *p;
   110475     int i;
   110476     for(p=pTab->pFKey; p; p=p->pNextFrom){
   110477       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
   110478     }
   110479     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   110480       Index *pIdx = 0;
   110481       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
   110482       if( pIdx ){
   110483         for(i=0; i<pIdx->nKeyCol; i++){
   110484           assert( pIdx->aiColumn[i]>=0 );
   110485           mask |= COLUMN_MASK(pIdx->aiColumn[i]);
   110486         }
   110487       }
   110488     }
   110489   }
   110490   return mask;
   110491 }
   110492 
   110493 
   110494 /*
   110495 ** This function is called before generating code to update or delete a
   110496 ** row contained in table pTab. If the operation is a DELETE, then
   110497 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
   110498 ** to an array of size N, where N is the number of columns in table pTab.
   110499 ** If the i'th column is not modified by the UPDATE, then the corresponding
   110500 ** entry in the aChange[] array is set to -1. If the column is modified,
   110501 ** the value is 0 or greater. Parameter chngRowid is set to true if the
   110502 ** UPDATE statement modifies the rowid fields of the table.
   110503 **
   110504 ** If any foreign key processing will be required, this function returns
   110505 ** non-zero. If there is no foreign key related processing, this function
   110506 ** returns zero.
   110507 **
   110508 ** For an UPDATE, this function returns 2 if:
   110509 **
   110510 **   * There are any FKs for which pTab is the child and the parent table, or
   110511 **   * the UPDATE modifies one or more parent keys for which the action is
   110512 **     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
   110513 **
   110514 ** Or, assuming some other foreign key processing is required, 1.
   110515 */
   110516 SQLITE_PRIVATE int sqlite3FkRequired(
   110517   Parse *pParse,                  /* Parse context */
   110518   Table *pTab,                    /* Table being modified */
   110519   int *aChange,                   /* Non-NULL for UPDATE operations */
   110520   int chngRowid                   /* True for UPDATE that affects rowid */
   110521 ){
   110522   int eRet = 0;
   110523   if( pParse->db->flags&SQLITE_ForeignKeys ){
   110524     if( !aChange ){
   110525       /* A DELETE operation. Foreign key processing is required if the
   110526       ** table in question is either the child or parent table for any
   110527       ** foreign key constraint.  */
   110528       eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
   110529     }else{
   110530       /* This is an UPDATE. Foreign key processing is only required if the
   110531       ** operation modifies one or more child or parent key columns. */
   110532       FKey *p;
   110533 
   110534       /* Check if any child key columns are being modified. */
   110535       for(p=pTab->pFKey; p; p=p->pNextFrom){
   110536         if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
   110537         if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
   110538           eRet = 1;
   110539         }
   110540       }
   110541 
   110542       /* Check if any parent key columns are being modified. */
   110543       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   110544         if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
   110545           if( p->aAction[1]!=OE_None ) return 2;
   110546           eRet = 1;
   110547         }
   110548       }
   110549     }
   110550   }
   110551   return eRet;
   110552 }
   110553 
   110554 /*
   110555 ** This function is called when an UPDATE or DELETE operation is being
   110556 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
   110557 ** If the current operation is an UPDATE, then the pChanges parameter is
   110558 ** passed a pointer to the list of columns being modified. If it is a
   110559 ** DELETE, pChanges is passed a NULL pointer.
   110560 **
   110561 ** It returns a pointer to a Trigger structure containing a trigger
   110562 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
   110563 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
   110564 ** returned (these actions require no special handling by the triggers
   110565 ** sub-system, code for them is created by fkScanChildren()).
   110566 **
   110567 ** For example, if pFKey is the foreign key and pTab is table "p" in
   110568 ** the following schema:
   110569 **
   110570 **   CREATE TABLE p(pk PRIMARY KEY);
   110571 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
   110572 **
   110573 ** then the returned trigger structure is equivalent to:
   110574 **
   110575 **   CREATE TRIGGER ... DELETE ON p BEGIN
   110576 **     DELETE FROM c WHERE ck = old.pk;
   110577 **   END;
   110578 **
   110579 ** The returned pointer is cached as part of the foreign key object. It
   110580 ** is eventually freed along with the rest of the foreign key object by
   110581 ** sqlite3FkDelete().
   110582 */
   110583 static Trigger *fkActionTrigger(
   110584   Parse *pParse,                  /* Parse context */
   110585   Table *pTab,                    /* Table being updated or deleted from */
   110586   FKey *pFKey,                    /* Foreign key to get action for */
   110587   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
   110588 ){
   110589   sqlite3 *db = pParse->db;       /* Database handle */
   110590   int action;                     /* One of OE_None, OE_Cascade etc. */
   110591   Trigger *pTrigger;              /* Trigger definition to return */
   110592   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
   110593 
   110594   action = pFKey->aAction[iAction];
   110595   if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
   110596     return 0;
   110597   }
   110598   pTrigger = pFKey->apTrigger[iAction];
   110599 
   110600   if( action!=OE_None && !pTrigger ){
   110601     char const *zFrom;            /* Name of child table */
   110602     int nFrom;                    /* Length in bytes of zFrom */
   110603     Index *pIdx = 0;              /* Parent key index for this FK */
   110604     int *aiCol = 0;               /* child table cols -> parent key cols */
   110605     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
   110606     Expr *pWhere = 0;             /* WHERE clause of trigger step */
   110607     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
   110608     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
   110609     int i;                        /* Iterator variable */
   110610     Expr *pWhen = 0;              /* WHEN clause for the trigger */
   110611 
   110612     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
   110613     assert( aiCol || pFKey->nCol==1 );
   110614 
   110615     for(i=0; i<pFKey->nCol; i++){
   110616       Token tOld = { "old", 3 };  /* Literal "old" token */
   110617       Token tNew = { "new", 3 };  /* Literal "new" token */
   110618       Token tFromCol;             /* Name of column in child table */
   110619       Token tToCol;               /* Name of column in parent table */
   110620       int iFromCol;               /* Idx of column in child table */
   110621       Expr *pEq;                  /* tFromCol = OLD.tToCol */
   110622 
   110623       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   110624       assert( iFromCol>=0 );
   110625       assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
   110626       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
   110627       sqlite3TokenInit(&tToCol,
   110628                    pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
   110629       sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
   110630 
   110631       /* Create the expression "OLD.zToCol = zFromCol". It is important
   110632       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
   110633       ** that the affinity and collation sequence associated with the
   110634       ** parent table are used for the comparison. */
   110635       pEq = sqlite3PExpr(pParse, TK_EQ,
   110636           sqlite3PExpr(pParse, TK_DOT,
   110637             sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
   110638             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
   110639           sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
   110640       );
   110641       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   110642 
   110643       /* For ON UPDATE, construct the next term of the WHEN clause.
   110644       ** The final WHEN clause will be like this:
   110645       **
   110646       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
   110647       */
   110648       if( pChanges ){
   110649         pEq = sqlite3PExpr(pParse, TK_IS,
   110650             sqlite3PExpr(pParse, TK_DOT,
   110651               sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
   110652               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
   110653             sqlite3PExpr(pParse, TK_DOT,
   110654               sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
   110655               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
   110656             );
   110657         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
   110658       }
   110659 
   110660       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
   110661         Expr *pNew;
   110662         if( action==OE_Cascade ){
   110663           pNew = sqlite3PExpr(pParse, TK_DOT,
   110664             sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
   110665             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
   110666         }else if( action==OE_SetDflt ){
   110667           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
   110668           if( pDflt ){
   110669             pNew = sqlite3ExprDup(db, pDflt, 0);
   110670           }else{
   110671             pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
   110672           }
   110673         }else{
   110674           pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
   110675         }
   110676         pList = sqlite3ExprListAppend(pParse, pList, pNew);
   110677         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
   110678       }
   110679     }
   110680     sqlite3DbFree(db, aiCol);
   110681 
   110682     zFrom = pFKey->pFrom->zName;
   110683     nFrom = sqlite3Strlen30(zFrom);
   110684 
   110685     if( action==OE_Restrict ){
   110686       Token tFrom;
   110687       Expr *pRaise;
   110688 
   110689       tFrom.z = zFrom;
   110690       tFrom.n = nFrom;
   110691       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
   110692       if( pRaise ){
   110693         pRaise->affinity = OE_Abort;
   110694       }
   110695       pSelect = sqlite3SelectNew(pParse,
   110696           sqlite3ExprListAppend(pParse, 0, pRaise),
   110697           sqlite3SrcListAppend(db, 0, &tFrom, 0),
   110698           pWhere,
   110699           0, 0, 0, 0, 0
   110700       );
   110701       pWhere = 0;
   110702     }
   110703 
   110704     /* Disable lookaside memory allocation */
   110705     db->lookaside.bDisable++;
   110706 
   110707     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
   110708         sizeof(Trigger) +         /* struct Trigger */
   110709         sizeof(TriggerStep) +     /* Single step in trigger program */
   110710         nFrom + 1                 /* Space for pStep->zTarget */
   110711     );
   110712     if( pTrigger ){
   110713       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
   110714       pStep->zTarget = (char *)&pStep[1];
   110715       memcpy((char *)pStep->zTarget, zFrom, nFrom);
   110716 
   110717       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   110718       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
   110719       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   110720       if( pWhen ){
   110721         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
   110722         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   110723       }
   110724     }
   110725 
   110726     /* Re-enable the lookaside buffer, if it was disabled earlier. */
   110727     db->lookaside.bDisable--;
   110728 
   110729     sqlite3ExprDelete(db, pWhere);
   110730     sqlite3ExprDelete(db, pWhen);
   110731     sqlite3ExprListDelete(db, pList);
   110732     sqlite3SelectDelete(db, pSelect);
   110733     if( db->mallocFailed==1 ){
   110734       fkTriggerDelete(db, pTrigger);
   110735       return 0;
   110736     }
   110737     assert( pStep!=0 );
   110738 
   110739     switch( action ){
   110740       case OE_Restrict:
   110741         pStep->op = TK_SELECT;
   110742         break;
   110743       case OE_Cascade:
   110744         if( !pChanges ){
   110745           pStep->op = TK_DELETE;
   110746           break;
   110747         }
   110748       default:
   110749         pStep->op = TK_UPDATE;
   110750     }
   110751     pStep->pTrig = pTrigger;
   110752     pTrigger->pSchema = pTab->pSchema;
   110753     pTrigger->pTabSchema = pTab->pSchema;
   110754     pFKey->apTrigger[iAction] = pTrigger;
   110755     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
   110756   }
   110757 
   110758   return pTrigger;
   110759 }
   110760 
   110761 /*
   110762 ** This function is called when deleting or updating a row to implement
   110763 ** any required CASCADE, SET NULL or SET DEFAULT actions.
   110764 */
   110765 SQLITE_PRIVATE void sqlite3FkActions(
   110766   Parse *pParse,                  /* Parse context */
   110767   Table *pTab,                    /* Table being updated or deleted from */
   110768   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
   110769   int regOld,                     /* Address of array containing old row */
   110770   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
   110771   int bChngRowid                  /* True if rowid is UPDATEd */
   110772 ){
   110773   /* If foreign-key support is enabled, iterate through all FKs that
   110774   ** refer to table pTab. If there is an action associated with the FK
   110775   ** for this operation (either update or delete), invoke the associated
   110776   ** trigger sub-program.  */
   110777   if( pParse->db->flags&SQLITE_ForeignKeys ){
   110778     FKey *pFKey;                  /* Iterator variable */
   110779     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   110780       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
   110781         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
   110782         if( pAct ){
   110783           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
   110784         }
   110785       }
   110786     }
   110787   }
   110788 }
   110789 
   110790 #endif /* ifndef SQLITE_OMIT_TRIGGER */
   110791 
   110792 /*
   110793 ** Free all memory associated with foreign key definitions attached to
   110794 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
   110795 ** hash table.
   110796 */
   110797 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
   110798   FKey *pFKey;                    /* Iterator variable */
   110799   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
   110800 
   110801   assert( db==0 || IsVirtual(pTab)
   110802          || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
   110803   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
   110804 
   110805     /* Remove the FK from the fkeyHash hash table. */
   110806     if( !db || db->pnBytesFreed==0 ){
   110807       if( pFKey->pPrevTo ){
   110808         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
   110809       }else{
   110810         void *p = (void *)pFKey->pNextTo;
   110811         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
   110812         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
   110813       }
   110814       if( pFKey->pNextTo ){
   110815         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
   110816       }
   110817     }
   110818 
   110819     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
   110820     ** classified as either immediate or deferred.
   110821     */
   110822     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
   110823 
   110824     /* Delete any triggers created to implement actions for this FK. */
   110825 #ifndef SQLITE_OMIT_TRIGGER
   110826     fkTriggerDelete(db, pFKey->apTrigger[0]);
   110827     fkTriggerDelete(db, pFKey->apTrigger[1]);
   110828 #endif
   110829 
   110830     pNext = pFKey->pNextFrom;
   110831     sqlite3DbFree(db, pFKey);
   110832   }
   110833 }
   110834 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
   110835 
   110836 /************** End of fkey.c ************************************************/
   110837 /************** Begin file insert.c ******************************************/
   110838 /*
   110839 ** 2001 September 15
   110840 **
   110841 ** The author disclaims copyright to this source code.  In place of
   110842 ** a legal notice, here is a blessing:
   110843 **
   110844 **    May you do good and not evil.
   110845 **    May you find forgiveness for yourself and forgive others.
   110846 **    May you share freely, never taking more than you give.
   110847 **
   110848 *************************************************************************
   110849 ** This file contains C code routines that are called by the parser
   110850 ** to handle INSERT statements in SQLite.
   110851 */
   110852 /* #include "sqliteInt.h" */
   110853 
   110854 /*
   110855 ** Generate code that will
   110856 **
   110857 **   (1) acquire a lock for table pTab then
   110858 **   (2) open pTab as cursor iCur.
   110859 **
   110860 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
   110861 ** for that table that is actually opened.
   110862 */
   110863 SQLITE_PRIVATE void sqlite3OpenTable(
   110864   Parse *pParse,  /* Generate code into this VDBE */
   110865   int iCur,       /* The cursor number of the table */
   110866   int iDb,        /* The database index in sqlite3.aDb[] */
   110867   Table *pTab,    /* The table to be opened */
   110868   int opcode      /* OP_OpenRead or OP_OpenWrite */
   110869 ){
   110870   Vdbe *v;
   110871   assert( !IsVirtual(pTab) );
   110872   v = sqlite3GetVdbe(pParse);
   110873   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
   110874   sqlite3TableLock(pParse, iDb, pTab->tnum,
   110875                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
   110876   if( HasRowid(pTab) ){
   110877     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
   110878     VdbeComment((v, "%s", pTab->zName));
   110879   }else{
   110880     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   110881     assert( pPk!=0 );
   110882     assert( pPk->tnum==pTab->tnum );
   110883     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
   110884     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   110885     VdbeComment((v, "%s", pTab->zName));
   110886   }
   110887 }
   110888 
   110889 /*
   110890 ** Return a pointer to the column affinity string associated with index
   110891 ** pIdx. A column affinity string has one character for each column in
   110892 ** the table, according to the affinity of the column:
   110893 **
   110894 **  Character      Column affinity
   110895 **  ------------------------------
   110896 **  'A'            BLOB
   110897 **  'B'            TEXT
   110898 **  'C'            NUMERIC
   110899 **  'D'            INTEGER
   110900 **  'F'            REAL
   110901 **
   110902 ** An extra 'D' is appended to the end of the string to cover the
   110903 ** rowid that appears as the last column in every index.
   110904 **
   110905 ** Memory for the buffer containing the column index affinity string
   110906 ** is managed along with the rest of the Index structure. It will be
   110907 ** released when sqlite3DeleteIndex() is called.
   110908 */
   110909 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
   110910   if( !pIdx->zColAff ){
   110911     /* The first time a column affinity string for a particular index is
   110912     ** required, it is allocated and populated here. It is then stored as
   110913     ** a member of the Index structure for subsequent use.
   110914     **
   110915     ** The column affinity string will eventually be deleted by
   110916     ** sqliteDeleteIndex() when the Index structure itself is cleaned
   110917     ** up.
   110918     */
   110919     int n;
   110920     Table *pTab = pIdx->pTable;
   110921     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
   110922     if( !pIdx->zColAff ){
   110923       sqlite3OomFault(db);
   110924       return 0;
   110925     }
   110926     for(n=0; n<pIdx->nColumn; n++){
   110927       i16 x = pIdx->aiColumn[n];
   110928       if( x>=0 ){
   110929         pIdx->zColAff[n] = pTab->aCol[x].affinity;
   110930       }else if( x==XN_ROWID ){
   110931         pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
   110932       }else{
   110933         char aff;
   110934         assert( x==XN_EXPR );
   110935         assert( pIdx->aColExpr!=0 );
   110936         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
   110937         if( aff==0 ) aff = SQLITE_AFF_BLOB;
   110938         pIdx->zColAff[n] = aff;
   110939       }
   110940     }
   110941     pIdx->zColAff[n] = 0;
   110942   }
   110943 
   110944   return pIdx->zColAff;
   110945 }
   110946 
   110947 /*
   110948 ** Compute the affinity string for table pTab, if it has not already been
   110949 ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
   110950 **
   110951 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
   110952 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
   110953 ** for register iReg and following.  Or if affinities exists and iReg==0,
   110954 ** then just set the P4 operand of the previous opcode (which should  be
   110955 ** an OP_MakeRecord) to the affinity string.
   110956 **
   110957 ** A column affinity string has one character per column:
   110958 **
   110959 **  Character      Column affinity
   110960 **  ------------------------------
   110961 **  'A'            BLOB
   110962 **  'B'            TEXT
   110963 **  'C'            NUMERIC
   110964 **  'D'            INTEGER
   110965 **  'E'            REAL
   110966 */
   110967 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
   110968   int i;
   110969   char *zColAff = pTab->zColAff;
   110970   if( zColAff==0 ){
   110971     sqlite3 *db = sqlite3VdbeDb(v);
   110972     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   110973     if( !zColAff ){
   110974       sqlite3OomFault(db);
   110975       return;
   110976     }
   110977 
   110978     for(i=0; i<pTab->nCol; i++){
   110979       zColAff[i] = pTab->aCol[i].affinity;
   110980     }
   110981     do{
   110982       zColAff[i--] = 0;
   110983     }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
   110984     pTab->zColAff = zColAff;
   110985   }
   110986   i = sqlite3Strlen30(zColAff);
   110987   if( i ){
   110988     if( iReg ){
   110989       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
   110990     }else{
   110991       sqlite3VdbeChangeP4(v, -1, zColAff, i);
   110992     }
   110993   }
   110994 }
   110995 
   110996 /*
   110997 ** Return non-zero if the table pTab in database iDb or any of its indices
   110998 ** have been opened at any point in the VDBE program. This is used to see if
   110999 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
   111000 ** run without using a temporary table for the results of the SELECT.
   111001 */
   111002 static int readsTable(Parse *p, int iDb, Table *pTab){
   111003   Vdbe *v = sqlite3GetVdbe(p);
   111004   int i;
   111005   int iEnd = sqlite3VdbeCurrentAddr(v);
   111006 #ifndef SQLITE_OMIT_VIRTUALTABLE
   111007   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   111008 #endif
   111009 
   111010   for(i=1; i<iEnd; i++){
   111011     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   111012     assert( pOp!=0 );
   111013     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   111014       Index *pIndex;
   111015       int tnum = pOp->p2;
   111016       if( tnum==pTab->tnum ){
   111017         return 1;
   111018       }
   111019       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   111020         if( tnum==pIndex->tnum ){
   111021           return 1;
   111022         }
   111023       }
   111024     }
   111025 #ifndef SQLITE_OMIT_VIRTUALTABLE
   111026     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   111027       assert( pOp->p4.pVtab!=0 );
   111028       assert( pOp->p4type==P4_VTAB );
   111029       return 1;
   111030     }
   111031 #endif
   111032   }
   111033   return 0;
   111034 }
   111035 
   111036 #ifndef SQLITE_OMIT_AUTOINCREMENT
   111037 /*
   111038 ** Locate or create an AutoincInfo structure associated with table pTab
   111039 ** which is in database iDb.  Return the register number for the register
   111040 ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
   111041 ** table.  (Also return zero when doing a VACUUM since we do not want to
   111042 ** update the AUTOINCREMENT counters during a VACUUM.)
   111043 **
   111044 ** There is at most one AutoincInfo structure per table even if the
   111045 ** same table is autoincremented multiple times due to inserts within
   111046 ** triggers.  A new AutoincInfo structure is created if this is the
   111047 ** first use of table pTab.  On 2nd and subsequent uses, the original
   111048 ** AutoincInfo structure is used.
   111049 **
   111050 ** Three memory locations are allocated:
   111051 **
   111052 **   (1)  Register to hold the name of the pTab table.
   111053 **   (2)  Register to hold the maximum ROWID of pTab.
   111054 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   111055 **
   111056 ** The 2nd register is the one that is returned.  That is all the
   111057 ** insert routine needs to know about.
   111058 */
   111059 static int autoIncBegin(
   111060   Parse *pParse,      /* Parsing context */
   111061   int iDb,            /* Index of the database holding pTab */
   111062   Table *pTab         /* The table we are writing to */
   111063 ){
   111064   int memId = 0;      /* Register holding maximum rowid */
   111065   if( (pTab->tabFlags & TF_Autoincrement)!=0
   111066    && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
   111067   ){
   111068     Parse *pToplevel = sqlite3ParseToplevel(pParse);
   111069     AutoincInfo *pInfo;
   111070 
   111071     pInfo = pToplevel->pAinc;
   111072     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   111073     if( pInfo==0 ){
   111074       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
   111075       if( pInfo==0 ) return 0;
   111076       pInfo->pNext = pToplevel->pAinc;
   111077       pToplevel->pAinc = pInfo;
   111078       pInfo->pTab = pTab;
   111079       pInfo->iDb = iDb;
   111080       pToplevel->nMem++;                  /* Register to hold name of table */
   111081       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   111082       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   111083     }
   111084     memId = pInfo->regCtr;
   111085   }
   111086   return memId;
   111087 }
   111088 
   111089 /*
   111090 ** This routine generates code that will initialize all of the
   111091 ** register used by the autoincrement tracker.
   111092 */
   111093 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   111094   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   111095   sqlite3 *db = pParse->db;  /* The database connection */
   111096   Db *pDb;                   /* Database only autoinc table */
   111097   int memId;                 /* Register holding max rowid */
   111098   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   111099 
   111100   /* This routine is never called during trigger-generation.  It is
   111101   ** only called from the top-level */
   111102   assert( pParse->pTriggerTab==0 );
   111103   assert( sqlite3IsToplevel(pParse) );
   111104 
   111105   assert( v );   /* We failed long ago if this is not so */
   111106   for(p = pParse->pAinc; p; p = p->pNext){
   111107     static const int iLn = VDBE_OFFSET_LINENO(2);
   111108     static const VdbeOpList autoInc[] = {
   111109       /* 0  */ {OP_Null,    0,  0, 0},
   111110       /* 1  */ {OP_Rewind,  0,  9, 0},
   111111       /* 2  */ {OP_Column,  0,  0, 0},
   111112       /* 3  */ {OP_Ne,      0,  7, 0},
   111113       /* 4  */ {OP_Rowid,   0,  0, 0},
   111114       /* 5  */ {OP_Column,  0,  1, 0},
   111115       /* 6  */ {OP_Goto,    0,  9, 0},
   111116       /* 7  */ {OP_Next,    0,  2, 0},
   111117       /* 8  */ {OP_Integer, 0,  0, 0},
   111118       /* 9  */ {OP_Close,   0,  0, 0}
   111119     };
   111120     VdbeOp *aOp;
   111121     pDb = &db->aDb[p->iDb];
   111122     memId = p->regCtr;
   111123     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   111124     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   111125     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
   111126     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
   111127     if( aOp==0 ) break;
   111128     aOp[0].p2 = memId;
   111129     aOp[0].p3 = memId+1;
   111130     aOp[2].p3 = memId;
   111131     aOp[3].p1 = memId-1;
   111132     aOp[3].p3 = memId;
   111133     aOp[3].p5 = SQLITE_JUMPIFNULL;
   111134     aOp[4].p2 = memId+1;
   111135     aOp[5].p3 = memId;
   111136     aOp[8].p2 = memId;
   111137   }
   111138 }
   111139 
   111140 /*
   111141 ** Update the maximum rowid for an autoincrement calculation.
   111142 **
   111143 ** This routine should be called when the regRowid register holds a
   111144 ** new rowid that is about to be inserted.  If that new rowid is
   111145 ** larger than the maximum rowid in the memId memory cell, then the
   111146 ** memory cell is updated.
   111147 */
   111148 static void autoIncStep(Parse *pParse, int memId, int regRowid){
   111149   if( memId>0 ){
   111150     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   111151   }
   111152 }
   111153 
   111154 /*
   111155 ** This routine generates the code needed to write autoincrement
   111156 ** maximum rowid values back into the sqlite_sequence register.
   111157 ** Every statement that might do an INSERT into an autoincrement
   111158 ** table (either directly or through triggers) needs to call this
   111159 ** routine just before the "exit" code.
   111160 */
   111161 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
   111162   AutoincInfo *p;
   111163   Vdbe *v = pParse->pVdbe;
   111164   sqlite3 *db = pParse->db;
   111165 
   111166   assert( v );
   111167   for(p = pParse->pAinc; p; p = p->pNext){
   111168     static const int iLn = VDBE_OFFSET_LINENO(2);
   111169     static const VdbeOpList autoIncEnd[] = {
   111170       /* 0 */ {OP_NotNull,     0, 2, 0},
   111171       /* 1 */ {OP_NewRowid,    0, 0, 0},
   111172       /* 2 */ {OP_MakeRecord,  0, 2, 0},
   111173       /* 3 */ {OP_Insert,      0, 0, 0},
   111174       /* 4 */ {OP_Close,       0, 0, 0}
   111175     };
   111176     VdbeOp *aOp;
   111177     Db *pDb = &db->aDb[p->iDb];
   111178     int iRec;
   111179     int memId = p->regCtr;
   111180 
   111181     iRec = sqlite3GetTempReg(pParse);
   111182     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   111183     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   111184     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
   111185     if( aOp==0 ) break;
   111186     aOp[0].p1 = memId+1;
   111187     aOp[1].p2 = memId+1;
   111188     aOp[2].p1 = memId-1;
   111189     aOp[2].p3 = iRec;
   111190     aOp[3].p2 = iRec;
   111191     aOp[3].p3 = memId+1;
   111192     aOp[3].p5 = OPFLAG_APPEND;
   111193     sqlite3ReleaseTempReg(pParse, iRec);
   111194   }
   111195 }
   111196 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
   111197   if( pParse->pAinc ) autoIncrementEnd(pParse);
   111198 }
   111199 #else
   111200 /*
   111201 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   111202 ** above are all no-ops
   111203 */
   111204 # define autoIncBegin(A,B,C) (0)
   111205 # define autoIncStep(A,B,C)
   111206 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   111207 
   111208 
   111209 /* Forward declaration */
   111210 static int xferOptimization(
   111211   Parse *pParse,        /* Parser context */
   111212   Table *pDest,         /* The table we are inserting into */
   111213   Select *pSelect,      /* A SELECT statement to use as the data source */
   111214   int onError,          /* How to handle constraint errors */
   111215   int iDbDest           /* The database of pDest */
   111216 );
   111217 
   111218 /*
   111219 ** This routine is called to handle SQL of the following forms:
   111220 **
   111221 **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
   111222 **    insert into TABLE (IDLIST) select
   111223 **    insert into TABLE (IDLIST) default values
   111224 **
   111225 ** The IDLIST following the table name is always optional.  If omitted,
   111226 ** then a list of all (non-hidden) columns for the table is substituted.
   111227 ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
   111228 ** is omitted.
   111229 **
   111230 ** For the pSelect parameter holds the values to be inserted for the
   111231 ** first two forms shown above.  A VALUES clause is really just short-hand
   111232 ** for a SELECT statement that omits the FROM clause and everything else
   111233 ** that follows.  If the pSelect parameter is NULL, that means that the
   111234 ** DEFAULT VALUES form of the INSERT statement is intended.
   111235 **
   111236 ** The code generated follows one of four templates.  For a simple
   111237 ** insert with data coming from a single-row VALUES clause, the code executes
   111238 ** once straight down through.  Pseudo-code follows (we call this
   111239 ** the "1st template"):
   111240 **
   111241 **         open write cursor to <table> and its indices
   111242 **         put VALUES clause expressions into registers
   111243 **         write the resulting record into <table>
   111244 **         cleanup
   111245 **
   111246 ** The three remaining templates assume the statement is of the form
   111247 **
   111248 **   INSERT INTO <table> SELECT ...
   111249 **
   111250 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   111251 ** in other words if the SELECT pulls all columns from a single table
   111252 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   111253 ** if <table2> and <table1> are distinct tables but have identical
   111254 ** schemas, including all the same indices, then a special optimization
   111255 ** is invoked that copies raw records from <table2> over to <table1>.
   111256 ** See the xferOptimization() function for the implementation of this
   111257 ** template.  This is the 2nd template.
   111258 **
   111259 **         open a write cursor to <table>
   111260 **         open read cursor on <table2>
   111261 **         transfer all records in <table2> over to <table>
   111262 **         close cursors
   111263 **         foreach index on <table>
   111264 **           open a write cursor on the <table> index
   111265 **           open a read cursor on the corresponding <table2> index
   111266 **           transfer all records from the read to the write cursors
   111267 **           close cursors
   111268 **         end foreach
   111269 **
   111270 ** The 3rd template is for when the second template does not apply
   111271 ** and the SELECT clause does not read from <table> at any time.
   111272 ** The generated code follows this template:
   111273 **
   111274 **         X <- A
   111275 **         goto B
   111276 **      A: setup for the SELECT
   111277 **         loop over the rows in the SELECT
   111278 **           load values into registers R..R+n
   111279 **           yield X
   111280 **         end loop
   111281 **         cleanup after the SELECT
   111282 **         end-coroutine X
   111283 **      B: open write cursor to <table> and its indices
   111284 **      C: yield X, at EOF goto D
   111285 **         insert the select result into <table> from R..R+n
   111286 **         goto C
   111287 **      D: cleanup
   111288 **
   111289 ** The 4th template is used if the insert statement takes its
   111290 ** values from a SELECT but the data is being inserted into a table
   111291 ** that is also read as part of the SELECT.  In the third form,
   111292 ** we have to use an intermediate table to store the results of
   111293 ** the select.  The template is like this:
   111294 **
   111295 **         X <- A
   111296 **         goto B
   111297 **      A: setup for the SELECT
   111298 **         loop over the tables in the SELECT
   111299 **           load value into register R..R+n
   111300 **           yield X
   111301 **         end loop
   111302 **         cleanup after the SELECT
   111303 **         end co-routine R
   111304 **      B: open temp table
   111305 **      L: yield X, at EOF goto M
   111306 **         insert row from R..R+n into temp table
   111307 **         goto L
   111308 **      M: open write cursor to <table> and its indices
   111309 **         rewind temp table
   111310 **      C: loop over rows of intermediate table
   111311 **           transfer values form intermediate table into <table>
   111312 **         end loop
   111313 **      D: cleanup
   111314 */
   111315 SQLITE_PRIVATE void sqlite3Insert(
   111316   Parse *pParse,        /* Parser context */
   111317   SrcList *pTabList,    /* Name of table into which we are inserting */
   111318   Select *pSelect,      /* A SELECT statement to use as the data source */
   111319   IdList *pColumn,      /* Column names corresponding to IDLIST. */
   111320   int onError           /* How to handle constraint errors */
   111321 ){
   111322   sqlite3 *db;          /* The main database structure */
   111323   Table *pTab;          /* The table to insert into.  aka TABLE */
   111324   int i, j;             /* Loop counters */
   111325   Vdbe *v;              /* Generate code into this virtual machine */
   111326   Index *pIdx;          /* For looping over indices of the table */
   111327   int nColumn;          /* Number of columns in the data */
   111328   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   111329   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
   111330   int iIdxCur = 0;      /* First index cursor */
   111331   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   111332   int endOfLoop;        /* Label for the end of the insertion loop */
   111333   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   111334   int addrInsTop = 0;   /* Jump to label "D" */
   111335   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   111336   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   111337   int iDb;              /* Index of database holding TABLE */
   111338   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
   111339   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
   111340   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
   111341   u8 bIdListInOrder;    /* True if IDLIST is in table order */
   111342   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
   111343 
   111344   /* Register allocations */
   111345   int regFromSelect = 0;/* Base register for data coming from SELECT */
   111346   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   111347   int regRowCount = 0;  /* Memory cell used for the row counter */
   111348   int regIns;           /* Block of regs holding rowid+data being inserted */
   111349   int regRowid;         /* registers holding insert rowid */
   111350   int regData;          /* register holding first column to insert */
   111351   int *aRegIdx = 0;     /* One register allocated to each index */
   111352 
   111353 #ifndef SQLITE_OMIT_TRIGGER
   111354   int isView;                 /* True if attempting to insert into a view */
   111355   Trigger *pTrigger;          /* List of triggers on pTab, if required */
   111356   int tmask;                  /* Mask of trigger times */
   111357 #endif
   111358 
   111359   db = pParse->db;
   111360   if( pParse->nErr || db->mallocFailed ){
   111361     goto insert_cleanup;
   111362   }
   111363   dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
   111364 
   111365   /* If the Select object is really just a simple VALUES() list with a
   111366   ** single row (the common case) then keep that one row of values
   111367   ** and discard the other (unused) parts of the pSelect object
   111368   */
   111369   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
   111370     pList = pSelect->pEList;
   111371     pSelect->pEList = 0;
   111372     sqlite3SelectDelete(db, pSelect);
   111373     pSelect = 0;
   111374   }
   111375 
   111376   /* Locate the table into which we will be inserting new information.
   111377   */
   111378   assert( pTabList->nSrc==1 );
   111379   pTab = sqlite3SrcListLookup(pParse, pTabList);
   111380   if( pTab==0 ){
   111381     goto insert_cleanup;
   111382   }
   111383   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   111384   assert( iDb<db->nDb );
   111385   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
   111386                        db->aDb[iDb].zDbSName) ){
   111387     goto insert_cleanup;
   111388   }
   111389   withoutRowid = !HasRowid(pTab);
   111390 
   111391   /* Figure out if we have any triggers and if the table being
   111392   ** inserted into is a view
   111393   */
   111394 #ifndef SQLITE_OMIT_TRIGGER
   111395   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   111396   isView = pTab->pSelect!=0;
   111397 #else
   111398 # define pTrigger 0
   111399 # define tmask 0
   111400 # define isView 0
   111401 #endif
   111402 #ifdef SQLITE_OMIT_VIEW
   111403 # undef isView
   111404 # define isView 0
   111405 #endif
   111406   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   111407 
   111408   /* If pTab is really a view, make sure it has been initialized.
   111409   ** ViewGetColumnNames() is a no-op if pTab is not a view.
   111410   */
   111411   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   111412     goto insert_cleanup;
   111413   }
   111414 
   111415   /* Cannot insert into a read-only table.
   111416   */
   111417   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   111418     goto insert_cleanup;
   111419   }
   111420 
   111421   /* Allocate a VDBE
   111422   */
   111423   v = sqlite3GetVdbe(pParse);
   111424   if( v==0 ) goto insert_cleanup;
   111425   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   111426   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   111427 
   111428 #ifndef SQLITE_OMIT_XFER_OPT
   111429   /* If the statement is of the form
   111430   **
   111431   **       INSERT INTO <table1> SELECT * FROM <table2>;
   111432   **
   111433   ** Then special optimizations can be applied that make the transfer
   111434   ** very fast and which reduce fragmentation of indices.
   111435   **
   111436   ** This is the 2nd template.
   111437   */
   111438   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   111439     assert( !pTrigger );
   111440     assert( pList==0 );
   111441     goto insert_end;
   111442   }
   111443 #endif /* SQLITE_OMIT_XFER_OPT */
   111444 
   111445   /* If this is an AUTOINCREMENT table, look up the sequence number in the
   111446   ** sqlite_sequence table and store it in memory cell regAutoinc.
   111447   */
   111448   regAutoinc = autoIncBegin(pParse, iDb, pTab);
   111449 
   111450   /* Allocate registers for holding the rowid of the new row,
   111451   ** the content of the new row, and the assembled row record.
   111452   */
   111453   regRowid = regIns = pParse->nMem+1;
   111454   pParse->nMem += pTab->nCol + 1;
   111455   if( IsVirtual(pTab) ){
   111456     regRowid++;
   111457     pParse->nMem++;
   111458   }
   111459   regData = regRowid+1;
   111460 
   111461   /* If the INSERT statement included an IDLIST term, then make sure
   111462   ** all elements of the IDLIST really are columns of the table and
   111463   ** remember the column indices.
   111464   **
   111465   ** If the table has an INTEGER PRIMARY KEY column and that column
   111466   ** is named in the IDLIST, then record in the ipkColumn variable
   111467   ** the index into IDLIST of the primary key column.  ipkColumn is
   111468   ** the index of the primary key as it appears in IDLIST, not as
   111469   ** is appears in the original table.  (The index of the INTEGER
   111470   ** PRIMARY KEY in the original table is pTab->iPKey.)
   111471   */
   111472   bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
   111473   if( pColumn ){
   111474     for(i=0; i<pColumn->nId; i++){
   111475       pColumn->a[i].idx = -1;
   111476     }
   111477     for(i=0; i<pColumn->nId; i++){
   111478       for(j=0; j<pTab->nCol; j++){
   111479         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   111480           pColumn->a[i].idx = j;
   111481           if( i!=j ) bIdListInOrder = 0;
   111482           if( j==pTab->iPKey ){
   111483             ipkColumn = i;  assert( !withoutRowid );
   111484           }
   111485           break;
   111486         }
   111487       }
   111488       if( j>=pTab->nCol ){
   111489         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
   111490           ipkColumn = i;
   111491           bIdListInOrder = 0;
   111492         }else{
   111493           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   111494               pTabList, 0, pColumn->a[i].zName);
   111495           pParse->checkSchema = 1;
   111496           goto insert_cleanup;
   111497         }
   111498       }
   111499     }
   111500   }
   111501 
   111502   /* Figure out how many columns of data are supplied.  If the data
   111503   ** is coming from a SELECT statement, then generate a co-routine that
   111504   ** produces a single row of the SELECT on each invocation.  The
   111505   ** co-routine is the common header to the 3rd and 4th templates.
   111506   */
   111507   if( pSelect ){
   111508     /* Data is coming from a SELECT or from a multi-row VALUES clause.
   111509     ** Generate a co-routine to run the SELECT. */
   111510     int regYield;       /* Register holding co-routine entry-point */
   111511     int addrTop;        /* Top of the co-routine */
   111512     int rc;             /* Result code */
   111513 
   111514     regYield = ++pParse->nMem;
   111515     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
   111516     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
   111517     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
   111518     dest.iSdst = bIdListInOrder ? regData : 0;
   111519     dest.nSdst = pTab->nCol;
   111520     rc = sqlite3Select(pParse, pSelect, &dest);
   111521     regFromSelect = dest.iSdst;
   111522     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
   111523     sqlite3VdbeEndCoroutine(v, regYield);
   111524     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
   111525     assert( pSelect->pEList );
   111526     nColumn = pSelect->pEList->nExpr;
   111527 
   111528     /* Set useTempTable to TRUE if the result of the SELECT statement
   111529     ** should be written into a temporary table (template 4).  Set to
   111530     ** FALSE if each output row of the SELECT can be written directly into
   111531     ** the destination table (template 3).
   111532     **
   111533     ** A temp table must be used if the table being updated is also one
   111534     ** of the tables being read by the SELECT statement.  Also use a
   111535     ** temp table in the case of row triggers.
   111536     */
   111537     if( pTrigger || readsTable(pParse, iDb, pTab) ){
   111538       useTempTable = 1;
   111539     }
   111540 
   111541     if( useTempTable ){
   111542       /* Invoke the coroutine to extract information from the SELECT
   111543       ** and add it to a transient table srcTab.  The code generated
   111544       ** here is from the 4th template:
   111545       **
   111546       **      B: open temp table
   111547       **      L: yield X, goto M at EOF
   111548       **         insert row from R..R+n into temp table
   111549       **         goto L
   111550       **      M: ...
   111551       */
   111552       int regRec;          /* Register to hold packed record */
   111553       int regTempRowid;    /* Register to hold temp table ROWID */
   111554       int addrL;           /* Label "L" */
   111555 
   111556       srcTab = pParse->nTab++;
   111557       regRec = sqlite3GetTempReg(pParse);
   111558       regTempRowid = sqlite3GetTempReg(pParse);
   111559       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   111560       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
   111561       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   111562       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   111563       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   111564       sqlite3VdbeGoto(v, addrL);
   111565       sqlite3VdbeJumpHere(v, addrL);
   111566       sqlite3ReleaseTempReg(pParse, regRec);
   111567       sqlite3ReleaseTempReg(pParse, regTempRowid);
   111568     }
   111569   }else{
   111570     /* This is the case if the data for the INSERT is coming from a
   111571     ** single-row VALUES clause
   111572     */
   111573     NameContext sNC;
   111574     memset(&sNC, 0, sizeof(sNC));
   111575     sNC.pParse = pParse;
   111576     srcTab = -1;
   111577     assert( useTempTable==0 );
   111578     if( pList ){
   111579       nColumn = pList->nExpr;
   111580       if( sqlite3ResolveExprListNames(&sNC, pList) ){
   111581         goto insert_cleanup;
   111582       }
   111583     }else{
   111584       nColumn = 0;
   111585     }
   111586   }
   111587 
   111588   /* If there is no IDLIST term but the table has an integer primary
   111589   ** key, the set the ipkColumn variable to the integer primary key
   111590   ** column index in the original table definition.
   111591   */
   111592   if( pColumn==0 && nColumn>0 ){
   111593     ipkColumn = pTab->iPKey;
   111594   }
   111595 
   111596   /* Make sure the number of columns in the source data matches the number
   111597   ** of columns to be inserted into the table.
   111598   */
   111599   for(i=0; i<pTab->nCol; i++){
   111600     nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   111601   }
   111602   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   111603     sqlite3ErrorMsg(pParse,
   111604        "table %S has %d columns but %d values were supplied",
   111605        pTabList, 0, pTab->nCol-nHidden, nColumn);
   111606     goto insert_cleanup;
   111607   }
   111608   if( pColumn!=0 && nColumn!=pColumn->nId ){
   111609     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   111610     goto insert_cleanup;
   111611   }
   111612 
   111613   /* Initialize the count of rows to be inserted
   111614   */
   111615   if( db->flags & SQLITE_CountRows ){
   111616     regRowCount = ++pParse->nMem;
   111617     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   111618   }
   111619 
   111620   /* If this is not a view, open the table and and all indices */
   111621   if( !isView ){
   111622     int nIdx;
   111623     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
   111624                                       &iDataCur, &iIdxCur);
   111625     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
   111626     if( aRegIdx==0 ){
   111627       goto insert_cleanup;
   111628     }
   111629     for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
   111630       assert( pIdx );
   111631       aRegIdx[i] = ++pParse->nMem;
   111632       pParse->nMem += pIdx->nColumn;
   111633     }
   111634   }
   111635 
   111636   /* This is the top of the main insertion loop */
   111637   if( useTempTable ){
   111638     /* This block codes the top of loop only.  The complete loop is the
   111639     ** following pseudocode (template 4):
   111640     **
   111641     **         rewind temp table, if empty goto D
   111642     **      C: loop over rows of intermediate table
   111643     **           transfer values form intermediate table into <table>
   111644     **         end loop
   111645     **      D: ...
   111646     */
   111647     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
   111648     addrCont = sqlite3VdbeCurrentAddr(v);
   111649   }else if( pSelect ){
   111650     /* This block codes the top of loop only.  The complete loop is the
   111651     ** following pseudocode (template 3):
   111652     **
   111653     **      C: yield X, at EOF goto D
   111654     **         insert the select result into <table> from R..R+n
   111655     **         goto C
   111656     **      D: ...
   111657     */
   111658     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
   111659     VdbeCoverage(v);
   111660   }
   111661 
   111662   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   111663   */
   111664   endOfLoop = sqlite3VdbeMakeLabel(v);
   111665   if( tmask & TRIGGER_BEFORE ){
   111666     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   111667 
   111668     /* build the NEW.* reference row.  Note that if there is an INTEGER
   111669     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   111670     ** translated into a unique ID for the row.  But on a BEFORE trigger,
   111671     ** we do not know what the unique ID will be (because the insert has
   111672     ** not happened yet) so we substitute a rowid of -1
   111673     */
   111674     if( ipkColumn<0 ){
   111675       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   111676     }else{
   111677       int addr1;
   111678       assert( !withoutRowid );
   111679       if( useTempTable ){
   111680         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
   111681       }else{
   111682         assert( pSelect==0 );  /* Otherwise useTempTable is true */
   111683         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
   111684       }
   111685       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
   111686       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   111687       sqlite3VdbeJumpHere(v, addr1);
   111688       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
   111689     }
   111690 
   111691     /* Cannot have triggers on a virtual table. If it were possible,
   111692     ** this block would have to account for hidden column.
   111693     */
   111694     assert( !IsVirtual(pTab) );
   111695 
   111696     /* Create the new column data
   111697     */
   111698     for(i=j=0; i<pTab->nCol; i++){
   111699       if( pColumn ){
   111700         for(j=0; j<pColumn->nId; j++){
   111701           if( pColumn->a[j].idx==i ) break;
   111702         }
   111703       }
   111704       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
   111705             || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
   111706         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   111707       }else if( useTempTable ){
   111708         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
   111709       }else{
   111710         assert( pSelect==0 ); /* Otherwise useTempTable is true */
   111711         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   111712       }
   111713       if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
   111714     }
   111715 
   111716     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   111717     ** do not attempt any conversions before assembling the record.
   111718     ** If this is a real table, attempt conversions as required by the
   111719     ** table column affinities.
   111720     */
   111721     if( !isView ){
   111722       sqlite3TableAffinity(v, pTab, regCols+1);
   111723     }
   111724 
   111725     /* Fire BEFORE or INSTEAD OF triggers */
   111726     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
   111727         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   111728 
   111729     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   111730   }
   111731 
   111732   /* Compute the content of the next row to insert into a range of
   111733   ** registers beginning at regIns.
   111734   */
   111735   if( !isView ){
   111736     if( IsVirtual(pTab) ){
   111737       /* The row that the VUpdate opcode will delete: none */
   111738       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   111739     }
   111740     if( ipkColumn>=0 ){
   111741       if( useTempTable ){
   111742         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
   111743       }else if( pSelect ){
   111744         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
   111745       }else{
   111746         VdbeOp *pOp;
   111747         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
   111748         pOp = sqlite3VdbeGetOp(v, -1);
   111749         assert( pOp!=0 );
   111750         if( pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   111751           appendFlag = 1;
   111752           pOp->opcode = OP_NewRowid;
   111753           pOp->p1 = iDataCur;
   111754           pOp->p2 = regRowid;
   111755           pOp->p3 = regAutoinc;
   111756         }
   111757       }
   111758       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   111759       ** to generate a unique primary key value.
   111760       */
   111761       if( !appendFlag ){
   111762         int addr1;
   111763         if( !IsVirtual(pTab) ){
   111764           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
   111765           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   111766           sqlite3VdbeJumpHere(v, addr1);
   111767         }else{
   111768           addr1 = sqlite3VdbeCurrentAddr(v);
   111769           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
   111770         }
   111771         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
   111772       }
   111773     }else if( IsVirtual(pTab) || withoutRowid ){
   111774       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   111775     }else{
   111776       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   111777       appendFlag = 1;
   111778     }
   111779     autoIncStep(pParse, regAutoinc, regRowid);
   111780 
   111781     /* Compute data for all columns of the new entry, beginning
   111782     ** with the first column.
   111783     */
   111784     nHidden = 0;
   111785     for(i=0; i<pTab->nCol; i++){
   111786       int iRegStore = regRowid+1+i;
   111787       if( i==pTab->iPKey ){
   111788         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   111789         ** Whenever this column is read, the rowid will be substituted
   111790         ** in its place.  Hence, fill this column with a NULL to avoid
   111791         ** taking up data space with information that will never be used.
   111792         ** As there may be shallow copies of this value, make it a soft-NULL */
   111793         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
   111794         continue;
   111795       }
   111796       if( pColumn==0 ){
   111797         if( IsHiddenColumn(&pTab->aCol[i]) ){
   111798           j = -1;
   111799           nHidden++;
   111800         }else{
   111801           j = i - nHidden;
   111802         }
   111803       }else{
   111804         for(j=0; j<pColumn->nId; j++){
   111805           if( pColumn->a[j].idx==i ) break;
   111806         }
   111807       }
   111808       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   111809         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
   111810       }else if( useTempTable ){
   111811         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
   111812       }else if( pSelect ){
   111813         if( regFromSelect!=regData ){
   111814           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   111815         }
   111816       }else{
   111817         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   111818       }
   111819     }
   111820 
   111821     /* Generate code to check constraints and generate index keys and
   111822     ** do the insertion.
   111823     */
   111824 #ifndef SQLITE_OMIT_VIRTUALTABLE
   111825     if( IsVirtual(pTab) ){
   111826       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   111827       sqlite3VtabMakeWritable(pParse, pTab);
   111828       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   111829       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   111830       sqlite3MayAbort(pParse);
   111831     }else
   111832 #endif
   111833     {
   111834       int isReplace;    /* Set to true if constraints may cause a replace */
   111835       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
   111836       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
   111837           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
   111838       );
   111839       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
   111840 
   111841       /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
   111842       ** constraints or (b) there are no triggers and this table is not a
   111843       ** parent table in a foreign key constraint. It is safe to set the
   111844       ** flag in the second case as if any REPLACE constraint is hit, an
   111845       ** OP_Delete or OP_IdxDelete instruction will be executed on each
   111846       ** cursor that is disturbed. And these instructions both clear the
   111847       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
   111848       ** functionality.  */
   111849       bUseSeek = (isReplace==0 || (pTrigger==0 &&
   111850           ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
   111851       ));
   111852       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
   111853           regIns, aRegIdx, 0, appendFlag, bUseSeek
   111854       );
   111855     }
   111856   }
   111857 
   111858   /* Update the count of rows that are inserted
   111859   */
   111860   if( (db->flags & SQLITE_CountRows)!=0 ){
   111861     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   111862   }
   111863 
   111864   if( pTrigger ){
   111865     /* Code AFTER triggers */
   111866     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
   111867         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   111868   }
   111869 
   111870   /* The bottom of the main insertion loop, if the data source
   111871   ** is a SELECT statement.
   111872   */
   111873   sqlite3VdbeResolveLabel(v, endOfLoop);
   111874   if( useTempTable ){
   111875     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
   111876     sqlite3VdbeJumpHere(v, addrInsTop);
   111877     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   111878   }else if( pSelect ){
   111879     sqlite3VdbeGoto(v, addrCont);
   111880     sqlite3VdbeJumpHere(v, addrInsTop);
   111881   }
   111882 
   111883 insert_end:
   111884   /* Update the sqlite_sequence table by storing the content of the
   111885   ** maximum rowid counter values recorded while inserting into
   111886   ** autoincrement tables.
   111887   */
   111888   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   111889     sqlite3AutoincrementEnd(pParse);
   111890   }
   111891 
   111892   /*
   111893   ** Return the number of rows inserted. If this routine is
   111894   ** generating code because of a call to sqlite3NestedParse(), do not
   111895   ** invoke the callback function.
   111896   */
   111897   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   111898     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   111899     sqlite3VdbeSetNumCols(v, 1);
   111900     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   111901   }
   111902 
   111903 insert_cleanup:
   111904   sqlite3SrcListDelete(db, pTabList);
   111905   sqlite3ExprListDelete(db, pList);
   111906   sqlite3SelectDelete(db, pSelect);
   111907   sqlite3IdListDelete(db, pColumn);
   111908   sqlite3DbFree(db, aRegIdx);
   111909 }
   111910 
   111911 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   111912 ** they may interfere with compilation of other functions in this file
   111913 ** (or in another file, if this file becomes part of the amalgamation).  */
   111914 #ifdef isView
   111915  #undef isView
   111916 #endif
   111917 #ifdef pTrigger
   111918  #undef pTrigger
   111919 #endif
   111920 #ifdef tmask
   111921  #undef tmask
   111922 #endif
   111923 
   111924 /*
   111925 ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
   111926 */
   111927 #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
   111928 #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
   111929 
   111930 /* This is the Walker callback from checkConstraintUnchanged().  Set
   111931 ** bit 0x01 of pWalker->eCode if
   111932 ** pWalker->eCode to 0 if this expression node references any of the
   111933 ** columns that are being modifed by an UPDATE statement.
   111934 */
   111935 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
   111936   if( pExpr->op==TK_COLUMN ){
   111937     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
   111938     if( pExpr->iColumn>=0 ){
   111939       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
   111940         pWalker->eCode |= CKCNSTRNT_COLUMN;
   111941       }
   111942     }else{
   111943       pWalker->eCode |= CKCNSTRNT_ROWID;
   111944     }
   111945   }
   111946   return WRC_Continue;
   111947 }
   111948 
   111949 /*
   111950 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
   111951 ** only columns that are modified by the UPDATE are those for which
   111952 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
   111953 **
   111954 ** Return true if CHECK constraint pExpr does not use any of the
   111955 ** changing columns (or the rowid if it is changing).  In other words,
   111956 ** return true if this CHECK constraint can be skipped when validating
   111957 ** the new row in the UPDATE statement.
   111958 */
   111959 static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
   111960   Walker w;
   111961   memset(&w, 0, sizeof(w));
   111962   w.eCode = 0;
   111963   w.xExprCallback = checkConstraintExprNode;
   111964   w.u.aiCol = aiChng;
   111965   sqlite3WalkExpr(&w, pExpr);
   111966   if( !chngRowid ){
   111967     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
   111968     w.eCode &= ~CKCNSTRNT_ROWID;
   111969   }
   111970   testcase( w.eCode==0 );
   111971   testcase( w.eCode==CKCNSTRNT_COLUMN );
   111972   testcase( w.eCode==CKCNSTRNT_ROWID );
   111973   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
   111974   return !w.eCode;
   111975 }
   111976 
   111977 /*
   111978 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
   111979 ** on table pTab.
   111980 **
   111981 ** The regNewData parameter is the first register in a range that contains
   111982 ** the data to be inserted or the data after the update.  There will be
   111983 ** pTab->nCol+1 registers in this range.  The first register (the one
   111984 ** that regNewData points to) will contain the new rowid, or NULL in the
   111985 ** case of a WITHOUT ROWID table.  The second register in the range will
   111986 ** contain the content of the first table column.  The third register will
   111987 ** contain the content of the second table column.  And so forth.
   111988 **
   111989 ** The regOldData parameter is similar to regNewData except that it contains
   111990 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
   111991 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
   111992 ** checking regOldData for zero.
   111993 **
   111994 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
   111995 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
   111996 ** might be modified by the UPDATE.  If pkChng is false, then the key of
   111997 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
   111998 **
   111999 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
   112000 ** was explicitly specified as part of the INSERT statement.  If pkChng
   112001 ** is zero, it means that the either rowid is computed automatically or
   112002 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
   112003 ** pkChng will only be true if the INSERT statement provides an integer
   112004 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
   112005 **
   112006 ** The code generated by this routine will store new index entries into
   112007 ** registers identified by aRegIdx[].  No index entry is created for
   112008 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
   112009 ** the same as the order of indices on the linked list of indices
   112010 ** at pTab->pIndex.
   112011 **
   112012 ** The caller must have already opened writeable cursors on the main
   112013 ** table and all applicable indices (that is to say, all indices for which
   112014 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
   112015 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
   112016 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
   112017 ** for the first index in the pTab->pIndex list.  Cursors for other indices
   112018 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
   112019 **
   112020 ** This routine also generates code to check constraints.  NOT NULL,
   112021 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   112022 ** then the appropriate action is performed.  There are five possible
   112023 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   112024 **
   112025 **  Constraint type  Action       What Happens
   112026 **  ---------------  ----------   ----------------------------------------
   112027 **  any              ROLLBACK     The current transaction is rolled back and
   112028 **                                sqlite3_step() returns immediately with a
   112029 **                                return code of SQLITE_CONSTRAINT.
   112030 **
   112031 **  any              ABORT        Back out changes from the current command
   112032 **                                only (do not do a complete rollback) then
   112033 **                                cause sqlite3_step() to return immediately
   112034 **                                with SQLITE_CONSTRAINT.
   112035 **
   112036 **  any              FAIL         Sqlite3_step() returns immediately with a
   112037 **                                return code of SQLITE_CONSTRAINT.  The
   112038 **                                transaction is not rolled back and any
   112039 **                                changes to prior rows are retained.
   112040 **
   112041 **  any              IGNORE       The attempt in insert or update the current
   112042 **                                row is skipped, without throwing an error.
   112043 **                                Processing continues with the next row.
   112044 **                                (There is an immediate jump to ignoreDest.)
   112045 **
   112046 **  NOT NULL         REPLACE      The NULL value is replace by the default
   112047 **                                value for that column.  If the default value
   112048 **                                is NULL, the action is the same as ABORT.
   112049 **
   112050 **  UNIQUE           REPLACE      The other row that conflicts with the row
   112051 **                                being inserted is removed.
   112052 **
   112053 **  CHECK            REPLACE      Illegal.  The results in an exception.
   112054 **
   112055 ** Which action to take is determined by the overrideError parameter.
   112056 ** Or if overrideError==OE_Default, then the pParse->onError parameter
   112057 ** is used.  Or if pParse->onError==OE_Default then the onError value
   112058 ** for the constraint is used.
   112059 */
   112060 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   112061   Parse *pParse,       /* The parser context */
   112062   Table *pTab,         /* The table being inserted or updated */
   112063   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
   112064   int iDataCur,        /* Canonical data cursor (main table or PK index) */
   112065   int iIdxCur,         /* First index cursor */
   112066   int regNewData,      /* First register in a range holding values to insert */
   112067   int regOldData,      /* Previous content.  0 for INSERTs */
   112068   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
   112069   u8 overrideError,    /* Override onError to this if not OE_Default */
   112070   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
   112071   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
   112072   int *aiChng          /* column i is unchanged if aiChng[i]<0 */
   112073 ){
   112074   Vdbe *v;             /* VDBE under constrution */
   112075   Index *pIdx;         /* Pointer to one of the indices */
   112076   Index *pPk = 0;      /* The PRIMARY KEY index */
   112077   sqlite3 *db;         /* Database connection */
   112078   int i;               /* loop counter */
   112079   int ix;              /* Index loop counter */
   112080   int nCol;            /* Number of columns */
   112081   int onError;         /* Conflict resolution strategy */
   112082   int addr1;           /* Address of jump instruction */
   112083   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   112084   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
   112085   int ipkTop = 0;      /* Top of the rowid change constraint check */
   112086   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
   112087   u8 isUpdate;         /* True if this is an UPDATE operation */
   112088   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
   112089 
   112090   isUpdate = regOldData!=0;
   112091   db = pParse->db;
   112092   v = sqlite3GetVdbe(pParse);
   112093   assert( v!=0 );
   112094   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   112095   nCol = pTab->nCol;
   112096 
   112097   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
   112098   ** normal rowid tables.  nPkField is the number of key fields in the
   112099   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
   112100   ** number of fields in the true primary key of the table. */
   112101   if( HasRowid(pTab) ){
   112102     pPk = 0;
   112103     nPkField = 1;
   112104   }else{
   112105     pPk = sqlite3PrimaryKeyIndex(pTab);
   112106     nPkField = pPk->nKeyCol;
   112107   }
   112108 
   112109   /* Record that this module has started */
   112110   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
   112111                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
   112112 
   112113   /* Test all NOT NULL constraints.
   112114   */
   112115   for(i=0; i<nCol; i++){
   112116     if( i==pTab->iPKey ){
   112117       continue;        /* ROWID is never NULL */
   112118     }
   112119     if( aiChng && aiChng[i]<0 ){
   112120       /* Don't bother checking for NOT NULL on columns that do not change */
   112121       continue;
   112122     }
   112123     onError = pTab->aCol[i].notNull;
   112124     if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
   112125     if( overrideError!=OE_Default ){
   112126       onError = overrideError;
   112127     }else if( onError==OE_Default ){
   112128       onError = OE_Abort;
   112129     }
   112130     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   112131       onError = OE_Abort;
   112132     }
   112133     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   112134         || onError==OE_Ignore || onError==OE_Replace );
   112135     switch( onError ){
   112136       case OE_Abort:
   112137         sqlite3MayAbort(pParse);
   112138         /* Fall through */
   112139       case OE_Rollback:
   112140       case OE_Fail: {
   112141         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
   112142                                     pTab->aCol[i].zName);
   112143         sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
   112144                           regNewData+1+i);
   112145         sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
   112146         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
   112147         VdbeCoverage(v);
   112148         break;
   112149       }
   112150       case OE_Ignore: {
   112151         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
   112152         VdbeCoverage(v);
   112153         break;
   112154       }
   112155       default: {
   112156         assert( onError==OE_Replace );
   112157         addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
   112158            VdbeCoverage(v);
   112159         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
   112160         sqlite3VdbeJumpHere(v, addr1);
   112161         break;
   112162       }
   112163     }
   112164   }
   112165 
   112166   /* Test all CHECK constraints
   112167   */
   112168 #ifndef SQLITE_OMIT_CHECK
   112169   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
   112170     ExprList *pCheck = pTab->pCheck;
   112171     pParse->iSelfTab = -(regNewData+1);
   112172     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
   112173     for(i=0; i<pCheck->nExpr; i++){
   112174       int allOk;
   112175       Expr *pExpr = pCheck->a[i].pExpr;
   112176       if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
   112177       allOk = sqlite3VdbeMakeLabel(v);
   112178       sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
   112179       if( onError==OE_Ignore ){
   112180         sqlite3VdbeGoto(v, ignoreDest);
   112181       }else{
   112182         char *zName = pCheck->a[i].zName;
   112183         if( zName==0 ) zName = pTab->zName;
   112184         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
   112185         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
   112186                               onError, zName, P4_TRANSIENT,
   112187                               P5_ConstraintCheck);
   112188       }
   112189       sqlite3VdbeResolveLabel(v, allOk);
   112190     }
   112191     pParse->iSelfTab = 0;
   112192   }
   112193 #endif /* !defined(SQLITE_OMIT_CHECK) */
   112194 
   112195   /* If rowid is changing, make sure the new rowid does not previously
   112196   ** exist in the table.
   112197   */
   112198   if( pkChng && pPk==0 ){
   112199     int addrRowidOk = sqlite3VdbeMakeLabel(v);
   112200 
   112201     /* Figure out what action to take in case of a rowid collision */
   112202     onError = pTab->keyConf;
   112203     if( overrideError!=OE_Default ){
   112204       onError = overrideError;
   112205     }else if( onError==OE_Default ){
   112206       onError = OE_Abort;
   112207     }
   112208 
   112209     if( isUpdate ){
   112210       /* pkChng!=0 does not mean that the rowid has changed, only that
   112211       ** it might have changed.  Skip the conflict logic below if the rowid
   112212       ** is unchanged. */
   112213       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
   112214       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   112215       VdbeCoverage(v);
   112216     }
   112217 
   112218     /* If the response to a rowid conflict is REPLACE but the response
   112219     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
   112220     ** to defer the running of the rowid conflict checking until after
   112221     ** the UNIQUE constraints have run.
   112222     */
   112223     if( onError==OE_Replace && overrideError!=OE_Replace ){
   112224       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   112225         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
   112226           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
   112227           break;
   112228         }
   112229       }
   112230     }
   112231 
   112232     /* Check to see if the new rowid already exists in the table.  Skip
   112233     ** the following conflict logic if it does not. */
   112234     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
   112235     VdbeCoverage(v);
   112236 
   112237     /* Generate code that deals with a rowid collision */
   112238     switch( onError ){
   112239       default: {
   112240         onError = OE_Abort;
   112241         /* Fall thru into the next case */
   112242       }
   112243       case OE_Rollback:
   112244       case OE_Abort:
   112245       case OE_Fail: {
   112246         sqlite3RowidConstraint(pParse, onError, pTab);
   112247         break;
   112248       }
   112249       case OE_Replace: {
   112250         /* If there are DELETE triggers on this table and the
   112251         ** recursive-triggers flag is set, call GenerateRowDelete() to
   112252         ** remove the conflicting row from the table. This will fire
   112253         ** the triggers and remove both the table and index b-tree entries.
   112254         **
   112255         ** Otherwise, if there are no triggers or the recursive-triggers
   112256         ** flag is not set, but the table has one or more indexes, call
   112257         ** GenerateRowIndexDelete(). This removes the index b-tree entries
   112258         ** only. The table b-tree entry will be replaced by the new entry
   112259         ** when it is inserted.
   112260         **
   112261         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
   112262         ** also invoke MultiWrite() to indicate that this VDBE may require
   112263         ** statement rollback (if the statement is aborted after the delete
   112264         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
   112265         ** but being more selective here allows statements like:
   112266         **
   112267         **   REPLACE INTO t(rowid) VALUES($newrowid)
   112268         **
   112269         ** to run without a statement journal if there are no indexes on the
   112270         ** table.
   112271         */
   112272         Trigger *pTrigger = 0;
   112273         if( db->flags&SQLITE_RecTriggers ){
   112274           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   112275         }
   112276         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
   112277           sqlite3MultiWrite(pParse);
   112278           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   112279                                    regNewData, 1, 0, OE_Replace, 1, -1);
   112280         }else{
   112281 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   112282           if( HasRowid(pTab) ){
   112283             /* This OP_Delete opcode fires the pre-update-hook only. It does
   112284             ** not modify the b-tree. It is more efficient to let the coming
   112285             ** OP_Insert replace the existing entry than it is to delete the
   112286             ** existing entry and then insert a new one. */
   112287             sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
   112288             sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
   112289           }
   112290 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   112291           if( pTab->pIndex ){
   112292             sqlite3MultiWrite(pParse);
   112293             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
   112294           }
   112295         }
   112296         seenReplace = 1;
   112297         break;
   112298       }
   112299       case OE_Ignore: {
   112300         /*assert( seenReplace==0 );*/
   112301         sqlite3VdbeGoto(v, ignoreDest);
   112302         break;
   112303       }
   112304     }
   112305     sqlite3VdbeResolveLabel(v, addrRowidOk);
   112306     if( ipkTop ){
   112307       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
   112308       sqlite3VdbeJumpHere(v, ipkTop);
   112309     }
   112310   }
   112311 
   112312   /* Test all UNIQUE constraints by creating entries for each UNIQUE
   112313   ** index and making sure that duplicate entries do not already exist.
   112314   ** Compute the revised record entries for indices as we go.
   112315   **
   112316   ** This loop also handles the case of the PRIMARY KEY index for a
   112317   ** WITHOUT ROWID table.
   112318   */
   112319   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
   112320     int regIdx;          /* Range of registers hold conent for pIdx */
   112321     int regR;            /* Range of registers holding conflicting PK */
   112322     int iThisCur;        /* Cursor for this UNIQUE index */
   112323     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
   112324 
   112325     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
   112326     if( bAffinityDone==0 ){
   112327       sqlite3TableAffinity(v, pTab, regNewData+1);
   112328       bAffinityDone = 1;
   112329     }
   112330     iThisCur = iIdxCur+ix;
   112331     addrUniqueOk = sqlite3VdbeMakeLabel(v);
   112332 
   112333     /* Skip partial indices for which the WHERE clause is not true */
   112334     if( pIdx->pPartIdxWhere ){
   112335       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
   112336       pParse->iSelfTab = -(regNewData+1);
   112337       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
   112338                             SQLITE_JUMPIFNULL);
   112339       pParse->iSelfTab = 0;
   112340     }
   112341 
   112342     /* Create a record for this index entry as it should appear after
   112343     ** the insert or update.  Store that record in the aRegIdx[ix] register
   112344     */
   112345     regIdx = aRegIdx[ix]+1;
   112346     for(i=0; i<pIdx->nColumn; i++){
   112347       int iField = pIdx->aiColumn[i];
   112348       int x;
   112349       if( iField==XN_EXPR ){
   112350         pParse->iSelfTab = -(regNewData+1);
   112351         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
   112352         pParse->iSelfTab = 0;
   112353         VdbeComment((v, "%s column %d", pIdx->zName, i));
   112354       }else{
   112355         if( iField==XN_ROWID || iField==pTab->iPKey ){
   112356           x = regNewData;
   112357         }else{
   112358           x = iField + regNewData + 1;
   112359         }
   112360         sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
   112361         VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
   112362       }
   112363     }
   112364     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
   112365     VdbeComment((v, "for %s", pIdx->zName));
   112366 #ifdef SQLITE_ENABLE_NULL_TRIM
   112367     if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
   112368 #endif
   112369 
   112370     /* In an UPDATE operation, if this index is the PRIMARY KEY index
   112371     ** of a WITHOUT ROWID table and there has been no change the
   112372     ** primary key, then no collision is possible.  The collision detection
   112373     ** logic below can all be skipped. */
   112374     if( isUpdate && pPk==pIdx && pkChng==0 ){
   112375       sqlite3VdbeResolveLabel(v, addrUniqueOk);
   112376       continue;
   112377     }
   112378 
   112379     /* Find out what action to take in case there is a uniqueness conflict */
   112380     onError = pIdx->onError;
   112381     if( onError==OE_None ){
   112382       sqlite3VdbeResolveLabel(v, addrUniqueOk);
   112383       continue;  /* pIdx is not a UNIQUE index */
   112384     }
   112385     if( overrideError!=OE_Default ){
   112386       onError = overrideError;
   112387     }else if( onError==OE_Default ){
   112388       onError = OE_Abort;
   112389     }
   112390 
   112391     /* Collision detection may be omitted if all of the following are true:
   112392     **   (1) The conflict resolution algorithm is REPLACE
   112393     **   (2) The table is a WITHOUT ROWID table
   112394     **   (3) There are no secondary indexes on the table
   112395     **   (4) No delete triggers need to be fired if there is a conflict
   112396     **   (5) No FK constraint counters need to be updated if a conflict occurs.
   112397     */
   112398     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
   112399      && pPk==pIdx                                   /* Condition 2 */
   112400      && onError==OE_Replace                         /* Condition 1 */
   112401      && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
   112402           0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
   112403      && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
   112404          (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
   112405     ){
   112406       sqlite3VdbeResolveLabel(v, addrUniqueOk);
   112407       continue;
   112408     }
   112409 
   112410     /* Check to see if the new index entry will be unique */
   112411     sqlite3ExprCachePush(pParse);
   112412     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
   112413                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
   112414 
   112415     /* Generate code to handle collisions */
   112416     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
   112417     if( isUpdate || onError==OE_Replace ){
   112418       if( HasRowid(pTab) ){
   112419         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
   112420         /* Conflict only if the rowid of the existing index entry
   112421         ** is different from old-rowid */
   112422         if( isUpdate ){
   112423           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
   112424           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   112425           VdbeCoverage(v);
   112426         }
   112427       }else{
   112428         int x;
   112429         /* Extract the PRIMARY KEY from the end of the index entry and
   112430         ** store it in registers regR..regR+nPk-1 */
   112431         if( pIdx!=pPk ){
   112432           for(i=0; i<pPk->nKeyCol; i++){
   112433             assert( pPk->aiColumn[i]>=0 );
   112434             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
   112435             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
   112436             VdbeComment((v, "%s.%s", pTab->zName,
   112437                          pTab->aCol[pPk->aiColumn[i]].zName));
   112438           }
   112439         }
   112440         if( isUpdate ){
   112441           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
   112442           ** table, only conflict if the new PRIMARY KEY values are actually
   112443           ** different from the old.
   112444           **
   112445           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
   112446           ** of the matched index row are different from the original PRIMARY
   112447           ** KEY values of this row before the update.  */
   112448           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
   112449           int op = OP_Ne;
   112450           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
   112451 
   112452           for(i=0; i<pPk->nKeyCol; i++){
   112453             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
   112454             x = pPk->aiColumn[i];
   112455             assert( x>=0 );
   112456             if( i==(pPk->nKeyCol-1) ){
   112457               addrJump = addrUniqueOk;
   112458               op = OP_Eq;
   112459             }
   112460             sqlite3VdbeAddOp4(v, op,
   112461                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
   112462             );
   112463             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   112464             VdbeCoverageIf(v, op==OP_Eq);
   112465             VdbeCoverageIf(v, op==OP_Ne);
   112466           }
   112467         }
   112468       }
   112469     }
   112470 
   112471     /* Generate code that executes if the new index entry is not unique */
   112472     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   112473         || onError==OE_Ignore || onError==OE_Replace );
   112474     switch( onError ){
   112475       case OE_Rollback:
   112476       case OE_Abort:
   112477       case OE_Fail: {
   112478         sqlite3UniqueConstraint(pParse, onError, pIdx);
   112479         break;
   112480       }
   112481       case OE_Ignore: {
   112482         sqlite3VdbeGoto(v, ignoreDest);
   112483         break;
   112484       }
   112485       default: {
   112486         Trigger *pTrigger = 0;
   112487         assert( onError==OE_Replace );
   112488         sqlite3MultiWrite(pParse);
   112489         if( db->flags&SQLITE_RecTriggers ){
   112490           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   112491         }
   112492         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
   112493             regR, nPkField, 0, OE_Replace,
   112494             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
   112495         seenReplace = 1;
   112496         break;
   112497       }
   112498     }
   112499     sqlite3VdbeResolveLabel(v, addrUniqueOk);
   112500     sqlite3ExprCachePop(pParse);
   112501     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
   112502   }
   112503   if( ipkTop ){
   112504     sqlite3VdbeGoto(v, ipkTop+1);
   112505     sqlite3VdbeJumpHere(v, ipkBottom);
   112506   }
   112507 
   112508   *pbMayReplace = seenReplace;
   112509   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
   112510 }
   112511 
   112512 #ifdef SQLITE_ENABLE_NULL_TRIM
   112513 /*
   112514 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
   112515 ** to be the number of columns in table pTab that must not be NULL-trimmed.
   112516 **
   112517 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
   112518 */
   112519 SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
   112520   u16 i;
   112521 
   112522   /* Records with omitted columns are only allowed for schema format
   112523   ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
   112524   if( pTab->pSchema->file_format<2 ) return;
   112525 
   112526   for(i=pTab->nCol-1; i>0; i--){
   112527     if( pTab->aCol[i].pDflt!=0 ) break;
   112528     if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
   112529   }
   112530   sqlite3VdbeChangeP5(v, i+1);
   112531 }
   112532 #endif
   112533 
   112534 /*
   112535 ** This routine generates code to finish the INSERT or UPDATE operation
   112536 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
   112537 ** A consecutive range of registers starting at regNewData contains the
   112538 ** rowid and the content to be inserted.
   112539 **
   112540 ** The arguments to this routine should be the same as the first six
   112541 ** arguments to sqlite3GenerateConstraintChecks.
   112542 */
   112543 SQLITE_PRIVATE void sqlite3CompleteInsertion(
   112544   Parse *pParse,      /* The parser context */
   112545   Table *pTab,        /* the table into which we are inserting */
   112546   int iDataCur,       /* Cursor of the canonical data source */
   112547   int iIdxCur,        /* First index cursor */
   112548   int regNewData,     /* Range of content */
   112549   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   112550   int update_flags,   /* True for UPDATE, False for INSERT */
   112551   int appendBias,     /* True if this is likely to be an append */
   112552   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
   112553 ){
   112554   Vdbe *v;            /* Prepared statements under construction */
   112555   Index *pIdx;        /* An index being inserted or updated */
   112556   u8 pik_flags;       /* flag values passed to the btree insert */
   112557   int regData;        /* Content registers (after the rowid) */
   112558   int regRec;         /* Register holding assembled record for the table */
   112559   int i;              /* Loop counter */
   112560   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
   112561 
   112562   assert( update_flags==0
   112563        || update_flags==OPFLAG_ISUPDATE
   112564        || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
   112565   );
   112566 
   112567   v = sqlite3GetVdbe(pParse);
   112568   assert( v!=0 );
   112569   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   112570   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   112571     if( aRegIdx[i]==0 ) continue;
   112572     bAffinityDone = 1;
   112573     if( pIdx->pPartIdxWhere ){
   112574       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
   112575       VdbeCoverage(v);
   112576     }
   112577     pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
   112578     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
   112579       assert( pParse->nested==0 );
   112580       pik_flags |= OPFLAG_NCHANGE;
   112581       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
   112582 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   112583       if( update_flags==0 ){
   112584         sqlite3VdbeAddOp4(v, OP_InsertInt,
   112585             iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
   112586         );
   112587         sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
   112588       }
   112589 #endif
   112590     }
   112591     sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
   112592                          aRegIdx[i]+1,
   112593                          pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
   112594     sqlite3VdbeChangeP5(v, pik_flags);
   112595   }
   112596   if( !HasRowid(pTab) ) return;
   112597   regData = regNewData + 1;
   112598   regRec = sqlite3GetTempReg(pParse);
   112599   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
   112600   sqlite3SetMakeRecordP5(v, pTab);
   112601   if( !bAffinityDone ){
   112602     sqlite3TableAffinity(v, pTab, 0);
   112603     sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
   112604   }
   112605   if( pParse->nested ){
   112606     pik_flags = 0;
   112607   }else{
   112608     pik_flags = OPFLAG_NCHANGE;
   112609     pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
   112610   }
   112611   if( appendBias ){
   112612     pik_flags |= OPFLAG_APPEND;
   112613   }
   112614   if( useSeekResult ){
   112615     pik_flags |= OPFLAG_USESEEKRESULT;
   112616   }
   112617   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
   112618   if( !pParse->nested ){
   112619     sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
   112620   }
   112621   sqlite3VdbeChangeP5(v, pik_flags);
   112622 }
   112623 
   112624 /*
   112625 ** Allocate cursors for the pTab table and all its indices and generate
   112626 ** code to open and initialized those cursors.
   112627 **
   112628 ** The cursor for the object that contains the complete data (normally
   112629 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
   112630 ** ROWID table) is returned in *piDataCur.  The first index cursor is
   112631 ** returned in *piIdxCur.  The number of indices is returned.
   112632 **
   112633 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
   112634 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
   112635 ** If iBase is negative, then allocate the next available cursor.
   112636 **
   112637 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
   112638 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
   112639 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
   112640 ** pTab->pIndex list.
   112641 **
   112642 ** If pTab is a virtual table, then this routine is a no-op and the
   112643 ** *piDataCur and *piIdxCur values are left uninitialized.
   112644 */
   112645 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   112646   Parse *pParse,   /* Parsing context */
   112647   Table *pTab,     /* Table to be opened */
   112648   int op,          /* OP_OpenRead or OP_OpenWrite */
   112649   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
   112650   int iBase,       /* Use this for the table cursor, if there is one */
   112651   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
   112652   int *piDataCur,  /* Write the database source cursor number here */
   112653   int *piIdxCur    /* Write the first index cursor number here */
   112654 ){
   112655   int i;
   112656   int iDb;
   112657   int iDataCur;
   112658   Index *pIdx;
   112659   Vdbe *v;
   112660 
   112661   assert( op==OP_OpenRead || op==OP_OpenWrite );
   112662   assert( op==OP_OpenWrite || p5==0 );
   112663   if( IsVirtual(pTab) ){
   112664     /* This routine is a no-op for virtual tables. Leave the output
   112665     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
   112666     ** can detect if they are used by mistake in the caller. */
   112667     return 0;
   112668   }
   112669   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   112670   v = sqlite3GetVdbe(pParse);
   112671   assert( v!=0 );
   112672   if( iBase<0 ) iBase = pParse->nTab;
   112673   iDataCur = iBase++;
   112674   if( piDataCur ) *piDataCur = iDataCur;
   112675   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
   112676     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
   112677   }else{
   112678     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
   112679   }
   112680   if( piIdxCur ) *piIdxCur = iBase;
   112681   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   112682     int iIdxCur = iBase++;
   112683     assert( pIdx->pSchema==pTab->pSchema );
   112684     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
   112685       if( piDataCur ) *piDataCur = iIdxCur;
   112686       p5 = 0;
   112687     }
   112688     if( aToOpen==0 || aToOpen[i+1] ){
   112689       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
   112690       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   112691       sqlite3VdbeChangeP5(v, p5);
   112692       VdbeComment((v, "%s", pIdx->zName));
   112693     }
   112694   }
   112695   if( iBase>pParse->nTab ) pParse->nTab = iBase;
   112696   return i;
   112697 }
   112698 
   112699 
   112700 #ifdef SQLITE_TEST
   112701 /*
   112702 ** The following global variable is incremented whenever the
   112703 ** transfer optimization is used.  This is used for testing
   112704 ** purposes only - to make sure the transfer optimization really
   112705 ** is happening when it is supposed to.
   112706 */
   112707 SQLITE_API int sqlite3_xferopt_count;
   112708 #endif /* SQLITE_TEST */
   112709 
   112710 
   112711 #ifndef SQLITE_OMIT_XFER_OPT
   112712 /*
   112713 ** Check to see if index pSrc is compatible as a source of data
   112714 ** for index pDest in an insert transfer optimization.  The rules
   112715 ** for a compatible index:
   112716 **
   112717 **    *   The index is over the same set of columns
   112718 **    *   The same DESC and ASC markings occurs on all columns
   112719 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
   112720 **    *   The same collating sequence on each column
   112721 **    *   The index has the exact same WHERE clause
   112722 */
   112723 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   112724   int i;
   112725   assert( pDest && pSrc );
   112726   assert( pDest->pTable!=pSrc->pTable );
   112727   if( pDest->nKeyCol!=pSrc->nKeyCol ){
   112728     return 0;   /* Different number of columns */
   112729   }
   112730   if( pDest->onError!=pSrc->onError ){
   112731     return 0;   /* Different conflict resolution strategies */
   112732   }
   112733   for(i=0; i<pSrc->nKeyCol; i++){
   112734     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
   112735       return 0;   /* Different columns indexed */
   112736     }
   112737     if( pSrc->aiColumn[i]==XN_EXPR ){
   112738       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
   112739       if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
   112740                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
   112741         return 0;   /* Different expressions in the index */
   112742       }
   112743     }
   112744     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
   112745       return 0;   /* Different sort orders */
   112746     }
   112747     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
   112748       return 0;   /* Different collating sequences */
   112749     }
   112750   }
   112751   if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
   112752     return 0;     /* Different WHERE clauses */
   112753   }
   112754 
   112755   /* If no test above fails then the indices must be compatible */
   112756   return 1;
   112757 }
   112758 
   112759 /*
   112760 ** Attempt the transfer optimization on INSERTs of the form
   112761 **
   112762 **     INSERT INTO tab1 SELECT * FROM tab2;
   112763 **
   112764 ** The xfer optimization transfers raw records from tab2 over to tab1.
   112765 ** Columns are not decoded and reassembled, which greatly improves
   112766 ** performance.  Raw index records are transferred in the same way.
   112767 **
   112768 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
   112769 ** There are lots of rules for determining compatibility - see comments
   112770 ** embedded in the code for details.
   112771 **
   112772 ** This routine returns TRUE if the optimization is guaranteed to be used.
   112773 ** Sometimes the xfer optimization will only work if the destination table
   112774 ** is empty - a factor that can only be determined at run-time.  In that
   112775 ** case, this routine generates code for the xfer optimization but also
   112776 ** does a test to see if the destination table is empty and jumps over the
   112777 ** xfer optimization code if the test fails.  In that case, this routine
   112778 ** returns FALSE so that the caller will know to go ahead and generate
   112779 ** an unoptimized transfer.  This routine also returns FALSE if there
   112780 ** is no chance that the xfer optimization can be applied.
   112781 **
   112782 ** This optimization is particularly useful at making VACUUM run faster.
   112783 */
   112784 static int xferOptimization(
   112785   Parse *pParse,        /* Parser context */
   112786   Table *pDest,         /* The table we are inserting into */
   112787   Select *pSelect,      /* A SELECT statement to use as the data source */
   112788   int onError,          /* How to handle constraint errors */
   112789   int iDbDest           /* The database of pDest */
   112790 ){
   112791   sqlite3 *db = pParse->db;
   112792   ExprList *pEList;                /* The result set of the SELECT */
   112793   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   112794   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
   112795   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
   112796   int i;                           /* Loop counter */
   112797   int iDbSrc;                      /* The database of pSrc */
   112798   int iSrc, iDest;                 /* Cursors from source and destination */
   112799   int addr1, addr2;                /* Loop addresses */
   112800   int emptyDestTest = 0;           /* Address of test for empty pDest */
   112801   int emptySrcTest = 0;            /* Address of test for empty pSrc */
   112802   Vdbe *v;                         /* The VDBE we are building */
   112803   int regAutoinc;                  /* Memory register used by AUTOINC */
   112804   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   112805   int regData, regRowid;           /* Registers holding data and rowid */
   112806 
   112807   if( pSelect==0 ){
   112808     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
   112809   }
   112810   if( pParse->pWith || pSelect->pWith ){
   112811     /* Do not attempt to process this query if there are an WITH clauses
   112812     ** attached to it. Proceeding may generate a false "no such table: xxx"
   112813     ** error if pSelect reads from a CTE named "xxx".  */
   112814     return 0;
   112815   }
   112816   if( sqlite3TriggerList(pParse, pDest) ){
   112817     return 0;   /* tab1 must not have triggers */
   112818   }
   112819 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112820   if( IsVirtual(pDest) ){
   112821     return 0;   /* tab1 must not be a virtual table */
   112822   }
   112823 #endif
   112824   if( onError==OE_Default ){
   112825     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
   112826     if( onError==OE_Default ) onError = OE_Abort;
   112827   }
   112828   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
   112829   if( pSelect->pSrc->nSrc!=1 ){
   112830     return 0;   /* FROM clause must have exactly one term */
   112831   }
   112832   if( pSelect->pSrc->a[0].pSelect ){
   112833     return 0;   /* FROM clause cannot contain a subquery */
   112834   }
   112835   if( pSelect->pWhere ){
   112836     return 0;   /* SELECT may not have a WHERE clause */
   112837   }
   112838   if( pSelect->pOrderBy ){
   112839     return 0;   /* SELECT may not have an ORDER BY clause */
   112840   }
   112841   /* Do not need to test for a HAVING clause.  If HAVING is present but
   112842   ** there is no ORDER BY, we will get an error. */
   112843   if( pSelect->pGroupBy ){
   112844     return 0;   /* SELECT may not have a GROUP BY clause */
   112845   }
   112846   if( pSelect->pLimit ){
   112847     return 0;   /* SELECT may not have a LIMIT clause */
   112848   }
   112849   if( pSelect->pPrior ){
   112850     return 0;   /* SELECT may not be a compound query */
   112851   }
   112852   if( pSelect->selFlags & SF_Distinct ){
   112853     return 0;   /* SELECT may not be DISTINCT */
   112854   }
   112855   pEList = pSelect->pEList;
   112856   assert( pEList!=0 );
   112857   if( pEList->nExpr!=1 ){
   112858     return 0;   /* The result set must have exactly one column */
   112859   }
   112860   assert( pEList->a[0].pExpr );
   112861   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
   112862     return 0;   /* The result set must be the special operator "*" */
   112863   }
   112864 
   112865   /* At this point we have established that the statement is of the
   112866   ** correct syntactic form to participate in this optimization.  Now
   112867   ** we have to check the semantics.
   112868   */
   112869   pItem = pSelect->pSrc->a;
   112870   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
   112871   if( pSrc==0 ){
   112872     return 0;   /* FROM clause does not contain a real table */
   112873   }
   112874   if( pSrc==pDest ){
   112875     return 0;   /* tab1 and tab2 may not be the same table */
   112876   }
   112877   if( HasRowid(pDest)!=HasRowid(pSrc) ){
   112878     return 0;   /* source and destination must both be WITHOUT ROWID or not */
   112879   }
   112880 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112881   if( IsVirtual(pSrc) ){
   112882     return 0;   /* tab2 must not be a virtual table */
   112883   }
   112884 #endif
   112885   if( pSrc->pSelect ){
   112886     return 0;   /* tab2 may not be a view */
   112887   }
   112888   if( pDest->nCol!=pSrc->nCol ){
   112889     return 0;   /* Number of columns must be the same in tab1 and tab2 */
   112890   }
   112891   if( pDest->iPKey!=pSrc->iPKey ){
   112892     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   112893   }
   112894   for(i=0; i<pDest->nCol; i++){
   112895     Column *pDestCol = &pDest->aCol[i];
   112896     Column *pSrcCol = &pSrc->aCol[i];
   112897 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
   112898     if( (db->mDbFlags & DBFLAG_Vacuum)==0
   112899      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
   112900     ){
   112901       return 0;    /* Neither table may have __hidden__ columns */
   112902     }
   112903 #endif
   112904     if( pDestCol->affinity!=pSrcCol->affinity ){
   112905       return 0;    /* Affinity must be the same on all columns */
   112906     }
   112907     if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
   112908       return 0;    /* Collating sequence must be the same on all columns */
   112909     }
   112910     if( pDestCol->notNull && !pSrcCol->notNull ){
   112911       return 0;    /* tab2 must be NOT NULL if tab1 is */
   112912     }
   112913     /* Default values for second and subsequent columns need to match. */
   112914     if( i>0 ){
   112915       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
   112916       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
   112917       if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
   112918        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
   112919                                        pSrcCol->pDflt->u.zToken)!=0)
   112920       ){
   112921         return 0;    /* Default values must be the same for all columns */
   112922       }
   112923     }
   112924   }
   112925   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   112926     if( IsUniqueIndex(pDestIdx) ){
   112927       destHasUniqueIdx = 1;
   112928     }
   112929     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
   112930       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   112931     }
   112932     if( pSrcIdx==0 ){
   112933       return 0;    /* pDestIdx has no corresponding index in pSrc */
   112934     }
   112935   }
   112936 #ifndef SQLITE_OMIT_CHECK
   112937   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
   112938     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
   112939   }
   112940 #endif
   112941 #ifndef SQLITE_OMIT_FOREIGN_KEY
   112942   /* Disallow the transfer optimization if the destination table constains
   112943   ** any foreign key constraints.  This is more restrictive than necessary.
   112944   ** But the main beneficiary of the transfer optimization is the VACUUM
   112945   ** command, and the VACUUM command disables foreign key constraints.  So
   112946   ** the extra complication to make this rule less restrictive is probably
   112947   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
   112948   */
   112949   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
   112950     return 0;
   112951   }
   112952 #endif
   112953   if( (db->flags & SQLITE_CountRows)!=0 ){
   112954     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
   112955   }
   112956 
   112957   /* If we get this far, it means that the xfer optimization is at
   112958   ** least a possibility, though it might only work if the destination
   112959   ** table (tab1) is initially empty.
   112960   */
   112961 #ifdef SQLITE_TEST
   112962   sqlite3_xferopt_count++;
   112963 #endif
   112964   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
   112965   v = sqlite3GetVdbe(pParse);
   112966   sqlite3CodeVerifySchema(pParse, iDbSrc);
   112967   iSrc = pParse->nTab++;
   112968   iDest = pParse->nTab++;
   112969   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   112970   regData = sqlite3GetTempReg(pParse);
   112971   regRowid = sqlite3GetTempReg(pParse);
   112972   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   112973   assert( HasRowid(pDest) || destHasUniqueIdx );
   112974   if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
   112975       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
   112976    || destHasUniqueIdx                              /* (2) */
   112977    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
   112978   )){
   112979     /* In some circumstances, we are able to run the xfer optimization
   112980     ** only if the destination table is initially empty. Unless the
   112981     ** DBFLAG_Vacuum flag is set, this block generates code to make
   112982     ** that determination. If DBFLAG_Vacuum is set, then the destination
   112983     ** table is always empty.
   112984     **
   112985     ** Conditions under which the destination must be empty:
   112986     **
   112987     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
   112988     **     (If the destination is not initially empty, the rowid fields
   112989     **     of index entries might need to change.)
   112990     **
   112991     ** (2) The destination has a unique index.  (The xfer optimization
   112992     **     is unable to test uniqueness.)
   112993     **
   112994     ** (3) onError is something other than OE_Abort and OE_Rollback.
   112995     */
   112996     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
   112997     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
   112998     sqlite3VdbeJumpHere(v, addr1);
   112999   }
   113000   if( HasRowid(pSrc) ){
   113001     u8 insFlags;
   113002     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
   113003     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
   113004     if( pDest->iPKey>=0 ){
   113005       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   113006       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
   113007       VdbeCoverage(v);
   113008       sqlite3RowidConstraint(pParse, onError, pDest);
   113009       sqlite3VdbeJumpHere(v, addr2);
   113010       autoIncStep(pParse, regAutoinc, regRowid);
   113011     }else if( pDest->pIndex==0 ){
   113012       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
   113013     }else{
   113014       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   113015       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
   113016     }
   113017     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
   113018     if( db->mDbFlags & DBFLAG_Vacuum ){
   113019       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
   113020       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
   113021                            OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
   113022     }else{
   113023       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
   113024     }
   113025     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
   113026                       (char*)pDest, P4_TABLE);
   113027     sqlite3VdbeChangeP5(v, insFlags);
   113028     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
   113029     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   113030     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   113031   }else{
   113032     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
   113033     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
   113034   }
   113035   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   113036     u8 idxInsFlags = 0;
   113037     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
   113038       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   113039     }
   113040     assert( pSrcIdx );
   113041     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
   113042     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
   113043     VdbeComment((v, "%s", pSrcIdx->zName));
   113044     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
   113045     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
   113046     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
   113047     VdbeComment((v, "%s", pDestIdx->zName));
   113048     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
   113049     sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
   113050     if( db->mDbFlags & DBFLAG_Vacuum ){
   113051       /* This INSERT command is part of a VACUUM operation, which guarantees
   113052       ** that the destination table is empty. If all indexed columns use
   113053       ** collation sequence BINARY, then it can also be assumed that the
   113054       ** index will be populated by inserting keys in strictly sorted
   113055       ** order. In this case, instead of seeking within the b-tree as part
   113056       ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
   113057       ** OP_IdxInsert to seek to the point within the b-tree where each key
   113058       ** should be inserted. This is faster.
   113059       **
   113060       ** If any of the indexed columns use a collation sequence other than
   113061       ** BINARY, this optimization is disabled. This is because the user
   113062       ** might change the definition of a collation sequence and then run
   113063       ** a VACUUM command. In that case keys may not be written in strictly
   113064       ** sorted order.  */
   113065       for(i=0; i<pSrcIdx->nColumn; i++){
   113066         const char *zColl = pSrcIdx->azColl[i];
   113067         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
   113068       }
   113069       if( i==pSrcIdx->nColumn ){
   113070         idxInsFlags = OPFLAG_USESEEKRESULT;
   113071         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
   113072       }
   113073     }
   113074     if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
   113075       idxInsFlags |= OPFLAG_NCHANGE;
   113076     }
   113077     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
   113078     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
   113079     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
   113080     sqlite3VdbeJumpHere(v, addr1);
   113081     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   113082     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   113083   }
   113084   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
   113085   sqlite3ReleaseTempReg(pParse, regRowid);
   113086   sqlite3ReleaseTempReg(pParse, regData);
   113087   if( emptyDestTest ){
   113088     sqlite3AutoincrementEnd(pParse);
   113089     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
   113090     sqlite3VdbeJumpHere(v, emptyDestTest);
   113091     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   113092     return 0;
   113093   }else{
   113094     return 1;
   113095   }
   113096 }
   113097 #endif /* SQLITE_OMIT_XFER_OPT */
   113098 
   113099 /************** End of insert.c **********************************************/
   113100 /************** Begin file legacy.c ******************************************/
   113101 /*
   113102 ** 2001 September 15
   113103 **
   113104 ** The author disclaims copyright to this source code.  In place of
   113105 ** a legal notice, here is a blessing:
   113106 **
   113107 **    May you do good and not evil.
   113108 **    May you find forgiveness for yourself and forgive others.
   113109 **    May you share freely, never taking more than you give.
   113110 **
   113111 *************************************************************************
   113112 ** Main file for the SQLite library.  The routines in this file
   113113 ** implement the programmer interface to the library.  Routines in
   113114 ** other files are for internal use by SQLite and should not be
   113115 ** accessed by users of the library.
   113116 */
   113117 
   113118 /* #include "sqliteInt.h" */
   113119 
   113120 /*
   113121 ** Execute SQL code.  Return one of the SQLITE_ success/failure
   113122 ** codes.  Also write an error message into memory obtained from
   113123 ** malloc() and make *pzErrMsg point to that message.
   113124 **
   113125 ** If the SQL is a query, then for each row in the query result
   113126 ** the xCallback() function is called.  pArg becomes the first
   113127 ** argument to xCallback().  If xCallback=NULL then no callback
   113128 ** is invoked, even for queries.
   113129 */
   113130 SQLITE_API int sqlite3_exec(
   113131   sqlite3 *db,                /* The database on which the SQL executes */
   113132   const char *zSql,           /* The SQL to be executed */
   113133   sqlite3_callback xCallback, /* Invoke this callback routine */
   113134   void *pArg,                 /* First argument to xCallback() */
   113135   char **pzErrMsg             /* Write error messages here */
   113136 ){
   113137   int rc = SQLITE_OK;         /* Return code */
   113138   const char *zLeftover;      /* Tail of unprocessed SQL */
   113139   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
   113140   char **azCols = 0;          /* Names of result columns */
   113141   int callbackIsInit;         /* True if callback data is initialized */
   113142 
   113143   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   113144   if( zSql==0 ) zSql = "";
   113145 
   113146   sqlite3_mutex_enter(db->mutex);
   113147   sqlite3Error(db, SQLITE_OK);
   113148   while( rc==SQLITE_OK && zSql[0] ){
   113149     int nCol;
   113150     char **azVals = 0;
   113151 
   113152     pStmt = 0;
   113153     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
   113154     assert( rc==SQLITE_OK || pStmt==0 );
   113155     if( rc!=SQLITE_OK ){
   113156       continue;
   113157     }
   113158     if( !pStmt ){
   113159       /* this happens for a comment or white-space */
   113160       zSql = zLeftover;
   113161       continue;
   113162     }
   113163 
   113164     callbackIsInit = 0;
   113165     nCol = sqlite3_column_count(pStmt);
   113166 
   113167     while( 1 ){
   113168       int i;
   113169       rc = sqlite3_step(pStmt);
   113170 
   113171       /* Invoke the callback function if required */
   113172       if( xCallback && (SQLITE_ROW==rc ||
   113173           (SQLITE_DONE==rc && !callbackIsInit
   113174                            && db->flags&SQLITE_NullCallback)) ){
   113175         if( !callbackIsInit ){
   113176           azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
   113177           if( azCols==0 ){
   113178             goto exec_out;
   113179           }
   113180           for(i=0; i<nCol; i++){
   113181             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   113182             /* sqlite3VdbeSetColName() installs column names as UTF8
   113183             ** strings so there is no way for sqlite3_column_name() to fail. */
   113184             assert( azCols[i]!=0 );
   113185           }
   113186           callbackIsInit = 1;
   113187         }
   113188         if( rc==SQLITE_ROW ){
   113189           azVals = &azCols[nCol];
   113190           for(i=0; i<nCol; i++){
   113191             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
   113192             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   113193               sqlite3OomFault(db);
   113194               goto exec_out;
   113195             }
   113196           }
   113197           azVals[i] = 0;
   113198         }
   113199         if( xCallback(pArg, nCol, azVals, azCols) ){
   113200           /* EVIDENCE-OF: R-38229-40159 If the callback function to
   113201           ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
   113202           ** return SQLITE_ABORT. */
   113203           rc = SQLITE_ABORT;
   113204           sqlite3VdbeFinalize((Vdbe *)pStmt);
   113205           pStmt = 0;
   113206           sqlite3Error(db, SQLITE_ABORT);
   113207           goto exec_out;
   113208         }
   113209       }
   113210 
   113211       if( rc!=SQLITE_ROW ){
   113212         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
   113213         pStmt = 0;
   113214         zSql = zLeftover;
   113215         while( sqlite3Isspace(zSql[0]) ) zSql++;
   113216         break;
   113217       }
   113218     }
   113219 
   113220     sqlite3DbFree(db, azCols);
   113221     azCols = 0;
   113222   }
   113223 
   113224 exec_out:
   113225   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
   113226   sqlite3DbFree(db, azCols);
   113227 
   113228   rc = sqlite3ApiExit(db, rc);
   113229   if( rc!=SQLITE_OK && pzErrMsg ){
   113230     *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
   113231     if( *pzErrMsg==0 ){
   113232       rc = SQLITE_NOMEM_BKPT;
   113233       sqlite3Error(db, SQLITE_NOMEM);
   113234     }
   113235   }else if( pzErrMsg ){
   113236     *pzErrMsg = 0;
   113237   }
   113238 
   113239   assert( (rc&db->errMask)==rc );
   113240   sqlite3_mutex_leave(db->mutex);
   113241   return rc;
   113242 }
   113243 
   113244 /************** End of legacy.c **********************************************/
   113245 /************** Begin file loadext.c *****************************************/
   113246 /*
   113247 ** 2006 June 7
   113248 **
   113249 ** The author disclaims copyright to this source code.  In place of
   113250 ** a legal notice, here is a blessing:
   113251 **
   113252 **    May you do good and not evil.
   113253 **    May you find forgiveness for yourself and forgive others.
   113254 **    May you share freely, never taking more than you give.
   113255 **
   113256 *************************************************************************
   113257 ** This file contains code used to dynamically load extensions into
   113258 ** the SQLite library.
   113259 */
   113260 
   113261 #ifndef SQLITE_CORE
   113262   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
   113263 #endif
   113264 /************** Include sqlite3ext.h in the middle of loadext.c **************/
   113265 /************** Begin file sqlite3ext.h **************************************/
   113266 /*
   113267 ** 2006 June 7
   113268 **
   113269 ** The author disclaims copyright to this source code.  In place of
   113270 ** a legal notice, here is a blessing:
   113271 **
   113272 **    May you do good and not evil.
   113273 **    May you find forgiveness for yourself and forgive others.
   113274 **    May you share freely, never taking more than you give.
   113275 **
   113276 *************************************************************************
   113277 ** This header file defines the SQLite interface for use by
   113278 ** shared libraries that want to be imported as extensions into
   113279 ** an SQLite instance.  Shared libraries that intend to be loaded
   113280 ** as extensions by SQLite should #include this file instead of
   113281 ** sqlite3.h.
   113282 */
   113283 #ifndef SQLITE3EXT_H
   113284 #define SQLITE3EXT_H
   113285 /* #include "sqlite3.h" */
   113286 
   113287 /*
   113288 ** The following structure holds pointers to all of the SQLite API
   113289 ** routines.
   113290 **
   113291 ** WARNING:  In order to maintain backwards compatibility, add new
   113292 ** interfaces to the end of this structure only.  If you insert new
   113293 ** interfaces in the middle of this structure, then older different
   113294 ** versions of SQLite will not be able to load each other's shared
   113295 ** libraries!
   113296 */
   113297 struct sqlite3_api_routines {
   113298   void * (*aggregate_context)(sqlite3_context*,int nBytes);
   113299   int  (*aggregate_count)(sqlite3_context*);
   113300   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
   113301   int  (*bind_double)(sqlite3_stmt*,int,double);
   113302   int  (*bind_int)(sqlite3_stmt*,int,int);
   113303   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
   113304   int  (*bind_null)(sqlite3_stmt*,int);
   113305   int  (*bind_parameter_count)(sqlite3_stmt*);
   113306   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
   113307   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
   113308   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
   113309   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
   113310   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
   113311   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
   113312   int  (*busy_timeout)(sqlite3*,int ms);
   113313   int  (*changes)(sqlite3*);
   113314   int  (*close)(sqlite3*);
   113315   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
   113316                            int eTextRep,const char*));
   113317   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
   113318                              int eTextRep,const void*));
   113319   const void * (*column_blob)(sqlite3_stmt*,int iCol);
   113320   int  (*column_bytes)(sqlite3_stmt*,int iCol);
   113321   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
   113322   int  (*column_count)(sqlite3_stmt*pStmt);
   113323   const char * (*column_database_name)(sqlite3_stmt*,int);
   113324   const void * (*column_database_name16)(sqlite3_stmt*,int);
   113325   const char * (*column_decltype)(sqlite3_stmt*,int i);
   113326   const void * (*column_decltype16)(sqlite3_stmt*,int);
   113327   double  (*column_double)(sqlite3_stmt*,int iCol);
   113328   int  (*column_int)(sqlite3_stmt*,int iCol);
   113329   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
   113330   const char * (*column_name)(sqlite3_stmt*,int);
   113331   const void * (*column_name16)(sqlite3_stmt*,int);
   113332   const char * (*column_origin_name)(sqlite3_stmt*,int);
   113333   const void * (*column_origin_name16)(sqlite3_stmt*,int);
   113334   const char * (*column_table_name)(sqlite3_stmt*,int);
   113335   const void * (*column_table_name16)(sqlite3_stmt*,int);
   113336   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
   113337   const void * (*column_text16)(sqlite3_stmt*,int iCol);
   113338   int  (*column_type)(sqlite3_stmt*,int iCol);
   113339   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
   113340   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
   113341   int  (*complete)(const char*sql);
   113342   int  (*complete16)(const void*sql);
   113343   int  (*create_collation)(sqlite3*,const char*,int,void*,
   113344                            int(*)(void*,int,const void*,int,const void*));
   113345   int  (*create_collation16)(sqlite3*,const void*,int,void*,
   113346                              int(*)(void*,int,const void*,int,const void*));
   113347   int  (*create_function)(sqlite3*,const char*,int,int,void*,
   113348                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   113349                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   113350                           void (*xFinal)(sqlite3_context*));
   113351   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
   113352                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   113353                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   113354                             void (*xFinal)(sqlite3_context*));
   113355   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
   113356   int  (*data_count)(sqlite3_stmt*pStmt);
   113357   sqlite3 * (*db_handle)(sqlite3_stmt*);
   113358   int (*declare_vtab)(sqlite3*,const char*);
   113359   int  (*enable_shared_cache)(int);
   113360   int  (*errcode)(sqlite3*db);
   113361   const char * (*errmsg)(sqlite3*);
   113362   const void * (*errmsg16)(sqlite3*);
   113363   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
   113364   int  (*expired)(sqlite3_stmt*);
   113365   int  (*finalize)(sqlite3_stmt*pStmt);
   113366   void  (*free)(void*);
   113367   void  (*free_table)(char**result);
   113368   int  (*get_autocommit)(sqlite3*);
   113369   void * (*get_auxdata)(sqlite3_context*,int);
   113370   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   113371   int  (*global_recover)(void);
   113372   void  (*interruptx)(sqlite3*);
   113373   sqlite_int64  (*last_insert_rowid)(sqlite3*);
   113374   const char * (*libversion)(void);
   113375   int  (*libversion_number)(void);
   113376   void *(*malloc)(int);
   113377   char * (*mprintf)(const char*,...);
   113378   int  (*open)(const char*,sqlite3**);
   113379   int  (*open16)(const void*,sqlite3**);
   113380   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   113381   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   113382   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   113383   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   113384   void *(*realloc)(void*,int);
   113385   int  (*reset)(sqlite3_stmt*pStmt);
   113386   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   113387   void  (*result_double)(sqlite3_context*,double);
   113388   void  (*result_error)(sqlite3_context*,const char*,int);
   113389   void  (*result_error16)(sqlite3_context*,const void*,int);
   113390   void  (*result_int)(sqlite3_context*,int);
   113391   void  (*result_int64)(sqlite3_context*,sqlite_int64);
   113392   void  (*result_null)(sqlite3_context*);
   113393   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   113394   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   113395   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   113396   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   113397   void  (*result_value)(sqlite3_context*,sqlite3_value*);
   113398   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   113399   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
   113400                          const char*,const char*),void*);
   113401   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   113402   char * (*xsnprintf)(int,char*,const char*,...);
   113403   int  (*step)(sqlite3_stmt*);
   113404   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
   113405                                 char const**,char const**,int*,int*,int*);
   113406   void  (*thread_cleanup)(void);
   113407   int  (*total_changes)(sqlite3*);
   113408   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   113409   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   113410   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
   113411                                          sqlite_int64),void*);
   113412   void * (*user_data)(sqlite3_context*);
   113413   const void * (*value_blob)(sqlite3_value*);
   113414   int  (*value_bytes)(sqlite3_value*);
   113415   int  (*value_bytes16)(sqlite3_value*);
   113416   double  (*value_double)(sqlite3_value*);
   113417   int  (*value_int)(sqlite3_value*);
   113418   sqlite_int64  (*value_int64)(sqlite3_value*);
   113419   int  (*value_numeric_type)(sqlite3_value*);
   113420   const unsigned char * (*value_text)(sqlite3_value*);
   113421   const void * (*value_text16)(sqlite3_value*);
   113422   const void * (*value_text16be)(sqlite3_value*);
   113423   const void * (*value_text16le)(sqlite3_value*);
   113424   int  (*value_type)(sqlite3_value*);
   113425   char *(*vmprintf)(const char*,va_list);
   113426   /* Added ??? */
   113427   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   113428   /* Added by 3.3.13 */
   113429   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   113430   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   113431   int (*clear_bindings)(sqlite3_stmt*);
   113432   /* Added by 3.4.1 */
   113433   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
   113434                           void (*xDestroy)(void *));
   113435   /* Added by 3.5.0 */
   113436   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   113437   int (*blob_bytes)(sqlite3_blob*);
   113438   int (*blob_close)(sqlite3_blob*);
   113439   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
   113440                    int,sqlite3_blob**);
   113441   int (*blob_read)(sqlite3_blob*,void*,int,int);
   113442   int (*blob_write)(sqlite3_blob*,const void*,int,int);
   113443   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
   113444                              int(*)(void*,int,const void*,int,const void*),
   113445                              void(*)(void*));
   113446   int (*file_control)(sqlite3*,const char*,int,void*);
   113447   sqlite3_int64 (*memory_highwater)(int);
   113448   sqlite3_int64 (*memory_used)(void);
   113449   sqlite3_mutex *(*mutex_alloc)(int);
   113450   void (*mutex_enter)(sqlite3_mutex*);
   113451   void (*mutex_free)(sqlite3_mutex*);
   113452   void (*mutex_leave)(sqlite3_mutex*);
   113453   int (*mutex_try)(sqlite3_mutex*);
   113454   int (*open_v2)(const char*,sqlite3**,int,const char*);
   113455   int (*release_memory)(int);
   113456   void (*result_error_nomem)(sqlite3_context*);
   113457   void (*result_error_toobig)(sqlite3_context*);
   113458   int (*sleep)(int);
   113459   void (*soft_heap_limit)(int);
   113460   sqlite3_vfs *(*vfs_find)(const char*);
   113461   int (*vfs_register)(sqlite3_vfs*,int);
   113462   int (*vfs_unregister)(sqlite3_vfs*);
   113463   int (*xthreadsafe)(void);
   113464   void (*result_zeroblob)(sqlite3_context*,int);
   113465   void (*result_error_code)(sqlite3_context*,int);
   113466   int (*test_control)(int, ...);
   113467   void (*randomness)(int,void*);
   113468   sqlite3 *(*context_db_handle)(sqlite3_context*);
   113469   int (*extended_result_codes)(sqlite3*,int);
   113470   int (*limit)(sqlite3*,int,int);
   113471   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   113472   const char *(*sql)(sqlite3_stmt*);
   113473   int (*status)(int,int*,int*,int);
   113474   int (*backup_finish)(sqlite3_backup*);
   113475   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
   113476   int (*backup_pagecount)(sqlite3_backup*);
   113477   int (*backup_remaining)(sqlite3_backup*);
   113478   int (*backup_step)(sqlite3_backup*,int);
   113479   const char *(*compileoption_get)(int);
   113480   int (*compileoption_used)(const char*);
   113481   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
   113482                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   113483                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   113484                             void (*xFinal)(sqlite3_context*),
   113485                             void(*xDestroy)(void*));
   113486   int (*db_config)(sqlite3*,int,...);
   113487   sqlite3_mutex *(*db_mutex)(sqlite3*);
   113488   int (*db_status)(sqlite3*,int,int*,int*,int);
   113489   int (*extended_errcode)(sqlite3*);
   113490   void (*log)(int,const char*,...);
   113491   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
   113492   const char *(*sourceid)(void);
   113493   int (*stmt_status)(sqlite3_stmt*,int,int);
   113494   int (*strnicmp)(const char*,const char*,int);
   113495   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
   113496   int (*wal_autocheckpoint)(sqlite3*,int);
   113497   int (*wal_checkpoint)(sqlite3*,const char*);
   113498   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
   113499   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
   113500   int (*vtab_config)(sqlite3*,int op,...);
   113501   int (*vtab_on_conflict)(sqlite3*);
   113502   /* Version 3.7.16 and later */
   113503   int (*close_v2)(sqlite3*);
   113504   const char *(*db_filename)(sqlite3*,const char*);
   113505   int (*db_readonly)(sqlite3*,const char*);
   113506   int (*db_release_memory)(sqlite3*);
   113507   const char *(*errstr)(int);
   113508   int (*stmt_busy)(sqlite3_stmt*);
   113509   int (*stmt_readonly)(sqlite3_stmt*);
   113510   int (*stricmp)(const char*,const char*);
   113511   int (*uri_boolean)(const char*,const char*,int);
   113512   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
   113513   const char *(*uri_parameter)(const char*,const char*);
   113514   char *(*xvsnprintf)(int,char*,const char*,va_list);
   113515   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
   113516   /* Version 3.8.7 and later */
   113517   int (*auto_extension)(void(*)(void));
   113518   int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
   113519                      void(*)(void*));
   113520   int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
   113521                       void(*)(void*),unsigned char);
   113522   int (*cancel_auto_extension)(void(*)(void));
   113523   int (*load_extension)(sqlite3*,const char*,const char*,char**);
   113524   void *(*malloc64)(sqlite3_uint64);
   113525   sqlite3_uint64 (*msize)(void*);
   113526   void *(*realloc64)(void*,sqlite3_uint64);
   113527   void (*reset_auto_extension)(void);
   113528   void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
   113529                         void(*)(void*));
   113530   void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
   113531                          void(*)(void*), unsigned char);
   113532   int (*strglob)(const char*,const char*);
   113533   /* Version 3.8.11 and later */
   113534   sqlite3_value *(*value_dup)(const sqlite3_value*);
   113535   void (*value_free)(sqlite3_value*);
   113536   int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
   113537   int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
   113538   /* Version 3.9.0 and later */
   113539   unsigned int (*value_subtype)(sqlite3_value*);
   113540   void (*result_subtype)(sqlite3_context*,unsigned int);
   113541   /* Version 3.10.0 and later */
   113542   int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
   113543   int (*strlike)(const char*,const char*,unsigned int);
   113544   int (*db_cacheflush)(sqlite3*);
   113545   /* Version 3.12.0 and later */
   113546   int (*system_errno)(sqlite3*);
   113547   /* Version 3.14.0 and later */
   113548   int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
   113549   char *(*expanded_sql)(sqlite3_stmt*);
   113550   /* Version 3.18.0 and later */
   113551   void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
   113552   /* Version 3.20.0 and later */
   113553   int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
   113554                     sqlite3_stmt**,const char**);
   113555   int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
   113556                       sqlite3_stmt**,const void**);
   113557   int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
   113558   void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
   113559   void *(*value_pointer)(sqlite3_value*,const char*);
   113560   int (*vtab_nochange)(sqlite3_context*);
   113561   int (*value_nochange)(sqlite3_value*);
   113562   const char *(*vtab_collation)(sqlite3_index_info*,int);
   113563 };
   113564 
   113565 /*
   113566 ** This is the function signature used for all extension entry points.  It
   113567 ** is also defined in the file "loadext.c".
   113568 */
   113569 typedef int (*sqlite3_loadext_entry)(
   113570   sqlite3 *db,                       /* Handle to the database. */
   113571   char **pzErrMsg,                   /* Used to set error string on failure. */
   113572   const sqlite3_api_routines *pThunk /* Extension API function pointers. */
   113573 );
   113574 
   113575 /*
   113576 ** The following macros redefine the API routines so that they are
   113577 ** redirected through the global sqlite3_api structure.
   113578 **
   113579 ** This header file is also used by the loadext.c source file
   113580 ** (part of the main SQLite library - not an extension) so that
   113581 ** it can get access to the sqlite3_api_routines structure
   113582 ** definition.  But the main library does not want to redefine
   113583 ** the API.  So the redefinition macros are only valid if the
   113584 ** SQLITE_CORE macros is undefined.
   113585 */
   113586 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   113587 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   113588 #ifndef SQLITE_OMIT_DEPRECATED
   113589 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
   113590 #endif
   113591 #define sqlite3_bind_blob              sqlite3_api->bind_blob
   113592 #define sqlite3_bind_double            sqlite3_api->bind_double
   113593 #define sqlite3_bind_int               sqlite3_api->bind_int
   113594 #define sqlite3_bind_int64             sqlite3_api->bind_int64
   113595 #define sqlite3_bind_null              sqlite3_api->bind_null
   113596 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   113597 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   113598 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   113599 #define sqlite3_bind_text              sqlite3_api->bind_text
   113600 #define sqlite3_bind_text16            sqlite3_api->bind_text16
   113601 #define sqlite3_bind_value             sqlite3_api->bind_value
   113602 #define sqlite3_busy_handler           sqlite3_api->busy_handler
   113603 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   113604 #define sqlite3_changes                sqlite3_api->changes
   113605 #define sqlite3_close                  sqlite3_api->close
   113606 #define sqlite3_collation_needed       sqlite3_api->collation_needed
   113607 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   113608 #define sqlite3_column_blob            sqlite3_api->column_blob
   113609 #define sqlite3_column_bytes           sqlite3_api->column_bytes
   113610 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   113611 #define sqlite3_column_count           sqlite3_api->column_count
   113612 #define sqlite3_column_database_name   sqlite3_api->column_database_name
   113613 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   113614 #define sqlite3_column_decltype        sqlite3_api->column_decltype
   113615 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   113616 #define sqlite3_column_double          sqlite3_api->column_double
   113617 #define sqlite3_column_int             sqlite3_api->column_int
   113618 #define sqlite3_column_int64           sqlite3_api->column_int64
   113619 #define sqlite3_column_name            sqlite3_api->column_name
   113620 #define sqlite3_column_name16          sqlite3_api->column_name16
   113621 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   113622 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   113623 #define sqlite3_column_table_name      sqlite3_api->column_table_name
   113624 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   113625 #define sqlite3_column_text            sqlite3_api->column_text
   113626 #define sqlite3_column_text16          sqlite3_api->column_text16
   113627 #define sqlite3_column_type            sqlite3_api->column_type
   113628 #define sqlite3_column_value           sqlite3_api->column_value
   113629 #define sqlite3_commit_hook            sqlite3_api->commit_hook
   113630 #define sqlite3_complete               sqlite3_api->complete
   113631 #define sqlite3_complete16             sqlite3_api->complete16
   113632 #define sqlite3_create_collation       sqlite3_api->create_collation
   113633 #define sqlite3_create_collation16     sqlite3_api->create_collation16
   113634 #define sqlite3_create_function        sqlite3_api->create_function
   113635 #define sqlite3_create_function16      sqlite3_api->create_function16
   113636 #define sqlite3_create_module          sqlite3_api->create_module
   113637 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   113638 #define sqlite3_data_count             sqlite3_api->data_count
   113639 #define sqlite3_db_handle              sqlite3_api->db_handle
   113640 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   113641 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   113642 #define sqlite3_errcode                sqlite3_api->errcode
   113643 #define sqlite3_errmsg                 sqlite3_api->errmsg
   113644 #define sqlite3_errmsg16               sqlite3_api->errmsg16
   113645 #define sqlite3_exec                   sqlite3_api->exec
   113646 #ifndef SQLITE_OMIT_DEPRECATED
   113647 #define sqlite3_expired                sqlite3_api->expired
   113648 #endif
   113649 #define sqlite3_finalize               sqlite3_api->finalize
   113650 #define sqlite3_free                   sqlite3_api->free
   113651 #define sqlite3_free_table             sqlite3_api->free_table
   113652 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   113653 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   113654 #define sqlite3_get_table              sqlite3_api->get_table
   113655 #ifndef SQLITE_OMIT_DEPRECATED
   113656 #define sqlite3_global_recover         sqlite3_api->global_recover
   113657 #endif
   113658 #define sqlite3_interrupt              sqlite3_api->interruptx
   113659 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   113660 #define sqlite3_libversion             sqlite3_api->libversion
   113661 #define sqlite3_libversion_number      sqlite3_api->libversion_number
   113662 #define sqlite3_malloc                 sqlite3_api->malloc
   113663 #define sqlite3_mprintf                sqlite3_api->mprintf
   113664 #define sqlite3_open                   sqlite3_api->open
   113665 #define sqlite3_open16                 sqlite3_api->open16
   113666 #define sqlite3_prepare                sqlite3_api->prepare
   113667 #define sqlite3_prepare16              sqlite3_api->prepare16
   113668 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   113669 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   113670 #define sqlite3_profile                sqlite3_api->profile
   113671 #define sqlite3_progress_handler       sqlite3_api->progress_handler
   113672 #define sqlite3_realloc                sqlite3_api->realloc
   113673 #define sqlite3_reset                  sqlite3_api->reset
   113674 #define sqlite3_result_blob            sqlite3_api->result_blob
   113675 #define sqlite3_result_double          sqlite3_api->result_double
   113676 #define sqlite3_result_error           sqlite3_api->result_error
   113677 #define sqlite3_result_error16         sqlite3_api->result_error16
   113678 #define sqlite3_result_int             sqlite3_api->result_int
   113679 #define sqlite3_result_int64           sqlite3_api->result_int64
   113680 #define sqlite3_result_null            sqlite3_api->result_null
   113681 #define sqlite3_result_text            sqlite3_api->result_text
   113682 #define sqlite3_result_text16          sqlite3_api->result_text16
   113683 #define sqlite3_result_text16be        sqlite3_api->result_text16be
   113684 #define sqlite3_result_text16le        sqlite3_api->result_text16le
   113685 #define sqlite3_result_value           sqlite3_api->result_value
   113686 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   113687 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   113688 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   113689 #define sqlite3_snprintf               sqlite3_api->xsnprintf
   113690 #define sqlite3_step                   sqlite3_api->step
   113691 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   113692 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
   113693 #define sqlite3_total_changes          sqlite3_api->total_changes
   113694 #define sqlite3_trace                  sqlite3_api->trace
   113695 #ifndef SQLITE_OMIT_DEPRECATED
   113696 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
   113697 #endif
   113698 #define sqlite3_update_hook            sqlite3_api->update_hook
   113699 #define sqlite3_user_data              sqlite3_api->user_data
   113700 #define sqlite3_value_blob             sqlite3_api->value_blob
   113701 #define sqlite3_value_bytes            sqlite3_api->value_bytes
   113702 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   113703 #define sqlite3_value_double           sqlite3_api->value_double
   113704 #define sqlite3_value_int              sqlite3_api->value_int
   113705 #define sqlite3_value_int64            sqlite3_api->value_int64
   113706 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   113707 #define sqlite3_value_text             sqlite3_api->value_text
   113708 #define sqlite3_value_text16           sqlite3_api->value_text16
   113709 #define sqlite3_value_text16be         sqlite3_api->value_text16be
   113710 #define sqlite3_value_text16le         sqlite3_api->value_text16le
   113711 #define sqlite3_value_type             sqlite3_api->value_type
   113712 #define sqlite3_vmprintf               sqlite3_api->vmprintf
   113713 #define sqlite3_vsnprintf              sqlite3_api->xvsnprintf
   113714 #define sqlite3_overload_function      sqlite3_api->overload_function
   113715 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   113716 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   113717 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   113718 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   113719 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   113720 #define sqlite3_blob_close             sqlite3_api->blob_close
   113721 #define sqlite3_blob_open              sqlite3_api->blob_open
   113722 #define sqlite3_blob_read              sqlite3_api->blob_read
   113723 #define sqlite3_blob_write             sqlite3_api->blob_write
   113724 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   113725 #define sqlite3_file_control           sqlite3_api->file_control
   113726 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   113727 #define sqlite3_memory_used            sqlite3_api->memory_used
   113728 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   113729 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   113730 #define sqlite3_mutex_free             sqlite3_api->mutex_free
   113731 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   113732 #define sqlite3_mutex_try              sqlite3_api->mutex_try
   113733 #define sqlite3_open_v2                sqlite3_api->open_v2
   113734 #define sqlite3_release_memory         sqlite3_api->release_memory
   113735 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   113736 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   113737 #define sqlite3_sleep                  sqlite3_api->sleep
   113738 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
   113739 #define sqlite3_vfs_find               sqlite3_api->vfs_find
   113740 #define sqlite3_vfs_register           sqlite3_api->vfs_register
   113741 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   113742 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   113743 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   113744 #define sqlite3_result_error_code      sqlite3_api->result_error_code
   113745 #define sqlite3_test_control           sqlite3_api->test_control
   113746 #define sqlite3_randomness             sqlite3_api->randomness
   113747 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   113748 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   113749 #define sqlite3_limit                  sqlite3_api->limit
   113750 #define sqlite3_next_stmt              sqlite3_api->next_stmt
   113751 #define sqlite3_sql                    sqlite3_api->sql
   113752 #define sqlite3_status                 sqlite3_api->status
   113753 #define sqlite3_backup_finish          sqlite3_api->backup_finish
   113754 #define sqlite3_backup_init            sqlite3_api->backup_init
   113755 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
   113756 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
   113757 #define sqlite3_backup_step            sqlite3_api->backup_step
   113758 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
   113759 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
   113760 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
   113761 #define sqlite3_db_config              sqlite3_api->db_config
   113762 #define sqlite3_db_mutex               sqlite3_api->db_mutex
   113763 #define sqlite3_db_status              sqlite3_api->db_status
   113764 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
   113765 #define sqlite3_log                    sqlite3_api->log
   113766 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
   113767 #define sqlite3_sourceid               sqlite3_api->sourceid
   113768 #define sqlite3_stmt_status            sqlite3_api->stmt_status
   113769 #define sqlite3_strnicmp               sqlite3_api->strnicmp
   113770 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
   113771 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
   113772 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
   113773 #define sqlite3_wal_hook               sqlite3_api->wal_hook
   113774 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
   113775 #define sqlite3_vtab_config            sqlite3_api->vtab_config
   113776 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
   113777 /* Version 3.7.16 and later */
   113778 #define sqlite3_close_v2               sqlite3_api->close_v2
   113779 #define sqlite3_db_filename            sqlite3_api->db_filename
   113780 #define sqlite3_db_readonly            sqlite3_api->db_readonly
   113781 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
   113782 #define sqlite3_errstr                 sqlite3_api->errstr
   113783 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
   113784 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
   113785 #define sqlite3_stricmp                sqlite3_api->stricmp
   113786 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
   113787 #define sqlite3_uri_int64              sqlite3_api->uri_int64
   113788 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
   113789 #define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf
   113790 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
   113791 /* Version 3.8.7 and later */
   113792 #define sqlite3_auto_extension         sqlite3_api->auto_extension
   113793 #define sqlite3_bind_blob64            sqlite3_api->bind_blob64
   113794 #define sqlite3_bind_text64            sqlite3_api->bind_text64
   113795 #define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
   113796 #define sqlite3_load_extension         sqlite3_api->load_extension
   113797 #define sqlite3_malloc64               sqlite3_api->malloc64
   113798 #define sqlite3_msize                  sqlite3_api->msize
   113799 #define sqlite3_realloc64              sqlite3_api->realloc64
   113800 #define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
   113801 #define sqlite3_result_blob64          sqlite3_api->result_blob64
   113802 #define sqlite3_result_text64          sqlite3_api->result_text64
   113803 #define sqlite3_strglob                sqlite3_api->strglob
   113804 /* Version 3.8.11 and later */
   113805 #define sqlite3_value_dup              sqlite3_api->value_dup
   113806 #define sqlite3_value_free             sqlite3_api->value_free
   113807 #define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
   113808 #define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
   113809 /* Version 3.9.0 and later */
   113810 #define sqlite3_value_subtype          sqlite3_api->value_subtype
   113811 #define sqlite3_result_subtype         sqlite3_api->result_subtype
   113812 /* Version 3.10.0 and later */
   113813 #define sqlite3_status64               sqlite3_api->status64
   113814 #define sqlite3_strlike                sqlite3_api->strlike
   113815 #define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
   113816 /* Version 3.12.0 and later */
   113817 #define sqlite3_system_errno           sqlite3_api->system_errno
   113818 /* Version 3.14.0 and later */
   113819 #define sqlite3_trace_v2               sqlite3_api->trace_v2
   113820 #define sqlite3_expanded_sql           sqlite3_api->expanded_sql
   113821 /* Version 3.18.0 and later */
   113822 #define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
   113823 /* Version 3.20.0 and later */
   113824 #define sqlite3_prepare_v3             sqlite3_api->prepare_v3
   113825 #define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3
   113826 #define sqlite3_bind_pointer           sqlite3_api->bind_pointer
   113827 #define sqlite3_result_pointer         sqlite3_api->result_pointer
   113828 #define sqlite3_value_pointer          sqlite3_api->value_pointer
   113829 /* Version 3.22.0 and later */
   113830 #define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange
   113831 #define sqlite3_value_nochange         sqltie3_api->value_nochange
   113832 #define sqlite3_vtab_collation         sqltie3_api->vtab_collation
   113833 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
   113834 
   113835 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   113836   /* This case when the file really is being compiled as a loadable
   113837   ** extension */
   113838 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
   113839 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
   113840 # define SQLITE_EXTENSION_INIT3     \
   113841     extern const sqlite3_api_routines *sqlite3_api;
   113842 #else
   113843   /* This case when the file is being statically linked into the
   113844   ** application */
   113845 # define SQLITE_EXTENSION_INIT1     /*no-op*/
   113846 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
   113847 # define SQLITE_EXTENSION_INIT3     /*no-op*/
   113848 #endif
   113849 
   113850 #endif /* SQLITE3EXT_H */
   113851 
   113852 /************** End of sqlite3ext.h ******************************************/
   113853 /************** Continuing where we left off in loadext.c ********************/
   113854 /* #include "sqliteInt.h" */
   113855 
   113856 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   113857 /*
   113858 ** Some API routines are omitted when various features are
   113859 ** excluded from a build of SQLite.  Substitute a NULL pointer
   113860 ** for any missing APIs.
   113861 */
   113862 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   113863 # define sqlite3_column_database_name   0
   113864 # define sqlite3_column_database_name16 0
   113865 # define sqlite3_column_table_name      0
   113866 # define sqlite3_column_table_name16    0
   113867 # define sqlite3_column_origin_name     0
   113868 # define sqlite3_column_origin_name16   0
   113869 #endif
   113870 
   113871 #ifdef SQLITE_OMIT_AUTHORIZATION
   113872 # define sqlite3_set_authorizer         0
   113873 #endif
   113874 
   113875 #ifdef SQLITE_OMIT_UTF16
   113876 # define sqlite3_bind_text16            0
   113877 # define sqlite3_collation_needed16     0
   113878 # define sqlite3_column_decltype16      0
   113879 # define sqlite3_column_name16          0
   113880 # define sqlite3_column_text16          0
   113881 # define sqlite3_complete16             0
   113882 # define sqlite3_create_collation16     0
   113883 # define sqlite3_create_function16      0
   113884 # define sqlite3_errmsg16               0
   113885 # define sqlite3_open16                 0
   113886 # define sqlite3_prepare16              0
   113887 # define sqlite3_prepare16_v2           0
   113888 # define sqlite3_prepare16_v3           0
   113889 # define sqlite3_result_error16         0
   113890 # define sqlite3_result_text16          0
   113891 # define sqlite3_result_text16be        0
   113892 # define sqlite3_result_text16le        0
   113893 # define sqlite3_value_text16           0
   113894 # define sqlite3_value_text16be         0
   113895 # define sqlite3_value_text16le         0
   113896 # define sqlite3_column_database_name16 0
   113897 # define sqlite3_column_table_name16    0
   113898 # define sqlite3_column_origin_name16   0
   113899 #endif
   113900 
   113901 #ifdef SQLITE_OMIT_COMPLETE
   113902 # define sqlite3_complete 0
   113903 # define sqlite3_complete16 0
   113904 #endif
   113905 
   113906 #ifdef SQLITE_OMIT_DECLTYPE
   113907 # define sqlite3_column_decltype16      0
   113908 # define sqlite3_column_decltype        0
   113909 #endif
   113910 
   113911 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   113912 # define sqlite3_progress_handler 0
   113913 #endif
   113914 
   113915 #ifdef SQLITE_OMIT_VIRTUALTABLE
   113916 # define sqlite3_create_module 0
   113917 # define sqlite3_create_module_v2 0
   113918 # define sqlite3_declare_vtab 0
   113919 # define sqlite3_vtab_config 0
   113920 # define sqlite3_vtab_on_conflict 0
   113921 #endif
   113922 
   113923 #ifdef SQLITE_OMIT_SHARED_CACHE
   113924 # define sqlite3_enable_shared_cache 0
   113925 #endif
   113926 
   113927 #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
   113928 # define sqlite3_profile       0
   113929 # define sqlite3_trace         0
   113930 #endif
   113931 
   113932 #ifdef SQLITE_OMIT_GET_TABLE
   113933 # define sqlite3_free_table    0
   113934 # define sqlite3_get_table     0
   113935 #endif
   113936 
   113937 #ifdef SQLITE_OMIT_INCRBLOB
   113938 #define sqlite3_bind_zeroblob  0
   113939 #define sqlite3_blob_bytes     0
   113940 #define sqlite3_blob_close     0
   113941 #define sqlite3_blob_open      0
   113942 #define sqlite3_blob_read      0
   113943 #define sqlite3_blob_write     0
   113944 #define sqlite3_blob_reopen    0
   113945 #endif
   113946 
   113947 #if defined(SQLITE_OMIT_TRACE)
   113948 # define sqlite3_trace_v2      0
   113949 #endif
   113950 
   113951 /*
   113952 ** The following structure contains pointers to all SQLite API routines.
   113953 ** A pointer to this structure is passed into extensions when they are
   113954 ** loaded so that the extension can make calls back into the SQLite
   113955 ** library.
   113956 **
   113957 ** When adding new APIs, add them to the bottom of this structure
   113958 ** in order to preserve backwards compatibility.
   113959 **
   113960 ** Extensions that use newer APIs should first call the
   113961 ** sqlite3_libversion_number() to make sure that the API they
   113962 ** intend to use is supported by the library.  Extensions should
   113963 ** also check to make sure that the pointer to the function is
   113964 ** not NULL before calling it.
   113965 */
   113966 static const sqlite3_api_routines sqlite3Apis = {
   113967   sqlite3_aggregate_context,
   113968 #ifndef SQLITE_OMIT_DEPRECATED
   113969   sqlite3_aggregate_count,
   113970 #else
   113971   0,
   113972 #endif
   113973   sqlite3_bind_blob,
   113974   sqlite3_bind_double,
   113975   sqlite3_bind_int,
   113976   sqlite3_bind_int64,
   113977   sqlite3_bind_null,
   113978   sqlite3_bind_parameter_count,
   113979   sqlite3_bind_parameter_index,
   113980   sqlite3_bind_parameter_name,
   113981   sqlite3_bind_text,
   113982   sqlite3_bind_text16,
   113983   sqlite3_bind_value,
   113984   sqlite3_busy_handler,
   113985   sqlite3_busy_timeout,
   113986   sqlite3_changes,
   113987   sqlite3_close,
   113988   sqlite3_collation_needed,
   113989   sqlite3_collation_needed16,
   113990   sqlite3_column_blob,
   113991   sqlite3_column_bytes,
   113992   sqlite3_column_bytes16,
   113993   sqlite3_column_count,
   113994   sqlite3_column_database_name,
   113995   sqlite3_column_database_name16,
   113996   sqlite3_column_decltype,
   113997   sqlite3_column_decltype16,
   113998   sqlite3_column_double,
   113999   sqlite3_column_int,
   114000   sqlite3_column_int64,
   114001   sqlite3_column_name,
   114002   sqlite3_column_name16,
   114003   sqlite3_column_origin_name,
   114004   sqlite3_column_origin_name16,
   114005   sqlite3_column_table_name,
   114006   sqlite3_column_table_name16,
   114007   sqlite3_column_text,
   114008   sqlite3_column_text16,
   114009   sqlite3_column_type,
   114010   sqlite3_column_value,
   114011   sqlite3_commit_hook,
   114012   sqlite3_complete,
   114013   sqlite3_complete16,
   114014   sqlite3_create_collation,
   114015   sqlite3_create_collation16,
   114016   sqlite3_create_function,
   114017   sqlite3_create_function16,
   114018   sqlite3_create_module,
   114019   sqlite3_data_count,
   114020   sqlite3_db_handle,
   114021   sqlite3_declare_vtab,
   114022   sqlite3_enable_shared_cache,
   114023   sqlite3_errcode,
   114024   sqlite3_errmsg,
   114025   sqlite3_errmsg16,
   114026   sqlite3_exec,
   114027 #ifndef SQLITE_OMIT_DEPRECATED
   114028   sqlite3_expired,
   114029 #else
   114030   0,
   114031 #endif
   114032   sqlite3_finalize,
   114033   sqlite3_free,
   114034   sqlite3_free_table,
   114035   sqlite3_get_autocommit,
   114036   sqlite3_get_auxdata,
   114037   sqlite3_get_table,
   114038   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
   114039   sqlite3_interrupt,
   114040   sqlite3_last_insert_rowid,
   114041   sqlite3_libversion,
   114042   sqlite3_libversion_number,
   114043   sqlite3_malloc,
   114044   sqlite3_mprintf,
   114045   sqlite3_open,
   114046   sqlite3_open16,
   114047   sqlite3_prepare,
   114048   sqlite3_prepare16,
   114049   sqlite3_profile,
   114050   sqlite3_progress_handler,
   114051   sqlite3_realloc,
   114052   sqlite3_reset,
   114053   sqlite3_result_blob,
   114054   sqlite3_result_double,
   114055   sqlite3_result_error,
   114056   sqlite3_result_error16,
   114057   sqlite3_result_int,
   114058   sqlite3_result_int64,
   114059   sqlite3_result_null,
   114060   sqlite3_result_text,
   114061   sqlite3_result_text16,
   114062   sqlite3_result_text16be,
   114063   sqlite3_result_text16le,
   114064   sqlite3_result_value,
   114065   sqlite3_rollback_hook,
   114066   sqlite3_set_authorizer,
   114067   sqlite3_set_auxdata,
   114068   sqlite3_snprintf,
   114069   sqlite3_step,
   114070   sqlite3_table_column_metadata,
   114071 #ifndef SQLITE_OMIT_DEPRECATED
   114072   sqlite3_thread_cleanup,
   114073 #else
   114074   0,
   114075 #endif
   114076   sqlite3_total_changes,
   114077   sqlite3_trace,
   114078 #ifndef SQLITE_OMIT_DEPRECATED
   114079   sqlite3_transfer_bindings,
   114080 #else
   114081   0,
   114082 #endif
   114083   sqlite3_update_hook,
   114084   sqlite3_user_data,
   114085   sqlite3_value_blob,
   114086   sqlite3_value_bytes,
   114087   sqlite3_value_bytes16,
   114088   sqlite3_value_double,
   114089   sqlite3_value_int,
   114090   sqlite3_value_int64,
   114091   sqlite3_value_numeric_type,
   114092   sqlite3_value_text,
   114093   sqlite3_value_text16,
   114094   sqlite3_value_text16be,
   114095   sqlite3_value_text16le,
   114096   sqlite3_value_type,
   114097   sqlite3_vmprintf,
   114098   /*
   114099   ** The original API set ends here.  All extensions can call any
   114100   ** of the APIs above provided that the pointer is not NULL.  But
   114101   ** before calling APIs that follow, extension should check the
   114102   ** sqlite3_libversion_number() to make sure they are dealing with
   114103   ** a library that is new enough to support that API.
   114104   *************************************************************************
   114105   */
   114106   sqlite3_overload_function,
   114107 
   114108   /*
   114109   ** Added after 3.3.13
   114110   */
   114111   sqlite3_prepare_v2,
   114112   sqlite3_prepare16_v2,
   114113   sqlite3_clear_bindings,
   114114 
   114115   /*
   114116   ** Added for 3.4.1
   114117   */
   114118   sqlite3_create_module_v2,
   114119 
   114120   /*
   114121   ** Added for 3.5.0
   114122   */
   114123   sqlite3_bind_zeroblob,
   114124   sqlite3_blob_bytes,
   114125   sqlite3_blob_close,
   114126   sqlite3_blob_open,
   114127   sqlite3_blob_read,
   114128   sqlite3_blob_write,
   114129   sqlite3_create_collation_v2,
   114130   sqlite3_file_control,
   114131   sqlite3_memory_highwater,
   114132   sqlite3_memory_used,
   114133 #ifdef SQLITE_MUTEX_OMIT
   114134   0,
   114135   0,
   114136   0,
   114137   0,
   114138   0,
   114139 #else
   114140   sqlite3_mutex_alloc,
   114141   sqlite3_mutex_enter,
   114142   sqlite3_mutex_free,
   114143   sqlite3_mutex_leave,
   114144   sqlite3_mutex_try,
   114145 #endif
   114146   sqlite3_open_v2,
   114147   sqlite3_release_memory,
   114148   sqlite3_result_error_nomem,
   114149   sqlite3_result_error_toobig,
   114150   sqlite3_sleep,
   114151   sqlite3_soft_heap_limit,
   114152   sqlite3_vfs_find,
   114153   sqlite3_vfs_register,
   114154   sqlite3_vfs_unregister,
   114155 
   114156   /*
   114157   ** Added for 3.5.8
   114158   */
   114159   sqlite3_threadsafe,
   114160   sqlite3_result_zeroblob,
   114161   sqlite3_result_error_code,
   114162   sqlite3_test_control,
   114163   sqlite3_randomness,
   114164   sqlite3_context_db_handle,
   114165 
   114166   /*
   114167   ** Added for 3.6.0
   114168   */
   114169   sqlite3_extended_result_codes,
   114170   sqlite3_limit,
   114171   sqlite3_next_stmt,
   114172   sqlite3_sql,
   114173   sqlite3_status,
   114174 
   114175   /*
   114176   ** Added for 3.7.4
   114177   */
   114178   sqlite3_backup_finish,
   114179   sqlite3_backup_init,
   114180   sqlite3_backup_pagecount,
   114181   sqlite3_backup_remaining,
   114182   sqlite3_backup_step,
   114183 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   114184   sqlite3_compileoption_get,
   114185   sqlite3_compileoption_used,
   114186 #else
   114187   0,
   114188   0,
   114189 #endif
   114190   sqlite3_create_function_v2,
   114191   sqlite3_db_config,
   114192   sqlite3_db_mutex,
   114193   sqlite3_db_status,
   114194   sqlite3_extended_errcode,
   114195   sqlite3_log,
   114196   sqlite3_soft_heap_limit64,
   114197   sqlite3_sourceid,
   114198   sqlite3_stmt_status,
   114199   sqlite3_strnicmp,
   114200 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   114201   sqlite3_unlock_notify,
   114202 #else
   114203   0,
   114204 #endif
   114205 #ifndef SQLITE_OMIT_WAL
   114206   sqlite3_wal_autocheckpoint,
   114207   sqlite3_wal_checkpoint,
   114208   sqlite3_wal_hook,
   114209 #else
   114210   0,
   114211   0,
   114212   0,
   114213 #endif
   114214   sqlite3_blob_reopen,
   114215   sqlite3_vtab_config,
   114216   sqlite3_vtab_on_conflict,
   114217   sqlite3_close_v2,
   114218   sqlite3_db_filename,
   114219   sqlite3_db_readonly,
   114220   sqlite3_db_release_memory,
   114221   sqlite3_errstr,
   114222   sqlite3_stmt_busy,
   114223   sqlite3_stmt_readonly,
   114224   sqlite3_stricmp,
   114225   sqlite3_uri_boolean,
   114226   sqlite3_uri_int64,
   114227   sqlite3_uri_parameter,
   114228   sqlite3_vsnprintf,
   114229   sqlite3_wal_checkpoint_v2,
   114230   /* Version 3.8.7 and later */
   114231   sqlite3_auto_extension,
   114232   sqlite3_bind_blob64,
   114233   sqlite3_bind_text64,
   114234   sqlite3_cancel_auto_extension,
   114235   sqlite3_load_extension,
   114236   sqlite3_malloc64,
   114237   sqlite3_msize,
   114238   sqlite3_realloc64,
   114239   sqlite3_reset_auto_extension,
   114240   sqlite3_result_blob64,
   114241   sqlite3_result_text64,
   114242   sqlite3_strglob,
   114243   /* Version 3.8.11 and later */
   114244   (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
   114245   sqlite3_value_free,
   114246   sqlite3_result_zeroblob64,
   114247   sqlite3_bind_zeroblob64,
   114248   /* Version 3.9.0 and later */
   114249   sqlite3_value_subtype,
   114250   sqlite3_result_subtype,
   114251   /* Version 3.10.0 and later */
   114252   sqlite3_status64,
   114253   sqlite3_strlike,
   114254   sqlite3_db_cacheflush,
   114255   /* Version 3.12.0 and later */
   114256   sqlite3_system_errno,
   114257   /* Version 3.14.0 and later */
   114258   sqlite3_trace_v2,
   114259   sqlite3_expanded_sql,
   114260   /* Version 3.18.0 and later */
   114261   sqlite3_set_last_insert_rowid,
   114262   /* Version 3.20.0 and later */
   114263   sqlite3_prepare_v3,
   114264   sqlite3_prepare16_v3,
   114265   sqlite3_bind_pointer,
   114266   sqlite3_result_pointer,
   114267   sqlite3_value_pointer,
   114268   /* Version 3.22.0 and later */
   114269   sqlite3_vtab_nochange,
   114270   sqlite3_value_nochange,
   114271   sqlite3_vtab_collation
   114272 };
   114273 
   114274 /*
   114275 ** Attempt to load an SQLite extension library contained in the file
   114276 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
   114277 ** default entry point name (sqlite3_extension_init) is used.  Use
   114278 ** of the default name is recommended.
   114279 **
   114280 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
   114281 **
   114282 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
   114283 ** error message text.  The calling function should free this memory
   114284 ** by calling sqlite3DbFree(db, ).
   114285 */
   114286 static int sqlite3LoadExtension(
   114287   sqlite3 *db,          /* Load the extension into this database connection */
   114288   const char *zFile,    /* Name of the shared library containing extension */
   114289   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   114290   char **pzErrMsg       /* Put error message here if not 0 */
   114291 ){
   114292   sqlite3_vfs *pVfs = db->pVfs;
   114293   void *handle;
   114294   sqlite3_loadext_entry xInit;
   114295   char *zErrmsg = 0;
   114296   const char *zEntry;
   114297   char *zAltEntry = 0;
   114298   void **aHandle;
   114299   u64 nMsg = 300 + sqlite3Strlen30(zFile);
   114300   int ii;
   114301   int rc;
   114302 
   114303   /* Shared library endings to try if zFile cannot be loaded as written */
   114304   static const char *azEndings[] = {
   114305 #if SQLITE_OS_WIN
   114306      "dll"
   114307 #elif defined(__APPLE__)
   114308      "dylib"
   114309 #else
   114310      "so"
   114311 #endif
   114312   };
   114313 
   114314 
   114315   if( pzErrMsg ) *pzErrMsg = 0;
   114316 
   114317   /* Ticket #1863.  To avoid a creating security problems for older
   114318   ** applications that relink against newer versions of SQLite, the
   114319   ** ability to run load_extension is turned off by default.  One
   114320   ** must call either sqlite3_enable_load_extension(db) or
   114321   ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
   114322   ** to turn on extension loading.
   114323   */
   114324   if( (db->flags & SQLITE_LoadExtension)==0 ){
   114325     if( pzErrMsg ){
   114326       *pzErrMsg = sqlite3_mprintf("not authorized");
   114327     }
   114328     return SQLITE_ERROR;
   114329   }
   114330 
   114331   zEntry = zProc ? zProc : "sqlite3_extension_init";
   114332 
   114333   handle = sqlite3OsDlOpen(pVfs, zFile);
   114334 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
   114335   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
   114336     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
   114337     int bExists = 0;
   114338     if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
   114339     sqlite3OsAccess(pVfs, zAltFile, SQLITE_ACCESS_EXISTS, &bExists);
   114340     if( bExists )  handle = sqlite3OsDlOpen(pVfs, zAltFile);
   114341     sqlite3_free(zAltFile);
   114342   }
   114343 #endif
   114344   if( handle==0 ){
   114345     if( pzErrMsg ){
   114346       *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
   114347       if( zErrmsg ){
   114348         sqlite3_snprintf(nMsg, zErrmsg,
   114349             "unable to open shared library [%s]", zFile);
   114350         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   114351       }
   114352     }
   114353     return SQLITE_ERROR;
   114354   }
   114355   xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
   114356 
   114357   /* If no entry point was specified and the default legacy
   114358   ** entry point name "sqlite3_extension_init" was not found, then
   114359   ** construct an entry point name "sqlite3_X_init" where the X is
   114360   ** replaced by the lowercase value of every ASCII alphabetic
   114361   ** character in the filename after the last "/" upto the first ".",
   114362   ** and eliding the first three characters if they are "lib".
   114363   ** Examples:
   114364   **
   114365   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
   114366   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
   114367   */
   114368   if( xInit==0 && zProc==0 ){
   114369     int iFile, iEntry, c;
   114370     int ncFile = sqlite3Strlen30(zFile);
   114371     zAltEntry = sqlite3_malloc64(ncFile+30);
   114372     if( zAltEntry==0 ){
   114373       sqlite3OsDlClose(pVfs, handle);
   114374       return SQLITE_NOMEM_BKPT;
   114375     }
   114376     memcpy(zAltEntry, "sqlite3_", 8);
   114377     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
   114378     iFile++;
   114379     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
   114380     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
   114381       if( sqlite3Isalpha(c) ){
   114382         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
   114383       }
   114384     }
   114385     memcpy(zAltEntry+iEntry, "_init", 6);
   114386     zEntry = zAltEntry;
   114387     xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
   114388   }
   114389   if( xInit==0 ){
   114390     if( pzErrMsg ){
   114391       nMsg += sqlite3Strlen30(zEntry);
   114392       *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
   114393       if( zErrmsg ){
   114394         sqlite3_snprintf(nMsg, zErrmsg,
   114395             "no entry point [%s] in shared library [%s]", zEntry, zFile);
   114396         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   114397       }
   114398     }
   114399     sqlite3OsDlClose(pVfs, handle);
   114400     sqlite3_free(zAltEntry);
   114401     return SQLITE_ERROR;
   114402   }
   114403   sqlite3_free(zAltEntry);
   114404   rc = xInit(db, &zErrmsg, &sqlite3Apis);
   114405   if( rc ){
   114406     if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
   114407     if( pzErrMsg ){
   114408       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
   114409     }
   114410     sqlite3_free(zErrmsg);
   114411     sqlite3OsDlClose(pVfs, handle);
   114412     return SQLITE_ERROR;
   114413   }
   114414 
   114415   /* Append the new shared library handle to the db->aExtension array. */
   114416   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
   114417   if( aHandle==0 ){
   114418     return SQLITE_NOMEM_BKPT;
   114419   }
   114420   if( db->nExtension>0 ){
   114421     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
   114422   }
   114423   sqlite3DbFree(db, db->aExtension);
   114424   db->aExtension = aHandle;
   114425 
   114426   db->aExtension[db->nExtension++] = handle;
   114427   return SQLITE_OK;
   114428 }
   114429 SQLITE_API int sqlite3_load_extension(
   114430   sqlite3 *db,          /* Load the extension into this database connection */
   114431   const char *zFile,    /* Name of the shared library containing extension */
   114432   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   114433   char **pzErrMsg       /* Put error message here if not 0 */
   114434 ){
   114435   int rc;
   114436   sqlite3_mutex_enter(db->mutex);
   114437   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
   114438   rc = sqlite3ApiExit(db, rc);
   114439   sqlite3_mutex_leave(db->mutex);
   114440   return rc;
   114441 }
   114442 
   114443 /*
   114444 ** Call this routine when the database connection is closing in order
   114445 ** to clean up loaded extensions
   114446 */
   114447 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
   114448   int i;
   114449   assert( sqlite3_mutex_held(db->mutex) );
   114450   for(i=0; i<db->nExtension; i++){
   114451     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
   114452   }
   114453   sqlite3DbFree(db, db->aExtension);
   114454 }
   114455 
   114456 /*
   114457 ** Enable or disable extension loading.  Extension loading is disabled by
   114458 ** default so as not to open security holes in older applications.
   114459 */
   114460 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
   114461   sqlite3_mutex_enter(db->mutex);
   114462   if( onoff ){
   114463     db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
   114464   }else{
   114465     db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
   114466   }
   114467   sqlite3_mutex_leave(db->mutex);
   114468   return SQLITE_OK;
   114469 }
   114470 
   114471 #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
   114472 
   114473 /*
   114474 ** The following object holds the list of automatically loaded
   114475 ** extensions.
   114476 **
   114477 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
   114478 ** mutex must be held while accessing this list.
   114479 */
   114480 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
   114481 static SQLITE_WSD struct sqlite3AutoExtList {
   114482   u32 nExt;              /* Number of entries in aExt[] */
   114483   void (**aExt)(void);   /* Pointers to the extension init functions */
   114484 } sqlite3Autoext = { 0, 0 };
   114485 
   114486 /* The "wsdAutoext" macro will resolve to the autoextension
   114487 ** state vector.  If writable static data is unsupported on the target,
   114488 ** we have to locate the state vector at run-time.  In the more common
   114489 ** case where writable static data is supported, wsdStat can refer directly
   114490 ** to the "sqlite3Autoext" state vector declared above.
   114491 */
   114492 #ifdef SQLITE_OMIT_WSD
   114493 # define wsdAutoextInit \
   114494   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
   114495 # define wsdAutoext x[0]
   114496 #else
   114497 # define wsdAutoextInit
   114498 # define wsdAutoext sqlite3Autoext
   114499 #endif
   114500 
   114501 
   114502 /*
   114503 ** Register a statically linked extension that is automatically
   114504 ** loaded by every new database connection.
   114505 */
   114506 SQLITE_API int sqlite3_auto_extension(
   114507   void (*xInit)(void)
   114508 ){
   114509   int rc = SQLITE_OK;
   114510 #ifndef SQLITE_OMIT_AUTOINIT
   114511   rc = sqlite3_initialize();
   114512   if( rc ){
   114513     return rc;
   114514   }else
   114515 #endif
   114516   {
   114517     u32 i;
   114518 #if SQLITE_THREADSAFE
   114519     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   114520 #endif
   114521     wsdAutoextInit;
   114522     sqlite3_mutex_enter(mutex);
   114523     for(i=0; i<wsdAutoext.nExt; i++){
   114524       if( wsdAutoext.aExt[i]==xInit ) break;
   114525     }
   114526     if( i==wsdAutoext.nExt ){
   114527       u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
   114528       void (**aNew)(void);
   114529       aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
   114530       if( aNew==0 ){
   114531         rc = SQLITE_NOMEM_BKPT;
   114532       }else{
   114533         wsdAutoext.aExt = aNew;
   114534         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
   114535         wsdAutoext.nExt++;
   114536       }
   114537     }
   114538     sqlite3_mutex_leave(mutex);
   114539     assert( (rc&0xff)==rc );
   114540     return rc;
   114541   }
   114542 }
   114543 
   114544 /*
   114545 ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
   114546 ** set of routines that is invoked for each new database connection, if it
   114547 ** is currently on the list.  If xInit is not on the list, then this
   114548 ** routine is a no-op.
   114549 **
   114550 ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
   114551 ** was not on the list.
   114552 */
   114553 SQLITE_API int sqlite3_cancel_auto_extension(
   114554   void (*xInit)(void)
   114555 ){
   114556 #if SQLITE_THREADSAFE
   114557   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   114558 #endif
   114559   int i;
   114560   int n = 0;
   114561   wsdAutoextInit;
   114562   sqlite3_mutex_enter(mutex);
   114563   for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
   114564     if( wsdAutoext.aExt[i]==xInit ){
   114565       wsdAutoext.nExt--;
   114566       wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
   114567       n++;
   114568       break;
   114569     }
   114570   }
   114571   sqlite3_mutex_leave(mutex);
   114572   return n;
   114573 }
   114574 
   114575 /*
   114576 ** Reset the automatic extension loading mechanism.
   114577 */
   114578 SQLITE_API void sqlite3_reset_auto_extension(void){
   114579 #ifndef SQLITE_OMIT_AUTOINIT
   114580   if( sqlite3_initialize()==SQLITE_OK )
   114581 #endif
   114582   {
   114583 #if SQLITE_THREADSAFE
   114584     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   114585 #endif
   114586     wsdAutoextInit;
   114587     sqlite3_mutex_enter(mutex);
   114588     sqlite3_free(wsdAutoext.aExt);
   114589     wsdAutoext.aExt = 0;
   114590     wsdAutoext.nExt = 0;
   114591     sqlite3_mutex_leave(mutex);
   114592   }
   114593 }
   114594 
   114595 /*
   114596 ** Load all automatic extensions.
   114597 **
   114598 ** If anything goes wrong, set an error in the database connection.
   114599 */
   114600 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   114601   u32 i;
   114602   int go = 1;
   114603   int rc;
   114604   sqlite3_loadext_entry xInit;
   114605 
   114606   wsdAutoextInit;
   114607   if( wsdAutoext.nExt==0 ){
   114608     /* Common case: early out without every having to acquire a mutex */
   114609     return;
   114610   }
   114611   for(i=0; go; i++){
   114612     char *zErrmsg;
   114613 #if SQLITE_THREADSAFE
   114614     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   114615 #endif
   114616 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   114617     const sqlite3_api_routines *pThunk = 0;
   114618 #else
   114619     const sqlite3_api_routines *pThunk = &sqlite3Apis;
   114620 #endif
   114621     sqlite3_mutex_enter(mutex);
   114622     if( i>=wsdAutoext.nExt ){
   114623       xInit = 0;
   114624       go = 0;
   114625     }else{
   114626       xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
   114627     }
   114628     sqlite3_mutex_leave(mutex);
   114629     zErrmsg = 0;
   114630     if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
   114631       sqlite3ErrorWithMsg(db, rc,
   114632             "automatic extension loading failed: %s", zErrmsg);
   114633       go = 0;
   114634     }
   114635     sqlite3_free(zErrmsg);
   114636   }
   114637 }
   114638 
   114639 /************** End of loadext.c *********************************************/
   114640 /************** Begin file pragma.c ******************************************/
   114641 /*
   114642 ** 2003 April 6
   114643 **
   114644 ** The author disclaims copyright to this source code.  In place of
   114645 ** a legal notice, here is a blessing:
   114646 **
   114647 **    May you do good and not evil.
   114648 **    May you find forgiveness for yourself and forgive others.
   114649 **    May you share freely, never taking more than you give.
   114650 **
   114651 *************************************************************************
   114652 ** This file contains code used to implement the PRAGMA command.
   114653 */
   114654 /* #include "sqliteInt.h" */
   114655 
   114656 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   114657 #  if defined(__APPLE__)
   114658 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   114659 #  else
   114660 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   114661 #  endif
   114662 #endif
   114663 
   114664 /***************************************************************************
   114665 ** The "pragma.h" include file is an automatically generated file that
   114666 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
   114667 ** object.  This ensures that the aPragmaName[] table is arranged in
   114668 ** lexicographical order to facility a binary search of the pragma name.
   114669 ** Do not edit pragma.h directly.  Edit and rerun the script in at
   114670 ** ../tool/mkpragmatab.tcl. */
   114671 /************** Include pragma.h in the middle of pragma.c *******************/
   114672 /************** Begin file pragma.h ******************************************/
   114673 /* DO NOT EDIT!
   114674 ** This file is automatically generated by the script at
   114675 ** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
   114676 ** that script and rerun it.
   114677 */
   114678 
   114679 /* The various pragma types */
   114680 #define PragTyp_HEADER_VALUE                   0
   114681 #define PragTyp_AUTO_VACUUM                    1
   114682 #define PragTyp_FLAG                           2
   114683 #define PragTyp_BUSY_TIMEOUT                   3
   114684 #define PragTyp_CACHE_SIZE                     4
   114685 #define PragTyp_CACHE_SPILL                    5
   114686 #define PragTyp_CASE_SENSITIVE_LIKE            6
   114687 #define PragTyp_COLLATION_LIST                 7
   114688 #define PragTyp_COMPILE_OPTIONS                8
   114689 #define PragTyp_DATA_STORE_DIRECTORY           9
   114690 #define PragTyp_DATABASE_LIST                 10
   114691 #define PragTyp_DEFAULT_CACHE_SIZE            11
   114692 #define PragTyp_ENCODING                      12
   114693 #define PragTyp_FOREIGN_KEY_CHECK             13
   114694 #define PragTyp_FOREIGN_KEY_LIST              14
   114695 #define PragTyp_FUNCTION_LIST                 15
   114696 #define PragTyp_INCREMENTAL_VACUUM            16
   114697 #define PragTyp_INDEX_INFO                    17
   114698 #define PragTyp_INDEX_LIST                    18
   114699 #define PragTyp_INTEGRITY_CHECK               19
   114700 #define PragTyp_JOURNAL_MODE                  20
   114701 #define PragTyp_JOURNAL_SIZE_LIMIT            21
   114702 #define PragTyp_LOCK_PROXY_FILE               22
   114703 #define PragTyp_LOCKING_MODE                  23
   114704 #define PragTyp_PAGE_COUNT                    24
   114705 #define PragTyp_MMAP_SIZE                     25
   114706 #define PragTyp_MODULE_LIST                   26
   114707 #define PragTyp_OPTIMIZE                      27
   114708 #define PragTyp_PAGE_SIZE                     28
   114709 #define PragTyp_PRAGMA_LIST                   29
   114710 #define PragTyp_SECURE_DELETE                 30
   114711 #define PragTyp_SHRINK_MEMORY                 31
   114712 #define PragTyp_SOFT_HEAP_LIMIT               32
   114713 #define PragTyp_SYNCHRONOUS                   33
   114714 #define PragTyp_TABLE_INFO                    34
   114715 #define PragTyp_TEMP_STORE                    35
   114716 #define PragTyp_TEMP_STORE_DIRECTORY          36
   114717 #define PragTyp_THREADS                       37
   114718 #define PragTyp_WAL_AUTOCHECKPOINT            38
   114719 #define PragTyp_WAL_CHECKPOINT                39
   114720 #define PragTyp_ACTIVATE_EXTENSIONS           40
   114721 #define PragTyp_HEXKEY                        41
   114722 #define PragTyp_KEY                           42
   114723 #define PragTyp_REKEY                         43
   114724 #define PragTyp_LOCK_STATUS                   44
   114725 #define PragTyp_PARSER_TRACE                  45
   114726 #define PragTyp_STATS                         46
   114727 
   114728 /* Property flags associated with various pragma. */
   114729 #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
   114730 #define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */
   114731 #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
   114732 #define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */
   114733 #define PragFlg_Result0    0x10 /* Acts as query when no argument */
   114734 #define PragFlg_Result1    0x20 /* Acts as query when has one argument */
   114735 #define PragFlg_SchemaOpt  0x40 /* Schema restricts name search if present */
   114736 #define PragFlg_SchemaReq  0x80 /* Schema required - "main" is default */
   114737 
   114738 /* Names of columns for pragmas that return multi-column result
   114739 ** or that return single-column results where the name of the
   114740 ** result column is different from the name of the pragma
   114741 */
   114742 static const char *const pragCName[] = {
   114743   /*   0 */ "cache_size",  /* Used by: default_cache_size */
   114744   /*   1 */ "cid",         /* Used by: table_info */
   114745   /*   2 */ "name",
   114746   /*   3 */ "type",
   114747   /*   4 */ "notnull",
   114748   /*   5 */ "dflt_value",
   114749   /*   6 */ "pk",
   114750   /*   7 */ "tbl",         /* Used by: stats */
   114751   /*   8 */ "idx",
   114752   /*   9 */ "wdth",
   114753   /*  10 */ "hght",
   114754   /*  11 */ "flgs",
   114755   /*  12 */ "seqno",       /* Used by: index_info */
   114756   /*  13 */ "cid",
   114757   /*  14 */ "name",
   114758   /*  15 */ "seqno",       /* Used by: index_xinfo */
   114759   /*  16 */ "cid",
   114760   /*  17 */ "name",
   114761   /*  18 */ "desc",
   114762   /*  19 */ "coll",
   114763   /*  20 */ "key",
   114764   /*  21 */ "seq",         /* Used by: index_list */
   114765   /*  22 */ "name",
   114766   /*  23 */ "unique",
   114767   /*  24 */ "origin",
   114768   /*  25 */ "partial",
   114769   /*  26 */ "seq",         /* Used by: database_list */
   114770   /*  27 */ "name",
   114771   /*  28 */ "file",
   114772   /*  29 */ "name",        /* Used by: function_list */
   114773   /*  30 */ "builtin",
   114774   /*  31 */ "name",        /* Used by: module_list pragma_list */
   114775   /*  32 */ "seq",         /* Used by: collation_list */
   114776   /*  33 */ "name",
   114777   /*  34 */ "id",          /* Used by: foreign_key_list */
   114778   /*  35 */ "seq",
   114779   /*  36 */ "table",
   114780   /*  37 */ "from",
   114781   /*  38 */ "to",
   114782   /*  39 */ "on_update",
   114783   /*  40 */ "on_delete",
   114784   /*  41 */ "match",
   114785   /*  42 */ "table",       /* Used by: foreign_key_check */
   114786   /*  43 */ "rowid",
   114787   /*  44 */ "parent",
   114788   /*  45 */ "fkid",
   114789   /*  46 */ "busy",        /* Used by: wal_checkpoint */
   114790   /*  47 */ "log",
   114791   /*  48 */ "checkpointed",
   114792   /*  49 */ "timeout",     /* Used by: busy_timeout */
   114793   /*  50 */ "database",    /* Used by: lock_status */
   114794   /*  51 */ "status",
   114795 };
   114796 
   114797 /* Definitions of all built-in pragmas */
   114798 typedef struct PragmaName {
   114799   const char *const zName; /* Name of pragma */
   114800   u8 ePragTyp;             /* PragTyp_XXX value */
   114801   u8 mPragFlg;             /* Zero or more PragFlg_XXX values */
   114802   u8 iPragCName;           /* Start of column names in pragCName[] */
   114803   u8 nPragCName;           /* Num of col names. 0 means use pragma name */
   114804   u32 iArg;                /* Extra argument */
   114805 } PragmaName;
   114806 static const PragmaName aPragmaName[] = {
   114807 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   114808  {/* zName:     */ "activate_extensions",
   114809   /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
   114810   /* ePragFlg:  */ 0,
   114811   /* ColNames:  */ 0, 0,
   114812   /* iArg:      */ 0 },
   114813 #endif
   114814 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   114815  {/* zName:     */ "application_id",
   114816   /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   114817   /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
   114818   /* ColNames:  */ 0, 0,
   114819   /* iArg:      */ BTREE_APPLICATION_ID },
   114820 #endif
   114821 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   114822  {/* zName:     */ "auto_vacuum",
   114823   /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
   114824   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
   114825   /* ColNames:  */ 0, 0,
   114826   /* iArg:      */ 0 },
   114827 #endif
   114828 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114829 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
   114830  {/* zName:     */ "automatic_index",
   114831   /* ePragTyp:  */ PragTyp_FLAG,
   114832   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114833   /* ColNames:  */ 0, 0,
   114834   /* iArg:      */ SQLITE_AutoIndex },
   114835 #endif
   114836 #endif
   114837  {/* zName:     */ "busy_timeout",
   114838   /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
   114839   /* ePragFlg:  */ PragFlg_Result0,
   114840   /* ColNames:  */ 49, 1,
   114841   /* iArg:      */ 0 },
   114842 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   114843  {/* zName:     */ "cache_size",
   114844   /* ePragTyp:  */ PragTyp_CACHE_SIZE,
   114845   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
   114846   /* ColNames:  */ 0, 0,
   114847   /* iArg:      */ 0 },
   114848 #endif
   114849 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114850  {/* zName:     */ "cache_spill",
   114851   /* ePragTyp:  */ PragTyp_CACHE_SPILL,
   114852   /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
   114853   /* ColNames:  */ 0, 0,
   114854   /* iArg:      */ 0 },
   114855 #endif
   114856  {/* zName:     */ "case_sensitive_like",
   114857   /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
   114858   /* ePragFlg:  */ PragFlg_NoColumns,
   114859   /* ColNames:  */ 0, 0,
   114860   /* iArg:      */ 0 },
   114861  {/* zName:     */ "cell_size_check",
   114862   /* ePragTyp:  */ PragTyp_FLAG,
   114863   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114864   /* ColNames:  */ 0, 0,
   114865   /* iArg:      */ SQLITE_CellSizeCk },
   114866 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114867  {/* zName:     */ "checkpoint_fullfsync",
   114868   /* ePragTyp:  */ PragTyp_FLAG,
   114869   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114870   /* ColNames:  */ 0, 0,
   114871   /* iArg:      */ SQLITE_CkptFullFSync },
   114872 #endif
   114873 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   114874  {/* zName:     */ "collation_list",
   114875   /* ePragTyp:  */ PragTyp_COLLATION_LIST,
   114876   /* ePragFlg:  */ PragFlg_Result0,
   114877   /* ColNames:  */ 32, 2,
   114878   /* iArg:      */ 0 },
   114879 #endif
   114880 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
   114881  {/* zName:     */ "compile_options",
   114882   /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
   114883   /* ePragFlg:  */ PragFlg_Result0,
   114884   /* ColNames:  */ 0, 0,
   114885   /* iArg:      */ 0 },
   114886 #endif
   114887 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114888  {/* zName:     */ "count_changes",
   114889   /* ePragTyp:  */ PragTyp_FLAG,
   114890   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114891   /* ColNames:  */ 0, 0,
   114892   /* iArg:      */ SQLITE_CountRows },
   114893 #endif
   114894 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
   114895  {/* zName:     */ "data_store_directory",
   114896   /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
   114897   /* ePragFlg:  */ PragFlg_NoColumns1,
   114898   /* ColNames:  */ 0, 0,
   114899   /* iArg:      */ 0 },
   114900 #endif
   114901 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   114902  {/* zName:     */ "data_version",
   114903   /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   114904   /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
   114905   /* ColNames:  */ 0, 0,
   114906   /* iArg:      */ BTREE_DATA_VERSION },
   114907 #endif
   114908 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   114909  {/* zName:     */ "database_list",
   114910   /* ePragTyp:  */ PragTyp_DATABASE_LIST,
   114911   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
   114912   /* ColNames:  */ 26, 3,
   114913   /* iArg:      */ 0 },
   114914 #endif
   114915 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   114916  {/* zName:     */ "default_cache_size",
   114917   /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
   114918   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
   114919   /* ColNames:  */ 0, 1,
   114920   /* iArg:      */ 0 },
   114921 #endif
   114922 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114923 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   114924  {/* zName:     */ "defer_foreign_keys",
   114925   /* ePragTyp:  */ PragTyp_FLAG,
   114926   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114927   /* ColNames:  */ 0, 0,
   114928   /* iArg:      */ SQLITE_DeferFKs },
   114929 #endif
   114930 #endif
   114931 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114932  {/* zName:     */ "empty_result_callbacks",
   114933   /* ePragTyp:  */ PragTyp_FLAG,
   114934   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114935   /* ColNames:  */ 0, 0,
   114936   /* iArg:      */ SQLITE_NullCallback },
   114937 #endif
   114938 #if !defined(SQLITE_OMIT_UTF16)
   114939  {/* zName:     */ "encoding",
   114940   /* ePragTyp:  */ PragTyp_ENCODING,
   114941   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114942   /* ColNames:  */ 0, 0,
   114943   /* iArg:      */ 0 },
   114944 #endif
   114945 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   114946  {/* zName:     */ "foreign_key_check",
   114947   /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
   114948   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
   114949   /* ColNames:  */ 42, 4,
   114950   /* iArg:      */ 0 },
   114951 #endif
   114952 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
   114953  {/* zName:     */ "foreign_key_list",
   114954   /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
   114955   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
   114956   /* ColNames:  */ 34, 8,
   114957   /* iArg:      */ 0 },
   114958 #endif
   114959 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114960 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   114961  {/* zName:     */ "foreign_keys",
   114962   /* ePragTyp:  */ PragTyp_FLAG,
   114963   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114964   /* ColNames:  */ 0, 0,
   114965   /* iArg:      */ SQLITE_ForeignKeys },
   114966 #endif
   114967 #endif
   114968 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   114969  {/* zName:     */ "freelist_count",
   114970   /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   114971   /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
   114972   /* ColNames:  */ 0, 0,
   114973   /* iArg:      */ BTREE_FREE_PAGE_COUNT },
   114974 #endif
   114975 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   114976  {/* zName:     */ "full_column_names",
   114977   /* ePragTyp:  */ PragTyp_FLAG,
   114978   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114979   /* ColNames:  */ 0, 0,
   114980   /* iArg:      */ SQLITE_FullColNames },
   114981  {/* zName:     */ "fullfsync",
   114982   /* ePragTyp:  */ PragTyp_FLAG,
   114983   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   114984   /* ColNames:  */ 0, 0,
   114985   /* iArg:      */ SQLITE_FullFSync },
   114986 #endif
   114987 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   114988 #if defined(SQLITE_INTROSPECTION_PRAGMAS)
   114989  {/* zName:     */ "function_list",
   114990   /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
   114991   /* ePragFlg:  */ PragFlg_Result0,
   114992   /* ColNames:  */ 29, 2,
   114993   /* iArg:      */ 0 },
   114994 #endif
   114995 #endif
   114996 #if defined(SQLITE_HAS_CODEC)
   114997  {/* zName:     */ "hexkey",
   114998   /* ePragTyp:  */ PragTyp_HEXKEY,
   114999   /* ePragFlg:  */ 0,
   115000   /* ColNames:  */ 0, 0,
   115001   /* iArg:      */ 0 },
   115002  {/* zName:     */ "hexrekey",
   115003   /* ePragTyp:  */ PragTyp_HEXKEY,
   115004   /* ePragFlg:  */ 0,
   115005   /* ColNames:  */ 0, 0,
   115006   /* iArg:      */ 0 },
   115007 #endif
   115008 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115009 #if !defined(SQLITE_OMIT_CHECK)
   115010  {/* zName:     */ "ignore_check_constraints",
   115011   /* ePragTyp:  */ PragTyp_FLAG,
   115012   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115013   /* ColNames:  */ 0, 0,
   115014   /* iArg:      */ SQLITE_IgnoreChecks },
   115015 #endif
   115016 #endif
   115017 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   115018  {/* zName:     */ "incremental_vacuum",
   115019   /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
   115020   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_NoColumns,
   115021   /* ColNames:  */ 0, 0,
   115022   /* iArg:      */ 0 },
   115023 #endif
   115024 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   115025  {/* zName:     */ "index_info",
   115026   /* ePragTyp:  */ PragTyp_INDEX_INFO,
   115027   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
   115028   /* ColNames:  */ 12, 3,
   115029   /* iArg:      */ 0 },
   115030  {/* zName:     */ "index_list",
   115031   /* ePragTyp:  */ PragTyp_INDEX_LIST,
   115032   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
   115033   /* ColNames:  */ 21, 5,
   115034   /* iArg:      */ 0 },
   115035  {/* zName:     */ "index_xinfo",
   115036   /* ePragTyp:  */ PragTyp_INDEX_INFO,
   115037   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
   115038   /* ColNames:  */ 15, 6,
   115039   /* iArg:      */ 1 },
   115040 #endif
   115041 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
   115042  {/* zName:     */ "integrity_check",
   115043   /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
   115044   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
   115045   /* ColNames:  */ 0, 0,
   115046   /* iArg:      */ 0 },
   115047 #endif
   115048 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   115049  {/* zName:     */ "journal_mode",
   115050   /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
   115051   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
   115052   /* ColNames:  */ 0, 0,
   115053   /* iArg:      */ 0 },
   115054  {/* zName:     */ "journal_size_limit",
   115055   /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
   115056   /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
   115057   /* ColNames:  */ 0, 0,
   115058   /* iArg:      */ 0 },
   115059 #endif
   115060 #if defined(SQLITE_HAS_CODEC)
   115061  {/* zName:     */ "key",
   115062   /* ePragTyp:  */ PragTyp_KEY,
   115063   /* ePragFlg:  */ 0,
   115064   /* ColNames:  */ 0, 0,
   115065   /* iArg:      */ 0 },
   115066 #endif
   115067 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115068  {/* zName:     */ "legacy_file_format",
   115069   /* ePragTyp:  */ PragTyp_FLAG,
   115070   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115071   /* ColNames:  */ 0, 0,
   115072   /* iArg:      */ SQLITE_LegacyFileFmt },
   115073 #endif
   115074 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
   115075  {/* zName:     */ "lock_proxy_file",
   115076   /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
   115077   /* ePragFlg:  */ PragFlg_NoColumns1,
   115078   /* ColNames:  */ 0, 0,
   115079   /* iArg:      */ 0 },
   115080 #endif
   115081 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   115082  {/* zName:     */ "lock_status",
   115083   /* ePragTyp:  */ PragTyp_LOCK_STATUS,
   115084   /* ePragFlg:  */ PragFlg_Result0,
   115085   /* ColNames:  */ 50, 2,
   115086   /* iArg:      */ 0 },
   115087 #endif
   115088 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   115089  {/* zName:     */ "locking_mode",
   115090   /* ePragTyp:  */ PragTyp_LOCKING_MODE,
   115091   /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
   115092   /* ColNames:  */ 0, 0,
   115093   /* iArg:      */ 0 },
   115094  {/* zName:     */ "max_page_count",
   115095   /* ePragTyp:  */ PragTyp_PAGE_COUNT,
   115096   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
   115097   /* ColNames:  */ 0, 0,
   115098   /* iArg:      */ 0 },
   115099  {/* zName:     */ "mmap_size",
   115100   /* ePragTyp:  */ PragTyp_MMAP_SIZE,
   115101   /* ePragFlg:  */ 0,
   115102   /* ColNames:  */ 0, 0,
   115103   /* iArg:      */ 0 },
   115104 #endif
   115105 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   115106 #if !defined(SQLITE_OMIT_VIRTUALTABLE)
   115107 #if defined(SQLITE_INTROSPECTION_PRAGMAS)
   115108  {/* zName:     */ "module_list",
   115109   /* ePragTyp:  */ PragTyp_MODULE_LIST,
   115110   /* ePragFlg:  */ PragFlg_Result0,
   115111   /* ColNames:  */ 31, 1,
   115112   /* iArg:      */ 0 },
   115113 #endif
   115114 #endif
   115115 #endif
   115116  {/* zName:     */ "optimize",
   115117   /* ePragTyp:  */ PragTyp_OPTIMIZE,
   115118   /* ePragFlg:  */ PragFlg_Result1|PragFlg_NeedSchema,
   115119   /* ColNames:  */ 0, 0,
   115120   /* iArg:      */ 0 },
   115121 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   115122  {/* zName:     */ "page_count",
   115123   /* ePragTyp:  */ PragTyp_PAGE_COUNT,
   115124   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
   115125   /* ColNames:  */ 0, 0,
   115126   /* iArg:      */ 0 },
   115127  {/* zName:     */ "page_size",
   115128   /* ePragTyp:  */ PragTyp_PAGE_SIZE,
   115129   /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
   115130   /* ColNames:  */ 0, 0,
   115131   /* iArg:      */ 0 },
   115132 #endif
   115133 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
   115134  {/* zName:     */ "parser_trace",
   115135   /* ePragTyp:  */ PragTyp_PARSER_TRACE,
   115136   /* ePragFlg:  */ 0,
   115137   /* ColNames:  */ 0, 0,
   115138   /* iArg:      */ 0 },
   115139 #endif
   115140 #if defined(SQLITE_INTROSPECTION_PRAGMAS)
   115141  {/* zName:     */ "pragma_list",
   115142   /* ePragTyp:  */ PragTyp_PRAGMA_LIST,
   115143   /* ePragFlg:  */ PragFlg_Result0,
   115144   /* ColNames:  */ 31, 1,
   115145   /* iArg:      */ 0 },
   115146 #endif
   115147 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115148  {/* zName:     */ "query_only",
   115149   /* ePragTyp:  */ PragTyp_FLAG,
   115150   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115151   /* ColNames:  */ 0, 0,
   115152   /* iArg:      */ SQLITE_QueryOnly },
   115153 #endif
   115154 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
   115155  {/* zName:     */ "quick_check",
   115156   /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
   115157   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
   115158   /* ColNames:  */ 0, 0,
   115159   /* iArg:      */ 0 },
   115160 #endif
   115161 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115162  {/* zName:     */ "read_uncommitted",
   115163   /* ePragTyp:  */ PragTyp_FLAG,
   115164   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115165   /* ColNames:  */ 0, 0,
   115166   /* iArg:      */ SQLITE_ReadUncommit },
   115167  {/* zName:     */ "recursive_triggers",
   115168   /* ePragTyp:  */ PragTyp_FLAG,
   115169   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115170   /* ColNames:  */ 0, 0,
   115171   /* iArg:      */ SQLITE_RecTriggers },
   115172 #endif
   115173 #if defined(SQLITE_HAS_CODEC)
   115174  {/* zName:     */ "rekey",
   115175   /* ePragTyp:  */ PragTyp_REKEY,
   115176   /* ePragFlg:  */ 0,
   115177   /* ColNames:  */ 0, 0,
   115178   /* iArg:      */ 0 },
   115179 #endif
   115180 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115181  {/* zName:     */ "reverse_unordered_selects",
   115182   /* ePragTyp:  */ PragTyp_FLAG,
   115183   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115184   /* ColNames:  */ 0, 0,
   115185   /* iArg:      */ SQLITE_ReverseOrder },
   115186 #endif
   115187 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   115188  {/* zName:     */ "schema_version",
   115189   /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   115190   /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
   115191   /* ColNames:  */ 0, 0,
   115192   /* iArg:      */ BTREE_SCHEMA_VERSION },
   115193 #endif
   115194 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   115195  {/* zName:     */ "secure_delete",
   115196   /* ePragTyp:  */ PragTyp_SECURE_DELETE,
   115197   /* ePragFlg:  */ PragFlg_Result0,
   115198   /* ColNames:  */ 0, 0,
   115199   /* iArg:      */ 0 },
   115200 #endif
   115201 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115202  {/* zName:     */ "short_column_names",
   115203   /* ePragTyp:  */ PragTyp_FLAG,
   115204   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115205   /* ColNames:  */ 0, 0,
   115206   /* iArg:      */ SQLITE_ShortColNames },
   115207 #endif
   115208  {/* zName:     */ "shrink_memory",
   115209   /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
   115210   /* ePragFlg:  */ PragFlg_NoColumns,
   115211   /* ColNames:  */ 0, 0,
   115212   /* iArg:      */ 0 },
   115213  {/* zName:     */ "soft_heap_limit",
   115214   /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
   115215   /* ePragFlg:  */ PragFlg_Result0,
   115216   /* ColNames:  */ 0, 0,
   115217   /* iArg:      */ 0 },
   115218 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115219 #if defined(SQLITE_DEBUG)
   115220  {/* zName:     */ "sql_trace",
   115221   /* ePragTyp:  */ PragTyp_FLAG,
   115222   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115223   /* ColNames:  */ 0, 0,
   115224   /* iArg:      */ SQLITE_SqlTrace },
   115225 #endif
   115226 #endif
   115227 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
   115228  {/* zName:     */ "stats",
   115229   /* ePragTyp:  */ PragTyp_STATS,
   115230   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
   115231   /* ColNames:  */ 7, 5,
   115232   /* iArg:      */ 0 },
   115233 #endif
   115234 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   115235  {/* zName:     */ "synchronous",
   115236   /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
   115237   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
   115238   /* ColNames:  */ 0, 0,
   115239   /* iArg:      */ 0 },
   115240 #endif
   115241 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
   115242  {/* zName:     */ "table_info",
   115243   /* ePragTyp:  */ PragTyp_TABLE_INFO,
   115244   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
   115245   /* ColNames:  */ 1, 6,
   115246   /* iArg:      */ 0 },
   115247 #endif
   115248 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   115249  {/* zName:     */ "temp_store",
   115250   /* ePragTyp:  */ PragTyp_TEMP_STORE,
   115251   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115252   /* ColNames:  */ 0, 0,
   115253   /* iArg:      */ 0 },
   115254  {/* zName:     */ "temp_store_directory",
   115255   /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
   115256   /* ePragFlg:  */ PragFlg_NoColumns1,
   115257   /* ColNames:  */ 0, 0,
   115258   /* iArg:      */ 0 },
   115259 #endif
   115260  {/* zName:     */ "threads",
   115261   /* ePragTyp:  */ PragTyp_THREADS,
   115262   /* ePragFlg:  */ PragFlg_Result0,
   115263   /* ColNames:  */ 0, 0,
   115264   /* iArg:      */ 0 },
   115265 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
   115266  {/* zName:     */ "user_version",
   115267   /* ePragTyp:  */ PragTyp_HEADER_VALUE,
   115268   /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
   115269   /* ColNames:  */ 0, 0,
   115270   /* iArg:      */ BTREE_USER_VERSION },
   115271 #endif
   115272 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115273 #if defined(SQLITE_DEBUG)
   115274  {/* zName:     */ "vdbe_addoptrace",
   115275   /* ePragTyp:  */ PragTyp_FLAG,
   115276   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115277   /* ColNames:  */ 0, 0,
   115278   /* iArg:      */ SQLITE_VdbeAddopTrace },
   115279  {/* zName:     */ "vdbe_debug",
   115280   /* ePragTyp:  */ PragTyp_FLAG,
   115281   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115282   /* ColNames:  */ 0, 0,
   115283   /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
   115284  {/* zName:     */ "vdbe_eqp",
   115285   /* ePragTyp:  */ PragTyp_FLAG,
   115286   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115287   /* ColNames:  */ 0, 0,
   115288   /* iArg:      */ SQLITE_VdbeEQP },
   115289  {/* zName:     */ "vdbe_listing",
   115290   /* ePragTyp:  */ PragTyp_FLAG,
   115291   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115292   /* ColNames:  */ 0, 0,
   115293   /* iArg:      */ SQLITE_VdbeListing },
   115294  {/* zName:     */ "vdbe_trace",
   115295   /* ePragTyp:  */ PragTyp_FLAG,
   115296   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115297   /* ColNames:  */ 0, 0,
   115298   /* iArg:      */ SQLITE_VdbeTrace },
   115299 #endif
   115300 #endif
   115301 #if !defined(SQLITE_OMIT_WAL)
   115302  {/* zName:     */ "wal_autocheckpoint",
   115303   /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
   115304   /* ePragFlg:  */ 0,
   115305   /* ColNames:  */ 0, 0,
   115306   /* iArg:      */ 0 },
   115307  {/* zName:     */ "wal_checkpoint",
   115308   /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
   115309   /* ePragFlg:  */ PragFlg_NeedSchema,
   115310   /* ColNames:  */ 46, 3,
   115311   /* iArg:      */ 0 },
   115312 #endif
   115313 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
   115314  {/* zName:     */ "writable_schema",
   115315   /* ePragTyp:  */ PragTyp_FLAG,
   115316   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   115317   /* ColNames:  */ 0, 0,
   115318   /* iArg:      */ SQLITE_WriteSchema },
   115319 #endif
   115320 };
   115321 /* Number of pragmas: 60 on by default, 77 total. */
   115322 
   115323 /************** End of pragma.h **********************************************/
   115324 /************** Continuing where we left off in pragma.c *********************/
   115325 
   115326 /*
   115327 ** Interpret the given string as a safety level.  Return 0 for OFF,
   115328 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or
   115329 ** unrecognized string argument.  The FULL and EXTRA option is disallowed
   115330 ** if the omitFull parameter it 1.
   115331 **
   115332 ** Note that the values returned are one less that the values that
   115333 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
   115334 ** to support legacy SQL code.  The safety level used to be boolean
   115335 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
   115336 */
   115337 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
   115338                              /* 123456789 123456789 123 */
   115339   static const char zText[] = "onoffalseyestruextrafull";
   115340   static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
   115341   static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
   115342   static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
   115343                             /* on no off false yes true extra full */
   115344   int i, n;
   115345   if( sqlite3Isdigit(*z) ){
   115346     return (u8)sqlite3Atoi(z);
   115347   }
   115348   n = sqlite3Strlen30(z);
   115349   for(i=0; i<ArraySize(iLength); i++){
   115350     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
   115351      && (!omitFull || iValue[i]<=1)
   115352     ){
   115353       return iValue[i];
   115354     }
   115355   }
   115356   return dflt;
   115357 }
   115358 
   115359 /*
   115360 ** Interpret the given string as a boolean value.
   115361 */
   115362 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
   115363   return getSafetyLevel(z,1,dflt)!=0;
   115364 }
   115365 
   115366 /* The sqlite3GetBoolean() function is used by other modules but the
   115367 ** remainder of this file is specific to PRAGMA processing.  So omit
   115368 ** the rest of the file if PRAGMAs are omitted from the build.
   115369 */
   115370 #if !defined(SQLITE_OMIT_PRAGMA)
   115371 
   115372 /*
   115373 ** Interpret the given string as a locking mode value.
   115374 */
   115375 static int getLockingMode(const char *z){
   115376   if( z ){
   115377     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
   115378     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
   115379   }
   115380   return PAGER_LOCKINGMODE_QUERY;
   115381 }
   115382 
   115383 #ifndef SQLITE_OMIT_AUTOVACUUM
   115384 /*
   115385 ** Interpret the given string as an auto-vacuum mode value.
   115386 **
   115387 ** The following strings, "none", "full" and "incremental" are
   115388 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
   115389 */
   115390 static int getAutoVacuum(const char *z){
   115391   int i;
   115392   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
   115393   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
   115394   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
   115395   i = sqlite3Atoi(z);
   115396   return (u8)((i>=0&&i<=2)?i:0);
   115397 }
   115398 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
   115399 
   115400 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   115401 /*
   115402 ** Interpret the given string as a temp db location. Return 1 for file
   115403 ** backed temporary databases, 2 for the Red-Black tree in memory database
   115404 ** and 0 to use the compile-time default.
   115405 */
   115406 static int getTempStore(const char *z){
   115407   if( z[0]>='0' && z[0]<='2' ){
   115408     return z[0] - '0';
   115409   }else if( sqlite3StrICmp(z, "file")==0 ){
   115410     return 1;
   115411   }else if( sqlite3StrICmp(z, "memory")==0 ){
   115412     return 2;
   115413   }else{
   115414     return 0;
   115415   }
   115416 }
   115417 #endif /* SQLITE_PAGER_PRAGMAS */
   115418 
   115419 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   115420 /*
   115421 ** Invalidate temp storage, either when the temp storage is changed
   115422 ** from default, or when 'file' and the temp_store_directory has changed
   115423 */
   115424 static int invalidateTempStorage(Parse *pParse){
   115425   sqlite3 *db = pParse->db;
   115426   if( db->aDb[1].pBt!=0 ){
   115427     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
   115428       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
   115429         "from within a transaction");
   115430       return SQLITE_ERROR;
   115431     }
   115432     sqlite3BtreeClose(db->aDb[1].pBt);
   115433     db->aDb[1].pBt = 0;
   115434     sqlite3ResetAllSchemasOfConnection(db);
   115435   }
   115436   return SQLITE_OK;
   115437 }
   115438 #endif /* SQLITE_PAGER_PRAGMAS */
   115439 
   115440 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   115441 /*
   115442 ** If the TEMP database is open, close it and mark the database schema
   115443 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
   115444 ** or DEFAULT_TEMP_STORE pragmas.
   115445 */
   115446 static int changeTempStorage(Parse *pParse, const char *zStorageType){
   115447   int ts = getTempStore(zStorageType);
   115448   sqlite3 *db = pParse->db;
   115449   if( db->temp_store==ts ) return SQLITE_OK;
   115450   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
   115451     return SQLITE_ERROR;
   115452   }
   115453   db->temp_store = (u8)ts;
   115454   return SQLITE_OK;
   115455 }
   115456 #endif /* SQLITE_PAGER_PRAGMAS */
   115457 
   115458 /*
   115459 ** Set result column names for a pragma.
   115460 */
   115461 static void setPragmaResultColumnNames(
   115462   Vdbe *v,                     /* The query under construction */
   115463   const PragmaName *pPragma    /* The pragma */
   115464 ){
   115465   u8 n = pPragma->nPragCName;
   115466   sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
   115467   if( n==0 ){
   115468     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
   115469   }else{
   115470     int i, j;
   115471     for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
   115472       sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
   115473     }
   115474   }
   115475 }
   115476 
   115477 /*
   115478 ** Generate code to return a single integer value.
   115479 */
   115480 static void returnSingleInt(Vdbe *v, i64 value){
   115481   sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
   115482   sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   115483 }
   115484 
   115485 /*
   115486 ** Generate code to return a single text value.
   115487 */
   115488 static void returnSingleText(
   115489   Vdbe *v,                /* Prepared statement under construction */
   115490   const char *zValue      /* Value to be returned */
   115491 ){
   115492   if( zValue ){
   115493     sqlite3VdbeLoadString(v, 1, (const char*)zValue);
   115494     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   115495   }
   115496 }
   115497 
   115498 
   115499 /*
   115500 ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
   115501 ** set these values for all pagers.
   115502 */
   115503 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   115504 static void setAllPagerFlags(sqlite3 *db){
   115505   if( db->autoCommit ){
   115506     Db *pDb = db->aDb;
   115507     int n = db->nDb;
   115508     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
   115509     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
   115510     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
   115511     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
   115512              ==  PAGER_FLAGS_MASK );
   115513     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
   115514     while( (n--) > 0 ){
   115515       if( pDb->pBt ){
   115516         sqlite3BtreeSetPagerFlags(pDb->pBt,
   115517                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
   115518       }
   115519       pDb++;
   115520     }
   115521   }
   115522 }
   115523 #else
   115524 # define setAllPagerFlags(X)  /* no-op */
   115525 #endif
   115526 
   115527 
   115528 /*
   115529 ** Return a human-readable name for a constraint resolution action.
   115530 */
   115531 #ifndef SQLITE_OMIT_FOREIGN_KEY
   115532 static const char *actionName(u8 action){
   115533   const char *zName;
   115534   switch( action ){
   115535     case OE_SetNull:  zName = "SET NULL";        break;
   115536     case OE_SetDflt:  zName = "SET DEFAULT";     break;
   115537     case OE_Cascade:  zName = "CASCADE";         break;
   115538     case OE_Restrict: zName = "RESTRICT";        break;
   115539     default:          zName = "NO ACTION";
   115540                       assert( action==OE_None ); break;
   115541   }
   115542   return zName;
   115543 }
   115544 #endif
   115545 
   115546 
   115547 /*
   115548 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
   115549 ** defined in pager.h. This function returns the associated lowercase
   115550 ** journal-mode name.
   115551 */
   115552 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
   115553   static char * const azModeName[] = {
   115554     "delete", "persist", "off", "truncate", "memory"
   115555 #ifndef SQLITE_OMIT_WAL
   115556      , "wal"
   115557 #endif
   115558   };
   115559   assert( PAGER_JOURNALMODE_DELETE==0 );
   115560   assert( PAGER_JOURNALMODE_PERSIST==1 );
   115561   assert( PAGER_JOURNALMODE_OFF==2 );
   115562   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
   115563   assert( PAGER_JOURNALMODE_MEMORY==4 );
   115564   assert( PAGER_JOURNALMODE_WAL==5 );
   115565   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
   115566 
   115567   if( eMode==ArraySize(azModeName) ) return 0;
   115568   return azModeName[eMode];
   115569 }
   115570 
   115571 /*
   115572 ** Locate a pragma in the aPragmaName[] array.
   115573 */
   115574 static const PragmaName *pragmaLocate(const char *zName){
   115575   int upr, lwr, mid = 0, rc;
   115576   lwr = 0;
   115577   upr = ArraySize(aPragmaName)-1;
   115578   while( lwr<=upr ){
   115579     mid = (lwr+upr)/2;
   115580     rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
   115581     if( rc==0 ) break;
   115582     if( rc<0 ){
   115583       upr = mid - 1;
   115584     }else{
   115585       lwr = mid + 1;
   115586     }
   115587   }
   115588   return lwr>upr ? 0 : &aPragmaName[mid];
   115589 }
   115590 
   115591 /*
   115592 ** Helper subroutine for PRAGMA integrity_check:
   115593 **
   115594 ** Generate code to output a single-column result row with a value of the
   115595 ** string held in register 3.  Decrement the result count in register 1
   115596 ** and halt if the maximum number of result rows have been issued.
   115597 */
   115598 static int integrityCheckResultRow(Vdbe *v){
   115599   int addr;
   115600   sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
   115601   addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
   115602   VdbeCoverage(v);
   115603   sqlite3VdbeAddOp0(v, OP_Halt);
   115604   return addr;
   115605 }
   115606 
   115607 /*
   115608 ** Process a pragma statement.
   115609 **
   115610 ** Pragmas are of this form:
   115611 **
   115612 **      PRAGMA [schema.]id [= value]
   115613 **
   115614 ** The identifier might also be a string.  The value is a string, and
   115615 ** identifier, or a number.  If minusFlag is true, then the value is
   115616 ** a number that was preceded by a minus sign.
   115617 **
   115618 ** If the left side is "database.id" then pId1 is the database name
   115619 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
   115620 ** id and pId2 is any empty string.
   115621 */
   115622 SQLITE_PRIVATE void sqlite3Pragma(
   115623   Parse *pParse,
   115624   Token *pId1,        /* First part of [schema.]id field */
   115625   Token *pId2,        /* Second part of [schema.]id field, or NULL */
   115626   Token *pValue,      /* Token for <value>, or NULL */
   115627   int minusFlag       /* True if a '-' sign preceded <value> */
   115628 ){
   115629   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
   115630   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
   115631   const char *zDb = 0;   /* The database name */
   115632   Token *pId;            /* Pointer to <id> token */
   115633   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
   115634   int iDb;               /* Database index for <database> */
   115635   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
   115636   sqlite3 *db = pParse->db;    /* The database connection */
   115637   Db *pDb;                     /* The specific database being pragmaed */
   115638   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
   115639   const PragmaName *pPragma;   /* The pragma */
   115640 
   115641   if( v==0 ) return;
   115642   sqlite3VdbeRunOnlyOnce(v);
   115643   pParse->nMem = 2;
   115644 
   115645   /* Interpret the [schema.] part of the pragma statement. iDb is the
   115646   ** index of the database this pragma is being applied to in db.aDb[]. */
   115647   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
   115648   if( iDb<0 ) return;
   115649   pDb = &db->aDb[iDb];
   115650 
   115651   /* If the temp database has been explicitly named as part of the
   115652   ** pragma, make sure it is open.
   115653   */
   115654   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
   115655     return;
   115656   }
   115657 
   115658   zLeft = sqlite3NameFromToken(db, pId);
   115659   if( !zLeft ) return;
   115660   if( minusFlag ){
   115661     zRight = sqlite3MPrintf(db, "-%T", pValue);
   115662   }else{
   115663     zRight = sqlite3NameFromToken(db, pValue);
   115664   }
   115665 
   115666   assert( pId2 );
   115667   zDb = pId2->n>0 ? pDb->zDbSName : 0;
   115668   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   115669     goto pragma_out;
   115670   }
   115671 
   115672   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
   115673   ** connection.  If it returns SQLITE_OK, then assume that the VFS
   115674   ** handled the pragma and generate a no-op prepared statement.
   115675   **
   115676   ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
   115677   ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
   115678   ** object corresponding to the database file to which the pragma
   115679   ** statement refers.
   115680   **
   115681   ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
   115682   ** file control is an array of pointers to strings (char**) in which the
   115683   ** second element of the array is the name of the pragma and the third
   115684   ** element is the argument to the pragma or NULL if the pragma has no
   115685   ** argument.
   115686   */
   115687   aFcntl[0] = 0;
   115688   aFcntl[1] = zLeft;
   115689   aFcntl[2] = zRight;
   115690   aFcntl[3] = 0;
   115691   db->busyHandler.nBusy = 0;
   115692   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
   115693   if( rc==SQLITE_OK ){
   115694     sqlite3VdbeSetNumCols(v, 1);
   115695     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
   115696     returnSingleText(v, aFcntl[0]);
   115697     sqlite3_free(aFcntl[0]);
   115698     goto pragma_out;
   115699   }
   115700   if( rc!=SQLITE_NOTFOUND ){
   115701     if( aFcntl[0] ){
   115702       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
   115703       sqlite3_free(aFcntl[0]);
   115704     }
   115705     pParse->nErr++;
   115706     pParse->rc = rc;
   115707     goto pragma_out;
   115708   }
   115709 
   115710   /* Locate the pragma in the lookup table */
   115711   pPragma = pragmaLocate(zLeft);
   115712   if( pPragma==0 ) goto pragma_out;
   115713 
   115714   /* Make sure the database schema is loaded if the pragma requires that */
   115715   if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
   115716     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   115717   }
   115718 
   115719   /* Register the result column names for pragmas that return results */
   115720   if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
   115721    && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
   115722   ){
   115723     setPragmaResultColumnNames(v, pPragma);
   115724   }
   115725 
   115726   /* Jump to the appropriate pragma handler */
   115727   switch( pPragma->ePragTyp ){
   115728 
   115729 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   115730   /*
   115731   **  PRAGMA [schema.]default_cache_size
   115732   **  PRAGMA [schema.]default_cache_size=N
   115733   **
   115734   ** The first form reports the current persistent setting for the
   115735   ** page cache size.  The value returned is the maximum number of
   115736   ** pages in the page cache.  The second form sets both the current
   115737   ** page cache size value and the persistent page cache size value
   115738   ** stored in the database file.
   115739   **
   115740   ** Older versions of SQLite would set the default cache size to a
   115741   ** negative number to indicate synchronous=OFF.  These days, synchronous
   115742   ** is always on by default regardless of the sign of the default cache
   115743   ** size.  But continue to take the absolute value of the default cache
   115744   ** size of historical compatibility.
   115745   */
   115746   case PragTyp_DEFAULT_CACHE_SIZE: {
   115747     static const int iLn = VDBE_OFFSET_LINENO(2);
   115748     static const VdbeOpList getCacheSize[] = {
   115749       { OP_Transaction, 0, 0,        0},                         /* 0 */
   115750       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   115751       { OP_IfPos,       1, 8,        0},
   115752       { OP_Integer,     0, 2,        0},
   115753       { OP_Subtract,    1, 2,        1},
   115754       { OP_IfPos,       1, 8,        0},
   115755       { OP_Integer,     0, 1,        0},                         /* 6 */
   115756       { OP_Noop,        0, 0,        0},
   115757       { OP_ResultRow,   1, 1,        0},
   115758     };
   115759     VdbeOp *aOp;
   115760     sqlite3VdbeUsesBtree(v, iDb);
   115761     if( !zRight ){
   115762       pParse->nMem += 2;
   115763       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
   115764       aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
   115765       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
   115766       aOp[0].p1 = iDb;
   115767       aOp[1].p1 = iDb;
   115768       aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
   115769     }else{
   115770       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
   115771       sqlite3BeginWriteOperation(pParse, 0, iDb);
   115772       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
   115773       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   115774       pDb->pSchema->cache_size = size;
   115775       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   115776     }
   115777     break;
   115778   }
   115779 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
   115780 
   115781 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   115782   /*
   115783   **  PRAGMA [schema.]page_size
   115784   **  PRAGMA [schema.]page_size=N
   115785   **
   115786   ** The first form reports the current setting for the
   115787   ** database page size in bytes.  The second form sets the
   115788   ** database page size value.  The value can only be set if
   115789   ** the database has not yet been created.
   115790   */
   115791   case PragTyp_PAGE_SIZE: {
   115792     Btree *pBt = pDb->pBt;
   115793     assert( pBt!=0 );
   115794     if( !zRight ){
   115795       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   115796       returnSingleInt(v, size);
   115797     }else{
   115798       /* Malloc may fail when setting the page-size, as there is an internal
   115799       ** buffer that the pager module resizes using sqlite3_realloc().
   115800       */
   115801       db->nextPagesize = sqlite3Atoi(zRight);
   115802       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
   115803         sqlite3OomFault(db);
   115804       }
   115805     }
   115806     break;
   115807   }
   115808 
   115809   /*
   115810   **  PRAGMA [schema.]secure_delete
   115811   **  PRAGMA [schema.]secure_delete=ON/OFF/FAST
   115812   **
   115813   ** The first form reports the current setting for the
   115814   ** secure_delete flag.  The second form changes the secure_delete
   115815   ** flag setting and reports the new value.
   115816   */
   115817   case PragTyp_SECURE_DELETE: {
   115818     Btree *pBt = pDb->pBt;
   115819     int b = -1;
   115820     assert( pBt!=0 );
   115821     if( zRight ){
   115822       if( sqlite3_stricmp(zRight, "fast")==0 ){
   115823         b = 2;
   115824       }else{
   115825         b = sqlite3GetBoolean(zRight, 0);
   115826       }
   115827     }
   115828     if( pId2->n==0 && b>=0 ){
   115829       int ii;
   115830       for(ii=0; ii<db->nDb; ii++){
   115831         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
   115832       }
   115833     }
   115834     b = sqlite3BtreeSecureDelete(pBt, b);
   115835     returnSingleInt(v, b);
   115836     break;
   115837   }
   115838 
   115839   /*
   115840   **  PRAGMA [schema.]max_page_count
   115841   **  PRAGMA [schema.]max_page_count=N
   115842   **
   115843   ** The first form reports the current setting for the
   115844   ** maximum number of pages in the database file.  The
   115845   ** second form attempts to change this setting.  Both
   115846   ** forms return the current setting.
   115847   **
   115848   ** The absolute value of N is used.  This is undocumented and might
   115849   ** change.  The only purpose is to provide an easy way to test
   115850   ** the sqlite3AbsInt32() function.
   115851   **
   115852   **  PRAGMA [schema.]page_count
   115853   **
   115854   ** Return the number of pages in the specified database.
   115855   */
   115856   case PragTyp_PAGE_COUNT: {
   115857     int iReg;
   115858     sqlite3CodeVerifySchema(pParse, iDb);
   115859     iReg = ++pParse->nMem;
   115860     if( sqlite3Tolower(zLeft[0])=='p' ){
   115861       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   115862     }else{
   115863       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
   115864                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
   115865     }
   115866     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   115867     break;
   115868   }
   115869 
   115870   /*
   115871   **  PRAGMA [schema.]locking_mode
   115872   **  PRAGMA [schema.]locking_mode = (normal|exclusive)
   115873   */
   115874   case PragTyp_LOCKING_MODE: {
   115875     const char *zRet = "normal";
   115876     int eMode = getLockingMode(zRight);
   115877 
   115878     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
   115879       /* Simple "PRAGMA locking_mode;" statement. This is a query for
   115880       ** the current default locking mode (which may be different to
   115881       ** the locking-mode of the main database).
   115882       */
   115883       eMode = db->dfltLockMode;
   115884     }else{
   115885       Pager *pPager;
   115886       if( pId2->n==0 ){
   115887         /* This indicates that no database name was specified as part
   115888         ** of the PRAGMA command. In this case the locking-mode must be
   115889         ** set on all attached databases, as well as the main db file.
   115890         **
   115891         ** Also, the sqlite3.dfltLockMode variable is set so that
   115892         ** any subsequently attached databases also use the specified
   115893         ** locking mode.
   115894         */
   115895         int ii;
   115896         assert(pDb==&db->aDb[0]);
   115897         for(ii=2; ii<db->nDb; ii++){
   115898           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   115899           sqlite3PagerLockingMode(pPager, eMode);
   115900         }
   115901         db->dfltLockMode = (u8)eMode;
   115902       }
   115903       pPager = sqlite3BtreePager(pDb->pBt);
   115904       eMode = sqlite3PagerLockingMode(pPager, eMode);
   115905     }
   115906 
   115907     assert( eMode==PAGER_LOCKINGMODE_NORMAL
   115908             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   115909     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
   115910       zRet = "exclusive";
   115911     }
   115912     returnSingleText(v, zRet);
   115913     break;
   115914   }
   115915 
   115916   /*
   115917   **  PRAGMA [schema.]journal_mode
   115918   **  PRAGMA [schema.]journal_mode =
   115919   **                      (delete|persist|off|truncate|memory|wal|off)
   115920   */
   115921   case PragTyp_JOURNAL_MODE: {
   115922     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
   115923     int ii;           /* Loop counter */
   115924 
   115925     if( zRight==0 ){
   115926       /* If there is no "=MODE" part of the pragma, do a query for the
   115927       ** current mode */
   115928       eMode = PAGER_JOURNALMODE_QUERY;
   115929     }else{
   115930       const char *zMode;
   115931       int n = sqlite3Strlen30(zRight);
   115932       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
   115933         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
   115934       }
   115935       if( !zMode ){
   115936         /* If the "=MODE" part does not match any known journal mode,
   115937         ** then do a query */
   115938         eMode = PAGER_JOURNALMODE_QUERY;
   115939       }
   115940     }
   115941     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
   115942       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
   115943       iDb = 0;
   115944       pId2->n = 1;
   115945     }
   115946     for(ii=db->nDb-1; ii>=0; ii--){
   115947       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   115948         sqlite3VdbeUsesBtree(v, ii);
   115949         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
   115950       }
   115951     }
   115952     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   115953     break;
   115954   }
   115955 
   115956   /*
   115957   **  PRAGMA [schema.]journal_size_limit
   115958   **  PRAGMA [schema.]journal_size_limit=N
   115959   **
   115960   ** Get or set the size limit on rollback journal files.
   115961   */
   115962   case PragTyp_JOURNAL_SIZE_LIMIT: {
   115963     Pager *pPager = sqlite3BtreePager(pDb->pBt);
   115964     i64 iLimit = -2;
   115965     if( zRight ){
   115966       sqlite3DecOrHexToI64(zRight, &iLimit);
   115967       if( iLimit<-1 ) iLimit = -1;
   115968     }
   115969     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
   115970     returnSingleInt(v, iLimit);
   115971     break;
   115972   }
   115973 
   115974 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   115975 
   115976   /*
   115977   **  PRAGMA [schema.]auto_vacuum
   115978   **  PRAGMA [schema.]auto_vacuum=N
   115979   **
   115980   ** Get or set the value of the database 'auto-vacuum' parameter.
   115981   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
   115982   */
   115983 #ifndef SQLITE_OMIT_AUTOVACUUM
   115984   case PragTyp_AUTO_VACUUM: {
   115985     Btree *pBt = pDb->pBt;
   115986     assert( pBt!=0 );
   115987     if( !zRight ){
   115988       returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
   115989     }else{
   115990       int eAuto = getAutoVacuum(zRight);
   115991       assert( eAuto>=0 && eAuto<=2 );
   115992       db->nextAutovac = (u8)eAuto;
   115993       /* Call SetAutoVacuum() to set initialize the internal auto and
   115994       ** incr-vacuum flags. This is required in case this connection
   115995       ** creates the database file. It is important that it is created
   115996       ** as an auto-vacuum capable db.
   115997       */
   115998       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
   115999       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
   116000         /* When setting the auto_vacuum mode to either "full" or
   116001         ** "incremental", write the value of meta[6] in the database
   116002         ** file. Before writing to meta[6], check that meta[3] indicates
   116003         ** that this really is an auto-vacuum capable database.
   116004         */
   116005         static const int iLn = VDBE_OFFSET_LINENO(2);
   116006         static const VdbeOpList setMeta6[] = {
   116007           { OP_Transaction,    0,         1,                 0},    /* 0 */
   116008           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
   116009           { OP_If,             1,         0,                 0},    /* 2 */
   116010           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
   116011           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
   116012         };
   116013         VdbeOp *aOp;
   116014         int iAddr = sqlite3VdbeCurrentAddr(v);
   116015         sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
   116016         aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
   116017         if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
   116018         aOp[0].p1 = iDb;
   116019         aOp[1].p1 = iDb;
   116020         aOp[2].p2 = iAddr+4;
   116021         aOp[4].p1 = iDb;
   116022         aOp[4].p3 = eAuto - 1;
   116023         sqlite3VdbeUsesBtree(v, iDb);
   116024       }
   116025     }
   116026     break;
   116027   }
   116028 #endif
   116029 
   116030   /*
   116031   **  PRAGMA [schema.]incremental_vacuum(N)
   116032   **
   116033   ** Do N steps of incremental vacuuming on a database.
   116034   */
   116035 #ifndef SQLITE_OMIT_AUTOVACUUM
   116036   case PragTyp_INCREMENTAL_VACUUM: {
   116037     int iLimit, addr;
   116038     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
   116039       iLimit = 0x7fffffff;
   116040     }
   116041     sqlite3BeginWriteOperation(pParse, 0, iDb);
   116042     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
   116043     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
   116044     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
   116045     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   116046     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
   116047     sqlite3VdbeJumpHere(v, addr);
   116048     break;
   116049   }
   116050 #endif
   116051 
   116052 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   116053   /*
   116054   **  PRAGMA [schema.]cache_size
   116055   **  PRAGMA [schema.]cache_size=N
   116056   **
   116057   ** The first form reports the current local setting for the
   116058   ** page cache size. The second form sets the local
   116059   ** page cache size value.  If N is positive then that is the
   116060   ** number of pages in the cache.  If N is negative, then the
   116061   ** number of pages is adjusted so that the cache uses -N kibibytes
   116062   ** of memory.
   116063   */
   116064   case PragTyp_CACHE_SIZE: {
   116065     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   116066     if( !zRight ){
   116067       returnSingleInt(v, pDb->pSchema->cache_size);
   116068     }else{
   116069       int size = sqlite3Atoi(zRight);
   116070       pDb->pSchema->cache_size = size;
   116071       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   116072     }
   116073     break;
   116074   }
   116075 
   116076   /*
   116077   **  PRAGMA [schema.]cache_spill
   116078   **  PRAGMA cache_spill=BOOLEAN
   116079   **  PRAGMA [schema.]cache_spill=N
   116080   **
   116081   ** The first form reports the current local setting for the
   116082   ** page cache spill size. The second form turns cache spill on
   116083   ** or off.  When turnning cache spill on, the size is set to the
   116084   ** current cache_size.  The third form sets a spill size that
   116085   ** may be different form the cache size.
   116086   ** If N is positive then that is the
   116087   ** number of pages in the cache.  If N is negative, then the
   116088   ** number of pages is adjusted so that the cache uses -N kibibytes
   116089   ** of memory.
   116090   **
   116091   ** If the number of cache_spill pages is less then the number of
   116092   ** cache_size pages, no spilling occurs until the page count exceeds
   116093   ** the number of cache_size pages.
   116094   **
   116095   ** The cache_spill=BOOLEAN setting applies to all attached schemas,
   116096   ** not just the schema specified.
   116097   */
   116098   case PragTyp_CACHE_SPILL: {
   116099     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   116100     if( !zRight ){
   116101       returnSingleInt(v,
   116102          (db->flags & SQLITE_CacheSpill)==0 ? 0 :
   116103             sqlite3BtreeSetSpillSize(pDb->pBt,0));
   116104     }else{
   116105       int size = 1;
   116106       if( sqlite3GetInt32(zRight, &size) ){
   116107         sqlite3BtreeSetSpillSize(pDb->pBt, size);
   116108       }
   116109       if( sqlite3GetBoolean(zRight, size!=0) ){
   116110         db->flags |= SQLITE_CacheSpill;
   116111       }else{
   116112         db->flags &= ~SQLITE_CacheSpill;
   116113       }
   116114       setAllPagerFlags(db);
   116115     }
   116116     break;
   116117   }
   116118 
   116119   /*
   116120   **  PRAGMA [schema.]mmap_size(N)
   116121   **
   116122   ** Used to set mapping size limit. The mapping size limit is
   116123   ** used to limit the aggregate size of all memory mapped regions of the
   116124   ** database file. If this parameter is set to zero, then memory mapping
   116125   ** is not used at all.  If N is negative, then the default memory map
   116126   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
   116127   ** The parameter N is measured in bytes.
   116128   **
   116129   ** This value is advisory.  The underlying VFS is free to memory map
   116130   ** as little or as much as it wants.  Except, if N is set to 0 then the
   116131   ** upper layers will never invoke the xFetch interfaces to the VFS.
   116132   */
   116133   case PragTyp_MMAP_SIZE: {
   116134     sqlite3_int64 sz;
   116135 #if SQLITE_MAX_MMAP_SIZE>0
   116136     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   116137     if( zRight ){
   116138       int ii;
   116139       sqlite3DecOrHexToI64(zRight, &sz);
   116140       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
   116141       if( pId2->n==0 ) db->szMmap = sz;
   116142       for(ii=db->nDb-1; ii>=0; ii--){
   116143         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   116144           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
   116145         }
   116146       }
   116147     }
   116148     sz = -1;
   116149     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
   116150 #else
   116151     sz = 0;
   116152     rc = SQLITE_OK;
   116153 #endif
   116154     if( rc==SQLITE_OK ){
   116155       returnSingleInt(v, sz);
   116156     }else if( rc!=SQLITE_NOTFOUND ){
   116157       pParse->nErr++;
   116158       pParse->rc = rc;
   116159     }
   116160     break;
   116161   }
   116162 
   116163   /*
   116164   **   PRAGMA temp_store
   116165   **   PRAGMA temp_store = "default"|"memory"|"file"
   116166   **
   116167   ** Return or set the local value of the temp_store flag.  Changing
   116168   ** the local value does not make changes to the disk file and the default
   116169   ** value will be restored the next time the database is opened.
   116170   **
   116171   ** Note that it is possible for the library compile-time options to
   116172   ** override this setting
   116173   */
   116174   case PragTyp_TEMP_STORE: {
   116175     if( !zRight ){
   116176       returnSingleInt(v, db->temp_store);
   116177     }else{
   116178       changeTempStorage(pParse, zRight);
   116179     }
   116180     break;
   116181   }
   116182 
   116183   /*
   116184   **   PRAGMA temp_store_directory
   116185   **   PRAGMA temp_store_directory = ""|"directory_name"
   116186   **
   116187   ** Return or set the local value of the temp_store_directory flag.  Changing
   116188   ** the value sets a specific directory to be used for temporary files.
   116189   ** Setting to a null string reverts to the default temporary directory search.
   116190   ** If temporary directory is changed, then invalidateTempStorage.
   116191   **
   116192   */
   116193   case PragTyp_TEMP_STORE_DIRECTORY: {
   116194     if( !zRight ){
   116195       returnSingleText(v, sqlite3_temp_directory);
   116196     }else{
   116197 #ifndef SQLITE_OMIT_WSD
   116198       if( zRight[0] ){
   116199         int res;
   116200         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   116201         if( rc!=SQLITE_OK || res==0 ){
   116202           sqlite3ErrorMsg(pParse, "not a writable directory");
   116203           goto pragma_out;
   116204         }
   116205       }
   116206       if( SQLITE_TEMP_STORE==0
   116207        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
   116208        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
   116209       ){
   116210         invalidateTempStorage(pParse);
   116211       }
   116212       sqlite3_free(sqlite3_temp_directory);
   116213       if( zRight[0] ){
   116214         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
   116215       }else{
   116216         sqlite3_temp_directory = 0;
   116217       }
   116218 #endif /* SQLITE_OMIT_WSD */
   116219     }
   116220     break;
   116221   }
   116222 
   116223 #if SQLITE_OS_WIN
   116224   /*
   116225   **   PRAGMA data_store_directory
   116226   **   PRAGMA data_store_directory = ""|"directory_name"
   116227   **
   116228   ** Return or set the local value of the data_store_directory flag.  Changing
   116229   ** the value sets a specific directory to be used for database files that
   116230   ** were specified with a relative pathname.  Setting to a null string reverts
   116231   ** to the default database directory, which for database files specified with
   116232   ** a relative path will probably be based on the current directory for the
   116233   ** process.  Database file specified with an absolute path are not impacted
   116234   ** by this setting, regardless of its value.
   116235   **
   116236   */
   116237   case PragTyp_DATA_STORE_DIRECTORY: {
   116238     if( !zRight ){
   116239       returnSingleText(v, sqlite3_data_directory);
   116240     }else{
   116241 #ifndef SQLITE_OMIT_WSD
   116242       if( zRight[0] ){
   116243         int res;
   116244         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   116245         if( rc!=SQLITE_OK || res==0 ){
   116246           sqlite3ErrorMsg(pParse, "not a writable directory");
   116247           goto pragma_out;
   116248         }
   116249       }
   116250       sqlite3_free(sqlite3_data_directory);
   116251       if( zRight[0] ){
   116252         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
   116253       }else{
   116254         sqlite3_data_directory = 0;
   116255       }
   116256 #endif /* SQLITE_OMIT_WSD */
   116257     }
   116258     break;
   116259   }
   116260 #endif
   116261 
   116262 #if SQLITE_ENABLE_LOCKING_STYLE
   116263   /*
   116264   **   PRAGMA [schema.]lock_proxy_file
   116265   **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
   116266   **
   116267   ** Return or set the value of the lock_proxy_file flag.  Changing
   116268   ** the value sets a specific file to be used for database access locks.
   116269   **
   116270   */
   116271   case PragTyp_LOCK_PROXY_FILE: {
   116272     if( !zRight ){
   116273       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   116274       char *proxy_file_path = NULL;
   116275       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   116276       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
   116277                            &proxy_file_path);
   116278       returnSingleText(v, proxy_file_path);
   116279     }else{
   116280       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   116281       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   116282       int res;
   116283       if( zRight[0] ){
   116284         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   116285                                      zRight);
   116286       } else {
   116287         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   116288                                      NULL);
   116289       }
   116290       if( res!=SQLITE_OK ){
   116291         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
   116292         goto pragma_out;
   116293       }
   116294     }
   116295     break;
   116296   }
   116297 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   116298 
   116299   /*
   116300   **   PRAGMA [schema.]synchronous
   116301   **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
   116302   **
   116303   ** Return or set the local value of the synchronous flag.  Changing
   116304   ** the local value does not make changes to the disk file and the
   116305   ** default value will be restored the next time the database is
   116306   ** opened.
   116307   */
   116308   case PragTyp_SYNCHRONOUS: {
   116309     if( !zRight ){
   116310       returnSingleInt(v, pDb->safety_level-1);
   116311     }else{
   116312       if( !db->autoCommit ){
   116313         sqlite3ErrorMsg(pParse,
   116314             "Safety level may not be changed inside a transaction");
   116315       }else if( iDb!=1 ){
   116316         int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
   116317         if( iLevel==0 ) iLevel = 1;
   116318         pDb->safety_level = iLevel;
   116319         pDb->bSyncSet = 1;
   116320         setAllPagerFlags(db);
   116321       }
   116322     }
   116323     break;
   116324   }
   116325 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   116326 
   116327 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   116328   case PragTyp_FLAG: {
   116329     if( zRight==0 ){
   116330       setPragmaResultColumnNames(v, pPragma);
   116331       returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
   116332     }else{
   116333       int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
   116334       if( db->autoCommit==0 ){
   116335         /* Foreign key support may not be enabled or disabled while not
   116336         ** in auto-commit mode.  */
   116337         mask &= ~(SQLITE_ForeignKeys);
   116338       }
   116339 #if SQLITE_USER_AUTHENTICATION
   116340       if( db->auth.authLevel==UAUTH_User ){
   116341         /* Do not allow non-admin users to modify the schema arbitrarily */
   116342         mask &= ~(SQLITE_WriteSchema);
   116343       }
   116344 #endif
   116345 
   116346       if( sqlite3GetBoolean(zRight, 0) ){
   116347         db->flags |= mask;
   116348       }else{
   116349         db->flags &= ~mask;
   116350         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
   116351       }
   116352 
   116353       /* Many of the flag-pragmas modify the code generated by the SQL
   116354       ** compiler (eg. count_changes). So add an opcode to expire all
   116355       ** compiled SQL statements after modifying a pragma value.
   116356       */
   116357       sqlite3VdbeAddOp0(v, OP_Expire);
   116358       setAllPagerFlags(db);
   116359     }
   116360     break;
   116361   }
   116362 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   116363 
   116364 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
   116365   /*
   116366   **   PRAGMA table_info(<table>)
   116367   **
   116368   ** Return a single row for each column of the named table. The columns of
   116369   ** the returned data set are:
   116370   **
   116371   ** cid:        Column id (numbered from left to right, starting at 0)
   116372   ** name:       Column name
   116373   ** type:       Column declaration type.
   116374   ** notnull:    True if 'NOT NULL' is part of column declaration
   116375   ** dflt_value: The default value for the column, if any.
   116376   ** pk:         Non-zero for PK fields.
   116377   */
   116378   case PragTyp_TABLE_INFO: if( zRight ){
   116379     Table *pTab;
   116380     pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
   116381     if( pTab ){
   116382       int i, k;
   116383       int nHidden = 0;
   116384       Column *pCol;
   116385       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   116386       pParse->nMem = 6;
   116387       sqlite3CodeVerifySchema(pParse, iDb);
   116388       sqlite3ViewGetColumnNames(pParse, pTab);
   116389       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   116390         if( IsHiddenColumn(pCol) ){
   116391           nHidden++;
   116392           continue;
   116393         }
   116394         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
   116395           k = 0;
   116396         }else if( pPk==0 ){
   116397           k = 1;
   116398         }else{
   116399           for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
   116400         }
   116401         assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
   116402         sqlite3VdbeMultiLoad(v, 1, "issisi",
   116403                i-nHidden,
   116404                pCol->zName,
   116405                sqlite3ColumnType(pCol,""),
   116406                pCol->notNull ? 1 : 0,
   116407                pCol->pDflt ? pCol->pDflt->u.zToken : 0,
   116408                k);
   116409       }
   116410     }
   116411   }
   116412   break;
   116413 
   116414 #ifdef SQLITE_DEBUG
   116415   case PragTyp_STATS: {
   116416     Index *pIdx;
   116417     HashElem *i;
   116418     pParse->nMem = 5;
   116419     sqlite3CodeVerifySchema(pParse, iDb);
   116420     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
   116421       Table *pTab = sqliteHashData(i);
   116422       sqlite3VdbeMultiLoad(v, 1, "ssiii",
   116423            pTab->zName,
   116424            0,
   116425            pTab->szTabRow,
   116426            pTab->nRowLogEst,
   116427            pTab->tabFlags);
   116428       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   116429         sqlite3VdbeMultiLoad(v, 2, "siiiX",
   116430            pIdx->zName,
   116431            pIdx->szIdxRow,
   116432            pIdx->aiRowLogEst[0],
   116433            pIdx->hasStat1);
   116434         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
   116435       }
   116436     }
   116437   }
   116438   break;
   116439 #endif
   116440 
   116441   case PragTyp_INDEX_INFO: if( zRight ){
   116442     Index *pIdx;
   116443     Table *pTab;
   116444     pIdx = sqlite3FindIndex(db, zRight, zDb);
   116445     if( pIdx ){
   116446       int i;
   116447       int mx;
   116448       if( pPragma->iArg ){
   116449         /* PRAGMA index_xinfo (newer version with more rows and columns) */
   116450         mx = pIdx->nColumn;
   116451         pParse->nMem = 6;
   116452       }else{
   116453         /* PRAGMA index_info (legacy version) */
   116454         mx = pIdx->nKeyCol;
   116455         pParse->nMem = 3;
   116456       }
   116457       pTab = pIdx->pTable;
   116458       sqlite3CodeVerifySchema(pParse, iDb);
   116459       assert( pParse->nMem<=pPragma->nPragCName );
   116460       for(i=0; i<mx; i++){
   116461         i16 cnum = pIdx->aiColumn[i];
   116462         sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
   116463                              cnum<0 ? 0 : pTab->aCol[cnum].zName);
   116464         if( pPragma->iArg ){
   116465           sqlite3VdbeMultiLoad(v, 4, "isiX",
   116466             pIdx->aSortOrder[i],
   116467             pIdx->azColl[i],
   116468             i<pIdx->nKeyCol);
   116469         }
   116470         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
   116471       }
   116472     }
   116473   }
   116474   break;
   116475 
   116476   case PragTyp_INDEX_LIST: if( zRight ){
   116477     Index *pIdx;
   116478     Table *pTab;
   116479     int i;
   116480     pTab = sqlite3FindTable(db, zRight, zDb);
   116481     if( pTab ){
   116482       pParse->nMem = 5;
   116483       sqlite3CodeVerifySchema(pParse, iDb);
   116484       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
   116485         const char *azOrigin[] = { "c", "u", "pk" };
   116486         sqlite3VdbeMultiLoad(v, 1, "isisi",
   116487            i,
   116488            pIdx->zName,
   116489            IsUniqueIndex(pIdx),
   116490            azOrigin[pIdx->idxType],
   116491            pIdx->pPartIdxWhere!=0);
   116492       }
   116493     }
   116494   }
   116495   break;
   116496 
   116497   case PragTyp_DATABASE_LIST: {
   116498     int i;
   116499     pParse->nMem = 3;
   116500     for(i=0; i<db->nDb; i++){
   116501       if( db->aDb[i].pBt==0 ) continue;
   116502       assert( db->aDb[i].zDbSName!=0 );
   116503       sqlite3VdbeMultiLoad(v, 1, "iss",
   116504          i,
   116505          db->aDb[i].zDbSName,
   116506          sqlite3BtreeGetFilename(db->aDb[i].pBt));
   116507     }
   116508   }
   116509   break;
   116510 
   116511   case PragTyp_COLLATION_LIST: {
   116512     int i = 0;
   116513     HashElem *p;
   116514     pParse->nMem = 2;
   116515     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
   116516       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
   116517       sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
   116518     }
   116519   }
   116520   break;
   116521 
   116522 #ifdef SQLITE_INTROSPECTION_PRAGMAS
   116523   case PragTyp_FUNCTION_LIST: {
   116524     int i;
   116525     HashElem *j;
   116526     FuncDef *p;
   116527     pParse->nMem = 2;
   116528     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
   116529       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
   116530         sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
   116531       }
   116532     }
   116533     for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
   116534       p = (FuncDef*)sqliteHashData(j);
   116535       sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
   116536     }
   116537   }
   116538   break;
   116539 
   116540 #ifndef SQLITE_OMIT_VIRTUALTABLE
   116541   case PragTyp_MODULE_LIST: {
   116542     HashElem *j;
   116543     pParse->nMem = 1;
   116544     for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
   116545       Module *pMod = (Module*)sqliteHashData(j);
   116546       sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
   116547     }
   116548   }
   116549   break;
   116550 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   116551 
   116552   case PragTyp_PRAGMA_LIST: {
   116553     int i;
   116554     for(i=0; i<ArraySize(aPragmaName); i++){
   116555       sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
   116556     }
   116557   }
   116558   break;
   116559 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
   116560 
   116561 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
   116562 
   116563 #ifndef SQLITE_OMIT_FOREIGN_KEY
   116564   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
   116565     FKey *pFK;
   116566     Table *pTab;
   116567     pTab = sqlite3FindTable(db, zRight, zDb);
   116568     if( pTab ){
   116569       pFK = pTab->pFKey;
   116570       if( pFK ){
   116571         int i = 0;
   116572         pParse->nMem = 8;
   116573         sqlite3CodeVerifySchema(pParse, iDb);
   116574         while(pFK){
   116575           int j;
   116576           for(j=0; j<pFK->nCol; j++){
   116577             sqlite3VdbeMultiLoad(v, 1, "iissssss",
   116578                    i,
   116579                    j,
   116580                    pFK->zTo,
   116581                    pTab->aCol[pFK->aCol[j].iFrom].zName,
   116582                    pFK->aCol[j].zCol,
   116583                    actionName(pFK->aAction[1]),  /* ON UPDATE */
   116584                    actionName(pFK->aAction[0]),  /* ON DELETE */
   116585                    "NONE");
   116586           }
   116587           ++i;
   116588           pFK = pFK->pNextFrom;
   116589         }
   116590       }
   116591     }
   116592   }
   116593   break;
   116594 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   116595 
   116596 #ifndef SQLITE_OMIT_FOREIGN_KEY
   116597 #ifndef SQLITE_OMIT_TRIGGER
   116598   case PragTyp_FOREIGN_KEY_CHECK: {
   116599     FKey *pFK;             /* A foreign key constraint */
   116600     Table *pTab;           /* Child table contain "REFERENCES" keyword */
   116601     Table *pParent;        /* Parent table that child points to */
   116602     Index *pIdx;           /* Index in the parent table */
   116603     int i;                 /* Loop counter:  Foreign key number for pTab */
   116604     int j;                 /* Loop counter:  Field of the foreign key */
   116605     HashElem *k;           /* Loop counter:  Next table in schema */
   116606     int x;                 /* result variable */
   116607     int regResult;         /* 3 registers to hold a result row */
   116608     int regKey;            /* Register to hold key for checking the FK */
   116609     int regRow;            /* Registers to hold a row from pTab */
   116610     int addrTop;           /* Top of a loop checking foreign keys */
   116611     int addrOk;            /* Jump here if the key is OK */
   116612     int *aiCols;           /* child to parent column mapping */
   116613 
   116614     regResult = pParse->nMem+1;
   116615     pParse->nMem += 4;
   116616     regKey = ++pParse->nMem;
   116617     regRow = ++pParse->nMem;
   116618     sqlite3CodeVerifySchema(pParse, iDb);
   116619     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
   116620     while( k ){
   116621       if( zRight ){
   116622         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
   116623         k = 0;
   116624       }else{
   116625         pTab = (Table*)sqliteHashData(k);
   116626         k = sqliteHashNext(k);
   116627       }
   116628       if( pTab==0 || pTab->pFKey==0 ) continue;
   116629       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   116630       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
   116631       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
   116632       sqlite3VdbeLoadString(v, regResult, pTab->zName);
   116633       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
   116634         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
   116635         if( pParent==0 ) continue;
   116636         pIdx = 0;
   116637         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
   116638         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
   116639         if( x==0 ){
   116640           if( pIdx==0 ){
   116641             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
   116642           }else{
   116643             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
   116644             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   116645           }
   116646         }else{
   116647           k = 0;
   116648           break;
   116649         }
   116650       }
   116651       assert( pParse->nErr>0 || pFK==0 );
   116652       if( pFK ) break;
   116653       if( pParse->nTab<i ) pParse->nTab = i;
   116654       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
   116655       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
   116656         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
   116657         pIdx = 0;
   116658         aiCols = 0;
   116659         if( pParent ){
   116660           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
   116661           assert( x==0 );
   116662         }
   116663         addrOk = sqlite3VdbeMakeLabel(v);
   116664 
   116665         /* Generate code to read the child key values into registers
   116666         ** regRow..regRow+n. If any of the child key values are NULL, this
   116667         ** row cannot cause an FK violation. Jump directly to addrOk in
   116668         ** this case. */
   116669         for(j=0; j<pFK->nCol; j++){
   116670           int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
   116671           sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
   116672           sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
   116673         }
   116674 
   116675         /* Generate code to query the parent index for a matching parent
   116676         ** key. If a match is found, jump to addrOk. */
   116677         if( pIdx ){
   116678           sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
   116679               sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
   116680           sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
   116681           VdbeCoverage(v);
   116682         }else if( pParent ){
   116683           int jmp = sqlite3VdbeCurrentAddr(v)+2;
   116684           sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
   116685           sqlite3VdbeGoto(v, addrOk);
   116686           assert( pFK->nCol==1 );
   116687         }
   116688 
   116689         /* Generate code to report an FK violation to the caller. */
   116690         if( HasRowid(pTab) ){
   116691           sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
   116692         }else{
   116693           sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
   116694         }
   116695         sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
   116696         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
   116697         sqlite3VdbeResolveLabel(v, addrOk);
   116698         sqlite3DbFree(db, aiCols);
   116699       }
   116700       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
   116701       sqlite3VdbeJumpHere(v, addrTop);
   116702     }
   116703   }
   116704   break;
   116705 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   116706 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   116707 
   116708 #ifndef NDEBUG
   116709   case PragTyp_PARSER_TRACE: {
   116710     if( zRight ){
   116711       if( sqlite3GetBoolean(zRight, 0) ){
   116712         sqlite3ParserTrace(stdout, "parser: ");
   116713       }else{
   116714         sqlite3ParserTrace(0, 0);
   116715       }
   116716     }
   116717   }
   116718   break;
   116719 #endif
   116720 
   116721   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
   116722   ** used will be case sensitive or not depending on the RHS.
   116723   */
   116724   case PragTyp_CASE_SENSITIVE_LIKE: {
   116725     if( zRight ){
   116726       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
   116727     }
   116728   }
   116729   break;
   116730 
   116731 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   116732 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
   116733 #endif
   116734 
   116735 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   116736   /*    PRAGMA integrity_check
   116737   **    PRAGMA integrity_check(N)
   116738   **    PRAGMA quick_check
   116739   **    PRAGMA quick_check(N)
   116740   **
   116741   ** Verify the integrity of the database.
   116742   **
   116743   ** The "quick_check" is reduced version of
   116744   ** integrity_check designed to detect most database corruption
   116745   ** without the overhead of cross-checking indexes.  Quick_check
   116746   ** is linear time wherease integrity_check is O(NlogN).
   116747   */
   116748   case PragTyp_INTEGRITY_CHECK: {
   116749     int i, j, addr, mxErr;
   116750 
   116751     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
   116752 
   116753     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
   116754     ** then iDb is set to the index of the database identified by <db>.
   116755     ** In this case, the integrity of database iDb only is verified by
   116756     ** the VDBE created below.
   116757     **
   116758     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
   116759     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
   116760     ** to -1 here, to indicate that the VDBE should verify the integrity
   116761     ** of all attached databases.  */
   116762     assert( iDb>=0 );
   116763     assert( iDb==0 || pId2->z );
   116764     if( pId2->z==0 ) iDb = -1;
   116765 
   116766     /* Initialize the VDBE program */
   116767     pParse->nMem = 6;
   116768 
   116769     /* Set the maximum error count */
   116770     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   116771     if( zRight ){
   116772       sqlite3GetInt32(zRight, &mxErr);
   116773       if( mxErr<=0 ){
   116774         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   116775       }
   116776     }
   116777     sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
   116778 
   116779     /* Do an integrity check on each database file */
   116780     for(i=0; i<db->nDb; i++){
   116781       HashElem *x;     /* For looping over tables in the schema */
   116782       Hash *pTbls;     /* Set of all tables in the schema */
   116783       int *aRoot;      /* Array of root page numbers of all btrees */
   116784       int cnt = 0;     /* Number of entries in aRoot[] */
   116785       int mxIdx = 0;   /* Maximum number of indexes for any table */
   116786 
   116787       if( OMIT_TEMPDB && i==1 ) continue;
   116788       if( iDb>=0 && i!=iDb ) continue;
   116789 
   116790       sqlite3CodeVerifySchema(pParse, i);
   116791 
   116792       /* Do an integrity check of the B-Tree
   116793       **
   116794       ** Begin by finding the root pages numbers
   116795       ** for all tables and indices in the database.
   116796       */
   116797       assert( sqlite3SchemaMutexHeld(db, i, 0) );
   116798       pTbls = &db->aDb[i].pSchema->tblHash;
   116799       for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   116800         Table *pTab = sqliteHashData(x);  /* Current table */
   116801         Index *pIdx;                      /* An index on pTab */
   116802         int nIdx;                         /* Number of indexes on pTab */
   116803         if( HasRowid(pTab) ) cnt++;
   116804         for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
   116805         if( nIdx>mxIdx ) mxIdx = nIdx;
   116806       }
   116807       aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
   116808       if( aRoot==0 ) break;
   116809       for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   116810         Table *pTab = sqliteHashData(x);
   116811         Index *pIdx;
   116812         if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
   116813         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   116814           aRoot[++cnt] = pIdx->tnum;
   116815         }
   116816       }
   116817       aRoot[0] = cnt;
   116818 
   116819       /* Make sure sufficient number of registers have been allocated */
   116820       pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
   116821       sqlite3ClearTempRegCache(pParse);
   116822 
   116823       /* Do the b-tree integrity checks */
   116824       sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
   116825       sqlite3VdbeChangeP5(v, (u8)i);
   116826       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
   116827       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   116828          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
   116829          P4_DYNAMIC);
   116830       sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
   116831       integrityCheckResultRow(v);
   116832       sqlite3VdbeJumpHere(v, addr);
   116833 
   116834       /* Make sure all the indices are constructed correctly.
   116835       */
   116836       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   116837         Table *pTab = sqliteHashData(x);
   116838         Index *pIdx, *pPk;
   116839         Index *pPrior = 0;
   116840         int loopTop;
   116841         int iDataCur, iIdxCur;
   116842         int r1 = -1;
   116843 
   116844         if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
   116845         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   116846         sqlite3ExprCacheClear(pParse);
   116847         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
   116848                                    1, 0, &iDataCur, &iIdxCur);
   116849         /* reg[7] counts the number of entries in the table.
   116850         ** reg[8+i] counts the number of entries in the i-th index
   116851         */
   116852         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
   116853         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   116854           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
   116855         }
   116856         assert( pParse->nMem>=8+j );
   116857         assert( sqlite3NoTempsInRange(pParse,1,7+j) );
   116858         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
   116859         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
   116860         /* Verify that all NOT NULL columns really are NOT NULL */
   116861         for(j=0; j<pTab->nCol; j++){
   116862           char *zErr;
   116863           int jmp2;
   116864           if( j==pTab->iPKey ) continue;
   116865           if( pTab->aCol[j].notNull==0 ) continue;
   116866           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
   116867           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
   116868           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
   116869           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
   116870                               pTab->aCol[j].zName);
   116871           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
   116872           integrityCheckResultRow(v);
   116873           sqlite3VdbeJumpHere(v, jmp2);
   116874         }
   116875         /* Verify CHECK constraints */
   116876         if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
   116877           ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
   116878           if( db->mallocFailed==0 ){
   116879             int addrCkFault = sqlite3VdbeMakeLabel(v);
   116880             int addrCkOk = sqlite3VdbeMakeLabel(v);
   116881             char *zErr;
   116882             int k;
   116883             pParse->iSelfTab = iDataCur + 1;
   116884             sqlite3ExprCachePush(pParse);
   116885             for(k=pCheck->nExpr-1; k>0; k--){
   116886               sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
   116887             }
   116888             sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
   116889                 SQLITE_JUMPIFNULL);
   116890             sqlite3VdbeResolveLabel(v, addrCkFault);
   116891             pParse->iSelfTab = 0;
   116892             zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
   116893                 pTab->zName);
   116894             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
   116895             integrityCheckResultRow(v);
   116896             sqlite3VdbeResolveLabel(v, addrCkOk);
   116897             sqlite3ExprCachePop(pParse);
   116898           }
   116899           sqlite3ExprListDelete(db, pCheck);
   116900         }
   116901         if( !isQuick ){ /* Omit the remaining tests for quick_check */
   116902           /* Sanity check on record header decoding */
   116903           sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
   116904           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
   116905           /* Validate index entries for the current row */
   116906           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   116907             int jmp2, jmp3, jmp4, jmp5;
   116908             int ckUniq = sqlite3VdbeMakeLabel(v);
   116909             if( pPk==pIdx ) continue;
   116910             r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
   116911                                          pPrior, r1);
   116912             pPrior = pIdx;
   116913             sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
   116914             /* Verify that an index entry exists for the current table row */
   116915             jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
   116916                                         pIdx->nColumn); VdbeCoverage(v);
   116917             sqlite3VdbeLoadString(v, 3, "row ");
   116918             sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
   116919             sqlite3VdbeLoadString(v, 4, " missing from index ");
   116920             sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
   116921             jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
   116922             sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
   116923             jmp4 = integrityCheckResultRow(v);
   116924             sqlite3VdbeJumpHere(v, jmp2);
   116925             /* For UNIQUE indexes, verify that only one entry exists with the
   116926             ** current key.  The entry is unique if (1) any column is NULL
   116927             ** or (2) the next entry has a different key */
   116928             if( IsUniqueIndex(pIdx) ){
   116929               int uniqOk = sqlite3VdbeMakeLabel(v);
   116930               int jmp6;
   116931               int kk;
   116932               for(kk=0; kk<pIdx->nKeyCol; kk++){
   116933                 int iCol = pIdx->aiColumn[kk];
   116934                 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
   116935                 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
   116936                 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
   116937                 VdbeCoverage(v);
   116938               }
   116939               jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
   116940               sqlite3VdbeGoto(v, uniqOk);
   116941               sqlite3VdbeJumpHere(v, jmp6);
   116942               sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
   116943                                    pIdx->nKeyCol); VdbeCoverage(v);
   116944               sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
   116945               sqlite3VdbeGoto(v, jmp5);
   116946               sqlite3VdbeResolveLabel(v, uniqOk);
   116947             }
   116948             sqlite3VdbeJumpHere(v, jmp4);
   116949             sqlite3ResolvePartIdxLabel(pParse, jmp3);
   116950           }
   116951         }
   116952         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
   116953         sqlite3VdbeJumpHere(v, loopTop-1);
   116954 #ifndef SQLITE_OMIT_BTREECOUNT
   116955         if( !isQuick ){
   116956           sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
   116957           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   116958             if( pPk==pIdx ) continue;
   116959             sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
   116960             addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
   116961             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   116962             sqlite3VdbeLoadString(v, 4, pIdx->zName);
   116963             sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
   116964             integrityCheckResultRow(v);
   116965             sqlite3VdbeJumpHere(v, addr);
   116966           }
   116967         }
   116968 #endif /* SQLITE_OMIT_BTREECOUNT */
   116969       }
   116970     }
   116971     {
   116972       static const int iLn = VDBE_OFFSET_LINENO(2);
   116973       static const VdbeOpList endCode[] = {
   116974         { OP_AddImm,      1, 0,        0},    /* 0 */
   116975         { OP_IfNotZero,   1, 4,        0},    /* 1 */
   116976         { OP_String8,     0, 3,        0},    /* 2 */
   116977         { OP_ResultRow,   3, 1,        0},    /* 3 */
   116978         { OP_Halt,        0, 0,        0},    /* 4 */
   116979         { OP_String8,     0, 3,        0},    /* 5 */
   116980         { OP_Goto,        0, 3,        0},    /* 6 */
   116981       };
   116982       VdbeOp *aOp;
   116983 
   116984       aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
   116985       if( aOp ){
   116986         aOp[0].p2 = 1-mxErr;
   116987         aOp[2].p4type = P4_STATIC;
   116988         aOp[2].p4.z = "ok";
   116989         aOp[5].p4type = P4_STATIC;
   116990         aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
   116991       }
   116992       sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
   116993     }
   116994   }
   116995   break;
   116996 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   116997 
   116998 #ifndef SQLITE_OMIT_UTF16
   116999   /*
   117000   **   PRAGMA encoding
   117001   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
   117002   **
   117003   ** In its first form, this pragma returns the encoding of the main
   117004   ** database. If the database is not initialized, it is initialized now.
   117005   **
   117006   ** The second form of this pragma is a no-op if the main database file
   117007   ** has not already been initialized. In this case it sets the default
   117008   ** encoding that will be used for the main database file if a new file
   117009   ** is created. If an existing main database file is opened, then the
   117010   ** default text encoding for the existing database is used.
   117011   **
   117012   ** In all cases new databases created using the ATTACH command are
   117013   ** created to use the same default text encoding as the main database. If
   117014   ** the main database has not been initialized and/or created when ATTACH
   117015   ** is executed, this is done before the ATTACH operation.
   117016   **
   117017   ** In the second form this pragma sets the text encoding to be used in
   117018   ** new database files created using this database handle. It is only
   117019   ** useful if invoked immediately after the main database i
   117020   */
   117021   case PragTyp_ENCODING: {
   117022     static const struct EncName {
   117023       char *zName;
   117024       u8 enc;
   117025     } encnames[] = {
   117026       { "UTF8",     SQLITE_UTF8        },
   117027       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
   117028       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
   117029       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
   117030       { "UTF16le",  SQLITE_UTF16LE     },
   117031       { "UTF16be",  SQLITE_UTF16BE     },
   117032       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
   117033       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
   117034       { 0, 0 }
   117035     };
   117036     const struct EncName *pEnc;
   117037     if( !zRight ){    /* "PRAGMA encoding" */
   117038       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   117039       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
   117040       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
   117041       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
   117042       returnSingleText(v, encnames[ENC(pParse->db)].zName);
   117043     }else{                        /* "PRAGMA encoding = XXX" */
   117044       /* Only change the value of sqlite.enc if the database handle is not
   117045       ** initialized. If the main database exists, the new sqlite.enc value
   117046       ** will be overwritten when the schema is next loaded. If it does not
   117047       ** already exists, it will be created to use the new encoding value.
   117048       */
   117049       if(
   117050         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
   117051         DbHasProperty(db, 0, DB_Empty)
   117052       ){
   117053         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
   117054           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
   117055             SCHEMA_ENC(db) = ENC(db) =
   117056                 pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
   117057             break;
   117058           }
   117059         }
   117060         if( !pEnc->zName ){
   117061           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
   117062         }
   117063       }
   117064     }
   117065   }
   117066   break;
   117067 #endif /* SQLITE_OMIT_UTF16 */
   117068 
   117069 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   117070   /*
   117071   **   PRAGMA [schema.]schema_version
   117072   **   PRAGMA [schema.]schema_version = <integer>
   117073   **
   117074   **   PRAGMA [schema.]user_version
   117075   **   PRAGMA [schema.]user_version = <integer>
   117076   **
   117077   **   PRAGMA [schema.]freelist_count
   117078   **
   117079   **   PRAGMA [schema.]data_version
   117080   **
   117081   **   PRAGMA [schema.]application_id
   117082   **   PRAGMA [schema.]application_id = <integer>
   117083   **
   117084   ** The pragma's schema_version and user_version are used to set or get
   117085   ** the value of the schema-version and user-version, respectively. Both
   117086   ** the schema-version and the user-version are 32-bit signed integers
   117087   ** stored in the database header.
   117088   **
   117089   ** The schema-cookie is usually only manipulated internally by SQLite. It
   117090   ** is incremented by SQLite whenever the database schema is modified (by
   117091   ** creating or dropping a table or index). The schema version is used by
   117092   ** SQLite each time a query is executed to ensure that the internal cache
   117093   ** of the schema used when compiling the SQL query matches the schema of
   117094   ** the database against which the compiled query is actually executed.
   117095   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
   117096   ** the schema-version is potentially dangerous and may lead to program
   117097   ** crashes or database corruption. Use with caution!
   117098   **
   117099   ** The user-version is not used internally by SQLite. It may be used by
   117100   ** applications for any purpose.
   117101   */
   117102   case PragTyp_HEADER_VALUE: {
   117103     int iCookie = pPragma->iArg;  /* Which cookie to read or write */
   117104     sqlite3VdbeUsesBtree(v, iDb);
   117105     if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
   117106       /* Write the specified cookie value */
   117107       static const VdbeOpList setCookie[] = {
   117108         { OP_Transaction,    0,  1,  0},    /* 0 */
   117109         { OP_SetCookie,      0,  0,  0},    /* 1 */
   117110       };
   117111       VdbeOp *aOp;
   117112       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
   117113       aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
   117114       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
   117115       aOp[0].p1 = iDb;
   117116       aOp[1].p1 = iDb;
   117117       aOp[1].p2 = iCookie;
   117118       aOp[1].p3 = sqlite3Atoi(zRight);
   117119     }else{
   117120       /* Read the specified cookie value */
   117121       static const VdbeOpList readCookie[] = {
   117122         { OP_Transaction,     0,  0,  0},    /* 0 */
   117123         { OP_ReadCookie,      0,  1,  0},    /* 1 */
   117124         { OP_ResultRow,       1,  1,  0}
   117125       };
   117126       VdbeOp *aOp;
   117127       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
   117128       aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
   117129       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
   117130       aOp[0].p1 = iDb;
   117131       aOp[1].p1 = iDb;
   117132       aOp[1].p3 = iCookie;
   117133       sqlite3VdbeReusable(v);
   117134     }
   117135   }
   117136   break;
   117137 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
   117138 
   117139 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   117140   /*
   117141   **   PRAGMA compile_options
   117142   **
   117143   ** Return the names of all compile-time options used in this build,
   117144   ** one option per row.
   117145   */
   117146   case PragTyp_COMPILE_OPTIONS: {
   117147     int i = 0;
   117148     const char *zOpt;
   117149     pParse->nMem = 1;
   117150     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
   117151       sqlite3VdbeLoadString(v, 1, zOpt);
   117152       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   117153     }
   117154     sqlite3VdbeReusable(v);
   117155   }
   117156   break;
   117157 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   117158 
   117159 #ifndef SQLITE_OMIT_WAL
   117160   /*
   117161   **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
   117162   **
   117163   ** Checkpoint the database.
   117164   */
   117165   case PragTyp_WAL_CHECKPOINT: {
   117166     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
   117167     int eMode = SQLITE_CHECKPOINT_PASSIVE;
   117168     if( zRight ){
   117169       if( sqlite3StrICmp(zRight, "full")==0 ){
   117170         eMode = SQLITE_CHECKPOINT_FULL;
   117171       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
   117172         eMode = SQLITE_CHECKPOINT_RESTART;
   117173       }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
   117174         eMode = SQLITE_CHECKPOINT_TRUNCATE;
   117175       }
   117176     }
   117177     pParse->nMem = 3;
   117178     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
   117179     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   117180   }
   117181   break;
   117182 
   117183   /*
   117184   **   PRAGMA wal_autocheckpoint
   117185   **   PRAGMA wal_autocheckpoint = N
   117186   **
   117187   ** Configure a database connection to automatically checkpoint a database
   117188   ** after accumulating N frames in the log. Or query for the current value
   117189   ** of N.
   117190   */
   117191   case PragTyp_WAL_AUTOCHECKPOINT: {
   117192     if( zRight ){
   117193       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
   117194     }
   117195     returnSingleInt(v,
   117196        db->xWalCallback==sqlite3WalDefaultHook ?
   117197            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
   117198   }
   117199   break;
   117200 #endif
   117201 
   117202   /*
   117203   **  PRAGMA shrink_memory
   117204   **
   117205   ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
   117206   ** connection on which it is invoked to free up as much memory as it
   117207   ** can, by calling sqlite3_db_release_memory().
   117208   */
   117209   case PragTyp_SHRINK_MEMORY: {
   117210     sqlite3_db_release_memory(db);
   117211     break;
   117212   }
   117213 
   117214   /*
   117215   **  PRAGMA optimize
   117216   **  PRAGMA optimize(MASK)
   117217   **  PRAGMA schema.optimize
   117218   **  PRAGMA schema.optimize(MASK)
   117219   **
   117220   ** Attempt to optimize the database.  All schemas are optimized in the first
   117221   ** two forms, and only the specified schema is optimized in the latter two.
   117222   **
   117223   ** The details of optimizations performed by this pragma are expected
   117224   ** to change and improve over time.  Applications should anticipate that
   117225   ** this pragma will perform new optimizations in future releases.
   117226   **
   117227   ** The optional argument is a bitmask of optimizations to perform:
   117228   **
   117229   **    0x0001    Debugging mode.  Do not actually perform any optimizations
   117230   **              but instead return one line of text for each optimization
   117231   **              that would have been done.  Off by default.
   117232   **
   117233   **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
   117234   **              See below for additional information.
   117235   **
   117236   **    0x0004    (Not yet implemented) Record usage and performance
   117237   **              information from the current session in the
   117238   **              database file so that it will be available to "optimize"
   117239   **              pragmas run by future database connections.
   117240   **
   117241   **    0x0008    (Not yet implemented) Create indexes that might have
   117242   **              been helpful to recent queries
   117243   **
   117244   ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
   117245   ** of the optimizations listed above except Debug Mode, including new
   117246   ** optimizations that have not yet been invented.  If new optimizations are
   117247   ** ever added that should be off by default, those off-by-default
   117248   ** optimizations will have bitmasks of 0x10000 or larger.
   117249   **
   117250   ** DETERMINATION OF WHEN TO RUN ANALYZE
   117251   **
   117252   ** In the current implementation, a table is analyzed if only if all of
   117253   ** the following are true:
   117254   **
   117255   ** (1) MASK bit 0x02 is set.
   117256   **
   117257   ** (2) The query planner used sqlite_stat1-style statistics for one or
   117258   **     more indexes of the table at some point during the lifetime of
   117259   **     the current connection.
   117260   **
   117261   ** (3) One or more indexes of the table are currently unanalyzed OR
   117262   **     the number of rows in the table has increased by 25 times or more
   117263   **     since the last time ANALYZE was run.
   117264   **
   117265   ** The rules for when tables are analyzed are likely to change in
   117266   ** future releases.
   117267   */
   117268   case PragTyp_OPTIMIZE: {
   117269     int iDbLast;           /* Loop termination point for the schema loop */
   117270     int iTabCur;           /* Cursor for a table whose size needs checking */
   117271     HashElem *k;           /* Loop over tables of a schema */
   117272     Schema *pSchema;       /* The current schema */
   117273     Table *pTab;           /* A table in the schema */
   117274     Index *pIdx;           /* An index of the table */
   117275     LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
   117276     char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
   117277     u32 opMask;            /* Mask of operations to perform */
   117278 
   117279     if( zRight ){
   117280       opMask = (u32)sqlite3Atoi(zRight);
   117281       if( (opMask & 0x02)==0 ) break;
   117282     }else{
   117283       opMask = 0xfffe;
   117284     }
   117285     iTabCur = pParse->nTab++;
   117286     for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
   117287       if( iDb==1 ) continue;
   117288       sqlite3CodeVerifySchema(pParse, iDb);
   117289       pSchema = db->aDb[iDb].pSchema;
   117290       for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   117291         pTab = (Table*)sqliteHashData(k);
   117292 
   117293         /* If table pTab has not been used in a way that would benefit from
   117294         ** having analysis statistics during the current session, then skip it.
   117295         ** This also has the effect of skipping virtual tables and views */
   117296         if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
   117297 
   117298         /* Reanalyze if the table is 25 times larger than the last analysis */
   117299         szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
   117300         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   117301           if( !pIdx->hasStat1 ){
   117302             szThreshold = 0; /* Always analyze if any index lacks statistics */
   117303             break;
   117304           }
   117305         }
   117306         if( szThreshold ){
   117307           sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
   117308           sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
   117309                          sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
   117310           VdbeCoverage(v);
   117311         }
   117312         zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
   117313                                  db->aDb[iDb].zDbSName, pTab->zName);
   117314         if( opMask & 0x01 ){
   117315           int r1 = sqlite3GetTempReg(pParse);
   117316           sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
   117317           sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
   117318         }else{
   117319           sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
   117320         }
   117321       }
   117322     }
   117323     sqlite3VdbeAddOp0(v, OP_Expire);
   117324     break;
   117325   }
   117326 
   117327   /*
   117328   **   PRAGMA busy_timeout
   117329   **   PRAGMA busy_timeout = N
   117330   **
   117331   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
   117332   ** if one is set.  If no busy handler or a different busy handler is set
   117333   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
   117334   ** disables the timeout.
   117335   */
   117336   /*case PragTyp_BUSY_TIMEOUT*/ default: {
   117337     assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
   117338     if( zRight ){
   117339       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
   117340     }
   117341     returnSingleInt(v, db->busyTimeout);
   117342     break;
   117343   }
   117344 
   117345   /*
   117346   **   PRAGMA soft_heap_limit
   117347   **   PRAGMA soft_heap_limit = N
   117348   **
   117349   ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
   117350   ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
   117351   ** specified and is a non-negative integer.
   117352   ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
   117353   ** returns the same integer that would be returned by the
   117354   ** sqlite3_soft_heap_limit64(-1) C-language function.
   117355   */
   117356   case PragTyp_SOFT_HEAP_LIMIT: {
   117357     sqlite3_int64 N;
   117358     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
   117359       sqlite3_soft_heap_limit64(N);
   117360     }
   117361     returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
   117362     break;
   117363   }
   117364 
   117365   /*
   117366   **   PRAGMA threads
   117367   **   PRAGMA threads = N
   117368   **
   117369   ** Configure the maximum number of worker threads.  Return the new
   117370   ** maximum, which might be less than requested.
   117371   */
   117372   case PragTyp_THREADS: {
   117373     sqlite3_int64 N;
   117374     if( zRight
   117375      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
   117376      && N>=0
   117377     ){
   117378       sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
   117379     }
   117380     returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
   117381     break;
   117382   }
   117383 
   117384 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   117385   /*
   117386   ** Report the current state of file logs for all databases
   117387   */
   117388   case PragTyp_LOCK_STATUS: {
   117389     static const char *const azLockName[] = {
   117390       "unlocked", "shared", "reserved", "pending", "exclusive"
   117391     };
   117392     int i;
   117393     pParse->nMem = 2;
   117394     for(i=0; i<db->nDb; i++){
   117395       Btree *pBt;
   117396       const char *zState = "unknown";
   117397       int j;
   117398       if( db->aDb[i].zDbSName==0 ) continue;
   117399       pBt = db->aDb[i].pBt;
   117400       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
   117401         zState = "closed";
   117402       }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
   117403                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
   117404          zState = azLockName[j];
   117405       }
   117406       sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
   117407     }
   117408     break;
   117409   }
   117410 #endif
   117411 
   117412 #ifdef SQLITE_HAS_CODEC
   117413   case PragTyp_KEY: {
   117414     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
   117415     break;
   117416   }
   117417   case PragTyp_REKEY: {
   117418     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
   117419     break;
   117420   }
   117421   case PragTyp_HEXKEY: {
   117422     if( zRight ){
   117423       u8 iByte;
   117424       int i;
   117425       char zKey[40];
   117426       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
   117427         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
   117428         if( (i&1)!=0 ) zKey[i/2] = iByte;
   117429       }
   117430       if( (zLeft[3] & 0xf)==0xb ){
   117431         sqlite3_key_v2(db, zDb, zKey, i/2);
   117432       }else{
   117433         sqlite3_rekey_v2(db, zDb, zKey, i/2);
   117434       }
   117435     }
   117436     break;
   117437   }
   117438 #endif
   117439 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   117440   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
   117441 #ifdef SQLITE_HAS_CODEC
   117442     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
   117443       sqlite3_activate_see(&zRight[4]);
   117444     }
   117445 #endif
   117446 #ifdef SQLITE_ENABLE_CEROD
   117447     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
   117448       sqlite3_activate_cerod(&zRight[6]);
   117449     }
   117450 #endif
   117451   }
   117452   break;
   117453 #endif
   117454 
   117455   } /* End of the PRAGMA switch */
   117456 
   117457   /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
   117458   ** purpose is to execute assert() statements to verify that if the
   117459   ** PragFlg_NoColumns1 flag is set and the caller specified an argument
   117460   ** to the PRAGMA, the implementation has not added any OP_ResultRow
   117461   ** instructions to the VM.  */
   117462   if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
   117463     sqlite3VdbeVerifyNoResultRow(v);
   117464   }
   117465 
   117466 pragma_out:
   117467   sqlite3DbFree(db, zLeft);
   117468   sqlite3DbFree(db, zRight);
   117469 }
   117470 #ifndef SQLITE_OMIT_VIRTUALTABLE
   117471 /*****************************************************************************
   117472 ** Implementation of an eponymous virtual table that runs a pragma.
   117473 **
   117474 */
   117475 typedef struct PragmaVtab PragmaVtab;
   117476 typedef struct PragmaVtabCursor PragmaVtabCursor;
   117477 struct PragmaVtab {
   117478   sqlite3_vtab base;        /* Base class.  Must be first */
   117479   sqlite3 *db;              /* The database connection to which it belongs */
   117480   const PragmaName *pName;  /* Name of the pragma */
   117481   u8 nHidden;               /* Number of hidden columns */
   117482   u8 iHidden;               /* Index of the first hidden column */
   117483 };
   117484 struct PragmaVtabCursor {
   117485   sqlite3_vtab_cursor base; /* Base class.  Must be first */
   117486   sqlite3_stmt *pPragma;    /* The pragma statement to run */
   117487   sqlite_int64 iRowid;      /* Current rowid */
   117488   char *azArg[2];           /* Value of the argument and schema */
   117489 };
   117490 
   117491 /*
   117492 ** Pragma virtual table module xConnect method.
   117493 */
   117494 static int pragmaVtabConnect(
   117495   sqlite3 *db,
   117496   void *pAux,
   117497   int argc, const char *const*argv,
   117498   sqlite3_vtab **ppVtab,
   117499   char **pzErr
   117500 ){
   117501   const PragmaName *pPragma = (const PragmaName*)pAux;
   117502   PragmaVtab *pTab = 0;
   117503   int rc;
   117504   int i, j;
   117505   char cSep = '(';
   117506   StrAccum acc;
   117507   char zBuf[200];
   117508 
   117509   UNUSED_PARAMETER(argc);
   117510   UNUSED_PARAMETER(argv);
   117511   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
   117512   sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
   117513   for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
   117514     sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
   117515     cSep = ',';
   117516   }
   117517   if( i==0 ){
   117518     sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
   117519     cSep = ',';
   117520     i++;
   117521   }
   117522   j = 0;
   117523   if( pPragma->mPragFlg & PragFlg_Result1 ){
   117524     sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
   117525     j++;
   117526   }
   117527   if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
   117528     sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
   117529     j++;
   117530   }
   117531   sqlite3StrAccumAppend(&acc, ")", 1);
   117532   sqlite3StrAccumFinish(&acc);
   117533   assert( strlen(zBuf) < sizeof(zBuf)-1 );
   117534   rc = sqlite3_declare_vtab(db, zBuf);
   117535   if( rc==SQLITE_OK ){
   117536     pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
   117537     if( pTab==0 ){
   117538       rc = SQLITE_NOMEM;
   117539     }else{
   117540       memset(pTab, 0, sizeof(PragmaVtab));
   117541       pTab->pName = pPragma;
   117542       pTab->db = db;
   117543       pTab->iHidden = i;
   117544       pTab->nHidden = j;
   117545     }
   117546   }else{
   117547     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   117548   }
   117549 
   117550   *ppVtab = (sqlite3_vtab*)pTab;
   117551   return rc;
   117552 }
   117553 
   117554 /*
   117555 ** Pragma virtual table module xDisconnect method.
   117556 */
   117557 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
   117558   PragmaVtab *pTab = (PragmaVtab*)pVtab;
   117559   sqlite3_free(pTab);
   117560   return SQLITE_OK;
   117561 }
   117562 
   117563 /* Figure out the best index to use to search a pragma virtual table.
   117564 **
   117565 ** There are not really any index choices.  But we want to encourage the
   117566 ** query planner to give == constraints on as many hidden parameters as
   117567 ** possible, and especially on the first hidden parameter.  So return a
   117568 ** high cost if hidden parameters are unconstrained.
   117569 */
   117570 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   117571   PragmaVtab *pTab = (PragmaVtab*)tab;
   117572   const struct sqlite3_index_constraint *pConstraint;
   117573   int i, j;
   117574   int seen[2];
   117575 
   117576   pIdxInfo->estimatedCost = (double)1;
   117577   if( pTab->nHidden==0 ){ return SQLITE_OK; }
   117578   pConstraint = pIdxInfo->aConstraint;
   117579   seen[0] = 0;
   117580   seen[1] = 0;
   117581   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
   117582     if( pConstraint->usable==0 ) continue;
   117583     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   117584     if( pConstraint->iColumn < pTab->iHidden ) continue;
   117585     j = pConstraint->iColumn - pTab->iHidden;
   117586     assert( j < 2 );
   117587     seen[j] = i+1;
   117588   }
   117589   if( seen[0]==0 ){
   117590     pIdxInfo->estimatedCost = (double)2147483647;
   117591     pIdxInfo->estimatedRows = 2147483647;
   117592     return SQLITE_OK;
   117593   }
   117594   j = seen[0]-1;
   117595   pIdxInfo->aConstraintUsage[j].argvIndex = 1;
   117596   pIdxInfo->aConstraintUsage[j].omit = 1;
   117597   if( seen[1]==0 ) return SQLITE_OK;
   117598   pIdxInfo->estimatedCost = (double)20;
   117599   pIdxInfo->estimatedRows = 20;
   117600   j = seen[1]-1;
   117601   pIdxInfo->aConstraintUsage[j].argvIndex = 2;
   117602   pIdxInfo->aConstraintUsage[j].omit = 1;
   117603   return SQLITE_OK;
   117604 }
   117605 
   117606 /* Create a new cursor for the pragma virtual table */
   117607 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
   117608   PragmaVtabCursor *pCsr;
   117609   pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
   117610   if( pCsr==0 ) return SQLITE_NOMEM;
   117611   memset(pCsr, 0, sizeof(PragmaVtabCursor));
   117612   pCsr->base.pVtab = pVtab;
   117613   *ppCursor = &pCsr->base;
   117614   return SQLITE_OK;
   117615 }
   117616 
   117617 /* Clear all content from pragma virtual table cursor. */
   117618 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
   117619   int i;
   117620   sqlite3_finalize(pCsr->pPragma);
   117621   pCsr->pPragma = 0;
   117622   for(i=0; i<ArraySize(pCsr->azArg); i++){
   117623     sqlite3_free(pCsr->azArg[i]);
   117624     pCsr->azArg[i] = 0;
   117625   }
   117626 }
   117627 
   117628 /* Close a pragma virtual table cursor */
   117629 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
   117630   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
   117631   pragmaVtabCursorClear(pCsr);
   117632   sqlite3_free(pCsr);
   117633   return SQLITE_OK;
   117634 }
   117635 
   117636 /* Advance the pragma virtual table cursor to the next row */
   117637 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
   117638   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
   117639   int rc = SQLITE_OK;
   117640 
   117641   /* Increment the xRowid value */
   117642   pCsr->iRowid++;
   117643   assert( pCsr->pPragma );
   117644   if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
   117645     rc = sqlite3_finalize(pCsr->pPragma);
   117646     pCsr->pPragma = 0;
   117647     pragmaVtabCursorClear(pCsr);
   117648   }
   117649   return rc;
   117650 }
   117651 
   117652 /*
   117653 ** Pragma virtual table module xFilter method.
   117654 */
   117655 static int pragmaVtabFilter(
   117656   sqlite3_vtab_cursor *pVtabCursor,
   117657   int idxNum, const char *idxStr,
   117658   int argc, sqlite3_value **argv
   117659 ){
   117660   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
   117661   PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
   117662   int rc;
   117663   int i, j;
   117664   StrAccum acc;
   117665   char *zSql;
   117666 
   117667   UNUSED_PARAMETER(idxNum);
   117668   UNUSED_PARAMETER(idxStr);
   117669   pragmaVtabCursorClear(pCsr);
   117670   j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
   117671   for(i=0; i<argc; i++, j++){
   117672     const char *zText = (const char*)sqlite3_value_text(argv[i]);
   117673     assert( j<ArraySize(pCsr->azArg) );
   117674     assert( pCsr->azArg[j]==0 );
   117675     if( zText ){
   117676       pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
   117677       if( pCsr->azArg[j]==0 ){
   117678         return SQLITE_NOMEM;
   117679       }
   117680     }
   117681   }
   117682   sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
   117683   sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
   117684   if( pCsr->azArg[1] ){
   117685     sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
   117686   }
   117687   sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
   117688   if( pCsr->azArg[0] ){
   117689     sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
   117690   }
   117691   zSql = sqlite3StrAccumFinish(&acc);
   117692   if( zSql==0 ) return SQLITE_NOMEM;
   117693   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
   117694   sqlite3_free(zSql);
   117695   if( rc!=SQLITE_OK ){
   117696     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
   117697     return rc;
   117698   }
   117699   return pragmaVtabNext(pVtabCursor);
   117700 }
   117701 
   117702 /*
   117703 ** Pragma virtual table module xEof method.
   117704 */
   117705 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
   117706   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
   117707   return (pCsr->pPragma==0);
   117708 }
   117709 
   117710 /* The xColumn method simply returns the corresponding column from
   117711 ** the PRAGMA.
   117712 */
   117713 static int pragmaVtabColumn(
   117714   sqlite3_vtab_cursor *pVtabCursor,
   117715   sqlite3_context *ctx,
   117716   int i
   117717 ){
   117718   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
   117719   PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
   117720   if( i<pTab->iHidden ){
   117721     sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
   117722   }else{
   117723     sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
   117724   }
   117725   return SQLITE_OK;
   117726 }
   117727 
   117728 /*
   117729 ** Pragma virtual table module xRowid method.
   117730 */
   117731 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
   117732   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
   117733   *p = pCsr->iRowid;
   117734   return SQLITE_OK;
   117735 }
   117736 
   117737 /* The pragma virtual table object */
   117738 static const sqlite3_module pragmaVtabModule = {
   117739   0,                           /* iVersion */
   117740   0,                           /* xCreate - create a table */
   117741   pragmaVtabConnect,           /* xConnect - connect to an existing table */
   117742   pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
   117743   pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
   117744   0,                           /* xDestroy - Drop a table */
   117745   pragmaVtabOpen,              /* xOpen - open a cursor */
   117746   pragmaVtabClose,             /* xClose - close a cursor */
   117747   pragmaVtabFilter,            /* xFilter - configure scan constraints */
   117748   pragmaVtabNext,              /* xNext - advance a cursor */
   117749   pragmaVtabEof,               /* xEof */
   117750   pragmaVtabColumn,            /* xColumn - read data */
   117751   pragmaVtabRowid,             /* xRowid - read data */
   117752   0,                           /* xUpdate - write data */
   117753   0,                           /* xBegin - begin transaction */
   117754   0,                           /* xSync - sync transaction */
   117755   0,                           /* xCommit - commit transaction */
   117756   0,                           /* xRollback - rollback transaction */
   117757   0,                           /* xFindFunction - function overloading */
   117758   0,                           /* xRename - rename the table */
   117759   0,                           /* xSavepoint */
   117760   0,                           /* xRelease */
   117761   0                            /* xRollbackTo */
   117762 };
   117763 
   117764 /*
   117765 ** Check to see if zTabName is really the name of a pragma.  If it is,
   117766 ** then register an eponymous virtual table for that pragma and return
   117767 ** a pointer to the Module object for the new virtual table.
   117768 */
   117769 SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
   117770   const PragmaName *pName;
   117771   assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
   117772   pName = pragmaLocate(zName+7);
   117773   if( pName==0 ) return 0;
   117774   if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
   117775   assert( sqlite3HashFind(&db->aModule, zName)==0 );
   117776   return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
   117777 }
   117778 
   117779 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   117780 
   117781 #endif /* SQLITE_OMIT_PRAGMA */
   117782 
   117783 /************** End of pragma.c **********************************************/
   117784 /************** Begin file prepare.c *****************************************/
   117785 /*
   117786 ** 2005 May 25
   117787 **
   117788 ** The author disclaims copyright to this source code.  In place of
   117789 ** a legal notice, here is a blessing:
   117790 **
   117791 **    May you do good and not evil.
   117792 **    May you find forgiveness for yourself and forgive others.
   117793 **    May you share freely, never taking more than you give.
   117794 **
   117795 *************************************************************************
   117796 ** This file contains the implementation of the sqlite3_prepare()
   117797 ** interface, and routines that contribute to loading the database schema
   117798 ** from disk.
   117799 */
   117800 /* #include "sqliteInt.h" */
   117801 
   117802 /*
   117803 ** Fill the InitData structure with an error message that indicates
   117804 ** that the database is corrupt.
   117805 */
   117806 static void corruptSchema(
   117807   InitData *pData,     /* Initialization context */
   117808   const char *zObj,    /* Object being parsed at the point of error */
   117809   const char *zExtra   /* Error information */
   117810 ){
   117811   sqlite3 *db = pData->db;
   117812   if( !db->mallocFailed && (db->flags & SQLITE_WriteSchema)==0 ){
   117813     char *z;
   117814     if( zObj==0 ) zObj = "?";
   117815     z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
   117816     if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
   117817     sqlite3DbFree(db, *pData->pzErrMsg);
   117818     *pData->pzErrMsg = z;
   117819   }
   117820   pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
   117821 }
   117822 
   117823 /*
   117824 ** This is the callback routine for the code that initializes the
   117825 ** database.  See sqlite3Init() below for additional information.
   117826 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
   117827 **
   117828 ** Each callback contains the following information:
   117829 **
   117830 **     argv[0] = name of thing being created
   117831 **     argv[1] = root page number for table or index. 0 for trigger or view.
   117832 **     argv[2] = SQL text for the CREATE statement.
   117833 **
   117834 */
   117835 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
   117836   InitData *pData = (InitData*)pInit;
   117837   sqlite3 *db = pData->db;
   117838   int iDb = pData->iDb;
   117839 
   117840   assert( argc==3 );
   117841   UNUSED_PARAMETER2(NotUsed, argc);
   117842   assert( sqlite3_mutex_held(db->mutex) );
   117843   DbClearProperty(db, iDb, DB_Empty);
   117844   if( db->mallocFailed ){
   117845     corruptSchema(pData, argv[0], 0);
   117846     return 1;
   117847   }
   117848 
   117849   assert( iDb>=0 && iDb<db->nDb );
   117850   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   117851   if( argv[1]==0 ){
   117852     corruptSchema(pData, argv[0], 0);
   117853   }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
   117854     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
   117855     ** But because db->init.busy is set to 1, no VDBE code is generated
   117856     ** or executed.  All the parser does is build the internal data
   117857     ** structures that describe the table, index, or view.
   117858     */
   117859     int rc;
   117860     u8 saved_iDb = db->init.iDb;
   117861     sqlite3_stmt *pStmt;
   117862     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
   117863 
   117864     assert( db->init.busy );
   117865     db->init.iDb = iDb;
   117866     db->init.newTnum = sqlite3Atoi(argv[1]);
   117867     db->init.orphanTrigger = 0;
   117868     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
   117869     rc = db->errCode;
   117870     assert( (rc&0xFF)==(rcp&0xFF) );
   117871     db->init.iDb = saved_iDb;
   117872     assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 );
   117873     if( SQLITE_OK!=rc ){
   117874       if( db->init.orphanTrigger ){
   117875         assert( iDb==1 );
   117876       }else{
   117877         pData->rc = rc;
   117878         if( rc==SQLITE_NOMEM ){
   117879           sqlite3OomFault(db);
   117880         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
   117881           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
   117882         }
   117883       }
   117884     }
   117885     sqlite3_finalize(pStmt);
   117886   }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
   117887     corruptSchema(pData, argv[0], 0);
   117888   }else{
   117889     /* If the SQL column is blank it means this is an index that
   117890     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   117891     ** constraint for a CREATE TABLE.  The index should have already
   117892     ** been created when we processed the CREATE TABLE.  All we have
   117893     ** to do here is record the root page number for that index.
   117894     */
   117895     Index *pIndex;
   117896     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
   117897     if( pIndex==0 ){
   117898       /* This can occur if there exists an index on a TEMP table which
   117899       ** has the same name as another index on a permanent index.  Since
   117900       ** the permanent table is hidden by the TEMP table, we can also
   117901       ** safely ignore the index on the permanent table.
   117902       */
   117903       /* Do Nothing */;
   117904     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
   117905       corruptSchema(pData, argv[0], "invalid rootpage");
   117906     }
   117907   }
   117908   return 0;
   117909 }
   117910 
   117911 /*
   117912 ** Attempt to read the database schema and initialize internal
   117913 ** data structures for a single database file.  The index of the
   117914 ** database file is given by iDb.  iDb==0 is used for the main
   117915 ** database.  iDb==1 should never be used.  iDb>=2 is used for
   117916 ** auxiliary databases.  Return one of the SQLITE_ error codes to
   117917 ** indicate success or failure.
   117918 */
   117919 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
   117920   int rc;
   117921   int i;
   117922 #ifndef SQLITE_OMIT_DEPRECATED
   117923   int size;
   117924 #endif
   117925   Db *pDb;
   117926   char const *azArg[4];
   117927   int meta[5];
   117928   InitData initData;
   117929   const char *zMasterName;
   117930   int openedTransaction = 0;
   117931 
   117932   assert( iDb>=0 && iDb<db->nDb );
   117933   assert( db->aDb[iDb].pSchema );
   117934   assert( sqlite3_mutex_held(db->mutex) );
   117935   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   117936 
   117937   db->init.busy = 1;
   117938 
   117939   /* Construct the in-memory representation schema tables (sqlite_master or
   117940   ** sqlite_temp_master) by invoking the parser directly.  The appropriate
   117941   ** table name will be inserted automatically by the parser so we can just
   117942   ** use the abbreviation "x" here.  The parser will also automatically tag
   117943   ** the schema table as read-only. */
   117944   azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
   117945   azArg[1] = "1";
   117946   azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
   117947                             "rootpage int,sql text)";
   117948   azArg[3] = 0;
   117949   initData.db = db;
   117950   initData.iDb = iDb;
   117951   initData.rc = SQLITE_OK;
   117952   initData.pzErrMsg = pzErrMsg;
   117953   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   117954   if( initData.rc ){
   117955     rc = initData.rc;
   117956     goto error_out;
   117957   }
   117958 
   117959   /* Create a cursor to hold the database open
   117960   */
   117961   pDb = &db->aDb[iDb];
   117962   if( pDb->pBt==0 ){
   117963     assert( iDb==1 );
   117964     DbSetProperty(db, 1, DB_SchemaLoaded);
   117965     rc = SQLITE_OK;
   117966     goto error_out;
   117967   }
   117968 
   117969   /* If there is not already a read-only (or read-write) transaction opened
   117970   ** on the b-tree database, open one now. If a transaction is opened, it
   117971   ** will be closed before this function returns.  */
   117972   sqlite3BtreeEnter(pDb->pBt);
   117973   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
   117974     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
   117975     if( rc!=SQLITE_OK ){
   117976       sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
   117977       goto initone_error_out;
   117978     }
   117979     openedTransaction = 1;
   117980   }
   117981 
   117982   /* Get the database meta information.
   117983   **
   117984   ** Meta values are as follows:
   117985   **    meta[0]   Schema cookie.  Changes with each schema change.
   117986   **    meta[1]   File format of schema layer.
   117987   **    meta[2]   Size of the page cache.
   117988   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
   117989   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
   117990   **    meta[5]   User version
   117991   **    meta[6]   Incremental vacuum mode
   117992   **    meta[7]   unused
   117993   **    meta[8]   unused
   117994   **    meta[9]   unused
   117995   **
   117996   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
   117997   ** the possible values of meta[4].
   117998   */
   117999   for(i=0; i<ArraySize(meta); i++){
   118000     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   118001   }
   118002   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
   118003 
   118004   /* If opening a non-empty database, check the text encoding. For the
   118005   ** main database, set sqlite3.enc to the encoding of the main database.
   118006   ** For an attached db, it is an error if the encoding is not the same
   118007   ** as sqlite3.enc.
   118008   */
   118009   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
   118010     if( iDb==0 ){
   118011 #ifndef SQLITE_OMIT_UTF16
   118012       u8 encoding;
   118013       /* If opening the main database, set ENC(db). */
   118014       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
   118015       if( encoding==0 ) encoding = SQLITE_UTF8;
   118016       ENC(db) = encoding;
   118017 #else
   118018       ENC(db) = SQLITE_UTF8;
   118019 #endif
   118020     }else{
   118021       /* If opening an attached database, the encoding much match ENC(db) */
   118022       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
   118023         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
   118024             " text encoding as main database");
   118025         rc = SQLITE_ERROR;
   118026         goto initone_error_out;
   118027       }
   118028     }
   118029   }else{
   118030     DbSetProperty(db, iDb, DB_Empty);
   118031   }
   118032   pDb->pSchema->enc = ENC(db);
   118033 
   118034   if( pDb->pSchema->cache_size==0 ){
   118035 #ifndef SQLITE_OMIT_DEPRECATED
   118036     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
   118037     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   118038     pDb->pSchema->cache_size = size;
   118039 #else
   118040     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
   118041 #endif
   118042     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   118043   }
   118044 
   118045   /*
   118046   ** file_format==1    Version 3.0.0.
   118047   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   118048   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
   118049   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
   118050   */
   118051   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
   118052   if( pDb->pSchema->file_format==0 ){
   118053     pDb->pSchema->file_format = 1;
   118054   }
   118055   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
   118056     sqlite3SetString(pzErrMsg, db, "unsupported file format");
   118057     rc = SQLITE_ERROR;
   118058     goto initone_error_out;
   118059   }
   118060 
   118061   /* Ticket #2804:  When we open a database in the newer file format,
   118062   ** clear the legacy_file_format pragma flag so that a VACUUM will
   118063   ** not downgrade the database and thus invalidate any descending
   118064   ** indices that the user might have created.
   118065   */
   118066   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
   118067     db->flags &= ~SQLITE_LegacyFileFmt;
   118068   }
   118069 
   118070   /* Read the schema information out of the schema tables
   118071   */
   118072   assert( db->init.busy );
   118073   {
   118074     char *zSql;
   118075     zSql = sqlite3MPrintf(db,
   118076         "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
   118077         db->aDb[iDb].zDbSName, zMasterName);
   118078 #ifndef SQLITE_OMIT_AUTHORIZATION
   118079     {
   118080       sqlite3_xauth xAuth;
   118081       xAuth = db->xAuth;
   118082       db->xAuth = 0;
   118083 #endif
   118084       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   118085 #ifndef SQLITE_OMIT_AUTHORIZATION
   118086       db->xAuth = xAuth;
   118087     }
   118088 #endif
   118089     if( rc==SQLITE_OK ) rc = initData.rc;
   118090     sqlite3DbFree(db, zSql);
   118091 #ifndef SQLITE_OMIT_ANALYZE
   118092     if( rc==SQLITE_OK ){
   118093       sqlite3AnalysisLoad(db, iDb);
   118094     }
   118095 #endif
   118096   }
   118097   if( db->mallocFailed ){
   118098     rc = SQLITE_NOMEM_BKPT;
   118099     sqlite3ResetAllSchemasOfConnection(db);
   118100   }
   118101   if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
   118102     /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
   118103     ** the schema loaded, even if errors occurred. In this situation the
   118104     ** current sqlite3_prepare() operation will fail, but the following one
   118105     ** will attempt to compile the supplied statement against whatever subset
   118106     ** of the schema was loaded before the error occurred. The primary
   118107     ** purpose of this is to allow access to the sqlite_master table
   118108     ** even when its contents have been corrupted.
   118109     */
   118110     DbSetProperty(db, iDb, DB_SchemaLoaded);
   118111     rc = SQLITE_OK;
   118112   }
   118113 
   118114   /* Jump here for an error that occurs after successfully allocating
   118115   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
   118116   ** before that point, jump to error_out.
   118117   */
   118118 initone_error_out:
   118119   if( openedTransaction ){
   118120     sqlite3BtreeCommit(pDb->pBt);
   118121   }
   118122   sqlite3BtreeLeave(pDb->pBt);
   118123 
   118124 error_out:
   118125   if( rc ){
   118126     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   118127       sqlite3OomFault(db);
   118128     }
   118129     sqlite3ResetOneSchema(db, iDb);
   118130   }
   118131   db->init.busy = 0;
   118132   return rc;
   118133 }
   118134 
   118135 /*
   118136 ** Initialize all database files - the main database file, the file
   118137 ** used to store temporary tables, and any additional database files
   118138 ** created using ATTACH statements.  Return a success code.  If an
   118139 ** error occurs, write an error message into *pzErrMsg.
   118140 **
   118141 ** After a database is initialized, the DB_SchemaLoaded bit is set
   118142 ** bit is set in the flags field of the Db structure. If the database
   118143 ** file was of zero-length, then the DB_Empty flag is also set.
   118144 */
   118145 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   118146   int i, rc;
   118147   int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
   118148 
   118149   assert( sqlite3_mutex_held(db->mutex) );
   118150   assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
   118151   assert( db->init.busy==0 );
   118152   ENC(db) = SCHEMA_ENC(db);
   118153   assert( db->nDb>0 );
   118154   /* Do the main schema first */
   118155   if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
   118156     rc = sqlite3InitOne(db, 0, pzErrMsg);
   118157     if( rc ) return rc;
   118158   }
   118159   /* All other schemas after the main schema. The "temp" schema must be last */
   118160   for(i=db->nDb-1; i>0; i--){
   118161     if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
   118162       rc = sqlite3InitOne(db, i, pzErrMsg);
   118163       if( rc ) return rc;
   118164     }
   118165   }
   118166   if( commit_internal ){
   118167     sqlite3CommitInternalChanges(db);
   118168   }
   118169   return SQLITE_OK;
   118170 }
   118171 
   118172 /*
   118173 ** This routine is a no-op if the database schema is already initialized.
   118174 ** Otherwise, the schema is loaded. An error code is returned.
   118175 */
   118176 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
   118177   int rc = SQLITE_OK;
   118178   sqlite3 *db = pParse->db;
   118179   assert( sqlite3_mutex_held(db->mutex) );
   118180   if( !db->init.busy ){
   118181     rc = sqlite3Init(db, &pParse->zErrMsg);
   118182   }
   118183   if( rc!=SQLITE_OK ){
   118184     pParse->rc = rc;
   118185     pParse->nErr++;
   118186   }
   118187   return rc;
   118188 }
   118189 
   118190 
   118191 /*
   118192 ** Check schema cookies in all databases.  If any cookie is out
   118193 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
   118194 ** make no changes to pParse->rc.
   118195 */
   118196 static void schemaIsValid(Parse *pParse){
   118197   sqlite3 *db = pParse->db;
   118198   int iDb;
   118199   int rc;
   118200   int cookie;
   118201 
   118202   assert( pParse->checkSchema );
   118203   assert( sqlite3_mutex_held(db->mutex) );
   118204   for(iDb=0; iDb<db->nDb; iDb++){
   118205     int openedTransaction = 0;         /* True if a transaction is opened */
   118206     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
   118207     if( pBt==0 ) continue;
   118208 
   118209     /* If there is not already a read-only (or read-write) transaction opened
   118210     ** on the b-tree database, open one now. If a transaction is opened, it
   118211     ** will be closed immediately after reading the meta-value. */
   118212     if( !sqlite3BtreeIsInReadTrans(pBt) ){
   118213       rc = sqlite3BtreeBeginTrans(pBt, 0);
   118214       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   118215         sqlite3OomFault(db);
   118216       }
   118217       if( rc!=SQLITE_OK ) return;
   118218       openedTransaction = 1;
   118219     }
   118220 
   118221     /* Read the schema cookie from the database. If it does not match the
   118222     ** value stored as part of the in-memory schema representation,
   118223     ** set Parse.rc to SQLITE_SCHEMA. */
   118224     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
   118225     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   118226     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   118227       sqlite3ResetOneSchema(db, iDb);
   118228       pParse->rc = SQLITE_SCHEMA;
   118229     }
   118230 
   118231     /* Close the transaction, if one was opened. */
   118232     if( openedTransaction ){
   118233       sqlite3BtreeCommit(pBt);
   118234     }
   118235   }
   118236 }
   118237 
   118238 /*
   118239 ** Convert a schema pointer into the iDb index that indicates
   118240 ** which database file in db->aDb[] the schema refers to.
   118241 **
   118242 ** If the same database is attached more than once, the first
   118243 ** attached database is returned.
   118244 */
   118245 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
   118246   int i = -1000000;
   118247 
   118248   /* If pSchema is NULL, then return -1000000. This happens when code in
   118249   ** expr.c is trying to resolve a reference to a transient table (i.e. one
   118250   ** created by a sub-select). In this case the return value of this
   118251   ** function should never be used.
   118252   **
   118253   ** We return -1000000 instead of the more usual -1 simply because using
   118254   ** -1000000 as the incorrect index into db->aDb[] is much
   118255   ** more likely to cause a segfault than -1 (of course there are assert()
   118256   ** statements too, but it never hurts to play the odds).
   118257   */
   118258   assert( sqlite3_mutex_held(db->mutex) );
   118259   if( pSchema ){
   118260     for(i=0; 1; i++){
   118261       assert( i<db->nDb );
   118262       if( db->aDb[i].pSchema==pSchema ){
   118263         break;
   118264       }
   118265     }
   118266     assert( i>=0 && i<db->nDb );
   118267   }
   118268   return i;
   118269 }
   118270 
   118271 /*
   118272 ** Free all memory allocations in the pParse object
   118273 */
   118274 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
   118275   sqlite3 *db = pParse->db;
   118276   sqlite3DbFree(db, pParse->aLabel);
   118277   sqlite3ExprListDelete(db, pParse->pConstExpr);
   118278   if( db ){
   118279     assert( db->lookaside.bDisable >= pParse->disableLookaside );
   118280     db->lookaside.bDisable -= pParse->disableLookaside;
   118281   }
   118282   pParse->disableLookaside = 0;
   118283 }
   118284 
   118285 /*
   118286 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   118287 */
   118288 static int sqlite3Prepare(
   118289   sqlite3 *db,              /* Database handle. */
   118290   const char *zSql,         /* UTF-8 encoded SQL statement. */
   118291   int nBytes,               /* Length of zSql in bytes. */
   118292   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
   118293   Vdbe *pReprepare,         /* VM being reprepared */
   118294   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118295   const char **pzTail       /* OUT: End of parsed string */
   118296 ){
   118297   char *zErrMsg = 0;        /* Error message */
   118298   int rc = SQLITE_OK;       /* Result code */
   118299   int i;                    /* Loop counter */
   118300   Parse sParse;             /* Parsing context */
   118301 
   118302   memset(&sParse, 0, PARSE_HDR_SZ);
   118303   memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
   118304   sParse.pReprepare = pReprepare;
   118305   assert( ppStmt && *ppStmt==0 );
   118306   /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
   118307   assert( sqlite3_mutex_held(db->mutex) );
   118308 
   118309   /* For a long-term use prepared statement avoid the use of
   118310   ** lookaside memory.
   118311   */
   118312   if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
   118313     sParse.disableLookaside++;
   118314     db->lookaside.bDisable++;
   118315   }
   118316 
   118317   /* Check to verify that it is possible to get a read lock on all
   118318   ** database schemas.  The inability to get a read lock indicates that
   118319   ** some other database connection is holding a write-lock, which in
   118320   ** turn means that the other connection has made uncommitted changes
   118321   ** to the schema.
   118322   **
   118323   ** Were we to proceed and prepare the statement against the uncommitted
   118324   ** schema changes and if those schema changes are subsequently rolled
   118325   ** back and different changes are made in their place, then when this
   118326   ** prepared statement goes to run the schema cookie would fail to detect
   118327   ** the schema change.  Disaster would follow.
   118328   **
   118329   ** This thread is currently holding mutexes on all Btrees (because
   118330   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   118331   ** is not possible for another thread to start a new schema change
   118332   ** while this routine is running.  Hence, we do not need to hold
   118333   ** locks on the schema, we just need to make sure nobody else is
   118334   ** holding them.
   118335   **
   118336   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   118337   ** but it does *not* override schema lock detection, so this all still
   118338   ** works even if READ_UNCOMMITTED is set.
   118339   */
   118340   for(i=0; i<db->nDb; i++) {
   118341     Btree *pBt = db->aDb[i].pBt;
   118342     if( pBt ){
   118343       assert( sqlite3BtreeHoldsMutex(pBt) );
   118344       rc = sqlite3BtreeSchemaLocked(pBt);
   118345       if( rc ){
   118346         const char *zDb = db->aDb[i].zDbSName;
   118347         sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
   118348         testcase( db->flags & SQLITE_ReadUncommit );
   118349         goto end_prepare;
   118350       }
   118351     }
   118352   }
   118353 
   118354   sqlite3VtabUnlockList(db);
   118355 
   118356   sParse.db = db;
   118357   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
   118358     char *zSqlCopy;
   118359     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   118360     testcase( nBytes==mxLen );
   118361     testcase( nBytes==mxLen+1 );
   118362     if( nBytes>mxLen ){
   118363       sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
   118364       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
   118365       goto end_prepare;
   118366     }
   118367     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
   118368     if( zSqlCopy ){
   118369       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
   118370       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
   118371       sqlite3DbFree(db, zSqlCopy);
   118372     }else{
   118373       sParse.zTail = &zSql[nBytes];
   118374     }
   118375   }else{
   118376     sqlite3RunParser(&sParse, zSql, &zErrMsg);
   118377   }
   118378   assert( 0==sParse.nQueryLoop );
   118379 
   118380   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
   118381   if( sParse.checkSchema ){
   118382     schemaIsValid(&sParse);
   118383   }
   118384   if( db->mallocFailed ){
   118385     sParse.rc = SQLITE_NOMEM_BKPT;
   118386   }
   118387   if( pzTail ){
   118388     *pzTail = sParse.zTail;
   118389   }
   118390   rc = sParse.rc;
   118391 
   118392 #ifndef SQLITE_OMIT_EXPLAIN
   118393   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
   118394     static const char * const azColName[] = {
   118395        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
   118396        "selectid", "order", "from", "detail"
   118397     };
   118398     int iFirst, mx;
   118399     if( sParse.explain==2 ){
   118400       sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
   118401       iFirst = 8;
   118402       mx = 12;
   118403     }else{
   118404       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
   118405       iFirst = 0;
   118406       mx = 8;
   118407     }
   118408     for(i=iFirst; i<mx; i++){
   118409       sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
   118410                             azColName[i], SQLITE_STATIC);
   118411     }
   118412   }
   118413 #endif
   118414 
   118415   if( db->init.busy==0 ){
   118416     sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
   118417   }
   118418   if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
   118419     sqlite3VdbeFinalize(sParse.pVdbe);
   118420     assert(!(*ppStmt));
   118421   }else{
   118422     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
   118423   }
   118424 
   118425   if( zErrMsg ){
   118426     sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
   118427     sqlite3DbFree(db, zErrMsg);
   118428   }else{
   118429     sqlite3Error(db, rc);
   118430   }
   118431 
   118432   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   118433   while( sParse.pTriggerPrg ){
   118434     TriggerPrg *pT = sParse.pTriggerPrg;
   118435     sParse.pTriggerPrg = pT->pNext;
   118436     sqlite3DbFree(db, pT);
   118437   }
   118438 
   118439 end_prepare:
   118440 
   118441   sqlite3ParserReset(&sParse);
   118442   return rc;
   118443 }
   118444 static int sqlite3LockAndPrepare(
   118445   sqlite3 *db,              /* Database handle. */
   118446   const char *zSql,         /* UTF-8 encoded SQL statement. */
   118447   int nBytes,               /* Length of zSql in bytes. */
   118448   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
   118449   Vdbe *pOld,               /* VM being reprepared */
   118450   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118451   const char **pzTail       /* OUT: End of parsed string */
   118452 ){
   118453   int rc;
   118454   int cnt = 0;
   118455 
   118456 #ifdef SQLITE_ENABLE_API_ARMOR
   118457   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
   118458 #endif
   118459   *ppStmt = 0;
   118460   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
   118461     return SQLITE_MISUSE_BKPT;
   118462   }
   118463   sqlite3_mutex_enter(db->mutex);
   118464   sqlite3BtreeEnterAll(db);
   118465   do{
   118466     /* Make multiple attempts to compile the SQL, until it either succeeds
   118467     ** or encounters a permanent error.  A schema problem after one schema
   118468     ** reset is considered a permanent error. */
   118469     rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
   118470     assert( rc==SQLITE_OK || *ppStmt==0 );
   118471   }while( rc==SQLITE_ERROR_RETRY
   118472        || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
   118473   sqlite3BtreeLeaveAll(db);
   118474   rc = sqlite3ApiExit(db, rc);
   118475   assert( (rc&db->errMask)==rc );
   118476   sqlite3_mutex_leave(db->mutex);
   118477   return rc;
   118478 }
   118479 
   118480 /*
   118481 ** Rerun the compilation of a statement after a schema change.
   118482 **
   118483 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
   118484 ** if the statement cannot be recompiled because another connection has
   118485 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
   118486 ** occurs, return SQLITE_SCHEMA.
   118487 */
   118488 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
   118489   int rc;
   118490   sqlite3_stmt *pNew;
   118491   const char *zSql;
   118492   sqlite3 *db;
   118493   u8 prepFlags;
   118494 
   118495   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
   118496   zSql = sqlite3_sql((sqlite3_stmt *)p);
   118497   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   118498   db = sqlite3VdbeDb(p);
   118499   assert( sqlite3_mutex_held(db->mutex) );
   118500   prepFlags = sqlite3VdbePrepareFlags(p);
   118501   rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
   118502   if( rc ){
   118503     if( rc==SQLITE_NOMEM ){
   118504       sqlite3OomFault(db);
   118505     }
   118506     assert( pNew==0 );
   118507     return rc;
   118508   }else{
   118509     assert( pNew!=0 );
   118510   }
   118511   sqlite3VdbeSwap((Vdbe*)pNew, p);
   118512   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
   118513   sqlite3VdbeResetStepResult((Vdbe*)pNew);
   118514   sqlite3VdbeFinalize((Vdbe*)pNew);
   118515   return SQLITE_OK;
   118516 }
   118517 
   118518 
   118519 /*
   118520 ** Two versions of the official API.  Legacy and new use.  In the legacy
   118521 ** version, the original SQL text is not saved in the prepared statement
   118522 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   118523 ** sqlite3_step().  In the new version, the original SQL text is retained
   118524 ** and the statement is automatically recompiled if an schema change
   118525 ** occurs.
   118526 */
   118527 SQLITE_API int sqlite3_prepare(
   118528   sqlite3 *db,              /* Database handle. */
   118529   const char *zSql,         /* UTF-8 encoded SQL statement. */
   118530   int nBytes,               /* Length of zSql in bytes. */
   118531   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118532   const char **pzTail       /* OUT: End of parsed string */
   118533 ){
   118534   int rc;
   118535   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
   118536   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   118537   return rc;
   118538 }
   118539 SQLITE_API int sqlite3_prepare_v2(
   118540   sqlite3 *db,              /* Database handle. */
   118541   const char *zSql,         /* UTF-8 encoded SQL statement. */
   118542   int nBytes,               /* Length of zSql in bytes. */
   118543   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118544   const char **pzTail       /* OUT: End of parsed string */
   118545 ){
   118546   int rc;
   118547   /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
   118548   ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
   118549   ** parameter.
   118550   **
   118551   ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
   118552   rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
   118553                              ppStmt,pzTail);
   118554   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
   118555   return rc;
   118556 }
   118557 SQLITE_API int sqlite3_prepare_v3(
   118558   sqlite3 *db,              /* Database handle. */
   118559   const char *zSql,         /* UTF-8 encoded SQL statement. */
   118560   int nBytes,               /* Length of zSql in bytes. */
   118561   unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
   118562   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118563   const char **pzTail       /* OUT: End of parsed string */
   118564 ){
   118565   int rc;
   118566   /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
   118567   ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
   118568   ** which is a bit array consisting of zero or more of the
   118569   ** SQLITE_PREPARE_* flags.
   118570   **
   118571   ** Proof by comparison to the implementation of sqlite3_prepare_v2()
   118572   ** directly above. */
   118573   rc = sqlite3LockAndPrepare(db,zSql,nBytes,
   118574                  SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
   118575                  0,ppStmt,pzTail);
   118576   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
   118577   return rc;
   118578 }
   118579 
   118580 
   118581 #ifndef SQLITE_OMIT_UTF16
   118582 /*
   118583 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   118584 */
   118585 static int sqlite3Prepare16(
   118586   sqlite3 *db,              /* Database handle. */
   118587   const void *zSql,         /* UTF-16 encoded SQL statement. */
   118588   int nBytes,               /* Length of zSql in bytes. */
   118589   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
   118590   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118591   const void **pzTail       /* OUT: End of parsed string */
   118592 ){
   118593   /* This function currently works by first transforming the UTF-16
   118594   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
   118595   ** tricky bit is figuring out the pointer to return in *pzTail.
   118596   */
   118597   char *zSql8;
   118598   const char *zTail8 = 0;
   118599   int rc = SQLITE_OK;
   118600 
   118601 #ifdef SQLITE_ENABLE_API_ARMOR
   118602   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
   118603 #endif
   118604   *ppStmt = 0;
   118605   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
   118606     return SQLITE_MISUSE_BKPT;
   118607   }
   118608   if( nBytes>=0 ){
   118609     int sz;
   118610     const char *z = (const char*)zSql;
   118611     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
   118612     nBytes = sz;
   118613   }
   118614   sqlite3_mutex_enter(db->mutex);
   118615   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
   118616   if( zSql8 ){
   118617     rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
   118618   }
   118619 
   118620   if( zTail8 && pzTail ){
   118621     /* If sqlite3_prepare returns a tail pointer, we calculate the
   118622     ** equivalent pointer into the UTF-16 string by counting the unicode
   118623     ** characters between zSql8 and zTail8, and then returning a pointer
   118624     ** the same number of characters into the UTF-16 string.
   118625     */
   118626     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
   118627     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   118628   }
   118629   sqlite3DbFree(db, zSql8);
   118630   rc = sqlite3ApiExit(db, rc);
   118631   sqlite3_mutex_leave(db->mutex);
   118632   return rc;
   118633 }
   118634 
   118635 /*
   118636 ** Two versions of the official API.  Legacy and new use.  In the legacy
   118637 ** version, the original SQL text is not saved in the prepared statement
   118638 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   118639 ** sqlite3_step().  In the new version, the original SQL text is retained
   118640 ** and the statement is automatically recompiled if an schema change
   118641 ** occurs.
   118642 */
   118643 SQLITE_API int sqlite3_prepare16(
   118644   sqlite3 *db,              /* Database handle. */
   118645   const void *zSql,         /* UTF-16 encoded SQL statement. */
   118646   int nBytes,               /* Length of zSql in bytes. */
   118647   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118648   const void **pzTail       /* OUT: End of parsed string */
   118649 ){
   118650   int rc;
   118651   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
   118652   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   118653   return rc;
   118654 }
   118655 SQLITE_API int sqlite3_prepare16_v2(
   118656   sqlite3 *db,              /* Database handle. */
   118657   const void *zSql,         /* UTF-16 encoded SQL statement. */
   118658   int nBytes,               /* Length of zSql in bytes. */
   118659   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118660   const void **pzTail       /* OUT: End of parsed string */
   118661 ){
   118662   int rc;
   118663   rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
   118664   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   118665   return rc;
   118666 }
   118667 SQLITE_API int sqlite3_prepare16_v3(
   118668   sqlite3 *db,              /* Database handle. */
   118669   const void *zSql,         /* UTF-16 encoded SQL statement. */
   118670   int nBytes,               /* Length of zSql in bytes. */
   118671   unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
   118672   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   118673   const void **pzTail       /* OUT: End of parsed string */
   118674 ){
   118675   int rc;
   118676   rc = sqlite3Prepare16(db,zSql,nBytes,
   118677          SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
   118678          ppStmt,pzTail);
   118679   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   118680   return rc;
   118681 }
   118682 
   118683 #endif /* SQLITE_OMIT_UTF16 */
   118684 
   118685 /************** End of prepare.c *********************************************/
   118686 /************** Begin file select.c ******************************************/
   118687 /*
   118688 ** 2001 September 15
   118689 **
   118690 ** The author disclaims copyright to this source code.  In place of
   118691 ** a legal notice, here is a blessing:
   118692 **
   118693 **    May you do good and not evil.
   118694 **    May you find forgiveness for yourself and forgive others.
   118695 **    May you share freely, never taking more than you give.
   118696 **
   118697 *************************************************************************
   118698 ** This file contains C code routines that are called by the parser
   118699 ** to handle SELECT statements in SQLite.
   118700 */
   118701 /* #include "sqliteInt.h" */
   118702 
   118703 /*
   118704 ** Trace output macros
   118705 */
   118706 #if SELECTTRACE_ENABLED
   118707 /***/ int sqlite3SelectTrace = 0;
   118708 # define SELECTTRACE(K,P,S,X)  \
   118709   if(sqlite3SelectTrace&(K))   \
   118710     sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
   118711         (S)->zSelName,(S)),\
   118712     sqlite3DebugPrintf X
   118713 #else
   118714 # define SELECTTRACE(K,P,S,X)
   118715 #endif
   118716 
   118717 
   118718 /*
   118719 ** An instance of the following object is used to record information about
   118720 ** how to process the DISTINCT keyword, to simplify passing that information
   118721 ** into the selectInnerLoop() routine.
   118722 */
   118723 typedef struct DistinctCtx DistinctCtx;
   118724 struct DistinctCtx {
   118725   u8 isTnct;      /* True if the DISTINCT keyword is present */
   118726   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
   118727   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
   118728   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
   118729 };
   118730 
   118731 /*
   118732 ** An instance of the following object is used to record information about
   118733 ** the ORDER BY (or GROUP BY) clause of query is being coded.
   118734 */
   118735 typedef struct SortCtx SortCtx;
   118736 struct SortCtx {
   118737   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
   118738   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
   118739   int iECursor;         /* Cursor number for the sorter */
   118740   int regReturn;        /* Register holding block-output return address */
   118741   int labelBkOut;       /* Start label for the block-output subroutine */
   118742   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
   118743   int labelDone;        /* Jump here when done, ex: LIMIT reached */
   118744   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
   118745   u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
   118746 };
   118747 #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
   118748 
   118749 /*
   118750 ** Delete all the content of a Select structure.  Deallocate the structure
   118751 ** itself only if bFree is true.
   118752 */
   118753 static void clearSelect(sqlite3 *db, Select *p, int bFree){
   118754   while( p ){
   118755     Select *pPrior = p->pPrior;
   118756     sqlite3ExprListDelete(db, p->pEList);
   118757     sqlite3SrcListDelete(db, p->pSrc);
   118758     sqlite3ExprDelete(db, p->pWhere);
   118759     sqlite3ExprListDelete(db, p->pGroupBy);
   118760     sqlite3ExprDelete(db, p->pHaving);
   118761     sqlite3ExprListDelete(db, p->pOrderBy);
   118762     sqlite3ExprDelete(db, p->pLimit);
   118763     if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
   118764     if( bFree ) sqlite3DbFreeNN(db, p);
   118765     p = pPrior;
   118766     bFree = 1;
   118767   }
   118768 }
   118769 
   118770 /*
   118771 ** Initialize a SelectDest structure.
   118772 */
   118773 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   118774   pDest->eDest = (u8)eDest;
   118775   pDest->iSDParm = iParm;
   118776   pDest->zAffSdst = 0;
   118777   pDest->iSdst = 0;
   118778   pDest->nSdst = 0;
   118779 }
   118780 
   118781 
   118782 /*
   118783 ** Allocate a new Select structure and return a pointer to that
   118784 ** structure.
   118785 */
   118786 SQLITE_PRIVATE Select *sqlite3SelectNew(
   118787   Parse *pParse,        /* Parsing context */
   118788   ExprList *pEList,     /* which columns to include in the result */
   118789   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
   118790   Expr *pWhere,         /* the WHERE clause */
   118791   ExprList *pGroupBy,   /* the GROUP BY clause */
   118792   Expr *pHaving,        /* the HAVING clause */
   118793   ExprList *pOrderBy,   /* the ORDER BY clause */
   118794   u32 selFlags,         /* Flag parameters, such as SF_Distinct */
   118795   Expr *pLimit          /* LIMIT value.  NULL means not used */
   118796 ){
   118797   Select *pNew;
   118798   Select standin;
   118799   pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
   118800   if( pNew==0 ){
   118801     assert( pParse->db->mallocFailed );
   118802     pNew = &standin;
   118803   }
   118804   if( pEList==0 ){
   118805     pEList = sqlite3ExprListAppend(pParse, 0,
   118806                                    sqlite3Expr(pParse->db,TK_ASTERISK,0));
   118807   }
   118808   pNew->pEList = pEList;
   118809   pNew->op = TK_SELECT;
   118810   pNew->selFlags = selFlags;
   118811   pNew->iLimit = 0;
   118812   pNew->iOffset = 0;
   118813 #if SELECTTRACE_ENABLED
   118814   pNew->zSelName[0] = 0;
   118815 #endif
   118816   pNew->addrOpenEphm[0] = -1;
   118817   pNew->addrOpenEphm[1] = -1;
   118818   pNew->nSelectRow = 0;
   118819   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
   118820   pNew->pSrc = pSrc;
   118821   pNew->pWhere = pWhere;
   118822   pNew->pGroupBy = pGroupBy;
   118823   pNew->pHaving = pHaving;
   118824   pNew->pOrderBy = pOrderBy;
   118825   pNew->pPrior = 0;
   118826   pNew->pNext = 0;
   118827   pNew->pLimit = pLimit;
   118828   pNew->pWith = 0;
   118829   if( pParse->db->mallocFailed ) {
   118830     clearSelect(pParse->db, pNew, pNew!=&standin);
   118831     pNew = 0;
   118832   }else{
   118833     assert( pNew->pSrc!=0 || pParse->nErr>0 );
   118834   }
   118835   assert( pNew!=&standin );
   118836   return pNew;
   118837 }
   118838 
   118839 #if SELECTTRACE_ENABLED
   118840 /*
   118841 ** Set the name of a Select object
   118842 */
   118843 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
   118844   if( p && zName ){
   118845     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
   118846   }
   118847 }
   118848 #endif
   118849 
   118850 
   118851 /*
   118852 ** Delete the given Select structure and all of its substructures.
   118853 */
   118854 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
   118855   if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
   118856 }
   118857 
   118858 /*
   118859 ** Return a pointer to the right-most SELECT statement in a compound.
   118860 */
   118861 static Select *findRightmost(Select *p){
   118862   while( p->pNext ) p = p->pNext;
   118863   return p;
   118864 }
   118865 
   118866 /*
   118867 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
   118868 ** type of join.  Return an integer constant that expresses that type
   118869 ** in terms of the following bit values:
   118870 **
   118871 **     JT_INNER
   118872 **     JT_CROSS
   118873 **     JT_OUTER
   118874 **     JT_NATURAL
   118875 **     JT_LEFT
   118876 **     JT_RIGHT
   118877 **
   118878 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   118879 **
   118880 ** If an illegal or unsupported join type is seen, then still return
   118881 ** a join type, but put an error in the pParse structure.
   118882 */
   118883 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   118884   int jointype = 0;
   118885   Token *apAll[3];
   118886   Token *p;
   118887                              /*   0123456789 123456789 123456789 123 */
   118888   static const char zKeyText[] = "naturaleftouterightfullinnercross";
   118889   static const struct {
   118890     u8 i;        /* Beginning of keyword text in zKeyText[] */
   118891     u8 nChar;    /* Length of the keyword in characters */
   118892     u8 code;     /* Join type mask */
   118893   } aKeyword[] = {
   118894     /* natural */ { 0,  7, JT_NATURAL                },
   118895     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
   118896     /* outer   */ { 10, 5, JT_OUTER                  },
   118897     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
   118898     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
   118899     /* inner   */ { 23, 5, JT_INNER                  },
   118900     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
   118901   };
   118902   int i, j;
   118903   apAll[0] = pA;
   118904   apAll[1] = pB;
   118905   apAll[2] = pC;
   118906   for(i=0; i<3 && apAll[i]; i++){
   118907     p = apAll[i];
   118908     for(j=0; j<ArraySize(aKeyword); j++){
   118909       if( p->n==aKeyword[j].nChar
   118910           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
   118911         jointype |= aKeyword[j].code;
   118912         break;
   118913       }
   118914     }
   118915     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
   118916     if( j>=ArraySize(aKeyword) ){
   118917       jointype |= JT_ERROR;
   118918       break;
   118919     }
   118920   }
   118921   if(
   118922      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   118923      (jointype & JT_ERROR)!=0
   118924   ){
   118925     const char *zSp = " ";
   118926     assert( pB!=0 );
   118927     if( pC==0 ){ zSp++; }
   118928     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   118929        "%T %T%s%T", pA, pB, zSp, pC);
   118930     jointype = JT_INNER;
   118931   }else if( (jointype & JT_OUTER)!=0
   118932          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
   118933     sqlite3ErrorMsg(pParse,
   118934       "RIGHT and FULL OUTER JOINs are not currently supported");
   118935     jointype = JT_INNER;
   118936   }
   118937   return jointype;
   118938 }
   118939 
   118940 /*
   118941 ** Return the index of a column in a table.  Return -1 if the column
   118942 ** is not contained in the table.
   118943 */
   118944 static int columnIndex(Table *pTab, const char *zCol){
   118945   int i;
   118946   for(i=0; i<pTab->nCol; i++){
   118947     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   118948   }
   118949   return -1;
   118950 }
   118951 
   118952 /*
   118953 ** Search the first N tables in pSrc, from left to right, looking for a
   118954 ** table that has a column named zCol.
   118955 **
   118956 ** When found, set *piTab and *piCol to the table index and column index
   118957 ** of the matching column and return TRUE.
   118958 **
   118959 ** If not found, return FALSE.
   118960 */
   118961 static int tableAndColumnIndex(
   118962   SrcList *pSrc,       /* Array of tables to search */
   118963   int N,               /* Number of tables in pSrc->a[] to search */
   118964   const char *zCol,    /* Name of the column we are looking for */
   118965   int *piTab,          /* Write index of pSrc->a[] here */
   118966   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
   118967 ){
   118968   int i;               /* For looping over tables in pSrc */
   118969   int iCol;            /* Index of column matching zCol */
   118970 
   118971   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   118972   for(i=0; i<N; i++){
   118973     iCol = columnIndex(pSrc->a[i].pTab, zCol);
   118974     if( iCol>=0 ){
   118975       if( piTab ){
   118976         *piTab = i;
   118977         *piCol = iCol;
   118978       }
   118979       return 1;
   118980     }
   118981   }
   118982   return 0;
   118983 }
   118984 
   118985 /*
   118986 ** This function is used to add terms implied by JOIN syntax to the
   118987 ** WHERE clause expression of a SELECT statement. The new term, which
   118988 ** is ANDed with the existing WHERE clause, is of the form:
   118989 **
   118990 **    (tab1.col1 = tab2.col2)
   118991 **
   118992 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
   118993 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
   118994 ** column iColRight of tab2.
   118995 */
   118996 static void addWhereTerm(
   118997   Parse *pParse,                  /* Parsing context */
   118998   SrcList *pSrc,                  /* List of tables in FROM clause */
   118999   int iLeft,                      /* Index of first table to join in pSrc */
   119000   int iColLeft,                   /* Index of column in first table */
   119001   int iRight,                     /* Index of second table in pSrc */
   119002   int iColRight,                  /* Index of column in second table */
   119003   int isOuterJoin,                /* True if this is an OUTER join */
   119004   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
   119005 ){
   119006   sqlite3 *db = pParse->db;
   119007   Expr *pE1;
   119008   Expr *pE2;
   119009   Expr *pEq;
   119010 
   119011   assert( iLeft<iRight );
   119012   assert( pSrc->nSrc>iRight );
   119013   assert( pSrc->a[iLeft].pTab );
   119014   assert( pSrc->a[iRight].pTab );
   119015 
   119016   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
   119017   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
   119018 
   119019   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
   119020   if( pEq && isOuterJoin ){
   119021     ExprSetProperty(pEq, EP_FromJoin);
   119022     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
   119023     ExprSetVVAProperty(pEq, EP_NoReduce);
   119024     pEq->iRightJoinTable = (i16)pE2->iTable;
   119025   }
   119026   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
   119027 }
   119028 
   119029 /*
   119030 ** Set the EP_FromJoin property on all terms of the given expression.
   119031 ** And set the Expr.iRightJoinTable to iTable for every term in the
   119032 ** expression.
   119033 **
   119034 ** The EP_FromJoin property is used on terms of an expression to tell
   119035 ** the LEFT OUTER JOIN processing logic that this term is part of the
   119036 ** join restriction specified in the ON or USING clause and not a part
   119037 ** of the more general WHERE clause.  These terms are moved over to the
   119038 ** WHERE clause during join processing but we need to remember that they
   119039 ** originated in the ON or USING clause.
   119040 **
   119041 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
   119042 ** expression depends on table iRightJoinTable even if that table is not
   119043 ** explicitly mentioned in the expression.  That information is needed
   119044 ** for cases like this:
   119045 **
   119046 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   119047 **
   119048 ** The where clause needs to defer the handling of the t1.x=5
   119049 ** term until after the t2 loop of the join.  In that way, a
   119050 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   119051 ** defer the handling of t1.x=5, it will be processed immediately
   119052 ** after the t1 loop and rows with t1.x!=5 will never appear in
   119053 ** the output, which is incorrect.
   119054 */
   119055 static void setJoinExpr(Expr *p, int iTable){
   119056   while( p ){
   119057     ExprSetProperty(p, EP_FromJoin);
   119058     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
   119059     ExprSetVVAProperty(p, EP_NoReduce);
   119060     p->iRightJoinTable = (i16)iTable;
   119061     if( p->op==TK_FUNCTION && p->x.pList ){
   119062       int i;
   119063       for(i=0; i<p->x.pList->nExpr; i++){
   119064         setJoinExpr(p->x.pList->a[i].pExpr, iTable);
   119065       }
   119066     }
   119067     setJoinExpr(p->pLeft, iTable);
   119068     p = p->pRight;
   119069   }
   119070 }
   119071 
   119072 /*
   119073 ** This routine processes the join information for a SELECT statement.
   119074 ** ON and USING clauses are converted into extra terms of the WHERE clause.
   119075 ** NATURAL joins also create extra WHERE clause terms.
   119076 **
   119077 ** The terms of a FROM clause are contained in the Select.pSrc structure.
   119078 ** The left most table is the first entry in Select.pSrc.  The right-most
   119079 ** table is the last entry.  The join operator is held in the entry to
   119080 ** the left.  Thus entry 0 contains the join operator for the join between
   119081 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
   119082 ** also attached to the left entry.
   119083 **
   119084 ** This routine returns the number of errors encountered.
   119085 */
   119086 static int sqliteProcessJoin(Parse *pParse, Select *p){
   119087   SrcList *pSrc;                  /* All tables in the FROM clause */
   119088   int i, j;                       /* Loop counters */
   119089   struct SrcList_item *pLeft;     /* Left table being joined */
   119090   struct SrcList_item *pRight;    /* Right table being joined */
   119091 
   119092   pSrc = p->pSrc;
   119093   pLeft = &pSrc->a[0];
   119094   pRight = &pLeft[1];
   119095   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   119096     Table *pRightTab = pRight->pTab;
   119097     int isOuter;
   119098 
   119099     if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
   119100     isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
   119101 
   119102     /* When the NATURAL keyword is present, add WHERE clause terms for
   119103     ** every column that the two tables have in common.
   119104     */
   119105     if( pRight->fg.jointype & JT_NATURAL ){
   119106       if( pRight->pOn || pRight->pUsing ){
   119107         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   119108            "an ON or USING clause", 0);
   119109         return 1;
   119110       }
   119111       for(j=0; j<pRightTab->nCol; j++){
   119112         char *zName;   /* Name of column in the right table */
   119113         int iLeft;     /* Matching left table */
   119114         int iLeftCol;  /* Matching column in the left table */
   119115 
   119116         zName = pRightTab->aCol[j].zName;
   119117         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
   119118           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
   119119                        isOuter, &p->pWhere);
   119120         }
   119121       }
   119122     }
   119123 
   119124     /* Disallow both ON and USING clauses in the same join
   119125     */
   119126     if( pRight->pOn && pRight->pUsing ){
   119127       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   119128         "clauses in the same join");
   119129       return 1;
   119130     }
   119131 
   119132     /* Add the ON clause to the end of the WHERE clause, connected by
   119133     ** an AND operator.
   119134     */
   119135     if( pRight->pOn ){
   119136       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   119137       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   119138       pRight->pOn = 0;
   119139     }
   119140 
   119141     /* Create extra terms on the WHERE clause for each column named
   119142     ** in the USING clause.  Example: If the two tables to be joined are
   119143     ** A and B and the USING clause names X, Y, and Z, then add this
   119144     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   119145     ** Report an error if any column mentioned in the USING clause is
   119146     ** not contained in both tables to be joined.
   119147     */
   119148     if( pRight->pUsing ){
   119149       IdList *pList = pRight->pUsing;
   119150       for(j=0; j<pList->nId; j++){
   119151         char *zName;     /* Name of the term in the USING clause */
   119152         int iLeft;       /* Table on the left with matching column name */
   119153         int iLeftCol;    /* Column number of matching column on the left */
   119154         int iRightCol;   /* Column number of matching column on the right */
   119155 
   119156         zName = pList->a[j].zName;
   119157         iRightCol = columnIndex(pRightTab, zName);
   119158         if( iRightCol<0
   119159          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
   119160         ){
   119161           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   119162             "not present in both tables", zName);
   119163           return 1;
   119164         }
   119165         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
   119166                      isOuter, &p->pWhere);
   119167       }
   119168     }
   119169   }
   119170   return 0;
   119171 }
   119172 
   119173 /* Forward reference */
   119174 static KeyInfo *keyInfoFromExprList(
   119175   Parse *pParse,       /* Parsing context */
   119176   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
   119177   int iStart,          /* Begin with this column of pList */
   119178   int nExtra           /* Add this many extra columns to the end */
   119179 );
   119180 
   119181 /*
   119182 ** Generate code that will push the record in registers regData
   119183 ** through regData+nData-1 onto the sorter.
   119184 */
   119185 static void pushOntoSorter(
   119186   Parse *pParse,         /* Parser context */
   119187   SortCtx *pSort,        /* Information about the ORDER BY clause */
   119188   Select *pSelect,       /* The whole SELECT statement */
   119189   int regData,           /* First register holding data to be sorted */
   119190   int regOrigData,       /* First register holding data before packing */
   119191   int nData,             /* Number of elements in the data array */
   119192   int nPrefixReg         /* No. of reg prior to regData available for use */
   119193 ){
   119194   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
   119195   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
   119196   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
   119197   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
   119198   int regBase;                                     /* Regs for sorter record */
   119199   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
   119200   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
   119201   int op;                            /* Opcode to add sorter record to sorter */
   119202   int iLimit;                        /* LIMIT counter */
   119203 
   119204   assert( bSeq==0 || bSeq==1 );
   119205   assert( nData==1 || regData==regOrigData || regOrigData==0 );
   119206   if( nPrefixReg ){
   119207     assert( nPrefixReg==nExpr+bSeq );
   119208     regBase = regData - nExpr - bSeq;
   119209   }else{
   119210     regBase = pParse->nMem + 1;
   119211     pParse->nMem += nBase;
   119212   }
   119213   assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
   119214   iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
   119215   pSort->labelDone = sqlite3VdbeMakeLabel(v);
   119216   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
   119217                           SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
   119218   if( bSeq ){
   119219     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
   119220   }
   119221   if( nPrefixReg==0 && nData>0 ){
   119222     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
   119223   }
   119224   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
   119225   if( nOBSat>0 ){
   119226     int regPrevKey;   /* The first nOBSat columns of the previous row */
   119227     int addrFirst;    /* Address of the OP_IfNot opcode */
   119228     int addrJmp;      /* Address of the OP_Jump opcode */
   119229     VdbeOp *pOp;      /* Opcode that opens the sorter */
   119230     int nKey;         /* Number of sorting key columns, including OP_Sequence */
   119231     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
   119232 
   119233     regPrevKey = pParse->nMem+1;
   119234     pParse->nMem += pSort->nOBSat;
   119235     nKey = nExpr - pSort->nOBSat + bSeq;
   119236     if( bSeq ){
   119237       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
   119238     }else{
   119239       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
   119240     }
   119241     VdbeCoverage(v);
   119242     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
   119243     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
   119244     if( pParse->db->mallocFailed ) return;
   119245     pOp->p2 = nKey + nData;
   119246     pKI = pOp->p4.pKeyInfo;
   119247     memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
   119248     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
   119249     testcase( pKI->nAllField > pKI->nKeyField+2 );
   119250     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
   119251                                            pKI->nAllField-pKI->nKeyField-1);
   119252     addrJmp = sqlite3VdbeCurrentAddr(v);
   119253     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
   119254     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
   119255     pSort->regReturn = ++pParse->nMem;
   119256     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
   119257     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
   119258     if( iLimit ){
   119259       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
   119260       VdbeCoverage(v);
   119261     }
   119262     sqlite3VdbeJumpHere(v, addrFirst);
   119263     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
   119264     sqlite3VdbeJumpHere(v, addrJmp);
   119265   }
   119266   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   119267     op = OP_SorterInsert;
   119268   }else{
   119269     op = OP_IdxInsert;
   119270   }
   119271   sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
   119272                        regBase+nOBSat, nBase-nOBSat);
   119273   if( iLimit ){
   119274     int addr;
   119275     int r1 = 0;
   119276     /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
   119277     ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
   119278     ** fills up, delete the least entry in the sorter after each insert.
   119279     ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
   119280     addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
   119281     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
   119282     if( pSort->bOrderedInnerLoop ){
   119283       r1 = ++pParse->nMem;
   119284       sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
   119285       VdbeComment((v, "seq"));
   119286     }
   119287     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
   119288     if( pSort->bOrderedInnerLoop ){
   119289       /* If the inner loop is driven by an index such that values from
   119290       ** the same iteration of the inner loop are in sorted order, then
   119291       ** immediately jump to the next iteration of an inner loop if the
   119292       ** entry from the current iteration does not fit into the top
   119293       ** LIMIT+OFFSET entries of the sorter. */
   119294       int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
   119295       sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
   119296       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   119297       VdbeCoverage(v);
   119298     }
   119299     sqlite3VdbeJumpHere(v, addr);
   119300   }
   119301 }
   119302 
   119303 /*
   119304 ** Add code to implement the OFFSET
   119305 */
   119306 static void codeOffset(
   119307   Vdbe *v,          /* Generate code into this VM */
   119308   int iOffset,      /* Register holding the offset counter */
   119309   int iContinue     /* Jump here to skip the current record */
   119310 ){
   119311   if( iOffset>0 ){
   119312     sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
   119313     VdbeComment((v, "OFFSET"));
   119314   }
   119315 }
   119316 
   119317 /*
   119318 ** Add code that will check to make sure the N registers starting at iMem
   119319 ** form a distinct entry.  iTab is a sorting index that holds previously
   119320 ** seen combinations of the N values.  A new entry is made in iTab
   119321 ** if the current N values are new.
   119322 **
   119323 ** A jump to addrRepeat is made and the N+1 values are popped from the
   119324 ** stack if the top N elements are not distinct.
   119325 */
   119326 static void codeDistinct(
   119327   Parse *pParse,     /* Parsing and code generating context */
   119328   int iTab,          /* A sorting index used to test for distinctness */
   119329   int addrRepeat,    /* Jump to here if not distinct */
   119330   int N,             /* Number of elements */
   119331   int iMem           /* First element */
   119332 ){
   119333   Vdbe *v;
   119334   int r1;
   119335 
   119336   v = pParse->pVdbe;
   119337   r1 = sqlite3GetTempReg(pParse);
   119338   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
   119339   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   119340   sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
   119341   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   119342   sqlite3ReleaseTempReg(pParse, r1);
   119343 }
   119344 
   119345 /*
   119346 ** This routine generates the code for the inside of the inner loop
   119347 ** of a SELECT.
   119348 **
   119349 ** If srcTab is negative, then the p->pEList expressions
   119350 ** are evaluated in order to get the data for this row.  If srcTab is
   119351 ** zero or more, then data is pulled from srcTab and p->pEList is used only
   119352 ** to get the number of columns and the collation sequence for each column.
   119353 */
   119354 static void selectInnerLoop(
   119355   Parse *pParse,          /* The parser context */
   119356   Select *p,              /* The complete select statement being coded */
   119357   int srcTab,             /* Pull data from this table if non-negative */
   119358   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
   119359   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
   119360   SelectDest *pDest,      /* How to dispose of the results */
   119361   int iContinue,          /* Jump here to continue with next row */
   119362   int iBreak              /* Jump here to break out of the inner loop */
   119363 ){
   119364   Vdbe *v = pParse->pVdbe;
   119365   int i;
   119366   int hasDistinct;            /* True if the DISTINCT keyword is present */
   119367   int eDest = pDest->eDest;   /* How to dispose of results */
   119368   int iParm = pDest->iSDParm; /* First argument to disposal method */
   119369   int nResultCol;             /* Number of result columns */
   119370   int nPrefixReg = 0;         /* Number of extra registers before regResult */
   119371 
   119372   /* Usually, regResult is the first cell in an array of memory cells
   119373   ** containing the current result row. In this case regOrig is set to the
   119374   ** same value. However, if the results are being sent to the sorter, the
   119375   ** values for any expressions that are also part of the sort-key are omitted
   119376   ** from this array. In this case regOrig is set to zero.  */
   119377   int regResult;              /* Start of memory holding current results */
   119378   int regOrig;                /* Start of memory holding full result (or 0) */
   119379 
   119380   assert( v );
   119381   assert( p->pEList!=0 );
   119382   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
   119383   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
   119384   if( pSort==0 && !hasDistinct ){
   119385     assert( iContinue!=0 );
   119386     codeOffset(v, p->iOffset, iContinue);
   119387   }
   119388 
   119389   /* Pull the requested columns.
   119390   */
   119391   nResultCol = p->pEList->nExpr;
   119392 
   119393   if( pDest->iSdst==0 ){
   119394     if( pSort ){
   119395       nPrefixReg = pSort->pOrderBy->nExpr;
   119396       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
   119397       pParse->nMem += nPrefixReg;
   119398     }
   119399     pDest->iSdst = pParse->nMem+1;
   119400     pParse->nMem += nResultCol;
   119401   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
   119402     /* This is an error condition that can result, for example, when a SELECT
   119403     ** on the right-hand side of an INSERT contains more result columns than
   119404     ** there are columns in the table on the left.  The error will be caught
   119405     ** and reported later.  But we need to make sure enough memory is allocated
   119406     ** to avoid other spurious errors in the meantime. */
   119407     pParse->nMem += nResultCol;
   119408   }
   119409   pDest->nSdst = nResultCol;
   119410   regOrig = regResult = pDest->iSdst;
   119411   if( srcTab>=0 ){
   119412     for(i=0; i<nResultCol; i++){
   119413       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   119414       VdbeComment((v, "%s", p->pEList->a[i].zName));
   119415     }
   119416   }else if( eDest!=SRT_Exists ){
   119417     /* If the destination is an EXISTS(...) expression, the actual
   119418     ** values returned by the SELECT are not required.
   119419     */
   119420     u8 ecelFlags;
   119421     if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
   119422       ecelFlags = SQLITE_ECEL_DUP;
   119423     }else{
   119424       ecelFlags = 0;
   119425     }
   119426     if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
   119427       /* For each expression in p->pEList that is a copy of an expression in
   119428       ** the ORDER BY clause (pSort->pOrderBy), set the associated
   119429       ** iOrderByCol value to one more than the index of the ORDER BY
   119430       ** expression within the sort-key that pushOntoSorter() will generate.
   119431       ** This allows the p->pEList field to be omitted from the sorted record,
   119432       ** saving space and CPU cycles.  */
   119433       ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
   119434       for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
   119435         int j;
   119436         if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
   119437           p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
   119438         }
   119439       }
   119440       regOrig = 0;
   119441       assert( eDest==SRT_Set || eDest==SRT_Mem
   119442            || eDest==SRT_Coroutine || eDest==SRT_Output );
   119443     }
   119444     nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult,
   119445                                          0,ecelFlags);
   119446   }
   119447 
   119448   /* If the DISTINCT keyword was present on the SELECT statement
   119449   ** and this row has been seen before, then do not make this row
   119450   ** part of the result.
   119451   */
   119452   if( hasDistinct ){
   119453     switch( pDistinct->eTnctType ){
   119454       case WHERE_DISTINCT_ORDERED: {
   119455         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
   119456         int iJump;              /* Jump destination */
   119457         int regPrev;            /* Previous row content */
   119458 
   119459         /* Allocate space for the previous row */
   119460         regPrev = pParse->nMem+1;
   119461         pParse->nMem += nResultCol;
   119462 
   119463         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
   119464         ** sets the MEM_Cleared bit on the first register of the
   119465         ** previous value.  This will cause the OP_Ne below to always
   119466         ** fail on the first iteration of the loop even if the first
   119467         ** row is all NULLs.
   119468         */
   119469         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
   119470         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
   119471         pOp->opcode = OP_Null;
   119472         pOp->p1 = 1;
   119473         pOp->p2 = regPrev;
   119474 
   119475         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
   119476         for(i=0; i<nResultCol; i++){
   119477           CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
   119478           if( i<nResultCol-1 ){
   119479             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
   119480             VdbeCoverage(v);
   119481           }else{
   119482             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
   119483             VdbeCoverage(v);
   119484            }
   119485           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
   119486           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   119487         }
   119488         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
   119489         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
   119490         break;
   119491       }
   119492 
   119493       case WHERE_DISTINCT_UNIQUE: {
   119494         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
   119495         break;
   119496       }
   119497 
   119498       default: {
   119499         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
   119500         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
   119501                      regResult);
   119502         break;
   119503       }
   119504     }
   119505     if( pSort==0 ){
   119506       codeOffset(v, p->iOffset, iContinue);
   119507     }
   119508   }
   119509 
   119510   switch( eDest ){
   119511     /* In this mode, write each query result to the key of the temporary
   119512     ** table iParm.
   119513     */
   119514 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   119515     case SRT_Union: {
   119516       int r1;
   119517       r1 = sqlite3GetTempReg(pParse);
   119518       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
   119519       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
   119520       sqlite3ReleaseTempReg(pParse, r1);
   119521       break;
   119522     }
   119523 
   119524     /* Construct a record from the query result, but instead of
   119525     ** saving that record, use it as a key to delete elements from
   119526     ** the temporary table iParm.
   119527     */
   119528     case SRT_Except: {
   119529       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
   119530       break;
   119531     }
   119532 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   119533 
   119534     /* Store the result as data using a unique key.
   119535     */
   119536     case SRT_Fifo:
   119537     case SRT_DistFifo:
   119538     case SRT_Table:
   119539     case SRT_EphemTab: {
   119540       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
   119541       testcase( eDest==SRT_Table );
   119542       testcase( eDest==SRT_EphemTab );
   119543       testcase( eDest==SRT_Fifo );
   119544       testcase( eDest==SRT_DistFifo );
   119545       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
   119546 #ifndef SQLITE_OMIT_CTE
   119547       if( eDest==SRT_DistFifo ){
   119548         /* If the destination is DistFifo, then cursor (iParm+1) is open
   119549         ** on an ephemeral index. If the current row is already present
   119550         ** in the index, do not write it to the output. If not, add the
   119551         ** current row to the index and proceed with writing it to the
   119552         ** output table as well.  */
   119553         int addr = sqlite3VdbeCurrentAddr(v) + 4;
   119554         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
   119555         VdbeCoverage(v);
   119556         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
   119557         assert( pSort==0 );
   119558       }
   119559 #endif
   119560       if( pSort ){
   119561         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
   119562       }else{
   119563         int r2 = sqlite3GetTempReg(pParse);
   119564         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   119565         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   119566         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   119567         sqlite3ReleaseTempReg(pParse, r2);
   119568       }
   119569       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
   119570       break;
   119571     }
   119572 
   119573 #ifndef SQLITE_OMIT_SUBQUERY
   119574     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   119575     ** then there should be a single item on the stack.  Write this
   119576     ** item into the set table with bogus data.
   119577     */
   119578     case SRT_Set: {
   119579       if( pSort ){
   119580         /* At first glance you would think we could optimize out the
   119581         ** ORDER BY in this case since the order of entries in the set
   119582         ** does not matter.  But there might be a LIMIT clause, in which
   119583         ** case the order does matter */
   119584         pushOntoSorter(
   119585             pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
   119586       }else{
   119587         int r1 = sqlite3GetTempReg(pParse);
   119588         assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
   119589         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
   119590             r1, pDest->zAffSdst, nResultCol);
   119591         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
   119592         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
   119593         sqlite3ReleaseTempReg(pParse, r1);
   119594       }
   119595       break;
   119596     }
   119597 
   119598     /* If any row exist in the result set, record that fact and abort.
   119599     */
   119600     case SRT_Exists: {
   119601       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   119602       /* The LIMIT clause will terminate the loop for us */
   119603       break;
   119604     }
   119605 
   119606     /* If this is a scalar select that is part of an expression, then
   119607     ** store the results in the appropriate memory cell or array of
   119608     ** memory cells and break out of the scan loop.
   119609     */
   119610     case SRT_Mem: {
   119611       if( pSort ){
   119612         assert( nResultCol<=pDest->nSdst );
   119613         pushOntoSorter(
   119614             pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
   119615       }else{
   119616         assert( nResultCol==pDest->nSdst );
   119617         assert( regResult==iParm );
   119618         /* The LIMIT clause will jump out of the loop for us */
   119619       }
   119620       break;
   119621     }
   119622 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   119623 
   119624     case SRT_Coroutine:       /* Send data to a co-routine */
   119625     case SRT_Output: {        /* Return the results */
   119626       testcase( eDest==SRT_Coroutine );
   119627       testcase( eDest==SRT_Output );
   119628       if( pSort ){
   119629         pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
   119630                        nPrefixReg);
   119631       }else if( eDest==SRT_Coroutine ){
   119632         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   119633       }else{
   119634         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
   119635         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
   119636       }
   119637       break;
   119638     }
   119639 
   119640 #ifndef SQLITE_OMIT_CTE
   119641     /* Write the results into a priority queue that is order according to
   119642     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
   119643     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
   119644     ** pSO->nExpr columns, then make sure all keys are unique by adding a
   119645     ** final OP_Sequence column.  The last column is the record as a blob.
   119646     */
   119647     case SRT_DistQueue:
   119648     case SRT_Queue: {
   119649       int nKey;
   119650       int r1, r2, r3;
   119651       int addrTest = 0;
   119652       ExprList *pSO;
   119653       pSO = pDest->pOrderBy;
   119654       assert( pSO );
   119655       nKey = pSO->nExpr;
   119656       r1 = sqlite3GetTempReg(pParse);
   119657       r2 = sqlite3GetTempRange(pParse, nKey+2);
   119658       r3 = r2+nKey+1;
   119659       if( eDest==SRT_DistQueue ){
   119660         /* If the destination is DistQueue, then cursor (iParm+1) is open
   119661         ** on a second ephemeral index that holds all values every previously
   119662         ** added to the queue. */
   119663         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
   119664                                         regResult, nResultCol);
   119665         VdbeCoverage(v);
   119666       }
   119667       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
   119668       if( eDest==SRT_DistQueue ){
   119669         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
   119670         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   119671       }
   119672       for(i=0; i<nKey; i++){
   119673         sqlite3VdbeAddOp2(v, OP_SCopy,
   119674                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
   119675                           r2+i);
   119676       }
   119677       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
   119678       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
   119679       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
   119680       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
   119681       sqlite3ReleaseTempReg(pParse, r1);
   119682       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
   119683       break;
   119684     }
   119685 #endif /* SQLITE_OMIT_CTE */
   119686 
   119687 
   119688 
   119689 #if !defined(SQLITE_OMIT_TRIGGER)
   119690     /* Discard the results.  This is used for SELECT statements inside
   119691     ** the body of a TRIGGER.  The purpose of such selects is to call
   119692     ** user-defined functions that have side effects.  We do not care
   119693     ** about the actual results of the select.
   119694     */
   119695     default: {
   119696       assert( eDest==SRT_Discard );
   119697       break;
   119698     }
   119699 #endif
   119700   }
   119701 
   119702   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
   119703   ** there is a sorter, in which case the sorter has already limited
   119704   ** the output for us.
   119705   */
   119706   if( pSort==0 && p->iLimit ){
   119707     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
   119708   }
   119709 }
   119710 
   119711 /*
   119712 ** Allocate a KeyInfo object sufficient for an index of N key columns and
   119713 ** X extra columns.
   119714 */
   119715 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
   119716   int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
   119717   KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
   119718   if( p ){
   119719     p->aSortOrder = (u8*)&p->aColl[N+X];
   119720     p->nKeyField = (u16)N;
   119721     p->nAllField = (u16)(N+X);
   119722     p->enc = ENC(db);
   119723     p->db = db;
   119724     p->nRef = 1;
   119725     memset(&p[1], 0, nExtra);
   119726   }else{
   119727     sqlite3OomFault(db);
   119728   }
   119729   return p;
   119730 }
   119731 
   119732 /*
   119733 ** Deallocate a KeyInfo object
   119734 */
   119735 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
   119736   if( p ){
   119737     assert( p->nRef>0 );
   119738     p->nRef--;
   119739     if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
   119740   }
   119741 }
   119742 
   119743 /*
   119744 ** Make a new pointer to a KeyInfo object
   119745 */
   119746 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
   119747   if( p ){
   119748     assert( p->nRef>0 );
   119749     p->nRef++;
   119750   }
   119751   return p;
   119752 }
   119753 
   119754 #ifdef SQLITE_DEBUG
   119755 /*
   119756 ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
   119757 ** can only be changed if this is just a single reference to the object.
   119758 **
   119759 ** This routine is used only inside of assert() statements.
   119760 */
   119761 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
   119762 #endif /* SQLITE_DEBUG */
   119763 
   119764 /*
   119765 ** Given an expression list, generate a KeyInfo structure that records
   119766 ** the collating sequence for each expression in that expression list.
   119767 **
   119768 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   119769 ** KeyInfo structure is appropriate for initializing a virtual index to
   119770 ** implement that clause.  If the ExprList is the result set of a SELECT
   119771 ** then the KeyInfo structure is appropriate for initializing a virtual
   119772 ** index to implement a DISTINCT test.
   119773 **
   119774 ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
   119775 ** function is responsible for seeing that this structure is eventually
   119776 ** freed.
   119777 */
   119778 static KeyInfo *keyInfoFromExprList(
   119779   Parse *pParse,       /* Parsing context */
   119780   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
   119781   int iStart,          /* Begin with this column of pList */
   119782   int nExtra           /* Add this many extra columns to the end */
   119783 ){
   119784   int nExpr;
   119785   KeyInfo *pInfo;
   119786   struct ExprList_item *pItem;
   119787   sqlite3 *db = pParse->db;
   119788   int i;
   119789 
   119790   nExpr = pList->nExpr;
   119791   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
   119792   if( pInfo ){
   119793     assert( sqlite3KeyInfoIsWriteable(pInfo) );
   119794     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
   119795       pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
   119796       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
   119797     }
   119798   }
   119799   return pInfo;
   119800 }
   119801 
   119802 /*
   119803 ** Name of the connection operator, used for error messages.
   119804 */
   119805 static const char *selectOpName(int id){
   119806   char *z;
   119807   switch( id ){
   119808     case TK_ALL:       z = "UNION ALL";   break;
   119809     case TK_INTERSECT: z = "INTERSECT";   break;
   119810     case TK_EXCEPT:    z = "EXCEPT";      break;
   119811     default:           z = "UNION";       break;
   119812   }
   119813   return z;
   119814 }
   119815 
   119816 #ifndef SQLITE_OMIT_EXPLAIN
   119817 /*
   119818 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   119819 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   119820 ** where the caption is of the form:
   119821 **
   119822 **   "USE TEMP B-TREE FOR xxx"
   119823 **
   119824 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
   119825 ** is determined by the zUsage argument.
   119826 */
   119827 static void explainTempTable(Parse *pParse, const char *zUsage){
   119828   if( pParse->explain==2 ){
   119829     Vdbe *v = pParse->pVdbe;
   119830     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
   119831     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   119832   }
   119833 }
   119834 
   119835 /*
   119836 ** Assign expression b to lvalue a. A second, no-op, version of this macro
   119837 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
   119838 ** in sqlite3Select() to assign values to structure member variables that
   119839 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
   119840 ** code with #ifndef directives.
   119841 */
   119842 # define explainSetInteger(a, b) a = b
   119843 
   119844 #else
   119845 /* No-op versions of the explainXXX() functions and macros. */
   119846 # define explainTempTable(y,z)
   119847 # define explainSetInteger(y,z)
   119848 #endif
   119849 
   119850 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
   119851 /*
   119852 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   119853 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   119854 ** where the caption is of one of the two forms:
   119855 **
   119856 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
   119857 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
   119858 **
   119859 ** where iSub1 and iSub2 are the integers passed as the corresponding
   119860 ** function parameters, and op is the text representation of the parameter
   119861 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
   119862 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
   119863 ** false, or the second form if it is true.
   119864 */
   119865 static void explainComposite(
   119866   Parse *pParse,                  /* Parse context */
   119867   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
   119868   int iSub1,                      /* Subquery id 1 */
   119869   int iSub2,                      /* Subquery id 2 */
   119870   int bUseTmp                     /* True if a temp table was used */
   119871 ){
   119872   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
   119873   if( pParse->explain==2 ){
   119874     Vdbe *v = pParse->pVdbe;
   119875     char *zMsg = sqlite3MPrintf(
   119876         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
   119877         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
   119878     );
   119879     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   119880   }
   119881 }
   119882 #else
   119883 /* No-op versions of the explainXXX() functions and macros. */
   119884 # define explainComposite(v,w,x,y,z)
   119885 #endif
   119886 
   119887 /*
   119888 ** If the inner loop was generated using a non-null pOrderBy argument,
   119889 ** then the results were placed in a sorter.  After the loop is terminated
   119890 ** we need to run the sorter and output the results.  The following
   119891 ** routine generates the code needed to do that.
   119892 */
   119893 static void generateSortTail(
   119894   Parse *pParse,    /* Parsing context */
   119895   Select *p,        /* The SELECT statement */
   119896   SortCtx *pSort,   /* Information on the ORDER BY clause */
   119897   int nColumn,      /* Number of columns of data */
   119898   SelectDest *pDest /* Write the sorted results here */
   119899 ){
   119900   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
   119901   int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
   119902   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
   119903   int addr;
   119904   int addrOnce = 0;
   119905   int iTab;
   119906   ExprList *pOrderBy = pSort->pOrderBy;
   119907   int eDest = pDest->eDest;
   119908   int iParm = pDest->iSDParm;
   119909   int regRow;
   119910   int regRowid;
   119911   int iCol;
   119912   int nKey;
   119913   int iSortTab;                   /* Sorter cursor to read from */
   119914   int nSortData;                  /* Trailing values to read from sorter */
   119915   int i;
   119916   int bSeq;                       /* True if sorter record includes seq. no. */
   119917   struct ExprList_item *aOutEx = p->pEList->a;
   119918 
   119919   assert( addrBreak<0 );
   119920   if( pSort->labelBkOut ){
   119921     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
   119922     sqlite3VdbeGoto(v, addrBreak);
   119923     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
   119924   }
   119925   iTab = pSort->iECursor;
   119926   if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
   119927     regRowid = 0;
   119928     regRow = pDest->iSdst;
   119929     nSortData = nColumn;
   119930   }else{
   119931     regRowid = sqlite3GetTempReg(pParse);
   119932     regRow = sqlite3GetTempRange(pParse, nColumn);
   119933     nSortData = nColumn;
   119934   }
   119935   nKey = pOrderBy->nExpr - pSort->nOBSat;
   119936   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   119937     int regSortOut = ++pParse->nMem;
   119938     iSortTab = pParse->nTab++;
   119939     if( pSort->labelBkOut ){
   119940       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   119941     }
   119942     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
   119943     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
   119944     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
   119945     VdbeCoverage(v);
   119946     codeOffset(v, p->iOffset, addrContinue);
   119947     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
   119948     bSeq = 0;
   119949   }else{
   119950     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
   119951     codeOffset(v, p->iOffset, addrContinue);
   119952     iSortTab = iTab;
   119953     bSeq = 1;
   119954   }
   119955   for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
   119956     int iRead;
   119957     if( aOutEx[i].u.x.iOrderByCol ){
   119958       iRead = aOutEx[i].u.x.iOrderByCol-1;
   119959     }else{
   119960       iRead = iCol++;
   119961     }
   119962     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
   119963     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
   119964   }
   119965   switch( eDest ){
   119966     case SRT_Table:
   119967     case SRT_EphemTab: {
   119968       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   119969       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   119970       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   119971       break;
   119972     }
   119973 #ifndef SQLITE_OMIT_SUBQUERY
   119974     case SRT_Set: {
   119975       assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
   119976       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
   119977                         pDest->zAffSdst, nColumn);
   119978       sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
   119979       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
   119980       break;
   119981     }
   119982     case SRT_Mem: {
   119983       /* The LIMIT clause will terminate the loop for us */
   119984       break;
   119985     }
   119986 #endif
   119987     default: {
   119988       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
   119989       testcase( eDest==SRT_Output );
   119990       testcase( eDest==SRT_Coroutine );
   119991       if( eDest==SRT_Output ){
   119992         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
   119993         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
   119994       }else{
   119995         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   119996       }
   119997       break;
   119998     }
   119999   }
   120000   if( regRowid ){
   120001     if( eDest==SRT_Set ){
   120002       sqlite3ReleaseTempRange(pParse, regRow, nColumn);
   120003     }else{
   120004       sqlite3ReleaseTempReg(pParse, regRow);
   120005     }
   120006     sqlite3ReleaseTempReg(pParse, regRowid);
   120007   }
   120008   /* The bottom of the loop
   120009   */
   120010   sqlite3VdbeResolveLabel(v, addrContinue);
   120011   if( pSort->sortFlags & SORTFLAG_UseSorter ){
   120012     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
   120013   }else{
   120014     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
   120015   }
   120016   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
   120017   sqlite3VdbeResolveLabel(v, addrBreak);
   120018 }
   120019 
   120020 /*
   120021 ** Return a pointer to a string containing the 'declaration type' of the
   120022 ** expression pExpr. The string may be treated as static by the caller.
   120023 **
   120024 ** Also try to estimate the size of the returned value and return that
   120025 ** result in *pEstWidth.
   120026 **
   120027 ** The declaration type is the exact datatype definition extracted from the
   120028 ** original CREATE TABLE statement if the expression is a column. The
   120029 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
   120030 ** is considered a column can be complex in the presence of subqueries. The
   120031 ** result-set expression in all of the following SELECT statements is
   120032 ** considered a column by this function.
   120033 **
   120034 **   SELECT col FROM tbl;
   120035 **   SELECT (SELECT col FROM tbl;
   120036 **   SELECT (SELECT col FROM tbl);
   120037 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
   120038 **
   120039 ** The declaration type for any expression other than a column is NULL.
   120040 **
   120041 ** This routine has either 3 or 6 parameters depending on whether or not
   120042 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
   120043 */
   120044 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   120045 # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
   120046 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
   120047 # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
   120048 #endif
   120049 static const char *columnTypeImpl(
   120050   NameContext *pNC,
   120051 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   120052   Expr *pExpr
   120053 #else
   120054   Expr *pExpr,
   120055   const char **pzOrigDb,
   120056   const char **pzOrigTab,
   120057   const char **pzOrigCol
   120058 #endif
   120059 ){
   120060   char const *zType = 0;
   120061   int j;
   120062 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   120063   char const *zOrigDb = 0;
   120064   char const *zOrigTab = 0;
   120065   char const *zOrigCol = 0;
   120066 #endif
   120067 
   120068   assert( pExpr!=0 );
   120069   assert( pNC->pSrcList!=0 );
   120070   assert( pExpr->op!=TK_AGG_COLUMN );  /* This routine runes before aggregates
   120071                                        ** are processed */
   120072   switch( pExpr->op ){
   120073     case TK_COLUMN: {
   120074       /* The expression is a column. Locate the table the column is being
   120075       ** extracted from in NameContext.pSrcList. This table may be real
   120076       ** database table or a subquery.
   120077       */
   120078       Table *pTab = 0;            /* Table structure column is extracted from */
   120079       Select *pS = 0;             /* Select the column is extracted from */
   120080       int iCol = pExpr->iColumn;  /* Index of column in pTab */
   120081       while( pNC && !pTab ){
   120082         SrcList *pTabList = pNC->pSrcList;
   120083         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   120084         if( j<pTabList->nSrc ){
   120085           pTab = pTabList->a[j].pTab;
   120086           pS = pTabList->a[j].pSelect;
   120087         }else{
   120088           pNC = pNC->pNext;
   120089         }
   120090       }
   120091 
   120092       if( pTab==0 ){
   120093         /* At one time, code such as "SELECT new.x" within a trigger would
   120094         ** cause this condition to run.  Since then, we have restructured how
   120095         ** trigger code is generated and so this condition is no longer
   120096         ** possible. However, it can still be true for statements like
   120097         ** the following:
   120098         **
   120099         **   CREATE TABLE t1(col INTEGER);
   120100         **   SELECT (SELECT t1.col) FROM FROM t1;
   120101         **
   120102         ** when columnType() is called on the expression "t1.col" in the
   120103         ** sub-select. In this case, set the column type to NULL, even
   120104         ** though it should really be "INTEGER".
   120105         **
   120106         ** This is not a problem, as the column type of "t1.col" is never
   120107         ** used. When columnType() is called on the expression
   120108         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
   120109         ** branch below.  */
   120110         break;
   120111       }
   120112 
   120113       assert( pTab && pExpr->pTab==pTab );
   120114       if( pS ){
   120115         /* The "table" is actually a sub-select or a view in the FROM clause
   120116         ** of the SELECT statement. Return the declaration type and origin
   120117         ** data for the result-set column of the sub-select.
   120118         */
   120119         if( iCol>=0 && iCol<pS->pEList->nExpr ){
   120120           /* If iCol is less than zero, then the expression requests the
   120121           ** rowid of the sub-select or view. This expression is legal (see
   120122           ** test case misc2.2.2) - it always evaluates to NULL.
   120123           */
   120124           NameContext sNC;
   120125           Expr *p = pS->pEList->a[iCol].pExpr;
   120126           sNC.pSrcList = pS->pSrc;
   120127           sNC.pNext = pNC;
   120128           sNC.pParse = pNC->pParse;
   120129           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
   120130         }
   120131       }else{
   120132         /* A real table or a CTE table */
   120133         assert( !pS );
   120134 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   120135         if( iCol<0 ) iCol = pTab->iPKey;
   120136         assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
   120137         if( iCol<0 ){
   120138           zType = "INTEGER";
   120139           zOrigCol = "rowid";
   120140         }else{
   120141           zOrigCol = pTab->aCol[iCol].zName;
   120142           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
   120143         }
   120144         zOrigTab = pTab->zName;
   120145         if( pNC->pParse && pTab->pSchema ){
   120146           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   120147           zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
   120148         }
   120149 #else
   120150         assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
   120151         if( iCol<0 ){
   120152           zType = "INTEGER";
   120153         }else{
   120154           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
   120155         }
   120156 #endif
   120157       }
   120158       break;
   120159     }
   120160 #ifndef SQLITE_OMIT_SUBQUERY
   120161     case TK_SELECT: {
   120162       /* The expression is a sub-select. Return the declaration type and
   120163       ** origin info for the single column in the result set of the SELECT
   120164       ** statement.
   120165       */
   120166       NameContext sNC;
   120167       Select *pS = pExpr->x.pSelect;
   120168       Expr *p = pS->pEList->a[0].pExpr;
   120169       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   120170       sNC.pSrcList = pS->pSrc;
   120171       sNC.pNext = pNC;
   120172       sNC.pParse = pNC->pParse;
   120173       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
   120174       break;
   120175     }
   120176 #endif
   120177   }
   120178 
   120179 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   120180   if( pzOrigDb ){
   120181     assert( pzOrigTab && pzOrigCol );
   120182     *pzOrigDb = zOrigDb;
   120183     *pzOrigTab = zOrigTab;
   120184     *pzOrigCol = zOrigCol;
   120185   }
   120186 #endif
   120187   return zType;
   120188 }
   120189 
   120190 /*
   120191 ** Generate code that will tell the VDBE the declaration types of columns
   120192 ** in the result set.
   120193 */
   120194 static void generateColumnTypes(
   120195   Parse *pParse,      /* Parser context */
   120196   SrcList *pTabList,  /* List of tables */
   120197   ExprList *pEList    /* Expressions defining the result set */
   120198 ){
   120199 #ifndef SQLITE_OMIT_DECLTYPE
   120200   Vdbe *v = pParse->pVdbe;
   120201   int i;
   120202   NameContext sNC;
   120203   sNC.pSrcList = pTabList;
   120204   sNC.pParse = pParse;
   120205   sNC.pNext = 0;
   120206   for(i=0; i<pEList->nExpr; i++){
   120207     Expr *p = pEList->a[i].pExpr;
   120208     const char *zType;
   120209 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   120210     const char *zOrigDb = 0;
   120211     const char *zOrigTab = 0;
   120212     const char *zOrigCol = 0;
   120213     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
   120214 
   120215     /* The vdbe must make its own copy of the column-type and other
   120216     ** column specific strings, in case the schema is reset before this
   120217     ** virtual machine is deleted.
   120218     */
   120219     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
   120220     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
   120221     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
   120222 #else
   120223     zType = columnType(&sNC, p, 0, 0, 0);
   120224 #endif
   120225     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
   120226   }
   120227 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
   120228 }
   120229 
   120230 
   120231 /*
   120232 ** Compute the column names for a SELECT statement.
   120233 **
   120234 ** The only guarantee that SQLite makes about column names is that if the
   120235 ** column has an AS clause assigning it a name, that will be the name used.
   120236 ** That is the only documented guarantee.  However, countless applications
   120237 ** developed over the years have made baseless assumptions about column names
   120238 ** and will break if those assumptions changes.  Hence, use extreme caution
   120239 ** when modifying this routine to avoid breaking legacy.
   120240 **
   120241 ** See Also: sqlite3ColumnsFromExprList()
   120242 **
   120243 ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
   120244 ** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all
   120245 ** applications should operate this way.  Nevertheless, we need to support the
   120246 ** other modes for legacy:
   120247 **
   120248 **    short=OFF, full=OFF:      Column name is the text of the expression has it
   120249 **                              originally appears in the SELECT statement.  In
   120250 **                              other words, the zSpan of the result expression.
   120251 **
   120252 **    short=ON, full=OFF:       (This is the default setting).  If the result
   120253 **                              refers directly to a table column, then the
   120254 **                              result column name is just the table column
   120255 **                              name: COLUMN.  Otherwise use zSpan.
   120256 **
   120257 **    full=ON, short=ANY:       If the result refers directly to a table column,
   120258 **                              then the result column name with the table name
   120259 **                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
   120260 */
   120261 static void generateColumnNames(
   120262   Parse *pParse,      /* Parser context */
   120263   Select *pSelect     /* Generate column names for this SELECT statement */
   120264 ){
   120265   Vdbe *v = pParse->pVdbe;
   120266   int i;
   120267   Table *pTab;
   120268   SrcList *pTabList;
   120269   ExprList *pEList;
   120270   sqlite3 *db = pParse->db;
   120271   int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */
   120272   int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
   120273 
   120274 #ifndef SQLITE_OMIT_EXPLAIN
   120275   /* If this is an EXPLAIN, skip this step */
   120276   if( pParse->explain ){
   120277     return;
   120278   }
   120279 #endif
   120280 
   120281   if( pParse->colNamesSet || db->mallocFailed ) return;
   120282   /* Column names are determined by the left-most term of a compound select */
   120283   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   120284   SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
   120285   pTabList = pSelect->pSrc;
   120286   pEList = pSelect->pEList;
   120287   assert( v!=0 );
   120288   assert( pTabList!=0 );
   120289   pParse->colNamesSet = 1;
   120290   fullName = (db->flags & SQLITE_FullColNames)!=0;
   120291   srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
   120292   sqlite3VdbeSetNumCols(v, pEList->nExpr);
   120293   for(i=0; i<pEList->nExpr; i++){
   120294     Expr *p = pEList->a[i].pExpr;
   120295 
   120296     assert( p!=0 );
   120297     assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
   120298     assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
   120299     if( pEList->a[i].zName ){
   120300       /* An AS clause always takes first priority */
   120301       char *zName = pEList->a[i].zName;
   120302       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
   120303     }else if( srcName && p->op==TK_COLUMN ){
   120304       char *zCol;
   120305       int iCol = p->iColumn;
   120306       pTab = p->pTab;
   120307       assert( pTab!=0 );
   120308       if( iCol<0 ) iCol = pTab->iPKey;
   120309       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   120310       if( iCol<0 ){
   120311         zCol = "rowid";
   120312       }else{
   120313         zCol = pTab->aCol[iCol].zName;
   120314       }
   120315       if( fullName ){
   120316         char *zName = 0;
   120317         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
   120318         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
   120319       }else{
   120320         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
   120321       }
   120322     }else{
   120323       const char *z = pEList->a[i].zSpan;
   120324       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
   120325       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
   120326     }
   120327   }
   120328   generateColumnTypes(pParse, pTabList, pEList);
   120329 }
   120330 
   120331 /*
   120332 ** Given an expression list (which is really the list of expressions
   120333 ** that form the result set of a SELECT statement) compute appropriate
   120334 ** column names for a table that would hold the expression list.
   120335 **
   120336 ** All column names will be unique.
   120337 **
   120338 ** Only the column names are computed.  Column.zType, Column.zColl,
   120339 ** and other fields of Column are zeroed.
   120340 **
   120341 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
   120342 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
   120343 **
   120344 ** The only guarantee that SQLite makes about column names is that if the
   120345 ** column has an AS clause assigning it a name, that will be the name used.
   120346 ** That is the only documented guarantee.  However, countless applications
   120347 ** developed over the years have made baseless assumptions about column names
   120348 ** and will break if those assumptions changes.  Hence, use extreme caution
   120349 ** when modifying this routine to avoid breaking legacy.
   120350 **
   120351 ** See Also: generateColumnNames()
   120352 */
   120353 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
   120354   Parse *pParse,          /* Parsing context */
   120355   ExprList *pEList,       /* Expr list from which to derive column names */
   120356   i16 *pnCol,             /* Write the number of columns here */
   120357   Column **paCol          /* Write the new column list here */
   120358 ){
   120359   sqlite3 *db = pParse->db;   /* Database connection */
   120360   int i, j;                   /* Loop counters */
   120361   u32 cnt;                    /* Index added to make the name unique */
   120362   Column *aCol, *pCol;        /* For looping over result columns */
   120363   int nCol;                   /* Number of columns in the result set */
   120364   char *zName;                /* Column name */
   120365   int nName;                  /* Size of name in zName[] */
   120366   Hash ht;                    /* Hash table of column names */
   120367 
   120368   sqlite3HashInit(&ht);
   120369   if( pEList ){
   120370     nCol = pEList->nExpr;
   120371     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
   120372     testcase( aCol==0 );
   120373     if( nCol>32767 ) nCol = 32767;
   120374   }else{
   120375     nCol = 0;
   120376     aCol = 0;
   120377   }
   120378   assert( nCol==(i16)nCol );
   120379   *pnCol = nCol;
   120380   *paCol = aCol;
   120381 
   120382   for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
   120383     /* Get an appropriate name for the column
   120384     */
   120385     if( (zName = pEList->a[i].zName)!=0 ){
   120386       /* If the column contains an "AS <name>" phrase, use <name> as the name */
   120387     }else{
   120388       Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
   120389       while( pColExpr->op==TK_DOT ){
   120390         pColExpr = pColExpr->pRight;
   120391         assert( pColExpr!=0 );
   120392       }
   120393       assert( pColExpr->op!=TK_AGG_COLUMN );
   120394       if( pColExpr->op==TK_COLUMN ){
   120395         /* For columns use the column name name */
   120396         int iCol = pColExpr->iColumn;
   120397         Table *pTab = pColExpr->pTab;
   120398         assert( pTab!=0 );
   120399         if( iCol<0 ) iCol = pTab->iPKey;
   120400         zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
   120401       }else if( pColExpr->op==TK_ID ){
   120402         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
   120403         zName = pColExpr->u.zToken;
   120404       }else{
   120405         /* Use the original text of the column expression as its name */
   120406         zName = pEList->a[i].zSpan;
   120407       }
   120408     }
   120409     if( zName ){
   120410       zName = sqlite3DbStrDup(db, zName);
   120411     }else{
   120412       zName = sqlite3MPrintf(db,"column%d",i+1);
   120413     }
   120414 
   120415     /* Make sure the column name is unique.  If the name is not unique,
   120416     ** append an integer to the name so that it becomes unique.
   120417     */
   120418     cnt = 0;
   120419     while( zName && sqlite3HashFind(&ht, zName)!=0 ){
   120420       nName = sqlite3Strlen30(zName);
   120421       if( nName>0 ){
   120422         for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
   120423         if( zName[j]==':' ) nName = j;
   120424       }
   120425       zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
   120426       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
   120427     }
   120428     pCol->zName = zName;
   120429     sqlite3ColumnPropertiesFromName(0, pCol);
   120430     if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
   120431       sqlite3OomFault(db);
   120432     }
   120433   }
   120434   sqlite3HashClear(&ht);
   120435   if( db->mallocFailed ){
   120436     for(j=0; j<i; j++){
   120437       sqlite3DbFree(db, aCol[j].zName);
   120438     }
   120439     sqlite3DbFree(db, aCol);
   120440     *paCol = 0;
   120441     *pnCol = 0;
   120442     return SQLITE_NOMEM_BKPT;
   120443   }
   120444   return SQLITE_OK;
   120445 }
   120446 
   120447 /*
   120448 ** Add type and collation information to a column list based on
   120449 ** a SELECT statement.
   120450 **
   120451 ** The column list presumably came from selectColumnNamesFromExprList().
   120452 ** The column list has only names, not types or collations.  This
   120453 ** routine goes through and adds the types and collations.
   120454 **
   120455 ** This routine requires that all identifiers in the SELECT
   120456 ** statement be resolved.
   120457 */
   120458 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
   120459   Parse *pParse,        /* Parsing contexts */
   120460   Table *pTab,          /* Add column type information to this table */
   120461   Select *pSelect       /* SELECT used to determine types and collations */
   120462 ){
   120463   sqlite3 *db = pParse->db;
   120464   NameContext sNC;
   120465   Column *pCol;
   120466   CollSeq *pColl;
   120467   int i;
   120468   Expr *p;
   120469   struct ExprList_item *a;
   120470 
   120471   assert( pSelect!=0 );
   120472   assert( (pSelect->selFlags & SF_Resolved)!=0 );
   120473   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
   120474   if( db->mallocFailed ) return;
   120475   memset(&sNC, 0, sizeof(sNC));
   120476   sNC.pSrcList = pSelect->pSrc;
   120477   a = pSelect->pEList->a;
   120478   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   120479     const char *zType;
   120480     int n, m;
   120481     p = a[i].pExpr;
   120482     zType = columnType(&sNC, p, 0, 0, 0);
   120483     /* pCol->szEst = ... // Column size est for SELECT tables never used */
   120484     pCol->affinity = sqlite3ExprAffinity(p);
   120485     if( zType ){
   120486       m = sqlite3Strlen30(zType);
   120487       n = sqlite3Strlen30(pCol->zName);
   120488       pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
   120489       if( pCol->zName ){
   120490         memcpy(&pCol->zName[n+1], zType, m+1);
   120491         pCol->colFlags |= COLFLAG_HASTYPE;
   120492       }
   120493     }
   120494     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
   120495     pColl = sqlite3ExprCollSeq(pParse, p);
   120496     if( pColl && pCol->zColl==0 ){
   120497       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
   120498     }
   120499   }
   120500   pTab->szTabRow = 1; /* Any non-zero value works */
   120501 }
   120502 
   120503 /*
   120504 ** Given a SELECT statement, generate a Table structure that describes
   120505 ** the result set of that SELECT.
   120506 */
   120507 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
   120508   Table *pTab;
   120509   sqlite3 *db = pParse->db;
   120510   int savedFlags;
   120511 
   120512   savedFlags = db->flags;
   120513   db->flags &= ~SQLITE_FullColNames;
   120514   db->flags |= SQLITE_ShortColNames;
   120515   sqlite3SelectPrep(pParse, pSelect, 0);
   120516   if( pParse->nErr ) return 0;
   120517   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   120518   db->flags = savedFlags;
   120519   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
   120520   if( pTab==0 ){
   120521     return 0;
   120522   }
   120523   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
   120524   ** is disabled */
   120525   assert( db->lookaside.bDisable );
   120526   pTab->nTabRef = 1;
   120527   pTab->zName = 0;
   120528   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   120529   sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
   120530   sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
   120531   pTab->iPKey = -1;
   120532   if( db->mallocFailed ){
   120533     sqlite3DeleteTable(db, pTab);
   120534     return 0;
   120535   }
   120536   return pTab;
   120537 }
   120538 
   120539 /*
   120540 ** Get a VDBE for the given parser context.  Create a new one if necessary.
   120541 ** If an error occurs, return NULL and leave a message in pParse.
   120542 */
   120543 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
   120544   if( pParse->pVdbe ){
   120545     return pParse->pVdbe;
   120546   }
   120547   if( pParse->pToplevel==0
   120548    && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
   120549   ){
   120550     pParse->okConstFactor = 1;
   120551   }
   120552   return sqlite3VdbeCreate(pParse);
   120553 }
   120554 
   120555 
   120556 /*
   120557 ** Compute the iLimit and iOffset fields of the SELECT based on the
   120558 ** pLimit expressions.  pLimit->pLeft and pLimit->pRight hold the expressions
   120559 ** that appear in the original SQL statement after the LIMIT and OFFSET
   120560 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
   120561 ** are the integer memory register numbers for counters used to compute
   120562 ** the limit and offset.  If there is no limit and/or offset, then
   120563 ** iLimit and iOffset are negative.
   120564 **
   120565 ** This routine changes the values of iLimit and iOffset only if
   120566 ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight.  iLimit
   120567 ** and iOffset should have been preset to appropriate default values (zero)
   120568 ** prior to calling this routine.
   120569 **
   120570 ** The iOffset register (if it exists) is initialized to the value
   120571 ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
   120572 ** iOffset+1 is initialized to LIMIT+OFFSET.
   120573 **
   120574 ** Only if pLimit->pLeft!=0 do the limit registers get
   120575 ** redefined.  The UNION ALL operator uses this property to force
   120576 ** the reuse of the same limit and offset registers across multiple
   120577 ** SELECT statements.
   120578 */
   120579 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
   120580   Vdbe *v = 0;
   120581   int iLimit = 0;
   120582   int iOffset;
   120583   int n;
   120584   Expr *pLimit = p->pLimit;
   120585 
   120586   if( p->iLimit ) return;
   120587 
   120588   /*
   120589   ** "LIMIT -1" always shows all rows.  There is some
   120590   ** controversy about what the correct behavior should be.
   120591   ** The current implementation interprets "LIMIT 0" to mean
   120592   ** no rows.
   120593   */
   120594   sqlite3ExprCacheClear(pParse);
   120595   if( pLimit ){
   120596     assert( pLimit->op==TK_LIMIT );
   120597     assert( pLimit->pLeft!=0 );
   120598     p->iLimit = iLimit = ++pParse->nMem;
   120599     v = sqlite3GetVdbe(pParse);
   120600     assert( v!=0 );
   120601     if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
   120602       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
   120603       VdbeComment((v, "LIMIT counter"));
   120604       if( n==0 ){
   120605         sqlite3VdbeGoto(v, iBreak);
   120606       }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
   120607         p->nSelectRow = sqlite3LogEst((u64)n);
   120608         p->selFlags |= SF_FixedLimit;
   120609       }
   120610     }else{
   120611       sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
   120612       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
   120613       VdbeComment((v, "LIMIT counter"));
   120614       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
   120615     }
   120616     if( pLimit->pRight ){
   120617       p->iOffset = iOffset = ++pParse->nMem;
   120618       pParse->nMem++;   /* Allocate an extra register for limit+offset */
   120619       sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
   120620       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
   120621       VdbeComment((v, "OFFSET counter"));
   120622       sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
   120623       VdbeComment((v, "LIMIT+OFFSET"));
   120624     }
   120625   }
   120626 }
   120627 
   120628 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   120629 /*
   120630 ** Return the appropriate collating sequence for the iCol-th column of
   120631 ** the result set for the compound-select statement "p".  Return NULL if
   120632 ** the column has no default collating sequence.
   120633 **
   120634 ** The collating sequence for the compound select is taken from the
   120635 ** left-most term of the select that has a collating sequence.
   120636 */
   120637 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
   120638   CollSeq *pRet;
   120639   if( p->pPrior ){
   120640     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
   120641   }else{
   120642     pRet = 0;
   120643   }
   120644   assert( iCol>=0 );
   120645   /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
   120646   ** have been thrown during name resolution and we would not have gotten
   120647   ** this far */
   120648   if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
   120649     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
   120650   }
   120651   return pRet;
   120652 }
   120653 
   120654 /*
   120655 ** The select statement passed as the second parameter is a compound SELECT
   120656 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
   120657 ** structure suitable for implementing the ORDER BY.
   120658 **
   120659 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
   120660 ** function is responsible for ensuring that this structure is eventually
   120661 ** freed.
   120662 */
   120663 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
   120664   ExprList *pOrderBy = p->pOrderBy;
   120665   int nOrderBy = p->pOrderBy->nExpr;
   120666   sqlite3 *db = pParse->db;
   120667   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
   120668   if( pRet ){
   120669     int i;
   120670     for(i=0; i<nOrderBy; i++){
   120671       struct ExprList_item *pItem = &pOrderBy->a[i];
   120672       Expr *pTerm = pItem->pExpr;
   120673       CollSeq *pColl;
   120674 
   120675       if( pTerm->flags & EP_Collate ){
   120676         pColl = sqlite3ExprCollSeq(pParse, pTerm);
   120677       }else{
   120678         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
   120679         if( pColl==0 ) pColl = db->pDfltColl;
   120680         pOrderBy->a[i].pExpr =
   120681           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
   120682       }
   120683       assert( sqlite3KeyInfoIsWriteable(pRet) );
   120684       pRet->aColl[i] = pColl;
   120685       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
   120686     }
   120687   }
   120688 
   120689   return pRet;
   120690 }
   120691 
   120692 #ifndef SQLITE_OMIT_CTE
   120693 /*
   120694 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
   120695 ** query of the form:
   120696 **
   120697 **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
   120698 **                         \___________/             \_______________/
   120699 **                           p->pPrior                      p
   120700 **
   120701 **
   120702 ** There is exactly one reference to the recursive-table in the FROM clause
   120703 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
   120704 **
   120705 ** The setup-query runs once to generate an initial set of rows that go
   120706 ** into a Queue table.  Rows are extracted from the Queue table one by
   120707 ** one.  Each row extracted from Queue is output to pDest.  Then the single
   120708 ** extracted row (now in the iCurrent table) becomes the content of the
   120709 ** recursive-table for a recursive-query run.  The output of the recursive-query
   120710 ** is added back into the Queue table.  Then another row is extracted from Queue
   120711 ** and the iteration continues until the Queue table is empty.
   120712 **
   120713 ** If the compound query operator is UNION then no duplicate rows are ever
   120714 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
   120715 ** that have ever been inserted into Queue and causes duplicates to be
   120716 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
   120717 **
   120718 ** If the query has an ORDER BY, then entries in the Queue table are kept in
   120719 ** ORDER BY order and the first entry is extracted for each cycle.  Without
   120720 ** an ORDER BY, the Queue table is just a FIFO.
   120721 **
   120722 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
   120723 ** have been output to pDest.  A LIMIT of zero means to output no rows and a
   120724 ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
   120725 ** with a positive value, then the first OFFSET outputs are discarded rather
   120726 ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
   120727 ** rows have been skipped.
   120728 */
   120729 static void generateWithRecursiveQuery(
   120730   Parse *pParse,        /* Parsing context */
   120731   Select *p,            /* The recursive SELECT to be coded */
   120732   SelectDest *pDest     /* What to do with query results */
   120733 ){
   120734   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
   120735   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
   120736   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
   120737   Select *pSetup = p->pPrior;   /* The setup query */
   120738   int addrTop;                  /* Top of the loop */
   120739   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
   120740   int iCurrent = 0;             /* The Current table */
   120741   int regCurrent;               /* Register holding Current table */
   120742   int iQueue;                   /* The Queue table */
   120743   int iDistinct = 0;            /* To ensure unique results if UNION */
   120744   int eDest = SRT_Fifo;         /* How to write to Queue */
   120745   SelectDest destQueue;         /* SelectDest targetting the Queue table */
   120746   int i;                        /* Loop counter */
   120747   int rc;                       /* Result code */
   120748   ExprList *pOrderBy;           /* The ORDER BY clause */
   120749   Expr *pLimit;                 /* Saved LIMIT and OFFSET */
   120750   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
   120751 
   120752   /* Obtain authorization to do a recursive query */
   120753   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
   120754 
   120755   /* Process the LIMIT and OFFSET clauses, if they exist */
   120756   addrBreak = sqlite3VdbeMakeLabel(v);
   120757   p->nSelectRow = 320;  /* 4 billion rows */
   120758   computeLimitRegisters(pParse, p, addrBreak);
   120759   pLimit = p->pLimit;
   120760   regLimit = p->iLimit;
   120761   regOffset = p->iOffset;
   120762   p->pLimit = 0;
   120763   p->iLimit = p->iOffset = 0;
   120764   pOrderBy = p->pOrderBy;
   120765 
   120766   /* Locate the cursor number of the Current table */
   120767   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
   120768     if( pSrc->a[i].fg.isRecursive ){
   120769       iCurrent = pSrc->a[i].iCursor;
   120770       break;
   120771     }
   120772   }
   120773 
   120774   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
   120775   ** the Distinct table must be exactly one greater than Queue in order
   120776   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
   120777   iQueue = pParse->nTab++;
   120778   if( p->op==TK_UNION ){
   120779     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
   120780     iDistinct = pParse->nTab++;
   120781   }else{
   120782     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
   120783   }
   120784   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
   120785 
   120786   /* Allocate cursors for Current, Queue, and Distinct. */
   120787   regCurrent = ++pParse->nMem;
   120788   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
   120789   if( pOrderBy ){
   120790     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
   120791     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
   120792                       (char*)pKeyInfo, P4_KEYINFO);
   120793     destQueue.pOrderBy = pOrderBy;
   120794   }else{
   120795     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
   120796   }
   120797   VdbeComment((v, "Queue table"));
   120798   if( iDistinct ){
   120799     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
   120800     p->selFlags |= SF_UsesEphemeral;
   120801   }
   120802 
   120803   /* Detach the ORDER BY clause from the compound SELECT */
   120804   p->pOrderBy = 0;
   120805 
   120806   /* Store the results of the setup-query in Queue. */
   120807   pSetup->pNext = 0;
   120808   rc = sqlite3Select(pParse, pSetup, &destQueue);
   120809   pSetup->pNext = p;
   120810   if( rc ) goto end_of_recursive_query;
   120811 
   120812   /* Find the next row in the Queue and output that row */
   120813   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
   120814 
   120815   /* Transfer the next row in Queue over to Current */
   120816   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
   120817   if( pOrderBy ){
   120818     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
   120819   }else{
   120820     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
   120821   }
   120822   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
   120823 
   120824   /* Output the single row in Current */
   120825   addrCont = sqlite3VdbeMakeLabel(v);
   120826   codeOffset(v, regOffset, addrCont);
   120827   selectInnerLoop(pParse, p, iCurrent,
   120828       0, 0, pDest, addrCont, addrBreak);
   120829   if( regLimit ){
   120830     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
   120831     VdbeCoverage(v);
   120832   }
   120833   sqlite3VdbeResolveLabel(v, addrCont);
   120834 
   120835   /* Execute the recursive SELECT taking the single row in Current as
   120836   ** the value for the recursive-table. Store the results in the Queue.
   120837   */
   120838   if( p->selFlags & SF_Aggregate ){
   120839     sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
   120840   }else{
   120841     p->pPrior = 0;
   120842     sqlite3Select(pParse, p, &destQueue);
   120843     assert( p->pPrior==0 );
   120844     p->pPrior = pSetup;
   120845   }
   120846 
   120847   /* Keep running the loop until the Queue is empty */
   120848   sqlite3VdbeGoto(v, addrTop);
   120849   sqlite3VdbeResolveLabel(v, addrBreak);
   120850 
   120851 end_of_recursive_query:
   120852   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
   120853   p->pOrderBy = pOrderBy;
   120854   p->pLimit = pLimit;
   120855   return;
   120856 }
   120857 #endif /* SQLITE_OMIT_CTE */
   120858 
   120859 /* Forward references */
   120860 static int multiSelectOrderBy(
   120861   Parse *pParse,        /* Parsing context */
   120862   Select *p,            /* The right-most of SELECTs to be coded */
   120863   SelectDest *pDest     /* What to do with query results */
   120864 );
   120865 
   120866 /*
   120867 ** Handle the special case of a compound-select that originates from a
   120868 ** VALUES clause.  By handling this as a special case, we avoid deep
   120869 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
   120870 ** on a VALUES clause.
   120871 **
   120872 ** Because the Select object originates from a VALUES clause:
   120873 **   (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
   120874 **   (2) All terms are UNION ALL
   120875 **   (3) There is no ORDER BY clause
   120876 **
   120877 ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
   120878 ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
   120879 ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
   120880 ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
   120881 */
   120882 static int multiSelectValues(
   120883   Parse *pParse,        /* Parsing context */
   120884   Select *p,            /* The right-most of SELECTs to be coded */
   120885   SelectDest *pDest     /* What to do with query results */
   120886 ){
   120887   Select *pPrior;
   120888   Select *pRightmost = p;
   120889   int nRow = 1;
   120890   int rc = 0;
   120891   assert( p->selFlags & SF_MultiValue );
   120892   do{
   120893     assert( p->selFlags & SF_Values );
   120894     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
   120895     assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
   120896     if( p->pPrior==0 ) break;
   120897     assert( p->pPrior->pNext==p );
   120898     p = p->pPrior;
   120899     nRow++;
   120900   }while(1);
   120901   while( p ){
   120902     pPrior = p->pPrior;
   120903     p->pPrior = 0;
   120904     rc = sqlite3Select(pParse, p, pDest);
   120905     p->pPrior = pPrior;
   120906     if( rc || pRightmost->pLimit ) break;
   120907     p->nSelectRow = nRow;
   120908     p = p->pNext;
   120909   }
   120910   return rc;
   120911 }
   120912 
   120913 /*
   120914 ** This routine is called to process a compound query form from
   120915 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
   120916 ** INTERSECT
   120917 **
   120918 ** "p" points to the right-most of the two queries.  the query on the
   120919 ** left is p->pPrior.  The left query could also be a compound query
   120920 ** in which case this routine will be called recursively.
   120921 **
   120922 ** The results of the total query are to be written into a destination
   120923 ** of type eDest with parameter iParm.
   120924 **
   120925 ** Example 1:  Consider a three-way compound SQL statement.
   120926 **
   120927 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
   120928 **
   120929 ** This statement is parsed up as follows:
   120930 **
   120931 **     SELECT c FROM t3
   120932 **      |
   120933 **      `----->  SELECT b FROM t2
   120934 **                |
   120935 **                `------>  SELECT a FROM t1
   120936 **
   120937 ** The arrows in the diagram above represent the Select.pPrior pointer.
   120938 ** So if this routine is called with p equal to the t3 query, then
   120939 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
   120940 **
   120941 ** Notice that because of the way SQLite parses compound SELECTs, the
   120942 ** individual selects always group from left to right.
   120943 */
   120944 static int multiSelect(
   120945   Parse *pParse,        /* Parsing context */
   120946   Select *p,            /* The right-most of SELECTs to be coded */
   120947   SelectDest *pDest     /* What to do with query results */
   120948 ){
   120949   int rc = SQLITE_OK;   /* Success code from a subroutine */
   120950   Select *pPrior;       /* Another SELECT immediately to our left */
   120951   Vdbe *v;              /* Generate code to this VDBE */
   120952   SelectDest dest;      /* Alternative data destination */
   120953   Select *pDelete = 0;  /* Chain of simple selects to delete */
   120954   sqlite3 *db;          /* Database connection */
   120955 #ifndef SQLITE_OMIT_EXPLAIN
   120956   int iSub1 = 0;        /* EQP id of left-hand query */
   120957   int iSub2 = 0;        /* EQP id of right-hand query */
   120958 #endif
   120959 
   120960   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
   120961   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
   120962   */
   120963   assert( p && p->pPrior );  /* Calling function guarantees this much */
   120964   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
   120965   db = pParse->db;
   120966   pPrior = p->pPrior;
   120967   dest = *pDest;
   120968   if( pPrior->pOrderBy || pPrior->pLimit ){
   120969     sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
   120970       pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
   120971     rc = 1;
   120972     goto multi_select_end;
   120973   }
   120974 
   120975   v = sqlite3GetVdbe(pParse);
   120976   assert( v!=0 );  /* The VDBE already created by calling function */
   120977 
   120978   /* Create the destination temporary table if necessary
   120979   */
   120980   if( dest.eDest==SRT_EphemTab ){
   120981     assert( p->pEList );
   120982     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
   120983     dest.eDest = SRT_Table;
   120984   }
   120985 
   120986   /* Special handling for a compound-select that originates as a VALUES clause.
   120987   */
   120988   if( p->selFlags & SF_MultiValue ){
   120989     rc = multiSelectValues(pParse, p, &dest);
   120990     goto multi_select_end;
   120991   }
   120992 
   120993   /* Make sure all SELECTs in the statement have the same number of elements
   120994   ** in their result sets.
   120995   */
   120996   assert( p->pEList && pPrior->pEList );
   120997   assert( p->pEList->nExpr==pPrior->pEList->nExpr );
   120998 
   120999 #ifndef SQLITE_OMIT_CTE
   121000   if( p->selFlags & SF_Recursive ){
   121001     generateWithRecursiveQuery(pParse, p, &dest);
   121002   }else
   121003 #endif
   121004 
   121005   /* Compound SELECTs that have an ORDER BY clause are handled separately.
   121006   */
   121007   if( p->pOrderBy ){
   121008     return multiSelectOrderBy(pParse, p, pDest);
   121009   }else
   121010 
   121011   /* Generate code for the left and right SELECT statements.
   121012   */
   121013   switch( p->op ){
   121014     case TK_ALL: {
   121015       int addr = 0;
   121016       int nLimit;
   121017       assert( !pPrior->pLimit );
   121018       pPrior->iLimit = p->iLimit;
   121019       pPrior->iOffset = p->iOffset;
   121020       pPrior->pLimit = p->pLimit;
   121021       explainSetInteger(iSub1, pParse->iNextSelectId);
   121022       rc = sqlite3Select(pParse, pPrior, &dest);
   121023       p->pLimit = 0;
   121024       if( rc ){
   121025         goto multi_select_end;
   121026       }
   121027       p->pPrior = 0;
   121028       p->iLimit = pPrior->iLimit;
   121029       p->iOffset = pPrior->iOffset;
   121030       if( p->iLimit ){
   121031         addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
   121032         VdbeComment((v, "Jump ahead if LIMIT reached"));
   121033         if( p->iOffset ){
   121034           sqlite3VdbeAddOp3(v, OP_OffsetLimit,
   121035                             p->iLimit, p->iOffset+1, p->iOffset);
   121036         }
   121037       }
   121038       explainSetInteger(iSub2, pParse->iNextSelectId);
   121039       rc = sqlite3Select(pParse, p, &dest);
   121040       testcase( rc!=SQLITE_OK );
   121041       pDelete = p->pPrior;
   121042       p->pPrior = pPrior;
   121043       p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
   121044       if( pPrior->pLimit
   121045        && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
   121046        && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
   121047       ){
   121048         p->nSelectRow = sqlite3LogEst((u64)nLimit);
   121049       }
   121050       if( addr ){
   121051         sqlite3VdbeJumpHere(v, addr);
   121052       }
   121053       break;
   121054     }
   121055     case TK_EXCEPT:
   121056     case TK_UNION: {
   121057       int unionTab;    /* Cursor number of the temporary table holding result */
   121058       u8 op = 0;       /* One of the SRT_ operations to apply to self */
   121059       int priorOp;     /* The SRT_ operation to apply to prior selects */
   121060       Expr *pLimit;    /* Saved values of p->nLimit  */
   121061       int addr;
   121062       SelectDest uniondest;
   121063 
   121064       testcase( p->op==TK_EXCEPT );
   121065       testcase( p->op==TK_UNION );
   121066       priorOp = SRT_Union;
   121067       if( dest.eDest==priorOp ){
   121068         /* We can reuse a temporary table generated by a SELECT to our
   121069         ** right.
   121070         */
   121071         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
   121072         unionTab = dest.iSDParm;
   121073       }else{
   121074         /* We will need to create our own temporary table to hold the
   121075         ** intermediate results.
   121076         */
   121077         unionTab = pParse->nTab++;
   121078         assert( p->pOrderBy==0 );
   121079         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
   121080         assert( p->addrOpenEphm[0] == -1 );
   121081         p->addrOpenEphm[0] = addr;
   121082         findRightmost(p)->selFlags |= SF_UsesEphemeral;
   121083         assert( p->pEList );
   121084       }
   121085 
   121086       /* Code the SELECT statements to our left
   121087       */
   121088       assert( !pPrior->pOrderBy );
   121089       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
   121090       explainSetInteger(iSub1, pParse->iNextSelectId);
   121091       rc = sqlite3Select(pParse, pPrior, &uniondest);
   121092       if( rc ){
   121093         goto multi_select_end;
   121094       }
   121095 
   121096       /* Code the current SELECT statement
   121097       */
   121098       if( p->op==TK_EXCEPT ){
   121099         op = SRT_Except;
   121100       }else{
   121101         assert( p->op==TK_UNION );
   121102         op = SRT_Union;
   121103       }
   121104       p->pPrior = 0;
   121105       pLimit = p->pLimit;
   121106       p->pLimit = 0;
   121107       uniondest.eDest = op;
   121108       explainSetInteger(iSub2, pParse->iNextSelectId);
   121109       rc = sqlite3Select(pParse, p, &uniondest);
   121110       testcase( rc!=SQLITE_OK );
   121111       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
   121112       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
   121113       sqlite3ExprListDelete(db, p->pOrderBy);
   121114       pDelete = p->pPrior;
   121115       p->pPrior = pPrior;
   121116       p->pOrderBy = 0;
   121117       if( p->op==TK_UNION ){
   121118         p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
   121119       }
   121120       sqlite3ExprDelete(db, p->pLimit);
   121121       p->pLimit = pLimit;
   121122       p->iLimit = 0;
   121123       p->iOffset = 0;
   121124 
   121125       /* Convert the data in the temporary table into whatever form
   121126       ** it is that we currently need.
   121127       */
   121128       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
   121129       if( dest.eDest!=priorOp ){
   121130         int iCont, iBreak, iStart;
   121131         assert( p->pEList );
   121132         iBreak = sqlite3VdbeMakeLabel(v);
   121133         iCont = sqlite3VdbeMakeLabel(v);
   121134         computeLimitRegisters(pParse, p, iBreak);
   121135         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
   121136         iStart = sqlite3VdbeCurrentAddr(v);
   121137         selectInnerLoop(pParse, p, unionTab,
   121138                         0, 0, &dest, iCont, iBreak);
   121139         sqlite3VdbeResolveLabel(v, iCont);
   121140         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
   121141         sqlite3VdbeResolveLabel(v, iBreak);
   121142         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
   121143       }
   121144       break;
   121145     }
   121146     default: assert( p->op==TK_INTERSECT ); {
   121147       int tab1, tab2;
   121148       int iCont, iBreak, iStart;
   121149       Expr *pLimit;
   121150       int addr;
   121151       SelectDest intersectdest;
   121152       int r1;
   121153 
   121154       /* INTERSECT is different from the others since it requires
   121155       ** two temporary tables.  Hence it has its own case.  Begin
   121156       ** by allocating the tables we will need.
   121157       */
   121158       tab1 = pParse->nTab++;
   121159       tab2 = pParse->nTab++;
   121160       assert( p->pOrderBy==0 );
   121161 
   121162       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
   121163       assert( p->addrOpenEphm[0] == -1 );
   121164       p->addrOpenEphm[0] = addr;
   121165       findRightmost(p)->selFlags |= SF_UsesEphemeral;
   121166       assert( p->pEList );
   121167 
   121168       /* Code the SELECTs to our left into temporary table "tab1".
   121169       */
   121170       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
   121171       explainSetInteger(iSub1, pParse->iNextSelectId);
   121172       rc = sqlite3Select(pParse, pPrior, &intersectdest);
   121173       if( rc ){
   121174         goto multi_select_end;
   121175       }
   121176 
   121177       /* Code the current SELECT into temporary table "tab2"
   121178       */
   121179       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
   121180       assert( p->addrOpenEphm[1] == -1 );
   121181       p->addrOpenEphm[1] = addr;
   121182       p->pPrior = 0;
   121183       pLimit = p->pLimit;
   121184       p->pLimit = 0;
   121185       intersectdest.iSDParm = tab2;
   121186       explainSetInteger(iSub2, pParse->iNextSelectId);
   121187       rc = sqlite3Select(pParse, p, &intersectdest);
   121188       testcase( rc!=SQLITE_OK );
   121189       pDelete = p->pPrior;
   121190       p->pPrior = pPrior;
   121191       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   121192       sqlite3ExprDelete(db, p->pLimit);
   121193       p->pLimit = pLimit;
   121194 
   121195       /* Generate code to take the intersection of the two temporary
   121196       ** tables.
   121197       */
   121198       assert( p->pEList );
   121199       iBreak = sqlite3VdbeMakeLabel(v);
   121200       iCont = sqlite3VdbeMakeLabel(v);
   121201       computeLimitRegisters(pParse, p, iBreak);
   121202       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
   121203       r1 = sqlite3GetTempReg(pParse);
   121204       iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
   121205       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
   121206       sqlite3ReleaseTempReg(pParse, r1);
   121207       selectInnerLoop(pParse, p, tab1,
   121208                       0, 0, &dest, iCont, iBreak);
   121209       sqlite3VdbeResolveLabel(v, iCont);
   121210       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
   121211       sqlite3VdbeResolveLabel(v, iBreak);
   121212       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
   121213       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
   121214       break;
   121215     }
   121216   }
   121217 
   121218   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
   121219 
   121220   /* Compute collating sequences used by
   121221   ** temporary tables needed to implement the compound select.
   121222   ** Attach the KeyInfo structure to all temporary tables.
   121223   **
   121224   ** This section is run by the right-most SELECT statement only.
   121225   ** SELECT statements to the left always skip this part.  The right-most
   121226   ** SELECT might also skip this part if it has no ORDER BY clause and
   121227   ** no temp tables are required.
   121228   */
   121229   if( p->selFlags & SF_UsesEphemeral ){
   121230     int i;                        /* Loop counter */
   121231     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
   121232     Select *pLoop;                /* For looping through SELECT statements */
   121233     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
   121234     int nCol;                     /* Number of columns in result set */
   121235 
   121236     assert( p->pNext==0 );
   121237     nCol = p->pEList->nExpr;
   121238     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
   121239     if( !pKeyInfo ){
   121240       rc = SQLITE_NOMEM_BKPT;
   121241       goto multi_select_end;
   121242     }
   121243     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
   121244       *apColl = multiSelectCollSeq(pParse, p, i);
   121245       if( 0==*apColl ){
   121246         *apColl = db->pDfltColl;
   121247       }
   121248     }
   121249 
   121250     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
   121251       for(i=0; i<2; i++){
   121252         int addr = pLoop->addrOpenEphm[i];
   121253         if( addr<0 ){
   121254           /* If [0] is unused then [1] is also unused.  So we can
   121255           ** always safely abort as soon as the first unused slot is found */
   121256           assert( pLoop->addrOpenEphm[1]<0 );
   121257           break;
   121258         }
   121259         sqlite3VdbeChangeP2(v, addr, nCol);
   121260         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
   121261                             P4_KEYINFO);
   121262         pLoop->addrOpenEphm[i] = -1;
   121263       }
   121264     }
   121265     sqlite3KeyInfoUnref(pKeyInfo);
   121266   }
   121267 
   121268 multi_select_end:
   121269   pDest->iSdst = dest.iSdst;
   121270   pDest->nSdst = dest.nSdst;
   121271   sqlite3SelectDelete(db, pDelete);
   121272   return rc;
   121273 }
   121274 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   121275 
   121276 /*
   121277 ** Error message for when two or more terms of a compound select have different
   121278 ** size result sets.
   121279 */
   121280 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
   121281   if( p->selFlags & SF_Values ){
   121282     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
   121283   }else{
   121284     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
   121285       " do not have the same number of result columns", selectOpName(p->op));
   121286   }
   121287 }
   121288 
   121289 /*
   121290 ** Code an output subroutine for a coroutine implementation of a
   121291 ** SELECT statment.
   121292 **
   121293 ** The data to be output is contained in pIn->iSdst.  There are
   121294 ** pIn->nSdst columns to be output.  pDest is where the output should
   121295 ** be sent.
   121296 **
   121297 ** regReturn is the number of the register holding the subroutine
   121298 ** return address.
   121299 **
   121300 ** If regPrev>0 then it is the first register in a vector that
   121301 ** records the previous output.  mem[regPrev] is a flag that is false
   121302 ** if there has been no previous output.  If regPrev>0 then code is
   121303 ** generated to suppress duplicates.  pKeyInfo is used for comparing
   121304 ** keys.
   121305 **
   121306 ** If the LIMIT found in p->iLimit is reached, jump immediately to
   121307 ** iBreak.
   121308 */
   121309 static int generateOutputSubroutine(
   121310   Parse *pParse,          /* Parsing context */
   121311   Select *p,              /* The SELECT statement */
   121312   SelectDest *pIn,        /* Coroutine supplying data */
   121313   SelectDest *pDest,      /* Where to send the data */
   121314   int regReturn,          /* The return address register */
   121315   int regPrev,            /* Previous result register.  No uniqueness if 0 */
   121316   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
   121317   int iBreak              /* Jump here if we hit the LIMIT */
   121318 ){
   121319   Vdbe *v = pParse->pVdbe;
   121320   int iContinue;
   121321   int addr;
   121322 
   121323   addr = sqlite3VdbeCurrentAddr(v);
   121324   iContinue = sqlite3VdbeMakeLabel(v);
   121325 
   121326   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   121327   */
   121328   if( regPrev ){
   121329     int addr1, addr2;
   121330     addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
   121331     addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
   121332                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
   121333     sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
   121334     sqlite3VdbeJumpHere(v, addr1);
   121335     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
   121336     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
   121337   }
   121338   if( pParse->db->mallocFailed ) return 0;
   121339 
   121340   /* Suppress the first OFFSET entries if there is an OFFSET clause
   121341   */
   121342   codeOffset(v, p->iOffset, iContinue);
   121343 
   121344   assert( pDest->eDest!=SRT_Exists );
   121345   assert( pDest->eDest!=SRT_Table );
   121346   switch( pDest->eDest ){
   121347     /* Store the result as data using a unique key.
   121348     */
   121349     case SRT_EphemTab: {
   121350       int r1 = sqlite3GetTempReg(pParse);
   121351       int r2 = sqlite3GetTempReg(pParse);
   121352       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
   121353       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
   121354       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
   121355       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   121356       sqlite3ReleaseTempReg(pParse, r2);
   121357       sqlite3ReleaseTempReg(pParse, r1);
   121358       break;
   121359     }
   121360 
   121361 #ifndef SQLITE_OMIT_SUBQUERY
   121362     /* If we are creating a set for an "expr IN (SELECT ...)".
   121363     */
   121364     case SRT_Set: {
   121365       int r1;
   121366       testcase( pIn->nSdst>1 );
   121367       r1 = sqlite3GetTempReg(pParse);
   121368       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
   121369           r1, pDest->zAffSdst, pIn->nSdst);
   121370       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
   121371       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
   121372                            pIn->iSdst, pIn->nSdst);
   121373       sqlite3ReleaseTempReg(pParse, r1);
   121374       break;
   121375     }
   121376 
   121377     /* If this is a scalar select that is part of an expression, then
   121378     ** store the results in the appropriate memory cell and break out
   121379     ** of the scan loop.
   121380     */
   121381     case SRT_Mem: {
   121382       assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
   121383       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
   121384       /* The LIMIT clause will jump out of the loop for us */
   121385       break;
   121386     }
   121387 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   121388 
   121389     /* The results are stored in a sequence of registers
   121390     ** starting at pDest->iSdst.  Then the co-routine yields.
   121391     */
   121392     case SRT_Coroutine: {
   121393       if( pDest->iSdst==0 ){
   121394         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
   121395         pDest->nSdst = pIn->nSdst;
   121396       }
   121397       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
   121398       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
   121399       break;
   121400     }
   121401 
   121402     /* If none of the above, then the result destination must be
   121403     ** SRT_Output.  This routine is never called with any other
   121404     ** destination other than the ones handled above or SRT_Output.
   121405     **
   121406     ** For SRT_Output, results are stored in a sequence of registers.
   121407     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
   121408     ** return the next row of result.
   121409     */
   121410     default: {
   121411       assert( pDest->eDest==SRT_Output );
   121412       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
   121413       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
   121414       break;
   121415     }
   121416   }
   121417 
   121418   /* Jump to the end of the loop if the LIMIT is reached.
   121419   */
   121420   if( p->iLimit ){
   121421     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
   121422   }
   121423 
   121424   /* Generate the subroutine return
   121425   */
   121426   sqlite3VdbeResolveLabel(v, iContinue);
   121427   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
   121428 
   121429   return addr;
   121430 }
   121431 
   121432 /*
   121433 ** Alternative compound select code generator for cases when there
   121434 ** is an ORDER BY clause.
   121435 **
   121436 ** We assume a query of the following form:
   121437 **
   121438 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
   121439 **
   121440 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
   121441 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
   121442 ** co-routines.  Then run the co-routines in parallel and merge the results
   121443 ** into the output.  In addition to the two coroutines (called selectA and
   121444 ** selectB) there are 7 subroutines:
   121445 **
   121446 **    outA:    Move the output of the selectA coroutine into the output
   121447 **             of the compound query.
   121448 **
   121449 **    outB:    Move the output of the selectB coroutine into the output
   121450 **             of the compound query.  (Only generated for UNION and
   121451 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
   121452 **             appears only in B.)
   121453 **
   121454 **    AltB:    Called when there is data from both coroutines and A<B.
   121455 **
   121456 **    AeqB:    Called when there is data from both coroutines and A==B.
   121457 **
   121458 **    AgtB:    Called when there is data from both coroutines and A>B.
   121459 **
   121460 **    EofA:    Called when data is exhausted from selectA.
   121461 **
   121462 **    EofB:    Called when data is exhausted from selectB.
   121463 **
   121464 ** The implementation of the latter five subroutines depend on which
   121465 ** <operator> is used:
   121466 **
   121467 **
   121468 **             UNION ALL         UNION            EXCEPT          INTERSECT
   121469 **          -------------  -----------------  --------------  -----------------
   121470 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
   121471 **
   121472 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
   121473 **
   121474 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
   121475 **
   121476 **   EofA:   outB, nextB      outB, nextB          halt             halt
   121477 **
   121478 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
   121479 **
   121480 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
   121481 ** causes an immediate jump to EofA and an EOF on B following nextB causes
   121482 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
   121483 ** following nextX causes a jump to the end of the select processing.
   121484 **
   121485 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
   121486 ** within the output subroutine.  The regPrev register set holds the previously
   121487 ** output value.  A comparison is made against this value and the output
   121488 ** is skipped if the next results would be the same as the previous.
   121489 **
   121490 ** The implementation plan is to implement the two coroutines and seven
   121491 ** subroutines first, then put the control logic at the bottom.  Like this:
   121492 **
   121493 **          goto Init
   121494 **     coA: coroutine for left query (A)
   121495 **     coB: coroutine for right query (B)
   121496 **    outA: output one row of A
   121497 **    outB: output one row of B (UNION and UNION ALL only)
   121498 **    EofA: ...
   121499 **    EofB: ...
   121500 **    AltB: ...
   121501 **    AeqB: ...
   121502 **    AgtB: ...
   121503 **    Init: initialize coroutine registers
   121504 **          yield coA
   121505 **          if eof(A) goto EofA
   121506 **          yield coB
   121507 **          if eof(B) goto EofB
   121508 **    Cmpr: Compare A, B
   121509 **          Jump AltB, AeqB, AgtB
   121510 **     End: ...
   121511 **
   121512 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
   121513 ** actually called using Gosub and they do not Return.  EofA and EofB loop
   121514 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
   121515 ** and AgtB jump to either L2 or to one of EofA or EofB.
   121516 */
   121517 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   121518 static int multiSelectOrderBy(
   121519   Parse *pParse,        /* Parsing context */
   121520   Select *p,            /* The right-most of SELECTs to be coded */
   121521   SelectDest *pDest     /* What to do with query results */
   121522 ){
   121523   int i, j;             /* Loop counters */
   121524   Select *pPrior;       /* Another SELECT immediately to our left */
   121525   Vdbe *v;              /* Generate code to this VDBE */
   121526   SelectDest destA;     /* Destination for coroutine A */
   121527   SelectDest destB;     /* Destination for coroutine B */
   121528   int regAddrA;         /* Address register for select-A coroutine */
   121529   int regAddrB;         /* Address register for select-B coroutine */
   121530   int addrSelectA;      /* Address of the select-A coroutine */
   121531   int addrSelectB;      /* Address of the select-B coroutine */
   121532   int regOutA;          /* Address register for the output-A subroutine */
   121533   int regOutB;          /* Address register for the output-B subroutine */
   121534   int addrOutA;         /* Address of the output-A subroutine */
   121535   int addrOutB = 0;     /* Address of the output-B subroutine */
   121536   int addrEofA;         /* Address of the select-A-exhausted subroutine */
   121537   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
   121538   int addrEofB;         /* Address of the select-B-exhausted subroutine */
   121539   int addrAltB;         /* Address of the A<B subroutine */
   121540   int addrAeqB;         /* Address of the A==B subroutine */
   121541   int addrAgtB;         /* Address of the A>B subroutine */
   121542   int regLimitA;        /* Limit register for select-A */
   121543   int regLimitB;        /* Limit register for select-A */
   121544   int regPrev;          /* A range of registers to hold previous output */
   121545   int savedLimit;       /* Saved value of p->iLimit */
   121546   int savedOffset;      /* Saved value of p->iOffset */
   121547   int labelCmpr;        /* Label for the start of the merge algorithm */
   121548   int labelEnd;         /* Label for the end of the overall SELECT stmt */
   121549   int addr1;            /* Jump instructions that get retargetted */
   121550   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
   121551   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
   121552   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
   121553   sqlite3 *db;          /* Database connection */
   121554   ExprList *pOrderBy;   /* The ORDER BY clause */
   121555   int nOrderBy;         /* Number of terms in the ORDER BY clause */
   121556   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
   121557 #ifndef SQLITE_OMIT_EXPLAIN
   121558   int iSub1;            /* EQP id of left-hand query */
   121559   int iSub2;            /* EQP id of right-hand query */
   121560 #endif
   121561 
   121562   assert( p->pOrderBy!=0 );
   121563   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
   121564   db = pParse->db;
   121565   v = pParse->pVdbe;
   121566   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
   121567   labelEnd = sqlite3VdbeMakeLabel(v);
   121568   labelCmpr = sqlite3VdbeMakeLabel(v);
   121569 
   121570 
   121571   /* Patch up the ORDER BY clause
   121572   */
   121573   op = p->op;
   121574   pPrior = p->pPrior;
   121575   assert( pPrior->pOrderBy==0 );
   121576   pOrderBy = p->pOrderBy;
   121577   assert( pOrderBy );
   121578   nOrderBy = pOrderBy->nExpr;
   121579 
   121580   /* For operators other than UNION ALL we have to make sure that
   121581   ** the ORDER BY clause covers every term of the result set.  Add
   121582   ** terms to the ORDER BY clause as necessary.
   121583   */
   121584   if( op!=TK_ALL ){
   121585     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
   121586       struct ExprList_item *pItem;
   121587       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
   121588         assert( pItem->u.x.iOrderByCol>0 );
   121589         if( pItem->u.x.iOrderByCol==i ) break;
   121590       }
   121591       if( j==nOrderBy ){
   121592         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   121593         if( pNew==0 ) return SQLITE_NOMEM_BKPT;
   121594         pNew->flags |= EP_IntValue;
   121595         pNew->u.iValue = i;
   121596         p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
   121597         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
   121598       }
   121599     }
   121600   }
   121601 
   121602   /* Compute the comparison permutation and keyinfo that is used with
   121603   ** the permutation used to determine if the next
   121604   ** row of results comes from selectA or selectB.  Also add explicit
   121605   ** collations to the ORDER BY clause terms so that when the subqueries
   121606   ** to the right and the left are evaluated, they use the correct
   121607   ** collation.
   121608   */
   121609   aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
   121610   if( aPermute ){
   121611     struct ExprList_item *pItem;
   121612     aPermute[0] = nOrderBy;
   121613     for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
   121614       assert( pItem->u.x.iOrderByCol>0 );
   121615       assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
   121616       aPermute[i] = pItem->u.x.iOrderByCol - 1;
   121617     }
   121618     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
   121619   }else{
   121620     pKeyMerge = 0;
   121621   }
   121622 
   121623   /* Reattach the ORDER BY clause to the query.
   121624   */
   121625   p->pOrderBy = pOrderBy;
   121626   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   121627 
   121628   /* Allocate a range of temporary registers and the KeyInfo needed
   121629   ** for the logic that removes duplicate result rows when the
   121630   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
   121631   */
   121632   if( op==TK_ALL ){
   121633     regPrev = 0;
   121634   }else{
   121635     int nExpr = p->pEList->nExpr;
   121636     assert( nOrderBy>=nExpr || db->mallocFailed );
   121637     regPrev = pParse->nMem+1;
   121638     pParse->nMem += nExpr+1;
   121639     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
   121640     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
   121641     if( pKeyDup ){
   121642       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
   121643       for(i=0; i<nExpr; i++){
   121644         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
   121645         pKeyDup->aSortOrder[i] = 0;
   121646       }
   121647     }
   121648   }
   121649 
   121650   /* Separate the left and the right query from one another
   121651   */
   121652   p->pPrior = 0;
   121653   pPrior->pNext = 0;
   121654   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
   121655   if( pPrior->pPrior==0 ){
   121656     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
   121657   }
   121658 
   121659   /* Compute the limit registers */
   121660   computeLimitRegisters(pParse, p, labelEnd);
   121661   if( p->iLimit && op==TK_ALL ){
   121662     regLimitA = ++pParse->nMem;
   121663     regLimitB = ++pParse->nMem;
   121664     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
   121665                                   regLimitA);
   121666     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
   121667   }else{
   121668     regLimitA = regLimitB = 0;
   121669   }
   121670   sqlite3ExprDelete(db, p->pLimit);
   121671   p->pLimit = 0;
   121672 
   121673   regAddrA = ++pParse->nMem;
   121674   regAddrB = ++pParse->nMem;
   121675   regOutA = ++pParse->nMem;
   121676   regOutB = ++pParse->nMem;
   121677   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   121678   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
   121679 
   121680   /* Generate a coroutine to evaluate the SELECT statement to the
   121681   ** left of the compound operator - the "A" select.
   121682   */
   121683   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
   121684   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
   121685   VdbeComment((v, "left SELECT"));
   121686   pPrior->iLimit = regLimitA;
   121687   explainSetInteger(iSub1, pParse->iNextSelectId);
   121688   sqlite3Select(pParse, pPrior, &destA);
   121689   sqlite3VdbeEndCoroutine(v, regAddrA);
   121690   sqlite3VdbeJumpHere(v, addr1);
   121691 
   121692   /* Generate a coroutine to evaluate the SELECT statement on
   121693   ** the right - the "B" select
   121694   */
   121695   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
   121696   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
   121697   VdbeComment((v, "right SELECT"));
   121698   savedLimit = p->iLimit;
   121699   savedOffset = p->iOffset;
   121700   p->iLimit = regLimitB;
   121701   p->iOffset = 0;
   121702   explainSetInteger(iSub2, pParse->iNextSelectId);
   121703   sqlite3Select(pParse, p, &destB);
   121704   p->iLimit = savedLimit;
   121705   p->iOffset = savedOffset;
   121706   sqlite3VdbeEndCoroutine(v, regAddrB);
   121707 
   121708   /* Generate a subroutine that outputs the current row of the A
   121709   ** select as the next output row of the compound select.
   121710   */
   121711   VdbeNoopComment((v, "Output routine for A"));
   121712   addrOutA = generateOutputSubroutine(pParse,
   121713                  p, &destA, pDest, regOutA,
   121714                  regPrev, pKeyDup, labelEnd);
   121715 
   121716   /* Generate a subroutine that outputs the current row of the B
   121717   ** select as the next output row of the compound select.
   121718   */
   121719   if( op==TK_ALL || op==TK_UNION ){
   121720     VdbeNoopComment((v, "Output routine for B"));
   121721     addrOutB = generateOutputSubroutine(pParse,
   121722                  p, &destB, pDest, regOutB,
   121723                  regPrev, pKeyDup, labelEnd);
   121724   }
   121725   sqlite3KeyInfoUnref(pKeyDup);
   121726 
   121727   /* Generate a subroutine to run when the results from select A
   121728   ** are exhausted and only data in select B remains.
   121729   */
   121730   if( op==TK_EXCEPT || op==TK_INTERSECT ){
   121731     addrEofA_noB = addrEofA = labelEnd;
   121732   }else{
   121733     VdbeNoopComment((v, "eof-A subroutine"));
   121734     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   121735     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
   121736                                      VdbeCoverage(v);
   121737     sqlite3VdbeGoto(v, addrEofA);
   121738     p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
   121739   }
   121740 
   121741   /* Generate a subroutine to run when the results from select B
   121742   ** are exhausted and only data in select A remains.
   121743   */
   121744   if( op==TK_INTERSECT ){
   121745     addrEofB = addrEofA;
   121746     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   121747   }else{
   121748     VdbeNoopComment((v, "eof-B subroutine"));
   121749     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   121750     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
   121751     sqlite3VdbeGoto(v, addrEofB);
   121752   }
   121753 
   121754   /* Generate code to handle the case of A<B
   121755   */
   121756   VdbeNoopComment((v, "A-lt-B subroutine"));
   121757   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   121758   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
   121759   sqlite3VdbeGoto(v, labelCmpr);
   121760 
   121761   /* Generate code to handle the case of A==B
   121762   */
   121763   if( op==TK_ALL ){
   121764     addrAeqB = addrAltB;
   121765   }else if( op==TK_INTERSECT ){
   121766     addrAeqB = addrAltB;
   121767     addrAltB++;
   121768   }else{
   121769     VdbeNoopComment((v, "A-eq-B subroutine"));
   121770     addrAeqB =
   121771     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
   121772     sqlite3VdbeGoto(v, labelCmpr);
   121773   }
   121774 
   121775   /* Generate code to handle the case of A>B
   121776   */
   121777   VdbeNoopComment((v, "A-gt-B subroutine"));
   121778   addrAgtB = sqlite3VdbeCurrentAddr(v);
   121779   if( op==TK_ALL || op==TK_UNION ){
   121780     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   121781   }
   121782   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
   121783   sqlite3VdbeGoto(v, labelCmpr);
   121784 
   121785   /* This code runs once to initialize everything.
   121786   */
   121787   sqlite3VdbeJumpHere(v, addr1);
   121788   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
   121789   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
   121790 
   121791   /* Implement the main merge loop
   121792   */
   121793   sqlite3VdbeResolveLabel(v, labelCmpr);
   121794   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
   121795   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
   121796                          (char*)pKeyMerge, P4_KEYINFO);
   121797   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
   121798   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
   121799 
   121800   /* Jump to the this point in order to terminate the query.
   121801   */
   121802   sqlite3VdbeResolveLabel(v, labelEnd);
   121803 
   121804   /* Reassembly the compound query so that it will be freed correctly
   121805   ** by the calling function */
   121806   if( p->pPrior ){
   121807     sqlite3SelectDelete(db, p->pPrior);
   121808   }
   121809   p->pPrior = pPrior;
   121810   pPrior->pNext = p;
   121811 
   121812   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   121813   **** subqueries ****/
   121814   explainComposite(pParse, p->op, iSub1, iSub2, 0);
   121815   return pParse->nErr!=0;
   121816 }
   121817 #endif
   121818 
   121819 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   121820 
   121821 /* An instance of the SubstContext object describes an substitution edit
   121822 ** to be performed on a parse tree.
   121823 **
   121824 ** All references to columns in table iTable are to be replaced by corresponding
   121825 ** expressions in pEList.
   121826 */
   121827 typedef struct SubstContext {
   121828   Parse *pParse;            /* The parsing context */
   121829   int iTable;               /* Replace references to this table */
   121830   int iNewTable;            /* New table number */
   121831   int isLeftJoin;           /* Add TK_IF_NULL_ROW opcodes on each replacement */
   121832   ExprList *pEList;         /* Replacement expressions */
   121833 } SubstContext;
   121834 
   121835 /* Forward Declarations */
   121836 static void substExprList(SubstContext*, ExprList*);
   121837 static void substSelect(SubstContext*, Select*, int);
   121838 
   121839 /*
   121840 ** Scan through the expression pExpr.  Replace every reference to
   121841 ** a column in table number iTable with a copy of the iColumn-th
   121842 ** entry in pEList.  (But leave references to the ROWID column
   121843 ** unchanged.)
   121844 **
   121845 ** This routine is part of the flattening procedure.  A subquery
   121846 ** whose result set is defined by pEList appears as entry in the
   121847 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
   121848 ** FORM clause entry is iTable.  This routine makes the necessary
   121849 ** changes to pExpr so that it refers directly to the source table
   121850 ** of the subquery rather the result set of the subquery.
   121851 */
   121852 static Expr *substExpr(
   121853   SubstContext *pSubst,  /* Description of the substitution */
   121854   Expr *pExpr            /* Expr in which substitution occurs */
   121855 ){
   121856   if( pExpr==0 ) return 0;
   121857   if( ExprHasProperty(pExpr, EP_FromJoin)
   121858    && pExpr->iRightJoinTable==pSubst->iTable
   121859   ){
   121860     pExpr->iRightJoinTable = pSubst->iNewTable;
   121861   }
   121862   if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
   121863     if( pExpr->iColumn<0 ){
   121864       pExpr->op = TK_NULL;
   121865     }else{
   121866       Expr *pNew;
   121867       Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
   121868       Expr ifNullRow;
   121869       assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
   121870       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   121871       if( sqlite3ExprIsVector(pCopy) ){
   121872         sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
   121873       }else{
   121874         sqlite3 *db = pSubst->pParse->db;
   121875         if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
   121876           memset(&ifNullRow, 0, sizeof(ifNullRow));
   121877           ifNullRow.op = TK_IF_NULL_ROW;
   121878           ifNullRow.pLeft = pCopy;
   121879           ifNullRow.iTable = pSubst->iNewTable;
   121880           pCopy = &ifNullRow;
   121881         }
   121882         pNew = sqlite3ExprDup(db, pCopy, 0);
   121883         if( pNew && pSubst->isLeftJoin ){
   121884           ExprSetProperty(pNew, EP_CanBeNull);
   121885         }
   121886         if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
   121887           pNew->iRightJoinTable = pExpr->iRightJoinTable;
   121888           ExprSetProperty(pNew, EP_FromJoin);
   121889         }
   121890         sqlite3ExprDelete(db, pExpr);
   121891         pExpr = pNew;
   121892       }
   121893     }
   121894   }else{
   121895     if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
   121896       pExpr->iTable = pSubst->iNewTable;
   121897     }
   121898     pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
   121899     pExpr->pRight = substExpr(pSubst, pExpr->pRight);
   121900     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   121901       substSelect(pSubst, pExpr->x.pSelect, 1);
   121902     }else{
   121903       substExprList(pSubst, pExpr->x.pList);
   121904     }
   121905   }
   121906   return pExpr;
   121907 }
   121908 static void substExprList(
   121909   SubstContext *pSubst, /* Description of the substitution */
   121910   ExprList *pList       /* List to scan and in which to make substitutes */
   121911 ){
   121912   int i;
   121913   if( pList==0 ) return;
   121914   for(i=0; i<pList->nExpr; i++){
   121915     pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
   121916   }
   121917 }
   121918 static void substSelect(
   121919   SubstContext *pSubst, /* Description of the substitution */
   121920   Select *p,            /* SELECT statement in which to make substitutions */
   121921   int doPrior           /* Do substitutes on p->pPrior too */
   121922 ){
   121923   SrcList *pSrc;
   121924   struct SrcList_item *pItem;
   121925   int i;
   121926   if( !p ) return;
   121927   do{
   121928     substExprList(pSubst, p->pEList);
   121929     substExprList(pSubst, p->pGroupBy);
   121930     substExprList(pSubst, p->pOrderBy);
   121931     p->pHaving = substExpr(pSubst, p->pHaving);
   121932     p->pWhere = substExpr(pSubst, p->pWhere);
   121933     pSrc = p->pSrc;
   121934     assert( pSrc!=0 );
   121935     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   121936       substSelect(pSubst, pItem->pSelect, 1);
   121937       if( pItem->fg.isTabFunc ){
   121938         substExprList(pSubst, pItem->u1.pFuncArg);
   121939       }
   121940     }
   121941   }while( doPrior && (p = p->pPrior)!=0 );
   121942 }
   121943 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   121944 
   121945 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   121946 /*
   121947 ** This routine attempts to flatten subqueries as a performance optimization.
   121948 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
   121949 **
   121950 ** To understand the concept of flattening, consider the following
   121951 ** query:
   121952 **
   121953 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
   121954 **
   121955 ** The default way of implementing this query is to execute the
   121956 ** subquery first and store the results in a temporary table, then
   121957 ** run the outer query on that temporary table.  This requires two
   121958 ** passes over the data.  Furthermore, because the temporary table
   121959 ** has no indices, the WHERE clause on the outer query cannot be
   121960 ** optimized.
   121961 **
   121962 ** This routine attempts to rewrite queries such as the above into
   121963 ** a single flat select, like this:
   121964 **
   121965 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
   121966 **
   121967 ** The code generated for this simplification gives the same result
   121968 ** but only has to scan the data once.  And because indices might
   121969 ** exist on the table t1, a complete scan of the data might be
   121970 ** avoided.
   121971 **
   121972 ** Flattening is subject to the following constraints:
   121973 **
   121974 **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
   121975 **        The subquery and the outer query cannot both be aggregates.
   121976 **
   121977 **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
   121978 **        (2) If the subquery is an aggregate then
   121979 **        (2a) the outer query must not be a join and
   121980 **        (2b) the outer query must not use subqueries
   121981 **             other than the one FROM-clause subquery that is a candidate
   121982 **             for flattening.  (This is due to ticket [2f7170d73bf9abf80]
   121983 **             from 2015-02-09.)
   121984 **
   121985 **   (3)  If the subquery is the right operand of a LEFT JOIN then
   121986 **        (3a) the subquery may not be a join and
   121987 **        (3b) the FROM clause of the subquery may not contain a virtual
   121988 **             table and
   121989 **        (3c) the outer query may not be an aggregate.
   121990 **
   121991 **   (4)  The subquery can not be DISTINCT.
   121992 **
   121993 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
   121994 **        sub-queries that were excluded from this optimization. Restriction
   121995 **        (4) has since been expanded to exclude all DISTINCT subqueries.
   121996 **
   121997 **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
   121998 **        If the subquery is aggregate, the outer query may not be DISTINCT.
   121999 **
   122000 **   (7)  The subquery must have a FROM clause.  TODO:  For subqueries without
   122001 **        A FROM clause, consider adding a FROM clause with the special
   122002 **        table sqlite_once that consists of a single row containing a
   122003 **        single NULL.
   122004 **
   122005 **   (8)  If the subquery uses LIMIT then the outer query may not be a join.
   122006 **
   122007 **   (9)  If the subquery uses LIMIT then the outer query may not be aggregate.
   122008 **
   122009 **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
   122010 **        accidently carried the comment forward until 2014-09-15.  Original
   122011 **        constraint: "If the subquery is aggregate then the outer query
   122012 **        may not use LIMIT."
   122013 **
   122014 **  (11)  The subquery and the outer query may not both have ORDER BY clauses.
   122015 **
   122016 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
   122017 **        a separate restriction deriving from ticket #350.
   122018 **
   122019 **  (13)  The subquery and outer query may not both use LIMIT.
   122020 **
   122021 **  (14)  The subquery may not use OFFSET.
   122022 **
   122023 **  (15)  If the outer query is part of a compound select, then the
   122024 **        subquery may not use LIMIT.
   122025 **        (See ticket #2339 and ticket [02a8e81d44]).
   122026 **
   122027 **  (16)  If the outer query is aggregate, then the subquery may not
   122028 **        use ORDER BY.  (Ticket #2942)  This used to not matter
   122029 **        until we introduced the group_concat() function.
   122030 **
   122031 **  (17)  If the subquery is a compound select, then
   122032 **        (17a) all compound operators must be a UNION ALL, and
   122033 **        (17b) no terms within the subquery compound may be aggregate
   122034 **              or DISTINCT, and
   122035 **        (17c) every term within the subquery compound must have a FROM clause
   122036 **        (17d) the outer query may not be
   122037 **              (17d1) aggregate, or
   122038 **              (17d2) DISTINCT, or
   122039 **              (17d3) a join.
   122040 **
   122041 **        The parent and sub-query may contain WHERE clauses. Subject to
   122042 **        rules (11), (13) and (14), they may also contain ORDER BY,
   122043 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
   122044 **        operator other than UNION ALL because all the other compound
   122045 **        operators have an implied DISTINCT which is disallowed by
   122046 **        restriction (4).
   122047 **
   122048 **        Also, each component of the sub-query must return the same number
   122049 **        of result columns. This is actually a requirement for any compound
   122050 **        SELECT statement, but all the code here does is make sure that no
   122051 **        such (illegal) sub-query is flattened. The caller will detect the
   122052 **        syntax error and return a detailed message.
   122053 **
   122054 **  (18)  If the sub-query is a compound select, then all terms of the
   122055 **        ORDER BY clause of the parent must be simple references to
   122056 **        columns of the sub-query.
   122057 **
   122058 **  (19)  If the subquery uses LIMIT then the outer query may not
   122059 **        have a WHERE clause.
   122060 **
   122061 **  (20)  If the sub-query is a compound select, then it must not use
   122062 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
   122063 **        somewhat by saying that the terms of the ORDER BY clause must
   122064 **        appear as unmodified result columns in the outer query.  But we
   122065 **        have other optimizations in mind to deal with that case.
   122066 **
   122067 **  (21)  If the subquery uses LIMIT then the outer query may not be
   122068 **        DISTINCT.  (See ticket [752e1646fc]).
   122069 **
   122070 **  (22)  The subquery may not be a recursive CTE.
   122071 **
   122072 **  (**)  Subsumed into restriction (17d3).  Was: If the outer query is
   122073 **        a recursive CTE, then the sub-query may not be a compound query.
   122074 **        This restriction is because transforming the
   122075 **        parent to a compound query confuses the code that handles
   122076 **        recursive queries in multiSelect().
   122077 **
   122078 **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
   122079 **        The subquery may not be an aggregate that uses the built-in min() or
   122080 **        or max() functions.  (Without this restriction, a query like:
   122081 **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
   122082 **        return the value X for which Y was maximal.)
   122083 **
   122084 **
   122085 ** In this routine, the "p" parameter is a pointer to the outer query.
   122086 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
   122087 ** uses aggregates.
   122088 **
   122089 ** If flattening is not attempted, this routine is a no-op and returns 0.
   122090 ** If flattening is attempted this routine returns 1.
   122091 **
   122092 ** All of the expression analysis must occur on both the outer query and
   122093 ** the subquery before this routine runs.
   122094 */
   122095 static int flattenSubquery(
   122096   Parse *pParse,       /* Parsing context */
   122097   Select *p,           /* The parent or outer SELECT statement */
   122098   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
   122099   int isAgg            /* True if outer SELECT uses aggregate functions */
   122100 ){
   122101   const char *zSavedAuthContext = pParse->zAuthContext;
   122102   Select *pParent;    /* Current UNION ALL term of the other query */
   122103   Select *pSub;       /* The inner query or "subquery" */
   122104   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
   122105   SrcList *pSrc;      /* The FROM clause of the outer query */
   122106   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   122107   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   122108   int iNewParent = -1;/* Replacement table for iParent */
   122109   int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
   122110   int i;              /* Loop counter */
   122111   Expr *pWhere;                    /* The WHERE clause */
   122112   struct SrcList_item *pSubitem;   /* The subquery */
   122113   sqlite3 *db = pParse->db;
   122114 
   122115   /* Check to see if flattening is permitted.  Return 0 if not.
   122116   */
   122117   assert( p!=0 );
   122118   assert( p->pPrior==0 );
   122119   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
   122120   pSrc = p->pSrc;
   122121   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
   122122   pSubitem = &pSrc->a[iFrom];
   122123   iParent = pSubitem->iCursor;
   122124   pSub = pSubitem->pSelect;
   122125   assert( pSub!=0 );
   122126 
   122127   pSubSrc = pSub->pSrc;
   122128   assert( pSubSrc );
   122129   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
   122130   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
   122131   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
   122132   ** became arbitrary expressions, we were forced to add restrictions (13)
   122133   ** and (14). */
   122134   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
   122135   if( pSub->pLimit && pSub->pLimit->pRight ) return 0;   /* Restriction (14) */
   122136   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
   122137     return 0;                                            /* Restriction (15) */
   122138   }
   122139   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
   122140   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (4)  */
   122141   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
   122142      return 0;         /* Restrictions (8)(9) */
   122143   }
   122144   if( p->pOrderBy && pSub->pOrderBy ){
   122145      return 0;                                           /* Restriction (11) */
   122146   }
   122147   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
   122148   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
   122149   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
   122150      return 0;         /* Restriction (21) */
   122151   }
   122152   if( pSub->selFlags & (SF_Recursive) ){
   122153     return 0; /* Restrictions (22) */
   122154   }
   122155 
   122156   /*
   122157   ** If the subquery is the right operand of a LEFT JOIN, then the
   122158   ** subquery may not be a join itself (3a). Example of why this is not
   122159   ** allowed:
   122160   **
   122161   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
   122162   **
   122163   ** If we flatten the above, we would get
   122164   **
   122165   **         (t1 LEFT OUTER JOIN t2) JOIN t3
   122166   **
   122167   ** which is not at all the same thing.
   122168   **
   122169   ** If the subquery is the right operand of a LEFT JOIN, then the outer
   122170   ** query cannot be an aggregate. (3c)  This is an artifact of the way
   122171   ** aggregates are processed - there is no mechanism to determine if
   122172   ** the LEFT JOIN table should be all-NULL.
   122173   **
   122174   ** See also tickets #306, #350, and #3300.
   122175   */
   122176   if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
   122177     isLeftJoin = 1;
   122178     if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
   122179       /*  (3a)             (3c)     (3b) */
   122180       return 0;
   122181     }
   122182   }
   122183 #ifdef SQLITE_EXTRA_IFNULLROW
   122184   else if( iFrom>0 && !isAgg ){
   122185     /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
   122186     ** every reference to any result column from subquery in a join, even
   122187     ** though they are not necessary.  This will stress-test the OP_IfNullRow
   122188     ** opcode. */
   122189     isLeftJoin = -1;
   122190   }
   122191 #endif
   122192 
   122193   /* Restriction (17): If the sub-query is a compound SELECT, then it must
   122194   ** use only the UNION ALL operator. And none of the simple select queries
   122195   ** that make up the compound SELECT are allowed to be aggregate or distinct
   122196   ** queries.
   122197   */
   122198   if( pSub->pPrior ){
   122199     if( pSub->pOrderBy ){
   122200       return 0;  /* Restriction (20) */
   122201     }
   122202     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
   122203       return 0; /* (17d1), (17d2), or (17d3) */
   122204     }
   122205     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
   122206       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   122207       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   122208       assert( pSub->pSrc!=0 );
   122209       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
   122210       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
   122211        || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
   122212        || pSub1->pSrc->nSrc<1                                  /* (17c) */
   122213       ){
   122214         return 0;
   122215       }
   122216       testcase( pSub1->pSrc->nSrc>1 );
   122217     }
   122218 
   122219     /* Restriction (18). */
   122220     if( p->pOrderBy ){
   122221       int ii;
   122222       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
   122223         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
   122224       }
   122225     }
   122226   }
   122227 
   122228   /* Ex-restriction (23):
   122229   ** The only way that the recursive part of a CTE can contain a compound
   122230   ** subquery is for the subquery to be one term of a join.  But if the
   122231   ** subquery is a join, then the flattening has already been stopped by
   122232   ** restriction (17d3)
   122233   */
   122234   assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
   122235 
   122236   /***** If we reach this point, flattening is permitted. *****/
   122237   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
   122238                    pSub->zSelName, pSub, iFrom));
   122239 
   122240   /* Authorize the subquery */
   122241   pParse->zAuthContext = pSubitem->zName;
   122242   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
   122243   testcase( i==SQLITE_DENY );
   122244   pParse->zAuthContext = zSavedAuthContext;
   122245 
   122246   /* If the sub-query is a compound SELECT statement, then (by restrictions
   122247   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   122248   ** be of the form:
   122249   **
   122250   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   122251   **
   122252   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
   122253   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   122254   ** OFFSET clauses and joins them to the left-hand-side of the original
   122255   ** using UNION ALL operators. In this case N is the number of simple
   122256   ** select statements in the compound sub-query.
   122257   **
   122258   ** Example:
   122259   **
   122260   **     SELECT a+1 FROM (
   122261   **        SELECT x FROM tab
   122262   **        UNION ALL
   122263   **        SELECT y FROM tab
   122264   **        UNION ALL
   122265   **        SELECT abs(z*2) FROM tab2
   122266   **     ) WHERE a!=5 ORDER BY 1
   122267   **
   122268   ** Transformed into:
   122269   **
   122270   **     SELECT x+1 FROM tab WHERE x+1!=5
   122271   **     UNION ALL
   122272   **     SELECT y+1 FROM tab WHERE y+1!=5
   122273   **     UNION ALL
   122274   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
   122275   **     ORDER BY 1
   122276   **
   122277   ** We call this the "compound-subquery flattening".
   122278   */
   122279   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
   122280     Select *pNew;
   122281     ExprList *pOrderBy = p->pOrderBy;
   122282     Expr *pLimit = p->pLimit;
   122283     Select *pPrior = p->pPrior;
   122284     p->pOrderBy = 0;
   122285     p->pSrc = 0;
   122286     p->pPrior = 0;
   122287     p->pLimit = 0;
   122288     pNew = sqlite3SelectDup(db, p, 0);
   122289     sqlite3SelectSetName(pNew, pSub->zSelName);
   122290     p->pLimit = pLimit;
   122291     p->pOrderBy = pOrderBy;
   122292     p->pSrc = pSrc;
   122293     p->op = TK_ALL;
   122294     if( pNew==0 ){
   122295       p->pPrior = pPrior;
   122296     }else{
   122297       pNew->pPrior = pPrior;
   122298       if( pPrior ) pPrior->pNext = pNew;
   122299       pNew->pNext = p;
   122300       p->pPrior = pNew;
   122301       SELECTTRACE(2,pParse,p,
   122302          ("compound-subquery flattener creates %s.%p as peer\n",
   122303          pNew->zSelName, pNew));
   122304     }
   122305     if( db->mallocFailed ) return 1;
   122306   }
   122307 
   122308   /* Begin flattening the iFrom-th entry of the FROM clause
   122309   ** in the outer query.
   122310   */
   122311   pSub = pSub1 = pSubitem->pSelect;
   122312 
   122313   /* Delete the transient table structure associated with the
   122314   ** subquery
   122315   */
   122316   sqlite3DbFree(db, pSubitem->zDatabase);
   122317   sqlite3DbFree(db, pSubitem->zName);
   122318   sqlite3DbFree(db, pSubitem->zAlias);
   122319   pSubitem->zDatabase = 0;
   122320   pSubitem->zName = 0;
   122321   pSubitem->zAlias = 0;
   122322   pSubitem->pSelect = 0;
   122323 
   122324   /* Defer deleting the Table object associated with the
   122325   ** subquery until code generation is
   122326   ** complete, since there may still exist Expr.pTab entries that
   122327   ** refer to the subquery even after flattening.  Ticket #3346.
   122328   **
   122329   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
   122330   */
   122331   if( ALWAYS(pSubitem->pTab!=0) ){
   122332     Table *pTabToDel = pSubitem->pTab;
   122333     if( pTabToDel->nTabRef==1 ){
   122334       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   122335       pTabToDel->pNextZombie = pToplevel->pZombieTab;
   122336       pToplevel->pZombieTab = pTabToDel;
   122337     }else{
   122338       pTabToDel->nTabRef--;
   122339     }
   122340     pSubitem->pTab = 0;
   122341   }
   122342 
   122343   /* The following loop runs once for each term in a compound-subquery
   122344   ** flattening (as described above).  If we are doing a different kind
   122345   ** of flattening - a flattening other than a compound-subquery flattening -
   122346   ** then this loop only runs once.
   122347   **
   122348   ** This loop moves all of the FROM elements of the subquery into the
   122349   ** the FROM clause of the outer query.  Before doing this, remember
   122350   ** the cursor number for the original outer query FROM element in
   122351   ** iParent.  The iParent cursor will never be used.  Subsequent code
   122352   ** will scan expressions looking for iParent references and replace
   122353   ** those references with expressions that resolve to the subquery FROM
   122354   ** elements we are now copying in.
   122355   */
   122356   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
   122357     int nSubSrc;
   122358     u8 jointype = 0;
   122359     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
   122360     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
   122361     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
   122362 
   122363     if( pSrc ){
   122364       assert( pParent==p );  /* First time through the loop */
   122365       jointype = pSubitem->fg.jointype;
   122366     }else{
   122367       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
   122368       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   122369       if( pSrc==0 ){
   122370         assert( db->mallocFailed );
   122371         break;
   122372       }
   122373     }
   122374 
   122375     /* The subquery uses a single slot of the FROM clause of the outer
   122376     ** query.  If the subquery has more than one element in its FROM clause,
   122377     ** then expand the outer query to make space for it to hold all elements
   122378     ** of the subquery.
   122379     **
   122380     ** Example:
   122381     **
   122382     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
   122383     **
   122384     ** The outer query has 3 slots in its FROM clause.  One slot of the
   122385     ** outer query (the middle slot) is used by the subquery.  The next
   122386     ** block of code will expand the outer query FROM clause to 4 slots.
   122387     ** The middle slot is expanded to two slots in order to make space
   122388     ** for the two elements in the FROM clause of the subquery.
   122389     */
   122390     if( nSubSrc>1 ){
   122391       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
   122392       if( db->mallocFailed ){
   122393         break;
   122394       }
   122395     }
   122396 
   122397     /* Transfer the FROM clause terms from the subquery into the
   122398     ** outer query.
   122399     */
   122400     for(i=0; i<nSubSrc; i++){
   122401       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
   122402       assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
   122403       pSrc->a[i+iFrom] = pSubSrc->a[i];
   122404       iNewParent = pSubSrc->a[i].iCursor;
   122405       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
   122406     }
   122407     pSrc->a[iFrom].fg.jointype = jointype;
   122408 
   122409     /* Now begin substituting subquery result set expressions for
   122410     ** references to the iParent in the outer query.
   122411     **
   122412     ** Example:
   122413     **
   122414     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
   122415     **   \                     \_____________ subquery __________/          /
   122416     **    \_____________________ outer query ______________________________/
   122417     **
   122418     ** We look at every expression in the outer query and every place we see
   122419     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
   122420     */
   122421     if( pSub->pOrderBy ){
   122422       /* At this point, any non-zero iOrderByCol values indicate that the
   122423       ** ORDER BY column expression is identical to the iOrderByCol'th
   122424       ** expression returned by SELECT statement pSub. Since these values
   122425       ** do not necessarily correspond to columns in SELECT statement pParent,
   122426       ** zero them before transfering the ORDER BY clause.
   122427       **
   122428       ** Not doing this may cause an error if a subsequent call to this
   122429       ** function attempts to flatten a compound sub-query into pParent
   122430       ** (the only way this can happen is if the compound sub-query is
   122431       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
   122432       ExprList *pOrderBy = pSub->pOrderBy;
   122433       for(i=0; i<pOrderBy->nExpr; i++){
   122434         pOrderBy->a[i].u.x.iOrderByCol = 0;
   122435       }
   122436       assert( pParent->pOrderBy==0 );
   122437       assert( pSub->pPrior==0 );
   122438       pParent->pOrderBy = pOrderBy;
   122439       pSub->pOrderBy = 0;
   122440     }
   122441     pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
   122442     if( isLeftJoin>0 ){
   122443       setJoinExpr(pWhere, iNewParent);
   122444     }
   122445     pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
   122446     if( db->mallocFailed==0 ){
   122447       SubstContext x;
   122448       x.pParse = pParse;
   122449       x.iTable = iParent;
   122450       x.iNewTable = iNewParent;
   122451       x.isLeftJoin = isLeftJoin;
   122452       x.pEList = pSub->pEList;
   122453       substSelect(&x, pParent, 0);
   122454     }
   122455 
   122456     /* The flattened query is distinct if either the inner or the
   122457     ** outer query is distinct.
   122458     */
   122459     pParent->selFlags |= pSub->selFlags & SF_Distinct;
   122460 
   122461     /*
   122462     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
   122463     **
   122464     ** One is tempted to try to add a and b to combine the limits.  But this
   122465     ** does not work if either limit is negative.
   122466     */
   122467     if( pSub->pLimit ){
   122468       pParent->pLimit = pSub->pLimit;
   122469       pSub->pLimit = 0;
   122470     }
   122471   }
   122472 
   122473   /* Finially, delete what is left of the subquery and return
   122474   ** success.
   122475   */
   122476   sqlite3SelectDelete(db, pSub1);
   122477 
   122478 #if SELECTTRACE_ENABLED
   122479   if( sqlite3SelectTrace & 0x100 ){
   122480     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
   122481     sqlite3TreeViewSelect(0, p, 0);
   122482   }
   122483 #endif
   122484 
   122485   return 1;
   122486 }
   122487 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   122488 
   122489 
   122490 
   122491 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   122492 /*
   122493 ** Make copies of relevant WHERE clause terms of the outer query into
   122494 ** the WHERE clause of subquery.  Example:
   122495 **
   122496 **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
   122497 **
   122498 ** Transformed into:
   122499 **
   122500 **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
   122501 **     WHERE x=5 AND y=10;
   122502 **
   122503 ** The hope is that the terms added to the inner query will make it more
   122504 ** efficient.
   122505 **
   122506 ** Do not attempt this optimization if:
   122507 **
   122508 **   (1) (** This restriction was removed on 2017-09-29.  We used to
   122509 **           disallow this optimization for aggregate subqueries, but now
   122510 **           it is allowed by putting the extra terms on the HAVING clause.
   122511 **           The added HAVING clause is pointless if the subquery lacks
   122512 **           a GROUP BY clause.  But such a HAVING clause is also harmless
   122513 **           so there does not appear to be any reason to add extra logic
   122514 **           to suppress it. **)
   122515 **
   122516 **   (2) The inner query is the recursive part of a common table expression.
   122517 **
   122518 **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
   122519 **       close would change the meaning of the LIMIT).
   122520 **
   122521 **   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
   122522 **       enforces this restriction since this routine does not have enough
   122523 **       information to know.)
   122524 **
   122525 **   (5) The WHERE clause expression originates in the ON or USING clause
   122526 **       of a LEFT JOIN.
   122527 **
   122528 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
   122529 ** terms are duplicated into the subquery.
   122530 */
   122531 static int pushDownWhereTerms(
   122532   Parse *pParse,        /* Parse context (for malloc() and error reporting) */
   122533   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
   122534   Expr *pWhere,         /* The WHERE clause of the outer query */
   122535   int iCursor           /* Cursor number of the subquery */
   122536 ){
   122537   Expr *pNew;
   122538   int nChng = 0;
   122539   if( pWhere==0 ) return 0;
   122540   if( pSubq->selFlags & SF_Recursive ) return 0;  /* restriction (2) */
   122541 
   122542 #ifdef SQLITE_DEBUG
   122543   /* Only the first term of a compound can have a WITH clause.  But make
   122544   ** sure no other terms are marked SF_Recursive in case something changes
   122545   ** in the future.
   122546   */
   122547   {
   122548     Select *pX;
   122549     for(pX=pSubq; pX; pX=pX->pPrior){
   122550       assert( (pX->selFlags & (SF_Recursive))==0 );
   122551     }
   122552   }
   122553 #endif
   122554 
   122555   if( pSubq->pLimit!=0 ){
   122556     return 0; /* restriction (3) */
   122557   }
   122558   while( pWhere->op==TK_AND ){
   122559     nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
   122560     pWhere = pWhere->pLeft;
   122561   }
   122562   if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction (5) */
   122563   if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
   122564     nChng++;
   122565     while( pSubq ){
   122566       SubstContext x;
   122567       pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
   122568       x.pParse = pParse;
   122569       x.iTable = iCursor;
   122570       x.iNewTable = iCursor;
   122571       x.isLeftJoin = 0;
   122572       x.pEList = pSubq->pEList;
   122573       pNew = substExpr(&x, pNew);
   122574       if( pSubq->selFlags & SF_Aggregate ){
   122575         pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
   122576       }else{
   122577         pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
   122578       }
   122579       pSubq = pSubq->pPrior;
   122580     }
   122581   }
   122582   return nChng;
   122583 }
   122584 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   122585 
   122586 /*
   122587 ** The pFunc is the only aggregate function in the query.  Check to see
   122588 ** if the query is a candidate for the min/max optimization.
   122589 **
   122590 ** If the query is a candidate for the min/max optimization, then set
   122591 ** *ppMinMax to be an ORDER BY clause to be used for the optimization
   122592 ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
   122593 ** whether pFunc is a min() or max() function.
   122594 **
   122595 ** If the query is not a candidate for the min/max optimization, return
   122596 ** WHERE_ORDERBY_NORMAL (which must be zero).
   122597 **
   122598 ** This routine must be called after aggregate functions have been
   122599 ** located but before their arguments have been subjected to aggregate
   122600 ** analysis.
   122601 */
   122602 static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
   122603   int eRet = WHERE_ORDERBY_NORMAL;      /* Return value */
   122604   ExprList *pEList = pFunc->x.pList;    /* Arguments to agg function */
   122605   const char *zFunc;                    /* Name of aggregate function pFunc */
   122606   ExprList *pOrderBy;
   122607   u8 sortOrder;
   122608 
   122609   assert( *ppMinMax==0 );
   122610   assert( pFunc->op==TK_AGG_FUNCTION );
   122611   if( pEList==0 || pEList->nExpr!=1 ) return eRet;
   122612   zFunc = pFunc->u.zToken;
   122613   if( sqlite3StrICmp(zFunc, "min")==0 ){
   122614     eRet = WHERE_ORDERBY_MIN;
   122615     sortOrder = SQLITE_SO_ASC;
   122616   }else if( sqlite3StrICmp(zFunc, "max")==0 ){
   122617     eRet = WHERE_ORDERBY_MAX;
   122618     sortOrder = SQLITE_SO_DESC;
   122619   }else{
   122620     return eRet;
   122621   }
   122622   *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
   122623   assert( pOrderBy!=0 || db->mallocFailed );
   122624   if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder;
   122625   return eRet;
   122626 }
   122627 
   122628 /*
   122629 ** The select statement passed as the first argument is an aggregate query.
   122630 ** The second argument is the associated aggregate-info object. This
   122631 ** function tests if the SELECT is of the form:
   122632 **
   122633 **   SELECT count(*) FROM <tbl>
   122634 **
   122635 ** where table is a database table, not a sub-select or view. If the query
   122636 ** does match this pattern, then a pointer to the Table object representing
   122637 ** <tbl> is returned. Otherwise, 0 is returned.
   122638 */
   122639 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   122640   Table *pTab;
   122641   Expr *pExpr;
   122642 
   122643   assert( !p->pGroupBy );
   122644 
   122645   if( p->pWhere || p->pEList->nExpr!=1
   122646    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   122647   ){
   122648     return 0;
   122649   }
   122650   pTab = p->pSrc->a[0].pTab;
   122651   pExpr = p->pEList->a[0].pExpr;
   122652   assert( pTab && !pTab->pSelect && pExpr );
   122653 
   122654   if( IsVirtual(pTab) ) return 0;
   122655   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   122656   if( NEVER(pAggInfo->nFunc==0) ) return 0;
   122657   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
   122658   if( pExpr->flags&EP_Distinct ) return 0;
   122659 
   122660   return pTab;
   122661 }
   122662 
   122663 /*
   122664 ** If the source-list item passed as an argument was augmented with an
   122665 ** INDEXED BY clause, then try to locate the specified index. If there
   122666 ** was such a clause and the named index cannot be found, return
   122667 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
   122668 ** pFrom->pIndex and return SQLITE_OK.
   122669 */
   122670 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
   122671   if( pFrom->pTab && pFrom->fg.isIndexedBy ){
   122672     Table *pTab = pFrom->pTab;
   122673     char *zIndexedBy = pFrom->u1.zIndexedBy;
   122674     Index *pIdx;
   122675     for(pIdx=pTab->pIndex;
   122676         pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
   122677         pIdx=pIdx->pNext
   122678     );
   122679     if( !pIdx ){
   122680       sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
   122681       pParse->checkSchema = 1;
   122682       return SQLITE_ERROR;
   122683     }
   122684     pFrom->pIBIndex = pIdx;
   122685   }
   122686   return SQLITE_OK;
   122687 }
   122688 /*
   122689 ** Detect compound SELECT statements that use an ORDER BY clause with
   122690 ** an alternative collating sequence.
   122691 **
   122692 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
   122693 **
   122694 ** These are rewritten as a subquery:
   122695 **
   122696 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
   122697 **     ORDER BY ... COLLATE ...
   122698 **
   122699 ** This transformation is necessary because the multiSelectOrderBy() routine
   122700 ** above that generates the code for a compound SELECT with an ORDER BY clause
   122701 ** uses a merge algorithm that requires the same collating sequence on the
   122702 ** result columns as on the ORDER BY clause.  See ticket
   122703 ** http://www.sqlite.org/src/info/6709574d2a
   122704 **
   122705 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
   122706 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
   122707 ** there are COLLATE terms in the ORDER BY.
   122708 */
   122709 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
   122710   int i;
   122711   Select *pNew;
   122712   Select *pX;
   122713   sqlite3 *db;
   122714   struct ExprList_item *a;
   122715   SrcList *pNewSrc;
   122716   Parse *pParse;
   122717   Token dummy;
   122718 
   122719   if( p->pPrior==0 ) return WRC_Continue;
   122720   if( p->pOrderBy==0 ) return WRC_Continue;
   122721   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
   122722   if( pX==0 ) return WRC_Continue;
   122723   a = p->pOrderBy->a;
   122724   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
   122725     if( a[i].pExpr->flags & EP_Collate ) break;
   122726   }
   122727   if( i<0 ) return WRC_Continue;
   122728 
   122729   /* If we reach this point, that means the transformation is required. */
   122730 
   122731   pParse = pWalker->pParse;
   122732   db = pParse->db;
   122733   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   122734   if( pNew==0 ) return WRC_Abort;
   122735   memset(&dummy, 0, sizeof(dummy));
   122736   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
   122737   if( pNewSrc==0 ) return WRC_Abort;
   122738   *pNew = *p;
   122739   p->pSrc = pNewSrc;
   122740   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
   122741   p->op = TK_SELECT;
   122742   p->pWhere = 0;
   122743   pNew->pGroupBy = 0;
   122744   pNew->pHaving = 0;
   122745   pNew->pOrderBy = 0;
   122746   p->pPrior = 0;
   122747   p->pNext = 0;
   122748   p->pWith = 0;
   122749   p->selFlags &= ~SF_Compound;
   122750   assert( (p->selFlags & SF_Converted)==0 );
   122751   p->selFlags |= SF_Converted;
   122752   assert( pNew->pPrior!=0 );
   122753   pNew->pPrior->pNext = pNew;
   122754   pNew->pLimit = 0;
   122755   return WRC_Continue;
   122756 }
   122757 
   122758 /*
   122759 ** Check to see if the FROM clause term pFrom has table-valued function
   122760 ** arguments.  If it does, leave an error message in pParse and return
   122761 ** non-zero, since pFrom is not allowed to be a table-valued function.
   122762 */
   122763 static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
   122764   if( pFrom->fg.isTabFunc ){
   122765     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
   122766     return 1;
   122767   }
   122768   return 0;
   122769 }
   122770 
   122771 #ifndef SQLITE_OMIT_CTE
   122772 /*
   122773 ** Argument pWith (which may be NULL) points to a linked list of nested
   122774 ** WITH contexts, from inner to outermost. If the table identified by
   122775 ** FROM clause element pItem is really a common-table-expression (CTE)
   122776 ** then return a pointer to the CTE definition for that table. Otherwise
   122777 ** return NULL.
   122778 **
   122779 ** If a non-NULL value is returned, set *ppContext to point to the With
   122780 ** object that the returned CTE belongs to.
   122781 */
   122782 static struct Cte *searchWith(
   122783   With *pWith,                    /* Current innermost WITH clause */
   122784   struct SrcList_item *pItem,     /* FROM clause element to resolve */
   122785   With **ppContext                /* OUT: WITH clause return value belongs to */
   122786 ){
   122787   const char *zName;
   122788   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
   122789     With *p;
   122790     for(p=pWith; p; p=p->pOuter){
   122791       int i;
   122792       for(i=0; i<p->nCte; i++){
   122793         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
   122794           *ppContext = p;
   122795           return &p->a[i];
   122796         }
   122797       }
   122798     }
   122799   }
   122800   return 0;
   122801 }
   122802 
   122803 /* The code generator maintains a stack of active WITH clauses
   122804 ** with the inner-most WITH clause being at the top of the stack.
   122805 **
   122806 ** This routine pushes the WITH clause passed as the second argument
   122807 ** onto the top of the stack. If argument bFree is true, then this
   122808 ** WITH clause will never be popped from the stack. In this case it
   122809 ** should be freed along with the Parse object. In other cases, when
   122810 ** bFree==0, the With object will be freed along with the SELECT
   122811 ** statement with which it is associated.
   122812 */
   122813 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
   122814   assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
   122815   if( pWith ){
   122816     assert( pParse->pWith!=pWith );
   122817     pWith->pOuter = pParse->pWith;
   122818     pParse->pWith = pWith;
   122819     if( bFree ) pParse->pWithToFree = pWith;
   122820   }
   122821 }
   122822 
   122823 /*
   122824 ** This function checks if argument pFrom refers to a CTE declared by
   122825 ** a WITH clause on the stack currently maintained by the parser. And,
   122826 ** if currently processing a CTE expression, if it is a recursive
   122827 ** reference to the current CTE.
   122828 **
   122829 ** If pFrom falls into either of the two categories above, pFrom->pTab
   122830 ** and other fields are populated accordingly. The caller should check
   122831 ** (pFrom->pTab!=0) to determine whether or not a successful match
   122832 ** was found.
   122833 **
   122834 ** Whether or not a match is found, SQLITE_OK is returned if no error
   122835 ** occurs. If an error does occur, an error message is stored in the
   122836 ** parser and some error code other than SQLITE_OK returned.
   122837 */
   122838 static int withExpand(
   122839   Walker *pWalker,
   122840   struct SrcList_item *pFrom
   122841 ){
   122842   Parse *pParse = pWalker->pParse;
   122843   sqlite3 *db = pParse->db;
   122844   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
   122845   With *pWith;                    /* WITH clause that pCte belongs to */
   122846 
   122847   assert( pFrom->pTab==0 );
   122848 
   122849   pCte = searchWith(pParse->pWith, pFrom, &pWith);
   122850   if( pCte ){
   122851     Table *pTab;
   122852     ExprList *pEList;
   122853     Select *pSel;
   122854     Select *pLeft;                /* Left-most SELECT statement */
   122855     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
   122856     With *pSavedWith;             /* Initial value of pParse->pWith */
   122857 
   122858     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
   122859     ** recursive reference to CTE pCte. Leave an error in pParse and return
   122860     ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
   122861     ** In this case, proceed.  */
   122862     if( pCte->zCteErr ){
   122863       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
   122864       return SQLITE_ERROR;
   122865     }
   122866     if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
   122867 
   122868     assert( pFrom->pTab==0 );
   122869     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   122870     if( pTab==0 ) return WRC_Abort;
   122871     pTab->nTabRef = 1;
   122872     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
   122873     pTab->iPKey = -1;
   122874     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   122875     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
   122876     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
   122877     if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
   122878     assert( pFrom->pSelect );
   122879 
   122880     /* Check if this is a recursive CTE. */
   122881     pSel = pFrom->pSelect;
   122882     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
   122883     if( bMayRecursive ){
   122884       int i;
   122885       SrcList *pSrc = pFrom->pSelect->pSrc;
   122886       for(i=0; i<pSrc->nSrc; i++){
   122887         struct SrcList_item *pItem = &pSrc->a[i];
   122888         if( pItem->zDatabase==0
   122889          && pItem->zName!=0
   122890          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
   122891           ){
   122892           pItem->pTab = pTab;
   122893           pItem->fg.isRecursive = 1;
   122894           pTab->nTabRef++;
   122895           pSel->selFlags |= SF_Recursive;
   122896         }
   122897       }
   122898     }
   122899 
   122900     /* Only one recursive reference is permitted. */
   122901     if( pTab->nTabRef>2 ){
   122902       sqlite3ErrorMsg(
   122903           pParse, "multiple references to recursive table: %s", pCte->zName
   122904       );
   122905       return SQLITE_ERROR;
   122906     }
   122907     assert( pTab->nTabRef==1 ||
   122908             ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
   122909 
   122910     pCte->zCteErr = "circular reference: %s";
   122911     pSavedWith = pParse->pWith;
   122912     pParse->pWith = pWith;
   122913     if( bMayRecursive ){
   122914       Select *pPrior = pSel->pPrior;
   122915       assert( pPrior->pWith==0 );
   122916       pPrior->pWith = pSel->pWith;
   122917       sqlite3WalkSelect(pWalker, pPrior);
   122918       pPrior->pWith = 0;
   122919     }else{
   122920       sqlite3WalkSelect(pWalker, pSel);
   122921     }
   122922     pParse->pWith = pWith;
   122923 
   122924     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
   122925     pEList = pLeft->pEList;
   122926     if( pCte->pCols ){
   122927       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
   122928         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
   122929             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
   122930         );
   122931         pParse->pWith = pSavedWith;
   122932         return SQLITE_ERROR;
   122933       }
   122934       pEList = pCte->pCols;
   122935     }
   122936 
   122937     sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
   122938     if( bMayRecursive ){
   122939       if( pSel->selFlags & SF_Recursive ){
   122940         pCte->zCteErr = "multiple recursive references: %s";
   122941       }else{
   122942         pCte->zCteErr = "recursive reference in a subquery: %s";
   122943       }
   122944       sqlite3WalkSelect(pWalker, pSel);
   122945     }
   122946     pCte->zCteErr = 0;
   122947     pParse->pWith = pSavedWith;
   122948   }
   122949 
   122950   return SQLITE_OK;
   122951 }
   122952 #endif
   122953 
   122954 #ifndef SQLITE_OMIT_CTE
   122955 /*
   122956 ** If the SELECT passed as the second argument has an associated WITH
   122957 ** clause, pop it from the stack stored as part of the Parse object.
   122958 **
   122959 ** This function is used as the xSelectCallback2() callback by
   122960 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
   122961 ** names and other FROM clause elements.
   122962 */
   122963 static void selectPopWith(Walker *pWalker, Select *p){
   122964   Parse *pParse = pWalker->pParse;
   122965   if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
   122966     With *pWith = findRightmost(p)->pWith;
   122967     if( pWith!=0 ){
   122968       assert( pParse->pWith==pWith );
   122969       pParse->pWith = pWith->pOuter;
   122970     }
   122971   }
   122972 }
   122973 #else
   122974 #define selectPopWith 0
   122975 #endif
   122976 
   122977 /*
   122978 ** This routine is a Walker callback for "expanding" a SELECT statement.
   122979 ** "Expanding" means to do the following:
   122980 **
   122981 **    (1)  Make sure VDBE cursor numbers have been assigned to every
   122982 **         element of the FROM clause.
   122983 **
   122984 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
   122985 **         defines FROM clause.  When views appear in the FROM clause,
   122986 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
   122987 **         that implements the view.  A copy is made of the view's SELECT
   122988 **         statement so that we can freely modify or delete that statement
   122989 **         without worrying about messing up the persistent representation
   122990 **         of the view.
   122991 **
   122992 **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
   122993 **         on joins and the ON and USING clause of joins.
   122994 **
   122995 **    (4)  Scan the list of columns in the result set (pEList) looking
   122996 **         for instances of the "*" operator or the TABLE.* operator.
   122997 **         If found, expand each "*" to be every column in every table
   122998 **         and TABLE.* to be every column in TABLE.
   122999 **
   123000 */
   123001 static int selectExpander(Walker *pWalker, Select *p){
   123002   Parse *pParse = pWalker->pParse;
   123003   int i, j, k;
   123004   SrcList *pTabList;
   123005   ExprList *pEList;
   123006   struct SrcList_item *pFrom;
   123007   sqlite3 *db = pParse->db;
   123008   Expr *pE, *pRight, *pExpr;
   123009   u16 selFlags = p->selFlags;
   123010   u32 elistFlags = 0;
   123011 
   123012   p->selFlags |= SF_Expanded;
   123013   if( db->mallocFailed  ){
   123014     return WRC_Abort;
   123015   }
   123016   assert( p->pSrc!=0 );
   123017   if( (selFlags & SF_Expanded)!=0 ){
   123018     return WRC_Prune;
   123019   }
   123020   pTabList = p->pSrc;
   123021   pEList = p->pEList;
   123022   if( OK_IF_ALWAYS_TRUE(p->pWith) ){
   123023     sqlite3WithPush(pParse, p->pWith, 0);
   123024   }
   123025 
   123026   /* Make sure cursor numbers have been assigned to all entries in
   123027   ** the FROM clause of the SELECT statement.
   123028   */
   123029   sqlite3SrcListAssignCursors(pParse, pTabList);
   123030 
   123031   /* Look up every table named in the FROM clause of the select.  If
   123032   ** an entry of the FROM clause is a subquery instead of a table or view,
   123033   ** then create a transient table structure to describe the subquery.
   123034   */
   123035   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   123036     Table *pTab;
   123037     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
   123038     if( pFrom->fg.isRecursive ) continue;
   123039     assert( pFrom->pTab==0 );
   123040 #ifndef SQLITE_OMIT_CTE
   123041     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
   123042     if( pFrom->pTab ) {} else
   123043 #endif
   123044     if( pFrom->zName==0 ){
   123045 #ifndef SQLITE_OMIT_SUBQUERY
   123046       Select *pSel = pFrom->pSelect;
   123047       /* A sub-query in the FROM clause of a SELECT */
   123048       assert( pSel!=0 );
   123049       assert( pFrom->pTab==0 );
   123050       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
   123051       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   123052       if( pTab==0 ) return WRC_Abort;
   123053       pTab->nTabRef = 1;
   123054       if( pFrom->zAlias ){
   123055         pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias);
   123056       }else{
   123057         pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab);
   123058       }
   123059       while( pSel->pPrior ){ pSel = pSel->pPrior; }
   123060       sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
   123061       pTab->iPKey = -1;
   123062       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
   123063       pTab->tabFlags |= TF_Ephemeral;
   123064 #endif
   123065     }else{
   123066       /* An ordinary table or view name in the FROM clause */
   123067       assert( pFrom->pTab==0 );
   123068       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
   123069       if( pTab==0 ) return WRC_Abort;
   123070       if( pTab->nTabRef>=0xffff ){
   123071         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
   123072            pTab->zName);
   123073         pFrom->pTab = 0;
   123074         return WRC_Abort;
   123075       }
   123076       pTab->nTabRef++;
   123077       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
   123078         return WRC_Abort;
   123079       }
   123080 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
   123081       if( IsVirtual(pTab) || pTab->pSelect ){
   123082         i16 nCol;
   123083         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
   123084         assert( pFrom->pSelect==0 );
   123085         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
   123086         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
   123087         nCol = pTab->nCol;
   123088         pTab->nCol = -1;
   123089         sqlite3WalkSelect(pWalker, pFrom->pSelect);
   123090         pTab->nCol = nCol;
   123091       }
   123092 #endif
   123093     }
   123094 
   123095     /* Locate the index named by the INDEXED BY clause, if any. */
   123096     if( sqlite3IndexedByLookup(pParse, pFrom) ){
   123097       return WRC_Abort;
   123098     }
   123099   }
   123100 
   123101   /* Process NATURAL keywords, and ON and USING clauses of joins.
   123102   */
   123103   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
   123104     return WRC_Abort;
   123105   }
   123106 
   123107   /* For every "*" that occurs in the column list, insert the names of
   123108   ** all columns in all tables.  And for every TABLE.* insert the names
   123109   ** of all columns in TABLE.  The parser inserted a special expression
   123110   ** with the TK_ASTERISK operator for each "*" that it found in the column
   123111   ** list.  The following code just has to locate the TK_ASTERISK
   123112   ** expressions and expand each one to the list of all columns in
   123113   ** all tables.
   123114   **
   123115   ** The first loop just checks to see if there are any "*" operators
   123116   ** that need expanding.
   123117   */
   123118   for(k=0; k<pEList->nExpr; k++){
   123119     pE = pEList->a[k].pExpr;
   123120     if( pE->op==TK_ASTERISK ) break;
   123121     assert( pE->op!=TK_DOT || pE->pRight!=0 );
   123122     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
   123123     if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
   123124     elistFlags |= pE->flags;
   123125   }
   123126   if( k<pEList->nExpr ){
   123127     /*
   123128     ** If we get here it means the result set contains one or more "*"
   123129     ** operators that need to be expanded.  Loop through each expression
   123130     ** in the result set and expand them one by one.
   123131     */
   123132     struct ExprList_item *a = pEList->a;
   123133     ExprList *pNew = 0;
   123134     int flags = pParse->db->flags;
   123135     int longNames = (flags & SQLITE_FullColNames)!=0
   123136                       && (flags & SQLITE_ShortColNames)==0;
   123137 
   123138     for(k=0; k<pEList->nExpr; k++){
   123139       pE = a[k].pExpr;
   123140       elistFlags |= pE->flags;
   123141       pRight = pE->pRight;
   123142       assert( pE->op!=TK_DOT || pRight!=0 );
   123143       if( pE->op!=TK_ASTERISK
   123144        && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
   123145       ){
   123146         /* This particular expression does not need to be expanded.
   123147         */
   123148         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
   123149         if( pNew ){
   123150           pNew->a[pNew->nExpr-1].zName = a[k].zName;
   123151           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
   123152           a[k].zName = 0;
   123153           a[k].zSpan = 0;
   123154         }
   123155         a[k].pExpr = 0;
   123156       }else{
   123157         /* This expression is a "*" or a "TABLE.*" and needs to be
   123158         ** expanded. */
   123159         int tableSeen = 0;      /* Set to 1 when TABLE matches */
   123160         char *zTName = 0;       /* text of name of TABLE */
   123161         if( pE->op==TK_DOT ){
   123162           assert( pE->pLeft!=0 );
   123163           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
   123164           zTName = pE->pLeft->u.zToken;
   123165         }
   123166         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   123167           Table *pTab = pFrom->pTab;
   123168           Select *pSub = pFrom->pSelect;
   123169           char *zTabName = pFrom->zAlias;
   123170           const char *zSchemaName = 0;
   123171           int iDb;
   123172           if( zTabName==0 ){
   123173             zTabName = pTab->zName;
   123174           }
   123175           if( db->mallocFailed ) break;
   123176           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
   123177             pSub = 0;
   123178             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
   123179               continue;
   123180             }
   123181             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   123182             zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
   123183           }
   123184           for(j=0; j<pTab->nCol; j++){
   123185             char *zName = pTab->aCol[j].zName;
   123186             char *zColname;  /* The computed column name */
   123187             char *zToFree;   /* Malloced string that needs to be freed */
   123188             Token sColname;  /* Computed column name as a token */
   123189 
   123190             assert( zName );
   123191             if( zTName && pSub
   123192              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
   123193             ){
   123194               continue;
   123195             }
   123196 
   123197             /* If a column is marked as 'hidden', omit it from the expanded
   123198             ** result-set list unless the SELECT has the SF_IncludeHidden
   123199             ** bit set.
   123200             */
   123201             if( (p->selFlags & SF_IncludeHidden)==0
   123202              && IsHiddenColumn(&pTab->aCol[j])
   123203             ){
   123204               continue;
   123205             }
   123206             tableSeen = 1;
   123207 
   123208             if( i>0 && zTName==0 ){
   123209               if( (pFrom->fg.jointype & JT_NATURAL)!=0
   123210                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
   123211               ){
   123212                 /* In a NATURAL join, omit the join columns from the
   123213                 ** table to the right of the join */
   123214                 continue;
   123215               }
   123216               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
   123217                 /* In a join with a USING clause, omit columns in the
   123218                 ** using clause from the table on the right. */
   123219                 continue;
   123220               }
   123221             }
   123222             pRight = sqlite3Expr(db, TK_ID, zName);
   123223             zColname = zName;
   123224             zToFree = 0;
   123225             if( longNames || pTabList->nSrc>1 ){
   123226               Expr *pLeft;
   123227               pLeft = sqlite3Expr(db, TK_ID, zTabName);
   123228               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
   123229               if( zSchemaName ){
   123230                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
   123231                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
   123232               }
   123233               if( longNames ){
   123234                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
   123235                 zToFree = zColname;
   123236               }
   123237             }else{
   123238               pExpr = pRight;
   123239             }
   123240             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
   123241             sqlite3TokenInit(&sColname, zColname);
   123242             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
   123243             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
   123244               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
   123245               if( pSub ){
   123246                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
   123247                 testcase( pX->zSpan==0 );
   123248               }else{
   123249                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
   123250                                            zSchemaName, zTabName, zColname);
   123251                 testcase( pX->zSpan==0 );
   123252               }
   123253               pX->bSpanIsTab = 1;
   123254             }
   123255             sqlite3DbFree(db, zToFree);
   123256           }
   123257         }
   123258         if( !tableSeen ){
   123259           if( zTName ){
   123260             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
   123261           }else{
   123262             sqlite3ErrorMsg(pParse, "no tables specified");
   123263           }
   123264         }
   123265       }
   123266     }
   123267     sqlite3ExprListDelete(db, pEList);
   123268     p->pEList = pNew;
   123269   }
   123270   if( p->pEList ){
   123271     if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   123272       sqlite3ErrorMsg(pParse, "too many columns in result set");
   123273       return WRC_Abort;
   123274     }
   123275     if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
   123276       p->selFlags |= SF_ComplexResult;
   123277     }
   123278   }
   123279   return WRC_Continue;
   123280 }
   123281 
   123282 /*
   123283 ** No-op routine for the parse-tree walker.
   123284 **
   123285 ** When this routine is the Walker.xExprCallback then expression trees
   123286 ** are walked without any actions being taken at each node.  Presumably,
   123287 ** when this routine is used for Walker.xExprCallback then
   123288 ** Walker.xSelectCallback is set to do something useful for every
   123289 ** subquery in the parser tree.
   123290 */
   123291 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
   123292   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   123293   return WRC_Continue;
   123294 }
   123295 
   123296 /*
   123297 ** No-op routine for the parse-tree walker for SELECT statements.
   123298 ** subquery in the parser tree.
   123299 */
   123300 SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
   123301   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   123302   return WRC_Continue;
   123303 }
   123304 
   123305 #if SQLITE_DEBUG
   123306 /*
   123307 ** Always assert.  This xSelectCallback2 implementation proves that the
   123308 ** xSelectCallback2 is never invoked.
   123309 */
   123310 SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
   123311   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   123312   assert( 0 );
   123313 }
   123314 #endif
   123315 /*
   123316 ** This routine "expands" a SELECT statement and all of its subqueries.
   123317 ** For additional information on what it means to "expand" a SELECT
   123318 ** statement, see the comment on the selectExpand worker callback above.
   123319 **
   123320 ** Expanding a SELECT statement is the first step in processing a
   123321 ** SELECT statement.  The SELECT statement must be expanded before
   123322 ** name resolution is performed.
   123323 **
   123324 ** If anything goes wrong, an error message is written into pParse.
   123325 ** The calling function can detect the problem by looking at pParse->nErr
   123326 ** and/or pParse->db->mallocFailed.
   123327 */
   123328 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
   123329   Walker w;
   123330   w.xExprCallback = sqlite3ExprWalkNoop;
   123331   w.pParse = pParse;
   123332   if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
   123333     w.xSelectCallback = convertCompoundSelectToSubquery;
   123334     w.xSelectCallback2 = 0;
   123335     sqlite3WalkSelect(&w, pSelect);
   123336   }
   123337   w.xSelectCallback = selectExpander;
   123338   w.xSelectCallback2 = selectPopWith;
   123339   sqlite3WalkSelect(&w, pSelect);
   123340 }
   123341 
   123342 
   123343 #ifndef SQLITE_OMIT_SUBQUERY
   123344 /*
   123345 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
   123346 ** interface.
   123347 **
   123348 ** For each FROM-clause subquery, add Column.zType and Column.zColl
   123349 ** information to the Table structure that represents the result set
   123350 ** of that subquery.
   123351 **
   123352 ** The Table structure that represents the result set was constructed
   123353 ** by selectExpander() but the type and collation information was omitted
   123354 ** at that point because identifiers had not yet been resolved.  This
   123355 ** routine is called after identifier resolution.
   123356 */
   123357 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
   123358   Parse *pParse;
   123359   int i;
   123360   SrcList *pTabList;
   123361   struct SrcList_item *pFrom;
   123362 
   123363   assert( p->selFlags & SF_Resolved );
   123364   assert( (p->selFlags & SF_HasTypeInfo)==0 );
   123365   p->selFlags |= SF_HasTypeInfo;
   123366   pParse = pWalker->pParse;
   123367   pTabList = p->pSrc;
   123368   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   123369     Table *pTab = pFrom->pTab;
   123370     assert( pTab!=0 );
   123371     if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
   123372       /* A sub-query in the FROM clause of a SELECT */
   123373       Select *pSel = pFrom->pSelect;
   123374       if( pSel ){
   123375         while( pSel->pPrior ) pSel = pSel->pPrior;
   123376         sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
   123377       }
   123378     }
   123379   }
   123380 }
   123381 #endif
   123382 
   123383 
   123384 /*
   123385 ** This routine adds datatype and collating sequence information to
   123386 ** the Table structures of all FROM-clause subqueries in a
   123387 ** SELECT statement.
   123388 **
   123389 ** Use this routine after name resolution.
   123390 */
   123391 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
   123392 #ifndef SQLITE_OMIT_SUBQUERY
   123393   Walker w;
   123394   w.xSelectCallback = sqlite3SelectWalkNoop;
   123395   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
   123396   w.xExprCallback = sqlite3ExprWalkNoop;
   123397   w.pParse = pParse;
   123398   sqlite3WalkSelect(&w, pSelect);
   123399 #endif
   123400 }
   123401 
   123402 
   123403 /*
   123404 ** This routine sets up a SELECT statement for processing.  The
   123405 ** following is accomplished:
   123406 **
   123407 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
   123408 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
   123409 **     *  ON and USING clauses are shifted into WHERE statements
   123410 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
   123411 **     *  Identifiers in expression are matched to tables.
   123412 **
   123413 ** This routine acts recursively on all subqueries within the SELECT.
   123414 */
   123415 SQLITE_PRIVATE void sqlite3SelectPrep(
   123416   Parse *pParse,         /* The parser context */
   123417   Select *p,             /* The SELECT statement being coded. */
   123418   NameContext *pOuterNC  /* Name context for container */
   123419 ){
   123420   assert( p!=0 || pParse->db->mallocFailed );
   123421   if( pParse->db->mallocFailed ) return;
   123422   if( p->selFlags & SF_HasTypeInfo ) return;
   123423   sqlite3SelectExpand(pParse, p);
   123424   if( pParse->nErr || pParse->db->mallocFailed ) return;
   123425   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
   123426   if( pParse->nErr || pParse->db->mallocFailed ) return;
   123427   sqlite3SelectAddTypeInfo(pParse, p);
   123428 }
   123429 
   123430 /*
   123431 ** Reset the aggregate accumulator.
   123432 **
   123433 ** The aggregate accumulator is a set of memory cells that hold
   123434 ** intermediate results while calculating an aggregate.  This
   123435 ** routine generates code that stores NULLs in all of those memory
   123436 ** cells.
   123437 */
   123438 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   123439   Vdbe *v = pParse->pVdbe;
   123440   int i;
   123441   struct AggInfo_func *pFunc;
   123442   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
   123443   if( nReg==0 ) return;
   123444 #ifdef SQLITE_DEBUG
   123445   /* Verify that all AggInfo registers are within the range specified by
   123446   ** AggInfo.mnReg..AggInfo.mxReg */
   123447   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
   123448   for(i=0; i<pAggInfo->nColumn; i++){
   123449     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
   123450          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
   123451   }
   123452   for(i=0; i<pAggInfo->nFunc; i++){
   123453     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
   123454          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
   123455   }
   123456 #endif
   123457   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
   123458   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
   123459     if( pFunc->iDistinct>=0 ){
   123460       Expr *pE = pFunc->pExpr;
   123461       assert( !ExprHasProperty(pE, EP_xIsSelect) );
   123462       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
   123463         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
   123464            "argument");
   123465         pFunc->iDistinct = -1;
   123466       }else{
   123467         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
   123468         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
   123469                           (char*)pKeyInfo, P4_KEYINFO);
   123470       }
   123471     }
   123472   }
   123473 }
   123474 
   123475 /*
   123476 ** Invoke the OP_AggFinalize opcode for every aggregate function
   123477 ** in the AggInfo structure.
   123478 */
   123479 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   123480   Vdbe *v = pParse->pVdbe;
   123481   int i;
   123482   struct AggInfo_func *pF;
   123483   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   123484     ExprList *pList = pF->pExpr->x.pList;
   123485     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   123486     sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
   123487     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
   123488   }
   123489 }
   123490 
   123491 /*
   123492 ** Update the accumulator memory cells for an aggregate based on
   123493 ** the current cursor position.
   123494 */
   123495 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
   123496   Vdbe *v = pParse->pVdbe;
   123497   int i;
   123498   int regHit = 0;
   123499   int addrHitTest = 0;
   123500   struct AggInfo_func *pF;
   123501   struct AggInfo_col *pC;
   123502 
   123503   pAggInfo->directMode = 1;
   123504   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   123505     int nArg;
   123506     int addrNext = 0;
   123507     int regAgg;
   123508     ExprList *pList = pF->pExpr->x.pList;
   123509     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   123510     if( pList ){
   123511       nArg = pList->nExpr;
   123512       regAgg = sqlite3GetTempRange(pParse, nArg);
   123513       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
   123514     }else{
   123515       nArg = 0;
   123516       regAgg = 0;
   123517     }
   123518     if( pF->iDistinct>=0 ){
   123519       addrNext = sqlite3VdbeMakeLabel(v);
   123520       testcase( nArg==0 );  /* Error condition */
   123521       testcase( nArg>1 );   /* Also an error */
   123522       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
   123523     }
   123524     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
   123525       CollSeq *pColl = 0;
   123526       struct ExprList_item *pItem;
   123527       int j;
   123528       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
   123529       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
   123530         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   123531       }
   123532       if( !pColl ){
   123533         pColl = pParse->db->pDfltColl;
   123534       }
   123535       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
   123536       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
   123537     }
   123538     sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
   123539     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
   123540     sqlite3VdbeChangeP5(v, (u8)nArg);
   123541     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
   123542     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
   123543     if( addrNext ){
   123544       sqlite3VdbeResolveLabel(v, addrNext);
   123545       sqlite3ExprCacheClear(pParse);
   123546     }
   123547   }
   123548 
   123549   /* Before populating the accumulator registers, clear the column cache.
   123550   ** Otherwise, if any of the required column values are already present
   123551   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
   123552   ** to pC->iMem. But by the time the value is used, the original register
   123553   ** may have been used, invalidating the underlying buffer holding the
   123554   ** text or blob value. See ticket [883034dcb5].
   123555   **
   123556   ** Another solution would be to change the OP_SCopy used to copy cached
   123557   ** values to an OP_Copy.
   123558   */
   123559   if( regHit ){
   123560     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
   123561   }
   123562   sqlite3ExprCacheClear(pParse);
   123563   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
   123564     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
   123565   }
   123566   pAggInfo->directMode = 0;
   123567   sqlite3ExprCacheClear(pParse);
   123568   if( addrHitTest ){
   123569     sqlite3VdbeJumpHere(v, addrHitTest);
   123570   }
   123571 }
   123572 
   123573 /*
   123574 ** Add a single OP_Explain instruction to the VDBE to explain a simple
   123575 ** count(*) query ("SELECT count(*) FROM pTab").
   123576 */
   123577 #ifndef SQLITE_OMIT_EXPLAIN
   123578 static void explainSimpleCount(
   123579   Parse *pParse,                  /* Parse context */
   123580   Table *pTab,                    /* Table being queried */
   123581   Index *pIdx                     /* Index used to optimize scan, or NULL */
   123582 ){
   123583   if( pParse->explain==2 ){
   123584     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
   123585     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
   123586         pTab->zName,
   123587         bCover ? " USING COVERING INDEX " : "",
   123588         bCover ? pIdx->zName : ""
   123589     );
   123590     sqlite3VdbeAddOp4(
   123591         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
   123592     );
   123593   }
   123594 }
   123595 #else
   123596 # define explainSimpleCount(a,b,c)
   123597 #endif
   123598 
   123599 /*
   123600 ** Context object for havingToWhereExprCb().
   123601 */
   123602 struct HavingToWhereCtx {
   123603   Expr **ppWhere;
   123604   ExprList *pGroupBy;
   123605 };
   123606 
   123607 /*
   123608 ** sqlite3WalkExpr() callback used by havingToWhere().
   123609 **
   123610 ** If the node passed to the callback is a TK_AND node, return
   123611 ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
   123612 **
   123613 ** Otherwise, return WRC_Prune. In this case, also check if the
   123614 ** sub-expression matches the criteria for being moved to the WHERE
   123615 ** clause. If so, add it to the WHERE clause and replace the sub-expression
   123616 ** within the HAVING expression with a constant "1".
   123617 */
   123618 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
   123619   if( pExpr->op!=TK_AND ){
   123620     struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
   123621     if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
   123622       sqlite3 *db = pWalker->pParse->db;
   123623       Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
   123624       if( pNew ){
   123625         Expr *pWhere = *(p->ppWhere);
   123626         SWAP(Expr, *pNew, *pExpr);
   123627         pNew = sqlite3ExprAnd(db, pWhere, pNew);
   123628         *(p->ppWhere) = pNew;
   123629       }
   123630     }
   123631     return WRC_Prune;
   123632   }
   123633   return WRC_Continue;
   123634 }
   123635 
   123636 /*
   123637 ** Transfer eligible terms from the HAVING clause of a query, which is
   123638 ** processed after grouping, to the WHERE clause, which is processed before
   123639 ** grouping. For example, the query:
   123640 **
   123641 **   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
   123642 **
   123643 ** can be rewritten as:
   123644 **
   123645 **   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
   123646 **
   123647 ** A term of the HAVING expression is eligible for transfer if it consists
   123648 ** entirely of constants and expressions that are also GROUP BY terms that
   123649 ** use the "BINARY" collation sequence.
   123650 */
   123651 static void havingToWhere(
   123652   Parse *pParse,
   123653   ExprList *pGroupBy,
   123654   Expr *pHaving,
   123655   Expr **ppWhere
   123656 ){
   123657   struct HavingToWhereCtx sCtx;
   123658   Walker sWalker;
   123659 
   123660   sCtx.ppWhere = ppWhere;
   123661   sCtx.pGroupBy = pGroupBy;
   123662 
   123663   memset(&sWalker, 0, sizeof(sWalker));
   123664   sWalker.pParse = pParse;
   123665   sWalker.xExprCallback = havingToWhereExprCb;
   123666   sWalker.u.pHavingCtx = &sCtx;
   123667   sqlite3WalkExpr(&sWalker, pHaving);
   123668 }
   123669 
   123670 /*
   123671 ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
   123672 ** If it is, then return the SrcList_item for the prior view.  If it is not,
   123673 ** then return 0.
   123674 */
   123675 static struct SrcList_item *isSelfJoinView(
   123676   SrcList *pTabList,           /* Search for self-joins in this FROM clause */
   123677   struct SrcList_item *pThis   /* Search for prior reference to this subquery */
   123678 ){
   123679   struct SrcList_item *pItem;
   123680   for(pItem = pTabList->a; pItem<pThis; pItem++){
   123681     if( pItem->pSelect==0 ) continue;
   123682     if( pItem->fg.viaCoroutine ) continue;
   123683     if( pItem->zName==0 ) continue;
   123684     if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
   123685     if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
   123686     if( sqlite3ExprCompare(0,
   123687           pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
   123688     ){
   123689       /* The view was modified by some other optimization such as
   123690       ** pushDownWhereTerms() */
   123691       continue;
   123692     }
   123693     return pItem;
   123694   }
   123695   return 0;
   123696 }
   123697 
   123698 #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
   123699 /*
   123700 ** Attempt to transform a query of the form
   123701 **
   123702 **    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
   123703 **
   123704 ** Into this:
   123705 **
   123706 **    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
   123707 **
   123708 ** The transformation only works if all of the following are true:
   123709 **
   123710 **   *  The subquery is a UNION ALL of two or more terms
   123711 **   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
   123712 **   *  The outer query is a simple count(*)
   123713 **
   123714 ** Return TRUE if the optimization is undertaken.
   123715 */
   123716 static int countOfViewOptimization(Parse *pParse, Select *p){
   123717   Select *pSub, *pPrior;
   123718   Expr *pExpr;
   123719   Expr *pCount;
   123720   sqlite3 *db;
   123721   if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
   123722   if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
   123723   pExpr = p->pEList->a[0].pExpr;
   123724   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
   123725   if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
   123726   if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
   123727   if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
   123728   pSub = p->pSrc->a[0].pSelect;
   123729   if( pSub==0 ) return 0;                           /* The FROM is a subquery */
   123730   if( pSub->pPrior==0 ) return 0;                   /* Must be a compound ry */
   123731   do{
   123732     if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
   123733     if( pSub->pWhere ) return 0;                      /* No WHERE clause */
   123734     if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
   123735     pSub = pSub->pPrior;                              /* Repeat over compound */
   123736   }while( pSub );
   123737 
   123738   /* If we reach this point then it is OK to perform the transformation */
   123739 
   123740   db = pParse->db;
   123741   pCount = pExpr;
   123742   pExpr = 0;
   123743   pSub = p->pSrc->a[0].pSelect;
   123744   p->pSrc->a[0].pSelect = 0;
   123745   sqlite3SrcListDelete(db, p->pSrc);
   123746   p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
   123747   while( pSub ){
   123748     Expr *pTerm;
   123749     pPrior = pSub->pPrior;
   123750     pSub->pPrior = 0;
   123751     pSub->pNext = 0;
   123752     pSub->selFlags |= SF_Aggregate;
   123753     pSub->selFlags &= ~SF_Compound;
   123754     pSub->nSelectRow = 0;
   123755     sqlite3ExprListDelete(db, pSub->pEList);
   123756     pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
   123757     pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
   123758     pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
   123759     sqlite3PExprAddSelect(pParse, pTerm, pSub);
   123760     if( pExpr==0 ){
   123761       pExpr = pTerm;
   123762     }else{
   123763       pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
   123764     }
   123765     pSub = pPrior;
   123766   }
   123767   p->pEList->a[0].pExpr = pExpr;
   123768   p->selFlags &= ~SF_Aggregate;
   123769 
   123770 #if SELECTTRACE_ENABLED
   123771   if( sqlite3SelectTrace & 0x400 ){
   123772     SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
   123773     sqlite3TreeViewSelect(0, p, 0);
   123774   }
   123775 #endif
   123776   return 1;
   123777 }
   123778 #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
   123779 
   123780 /*
   123781 ** Generate code for the SELECT statement given in the p argument.
   123782 **
   123783 ** The results are returned according to the SelectDest structure.
   123784 ** See comments in sqliteInt.h for further information.
   123785 **
   123786 ** This routine returns the number of errors.  If any errors are
   123787 ** encountered, then an appropriate error message is left in
   123788 ** pParse->zErrMsg.
   123789 **
   123790 ** This routine does NOT free the Select structure passed in.  The
   123791 ** calling function needs to do that.
   123792 */
   123793 SQLITE_PRIVATE int sqlite3Select(
   123794   Parse *pParse,         /* The parser context */
   123795   Select *p,             /* The SELECT statement being coded. */
   123796   SelectDest *pDest      /* What to do with the query results */
   123797 ){
   123798   int i, j;              /* Loop counters */
   123799   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
   123800   Vdbe *v;               /* The virtual machine under construction */
   123801   int isAgg;             /* True for select lists like "count(*)" */
   123802   ExprList *pEList = 0;  /* List of columns to extract. */
   123803   SrcList *pTabList;     /* List of tables to select from */
   123804   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   123805   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   123806   Expr *pHaving;         /* The HAVING clause.  May be NULL */
   123807   int rc = 1;            /* Value to return from this function */
   123808   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
   123809   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
   123810   AggInfo sAggInfo;      /* Information used by aggregate queries */
   123811   int iEnd;              /* Address of the end of the query */
   123812   sqlite3 *db;           /* The database connection */
   123813   ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */
   123814   u8 minMaxFlag;                 /* Flag for min/max queries */
   123815 
   123816 #ifndef SQLITE_OMIT_EXPLAIN
   123817   int iRestoreSelectId = pParse->iSelectId;
   123818   pParse->iSelectId = pParse->iNextSelectId++;
   123819 #endif
   123820 
   123821   db = pParse->db;
   123822   if( p==0 || db->mallocFailed || pParse->nErr ){
   123823     return 1;
   123824   }
   123825   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
   123826   memset(&sAggInfo, 0, sizeof(sAggInfo));
   123827 #if SELECTTRACE_ENABLED
   123828   pParse->nSelectIndent++;
   123829   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
   123830   if( sqlite3SelectTrace & 0x100 ){
   123831     sqlite3TreeViewSelect(0, p, 0);
   123832   }
   123833 #endif
   123834 
   123835   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
   123836   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
   123837   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
   123838   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
   123839   if( IgnorableOrderby(pDest) ){
   123840     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
   123841            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
   123842            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
   123843            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
   123844     /* If ORDER BY makes no difference in the output then neither does
   123845     ** DISTINCT so it can be removed too. */
   123846     sqlite3ExprListDelete(db, p->pOrderBy);
   123847     p->pOrderBy = 0;
   123848     p->selFlags &= ~SF_Distinct;
   123849   }
   123850   sqlite3SelectPrep(pParse, p, 0);
   123851   memset(&sSort, 0, sizeof(sSort));
   123852   sSort.pOrderBy = p->pOrderBy;
   123853   pTabList = p->pSrc;
   123854   if( pParse->nErr || db->mallocFailed ){
   123855     goto select_end;
   123856   }
   123857   assert( p->pEList!=0 );
   123858   isAgg = (p->selFlags & SF_Aggregate)!=0;
   123859 #if SELECTTRACE_ENABLED
   123860   if( sqlite3SelectTrace & 0x100 ){
   123861     SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
   123862     sqlite3TreeViewSelect(0, p, 0);
   123863   }
   123864 #endif
   123865 
   123866   /* Get a pointer the VDBE under construction, allocating a new VDBE if one
   123867   ** does not already exist */
   123868   v = sqlite3GetVdbe(pParse);
   123869   if( v==0 ) goto select_end;
   123870   if( pDest->eDest==SRT_Output ){
   123871     generateColumnNames(pParse, p);
   123872   }
   123873 
   123874   /* Try to flatten subqueries in the FROM clause up into the main query
   123875   */
   123876 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   123877   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
   123878     struct SrcList_item *pItem = &pTabList->a[i];
   123879     Select *pSub = pItem->pSelect;
   123880     Table *pTab = pItem->pTab;
   123881     if( pSub==0 ) continue;
   123882 
   123883     /* Catch mismatch in the declared columns of a view and the number of
   123884     ** columns in the SELECT on the RHS */
   123885     if( pTab->nCol!=pSub->pEList->nExpr ){
   123886       sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
   123887                       pTab->nCol, pTab->zName, pSub->pEList->nExpr);
   123888       goto select_end;
   123889     }
   123890 
   123891     /* Do not try to flatten an aggregate subquery.
   123892     **
   123893     ** Flattening an aggregate subquery is only possible if the outer query
   123894     ** is not a join.  But if the outer query is not a join, then the subquery
   123895     ** will be implemented as a co-routine and there is no advantage to
   123896     ** flattening in that case.
   123897     */
   123898     if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
   123899     assert( pSub->pGroupBy==0 );
   123900 
   123901     /* If the outer query contains a "complex" result set (that is,
   123902     ** if the result set of the outer query uses functions or subqueries)
   123903     ** and if the subquery contains an ORDER BY clause and if
   123904     ** it will be implemented as a co-routine, then do not flatten.  This
   123905     ** restriction allows SQL constructs like this:
   123906     **
   123907     **  SELECT expensive_function(x)
   123908     **    FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
   123909     **
   123910     ** The expensive_function() is only computed on the 10 rows that
   123911     ** are output, rather than every row of the table.
   123912     **
   123913     ** The requirement that the outer query have a complex result set
   123914     ** means that flattening does occur on simpler SQL constraints without
   123915     ** the expensive_function() like:
   123916     **
   123917     **  SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
   123918     */
   123919     if( pSub->pOrderBy!=0
   123920      && i==0
   123921      && (p->selFlags & SF_ComplexResult)!=0
   123922      && (pTabList->nSrc==1
   123923          || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
   123924     ){
   123925       continue;
   123926     }
   123927 
   123928     if( flattenSubquery(pParse, p, i, isAgg) ){
   123929       /* This subquery can be absorbed into its parent. */
   123930       i = -1;
   123931     }
   123932     pTabList = p->pSrc;
   123933     if( db->mallocFailed ) goto select_end;
   123934     if( !IgnorableOrderby(pDest) ){
   123935       sSort.pOrderBy = p->pOrderBy;
   123936     }
   123937   }
   123938 #endif
   123939 
   123940 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   123941   /* Handle compound SELECT statements using the separate multiSelect()
   123942   ** procedure.
   123943   */
   123944   if( p->pPrior ){
   123945     rc = multiSelect(pParse, p, pDest);
   123946     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   123947 #if SELECTTRACE_ENABLED
   123948     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
   123949     pParse->nSelectIndent--;
   123950 #endif
   123951     return rc;
   123952   }
   123953 #endif
   123954 
   123955   /* For each term in the FROM clause, do two things:
   123956   ** (1) Authorized unreferenced tables
   123957   ** (2) Generate code for all sub-queries
   123958   */
   123959   for(i=0; i<pTabList->nSrc; i++){
   123960     struct SrcList_item *pItem = &pTabList->a[i];
   123961     SelectDest dest;
   123962     Select *pSub;
   123963 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   123964     const char *zSavedAuthContext;
   123965 #endif
   123966 
   123967     /* Issue SQLITE_READ authorizations with a fake column name for any
   123968     ** tables that are referenced but from which no values are extracted.
   123969     ** Examples of where these kinds of null SQLITE_READ authorizations
   123970     ** would occur:
   123971     **
   123972     **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
   123973     **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
   123974     **
   123975     ** The fake column name is an empty string.  It is possible for a table to
   123976     ** have a column named by the empty string, in which case there is no way to
   123977     ** distinguish between an unreferenced table and an actual reference to the
   123978     ** "" column. The original design was for the fake column name to be a NULL,
   123979     ** which would be unambiguous.  But legacy authorization callbacks might
   123980     ** assume the column name is non-NULL and segfault.  The use of an empty
   123981     ** string for the fake column name seems safer.
   123982     */
   123983     if( pItem->colUsed==0 ){
   123984       sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
   123985     }
   123986 
   123987 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   123988     /* Generate code for all sub-queries in the FROM clause
   123989     */
   123990     pSub = pItem->pSelect;
   123991     if( pSub==0 ) continue;
   123992 
   123993     /* Sometimes the code for a subquery will be generated more than
   123994     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
   123995     ** for example.  In that case, do not regenerate the code to manifest
   123996     ** a view or the co-routine to implement a view.  The first instance
   123997     ** is sufficient, though the subroutine to manifest the view does need
   123998     ** to be invoked again. */
   123999     if( pItem->addrFillSub ){
   124000       if( pItem->fg.viaCoroutine==0 ){
   124001         /* The subroutine that manifests the view might be a one-time routine,
   124002         ** or it might need to be rerun on each iteration because it
   124003         ** encodes a correlated subquery. */
   124004         testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
   124005         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
   124006       }
   124007       continue;
   124008     }
   124009 
   124010     /* Increment Parse.nHeight by the height of the largest expression
   124011     ** tree referred to by this, the parent select. The child select
   124012     ** may contain expression trees of at most
   124013     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
   124014     ** more conservative than necessary, but much easier than enforcing
   124015     ** an exact limit.
   124016     */
   124017     pParse->nHeight += sqlite3SelectExprHeight(p);
   124018 
   124019     /* Make copies of constant WHERE-clause terms in the outer query down
   124020     ** inside the subquery.  This can help the subquery to run more efficiently.
   124021     */
   124022     if( (pItem->fg.jointype & JT_OUTER)==0
   124023      && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
   124024     ){
   124025 #if SELECTTRACE_ENABLED
   124026       if( sqlite3SelectTrace & 0x100 ){
   124027         SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
   124028         sqlite3TreeViewSelect(0, p, 0);
   124029       }
   124030 #endif
   124031     }
   124032 
   124033     zSavedAuthContext = pParse->zAuthContext;
   124034     pParse->zAuthContext = pItem->zName;
   124035 
   124036     /* Generate code to implement the subquery
   124037     **
   124038     ** The subquery is implemented as a co-routine if the subquery is
   124039     ** guaranteed to be the outer loop (so that it does not need to be
   124040     ** computed more than once)
   124041     **
   124042     ** TODO: Are there other reasons beside (1) to use a co-routine
   124043     ** implementation?
   124044     */
   124045     if( i==0
   124046      && (pTabList->nSrc==1
   124047             || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
   124048     ){
   124049       /* Implement a co-routine that will return a single row of the result
   124050       ** set on each invocation.
   124051       */
   124052       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
   124053 
   124054       pItem->regReturn = ++pParse->nMem;
   124055       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
   124056       VdbeComment((v, "%s", pItem->pTab->zName));
   124057       pItem->addrFillSub = addrTop;
   124058       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
   124059       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   124060       sqlite3Select(pParse, pSub, &dest);
   124061       pItem->pTab->nRowLogEst = pSub->nSelectRow;
   124062       pItem->fg.viaCoroutine = 1;
   124063       pItem->regResult = dest.iSdst;
   124064       sqlite3VdbeEndCoroutine(v, pItem->regReturn);
   124065       sqlite3VdbeJumpHere(v, addrTop-1);
   124066       sqlite3ClearTempRegCache(pParse);
   124067     }else{
   124068       /* Generate a subroutine that will fill an ephemeral table with
   124069       ** the content of this subquery.  pItem->addrFillSub will point
   124070       ** to the address of the generated subroutine.  pItem->regReturn
   124071       ** is a register allocated to hold the subroutine return address
   124072       */
   124073       int topAddr;
   124074       int onceAddr = 0;
   124075       int retAddr;
   124076       struct SrcList_item *pPrior;
   124077 
   124078       assert( pItem->addrFillSub==0 );
   124079       pItem->regReturn = ++pParse->nMem;
   124080       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
   124081       pItem->addrFillSub = topAddr+1;
   124082       if( pItem->fg.isCorrelated==0 ){
   124083         /* If the subquery is not correlated and if we are not inside of
   124084         ** a trigger, then we only need to compute the value of the subquery
   124085         ** once. */
   124086         onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   124087         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
   124088       }else{
   124089         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
   124090       }
   124091       pPrior = isSelfJoinView(pTabList, pItem);
   124092       if( pPrior ){
   124093         sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
   124094         explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
   124095         assert( pPrior->pSelect!=0 );
   124096         pSub->nSelectRow = pPrior->pSelect->nSelectRow;
   124097       }else{
   124098         sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
   124099         explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   124100         sqlite3Select(pParse, pSub, &dest);
   124101       }
   124102       pItem->pTab->nRowLogEst = pSub->nSelectRow;
   124103       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
   124104       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
   124105       VdbeComment((v, "end %s", pItem->pTab->zName));
   124106       sqlite3VdbeChangeP1(v, topAddr, retAddr);
   124107       sqlite3ClearTempRegCache(pParse);
   124108     }
   124109     if( db->mallocFailed ) goto select_end;
   124110     pParse->nHeight -= sqlite3SelectExprHeight(p);
   124111     pParse->zAuthContext = zSavedAuthContext;
   124112 #endif
   124113   }
   124114 
   124115   /* Various elements of the SELECT copied into local variables for
   124116   ** convenience */
   124117   pEList = p->pEList;
   124118   pWhere = p->pWhere;
   124119   pGroupBy = p->pGroupBy;
   124120   pHaving = p->pHaving;
   124121   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
   124122 
   124123 #if SELECTTRACE_ENABLED
   124124   if( sqlite3SelectTrace & 0x400 ){
   124125     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
   124126     sqlite3TreeViewSelect(0, p, 0);
   124127   }
   124128 #endif
   124129 
   124130 #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
   124131   if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
   124132    && countOfViewOptimization(pParse, p)
   124133   ){
   124134     if( db->mallocFailed ) goto select_end;
   124135     pEList = p->pEList;
   124136     pTabList = p->pSrc;
   124137   }
   124138 #endif
   124139 
   124140   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
   124141   ** if the select-list is the same as the ORDER BY list, then this query
   124142   ** can be rewritten as a GROUP BY. In other words, this:
   124143   **
   124144   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
   124145   **
   124146   ** is transformed to:
   124147   **
   124148   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
   124149   **
   124150   ** The second form is preferred as a single index (or temp-table) may be
   124151   ** used for both the ORDER BY and DISTINCT processing. As originally
   124152   ** written the query must use a temp-table for at least one of the ORDER
   124153   ** BY and DISTINCT, and an index or separate temp-table for the other.
   124154   */
   124155   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
   124156    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
   124157   ){
   124158     p->selFlags &= ~SF_Distinct;
   124159     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
   124160     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
   124161     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
   124162     ** original setting of the SF_Distinct flag, not the current setting */
   124163     assert( sDistinct.isTnct );
   124164 
   124165 #if SELECTTRACE_ENABLED
   124166     if( sqlite3SelectTrace & 0x400 ){
   124167       SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
   124168       sqlite3TreeViewSelect(0, p, 0);
   124169     }
   124170 #endif
   124171   }
   124172 
   124173   /* If there is an ORDER BY clause, then create an ephemeral index to
   124174   ** do the sorting.  But this sorting ephemeral index might end up
   124175   ** being unused if the data can be extracted in pre-sorted order.
   124176   ** If that is the case, then the OP_OpenEphemeral instruction will be
   124177   ** changed to an OP_Noop once we figure out that the sorting index is
   124178   ** not needed.  The sSort.addrSortIndex variable is used to facilitate
   124179   ** that change.
   124180   */
   124181   if( sSort.pOrderBy ){
   124182     KeyInfo *pKeyInfo;
   124183     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
   124184     sSort.iECursor = pParse->nTab++;
   124185     sSort.addrSortIndex =
   124186       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   124187           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
   124188           (char*)pKeyInfo, P4_KEYINFO
   124189       );
   124190   }else{
   124191     sSort.addrSortIndex = -1;
   124192   }
   124193 
   124194   /* If the output is destined for a temporary table, open that table.
   124195   */
   124196   if( pDest->eDest==SRT_EphemTab ){
   124197     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
   124198   }
   124199 
   124200   /* Set the limiter.
   124201   */
   124202   iEnd = sqlite3VdbeMakeLabel(v);
   124203   if( (p->selFlags & SF_FixedLimit)==0 ){
   124204     p->nSelectRow = 320;  /* 4 billion rows */
   124205   }
   124206   computeLimitRegisters(pParse, p, iEnd);
   124207   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
   124208     sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
   124209     sSort.sortFlags |= SORTFLAG_UseSorter;
   124210   }
   124211 
   124212   /* Open an ephemeral index to use for the distinct set.
   124213   */
   124214   if( p->selFlags & SF_Distinct ){
   124215     sDistinct.tabTnct = pParse->nTab++;
   124216     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   124217                              sDistinct.tabTnct, 0, 0,
   124218                              (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
   124219                              P4_KEYINFO);
   124220     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   124221     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
   124222   }else{
   124223     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
   124224   }
   124225 
   124226   if( !isAgg && pGroupBy==0 ){
   124227     /* No aggregate functions and no GROUP BY clause */
   124228     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
   124229     assert( WHERE_USE_LIMIT==SF_FixedLimit );
   124230     wctrlFlags |= p->selFlags & SF_FixedLimit;
   124231 
   124232     /* Begin the database scan. */
   124233     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
   124234                                p->pEList, wctrlFlags, p->nSelectRow);
   124235     if( pWInfo==0 ) goto select_end;
   124236     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
   124237       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
   124238     }
   124239     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
   124240       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
   124241     }
   124242     if( sSort.pOrderBy ){
   124243       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
   124244       sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
   124245       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
   124246         sSort.pOrderBy = 0;
   124247       }
   124248     }
   124249 
   124250     /* If sorting index that was created by a prior OP_OpenEphemeral
   124251     ** instruction ended up not being needed, then change the OP_OpenEphemeral
   124252     ** into an OP_Noop.
   124253     */
   124254     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
   124255       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
   124256     }
   124257 
   124258     /* Use the standard inner loop. */
   124259     assert( p->pEList==pEList );
   124260     selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
   124261                     sqlite3WhereContinueLabel(pWInfo),
   124262                     sqlite3WhereBreakLabel(pWInfo));
   124263 
   124264     /* End the database scan loop.
   124265     */
   124266     sqlite3WhereEnd(pWInfo);
   124267   }else{
   124268     /* This case when there exist aggregate functions or a GROUP BY clause
   124269     ** or both */
   124270     NameContext sNC;    /* Name context for processing aggregate information */
   124271     int iAMem;          /* First Mem address for storing current GROUP BY */
   124272     int iBMem;          /* First Mem address for previous GROUP BY */
   124273     int iUseFlag;       /* Mem address holding flag indicating that at least
   124274                         ** one row of the input to the aggregator has been
   124275                         ** processed */
   124276     int iAbortFlag;     /* Mem address which causes query abort if positive */
   124277     int groupBySort;    /* Rows come from source in GROUP BY order */
   124278     int addrEnd;        /* End of processing for this SELECT */
   124279     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
   124280     int sortOut = 0;    /* Output register from the sorter */
   124281     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
   124282 
   124283     /* Remove any and all aliases between the result set and the
   124284     ** GROUP BY clause.
   124285     */
   124286     if( pGroupBy ){
   124287       int k;                        /* Loop counter */
   124288       struct ExprList_item *pItem;  /* For looping over expression in a list */
   124289 
   124290       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
   124291         pItem->u.x.iAlias = 0;
   124292       }
   124293       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
   124294         pItem->u.x.iAlias = 0;
   124295       }
   124296       assert( 66==sqlite3LogEst(100) );
   124297       if( p->nSelectRow>66 ) p->nSelectRow = 66;
   124298     }else{
   124299       assert( 0==sqlite3LogEst(1) );
   124300       p->nSelectRow = 0;
   124301     }
   124302 
   124303     /* If there is both a GROUP BY and an ORDER BY clause and they are
   124304     ** identical, then it may be possible to disable the ORDER BY clause
   124305     ** on the grounds that the GROUP BY will cause elements to come out
   124306     ** in the correct order. It also may not - the GROUP BY might use a
   124307     ** database index that causes rows to be grouped together as required
   124308     ** but not actually sorted. Either way, record the fact that the
   124309     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
   124310     ** variable.  */
   124311     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
   124312       orderByGrp = 1;
   124313     }
   124314 
   124315     /* Create a label to jump to when we want to abort the query */
   124316     addrEnd = sqlite3VdbeMakeLabel(v);
   124317 
   124318     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
   124319     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
   124320     ** SELECT statement.
   124321     */
   124322     memset(&sNC, 0, sizeof(sNC));
   124323     sNC.pParse = pParse;
   124324     sNC.pSrcList = pTabList;
   124325     sNC.pAggInfo = &sAggInfo;
   124326     sAggInfo.mnReg = pParse->nMem+1;
   124327     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
   124328     sAggInfo.pGroupBy = pGroupBy;
   124329     sqlite3ExprAnalyzeAggList(&sNC, pEList);
   124330     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
   124331     if( pHaving ){
   124332       if( pGroupBy ){
   124333         assert( pWhere==p->pWhere );
   124334         havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
   124335         pWhere = p->pWhere;
   124336       }
   124337       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
   124338     }
   124339     sAggInfo.nAccumulator = sAggInfo.nColumn;
   124340     if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
   124341       minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
   124342     }else{
   124343       minMaxFlag = WHERE_ORDERBY_NORMAL;
   124344     }
   124345     for(i=0; i<sAggInfo.nFunc; i++){
   124346       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
   124347       sNC.ncFlags |= NC_InAggFunc;
   124348       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
   124349       sNC.ncFlags &= ~NC_InAggFunc;
   124350     }
   124351     sAggInfo.mxReg = pParse->nMem;
   124352     if( db->mallocFailed ) goto select_end;
   124353 #if SELECTTRACE_ENABLED
   124354     if( sqlite3SelectTrace & 0x400 ){
   124355       int ii;
   124356       SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
   124357       sqlite3TreeViewSelect(0, p, 0);
   124358       for(ii=0; ii<sAggInfo.nColumn; ii++){
   124359         sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
   124360             ii, sAggInfo.aCol[ii].iMem);
   124361         sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
   124362       }
   124363       for(ii=0; ii<sAggInfo.nFunc; ii++){
   124364         sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
   124365             ii, sAggInfo.aFunc[ii].iMem);
   124366         sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
   124367       }
   124368     }
   124369 #endif
   124370 
   124371 
   124372     /* Processing for aggregates with GROUP BY is very different and
   124373     ** much more complex than aggregates without a GROUP BY.
   124374     */
   124375     if( pGroupBy ){
   124376       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
   124377       int addr1;          /* A-vs-B comparision jump */
   124378       int addrOutputRow;  /* Start of subroutine that outputs a result row */
   124379       int regOutputRow;   /* Return address register for output subroutine */
   124380       int addrSetAbort;   /* Set the abort flag and return */
   124381       int addrTopOfLoop;  /* Top of the input loop */
   124382       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
   124383       int addrReset;      /* Subroutine for resetting the accumulator */
   124384       int regReset;       /* Return address register for reset subroutine */
   124385 
   124386       /* If there is a GROUP BY clause we might need a sorting index to
   124387       ** implement it.  Allocate that sorting index now.  If it turns out
   124388       ** that we do not need it after all, the OP_SorterOpen instruction
   124389       ** will be converted into a Noop.
   124390       */
   124391       sAggInfo.sortingIdx = pParse->nTab++;
   124392       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
   124393       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
   124394           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
   124395           0, (char*)pKeyInfo, P4_KEYINFO);
   124396 
   124397       /* Initialize memory locations used by GROUP BY aggregate processing
   124398       */
   124399       iUseFlag = ++pParse->nMem;
   124400       iAbortFlag = ++pParse->nMem;
   124401       regOutputRow = ++pParse->nMem;
   124402       addrOutputRow = sqlite3VdbeMakeLabel(v);
   124403       regReset = ++pParse->nMem;
   124404       addrReset = sqlite3VdbeMakeLabel(v);
   124405       iAMem = pParse->nMem + 1;
   124406       pParse->nMem += pGroupBy->nExpr;
   124407       iBMem = pParse->nMem + 1;
   124408       pParse->nMem += pGroupBy->nExpr;
   124409       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
   124410       VdbeComment((v, "clear abort flag"));
   124411       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
   124412       VdbeComment((v, "indicate accumulator empty"));
   124413       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
   124414 
   124415       /* Begin a loop that will extract all source rows in GROUP BY order.
   124416       ** This might involve two separate loops with an OP_Sort in between, or
   124417       ** it might be a single loop that uses an index to extract information
   124418       ** in the right order to begin with.
   124419       */
   124420       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   124421       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
   124422           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
   124423       );
   124424       if( pWInfo==0 ) goto select_end;
   124425       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
   124426         /* The optimizer is able to deliver rows in group by order so
   124427         ** we do not have to sort.  The OP_OpenEphemeral table will be
   124428         ** cancelled later because we still need to use the pKeyInfo
   124429         */
   124430         groupBySort = 0;
   124431       }else{
   124432         /* Rows are coming out in undetermined order.  We have to push
   124433         ** each row into a sorting index, terminate the first loop,
   124434         ** then loop over the sorting index in order to get the output
   124435         ** in sorted order
   124436         */
   124437         int regBase;
   124438         int regRecord;
   124439         int nCol;
   124440         int nGroupBy;
   124441 
   124442         explainTempTable(pParse,
   124443             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
   124444                     "DISTINCT" : "GROUP BY");
   124445 
   124446         groupBySort = 1;
   124447         nGroupBy = pGroupBy->nExpr;
   124448         nCol = nGroupBy;
   124449         j = nGroupBy;
   124450         for(i=0; i<sAggInfo.nColumn; i++){
   124451           if( sAggInfo.aCol[i].iSorterColumn>=j ){
   124452             nCol++;
   124453             j++;
   124454           }
   124455         }
   124456         regBase = sqlite3GetTempRange(pParse, nCol);
   124457         sqlite3ExprCacheClear(pParse);
   124458         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
   124459         j = nGroupBy;
   124460         for(i=0; i<sAggInfo.nColumn; i++){
   124461           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
   124462           if( pCol->iSorterColumn>=j ){
   124463             int r1 = j + regBase;
   124464             sqlite3ExprCodeGetColumnToReg(pParse,
   124465                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
   124466             j++;
   124467           }
   124468         }
   124469         regRecord = sqlite3GetTempReg(pParse);
   124470         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
   124471         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
   124472         sqlite3ReleaseTempReg(pParse, regRecord);
   124473         sqlite3ReleaseTempRange(pParse, regBase, nCol);
   124474         sqlite3WhereEnd(pWInfo);
   124475         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
   124476         sortOut = sqlite3GetTempReg(pParse);
   124477         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
   124478         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
   124479         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
   124480         sAggInfo.useSortingIdx = 1;
   124481         sqlite3ExprCacheClear(pParse);
   124482 
   124483       }
   124484 
   124485       /* If the index or temporary table used by the GROUP BY sort
   124486       ** will naturally deliver rows in the order required by the ORDER BY
   124487       ** clause, cancel the ephemeral table open coded earlier.
   124488       **
   124489       ** This is an optimization - the correct answer should result regardless.
   124490       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
   124491       ** disable this optimization for testing purposes.  */
   124492       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
   124493        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
   124494       ){
   124495         sSort.pOrderBy = 0;
   124496         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
   124497       }
   124498 
   124499       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
   124500       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
   124501       ** Then compare the current GROUP BY terms against the GROUP BY terms
   124502       ** from the previous row currently stored in a0, a1, a2...
   124503       */
   124504       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
   124505       sqlite3ExprCacheClear(pParse);
   124506       if( groupBySort ){
   124507         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
   124508                           sortOut, sortPTab);
   124509       }
   124510       for(j=0; j<pGroupBy->nExpr; j++){
   124511         if( groupBySort ){
   124512           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
   124513         }else{
   124514           sAggInfo.directMode = 1;
   124515           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
   124516         }
   124517       }
   124518       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
   124519                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
   124520       addr1 = sqlite3VdbeCurrentAddr(v);
   124521       sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
   124522 
   124523       /* Generate code that runs whenever the GROUP BY changes.
   124524       ** Changes in the GROUP BY are detected by the previous code
   124525       ** block.  If there were no changes, this block is skipped.
   124526       **
   124527       ** This code copies current group by terms in b0,b1,b2,...
   124528       ** over to a0,a1,a2.  It then calls the output subroutine
   124529       ** and resets the aggregate accumulator registers in preparation
   124530       ** for the next GROUP BY batch.
   124531       */
   124532       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
   124533       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   124534       VdbeComment((v, "output one row"));
   124535       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
   124536       VdbeComment((v, "check abort flag"));
   124537       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   124538       VdbeComment((v, "reset accumulator"));
   124539 
   124540       /* Update the aggregate accumulators based on the content of
   124541       ** the current row
   124542       */
   124543       sqlite3VdbeJumpHere(v, addr1);
   124544       updateAccumulator(pParse, &sAggInfo);
   124545       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
   124546       VdbeComment((v, "indicate data in accumulator"));
   124547 
   124548       /* End of the loop
   124549       */
   124550       if( groupBySort ){
   124551         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
   124552         VdbeCoverage(v);
   124553       }else{
   124554         sqlite3WhereEnd(pWInfo);
   124555         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
   124556       }
   124557 
   124558       /* Output the final row of result
   124559       */
   124560       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   124561       VdbeComment((v, "output final row"));
   124562 
   124563       /* Jump over the subroutines
   124564       */
   124565       sqlite3VdbeGoto(v, addrEnd);
   124566 
   124567       /* Generate a subroutine that outputs a single row of the result
   124568       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
   124569       ** is less than or equal to zero, the subroutine is a no-op.  If
   124570       ** the processing calls for the query to abort, this subroutine
   124571       ** increments the iAbortFlag memory location before returning in
   124572       ** order to signal the caller to abort.
   124573       */
   124574       addrSetAbort = sqlite3VdbeCurrentAddr(v);
   124575       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
   124576       VdbeComment((v, "set abort flag"));
   124577       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   124578       sqlite3VdbeResolveLabel(v, addrOutputRow);
   124579       addrOutputRow = sqlite3VdbeCurrentAddr(v);
   124580       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
   124581       VdbeCoverage(v);
   124582       VdbeComment((v, "Groupby result generator entry point"));
   124583       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   124584       finalizeAggFunctions(pParse, &sAggInfo);
   124585       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
   124586       selectInnerLoop(pParse, p, -1, &sSort,
   124587                       &sDistinct, pDest,
   124588                       addrOutputRow+1, addrSetAbort);
   124589       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   124590       VdbeComment((v, "end groupby result generator"));
   124591 
   124592       /* Generate a subroutine that will reset the group-by accumulator
   124593       */
   124594       sqlite3VdbeResolveLabel(v, addrReset);
   124595       resetAccumulator(pParse, &sAggInfo);
   124596       sqlite3VdbeAddOp1(v, OP_Return, regReset);
   124597 
   124598     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
   124599     else {
   124600 #ifndef SQLITE_OMIT_BTREECOUNT
   124601       Table *pTab;
   124602       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
   124603         /* If isSimpleCount() returns a pointer to a Table structure, then
   124604         ** the SQL statement is of the form:
   124605         **
   124606         **   SELECT count(*) FROM <tbl>
   124607         **
   124608         ** where the Table structure returned represents table <tbl>.
   124609         **
   124610         ** This statement is so common that it is optimized specially. The
   124611         ** OP_Count instruction is executed either on the intkey table that
   124612         ** contains the data for table <tbl> or on one of its indexes. It
   124613         ** is better to execute the op on an index, as indexes are almost
   124614         ** always spread across less pages than their corresponding tables.
   124615         */
   124616         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   124617         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
   124618         Index *pIdx;                         /* Iterator variable */
   124619         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
   124620         Index *pBest = 0;                    /* Best index found so far */
   124621         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
   124622 
   124623         sqlite3CodeVerifySchema(pParse, iDb);
   124624         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   124625 
   124626         /* Search for the index that has the lowest scan cost.
   124627         **
   124628         ** (2011-04-15) Do not do a full scan of an unordered index.
   124629         **
   124630         ** (2013-10-03) Do not count the entries in a partial index.
   124631         **
   124632         ** In practice the KeyInfo structure will not be used. It is only
   124633         ** passed to keep OP_OpenRead happy.
   124634         */
   124635         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
   124636         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   124637           if( pIdx->bUnordered==0
   124638            && pIdx->szIdxRow<pTab->szTabRow
   124639            && pIdx->pPartIdxWhere==0
   124640            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
   124641           ){
   124642             pBest = pIdx;
   124643           }
   124644         }
   124645         if( pBest ){
   124646           iRoot = pBest->tnum;
   124647           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
   124648         }
   124649 
   124650         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
   124651         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
   124652         if( pKeyInfo ){
   124653           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
   124654         }
   124655         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
   124656         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
   124657         explainSimpleCount(pParse, pTab, pBest);
   124658       }else
   124659 #endif /* SQLITE_OMIT_BTREECOUNT */
   124660       {
   124661         /* This case runs if the aggregate has no GROUP BY clause.  The
   124662         ** processing is much simpler since there is only a single row
   124663         ** of output.
   124664         */
   124665         assert( p->pGroupBy==0 );
   124666         resetAccumulator(pParse, &sAggInfo);
   124667 
   124668         /* If this query is a candidate for the min/max optimization, then
   124669         ** minMaxFlag will have been previously set to either
   124670         ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
   124671         ** be an appropriate ORDER BY expression for the optimization.
   124672         */
   124673         assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
   124674         assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
   124675 
   124676         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
   124677                                    0, minMaxFlag, 0);
   124678         if( pWInfo==0 ){
   124679           goto select_end;
   124680         }
   124681         updateAccumulator(pParse, &sAggInfo);
   124682         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
   124683           sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
   124684           VdbeComment((v, "%s() by index",
   124685                 (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
   124686         }
   124687         sqlite3WhereEnd(pWInfo);
   124688         finalizeAggFunctions(pParse, &sAggInfo);
   124689       }
   124690 
   124691       sSort.pOrderBy = 0;
   124692       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
   124693       selectInnerLoop(pParse, p, -1, 0, 0,
   124694                       pDest, addrEnd, addrEnd);
   124695     }
   124696     sqlite3VdbeResolveLabel(v, addrEnd);
   124697 
   124698   } /* endif aggregate query */
   124699 
   124700   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
   124701     explainTempTable(pParse, "DISTINCT");
   124702   }
   124703 
   124704   /* If there is an ORDER BY clause, then we need to sort the results
   124705   ** and send them to the callback one by one.
   124706   */
   124707   if( sSort.pOrderBy ){
   124708     explainTempTable(pParse,
   124709                      sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
   124710     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
   124711   }
   124712 
   124713   /* Jump here to skip this query
   124714   */
   124715   sqlite3VdbeResolveLabel(v, iEnd);
   124716 
   124717   /* The SELECT has been coded. If there is an error in the Parse structure,
   124718   ** set the return code to 1. Otherwise 0. */
   124719   rc = (pParse->nErr>0);
   124720 
   124721   /* Control jumps to here if an error is encountered above, or upon
   124722   ** successful coding of the SELECT.
   124723   */
   124724 select_end:
   124725   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   124726   sqlite3ExprListDelete(db, pMinMaxOrderBy);
   124727   sqlite3DbFree(db, sAggInfo.aCol);
   124728   sqlite3DbFree(db, sAggInfo.aFunc);
   124729 #if SELECTTRACE_ENABLED
   124730   SELECTTRACE(1,pParse,p,("end processing\n"));
   124731   pParse->nSelectIndent--;
   124732 #endif
   124733   return rc;
   124734 }
   124735 
   124736 /************** End of select.c **********************************************/
   124737 /************** Begin file table.c *******************************************/
   124738 /*
   124739 ** 2001 September 15
   124740 **
   124741 ** The author disclaims copyright to this source code.  In place of
   124742 ** a legal notice, here is a blessing:
   124743 **
   124744 **    May you do good and not evil.
   124745 **    May you find forgiveness for yourself and forgive others.
   124746 **    May you share freely, never taking more than you give.
   124747 **
   124748 *************************************************************************
   124749 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
   124750 ** interface routines.  These are just wrappers around the main
   124751 ** interface routine of sqlite3_exec().
   124752 **
   124753 ** These routines are in a separate files so that they will not be linked
   124754 ** if they are not used.
   124755 */
   124756 /* #include "sqliteInt.h" */
   124757 
   124758 #ifndef SQLITE_OMIT_GET_TABLE
   124759 
   124760 /*
   124761 ** This structure is used to pass data from sqlite3_get_table() through
   124762 ** to the callback function is uses to build the result.
   124763 */
   124764 typedef struct TabResult {
   124765   char **azResult;   /* Accumulated output */
   124766   char *zErrMsg;     /* Error message text, if an error occurs */
   124767   u32 nAlloc;        /* Slots allocated for azResult[] */
   124768   u32 nRow;          /* Number of rows in the result */
   124769   u32 nColumn;       /* Number of columns in the result */
   124770   u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
   124771   int rc;            /* Return code from sqlite3_exec() */
   124772 } TabResult;
   124773 
   124774 /*
   124775 ** This routine is called once for each row in the result table.  Its job
   124776 ** is to fill in the TabResult structure appropriately, allocating new
   124777 ** memory as necessary.
   124778 */
   124779 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
   124780   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
   124781   int need;                         /* Slots needed in p->azResult[] */
   124782   int i;                            /* Loop counter */
   124783   char *z;                          /* A single column of result */
   124784 
   124785   /* Make sure there is enough space in p->azResult to hold everything
   124786   ** we need to remember from this invocation of the callback.
   124787   */
   124788   if( p->nRow==0 && argv!=0 ){
   124789     need = nCol*2;
   124790   }else{
   124791     need = nCol;
   124792   }
   124793   if( p->nData + need > p->nAlloc ){
   124794     char **azNew;
   124795     p->nAlloc = p->nAlloc*2 + need;
   124796     azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
   124797     if( azNew==0 ) goto malloc_failed;
   124798     p->azResult = azNew;
   124799   }
   124800 
   124801   /* If this is the first row, then generate an extra row containing
   124802   ** the names of all columns.
   124803   */
   124804   if( p->nRow==0 ){
   124805     p->nColumn = nCol;
   124806     for(i=0; i<nCol; i++){
   124807       z = sqlite3_mprintf("%s", colv[i]);
   124808       if( z==0 ) goto malloc_failed;
   124809       p->azResult[p->nData++] = z;
   124810     }
   124811   }else if( (int)p->nColumn!=nCol ){
   124812     sqlite3_free(p->zErrMsg);
   124813     p->zErrMsg = sqlite3_mprintf(
   124814        "sqlite3_get_table() called with two or more incompatible queries"
   124815     );
   124816     p->rc = SQLITE_ERROR;
   124817     return 1;
   124818   }
   124819 
   124820   /* Copy over the row data
   124821   */
   124822   if( argv!=0 ){
   124823     for(i=0; i<nCol; i++){
   124824       if( argv[i]==0 ){
   124825         z = 0;
   124826       }else{
   124827         int n = sqlite3Strlen30(argv[i])+1;
   124828         z = sqlite3_malloc64( n );
   124829         if( z==0 ) goto malloc_failed;
   124830         memcpy(z, argv[i], n);
   124831       }
   124832       p->azResult[p->nData++] = z;
   124833     }
   124834     p->nRow++;
   124835   }
   124836   return 0;
   124837 
   124838 malloc_failed:
   124839   p->rc = SQLITE_NOMEM_BKPT;
   124840   return 1;
   124841 }
   124842 
   124843 /*
   124844 ** Query the database.  But instead of invoking a callback for each row,
   124845 ** malloc() for space to hold the result and return the entire results
   124846 ** at the conclusion of the call.
   124847 **
   124848 ** The result that is written to ***pazResult is held in memory obtained
   124849 ** from malloc().  But the caller cannot free this memory directly.
   124850 ** Instead, the entire table should be passed to sqlite3_free_table() when
   124851 ** the calling procedure is finished using it.
   124852 */
   124853 SQLITE_API int sqlite3_get_table(
   124854   sqlite3 *db,                /* The database on which the SQL executes */
   124855   const char *zSql,           /* The SQL to be executed */
   124856   char ***pazResult,          /* Write the result table here */
   124857   int *pnRow,                 /* Write the number of rows in the result here */
   124858   int *pnColumn,              /* Write the number of columns of result here */
   124859   char **pzErrMsg             /* Write error messages here */
   124860 ){
   124861   int rc;
   124862   TabResult res;
   124863 
   124864 #ifdef SQLITE_ENABLE_API_ARMOR
   124865   if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
   124866 #endif
   124867   *pazResult = 0;
   124868   if( pnColumn ) *pnColumn = 0;
   124869   if( pnRow ) *pnRow = 0;
   124870   if( pzErrMsg ) *pzErrMsg = 0;
   124871   res.zErrMsg = 0;
   124872   res.nRow = 0;
   124873   res.nColumn = 0;
   124874   res.nData = 1;
   124875   res.nAlloc = 20;
   124876   res.rc = SQLITE_OK;
   124877   res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
   124878   if( res.azResult==0 ){
   124879      db->errCode = SQLITE_NOMEM;
   124880      return SQLITE_NOMEM_BKPT;
   124881   }
   124882   res.azResult[0] = 0;
   124883   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
   124884   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
   124885   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
   124886   if( (rc&0xff)==SQLITE_ABORT ){
   124887     sqlite3_free_table(&res.azResult[1]);
   124888     if( res.zErrMsg ){
   124889       if( pzErrMsg ){
   124890         sqlite3_free(*pzErrMsg);
   124891         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
   124892       }
   124893       sqlite3_free(res.zErrMsg);
   124894     }
   124895     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
   124896     return res.rc;
   124897   }
   124898   sqlite3_free(res.zErrMsg);
   124899   if( rc!=SQLITE_OK ){
   124900     sqlite3_free_table(&res.azResult[1]);
   124901     return rc;
   124902   }
   124903   if( res.nAlloc>res.nData ){
   124904     char **azNew;
   124905     azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
   124906     if( azNew==0 ){
   124907       sqlite3_free_table(&res.azResult[1]);
   124908       db->errCode = SQLITE_NOMEM;
   124909       return SQLITE_NOMEM_BKPT;
   124910     }
   124911     res.azResult = azNew;
   124912   }
   124913   *pazResult = &res.azResult[1];
   124914   if( pnColumn ) *pnColumn = res.nColumn;
   124915   if( pnRow ) *pnRow = res.nRow;
   124916   return rc;
   124917 }
   124918 
   124919 /*
   124920 ** This routine frees the space the sqlite3_get_table() malloced.
   124921 */
   124922 SQLITE_API void sqlite3_free_table(
   124923   char **azResult            /* Result returned from sqlite3_get_table() */
   124924 ){
   124925   if( azResult ){
   124926     int i, n;
   124927     azResult--;
   124928     assert( azResult!=0 );
   124929     n = SQLITE_PTR_TO_INT(azResult[0]);
   124930     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
   124931     sqlite3_free(azResult);
   124932   }
   124933 }
   124934 
   124935 #endif /* SQLITE_OMIT_GET_TABLE */
   124936 
   124937 /************** End of table.c ***********************************************/
   124938 /************** Begin file trigger.c *****************************************/
   124939 /*
   124940 **
   124941 ** The author disclaims copyright to this source code.  In place of
   124942 ** a legal notice, here is a blessing:
   124943 **
   124944 **    May you do good and not evil.
   124945 **    May you find forgiveness for yourself and forgive others.
   124946 **    May you share freely, never taking more than you give.
   124947 **
   124948 *************************************************************************
   124949 ** This file contains the implementation for TRIGGERs
   124950 */
   124951 /* #include "sqliteInt.h" */
   124952 
   124953 #ifndef SQLITE_OMIT_TRIGGER
   124954 /*
   124955 ** Delete a linked list of TriggerStep structures.
   124956 */
   124957 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
   124958   while( pTriggerStep ){
   124959     TriggerStep * pTmp = pTriggerStep;
   124960     pTriggerStep = pTriggerStep->pNext;
   124961 
   124962     sqlite3ExprDelete(db, pTmp->pWhere);
   124963     sqlite3ExprListDelete(db, pTmp->pExprList);
   124964     sqlite3SelectDelete(db, pTmp->pSelect);
   124965     sqlite3IdListDelete(db, pTmp->pIdList);
   124966     sqlite3DbFree(db, pTmp->zSpan);
   124967 
   124968     sqlite3DbFree(db, pTmp);
   124969   }
   124970 }
   124971 
   124972 /*
   124973 ** Given table pTab, return a list of all the triggers attached to
   124974 ** the table. The list is connected by Trigger.pNext pointers.
   124975 **
   124976 ** All of the triggers on pTab that are in the same database as pTab
   124977 ** are already attached to pTab->pTrigger.  But there might be additional
   124978 ** triggers on pTab in the TEMP schema.  This routine prepends all
   124979 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
   124980 ** and returns the combined list.
   124981 **
   124982 ** To state it another way:  This routine returns a list of all triggers
   124983 ** that fire off of pTab.  The list will include any TEMP triggers on
   124984 ** pTab as well as the triggers lised in pTab->pTrigger.
   124985 */
   124986 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   124987   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
   124988   Trigger *pList = 0;                  /* List of triggers to return */
   124989 
   124990   if( pParse->disableTriggers ){
   124991     return 0;
   124992   }
   124993 
   124994   if( pTmpSchema!=pTab->pSchema ){
   124995     HashElem *p;
   124996     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
   124997     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
   124998       Trigger *pTrig = (Trigger *)sqliteHashData(p);
   124999       if( pTrig->pTabSchema==pTab->pSchema
   125000        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
   125001       ){
   125002         pTrig->pNext = (pList ? pList : pTab->pTrigger);
   125003         pList = pTrig;
   125004       }
   125005     }
   125006   }
   125007 
   125008   return (pList ? pList : pTab->pTrigger);
   125009 }
   125010 
   125011 /*
   125012 ** This is called by the parser when it sees a CREATE TRIGGER statement
   125013 ** up to the point of the BEGIN before the trigger actions.  A Trigger
   125014 ** structure is generated based on the information available and stored
   125015 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
   125016 ** sqlite3FinishTrigger() function is called to complete the trigger
   125017 ** construction process.
   125018 */
   125019 SQLITE_PRIVATE void sqlite3BeginTrigger(
   125020   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
   125021   Token *pName1,      /* The name of the trigger */
   125022   Token *pName2,      /* The name of the trigger */
   125023   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
   125024   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
   125025   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
   125026   SrcList *pTableName,/* The name of the table/view the trigger applies to */
   125027   Expr *pWhen,        /* WHEN clause */
   125028   int isTemp,         /* True if the TEMPORARY keyword is present */
   125029   int noErr           /* Suppress errors if the trigger already exists */
   125030 ){
   125031   Trigger *pTrigger = 0;  /* The new trigger */
   125032   Table *pTab;            /* Table that the trigger fires off of */
   125033   char *zName = 0;        /* Name of the trigger */
   125034   sqlite3 *db = pParse->db;  /* The database connection */
   125035   int iDb;                /* The database to store the trigger in */
   125036   Token *pName;           /* The unqualified db name */
   125037   DbFixer sFix;           /* State vector for the DB fixer */
   125038 
   125039   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
   125040   assert( pName2!=0 );
   125041   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
   125042   assert( op>0 && op<0xff );
   125043   if( isTemp ){
   125044     /* If TEMP was specified, then the trigger name may not be qualified. */
   125045     if( pName2->n>0 ){
   125046       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
   125047       goto trigger_cleanup;
   125048     }
   125049     iDb = 1;
   125050     pName = pName1;
   125051   }else{
   125052     /* Figure out the db that the trigger will be created in */
   125053     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   125054     if( iDb<0 ){
   125055       goto trigger_cleanup;
   125056     }
   125057   }
   125058   if( !pTableName || db->mallocFailed ){
   125059     goto trigger_cleanup;
   125060   }
   125061 
   125062   /* A long-standing parser bug is that this syntax was allowed:
   125063   **
   125064   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
   125065   **                                                 ^^^^^^^^
   125066   **
   125067   ** To maintain backwards compatibility, ignore the database
   125068   ** name on pTableName if we are reparsing out of SQLITE_MASTER.
   125069   */
   125070   if( db->init.busy && iDb!=1 ){
   125071     sqlite3DbFree(db, pTableName->a[0].zDatabase);
   125072     pTableName->a[0].zDatabase = 0;
   125073   }
   125074 
   125075   /* If the trigger name was unqualified, and the table is a temp table,
   125076   ** then set iDb to 1 to create the trigger in the temporary database.
   125077   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
   125078   ** exist, the error is caught by the block below.
   125079   */
   125080   pTab = sqlite3SrcListLookup(pParse, pTableName);
   125081   if( db->init.busy==0 && pName2->n==0 && pTab
   125082         && pTab->pSchema==db->aDb[1].pSchema ){
   125083     iDb = 1;
   125084   }
   125085 
   125086   /* Ensure the table name matches database name and that the table exists */
   125087   if( db->mallocFailed ) goto trigger_cleanup;
   125088   assert( pTableName->nSrc==1 );
   125089   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
   125090   if( sqlite3FixSrcList(&sFix, pTableName) ){
   125091     goto trigger_cleanup;
   125092   }
   125093   pTab = sqlite3SrcListLookup(pParse, pTableName);
   125094   if( !pTab ){
   125095     /* The table does not exist. */
   125096     if( db->init.iDb==1 ){
   125097       /* Ticket #3810.
   125098       ** Normally, whenever a table is dropped, all associated triggers are
   125099       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
   125100       ** and the table is dropped by a different database connection, the
   125101       ** trigger is not visible to the database connection that does the
   125102       ** drop so the trigger cannot be dropped.  This results in an
   125103       ** "orphaned trigger" - a trigger whose associated table is missing.
   125104       */
   125105       db->init.orphanTrigger = 1;
   125106     }
   125107     goto trigger_cleanup;
   125108   }
   125109   if( IsVirtual(pTab) ){
   125110     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
   125111     goto trigger_cleanup;
   125112   }
   125113 
   125114   /* Check that the trigger name is not reserved and that no trigger of the
   125115   ** specified name exists */
   125116   zName = sqlite3NameFromToken(db, pName);
   125117   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   125118     goto trigger_cleanup;
   125119   }
   125120   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   125121   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
   125122     if( !noErr ){
   125123       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
   125124     }else{
   125125       assert( !db->init.busy );
   125126       sqlite3CodeVerifySchema(pParse, iDb);
   125127     }
   125128     goto trigger_cleanup;
   125129   }
   125130 
   125131   /* Do not create a trigger on a system table */
   125132   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   125133     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
   125134     goto trigger_cleanup;
   125135   }
   125136 
   125137   /* INSTEAD of triggers are only for views and views only support INSTEAD
   125138   ** of triggers.
   125139   */
   125140   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
   125141     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
   125142         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
   125143     goto trigger_cleanup;
   125144   }
   125145   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
   125146     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
   125147         " trigger on table: %S", pTableName, 0);
   125148     goto trigger_cleanup;
   125149   }
   125150 
   125151 #ifndef SQLITE_OMIT_AUTHORIZATION
   125152   {
   125153     int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   125154     int code = SQLITE_CREATE_TRIGGER;
   125155     const char *zDb = db->aDb[iTabDb].zDbSName;
   125156     const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
   125157     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   125158     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   125159       goto trigger_cleanup;
   125160     }
   125161     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   125162       goto trigger_cleanup;
   125163     }
   125164   }
   125165 #endif
   125166 
   125167   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
   125168   ** cannot appear on views.  So we might as well translate every
   125169   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
   125170   ** elsewhere.
   125171   */
   125172   if (tr_tm == TK_INSTEAD){
   125173     tr_tm = TK_BEFORE;
   125174   }
   125175 
   125176   /* Build the Trigger object */
   125177   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   125178   if( pTrigger==0 ) goto trigger_cleanup;
   125179   pTrigger->zName = zName;
   125180   zName = 0;
   125181   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   125182   pTrigger->pSchema = db->aDb[iDb].pSchema;
   125183   pTrigger->pTabSchema = pTab->pSchema;
   125184   pTrigger->op = (u8)op;
   125185   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   125186   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   125187   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
   125188   assert( pParse->pNewTrigger==0 );
   125189   pParse->pNewTrigger = pTrigger;
   125190 
   125191 trigger_cleanup:
   125192   sqlite3DbFree(db, zName);
   125193   sqlite3SrcListDelete(db, pTableName);
   125194   sqlite3IdListDelete(db, pColumns);
   125195   sqlite3ExprDelete(db, pWhen);
   125196   if( !pParse->pNewTrigger ){
   125197     sqlite3DeleteTrigger(db, pTrigger);
   125198   }else{
   125199     assert( pParse->pNewTrigger==pTrigger );
   125200   }
   125201 }
   125202 
   125203 /*
   125204 ** This routine is called after all of the trigger actions have been parsed
   125205 ** in order to complete the process of building the trigger.
   125206 */
   125207 SQLITE_PRIVATE void sqlite3FinishTrigger(
   125208   Parse *pParse,          /* Parser context */
   125209   TriggerStep *pStepList, /* The triggered program */
   125210   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
   125211 ){
   125212   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
   125213   char *zName;                            /* Name of trigger */
   125214   sqlite3 *db = pParse->db;               /* The database */
   125215   DbFixer sFix;                           /* Fixer object */
   125216   int iDb;                                /* Database containing the trigger */
   125217   Token nameToken;                        /* Trigger name for error reporting */
   125218 
   125219   pParse->pNewTrigger = 0;
   125220   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   125221   zName = pTrig->zName;
   125222   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   125223   pTrig->step_list = pStepList;
   125224   while( pStepList ){
   125225     pStepList->pTrig = pTrig;
   125226     pStepList = pStepList->pNext;
   125227   }
   125228   sqlite3TokenInit(&nameToken, pTrig->zName);
   125229   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
   125230   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
   125231    || sqlite3FixExpr(&sFix, pTrig->pWhen)
   125232   ){
   125233     goto triggerfinish_cleanup;
   125234   }
   125235 
   125236   /* if we are not initializing,
   125237   ** build the sqlite_master entry
   125238   */
   125239   if( !db->init.busy ){
   125240     Vdbe *v;
   125241     char *z;
   125242 
   125243     /* Make an entry in the sqlite_master table */
   125244     v = sqlite3GetVdbe(pParse);
   125245     if( v==0 ) goto triggerfinish_cleanup;
   125246     sqlite3BeginWriteOperation(pParse, 0, iDb);
   125247     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   125248     testcase( z==0 );
   125249     sqlite3NestedParse(pParse,
   125250        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   125251        db->aDb[iDb].zDbSName, MASTER_NAME, zName,
   125252        pTrig->table, z);
   125253     sqlite3DbFree(db, z);
   125254     sqlite3ChangeCookie(pParse, iDb);
   125255     sqlite3VdbeAddParseSchemaOp(v, iDb,
   125256         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
   125257   }
   125258 
   125259   if( db->init.busy ){
   125260     Trigger *pLink = pTrig;
   125261     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   125262     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   125263     pTrig = sqlite3HashInsert(pHash, zName, pTrig);
   125264     if( pTrig ){
   125265       sqlite3OomFault(db);
   125266     }else if( pLink->pSchema==pLink->pTabSchema ){
   125267       Table *pTab;
   125268       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
   125269       assert( pTab!=0 );
   125270       pLink->pNext = pTab->pTrigger;
   125271       pTab->pTrigger = pLink;
   125272     }
   125273   }
   125274 
   125275 triggerfinish_cleanup:
   125276   sqlite3DeleteTrigger(db, pTrig);
   125277   assert( !pParse->pNewTrigger );
   125278   sqlite3DeleteTriggerStep(db, pStepList);
   125279 }
   125280 
   125281 /*
   125282 ** Duplicate a range of text from an SQL statement, then convert all
   125283 ** whitespace characters into ordinary space characters.
   125284 */
   125285 static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
   125286   char *z = sqlite3DbSpanDup(db, zStart, zEnd);
   125287   int i;
   125288   if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
   125289   return z;
   125290 }
   125291 
   125292 /*
   125293 ** Turn a SELECT statement (that the pSelect parameter points to) into
   125294 ** a trigger step.  Return a pointer to a TriggerStep structure.
   125295 **
   125296 ** The parser calls this routine when it finds a SELECT statement in
   125297 ** body of a TRIGGER.
   125298 */
   125299 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
   125300   sqlite3 *db,                /* Database connection */
   125301   Select *pSelect,            /* The SELECT statement */
   125302   const char *zStart,         /* Start of SQL text */
   125303   const char *zEnd            /* End of SQL text */
   125304 ){
   125305   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
   125306   if( pTriggerStep==0 ) {
   125307     sqlite3SelectDelete(db, pSelect);
   125308     return 0;
   125309   }
   125310   pTriggerStep->op = TK_SELECT;
   125311   pTriggerStep->pSelect = pSelect;
   125312   pTriggerStep->orconf = OE_Default;
   125313   pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
   125314   return pTriggerStep;
   125315 }
   125316 
   125317 /*
   125318 ** Allocate space to hold a new trigger step.  The allocated space
   125319 ** holds both the TriggerStep object and the TriggerStep.target.z string.
   125320 **
   125321 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
   125322 */
   125323 static TriggerStep *triggerStepAllocate(
   125324   sqlite3 *db,                /* Database connection */
   125325   u8 op,                      /* Trigger opcode */
   125326   Token *pName,               /* The target name */
   125327   const char *zStart,         /* Start of SQL text */
   125328   const char *zEnd            /* End of SQL text */
   125329 ){
   125330   TriggerStep *pTriggerStep;
   125331 
   125332   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
   125333   if( pTriggerStep ){
   125334     char *z = (char*)&pTriggerStep[1];
   125335     memcpy(z, pName->z, pName->n);
   125336     sqlite3Dequote(z);
   125337     pTriggerStep->zTarget = z;
   125338     pTriggerStep->op = op;
   125339     pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
   125340   }
   125341   return pTriggerStep;
   125342 }
   125343 
   125344 /*
   125345 ** Build a trigger step out of an INSERT statement.  Return a pointer
   125346 ** to the new trigger step.
   125347 **
   125348 ** The parser calls this routine when it sees an INSERT inside the
   125349 ** body of a trigger.
   125350 */
   125351 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
   125352   sqlite3 *db,        /* The database connection */
   125353   Token *pTableName,  /* Name of the table into which we insert */
   125354   IdList *pColumn,    /* List of columns in pTableName to insert into */
   125355   Select *pSelect,    /* A SELECT statement that supplies values */
   125356   u8 orconf,          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
   125357   const char *zStart, /* Start of SQL text */
   125358   const char *zEnd    /* End of SQL text */
   125359 ){
   125360   TriggerStep *pTriggerStep;
   125361 
   125362   assert(pSelect != 0 || db->mallocFailed);
   125363 
   125364   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName, zStart, zEnd);
   125365   if( pTriggerStep ){
   125366     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   125367     pTriggerStep->pIdList = pColumn;
   125368     pTriggerStep->orconf = orconf;
   125369   }else{
   125370     sqlite3IdListDelete(db, pColumn);
   125371   }
   125372   sqlite3SelectDelete(db, pSelect);
   125373 
   125374   return pTriggerStep;
   125375 }
   125376 
   125377 /*
   125378 ** Construct a trigger step that implements an UPDATE statement and return
   125379 ** a pointer to that trigger step.  The parser calls this routine when it
   125380 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
   125381 */
   125382 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   125383   sqlite3 *db,         /* The database connection */
   125384   Token *pTableName,   /* Name of the table to be updated */
   125385   ExprList *pEList,    /* The SET clause: list of column and new values */
   125386   Expr *pWhere,        /* The WHERE clause */
   125387   u8 orconf,           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
   125388   const char *zStart,  /* Start of SQL text */
   125389   const char *zEnd     /* End of SQL text */
   125390 ){
   125391   TriggerStep *pTriggerStep;
   125392 
   125393   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName, zStart, zEnd);
   125394   if( pTriggerStep ){
   125395     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   125396     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   125397     pTriggerStep->orconf = orconf;
   125398   }
   125399   sqlite3ExprListDelete(db, pEList);
   125400   sqlite3ExprDelete(db, pWhere);
   125401   return pTriggerStep;
   125402 }
   125403 
   125404 /*
   125405 ** Construct a trigger step that implements a DELETE statement and return
   125406 ** a pointer to that trigger step.  The parser calls this routine when it
   125407 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
   125408 */
   125409 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   125410   sqlite3 *db,            /* Database connection */
   125411   Token *pTableName,      /* The table from which rows are deleted */
   125412   Expr *pWhere,           /* The WHERE clause */
   125413   const char *zStart,     /* Start of SQL text */
   125414   const char *zEnd        /* End of SQL text */
   125415 ){
   125416   TriggerStep *pTriggerStep;
   125417 
   125418   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName, zStart, zEnd);
   125419   if( pTriggerStep ){
   125420     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   125421     pTriggerStep->orconf = OE_Default;
   125422   }
   125423   sqlite3ExprDelete(db, pWhere);
   125424   return pTriggerStep;
   125425 }
   125426 
   125427 /*
   125428 ** Recursively delete a Trigger structure
   125429 */
   125430 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   125431   if( pTrigger==0 ) return;
   125432   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   125433   sqlite3DbFree(db, pTrigger->zName);
   125434   sqlite3DbFree(db, pTrigger->table);
   125435   sqlite3ExprDelete(db, pTrigger->pWhen);
   125436   sqlite3IdListDelete(db, pTrigger->pColumns);
   125437   sqlite3DbFree(db, pTrigger);
   125438 }
   125439 
   125440 /*
   125441 ** This function is called to drop a trigger from the database schema.
   125442 **
   125443 ** This may be called directly from the parser and therefore identifies
   125444 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
   125445 ** same job as this routine except it takes a pointer to the trigger
   125446 ** instead of the trigger name.
   125447 **/
   125448 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
   125449   Trigger *pTrigger = 0;
   125450   int i;
   125451   const char *zDb;
   125452   const char *zName;
   125453   sqlite3 *db = pParse->db;
   125454 
   125455   if( db->mallocFailed ) goto drop_trigger_cleanup;
   125456   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   125457     goto drop_trigger_cleanup;
   125458   }
   125459 
   125460   assert( pName->nSrc==1 );
   125461   zDb = pName->a[0].zDatabase;
   125462   zName = pName->a[0].zName;
   125463   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   125464   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   125465     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   125466     if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
   125467     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   125468     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
   125469     if( pTrigger ) break;
   125470   }
   125471   if( !pTrigger ){
   125472     if( !noErr ){
   125473       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
   125474     }else{
   125475       sqlite3CodeVerifyNamedSchema(pParse, zDb);
   125476     }
   125477     pParse->checkSchema = 1;
   125478     goto drop_trigger_cleanup;
   125479   }
   125480   sqlite3DropTriggerPtr(pParse, pTrigger);
   125481 
   125482 drop_trigger_cleanup:
   125483   sqlite3SrcListDelete(db, pName);
   125484 }
   125485 
   125486 /*
   125487 ** Return a pointer to the Table structure for the table that a trigger
   125488 ** is set on.
   125489 */
   125490 static Table *tableOfTrigger(Trigger *pTrigger){
   125491   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
   125492 }
   125493 
   125494 
   125495 /*
   125496 ** Drop a trigger given a pointer to that trigger.
   125497 */
   125498 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   125499   Table   *pTable;
   125500   Vdbe *v;
   125501   sqlite3 *db = pParse->db;
   125502   int iDb;
   125503 
   125504   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
   125505   assert( iDb>=0 && iDb<db->nDb );
   125506   pTable = tableOfTrigger(pTrigger);
   125507   assert( pTable );
   125508   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   125509 #ifndef SQLITE_OMIT_AUTHORIZATION
   125510   {
   125511     int code = SQLITE_DROP_TRIGGER;
   125512     const char *zDb = db->aDb[iDb].zDbSName;
   125513     const char *zTab = SCHEMA_TABLE(iDb);
   125514     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   125515     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   125516       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   125517       return;
   125518     }
   125519   }
   125520 #endif
   125521 
   125522   /* Generate code to destroy the database record of the trigger.
   125523   */
   125524   assert( pTable!=0 );
   125525   if( (v = sqlite3GetVdbe(pParse))!=0 ){
   125526     sqlite3NestedParse(pParse,
   125527        "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
   125528        db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
   125529     );
   125530     sqlite3ChangeCookie(pParse, iDb);
   125531     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   125532   }
   125533 }
   125534 
   125535 /*
   125536 ** Remove a trigger from the hash tables of the sqlite* pointer.
   125537 */
   125538 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
   125539   Trigger *pTrigger;
   125540   Hash *pHash;
   125541 
   125542   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   125543   pHash = &(db->aDb[iDb].pSchema->trigHash);
   125544   pTrigger = sqlite3HashInsert(pHash, zName, 0);
   125545   if( ALWAYS(pTrigger) ){
   125546     if( pTrigger->pSchema==pTrigger->pTabSchema ){
   125547       Table *pTab = tableOfTrigger(pTrigger);
   125548       Trigger **pp;
   125549       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
   125550       *pp = (*pp)->pNext;
   125551     }
   125552     sqlite3DeleteTrigger(db, pTrigger);
   125553     db->mDbFlags |= DBFLAG_SchemaChange;
   125554   }
   125555 }
   125556 
   125557 /*
   125558 ** pEList is the SET clause of an UPDATE statement.  Each entry
   125559 ** in pEList is of the format <id>=<expr>.  If any of the entries
   125560 ** in pEList have an <id> which matches an identifier in pIdList,
   125561 ** then return TRUE.  If pIdList==NULL, then it is considered a
   125562 ** wildcard that matches anything.  Likewise if pEList==NULL then
   125563 ** it matches anything so always return true.  Return false only
   125564 ** if there is no match.
   125565 */
   125566 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   125567   int e;
   125568   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   125569   for(e=0; e<pEList->nExpr; e++){
   125570     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
   125571   }
   125572   return 0;
   125573 }
   125574 
   125575 /*
   125576 ** Return a list of all triggers on table pTab if there exists at least
   125577 ** one trigger that must be fired when an operation of type 'op' is
   125578 ** performed on the table, and, if that operation is an UPDATE, if at
   125579 ** least one of the columns in pChanges is being modified.
   125580 */
   125581 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
   125582   Parse *pParse,          /* Parse context */
   125583   Table *pTab,            /* The table the contains the triggers */
   125584   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
   125585   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
   125586   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   125587 ){
   125588   int mask = 0;
   125589   Trigger *pList = 0;
   125590   Trigger *p;
   125591 
   125592   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
   125593     pList = sqlite3TriggerList(pParse, pTab);
   125594   }
   125595   assert( pList==0 || IsVirtual(pTab)==0 );
   125596   for(p=pList; p; p=p->pNext){
   125597     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
   125598       mask |= p->tr_tm;
   125599     }
   125600   }
   125601   if( pMask ){
   125602     *pMask = mask;
   125603   }
   125604   return (mask ? pList : 0);
   125605 }
   125606 
   125607 /*
   125608 ** Convert the pStep->zTarget string into a SrcList and return a pointer
   125609 ** to that SrcList.
   125610 **
   125611 ** This routine adds a specific database name, if needed, to the target when
   125612 ** forming the SrcList.  This prevents a trigger in one database from
   125613 ** referring to a target in another database.  An exception is when the
   125614 ** trigger is in TEMP in which case it can refer to any other database it
   125615 ** wants.
   125616 */
   125617 static SrcList *targetSrcList(
   125618   Parse *pParse,       /* The parsing context */
   125619   TriggerStep *pStep   /* The trigger containing the target token */
   125620 ){
   125621   sqlite3 *db = pParse->db;
   125622   int iDb;             /* Index of the database to use */
   125623   SrcList *pSrc;       /* SrcList to be returned */
   125624 
   125625   pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   125626   if( pSrc ){
   125627     assert( pSrc->nSrc>0 );
   125628     pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
   125629     iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
   125630     if( iDb==0 || iDb>=2 ){
   125631       const char *zDb;
   125632       assert( iDb<db->nDb );
   125633       zDb = db->aDb[iDb].zDbSName;
   125634       pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
   125635     }
   125636   }
   125637   return pSrc;
   125638 }
   125639 
   125640 /*
   125641 ** Generate VDBE code for the statements inside the body of a single
   125642 ** trigger.
   125643 */
   125644 static int codeTriggerProgram(
   125645   Parse *pParse,            /* The parser context */
   125646   TriggerStep *pStepList,   /* List of statements inside the trigger body */
   125647   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
   125648 ){
   125649   TriggerStep *pStep;
   125650   Vdbe *v = pParse->pVdbe;
   125651   sqlite3 *db = pParse->db;
   125652 
   125653   assert( pParse->pTriggerTab && pParse->pToplevel );
   125654   assert( pStepList );
   125655   assert( v!=0 );
   125656   for(pStep=pStepList; pStep; pStep=pStep->pNext){
   125657     /* Figure out the ON CONFLICT policy that will be used for this step
   125658     ** of the trigger program. If the statement that caused this trigger
   125659     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   125660     ** the ON CONFLICT policy that was specified as part of the trigger
   125661     ** step statement. Example:
   125662     **
   125663     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   125664     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   125665     **   END;
   125666     **
   125667     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   125668     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   125669     */
   125670     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
   125671     assert( pParse->okConstFactor==0 );
   125672 
   125673 #ifndef SQLITE_OMIT_TRACE
   125674     if( pStep->zSpan ){
   125675       sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
   125676                         sqlite3MPrintf(db, "-- %s", pStep->zSpan),
   125677                         P4_DYNAMIC);
   125678     }
   125679 #endif
   125680 
   125681     switch( pStep->op ){
   125682       case TK_UPDATE: {
   125683         sqlite3Update(pParse,
   125684           targetSrcList(pParse, pStep),
   125685           sqlite3ExprListDup(db, pStep->pExprList, 0),
   125686           sqlite3ExprDup(db, pStep->pWhere, 0),
   125687           pParse->eOrconf, 0, 0
   125688         );
   125689         break;
   125690       }
   125691       case TK_INSERT: {
   125692         sqlite3Insert(pParse,
   125693           targetSrcList(pParse, pStep),
   125694           sqlite3SelectDup(db, pStep->pSelect, 0),
   125695           sqlite3IdListDup(db, pStep->pIdList),
   125696           pParse->eOrconf
   125697         );
   125698         break;
   125699       }
   125700       case TK_DELETE: {
   125701         sqlite3DeleteFrom(pParse,
   125702           targetSrcList(pParse, pStep),
   125703           sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
   125704         );
   125705         break;
   125706       }
   125707       default: assert( pStep->op==TK_SELECT ); {
   125708         SelectDest sDest;
   125709         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
   125710         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
   125711         sqlite3Select(pParse, pSelect, &sDest);
   125712         sqlite3SelectDelete(db, pSelect);
   125713         break;
   125714       }
   125715     }
   125716     if( pStep->op!=TK_SELECT ){
   125717       sqlite3VdbeAddOp0(v, OP_ResetCount);
   125718     }
   125719   }
   125720 
   125721   return 0;
   125722 }
   125723 
   125724 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   125725 /*
   125726 ** This function is used to add VdbeComment() annotations to a VDBE
   125727 ** program. It is not used in production code, only for debugging.
   125728 */
   125729 static const char *onErrorText(int onError){
   125730   switch( onError ){
   125731     case OE_Abort:    return "abort";
   125732     case OE_Rollback: return "rollback";
   125733     case OE_Fail:     return "fail";
   125734     case OE_Replace:  return "replace";
   125735     case OE_Ignore:   return "ignore";
   125736     case OE_Default:  return "default";
   125737   }
   125738   return "n/a";
   125739 }
   125740 #endif
   125741 
   125742 /*
   125743 ** Parse context structure pFrom has just been used to create a sub-vdbe
   125744 ** (trigger program). If an error has occurred, transfer error information
   125745 ** from pFrom to pTo.
   125746 */
   125747 static void transferParseError(Parse *pTo, Parse *pFrom){
   125748   assert( pFrom->zErrMsg==0 || pFrom->nErr );
   125749   assert( pTo->zErrMsg==0 || pTo->nErr );
   125750   if( pTo->nErr==0 ){
   125751     pTo->zErrMsg = pFrom->zErrMsg;
   125752     pTo->nErr = pFrom->nErr;
   125753     pTo->rc = pFrom->rc;
   125754   }else{
   125755     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   125756   }
   125757 }
   125758 
   125759 /*
   125760 ** Create and populate a new TriggerPrg object with a sub-program
   125761 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
   125762 */
   125763 static TriggerPrg *codeRowTrigger(
   125764   Parse *pParse,       /* Current parse context */
   125765   Trigger *pTrigger,   /* Trigger to code */
   125766   Table *pTab,         /* The table pTrigger is attached to */
   125767   int orconf           /* ON CONFLICT policy to code trigger program with */
   125768 ){
   125769   Parse *pTop = sqlite3ParseToplevel(pParse);
   125770   sqlite3 *db = pParse->db;   /* Database handle */
   125771   TriggerPrg *pPrg;           /* Value to return */
   125772   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   125773   Vdbe *v;                    /* Temporary VM */
   125774   NameContext sNC;            /* Name context for sub-vdbe */
   125775   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   125776   Parse *pSubParse;           /* Parse context for sub-vdbe */
   125777   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   125778 
   125779   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   125780   assert( pTop->pVdbe );
   125781 
   125782   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
   125783   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   125784   ** list of the top-level Parse object sooner rather than later.  */
   125785   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   125786   if( !pPrg ) return 0;
   125787   pPrg->pNext = pTop->pTriggerPrg;
   125788   pTop->pTriggerPrg = pPrg;
   125789   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   125790   if( !pProgram ) return 0;
   125791   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
   125792   pPrg->pTrigger = pTrigger;
   125793   pPrg->orconf = orconf;
   125794   pPrg->aColmask[0] = 0xffffffff;
   125795   pPrg->aColmask[1] = 0xffffffff;
   125796 
   125797   /* Allocate and populate a new Parse context to use for coding the
   125798   ** trigger sub-program.  */
   125799   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   125800   if( !pSubParse ) return 0;
   125801   memset(&sNC, 0, sizeof(sNC));
   125802   sNC.pParse = pSubParse;
   125803   pSubParse->db = db;
   125804   pSubParse->pTriggerTab = pTab;
   125805   pSubParse->pToplevel = pTop;
   125806   pSubParse->zAuthContext = pTrigger->zName;
   125807   pSubParse->eTriggerOp = pTrigger->op;
   125808   pSubParse->nQueryLoop = pParse->nQueryLoop;
   125809 
   125810   v = sqlite3GetVdbe(pSubParse);
   125811   if( v ){
   125812     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
   125813       pTrigger->zName, onErrorText(orconf),
   125814       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   125815         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
   125816         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
   125817         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   125818       pTab->zName
   125819     ));
   125820 #ifndef SQLITE_OMIT_TRACE
   125821     if( pTrigger->zName ){
   125822       sqlite3VdbeChangeP4(v, -1,
   125823         sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   125824       );
   125825     }
   125826 #endif
   125827 
   125828     /* If one was specified, code the WHEN clause. If it evaluates to false
   125829     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
   125830     ** OP_Halt inserted at the end of the program.  */
   125831     if( pTrigger->pWhen ){
   125832       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   125833       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
   125834        && db->mallocFailed==0
   125835       ){
   125836         iEndTrigger = sqlite3VdbeMakeLabel(v);
   125837         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   125838       }
   125839       sqlite3ExprDelete(db, pWhen);
   125840     }
   125841 
   125842     /* Code the trigger program into the sub-vdbe. */
   125843     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
   125844 
   125845     /* Insert an OP_Halt at the end of the sub-program. */
   125846     if( iEndTrigger ){
   125847       sqlite3VdbeResolveLabel(v, iEndTrigger);
   125848     }
   125849     sqlite3VdbeAddOp0(v, OP_Halt);
   125850     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   125851 
   125852     transferParseError(pParse, pSubParse);
   125853     if( db->mallocFailed==0 && pParse->nErr==0 ){
   125854       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   125855     }
   125856     pProgram->nMem = pSubParse->nMem;
   125857     pProgram->nCsr = pSubParse->nTab;
   125858     pProgram->token = (void *)pTrigger;
   125859     pPrg->aColmask[0] = pSubParse->oldmask;
   125860     pPrg->aColmask[1] = pSubParse->newmask;
   125861     sqlite3VdbeDelete(v);
   125862   }
   125863 
   125864   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   125865   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   125866   sqlite3ParserReset(pSubParse);
   125867   sqlite3StackFree(db, pSubParse);
   125868 
   125869   return pPrg;
   125870 }
   125871 
   125872 /*
   125873 ** Return a pointer to a TriggerPrg object containing the sub-program for
   125874 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
   125875 ** TriggerPrg object exists, a new object is allocated and populated before
   125876 ** being returned.
   125877 */
   125878 static TriggerPrg *getRowTrigger(
   125879   Parse *pParse,       /* Current parse context */
   125880   Trigger *pTrigger,   /* Trigger to code */
   125881   Table *pTab,         /* The table trigger pTrigger is attached to */
   125882   int orconf           /* ON CONFLICT algorithm. */
   125883 ){
   125884   Parse *pRoot = sqlite3ParseToplevel(pParse);
   125885   TriggerPrg *pPrg;
   125886 
   125887   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   125888 
   125889   /* It may be that this trigger has already been coded (or is in the
   125890   ** process of being coded). If this is the case, then an entry with
   125891   ** a matching TriggerPrg.pTrigger field will be present somewhere
   125892   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   125893   for(pPrg=pRoot->pTriggerPrg;
   125894       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
   125895       pPrg=pPrg->pNext
   125896   );
   125897 
   125898   /* If an existing TriggerPrg could not be located, create a new one. */
   125899   if( !pPrg ){
   125900     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   125901   }
   125902 
   125903   return pPrg;
   125904 }
   125905 
   125906 /*
   125907 ** Generate code for the trigger program associated with trigger p on
   125908 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
   125909 ** function are the same as those described in the header function for
   125910 ** sqlite3CodeRowTrigger()
   125911 */
   125912 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   125913   Parse *pParse,       /* Parse context */
   125914   Trigger *p,          /* Trigger to code */
   125915   Table *pTab,         /* The table to code triggers from */
   125916   int reg,             /* Reg array containing OLD.* and NEW.* values */
   125917   int orconf,          /* ON CONFLICT policy */
   125918   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   125919 ){
   125920   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   125921   TriggerPrg *pPrg;
   125922   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   125923   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   125924 
   125925   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   125926   ** is a pointer to the sub-vdbe containing the trigger program.  */
   125927   if( pPrg ){
   125928     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
   125929 
   125930     sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
   125931                       (const char *)pPrg->pProgram, P4_SUBPROGRAM);
   125932     VdbeComment(
   125933         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
   125934 
   125935     /* Set the P5 operand of the OP_Program instruction to non-zero if
   125936     ** recursive invocation of this trigger program is disallowed. Recursive
   125937     ** invocation is disallowed if (a) the sub-program is really a trigger,
   125938     ** not a foreign key action, and (b) the flag to enable recursive triggers
   125939     ** is clear.  */
   125940     sqlite3VdbeChangeP5(v, (u8)bRecursive);
   125941   }
   125942 }
   125943 
   125944 /*
   125945 ** This is called to code the required FOR EACH ROW triggers for an operation
   125946 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
   125947 ** is given by the op parameter. The tr_tm parameter determines whether the
   125948 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
   125949 ** parameter pChanges is passed the list of columns being modified.
   125950 **
   125951 ** If there are no triggers that fire at the specified time for the specified
   125952 ** operation on pTab, this function is a no-op.
   125953 **
   125954 ** The reg argument is the address of the first in an array of registers
   125955 ** that contain the values substituted for the new.* and old.* references
   125956 ** in the trigger program. If N is the number of columns in table pTab
   125957 ** (a copy of pTab->nCol), then registers are populated as follows:
   125958 **
   125959 **   Register       Contains
   125960 **   ------------------------------------------------------
   125961 **   reg+0          OLD.rowid
   125962 **   reg+1          OLD.* value of left-most column of pTab
   125963 **   ...            ...
   125964 **   reg+N          OLD.* value of right-most column of pTab
   125965 **   reg+N+1        NEW.rowid
   125966 **   reg+N+2        OLD.* value of left-most column of pTab
   125967 **   ...            ...
   125968 **   reg+N+N+1      NEW.* value of right-most column of pTab
   125969 **
   125970 ** For ON DELETE triggers, the registers containing the NEW.* values will
   125971 ** never be accessed by the trigger program, so they are not allocated or
   125972 ** populated by the caller (there is no data to populate them with anyway).
   125973 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
   125974 ** are never accessed, and so are not allocated by the caller. So, for an
   125975 ** ON INSERT trigger, the value passed to this function as parameter reg
   125976 ** is not a readable register, although registers (reg+N) through
   125977 ** (reg+N+N+1) are.
   125978 **
   125979 ** Parameter orconf is the default conflict resolution algorithm for the
   125980 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
   125981 ** is the instruction that control should jump to if a trigger program
   125982 ** raises an IGNORE exception.
   125983 */
   125984 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
   125985   Parse *pParse,       /* Parse context */
   125986   Trigger *pTrigger,   /* List of triggers on table pTab */
   125987   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   125988   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   125989   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   125990   Table *pTab,         /* The table to code triggers from */
   125991   int reg,             /* The first in an array of registers (see above) */
   125992   int orconf,          /* ON CONFLICT policy */
   125993   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   125994 ){
   125995   Trigger *p;          /* Used to iterate through pTrigger list */
   125996 
   125997   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
   125998   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
   125999   assert( (op==TK_UPDATE)==(pChanges!=0) );
   126000 
   126001   for(p=pTrigger; p; p=p->pNext){
   126002 
   126003     /* Sanity checking:  The schema for the trigger and for the table are
   126004     ** always defined.  The trigger must be in the same schema as the table
   126005     ** or else it must be a TEMP trigger. */
   126006     assert( p->pSchema!=0 );
   126007     assert( p->pTabSchema!=0 );
   126008     assert( p->pSchema==p->pTabSchema
   126009          || p->pSchema==pParse->db->aDb[1].pSchema );
   126010 
   126011     /* Determine whether we should code this trigger */
   126012     if( p->op==op
   126013      && p->tr_tm==tr_tm
   126014      && checkColumnOverlap(p->pColumns, pChanges)
   126015     ){
   126016       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
   126017     }
   126018   }
   126019 }
   126020 
   126021 /*
   126022 ** Triggers may access values stored in the old.* or new.* pseudo-table.
   126023 ** This function returns a 32-bit bitmask indicating which columns of the
   126024 ** old.* or new.* tables actually are used by triggers. This information
   126025 ** may be used by the caller, for example, to avoid having to load the entire
   126026 ** old.* record into memory when executing an UPDATE or DELETE command.
   126027 **
   126028 ** Bit 0 of the returned mask is set if the left-most column of the
   126029 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
   126030 ** the second leftmost column value is required, and so on. If there
   126031 ** are more than 32 columns in the table, and at least one of the columns
   126032 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
   126033 **
   126034 ** It is not possible to determine if the old.rowid or new.rowid column is
   126035 ** accessed by triggers. The caller must always assume that it is.
   126036 **
   126037 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
   126038 ** applies to the old.* table. If 1, the new.* table.
   126039 **
   126040 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
   126041 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
   126042 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
   126043 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
   126044 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
   126045 */
   126046 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
   126047   Parse *pParse,       /* Parse context */
   126048   Trigger *pTrigger,   /* List of triggers on table pTab */
   126049   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   126050   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
   126051   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   126052   Table *pTab,         /* The table to code triggers from */
   126053   int orconf           /* Default ON CONFLICT policy for trigger steps */
   126054 ){
   126055   const int op = pChanges ? TK_UPDATE : TK_DELETE;
   126056   u32 mask = 0;
   126057   Trigger *p;
   126058 
   126059   assert( isNew==1 || isNew==0 );
   126060   for(p=pTrigger; p; p=p->pNext){
   126061     if( p->op==op && (tr_tm&p->tr_tm)
   126062      && checkColumnOverlap(p->pColumns,pChanges)
   126063     ){
   126064       TriggerPrg *pPrg;
   126065       pPrg = getRowTrigger(pParse, p, pTab, orconf);
   126066       if( pPrg ){
   126067         mask |= pPrg->aColmask[isNew];
   126068       }
   126069     }
   126070   }
   126071 
   126072   return mask;
   126073 }
   126074 
   126075 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   126076 
   126077 /************** End of trigger.c *********************************************/
   126078 /************** Begin file update.c ******************************************/
   126079 /*
   126080 ** 2001 September 15
   126081 **
   126082 ** The author disclaims copyright to this source code.  In place of
   126083 ** a legal notice, here is a blessing:
   126084 **
   126085 **    May you do good and not evil.
   126086 **    May you find forgiveness for yourself and forgive others.
   126087 **    May you share freely, never taking more than you give.
   126088 **
   126089 *************************************************************************
   126090 ** This file contains C code routines that are called by the parser
   126091 ** to handle UPDATE statements.
   126092 */
   126093 /* #include "sqliteInt.h" */
   126094 
   126095 #ifndef SQLITE_OMIT_VIRTUALTABLE
   126096 /* Forward declaration */
   126097 static void updateVirtualTable(
   126098   Parse *pParse,       /* The parsing context */
   126099   SrcList *pSrc,       /* The virtual table to be modified */
   126100   Table *pTab,         /* The virtual table */
   126101   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   126102   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
   126103   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   126104   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   126105   int onError          /* ON CONFLICT strategy */
   126106 );
   126107 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   126108 
   126109 /*
   126110 ** The most recently coded instruction was an OP_Column to retrieve the
   126111 ** i-th column of table pTab. This routine sets the P4 parameter of the
   126112 ** OP_Column to the default value, if any.
   126113 **
   126114 ** The default value of a column is specified by a DEFAULT clause in the
   126115 ** column definition. This was either supplied by the user when the table
   126116 ** was created, or added later to the table definition by an ALTER TABLE
   126117 ** command. If the latter, then the row-records in the table btree on disk
   126118 ** may not contain a value for the column and the default value, taken
   126119 ** from the P4 parameter of the OP_Column instruction, is returned instead.
   126120 ** If the former, then all row-records are guaranteed to include a value
   126121 ** for the column and the P4 value is not required.
   126122 **
   126123 ** Column definitions created by an ALTER TABLE command may only have
   126124 ** literal default values specified: a number, null or a string. (If a more
   126125 ** complicated default expression value was provided, it is evaluated
   126126 ** when the ALTER TABLE is executed and one of the literal values written
   126127 ** into the sqlite_master table.)
   126128 **
   126129 ** Therefore, the P4 parameter is only required if the default value for
   126130 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
   126131 ** function is capable of transforming these types of expressions into
   126132 ** sqlite3_value objects.
   126133 **
   126134 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
   126135 ** on register iReg. This is used when an equivalent integer value is
   126136 ** stored in place of an 8-byte floating point value in order to save
   126137 ** space.
   126138 */
   126139 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   126140   assert( pTab!=0 );
   126141   if( !pTab->pSelect ){
   126142     sqlite3_value *pValue = 0;
   126143     u8 enc = ENC(sqlite3VdbeDb(v));
   126144     Column *pCol = &pTab->aCol[i];
   126145     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
   126146     assert( i<pTab->nCol );
   126147     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
   126148                          pCol->affinity, &pValue);
   126149     if( pValue ){
   126150       sqlite3VdbeAppendP4(v, pValue, P4_MEM);
   126151     }
   126152   }
   126153 #ifndef SQLITE_OMIT_FLOATING_POINT
   126154   if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
   126155     sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   126156   }
   126157 #endif
   126158 }
   126159 
   126160 /*
   126161 ** Process an UPDATE statement.
   126162 **
   126163 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
   126164 **          \_______/ \________/     \______/       \________________/
   126165 *            onError   pTabList      pChanges             pWhere
   126166 */
   126167 SQLITE_PRIVATE void sqlite3Update(
   126168   Parse *pParse,         /* The parser context */
   126169   SrcList *pTabList,     /* The table in which we should change things */
   126170   ExprList *pChanges,    /* Things to be changed */
   126171   Expr *pWhere,          /* The WHERE clause.  May be null */
   126172   int onError,           /* How to handle constraint errors */
   126173   ExprList *pOrderBy,    /* ORDER BY clause. May be null */
   126174   Expr *pLimit           /* LIMIT clause. May be null */
   126175 ){
   126176   int i, j;              /* Loop counters */
   126177   Table *pTab;           /* The table to be updated */
   126178   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
   126179   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   126180   Vdbe *v;               /* The virtual database engine */
   126181   Index *pIdx;           /* For looping over indices */
   126182   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
   126183   int nIdx;              /* Number of indices that need updating */
   126184   int iBaseCur;          /* Base cursor number */
   126185   int iDataCur;          /* Cursor for the canonical data btree */
   126186   int iIdxCur;           /* Cursor for the first index */
   126187   sqlite3 *db;           /* The database structure */
   126188   int *aRegIdx = 0;      /* First register in array assigned to each index */
   126189   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   126190                          ** an expression for the i-th column of the table.
   126191                          ** aXRef[i]==-1 if the i-th column is not changed. */
   126192   u8 *aToOpen;           /* 1 for tables and indices to be opened */
   126193   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
   126194   u8 chngRowid;          /* Rowid changed in a normal table */
   126195   u8 chngKey;            /* Either chngPk or chngRowid */
   126196   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   126197   AuthContext sContext;  /* The authorization context */
   126198   NameContext sNC;       /* The name-context to resolve expressions in */
   126199   int iDb;               /* Database containing the table being updated */
   126200   int eOnePass;          /* ONEPASS_XXX value from where.c */
   126201   int hasFK;             /* True if foreign key processing is required */
   126202   int labelBreak;        /* Jump here to break out of UPDATE loop */
   126203   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
   126204   int flags;             /* Flags for sqlite3WhereBegin() */
   126205 
   126206 #ifndef SQLITE_OMIT_TRIGGER
   126207   int isView;            /* True when updating a view (INSTEAD OF trigger) */
   126208   Trigger *pTrigger;     /* List of triggers on pTab, if required */
   126209   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   126210 #endif
   126211   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
   126212   int iEph = 0;          /* Ephemeral table holding all primary key values */
   126213   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
   126214   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
   126215   int addrOpen = 0;      /* Address of OP_OpenEphemeral */
   126216   int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
   126217   i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
   126218   int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
   126219 
   126220   /* Register Allocations */
   126221   int regRowCount = 0;   /* A count of rows changed */
   126222   int regOldRowid = 0;   /* The old rowid */
   126223   int regNewRowid = 0;   /* The new rowid */
   126224   int regNew = 0;        /* Content of the NEW.* table in triggers */
   126225   int regOld = 0;        /* Content of OLD.* table in triggers */
   126226   int regRowSet = 0;     /* Rowset of rows to be updated */
   126227   int regKey = 0;        /* composite PRIMARY KEY value */
   126228 
   126229   memset(&sContext, 0, sizeof(sContext));
   126230   db = pParse->db;
   126231   if( pParse->nErr || db->mallocFailed ){
   126232     goto update_cleanup;
   126233   }
   126234   assert( pTabList->nSrc==1 );
   126235 
   126236   /* Locate the table which we want to update.
   126237   */
   126238   pTab = sqlite3SrcListLookup(pParse, pTabList);
   126239   if( pTab==0 ) goto update_cleanup;
   126240   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   126241 
   126242   /* Figure out if we have any triggers and if the table being
   126243   ** updated is a view.
   126244   */
   126245 #ifndef SQLITE_OMIT_TRIGGER
   126246   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
   126247   isView = pTab->pSelect!=0;
   126248   assert( pTrigger || tmask==0 );
   126249 #else
   126250 # define pTrigger 0
   126251 # define isView 0
   126252 # define tmask 0
   126253 #endif
   126254 #ifdef SQLITE_OMIT_VIEW
   126255 # undef isView
   126256 # define isView 0
   126257 #endif
   126258 
   126259 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
   126260   if( !isView ){
   126261     pWhere = sqlite3LimitWhere(
   126262         pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
   126263     );
   126264     pOrderBy = 0;
   126265     pLimit = 0;
   126266   }
   126267 #endif
   126268 
   126269   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   126270     goto update_cleanup;
   126271   }
   126272   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   126273     goto update_cleanup;
   126274   }
   126275 
   126276   /* Allocate a cursors for the main database table and for all indices.
   126277   ** The index cursors might not be used, but if they are used they
   126278   ** need to occur right after the database cursor.  So go ahead and
   126279   ** allocate enough space, just in case.
   126280   */
   126281   pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
   126282   iIdxCur = iDataCur+1;
   126283   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
   126284   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
   126285     if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
   126286       iDataCur = pParse->nTab;
   126287       pTabList->a[0].iCursor = iDataCur;
   126288     }
   126289     pParse->nTab++;
   126290   }
   126291 
   126292   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
   126293   ** Initialize aXRef[] and aToOpen[] to their default values.
   126294   */
   126295   aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
   126296   if( aXRef==0 ) goto update_cleanup;
   126297   aRegIdx = aXRef+pTab->nCol;
   126298   aToOpen = (u8*)(aRegIdx+nIdx);
   126299   memset(aToOpen, 1, nIdx+1);
   126300   aToOpen[nIdx+1] = 0;
   126301   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   126302 
   126303   /* Initialize the name-context */
   126304   memset(&sNC, 0, sizeof(sNC));
   126305   sNC.pParse = pParse;
   126306   sNC.pSrcList = pTabList;
   126307 
   126308   /* Resolve the column names in all the expressions of the
   126309   ** of the UPDATE statement.  Also find the column index
   126310   ** for each column to be updated in the pChanges array.  For each
   126311   ** column to be updated, make sure we have authorization to change
   126312   ** that column.
   126313   */
   126314   chngRowid = chngPk = 0;
   126315   for(i=0; i<pChanges->nExpr; i++){
   126316     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   126317       goto update_cleanup;
   126318     }
   126319     for(j=0; j<pTab->nCol; j++){
   126320       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   126321         if( j==pTab->iPKey ){
   126322           chngRowid = 1;
   126323           pRowidExpr = pChanges->a[i].pExpr;
   126324         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
   126325           chngPk = 1;
   126326         }
   126327         aXRef[j] = i;
   126328         break;
   126329       }
   126330     }
   126331     if( j>=pTab->nCol ){
   126332       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
   126333         j = -1;
   126334         chngRowid = 1;
   126335         pRowidExpr = pChanges->a[i].pExpr;
   126336       }else{
   126337         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   126338         pParse->checkSchema = 1;
   126339         goto update_cleanup;
   126340       }
   126341     }
   126342 #ifndef SQLITE_OMIT_AUTHORIZATION
   126343     {
   126344       int rc;
   126345       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   126346                             j<0 ? "ROWID" : pTab->aCol[j].zName,
   126347                             db->aDb[iDb].zDbSName);
   126348       if( rc==SQLITE_DENY ){
   126349         goto update_cleanup;
   126350       }else if( rc==SQLITE_IGNORE ){
   126351         aXRef[j] = -1;
   126352       }
   126353     }
   126354 #endif
   126355   }
   126356   assert( (chngRowid & chngPk)==0 );
   126357   assert( chngRowid==0 || chngRowid==1 );
   126358   assert( chngPk==0 || chngPk==1 );
   126359   chngKey = chngRowid + chngPk;
   126360 
   126361   /* The SET expressions are not actually used inside the WHERE loop.
   126362   ** So reset the colUsed mask. Unless this is a virtual table. In that
   126363   ** case, set all bits of the colUsed mask (to ensure that the virtual
   126364   ** table implementation makes all columns available).
   126365   */
   126366   pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
   126367 
   126368   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
   126369 
   126370   /* There is one entry in the aRegIdx[] array for each index on the table
   126371   ** being updated.  Fill in aRegIdx[] with a register number that will hold
   126372   ** the key for accessing each index.
   126373   **
   126374   ** FIXME:  Be smarter about omitting indexes that use expressions.
   126375   */
   126376   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   126377     int reg;
   126378     if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
   126379       reg = ++pParse->nMem;
   126380       pParse->nMem += pIdx->nColumn;
   126381     }else{
   126382       reg = 0;
   126383       for(i=0; i<pIdx->nKeyCol; i++){
   126384         i16 iIdxCol = pIdx->aiColumn[i];
   126385         if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
   126386           reg = ++pParse->nMem;
   126387           pParse->nMem += pIdx->nColumn;
   126388           if( (onError==OE_Replace)
   126389            || (onError==OE_Default && pIdx->onError==OE_Replace)
   126390           ){
   126391             bReplace = 1;
   126392           }
   126393           break;
   126394         }
   126395       }
   126396     }
   126397     if( reg==0 ) aToOpen[j+1] = 0;
   126398     aRegIdx[j] = reg;
   126399   }
   126400   if( bReplace ){
   126401     /* If REPLACE conflict resolution might be invoked, open cursors on all
   126402     ** indexes in case they are needed to delete records.  */
   126403     memset(aToOpen, 1, nIdx+1);
   126404   }
   126405 
   126406   /* Begin generating code. */
   126407   v = sqlite3GetVdbe(pParse);
   126408   if( v==0 ) goto update_cleanup;
   126409   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   126410   sqlite3BeginWriteOperation(pParse, 1, iDb);
   126411 
   126412   /* Allocate required registers. */
   126413   if( !IsVirtual(pTab) ){
   126414     regRowSet = ++pParse->nMem;
   126415     regOldRowid = regNewRowid = ++pParse->nMem;
   126416     if( chngPk || pTrigger || hasFK ){
   126417       regOld = pParse->nMem + 1;
   126418       pParse->nMem += pTab->nCol;
   126419     }
   126420     if( chngKey || pTrigger || hasFK ){
   126421       regNewRowid = ++pParse->nMem;
   126422     }
   126423     regNew = pParse->nMem + 1;
   126424     pParse->nMem += pTab->nCol;
   126425   }
   126426 
   126427   /* Start the view context. */
   126428   if( isView ){
   126429     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   126430   }
   126431 
   126432   /* If we are trying to update a view, realize that view into
   126433   ** an ephemeral table.
   126434   */
   126435 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   126436   if( isView ){
   126437     sqlite3MaterializeView(pParse, pTab,
   126438         pWhere, pOrderBy, pLimit, iDataCur
   126439     );
   126440     pOrderBy = 0;
   126441     pLimit = 0;
   126442   }
   126443 #endif
   126444 
   126445   /* Resolve the column names in all the expressions in the
   126446   ** WHERE clause.
   126447   */
   126448   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   126449     goto update_cleanup;
   126450   }
   126451 
   126452 #ifndef SQLITE_OMIT_VIRTUALTABLE
   126453   /* Virtual tables must be handled separately */
   126454   if( IsVirtual(pTab) ){
   126455     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
   126456                        pWhere, onError);
   126457     goto update_cleanup;
   126458   }
   126459 #endif
   126460 
   126461   /* Initialize the count of updated rows */
   126462   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   126463     regRowCount = ++pParse->nMem;
   126464     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   126465   }
   126466 
   126467   if( HasRowid(pTab) ){
   126468     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
   126469   }else{
   126470     assert( pPk!=0 );
   126471     nPk = pPk->nKeyCol;
   126472     iPk = pParse->nMem+1;
   126473     pParse->nMem += nPk;
   126474     regKey = ++pParse->nMem;
   126475     iEph = pParse->nTab++;
   126476 
   126477     sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
   126478     addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
   126479     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   126480   }
   126481 
   126482   /* Begin the database scan.
   126483   **
   126484   ** Do not consider a single-pass strategy for a multi-row update if
   126485   ** there are any triggers or foreign keys to process, or rows may
   126486   ** be deleted as a result of REPLACE conflict handling. Any of these
   126487   ** things might disturb a cursor being used to scan through the table
   126488   ** or index, causing a single-pass approach to malfunction.  */
   126489   flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
   126490   if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
   126491     flags |= WHERE_ONEPASS_MULTIROW;
   126492   }
   126493   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
   126494   if( pWInfo==0 ) goto update_cleanup;
   126495 
   126496   /* A one-pass strategy that might update more than one row may not
   126497   ** be used if any column of the index used for the scan is being
   126498   ** updated. Otherwise, if there is an index on "b", statements like
   126499   ** the following could create an infinite loop:
   126500   **
   126501   **   UPDATE t1 SET b=b+1 WHERE b>?
   126502   **
   126503   ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
   126504   ** strategy that uses an index for which one or more columns are being
   126505   ** updated.  */
   126506   eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
   126507   if( eOnePass==ONEPASS_MULTI ){
   126508     int iCur = aiCurOnePass[1];
   126509     if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
   126510       eOnePass = ONEPASS_OFF;
   126511     }
   126512     assert( iCur!=iDataCur || !HasRowid(pTab) );
   126513   }
   126514 
   126515   if( HasRowid(pTab) ){
   126516     /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
   126517     ** mode, write the rowid into the FIFO. In either of the one-pass modes,
   126518     ** leave it in register regOldRowid.  */
   126519     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
   126520     if( eOnePass==ONEPASS_OFF ){
   126521       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   126522     }
   126523   }else{
   126524     /* Read the PK of the current row into an array of registers. In
   126525     ** ONEPASS_OFF mode, serialize the array into a record and store it in
   126526     ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
   126527     ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
   126528     ** is not required) and leave the PK fields in the array of registers.  */
   126529     for(i=0; i<nPk; i++){
   126530       assert( pPk->aiColumn[i]>=0 );
   126531       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
   126532     }
   126533     if( eOnePass ){
   126534       sqlite3VdbeChangeToNoop(v, addrOpen);
   126535       nKey = nPk;
   126536       regKey = iPk;
   126537     }else{
   126538       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
   126539                         sqlite3IndexAffinityStr(db, pPk), nPk);
   126540       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
   126541     }
   126542   }
   126543 
   126544   if( eOnePass!=ONEPASS_MULTI ){
   126545     sqlite3WhereEnd(pWInfo);
   126546   }
   126547 
   126548   labelBreak = sqlite3VdbeMakeLabel(v);
   126549   if( !isView ){
   126550     int addrOnce = 0;
   126551 
   126552     /* Open every index that needs updating. */
   126553     if( eOnePass!=ONEPASS_OFF ){
   126554       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
   126555       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
   126556     }
   126557 
   126558     if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
   126559       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   126560     }
   126561     sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
   126562                                0, 0);
   126563     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
   126564   }
   126565 
   126566   /* Top of the update loop */
   126567   if( eOnePass!=ONEPASS_OFF ){
   126568     if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
   126569       assert( pPk );
   126570       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
   126571       VdbeCoverageNeverTaken(v);
   126572     }
   126573     if( eOnePass==ONEPASS_SINGLE ){
   126574       labelContinue = labelBreak;
   126575     }else{
   126576       labelContinue = sqlite3VdbeMakeLabel(v);
   126577     }
   126578     sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
   126579     VdbeCoverageIf(v, pPk==0);
   126580     VdbeCoverageIf(v, pPk!=0);
   126581   }else if( pPk ){
   126582     labelContinue = sqlite3VdbeMakeLabel(v);
   126583     sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
   126584     addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
   126585     sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
   126586     VdbeCoverage(v);
   126587   }else{
   126588     labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
   126589                              regOldRowid);
   126590     VdbeCoverage(v);
   126591     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
   126592     VdbeCoverage(v);
   126593   }
   126594 
   126595   /* If the record number will change, set register regNewRowid to
   126596   ** contain the new value. If the record number is not being modified,
   126597   ** then regNewRowid is the same register as regOldRowid, which is
   126598   ** already populated.  */
   126599   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
   126600   if( chngRowid ){
   126601     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   126602     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
   126603   }
   126604 
   126605   /* Compute the old pre-UPDATE content of the row being changed, if that
   126606   ** information is needed */
   126607   if( chngPk || hasFK || pTrigger ){
   126608     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   126609     oldmask |= sqlite3TriggerColmask(pParse,
   126610         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   126611     );
   126612     for(i=0; i<pTab->nCol; i++){
   126613       if( oldmask==0xffffffff
   126614        || (i<32 && (oldmask & MASKBIT32(i))!=0)
   126615        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
   126616       ){
   126617         testcase(  oldmask!=0xffffffff && i==31 );
   126618         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
   126619       }else{
   126620         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   126621       }
   126622     }
   126623     if( chngRowid==0 && pPk==0 ){
   126624       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   126625     }
   126626   }
   126627 
   126628   /* Populate the array of registers beginning at regNew with the new
   126629   ** row data. This array is used to check constants, create the new
   126630   ** table and index records, and as the values for any new.* references
   126631   ** made by triggers.
   126632   **
   126633   ** If there are one or more BEFORE triggers, then do not populate the
   126634   ** registers associated with columns that are (a) not modified by
   126635   ** this UPDATE statement and (b) not accessed by new.* references. The
   126636   ** values for registers not modified by the UPDATE must be reloaded from
   126637   ** the database after the BEFORE triggers are fired anyway (as the trigger
   126638   ** may have modified them). So not loading those that are not going to
   126639   ** be used eliminates some redundant opcodes.
   126640   */
   126641   newmask = sqlite3TriggerColmask(
   126642       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   126643   );
   126644   for(i=0; i<pTab->nCol; i++){
   126645     if( i==pTab->iPKey ){
   126646       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   126647     }else{
   126648       j = aXRef[i];
   126649       if( j>=0 ){
   126650         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   126651       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
   126652         /* This branch loads the value of a column that will not be changed
   126653         ** into a register. This is done if there are no BEFORE triggers, or
   126654         ** if there are one or more BEFORE triggers that use this value via
   126655         ** a new.* reference in a trigger program.
   126656         */
   126657         testcase( i==31 );
   126658         testcase( i==32 );
   126659         sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
   126660       }else{
   126661         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   126662       }
   126663     }
   126664   }
   126665 
   126666   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   126667   ** verified. One could argue that this is wrong.
   126668   */
   126669   if( tmask&TRIGGER_BEFORE ){
   126670     sqlite3TableAffinity(v, pTab, regNew);
   126671     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   126672         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
   126673 
   126674     /* The row-trigger may have deleted the row being updated. In this
   126675     ** case, jump to the next row. No updates or AFTER triggers are
   126676     ** required. This behavior - what happens when the row being updated
   126677     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   126678     ** documentation.
   126679     */
   126680     if( pPk ){
   126681       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
   126682       VdbeCoverage(v);
   126683     }else{
   126684       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
   126685       VdbeCoverage(v);
   126686     }
   126687 
   126688     /* If it did not delete it, the row-trigger may still have modified
   126689     ** some of the columns of the row being updated. Load the values for
   126690     ** all columns not modified by the update statement into their
   126691     ** registers in case this has happened.
   126692     */
   126693     for(i=0; i<pTab->nCol; i++){
   126694       if( aXRef[i]<0 && i!=pTab->iPKey ){
   126695         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
   126696       }
   126697     }
   126698   }
   126699 
   126700   if( !isView ){
   126701     int addr1 = 0;        /* Address of jump instruction */
   126702 
   126703     /* Do constraint checks. */
   126704     assert( regOldRowid>0 );
   126705     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
   126706         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
   126707         aXRef);
   126708 
   126709     /* Do FK constraint checks. */
   126710     if( hasFK ){
   126711       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
   126712     }
   126713 
   126714     /* Delete the index entries associated with the current record.  */
   126715     if( bReplace || chngKey ){
   126716       if( pPk ){
   126717         addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
   126718       }else{
   126719         addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
   126720       }
   126721       VdbeCoverageNeverTaken(v);
   126722     }
   126723     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
   126724 
   126725     /* If changing the rowid value, or if there are foreign key constraints
   126726     ** to process, delete the old record. Otherwise, add a noop OP_Delete
   126727     ** to invoke the pre-update hook.
   126728     **
   126729     ** That (regNew==regnewRowid+1) is true is also important for the
   126730     ** pre-update hook. If the caller invokes preupdate_new(), the returned
   126731     ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
   126732     ** is the column index supplied by the user.
   126733     */
   126734     assert( regNew==regNewRowid+1 );
   126735 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   126736     sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
   126737         OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
   126738         regNewRowid
   126739     );
   126740     if( eOnePass==ONEPASS_MULTI ){
   126741       assert( hasFK==0 && chngKey==0 );
   126742       sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
   126743     }
   126744     if( !pParse->nested ){
   126745       sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
   126746     }
   126747 #else
   126748     if( hasFK>1 || chngKey ){
   126749       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
   126750     }
   126751 #endif
   126752     if( bReplace || chngKey ){
   126753       sqlite3VdbeJumpHere(v, addr1);
   126754     }
   126755 
   126756     if( hasFK ){
   126757       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
   126758     }
   126759 
   126760     /* Insert the new index entries and the new record. */
   126761     sqlite3CompleteInsertion(
   126762         pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
   126763         OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
   126764         0, 0
   126765     );
   126766 
   126767     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   126768     ** handle rows (possibly in other tables) that refer via a foreign key
   126769     ** to the row just updated. */
   126770     if( hasFK ){
   126771       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
   126772     }
   126773   }
   126774 
   126775   /* Increment the row counter
   126776   */
   126777   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   126778     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   126779   }
   126780 
   126781   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   126782       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
   126783 
   126784   /* Repeat the above with the next record to be updated, until
   126785   ** all record selected by the WHERE clause have been updated.
   126786   */
   126787   if( eOnePass==ONEPASS_SINGLE ){
   126788     /* Nothing to do at end-of-loop for a single-pass */
   126789   }else if( eOnePass==ONEPASS_MULTI ){
   126790     sqlite3VdbeResolveLabel(v, labelContinue);
   126791     sqlite3WhereEnd(pWInfo);
   126792   }else if( pPk ){
   126793     sqlite3VdbeResolveLabel(v, labelContinue);
   126794     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
   126795   }else{
   126796     sqlite3VdbeGoto(v, labelContinue);
   126797   }
   126798   sqlite3VdbeResolveLabel(v, labelBreak);
   126799 
   126800   /* Update the sqlite_sequence table by storing the content of the
   126801   ** maximum rowid counter values recorded while inserting into
   126802   ** autoincrement tables.
   126803   */
   126804   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   126805     sqlite3AutoincrementEnd(pParse);
   126806   }
   126807 
   126808   /*
   126809   ** Return the number of rows that were changed. If this routine is
   126810   ** generating code because of a call to sqlite3NestedParse(), do not
   126811   ** invoke the callback function.
   126812   */
   126813   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   126814     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   126815     sqlite3VdbeSetNumCols(v, 1);
   126816     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   126817   }
   126818 
   126819 update_cleanup:
   126820   sqlite3AuthContextPop(&sContext);
   126821   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
   126822   sqlite3SrcListDelete(db, pTabList);
   126823   sqlite3ExprListDelete(db, pChanges);
   126824   sqlite3ExprDelete(db, pWhere);
   126825 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
   126826   sqlite3ExprListDelete(db, pOrderBy);
   126827   sqlite3ExprDelete(db, pLimit);
   126828 #endif
   126829   return;
   126830 }
   126831 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   126832 ** they may interfere with compilation of other functions in this file
   126833 ** (or in another file, if this file becomes part of the amalgamation).  */
   126834 #ifdef isView
   126835  #undef isView
   126836 #endif
   126837 #ifdef pTrigger
   126838  #undef pTrigger
   126839 #endif
   126840 
   126841 #ifndef SQLITE_OMIT_VIRTUALTABLE
   126842 /*
   126843 ** Generate code for an UPDATE of a virtual table.
   126844 **
   126845 ** There are two possible strategies - the default and the special
   126846 ** "onepass" strategy. Onepass is only used if the virtual table
   126847 ** implementation indicates that pWhere may match at most one row.
   126848 **
   126849 ** The default strategy is to create an ephemeral table that contains
   126850 ** for each row to be changed:
   126851 **
   126852 **   (A)  The original rowid of that row.
   126853 **   (B)  The revised rowid for the row.
   126854 **   (C)  The content of every column in the row.
   126855 **
   126856 ** Then loop through the contents of this ephemeral table executing a
   126857 ** VUpdate for each row. When finished, drop the ephemeral table.
   126858 **
   126859 ** The "onepass" strategy does not use an ephemeral table. Instead, it
   126860 ** stores the same values (A, B and C above) in a register array and
   126861 ** makes a single invocation of VUpdate.
   126862 */
   126863 static void updateVirtualTable(
   126864   Parse *pParse,       /* The parsing context */
   126865   SrcList *pSrc,       /* The virtual table to be modified */
   126866   Table *pTab,         /* The virtual table */
   126867   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   126868   Expr *pRowid,        /* Expression used to recompute the rowid */
   126869   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   126870   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   126871   int onError          /* ON CONFLICT strategy */
   126872 ){
   126873   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
   126874   int ephemTab;             /* Table holding the result of the SELECT */
   126875   int i;                    /* Loop counter */
   126876   sqlite3 *db = pParse->db; /* Database connection */
   126877   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
   126878   WhereInfo *pWInfo;
   126879   int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
   126880   int regArg;                     /* First register in VUpdate arg array */
   126881   int regRec;                     /* Register in which to assemble record */
   126882   int regRowid;                   /* Register for ephem table rowid */
   126883   int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
   126884   int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
   126885   int bOnePass;                   /* True to use onepass strategy */
   126886   int addr;                       /* Address of OP_OpenEphemeral */
   126887 
   126888   /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
   126889   ** create and open the ephemeral table in which the records created from
   126890   ** these arguments will be temporarily stored. */
   126891   assert( v );
   126892   ephemTab = pParse->nTab++;
   126893   addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
   126894   regArg = pParse->nMem + 1;
   126895   pParse->nMem += nArg;
   126896   regRec = ++pParse->nMem;
   126897   regRowid = ++pParse->nMem;
   126898 
   126899   /* Start scanning the virtual table */
   126900   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
   126901   if( pWInfo==0 ) return;
   126902 
   126903   /* Populate the argument registers. */
   126904   for(i=0; i<pTab->nCol; i++){
   126905     if( aXRef[i]>=0 ){
   126906       sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
   126907     }else{
   126908       sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
   126909       sqlite3VdbeChangeP5(v, 1); /* Enable sqlite3_vtab_nochange() */
   126910     }
   126911   }
   126912   if( HasRowid(pTab) ){
   126913     sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
   126914     if( pRowid ){
   126915       sqlite3ExprCode(pParse, pRowid, regArg+1);
   126916     }else{
   126917       sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
   126918     }
   126919   }else{
   126920     Index *pPk;   /* PRIMARY KEY index */
   126921     i16 iPk;      /* PRIMARY KEY column */
   126922     pPk = sqlite3PrimaryKeyIndex(pTab);
   126923     assert( pPk!=0 );
   126924     assert( pPk->nKeyCol==1 );
   126925     iPk = pPk->aiColumn[0];
   126926     sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
   126927     sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
   126928   }
   126929 
   126930   bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
   126931 
   126932   if( bOnePass ){
   126933     /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
   126934     ** above. Also, if this is a top-level parse (not a trigger), clear the
   126935     ** multi-write flag so that the VM does not open a statement journal */
   126936     sqlite3VdbeChangeToNoop(v, addr);
   126937     if( sqlite3IsToplevel(pParse) ){
   126938       pParse->isMultiWrite = 0;
   126939     }
   126940   }else{
   126941     /* Create a record from the argument register contents and insert it into
   126942     ** the ephemeral table. */
   126943     sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
   126944 #ifdef SQLITE_DEBUG
   126945     /* Signal an assert() within OP_MakeRecord that it is allowed to
   126946     ** accept no-change records with serial_type 10 */
   126947     sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
   126948 #endif
   126949     sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
   126950     sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
   126951   }
   126952 
   126953 
   126954   if( bOnePass==0 ){
   126955     /* End the virtual table scan */
   126956     sqlite3WhereEnd(pWInfo);
   126957 
   126958     /* Begin scannning through the ephemeral table. */
   126959     addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
   126960 
   126961     /* Extract arguments from the current row of the ephemeral table and
   126962     ** invoke the VUpdate method.  */
   126963     for(i=0; i<nArg; i++){
   126964       sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
   126965     }
   126966   }
   126967   sqlite3VtabMakeWritable(pParse, pTab);
   126968   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
   126969   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   126970   sqlite3MayAbort(pParse);
   126971 
   126972   /* End of the ephemeral table scan. Or, if using the onepass strategy,
   126973   ** jump to here if the scan visited zero rows. */
   126974   if( bOnePass==0 ){
   126975     sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
   126976     sqlite3VdbeJumpHere(v, addr);
   126977     sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   126978   }else{
   126979     sqlite3WhereEnd(pWInfo);
   126980   }
   126981 }
   126982 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   126983 
   126984 /************** End of update.c **********************************************/
   126985 /************** Begin file vacuum.c ******************************************/
   126986 /*
   126987 ** 2003 April 6
   126988 **
   126989 ** The author disclaims copyright to this source code.  In place of
   126990 ** a legal notice, here is a blessing:
   126991 **
   126992 **    May you do good and not evil.
   126993 **    May you find forgiveness for yourself and forgive others.
   126994 **    May you share freely, never taking more than you give.
   126995 **
   126996 *************************************************************************
   126997 ** This file contains code used to implement the VACUUM command.
   126998 **
   126999 ** Most of the code in this file may be omitted by defining the
   127000 ** SQLITE_OMIT_VACUUM macro.
   127001 */
   127002 /* #include "sqliteInt.h" */
   127003 /* #include "vdbeInt.h" */
   127004 
   127005 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   127006 
   127007 /*
   127008 ** Execute zSql on database db.
   127009 **
   127010 ** If zSql returns rows, then each row will have exactly one
   127011 ** column.  (This will only happen if zSql begins with "SELECT".)
   127012 ** Take each row of result and call execSql() again recursively.
   127013 **
   127014 ** The execSqlF() routine does the same thing, except it accepts
   127015 ** a format string as its third argument
   127016 */
   127017 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   127018   sqlite3_stmt *pStmt;
   127019   int rc;
   127020 
   127021   /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
   127022   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   127023   if( rc!=SQLITE_OK ) return rc;
   127024   while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   127025     const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
   127026     assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
   127027     if( zSubSql ){
   127028       assert( zSubSql[0]!='S' );
   127029       rc = execSql(db, pzErrMsg, zSubSql);
   127030       if( rc!=SQLITE_OK ) break;
   127031     }
   127032   }
   127033   assert( rc!=SQLITE_ROW );
   127034   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   127035   if( rc ){
   127036     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   127037   }
   127038   (void)sqlite3_finalize(pStmt);
   127039   return rc;
   127040 }
   127041 static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
   127042   char *z;
   127043   va_list ap;
   127044   int rc;
   127045   va_start(ap, zSql);
   127046   z = sqlite3VMPrintf(db, zSql, ap);
   127047   va_end(ap);
   127048   if( z==0 ) return SQLITE_NOMEM;
   127049   rc = execSql(db, pzErrMsg, z);
   127050   sqlite3DbFree(db, z);
   127051   return rc;
   127052 }
   127053 
   127054 /*
   127055 ** The VACUUM command is used to clean up the database,
   127056 ** collapse free space, etc.  It is modelled after the VACUUM command
   127057 ** in PostgreSQL.  The VACUUM command works as follows:
   127058 **
   127059 **   (1)  Create a new transient database file
   127060 **   (2)  Copy all content from the database being vacuumed into
   127061 **        the new transient database file
   127062 **   (3)  Copy content from the transient database back into the
   127063 **        original database.
   127064 **
   127065 ** The transient database requires temporary disk space approximately
   127066 ** equal to the size of the original database.  The copy operation of
   127067 ** step (3) requires additional temporary disk space approximately equal
   127068 ** to the size of the original database for the rollback journal.
   127069 ** Hence, temporary disk space that is approximately 2x the size of the
   127070 ** original database is required.  Every page of the database is written
   127071 ** approximately 3 times:  Once for step (2) and twice for step (3).
   127072 ** Two writes per page are required in step (3) because the original
   127073 ** database content must be written into the rollback journal prior to
   127074 ** overwriting the database with the vacuumed content.
   127075 **
   127076 ** Only 1x temporary space and only 1x writes would be required if
   127077 ** the copy of step (3) were replaced by deleting the original database
   127078 ** and renaming the transient database as the original.  But that will
   127079 ** not work if other processes are attached to the original database.
   127080 ** And a power loss in between deleting the original and renaming the
   127081 ** transient would cause the database file to appear to be deleted
   127082 ** following reboot.
   127083 */
   127084 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
   127085   Vdbe *v = sqlite3GetVdbe(pParse);
   127086   int iDb = 0;
   127087   if( v==0 ) return;
   127088   if( pNm ){
   127089 #ifndef SQLITE_BUG_COMPATIBLE_20160819
   127090     /* Default behavior:  Report an error if the argument to VACUUM is
   127091     ** not recognized */
   127092     iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
   127093     if( iDb<0 ) return;
   127094 #else
   127095     /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
   127096     ** to VACUUM are silently ignored.  This is a back-out of a bug fix that
   127097     ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
   127098     ** The buggy behavior is required for binary compatibility with some
   127099     ** legacy applications. */
   127100     iDb = sqlite3FindDb(pParse->db, pNm);
   127101     if( iDb<0 ) iDb = 0;
   127102 #endif
   127103   }
   127104   if( iDb!=1 ){
   127105     sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
   127106     sqlite3VdbeUsesBtree(v, iDb);
   127107   }
   127108   return;
   127109 }
   127110 
   127111 /*
   127112 ** This routine implements the OP_Vacuum opcode of the VDBE.
   127113 */
   127114 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
   127115   int rc = SQLITE_OK;     /* Return code from service routines */
   127116   Btree *pMain;           /* The database being vacuumed */
   127117   Btree *pTemp;           /* The temporary database we vacuum into */
   127118   u16 saved_mDbFlags;     /* Saved value of db->mDbFlags */
   127119   u32 saved_flags;        /* Saved value of db->flags */
   127120   int saved_nChange;      /* Saved value of db->nChange */
   127121   int saved_nTotalChange; /* Saved value of db->nTotalChange */
   127122   u8 saved_mTrace;        /* Saved trace settings */
   127123   Db *pDb = 0;            /* Database to detach at end of vacuum */
   127124   int isMemDb;            /* True if vacuuming a :memory: database */
   127125   int nRes;               /* Bytes of reserved space at the end of each page */
   127126   int nDb;                /* Number of attached databases */
   127127   const char *zDbMain;    /* Schema name of database to vacuum */
   127128 
   127129   if( !db->autoCommit ){
   127130     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   127131     return SQLITE_ERROR;
   127132   }
   127133   if( db->nVdbeActive>1 ){
   127134     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
   127135     return SQLITE_ERROR;
   127136   }
   127137 
   127138   /* Save the current value of the database flags so that it can be
   127139   ** restored before returning. Then set the writable-schema flag, and
   127140   ** disable CHECK and foreign key constraints.  */
   127141   saved_flags = db->flags;
   127142   saved_mDbFlags = db->mDbFlags;
   127143   saved_nChange = db->nChange;
   127144   saved_nTotalChange = db->nTotalChange;
   127145   saved_mTrace = db->mTrace;
   127146   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
   127147   db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
   127148   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
   127149   db->mTrace = 0;
   127150 
   127151   zDbMain = db->aDb[iDb].zDbSName;
   127152   pMain = db->aDb[iDb].pBt;
   127153   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   127154 
   127155   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   127156   ** can be set to 'off' for this file, as it is not recovered if a crash
   127157   ** occurs anyway. The integrity of the database is maintained by a
   127158   ** (possibly synchronous) transaction opened on the main database before
   127159   ** sqlite3BtreeCopyFile() is called.
   127160   **
   127161   ** An optimisation would be to use a non-journaled pager.
   127162   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
   127163   ** that actually made the VACUUM run slower.  Very little journalling
   127164   ** actually occurs when doing a vacuum since the vacuum_db is initially
   127165   ** empty.  Only the journal header is written.  Apparently it takes more
   127166   ** time to parse and run the PRAGMA to turn journalling off than it does
   127167   ** to write the journal header file.
   127168   */
   127169   nDb = db->nDb;
   127170   rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
   127171   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127172   assert( (db->nDb-1)==nDb );
   127173   pDb = &db->aDb[nDb];
   127174   assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
   127175   pTemp = pDb->pBt;
   127176 
   127177   /* The call to execSql() to attach the temp database has left the file
   127178   ** locked (as there was more than one active statement when the transaction
   127179   ** to read the schema was concluded. Unlock it here so that this doesn't
   127180   ** cause problems for the call to BtreeSetPageSize() below.  */
   127181   sqlite3BtreeCommit(pTemp);
   127182 
   127183   nRes = sqlite3BtreeGetOptimalReserve(pMain);
   127184 
   127185   /* A VACUUM cannot change the pagesize of an encrypted database. */
   127186 #ifdef SQLITE_HAS_CODEC
   127187   if( db->nextPagesize ){
   127188     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   127189     int nKey;
   127190     char *zKey;
   127191     sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
   127192     if( nKey ) db->nextPagesize = 0;
   127193   }
   127194 #endif
   127195 
   127196   sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
   127197   sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
   127198   sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
   127199 
   127200   /* Begin a transaction and take an exclusive lock on the main database
   127201   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
   127202   ** to ensure that we do not try to change the page-size on a WAL database.
   127203   */
   127204   rc = execSql(db, pzErrMsg, "BEGIN");
   127205   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127206   rc = sqlite3BtreeBeginTrans(pMain, 2);
   127207   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127208 
   127209   /* Do not attempt to change the page size for a WAL database */
   127210   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
   127211                                                ==PAGER_JOURNALMODE_WAL ){
   127212     db->nextPagesize = 0;
   127213   }
   127214 
   127215   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   127216    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   127217    || NEVER(db->mallocFailed)
   127218   ){
   127219     rc = SQLITE_NOMEM_BKPT;
   127220     goto end_of_vacuum;
   127221   }
   127222 
   127223 #ifndef SQLITE_OMIT_AUTOVACUUM
   127224   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   127225                                            sqlite3BtreeGetAutoVacuum(pMain));
   127226 #endif
   127227 
   127228   /* Query the schema of the main database. Create a mirror schema
   127229   ** in the temporary database.
   127230   */
   127231   db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
   127232   rc = execSqlF(db, pzErrMsg,
   127233       "SELECT sql FROM \"%w\".sqlite_master"
   127234       " WHERE type='table'AND name<>'sqlite_sequence'"
   127235       " AND coalesce(rootpage,1)>0",
   127236       zDbMain
   127237   );
   127238   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127239   rc = execSqlF(db, pzErrMsg,
   127240       "SELECT sql FROM \"%w\".sqlite_master"
   127241       " WHERE type='index' AND length(sql)>10",
   127242       zDbMain
   127243   );
   127244   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127245   db->init.iDb = 0;
   127246 
   127247   /* Loop through the tables in the main database. For each, do
   127248   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   127249   ** the contents to the temporary database.
   127250   */
   127251   rc = execSqlF(db, pzErrMsg,
   127252       "SELECT'INSERT INTO vacuum_db.'||quote(name)"
   127253       "||' SELECT*FROM\"%w\".'||quote(name)"
   127254       "FROM vacuum_db.sqlite_master "
   127255       "WHERE type='table'AND coalesce(rootpage,1)>0",
   127256       zDbMain
   127257   );
   127258   assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
   127259   db->mDbFlags &= ~DBFLAG_Vacuum;
   127260   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127261 
   127262   /* Copy the triggers, views, and virtual tables from the main database
   127263   ** over to the temporary database.  None of these objects has any
   127264   ** associated storage, so all we have to do is copy their entries
   127265   ** from the SQLITE_MASTER table.
   127266   */
   127267   rc = execSqlF(db, pzErrMsg,
   127268       "INSERT INTO vacuum_db.sqlite_master"
   127269       " SELECT*FROM \"%w\".sqlite_master"
   127270       " WHERE type IN('view','trigger')"
   127271       " OR(type='table'AND rootpage=0)",
   127272       zDbMain
   127273   );
   127274   if( rc ) goto end_of_vacuum;
   127275 
   127276   /* At this point, there is a write transaction open on both the
   127277   ** vacuum database and the main database. Assuming no error occurs,
   127278   ** both transactions are closed by this block - the main database
   127279   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
   127280   ** call to sqlite3BtreeCommit().
   127281   */
   127282   {
   127283     u32 meta;
   127284     int i;
   127285 
   127286     /* This array determines which meta meta values are preserved in the
   127287     ** vacuum.  Even entries are the meta value number and odd entries
   127288     ** are an increment to apply to the meta value after the vacuum.
   127289     ** The increment is used to increase the schema cookie so that other
   127290     ** connections to the same database will know to reread the schema.
   127291     */
   127292     static const unsigned char aCopy[] = {
   127293        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
   127294        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
   127295        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
   127296        BTREE_USER_VERSION,       0,  /* Preserve the user version */
   127297        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
   127298     };
   127299 
   127300     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
   127301     assert( 1==sqlite3BtreeIsInTrans(pMain) );
   127302 
   127303     /* Copy Btree meta values */
   127304     for(i=0; i<ArraySize(aCopy); i+=2){
   127305       /* GetMeta() and UpdateMeta() cannot fail in this context because
   127306       ** we already have page 1 loaded into cache and marked dirty. */
   127307       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
   127308       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
   127309       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
   127310     }
   127311 
   127312     rc = sqlite3BtreeCopyFile(pMain, pTemp);
   127313     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127314     rc = sqlite3BtreeCommit(pTemp);
   127315     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   127316 #ifndef SQLITE_OMIT_AUTOVACUUM
   127317     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
   127318 #endif
   127319   }
   127320 
   127321   assert( rc==SQLITE_OK );
   127322   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   127323 
   127324 end_of_vacuum:
   127325   /* Restore the original value of db->flags */
   127326   db->init.iDb = 0;
   127327   db->mDbFlags = saved_mDbFlags;
   127328   db->flags = saved_flags;
   127329   db->nChange = saved_nChange;
   127330   db->nTotalChange = saved_nTotalChange;
   127331   db->mTrace = saved_mTrace;
   127332   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
   127333 
   127334   /* Currently there is an SQL level transaction open on the vacuum
   127335   ** database. No locks are held on any other files (since the main file
   127336   ** was committed at the btree level). So it safe to end the transaction
   127337   ** by manually setting the autoCommit flag to true and detaching the
   127338   ** vacuum database. The vacuum_db journal file is deleted when the pager
   127339   ** is closed by the DETACH.
   127340   */
   127341   db->autoCommit = 1;
   127342 
   127343   if( pDb ){
   127344     sqlite3BtreeClose(pDb->pBt);
   127345     pDb->pBt = 0;
   127346     pDb->pSchema = 0;
   127347   }
   127348 
   127349   /* This both clears the schemas and reduces the size of the db->aDb[]
   127350   ** array. */
   127351   sqlite3ResetAllSchemasOfConnection(db);
   127352 
   127353   return rc;
   127354 }
   127355 
   127356 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
   127357 
   127358 /************** End of vacuum.c **********************************************/
   127359 /************** Begin file vtab.c ********************************************/
   127360 /*
   127361 ** 2006 June 10
   127362 **
   127363 ** The author disclaims copyright to this source code.  In place of
   127364 ** a legal notice, here is a blessing:
   127365 **
   127366 **    May you do good and not evil.
   127367 **    May you find forgiveness for yourself and forgive others.
   127368 **    May you share freely, never taking more than you give.
   127369 **
   127370 *************************************************************************
   127371 ** This file contains code used to help implement virtual tables.
   127372 */
   127373 #ifndef SQLITE_OMIT_VIRTUALTABLE
   127374 /* #include "sqliteInt.h" */
   127375 
   127376 /*
   127377 ** Before a virtual table xCreate() or xConnect() method is invoked, the
   127378 ** sqlite3.pVtabCtx member variable is set to point to an instance of
   127379 ** this struct allocated on the stack. It is used by the implementation of
   127380 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
   127381 ** are invoked only from within xCreate and xConnect methods.
   127382 */
   127383 struct VtabCtx {
   127384   VTable *pVTable;    /* The virtual table being constructed */
   127385   Table *pTab;        /* The Table object to which the virtual table belongs */
   127386   VtabCtx *pPrior;    /* Parent context (if any) */
   127387   int bDeclared;      /* True after sqlite3_declare_vtab() is called */
   127388 };
   127389 
   127390 /*
   127391 ** Construct and install a Module object for a virtual table.  When this
   127392 ** routine is called, it is guaranteed that all appropriate locks are held
   127393 ** and the module is not already part of the connection.
   127394 */
   127395 SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
   127396   sqlite3 *db,                    /* Database in which module is registered */
   127397   const char *zName,              /* Name assigned to this module */
   127398   const sqlite3_module *pModule,  /* The definition of the module */
   127399   void *pAux,                     /* Context pointer for xCreate/xConnect */
   127400   void (*xDestroy)(void *)        /* Module destructor function */
   127401 ){
   127402   Module *pMod;
   127403   int nName = sqlite3Strlen30(zName);
   127404   pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
   127405   if( pMod==0 ){
   127406     sqlite3OomFault(db);
   127407   }else{
   127408     Module *pDel;
   127409     char *zCopy = (char *)(&pMod[1]);
   127410     memcpy(zCopy, zName, nName+1);
   127411     pMod->zName = zCopy;
   127412     pMod->pModule = pModule;
   127413     pMod->pAux = pAux;
   127414     pMod->xDestroy = xDestroy;
   127415     pMod->pEpoTab = 0;
   127416     pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
   127417     assert( pDel==0 || pDel==pMod );
   127418     if( pDel ){
   127419       sqlite3OomFault(db);
   127420       sqlite3DbFree(db, pDel);
   127421       pMod = 0;
   127422     }
   127423   }
   127424   return pMod;
   127425 }
   127426 
   127427 /*
   127428 ** The actual function that does the work of creating a new module.
   127429 ** This function implements the sqlite3_create_module() and
   127430 ** sqlite3_create_module_v2() interfaces.
   127431 */
   127432 static int createModule(
   127433   sqlite3 *db,                    /* Database in which module is registered */
   127434   const char *zName,              /* Name assigned to this module */
   127435   const sqlite3_module *pModule,  /* The definition of the module */
   127436   void *pAux,                     /* Context pointer for xCreate/xConnect */
   127437   void (*xDestroy)(void *)        /* Module destructor function */
   127438 ){
   127439   int rc = SQLITE_OK;
   127440 
   127441   sqlite3_mutex_enter(db->mutex);
   127442   if( sqlite3HashFind(&db->aModule, zName) ){
   127443     rc = SQLITE_MISUSE_BKPT;
   127444   }else{
   127445     (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
   127446   }
   127447   rc = sqlite3ApiExit(db, rc);
   127448   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
   127449   sqlite3_mutex_leave(db->mutex);
   127450   return rc;
   127451 }
   127452 
   127453 
   127454 /*
   127455 ** External API function used to create a new virtual-table module.
   127456 */
   127457 SQLITE_API int sqlite3_create_module(
   127458   sqlite3 *db,                    /* Database in which module is registered */
   127459   const char *zName,              /* Name assigned to this module */
   127460   const sqlite3_module *pModule,  /* The definition of the module */
   127461   void *pAux                      /* Context pointer for xCreate/xConnect */
   127462 ){
   127463 #ifdef SQLITE_ENABLE_API_ARMOR
   127464   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
   127465 #endif
   127466   return createModule(db, zName, pModule, pAux, 0);
   127467 }
   127468 
   127469 /*
   127470 ** External API function used to create a new virtual-table module.
   127471 */
   127472 SQLITE_API int sqlite3_create_module_v2(
   127473   sqlite3 *db,                    /* Database in which module is registered */
   127474   const char *zName,              /* Name assigned to this module */
   127475   const sqlite3_module *pModule,  /* The definition of the module */
   127476   void *pAux,                     /* Context pointer for xCreate/xConnect */
   127477   void (*xDestroy)(void *)        /* Module destructor function */
   127478 ){
   127479 #ifdef SQLITE_ENABLE_API_ARMOR
   127480   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
   127481 #endif
   127482   return createModule(db, zName, pModule, pAux, xDestroy);
   127483 }
   127484 
   127485 /*
   127486 ** Lock the virtual table so that it cannot be disconnected.
   127487 ** Locks nest.  Every lock should have a corresponding unlock.
   127488 ** If an unlock is omitted, resources leaks will occur.
   127489 **
   127490 ** If a disconnect is attempted while a virtual table is locked,
   127491 ** the disconnect is deferred until all locks have been removed.
   127492 */
   127493 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
   127494   pVTab->nRef++;
   127495 }
   127496 
   127497 
   127498 /*
   127499 ** pTab is a pointer to a Table structure representing a virtual-table.
   127500 ** Return a pointer to the VTable object used by connection db to access
   127501 ** this virtual-table, if one has been created, or NULL otherwise.
   127502 */
   127503 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   127504   VTable *pVtab;
   127505   assert( IsVirtual(pTab) );
   127506   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   127507   return pVtab;
   127508 }
   127509 
   127510 /*
   127511 ** Decrement the ref-count on a virtual table object. When the ref-count
   127512 ** reaches zero, call the xDisconnect() method to delete the object.
   127513 */
   127514 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
   127515   sqlite3 *db = pVTab->db;
   127516 
   127517   assert( db );
   127518   assert( pVTab->nRef>0 );
   127519   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
   127520 
   127521   pVTab->nRef--;
   127522   if( pVTab->nRef==0 ){
   127523     sqlite3_vtab *p = pVTab->pVtab;
   127524     if( p ){
   127525       p->pModule->xDisconnect(p);
   127526     }
   127527     sqlite3DbFree(db, pVTab);
   127528   }
   127529 }
   127530 
   127531 /*
   127532 ** Table p is a virtual table. This function moves all elements in the
   127533 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
   127534 ** database connections to be disconnected at the next opportunity.
   127535 ** Except, if argument db is not NULL, then the entry associated with
   127536 ** connection db is left in the p->pVTable list.
   127537 */
   127538 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   127539   VTable *pRet = 0;
   127540   VTable *pVTable = p->pVTable;
   127541   p->pVTable = 0;
   127542 
   127543   /* Assert that the mutex (if any) associated with the BtShared database
   127544   ** that contains table p is held by the caller. See header comments
   127545   ** above function sqlite3VtabUnlockList() for an explanation of why
   127546   ** this makes it safe to access the sqlite3.pDisconnect list of any
   127547   ** database connection that may have an entry in the p->pVTable list.
   127548   */
   127549   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   127550 
   127551   while( pVTable ){
   127552     sqlite3 *db2 = pVTable->db;
   127553     VTable *pNext = pVTable->pNext;
   127554     assert( db2 );
   127555     if( db2==db ){
   127556       pRet = pVTable;
   127557       p->pVTable = pRet;
   127558       pRet->pNext = 0;
   127559     }else{
   127560       pVTable->pNext = db2->pDisconnect;
   127561       db2->pDisconnect = pVTable;
   127562     }
   127563     pVTable = pNext;
   127564   }
   127565 
   127566   assert( !db || pRet );
   127567   return pRet;
   127568 }
   127569 
   127570 /*
   127571 ** Table *p is a virtual table. This function removes the VTable object
   127572 ** for table *p associated with database connection db from the linked
   127573 ** list in p->pVTab. It also decrements the VTable ref count. This is
   127574 ** used when closing database connection db to free all of its VTable
   127575 ** objects without disturbing the rest of the Schema object (which may
   127576 ** be being used by other shared-cache connections).
   127577 */
   127578 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
   127579   VTable **ppVTab;
   127580 
   127581   assert( IsVirtual(p) );
   127582   assert( sqlite3BtreeHoldsAllMutexes(db) );
   127583   assert( sqlite3_mutex_held(db->mutex) );
   127584 
   127585   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
   127586     if( (*ppVTab)->db==db  ){
   127587       VTable *pVTab = *ppVTab;
   127588       *ppVTab = pVTab->pNext;
   127589       sqlite3VtabUnlock(pVTab);
   127590       break;
   127591     }
   127592   }
   127593 }
   127594 
   127595 
   127596 /*
   127597 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
   127598 **
   127599 ** This function may only be called when the mutexes associated with all
   127600 ** shared b-tree databases opened using connection db are held by the
   127601 ** caller. This is done to protect the sqlite3.pDisconnect list. The
   127602 ** sqlite3.pDisconnect list is accessed only as follows:
   127603 **
   127604 **   1) By this function. In this case, all BtShared mutexes and the mutex
   127605 **      associated with the database handle itself must be held.
   127606 **
   127607 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
   127608 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
   127609 **      associated with the database the virtual table is stored in is held
   127610 **      or, if the virtual table is stored in a non-sharable database, then
   127611 **      the database handle mutex is held.
   127612 **
   127613 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
   127614 ** by multiple threads. It is thread-safe.
   127615 */
   127616 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   127617   VTable *p = db->pDisconnect;
   127618   db->pDisconnect = 0;
   127619 
   127620   assert( sqlite3BtreeHoldsAllMutexes(db) );
   127621   assert( sqlite3_mutex_held(db->mutex) );
   127622 
   127623   if( p ){
   127624     sqlite3ExpirePreparedStatements(db);
   127625     do {
   127626       VTable *pNext = p->pNext;
   127627       sqlite3VtabUnlock(p);
   127628       p = pNext;
   127629     }while( p );
   127630   }
   127631 }
   127632 
   127633 /*
   127634 ** Clear any and all virtual-table information from the Table record.
   127635 ** This routine is called, for example, just before deleting the Table
   127636 ** record.
   127637 **
   127638 ** Since it is a virtual-table, the Table structure contains a pointer
   127639 ** to the head of a linked list of VTable structures. Each VTable
   127640 ** structure is associated with a single sqlite3* user of the schema.
   127641 ** The reference count of the VTable structure associated with database
   127642 ** connection db is decremented immediately (which may lead to the
   127643 ** structure being xDisconnected and free). Any other VTable structures
   127644 ** in the list are moved to the sqlite3.pDisconnect list of the associated
   127645 ** database connection.
   127646 */
   127647 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
   127648   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
   127649   if( p->azModuleArg ){
   127650     int i;
   127651     for(i=0; i<p->nModuleArg; i++){
   127652       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
   127653     }
   127654     sqlite3DbFree(db, p->azModuleArg);
   127655   }
   127656 }
   127657 
   127658 /*
   127659 ** Add a new module argument to pTable->azModuleArg[].
   127660 ** The string is not copied - the pointer is stored.  The
   127661 ** string will be freed automatically when the table is
   127662 ** deleted.
   127663 */
   127664 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
   127665   int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
   127666   char **azModuleArg;
   127667   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
   127668   if( azModuleArg==0 ){
   127669     sqlite3DbFree(db, zArg);
   127670   }else{
   127671     int i = pTable->nModuleArg++;
   127672     azModuleArg[i] = zArg;
   127673     azModuleArg[i+1] = 0;
   127674     pTable->azModuleArg = azModuleArg;
   127675   }
   127676 }
   127677 
   127678 /*
   127679 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
   127680 ** statement.  The module name has been parsed, but the optional list
   127681 ** of parameters that follow the module name are still pending.
   127682 */
   127683 SQLITE_PRIVATE void sqlite3VtabBeginParse(
   127684   Parse *pParse,        /* Parsing context */
   127685   Token *pName1,        /* Name of new table, or database name */
   127686   Token *pName2,        /* Name of new table or NULL */
   127687   Token *pModuleName,   /* Name of the module for the virtual table */
   127688   int ifNotExists       /* No error if the table already exists */
   127689 ){
   127690   int iDb;              /* The database the table is being created in */
   127691   Table *pTable;        /* The new virtual table */
   127692   sqlite3 *db;          /* Database connection */
   127693 
   127694   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
   127695   pTable = pParse->pNewTable;
   127696   if( pTable==0 ) return;
   127697   assert( 0==pTable->pIndex );
   127698 
   127699   db = pParse->db;
   127700   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
   127701   assert( iDb>=0 );
   127702 
   127703   assert( pTable->nModuleArg==0 );
   127704   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
   127705   addModuleArgument(db, pTable, 0);
   127706   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
   127707   assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
   127708        || (pParse->sNameToken.z==pName1->z && pName2->z==0)
   127709   );
   127710   pParse->sNameToken.n = (int)(
   127711       &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
   127712   );
   127713 
   127714 #ifndef SQLITE_OMIT_AUTHORIZATION
   127715   /* Creating a virtual table invokes the authorization callback twice.
   127716   ** The first invocation, to obtain permission to INSERT a row into the
   127717   ** sqlite_master table, has already been made by sqlite3StartTable().
   127718   ** The second call, to obtain permission to create the table, is made now.
   127719   */
   127720   if( pTable->azModuleArg ){
   127721     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
   127722             pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
   127723   }
   127724 #endif
   127725 }
   127726 
   127727 /*
   127728 ** This routine takes the module argument that has been accumulating
   127729 ** in pParse->zArg[] and appends it to the list of arguments on the
   127730 ** virtual table currently under construction in pParse->pTable.
   127731 */
   127732 static void addArgumentToVtab(Parse *pParse){
   127733   if( pParse->sArg.z && pParse->pNewTable ){
   127734     const char *z = (const char*)pParse->sArg.z;
   127735     int n = pParse->sArg.n;
   127736     sqlite3 *db = pParse->db;
   127737     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
   127738   }
   127739 }
   127740 
   127741 /*
   127742 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
   127743 ** has been completely parsed.
   127744 */
   127745 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   127746   Table *pTab = pParse->pNewTable;  /* The table being constructed */
   127747   sqlite3 *db = pParse->db;         /* The database connection */
   127748 
   127749   if( pTab==0 ) return;
   127750   addArgumentToVtab(pParse);
   127751   pParse->sArg.z = 0;
   127752   if( pTab->nModuleArg<1 ) return;
   127753 
   127754   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   127755   ** first time (in other words if the virtual table is actually being
   127756   ** created now instead of just being read out of sqlite_master) then
   127757   ** do additional initialization work and store the statement text
   127758   ** in the sqlite_master table.
   127759   */
   127760   if( !db->init.busy ){
   127761     char *zStmt;
   127762     char *zWhere;
   127763     int iDb;
   127764     int iReg;
   127765     Vdbe *v;
   127766 
   127767     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
   127768     if( pEnd ){
   127769       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
   127770     }
   127771     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
   127772 
   127773     /* A slot for the record has already been allocated in the
   127774     ** SQLITE_MASTER table.  We just need to update that slot with all
   127775     ** the information we've collected.
   127776     **
   127777     ** The VM register number pParse->regRowid holds the rowid of an
   127778     ** entry in the sqlite_master table tht was created for this vtab
   127779     ** by sqlite3StartTable().
   127780     */
   127781     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   127782     sqlite3NestedParse(pParse,
   127783       "UPDATE %Q.%s "
   127784          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   127785        "WHERE rowid=#%d",
   127786       db->aDb[iDb].zDbSName, MASTER_NAME,
   127787       pTab->zName,
   127788       pTab->zName,
   127789       zStmt,
   127790       pParse->regRowid
   127791     );
   127792     sqlite3DbFree(db, zStmt);
   127793     v = sqlite3GetVdbe(pParse);
   127794     sqlite3ChangeCookie(pParse, iDb);
   127795 
   127796     sqlite3VdbeAddOp0(v, OP_Expire);
   127797     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
   127798     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   127799 
   127800     iReg = ++pParse->nMem;
   127801     sqlite3VdbeLoadString(v, iReg, pTab->zName);
   127802     sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
   127803   }
   127804 
   127805   /* If we are rereading the sqlite_master table create the in-memory
   127806   ** record of the table. The xConnect() method is not called until
   127807   ** the first time the virtual table is used in an SQL statement. This
   127808   ** allows a schema that contains virtual tables to be loaded before
   127809   ** the required virtual table implementations are registered.  */
   127810   else {
   127811     Table *pOld;
   127812     Schema *pSchema = pTab->pSchema;
   127813     const char *zName = pTab->zName;
   127814     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
   127815     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
   127816     if( pOld ){
   127817       sqlite3OomFault(db);
   127818       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   127819       return;
   127820     }
   127821     pParse->pNewTable = 0;
   127822   }
   127823 }
   127824 
   127825 /*
   127826 ** The parser calls this routine when it sees the first token
   127827 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
   127828 */
   127829 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
   127830   addArgumentToVtab(pParse);
   127831   pParse->sArg.z = 0;
   127832   pParse->sArg.n = 0;
   127833 }
   127834 
   127835 /*
   127836 ** The parser calls this routine for each token after the first token
   127837 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
   127838 */
   127839 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
   127840   Token *pArg = &pParse->sArg;
   127841   if( pArg->z==0 ){
   127842     pArg->z = p->z;
   127843     pArg->n = p->n;
   127844   }else{
   127845     assert(pArg->z <= p->z);
   127846     pArg->n = (int)(&p->z[p->n] - pArg->z);
   127847   }
   127848 }
   127849 
   127850 /*
   127851 ** Invoke a virtual table constructor (either xCreate or xConnect). The
   127852 ** pointer to the function to invoke is passed as the fourth parameter
   127853 ** to this procedure.
   127854 */
   127855 static int vtabCallConstructor(
   127856   sqlite3 *db,
   127857   Table *pTab,
   127858   Module *pMod,
   127859   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
   127860   char **pzErr
   127861 ){
   127862   VtabCtx sCtx;
   127863   VTable *pVTable;
   127864   int rc;
   127865   const char *const*azArg = (const char *const*)pTab->azModuleArg;
   127866   int nArg = pTab->nModuleArg;
   127867   char *zErr = 0;
   127868   char *zModuleName;
   127869   int iDb;
   127870   VtabCtx *pCtx;
   127871 
   127872   /* Check that the virtual-table is not already being initialized */
   127873   for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
   127874     if( pCtx->pTab==pTab ){
   127875       *pzErr = sqlite3MPrintf(db,
   127876           "vtable constructor called recursively: %s", pTab->zName
   127877       );
   127878       return SQLITE_LOCKED;
   127879     }
   127880   }
   127881 
   127882   zModuleName = sqlite3DbStrDup(db, pTab->zName);
   127883   if( !zModuleName ){
   127884     return SQLITE_NOMEM_BKPT;
   127885   }
   127886 
   127887   pVTable = sqlite3MallocZero(sizeof(VTable));
   127888   if( !pVTable ){
   127889     sqlite3OomFault(db);
   127890     sqlite3DbFree(db, zModuleName);
   127891     return SQLITE_NOMEM_BKPT;
   127892   }
   127893   pVTable->db = db;
   127894   pVTable->pMod = pMod;
   127895 
   127896   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   127897   pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
   127898 
   127899   /* Invoke the virtual table constructor */
   127900   assert( &db->pVtabCtx );
   127901   assert( xConstruct );
   127902   sCtx.pTab = pTab;
   127903   sCtx.pVTable = pVTable;
   127904   sCtx.pPrior = db->pVtabCtx;
   127905   sCtx.bDeclared = 0;
   127906   db->pVtabCtx = &sCtx;
   127907   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   127908   db->pVtabCtx = sCtx.pPrior;
   127909   if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
   127910   assert( sCtx.pTab==pTab );
   127911 
   127912   if( SQLITE_OK!=rc ){
   127913     if( zErr==0 ){
   127914       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   127915     }else {
   127916       *pzErr = sqlite3MPrintf(db, "%s", zErr);
   127917       sqlite3_free(zErr);
   127918     }
   127919     sqlite3DbFree(db, pVTable);
   127920   }else if( ALWAYS(pVTable->pVtab) ){
   127921     /* Justification of ALWAYS():  A correct vtab constructor must allocate
   127922     ** the sqlite3_vtab object if successful.  */
   127923     memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
   127924     pVTable->pVtab->pModule = pMod->pModule;
   127925     pVTable->nRef = 1;
   127926     if( sCtx.bDeclared==0 ){
   127927       const char *zFormat = "vtable constructor did not declare schema: %s";
   127928       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   127929       sqlite3VtabUnlock(pVTable);
   127930       rc = SQLITE_ERROR;
   127931     }else{
   127932       int iCol;
   127933       u8 oooHidden = 0;
   127934       /* If everything went according to plan, link the new VTable structure
   127935       ** into the linked list headed by pTab->pVTable. Then loop through the
   127936       ** columns of the table to see if any of them contain the token "hidden".
   127937       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
   127938       ** the type string.  */
   127939       pVTable->pNext = pTab->pVTable;
   127940       pTab->pVTable = pVTable;
   127941 
   127942       for(iCol=0; iCol<pTab->nCol; iCol++){
   127943         char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
   127944         int nType;
   127945         int i = 0;
   127946         nType = sqlite3Strlen30(zType);
   127947         for(i=0; i<nType; i++){
   127948           if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
   127949            && (i==0 || zType[i-1]==' ')
   127950            && (zType[i+6]=='\0' || zType[i+6]==' ')
   127951           ){
   127952             break;
   127953           }
   127954         }
   127955         if( i<nType ){
   127956           int j;
   127957           int nDel = 6 + (zType[i+6] ? 1 : 0);
   127958           for(j=i; (j+nDel)<=nType; j++){
   127959             zType[j] = zType[j+nDel];
   127960           }
   127961           if( zType[i]=='\0' && i>0 ){
   127962             assert(zType[i-1]==' ');
   127963             zType[i-1] = '\0';
   127964           }
   127965           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
   127966           oooHidden = TF_OOOHidden;
   127967         }else{
   127968           pTab->tabFlags |= oooHidden;
   127969         }
   127970       }
   127971     }
   127972   }
   127973 
   127974   sqlite3DbFree(db, zModuleName);
   127975   return rc;
   127976 }
   127977 
   127978 /*
   127979 ** This function is invoked by the parser to call the xConnect() method
   127980 ** of the virtual table pTab. If an error occurs, an error code is returned
   127981 ** and an error left in pParse.
   127982 **
   127983 ** This call is a no-op if table pTab is not a virtual table.
   127984 */
   127985 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   127986   sqlite3 *db = pParse->db;
   127987   const char *zMod;
   127988   Module *pMod;
   127989   int rc;
   127990 
   127991   assert( pTab );
   127992   if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
   127993     return SQLITE_OK;
   127994   }
   127995 
   127996   /* Locate the required virtual table module */
   127997   zMod = pTab->azModuleArg[0];
   127998   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
   127999 
   128000   if( !pMod ){
   128001     const char *zModule = pTab->azModuleArg[0];
   128002     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
   128003     rc = SQLITE_ERROR;
   128004   }else{
   128005     char *zErr = 0;
   128006     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
   128007     if( rc!=SQLITE_OK ){
   128008       sqlite3ErrorMsg(pParse, "%s", zErr);
   128009       pParse->rc = rc;
   128010     }
   128011     sqlite3DbFree(db, zErr);
   128012   }
   128013 
   128014   return rc;
   128015 }
   128016 /*
   128017 ** Grow the db->aVTrans[] array so that there is room for at least one
   128018 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
   128019 */
   128020 static int growVTrans(sqlite3 *db){
   128021   const int ARRAY_INCR = 5;
   128022 
   128023   /* Grow the sqlite3.aVTrans array if required */
   128024   if( (db->nVTrans%ARRAY_INCR)==0 ){
   128025     VTable **aVTrans;
   128026     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
   128027     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
   128028     if( !aVTrans ){
   128029       return SQLITE_NOMEM_BKPT;
   128030     }
   128031     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
   128032     db->aVTrans = aVTrans;
   128033   }
   128034 
   128035   return SQLITE_OK;
   128036 }
   128037 
   128038 /*
   128039 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
   128040 ** have already been reserved using growVTrans().
   128041 */
   128042 static void addToVTrans(sqlite3 *db, VTable *pVTab){
   128043   /* Add pVtab to the end of sqlite3.aVTrans */
   128044   db->aVTrans[db->nVTrans++] = pVTab;
   128045   sqlite3VtabLock(pVTab);
   128046 }
   128047 
   128048 /*
   128049 ** This function is invoked by the vdbe to call the xCreate method
   128050 ** of the virtual table named zTab in database iDb.
   128051 **
   128052 ** If an error occurs, *pzErr is set to point to an English language
   128053 ** description of the error and an SQLITE_XXX error code is returned.
   128054 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   128055 */
   128056 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   128057   int rc = SQLITE_OK;
   128058   Table *pTab;
   128059   Module *pMod;
   128060   const char *zMod;
   128061 
   128062   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
   128063   assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
   128064 
   128065   /* Locate the required virtual table module */
   128066   zMod = pTab->azModuleArg[0];
   128067   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
   128068 
   128069   /* If the module has been registered and includes a Create method,
   128070   ** invoke it now. If the module has not been registered, return an
   128071   ** error. Otherwise, do nothing.
   128072   */
   128073   if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
   128074     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
   128075     rc = SQLITE_ERROR;
   128076   }else{
   128077     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
   128078   }
   128079 
   128080   /* Justification of ALWAYS():  The xConstructor method is required to
   128081   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
   128082   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
   128083     rc = growVTrans(db);
   128084     if( rc==SQLITE_OK ){
   128085       addToVTrans(db, sqlite3GetVTable(db, pTab));
   128086     }
   128087   }
   128088 
   128089   return rc;
   128090 }
   128091 
   128092 /*
   128093 ** This function is used to set the schema of a virtual table.  It is only
   128094 ** valid to call this function from within the xCreate() or xConnect() of a
   128095 ** virtual table module.
   128096 */
   128097 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   128098   VtabCtx *pCtx;
   128099   int rc = SQLITE_OK;
   128100   Table *pTab;
   128101   char *zErr = 0;
   128102   Parse sParse;
   128103 
   128104 #ifdef SQLITE_ENABLE_API_ARMOR
   128105   if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
   128106     return SQLITE_MISUSE_BKPT;
   128107   }
   128108 #endif
   128109   sqlite3_mutex_enter(db->mutex);
   128110   pCtx = db->pVtabCtx;
   128111   if( !pCtx || pCtx->bDeclared ){
   128112     sqlite3Error(db, SQLITE_MISUSE);
   128113     sqlite3_mutex_leave(db->mutex);
   128114     return SQLITE_MISUSE_BKPT;
   128115   }
   128116   pTab = pCtx->pTab;
   128117   assert( IsVirtual(pTab) );
   128118 
   128119   memset(&sParse, 0, sizeof(sParse));
   128120   sParse.declareVtab = 1;
   128121   sParse.db = db;
   128122   sParse.nQueryLoop = 1;
   128123   if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
   128124    && sParse.pNewTable
   128125    && !db->mallocFailed
   128126    && !sParse.pNewTable->pSelect
   128127    && !IsVirtual(sParse.pNewTable)
   128128   ){
   128129     if( !pTab->aCol ){
   128130       Table *pNew = sParse.pNewTable;
   128131       Index *pIdx;
   128132       pTab->aCol = pNew->aCol;
   128133       pTab->nCol = pNew->nCol;
   128134       pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
   128135       pNew->nCol = 0;
   128136       pNew->aCol = 0;
   128137       assert( pTab->pIndex==0 );
   128138       assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
   128139       if( !HasRowid(pNew)
   128140        && pCtx->pVTable->pMod->pModule->xUpdate!=0
   128141        && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
   128142       ){
   128143         /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
   128144         ** or else must have a single-column PRIMARY KEY */
   128145         rc = SQLITE_ERROR;
   128146       }
   128147       pIdx = pNew->pIndex;
   128148       if( pIdx ){
   128149         assert( pIdx->pNext==0 );
   128150         pTab->pIndex = pIdx;
   128151         pNew->pIndex = 0;
   128152         pIdx->pTable = pTab;
   128153       }
   128154     }
   128155     pCtx->bDeclared = 1;
   128156   }else{
   128157     sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
   128158     sqlite3DbFree(db, zErr);
   128159     rc = SQLITE_ERROR;
   128160   }
   128161   sParse.declareVtab = 0;
   128162 
   128163   if( sParse.pVdbe ){
   128164     sqlite3VdbeFinalize(sParse.pVdbe);
   128165   }
   128166   sqlite3DeleteTable(db, sParse.pNewTable);
   128167   sqlite3ParserReset(&sParse);
   128168 
   128169   assert( (rc&0xff)==rc );
   128170   rc = sqlite3ApiExit(db, rc);
   128171   sqlite3_mutex_leave(db->mutex);
   128172   return rc;
   128173 }
   128174 
   128175 /*
   128176 ** This function is invoked by the vdbe to call the xDestroy method
   128177 ** of the virtual table named zTab in database iDb. This occurs
   128178 ** when a DROP TABLE is mentioned.
   128179 **
   128180 ** This call is a no-op if zTab is not a virtual table.
   128181 */
   128182 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   128183   int rc = SQLITE_OK;
   128184   Table *pTab;
   128185 
   128186   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
   128187   if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
   128188     VTable *p;
   128189     int (*xDestroy)(sqlite3_vtab *);
   128190     for(p=pTab->pVTable; p; p=p->pNext){
   128191       assert( p->pVtab );
   128192       if( p->pVtab->nRef>0 ){
   128193         return SQLITE_LOCKED;
   128194       }
   128195     }
   128196     p = vtabDisconnectAll(db, pTab);
   128197     xDestroy = p->pMod->pModule->xDestroy;
   128198     assert( xDestroy!=0 );  /* Checked before the virtual table is created */
   128199     rc = xDestroy(p->pVtab);
   128200     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
   128201     if( rc==SQLITE_OK ){
   128202       assert( pTab->pVTable==p && p->pNext==0 );
   128203       p->pVtab = 0;
   128204       pTab->pVTable = 0;
   128205       sqlite3VtabUnlock(p);
   128206     }
   128207   }
   128208 
   128209   return rc;
   128210 }
   128211 
   128212 /*
   128213 ** This function invokes either the xRollback or xCommit method
   128214 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
   128215 ** called is identified by the second argument, "offset", which is
   128216 ** the offset of the method to call in the sqlite3_module structure.
   128217 **
   128218 ** The array is cleared after invoking the callbacks.
   128219 */
   128220 static void callFinaliser(sqlite3 *db, int offset){
   128221   int i;
   128222   if( db->aVTrans ){
   128223     VTable **aVTrans = db->aVTrans;
   128224     db->aVTrans = 0;
   128225     for(i=0; i<db->nVTrans; i++){
   128226       VTable *pVTab = aVTrans[i];
   128227       sqlite3_vtab *p = pVTab->pVtab;
   128228       if( p ){
   128229         int (*x)(sqlite3_vtab *);
   128230         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
   128231         if( x ) x(p);
   128232       }
   128233       pVTab->iSavepoint = 0;
   128234       sqlite3VtabUnlock(pVTab);
   128235     }
   128236     sqlite3DbFree(db, aVTrans);
   128237     db->nVTrans = 0;
   128238   }
   128239 }
   128240 
   128241 /*
   128242 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
   128243 ** array. Return the error code for the first error that occurs, or
   128244 ** SQLITE_OK if all xSync operations are successful.
   128245 **
   128246 ** If an error message is available, leave it in p->zErrMsg.
   128247 */
   128248 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
   128249   int i;
   128250   int rc = SQLITE_OK;
   128251   VTable **aVTrans = db->aVTrans;
   128252 
   128253   db->aVTrans = 0;
   128254   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   128255     int (*x)(sqlite3_vtab *);
   128256     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
   128257     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
   128258       rc = x(pVtab);
   128259       sqlite3VtabImportErrmsg(p, pVtab);
   128260     }
   128261   }
   128262   db->aVTrans = aVTrans;
   128263   return rc;
   128264 }
   128265 
   128266 /*
   128267 ** Invoke the xRollback method of all virtual tables in the
   128268 ** sqlite3.aVTrans array. Then clear the array itself.
   128269 */
   128270 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
   128271   callFinaliser(db, offsetof(sqlite3_module,xRollback));
   128272   return SQLITE_OK;
   128273 }
   128274 
   128275 /*
   128276 ** Invoke the xCommit method of all virtual tables in the
   128277 ** sqlite3.aVTrans array. Then clear the array itself.
   128278 */
   128279 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
   128280   callFinaliser(db, offsetof(sqlite3_module,xCommit));
   128281   return SQLITE_OK;
   128282 }
   128283 
   128284 /*
   128285 ** If the virtual table pVtab supports the transaction interface
   128286 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
   128287 ** not currently open, invoke the xBegin method now.
   128288 **
   128289 ** If the xBegin call is successful, place the sqlite3_vtab pointer
   128290 ** in the sqlite3.aVTrans array.
   128291 */
   128292 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   128293   int rc = SQLITE_OK;
   128294   const sqlite3_module *pModule;
   128295 
   128296   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   128297   ** than zero, then this function is being called from within a
   128298   ** virtual module xSync() callback. It is illegal to write to
   128299   ** virtual module tables in this case, so return SQLITE_LOCKED.
   128300   */
   128301   if( sqlite3VtabInSync(db) ){
   128302     return SQLITE_LOCKED;
   128303   }
   128304   if( !pVTab ){
   128305     return SQLITE_OK;
   128306   }
   128307   pModule = pVTab->pVtab->pModule;
   128308 
   128309   if( pModule->xBegin ){
   128310     int i;
   128311 
   128312     /* If pVtab is already in the aVTrans array, return early */
   128313     for(i=0; i<db->nVTrans; i++){
   128314       if( db->aVTrans[i]==pVTab ){
   128315         return SQLITE_OK;
   128316       }
   128317     }
   128318 
   128319     /* Invoke the xBegin method. If successful, add the vtab to the
   128320     ** sqlite3.aVTrans[] array. */
   128321     rc = growVTrans(db);
   128322     if( rc==SQLITE_OK ){
   128323       rc = pModule->xBegin(pVTab->pVtab);
   128324       if( rc==SQLITE_OK ){
   128325         int iSvpt = db->nStatement + db->nSavepoint;
   128326         addToVTrans(db, pVTab);
   128327         if( iSvpt && pModule->xSavepoint ){
   128328           pVTab->iSavepoint = iSvpt;
   128329           rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
   128330         }
   128331       }
   128332     }
   128333   }
   128334   return rc;
   128335 }
   128336 
   128337 /*
   128338 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
   128339 ** virtual tables that currently have an open transaction. Pass iSavepoint
   128340 ** as the second argument to the virtual table method invoked.
   128341 **
   128342 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
   128343 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
   128344 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
   128345 ** an open transaction is invoked.
   128346 **
   128347 ** If any virtual table method returns an error code other than SQLITE_OK,
   128348 ** processing is abandoned and the error returned to the caller of this
   128349 ** function immediately. If all calls to virtual table methods are successful,
   128350 ** SQLITE_OK is returned.
   128351 */
   128352 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
   128353   int rc = SQLITE_OK;
   128354 
   128355   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
   128356   assert( iSavepoint>=-1 );
   128357   if( db->aVTrans ){
   128358     int i;
   128359     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   128360       VTable *pVTab = db->aVTrans[i];
   128361       const sqlite3_module *pMod = pVTab->pMod->pModule;
   128362       if( pVTab->pVtab && pMod->iVersion>=2 ){
   128363         int (*xMethod)(sqlite3_vtab *, int);
   128364         switch( op ){
   128365           case SAVEPOINT_BEGIN:
   128366             xMethod = pMod->xSavepoint;
   128367             pVTab->iSavepoint = iSavepoint+1;
   128368             break;
   128369           case SAVEPOINT_ROLLBACK:
   128370             xMethod = pMod->xRollbackTo;
   128371             break;
   128372           default:
   128373             xMethod = pMod->xRelease;
   128374             break;
   128375         }
   128376         if( xMethod && pVTab->iSavepoint>iSavepoint ){
   128377           rc = xMethod(pVTab->pVtab, iSavepoint);
   128378         }
   128379       }
   128380     }
   128381   }
   128382   return rc;
   128383 }
   128384 
   128385 /*
   128386 ** The first parameter (pDef) is a function implementation.  The
   128387 ** second parameter (pExpr) is the first argument to this function.
   128388 ** If pExpr is a column in a virtual table, then let the virtual
   128389 ** table implementation have an opportunity to overload the function.
   128390 **
   128391 ** This routine is used to allow virtual table implementations to
   128392 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
   128393 **
   128394 ** Return either the pDef argument (indicating no change) or a
   128395 ** new FuncDef structure that is marked as ephemeral using the
   128396 ** SQLITE_FUNC_EPHEM flag.
   128397 */
   128398 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   128399   sqlite3 *db,    /* Database connection for reporting malloc problems */
   128400   FuncDef *pDef,  /* Function to possibly overload */
   128401   int nArg,       /* Number of arguments to the function */
   128402   Expr *pExpr     /* First argument to the function */
   128403 ){
   128404   Table *pTab;
   128405   sqlite3_vtab *pVtab;
   128406   sqlite3_module *pMod;
   128407   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
   128408   void *pArg = 0;
   128409   FuncDef *pNew;
   128410   int rc = 0;
   128411   char *zLowerName;
   128412   unsigned char *z;
   128413 
   128414 
   128415   /* Check to see the left operand is a column in a virtual table */
   128416   if( NEVER(pExpr==0) ) return pDef;
   128417   if( pExpr->op!=TK_COLUMN ) return pDef;
   128418   pTab = pExpr->pTab;
   128419   if( pTab==0 ) return pDef;
   128420   if( !IsVirtual(pTab) ) return pDef;
   128421   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
   128422   assert( pVtab!=0 );
   128423   assert( pVtab->pModule!=0 );
   128424   pMod = (sqlite3_module *)pVtab->pModule;
   128425   if( pMod->xFindFunction==0 ) return pDef;
   128426 
   128427   /* Call the xFindFunction method on the virtual table implementation
   128428   ** to see if the implementation wants to overload this function
   128429   */
   128430   zLowerName = sqlite3DbStrDup(db, pDef->zName);
   128431   if( zLowerName ){
   128432     for(z=(unsigned char*)zLowerName; *z; z++){
   128433       *z = sqlite3UpperToLower[*z];
   128434     }
   128435     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
   128436     sqlite3DbFree(db, zLowerName);
   128437   }
   128438   if( rc==0 ){
   128439     return pDef;
   128440   }
   128441 
   128442   /* Create a new ephemeral function definition for the overloaded
   128443   ** function */
   128444   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
   128445                              + sqlite3Strlen30(pDef->zName) + 1);
   128446   if( pNew==0 ){
   128447     return pDef;
   128448   }
   128449   *pNew = *pDef;
   128450   pNew->zName = (const char*)&pNew[1];
   128451   memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
   128452   pNew->xSFunc = xSFunc;
   128453   pNew->pUserData = pArg;
   128454   pNew->funcFlags |= SQLITE_FUNC_EPHEM;
   128455   return pNew;
   128456 }
   128457 
   128458 /*
   128459 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   128460 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   128461 ** array if it is missing.  If pTab is already in the array, this routine
   128462 ** is a no-op.
   128463 */
   128464 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
   128465   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   128466   int i, n;
   128467   Table **apVtabLock;
   128468 
   128469   assert( IsVirtual(pTab) );
   128470   for(i=0; i<pToplevel->nVtabLock; i++){
   128471     if( pTab==pToplevel->apVtabLock[i] ) return;
   128472   }
   128473   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
   128474   apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
   128475   if( apVtabLock ){
   128476     pToplevel->apVtabLock = apVtabLock;
   128477     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   128478   }else{
   128479     sqlite3OomFault(pToplevel->db);
   128480   }
   128481 }
   128482 
   128483 /*
   128484 ** Check to see if virtual table module pMod can be have an eponymous
   128485 ** virtual table instance.  If it can, create one if one does not already
   128486 ** exist. Return non-zero if the eponymous virtual table instance exists
   128487 ** when this routine returns, and return zero if it does not exist.
   128488 **
   128489 ** An eponymous virtual table instance is one that is named after its
   128490 ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
   128491 ** statement in order to come into existance.  Eponymous virtual table
   128492 ** instances always exist.  They cannot be DROP-ed.
   128493 **
   128494 ** Any virtual table module for which xConnect and xCreate are the same
   128495 ** method can have an eponymous virtual table instance.
   128496 */
   128497 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
   128498   const sqlite3_module *pModule = pMod->pModule;
   128499   Table *pTab;
   128500   char *zErr = 0;
   128501   int rc;
   128502   sqlite3 *db = pParse->db;
   128503   if( pMod->pEpoTab ) return 1;
   128504   if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
   128505   pTab = sqlite3DbMallocZero(db, sizeof(Table));
   128506   if( pTab==0 ) return 0;
   128507   pTab->zName = sqlite3DbStrDup(db, pMod->zName);
   128508   if( pTab->zName==0 ){
   128509     sqlite3DbFree(db, pTab);
   128510     return 0;
   128511   }
   128512   pMod->pEpoTab = pTab;
   128513   pTab->nTabRef = 1;
   128514   pTab->pSchema = db->aDb[0].pSchema;
   128515   assert( pTab->nModuleArg==0 );
   128516   pTab->iPKey = -1;
   128517   addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
   128518   addModuleArgument(db, pTab, 0);
   128519   addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
   128520   rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
   128521   if( rc ){
   128522     sqlite3ErrorMsg(pParse, "%s", zErr);
   128523     sqlite3DbFree(db, zErr);
   128524     sqlite3VtabEponymousTableClear(db, pMod);
   128525     return 0;
   128526   }
   128527   return 1;
   128528 }
   128529 
   128530 /*
   128531 ** Erase the eponymous virtual table instance associated with
   128532 ** virtual table module pMod, if it exists.
   128533 */
   128534 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
   128535   Table *pTab = pMod->pEpoTab;
   128536   if( pTab!=0 ){
   128537     /* Mark the table as Ephemeral prior to deleting it, so that the
   128538     ** sqlite3DeleteTable() routine will know that it is not stored in
   128539     ** the schema. */
   128540     pTab->tabFlags |= TF_Ephemeral;
   128541     sqlite3DeleteTable(db, pTab);
   128542     pMod->pEpoTab = 0;
   128543   }
   128544 }
   128545 
   128546 /*
   128547 ** Return the ON CONFLICT resolution mode in effect for the virtual
   128548 ** table update operation currently in progress.
   128549 **
   128550 ** The results of this routine are undefined unless it is called from
   128551 ** within an xUpdate method.
   128552 */
   128553 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
   128554   static const unsigned char aMap[] = {
   128555     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
   128556   };
   128557 #ifdef SQLITE_ENABLE_API_ARMOR
   128558   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   128559 #endif
   128560   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
   128561   assert( OE_Ignore==4 && OE_Replace==5 );
   128562   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
   128563   return (int)aMap[db->vtabOnConflict-1];
   128564 }
   128565 
   128566 /*
   128567 ** Call from within the xCreate() or xConnect() methods to provide
   128568 ** the SQLite core with additional information about the behavior
   128569 ** of the virtual table being implemented.
   128570 */
   128571 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
   128572   va_list ap;
   128573   int rc = SQLITE_OK;
   128574 
   128575 #ifdef SQLITE_ENABLE_API_ARMOR
   128576   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   128577 #endif
   128578   sqlite3_mutex_enter(db->mutex);
   128579   va_start(ap, op);
   128580   switch( op ){
   128581     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
   128582       VtabCtx *p = db->pVtabCtx;
   128583       if( !p ){
   128584         rc = SQLITE_MISUSE_BKPT;
   128585       }else{
   128586         assert( p->pTab==0 || IsVirtual(p->pTab) );
   128587         p->pVTable->bConstraint = (u8)va_arg(ap, int);
   128588       }
   128589       break;
   128590     }
   128591     default:
   128592       rc = SQLITE_MISUSE_BKPT;
   128593       break;
   128594   }
   128595   va_end(ap);
   128596 
   128597   if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
   128598   sqlite3_mutex_leave(db->mutex);
   128599   return rc;
   128600 }
   128601 
   128602 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   128603 
   128604 /************** End of vtab.c ************************************************/
   128605 /************** Begin file wherecode.c ***************************************/
   128606 /*
   128607 ** 2015-06-06
   128608 **
   128609 ** The author disclaims copyright to this source code.  In place of
   128610 ** a legal notice, here is a blessing:
   128611 **
   128612 **    May you do good and not evil.
   128613 **    May you find forgiveness for yourself and forgive others.
   128614 **    May you share freely, never taking more than you give.
   128615 **
   128616 *************************************************************************
   128617 ** This module contains C code that generates VDBE code used to process
   128618 ** the WHERE clause of SQL statements.
   128619 **
   128620 ** This file was split off from where.c on 2015-06-06 in order to reduce the
   128621 ** size of where.c and make it easier to edit.  This file contains the routines
   128622 ** that actually generate the bulk of the WHERE loop code.  The original where.c
   128623 ** file retains the code that does query planning and analysis.
   128624 */
   128625 /* #include "sqliteInt.h" */
   128626 /************** Include whereInt.h in the middle of wherecode.c **************/
   128627 /************** Begin file whereInt.h ****************************************/
   128628 /*
   128629 ** 2013-11-12
   128630 **
   128631 ** The author disclaims copyright to this source code.  In place of
   128632 ** a legal notice, here is a blessing:
   128633 **
   128634 **    May you do good and not evil.
   128635 **    May you find forgiveness for yourself and forgive others.
   128636 **    May you share freely, never taking more than you give.
   128637 **
   128638 *************************************************************************
   128639 **
   128640 ** This file contains structure and macro definitions for the query
   128641 ** planner logic in "where.c".  These definitions are broken out into
   128642 ** a separate source file for easier editing.
   128643 */
   128644 
   128645 /*
   128646 ** Trace output macros
   128647 */
   128648 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   128649 /***/ int sqlite3WhereTrace;
   128650 #endif
   128651 #if defined(SQLITE_DEBUG) \
   128652     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
   128653 # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
   128654 # define WHERETRACE_ENABLED 1
   128655 #else
   128656 # define WHERETRACE(K,X)
   128657 #endif
   128658 
   128659 /* Forward references
   128660 */
   128661 typedef struct WhereClause WhereClause;
   128662 typedef struct WhereMaskSet WhereMaskSet;
   128663 typedef struct WhereOrInfo WhereOrInfo;
   128664 typedef struct WhereAndInfo WhereAndInfo;
   128665 typedef struct WhereLevel WhereLevel;
   128666 typedef struct WhereLoop WhereLoop;
   128667 typedef struct WherePath WherePath;
   128668 typedef struct WhereTerm WhereTerm;
   128669 typedef struct WhereLoopBuilder WhereLoopBuilder;
   128670 typedef struct WhereScan WhereScan;
   128671 typedef struct WhereOrCost WhereOrCost;
   128672 typedef struct WhereOrSet WhereOrSet;
   128673 
   128674 /*
   128675 ** This object contains information needed to implement a single nested
   128676 ** loop in WHERE clause.
   128677 **
   128678 ** Contrast this object with WhereLoop.  This object describes the
   128679 ** implementation of the loop.  WhereLoop describes the algorithm.
   128680 ** This object contains a pointer to the WhereLoop algorithm as one of
   128681 ** its elements.
   128682 **
   128683 ** The WhereInfo object contains a single instance of this object for
   128684 ** each term in the FROM clause (which is to say, for each of the
   128685 ** nested loops as implemented).  The order of WhereLevel objects determines
   128686 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
   128687 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
   128688 */
   128689 struct WhereLevel {
   128690   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
   128691   int iTabCur;          /* The VDBE cursor used to access the table */
   128692   int iIdxCur;          /* The VDBE cursor used to access pIdx */
   128693   int addrBrk;          /* Jump here to break out of the loop */
   128694   int addrNxt;          /* Jump here to start the next IN combination */
   128695   int addrSkip;         /* Jump here for next iteration of skip-scan */
   128696   int addrCont;         /* Jump here to continue with the next loop cycle */
   128697   int addrFirst;        /* First instruction of interior of the loop */
   128698   int addrBody;         /* Beginning of the body of this loop */
   128699 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   128700   u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
   128701   int addrLikeRep;      /* LIKE range processing address */
   128702 #endif
   128703   u8 iFrom;             /* Which entry in the FROM clause */
   128704   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
   128705   int p1, p2;           /* Operands of the opcode used to ends the loop */
   128706   union {               /* Information that depends on pWLoop->wsFlags */
   128707     struct {
   128708       int nIn;              /* Number of entries in aInLoop[] */
   128709       struct InLoop {
   128710         int iCur;              /* The VDBE cursor used by this IN operator */
   128711         int addrInTop;         /* Top of the IN loop */
   128712         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
   128713       } *aInLoop;           /* Information about each nested IN operator */
   128714     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
   128715     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
   128716   } u;
   128717   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
   128718   Bitmask notReady;          /* FROM entries not usable at this level */
   128719 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   128720   int addrVisit;        /* Address at which row is visited */
   128721 #endif
   128722 };
   128723 
   128724 /*
   128725 ** Each instance of this object represents an algorithm for evaluating one
   128726 ** term of a join.  Every term of the FROM clause will have at least
   128727 ** one corresponding WhereLoop object (unless INDEXED BY constraints
   128728 ** prevent a query solution - which is an error) and many terms of the
   128729 ** FROM clause will have multiple WhereLoop objects, each describing a
   128730 ** potential way of implementing that FROM-clause term, together with
   128731 ** dependencies and cost estimates for using the chosen algorithm.
   128732 **
   128733 ** Query planning consists of building up a collection of these WhereLoop
   128734 ** objects, then computing a particular sequence of WhereLoop objects, with
   128735 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
   128736 ** and that minimize the overall cost.
   128737 */
   128738 struct WhereLoop {
   128739   Bitmask prereq;       /* Bitmask of other loops that must run first */
   128740   Bitmask maskSelf;     /* Bitmask identifying table iTab */
   128741 #ifdef SQLITE_DEBUG
   128742   char cId;             /* Symbolic ID of this loop for debugging use */
   128743 #endif
   128744   u8 iTab;              /* Position in FROM clause of table for this loop */
   128745   u8 iSortIdx;          /* Sorting index number.  0==None */
   128746   LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
   128747   LogEst rRun;          /* Cost of running each loop */
   128748   LogEst nOut;          /* Estimated number of output rows */
   128749   union {
   128750     struct {               /* Information for internal btree tables */
   128751       u16 nEq;               /* Number of equality constraints */
   128752       u16 nBtm;              /* Size of BTM vector */
   128753       u16 nTop;              /* Size of TOP vector */
   128754       u16 nIdxCol;           /* Index column used for ORDER BY */
   128755       Index *pIndex;         /* Index used, or NULL */
   128756     } btree;
   128757     struct {               /* Information for virtual tables */
   128758       int idxNum;            /* Index number */
   128759       u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
   128760       i8 isOrdered;          /* True if satisfies ORDER BY */
   128761       u16 omitMask;          /* Terms that may be omitted */
   128762       char *idxStr;          /* Index identifier string */
   128763     } vtab;
   128764   } u;
   128765   u32 wsFlags;          /* WHERE_* flags describing the plan */
   128766   u16 nLTerm;           /* Number of entries in aLTerm[] */
   128767   u16 nSkip;            /* Number of NULL aLTerm[] entries */
   128768   /**** whereLoopXfer() copies fields above ***********************/
   128769 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
   128770   u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
   128771   WhereTerm **aLTerm;   /* WhereTerms used */
   128772   WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
   128773   WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
   128774 };
   128775 
   128776 /* This object holds the prerequisites and the cost of running a
   128777 ** subquery on one operand of an OR operator in the WHERE clause.
   128778 ** See WhereOrSet for additional information
   128779 */
   128780 struct WhereOrCost {
   128781   Bitmask prereq;     /* Prerequisites */
   128782   LogEst rRun;        /* Cost of running this subquery */
   128783   LogEst nOut;        /* Number of outputs for this subquery */
   128784 };
   128785 
   128786 /* The WhereOrSet object holds a set of possible WhereOrCosts that
   128787 ** correspond to the subquery(s) of OR-clause processing.  Only the
   128788 ** best N_OR_COST elements are retained.
   128789 */
   128790 #define N_OR_COST 3
   128791 struct WhereOrSet {
   128792   u16 n;                      /* Number of valid a[] entries */
   128793   WhereOrCost a[N_OR_COST];   /* Set of best costs */
   128794 };
   128795 
   128796 /*
   128797 ** Each instance of this object holds a sequence of WhereLoop objects
   128798 ** that implement some or all of a query plan.
   128799 **
   128800 ** Think of each WhereLoop object as a node in a graph with arcs
   128801 ** showing dependencies and costs for travelling between nodes.  (That is
   128802 ** not a completely accurate description because WhereLoop costs are a
   128803 ** vector, not a scalar, and because dependencies are many-to-one, not
   128804 ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
   128805 ** Then a WherePath object is a path through the graph that visits some
   128806 ** or all of the WhereLoop objects once.
   128807 **
   128808 ** The "solver" works by creating the N best WherePath objects of length
   128809 ** 1.  Then using those as a basis to compute the N best WherePath objects
   128810 ** of length 2.  And so forth until the length of WherePaths equals the
   128811 ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
   128812 ** at the end is the chosen query plan.
   128813 */
   128814 struct WherePath {
   128815   Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
   128816   Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
   128817   LogEst nRow;          /* Estimated number of rows generated by this path */
   128818   LogEst rCost;         /* Total cost of this path */
   128819   LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
   128820   i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
   128821   WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
   128822 };
   128823 
   128824 /*
   128825 ** The query generator uses an array of instances of this structure to
   128826 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
   128827 ** clause subexpression is separated from the others by AND operators,
   128828 ** usually, or sometimes subexpressions separated by OR.
   128829 **
   128830 ** All WhereTerms are collected into a single WhereClause structure.
   128831 ** The following identity holds:
   128832 **
   128833 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
   128834 **
   128835 ** When a term is of the form:
   128836 **
   128837 **              X <op> <expr>
   128838 **
   128839 ** where X is a column name and <op> is one of certain operators,
   128840 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
   128841 ** cursor number and column number for X.  WhereTerm.eOperator records
   128842 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
   128843 ** use of a bitmask encoding for the operator allows us to search
   128844 ** quickly for terms that match any of several different operators.
   128845 **
   128846 ** A WhereTerm might also be two or more subterms connected by OR:
   128847 **
   128848 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   128849 **
   128850 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
   128851 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   128852 ** is collected about the OR clause.
   128853 **
   128854 ** If a term in the WHERE clause does not match either of the two previous
   128855 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   128856 ** to the original subexpression content and wtFlags is set up appropriately
   128857 ** but no other fields in the WhereTerm object are meaningful.
   128858 **
   128859 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
   128860 ** but they do so indirectly.  A single WhereMaskSet structure translates
   128861 ** cursor number into bits and the translated bit is stored in the prereq
   128862 ** fields.  The translation is used in order to maximize the number of
   128863 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
   128864 ** spread out over the non-negative integers.  For example, the cursor
   128865 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
   128866 ** translates these sparse cursor numbers into consecutive integers
   128867 ** beginning with 0 in order to make the best possible use of the available
   128868 ** bits in the Bitmask.  So, in the example above, the cursor numbers
   128869 ** would be mapped into integers 0 through 7.
   128870 **
   128871 ** The number of terms in a join is limited by the number of bits
   128872 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
   128873 ** is only able to process joins with 64 or fewer tables.
   128874 */
   128875 struct WhereTerm {
   128876   Expr *pExpr;            /* Pointer to the subexpression that is this term */
   128877   WhereClause *pWC;       /* The clause this term is part of */
   128878   LogEst truthProb;       /* Probability of truth for this expression */
   128879   u16 wtFlags;            /* TERM_xxx bit flags.  See below */
   128880   u16 eOperator;          /* A WO_xx value describing <op> */
   128881   u8 nChild;              /* Number of children that must disable us */
   128882   u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
   128883   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   128884   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
   128885   int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
   128886   union {
   128887     int leftColumn;         /* Column number of X in "X <op> <expr>" */
   128888     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
   128889     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
   128890   } u;
   128891   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
   128892   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
   128893 };
   128894 
   128895 /*
   128896 ** Allowed values of WhereTerm.wtFlags
   128897 */
   128898 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
   128899 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
   128900 #define TERM_CODED      0x04   /* This term is already coded */
   128901 #define TERM_COPIED     0x08   /* Has a child */
   128902 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
   128903 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
   128904 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
   128905 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   128906 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
   128907 #else
   128908 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
   128909 #endif
   128910 #define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
   128911 #define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
   128912 #define TERM_LIKE       0x400  /* The original LIKE operator */
   128913 #define TERM_IS         0x800  /* Term.pExpr is an IS operator */
   128914 #define TERM_VARSELECT  0x1000 /* Term.pExpr contains a correlated sub-query */
   128915 
   128916 /*
   128917 ** An instance of the WhereScan object is used as an iterator for locating
   128918 ** terms in the WHERE clause that are useful to the query planner.
   128919 */
   128920 struct WhereScan {
   128921   WhereClause *pOrigWC;      /* Original, innermost WhereClause */
   128922   WhereClause *pWC;          /* WhereClause currently being scanned */
   128923   const char *zCollName;     /* Required collating sequence, if not NULL */
   128924   Expr *pIdxExpr;            /* Search for this index expression */
   128925   char idxaff;               /* Must match this affinity, if zCollName!=NULL */
   128926   unsigned char nEquiv;      /* Number of entries in aEquiv[] */
   128927   unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
   128928   u32 opMask;                /* Acceptable operators */
   128929   int k;                     /* Resume scanning at this->pWC->a[this->k] */
   128930   int aiCur[11];             /* Cursors in the equivalence class */
   128931   i16 aiColumn[11];          /* Corresponding column number in the eq-class */
   128932 };
   128933 
   128934 /*
   128935 ** An instance of the following structure holds all information about a
   128936 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
   128937 **
   128938 ** Explanation of pOuter:  For a WHERE clause of the form
   128939 **
   128940 **           a AND ((b AND c) OR (d AND e)) AND f
   128941 **
   128942 ** There are separate WhereClause objects for the whole clause and for
   128943 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
   128944 ** subclauses points to the WhereClause object for the whole clause.
   128945 */
   128946 struct WhereClause {
   128947   WhereInfo *pWInfo;       /* WHERE clause processing context */
   128948   WhereClause *pOuter;     /* Outer conjunction */
   128949   u8 op;                   /* Split operator.  TK_AND or TK_OR */
   128950   int nTerm;               /* Number of terms */
   128951   int nSlot;               /* Number of entries in a[] */
   128952   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
   128953 #if defined(SQLITE_SMALL_STACK)
   128954   WhereTerm aStatic[1];    /* Initial static space for a[] */
   128955 #else
   128956   WhereTerm aStatic[8];    /* Initial static space for a[] */
   128957 #endif
   128958 };
   128959 
   128960 /*
   128961 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
   128962 ** a dynamically allocated instance of the following structure.
   128963 */
   128964 struct WhereOrInfo {
   128965   WhereClause wc;          /* Decomposition into subterms */
   128966   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
   128967 };
   128968 
   128969 /*
   128970 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
   128971 ** a dynamically allocated instance of the following structure.
   128972 */
   128973 struct WhereAndInfo {
   128974   WhereClause wc;          /* The subexpression broken out */
   128975 };
   128976 
   128977 /*
   128978 ** An instance of the following structure keeps track of a mapping
   128979 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
   128980 **
   128981 ** The VDBE cursor numbers are small integers contained in
   128982 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
   128983 ** clause, the cursor numbers might not begin with 0 and they might
   128984 ** contain gaps in the numbering sequence.  But we want to make maximum
   128985 ** use of the bits in our bitmasks.  This structure provides a mapping
   128986 ** from the sparse cursor numbers into consecutive integers beginning
   128987 ** with 0.
   128988 **
   128989 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
   128990 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
   128991 **
   128992 ** For example, if the WHERE clause expression used these VDBE
   128993 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
   128994 ** would map those cursor numbers into bits 0 through 5.
   128995 **
   128996 ** Note that the mapping is not necessarily ordered.  In the example
   128997 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
   128998 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
   128999 ** does not really matter.  What is important is that sparse cursor
   129000 ** numbers all get mapped into bit numbers that begin with 0 and contain
   129001 ** no gaps.
   129002 */
   129003 struct WhereMaskSet {
   129004   int bVarSelect;               /* Used by sqlite3WhereExprUsage() */
   129005   int n;                        /* Number of assigned cursor values */
   129006   int ix[BMS];                  /* Cursor assigned to each bit */
   129007 };
   129008 
   129009 /*
   129010 ** Initialize a WhereMaskSet object
   129011 */
   129012 #define initMaskSet(P)  (P)->n=0
   129013 
   129014 /*
   129015 ** This object is a convenience wrapper holding all information needed
   129016 ** to construct WhereLoop objects for a particular query.
   129017 */
   129018 struct WhereLoopBuilder {
   129019   WhereInfo *pWInfo;        /* Information about this WHERE */
   129020   WhereClause *pWC;         /* WHERE clause terms */
   129021   ExprList *pOrderBy;       /* ORDER BY clause */
   129022   WhereLoop *pNew;          /* Template WhereLoop */
   129023   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
   129024 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   129025   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
   129026   int nRecValid;            /* Number of valid fields currently in pRec */
   129027 #endif
   129028   unsigned int bldFlags;    /* SQLITE_BLDF_* flags */
   129029 };
   129030 
   129031 /* Allowed values for WhereLoopBuider.bldFlags */
   129032 #define SQLITE_BLDF_INDEXED  0x0001   /* An index is used */
   129033 #define SQLITE_BLDF_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
   129034 
   129035 /*
   129036 ** The WHERE clause processing routine has two halves.  The
   129037 ** first part does the start of the WHERE loop and the second
   129038 ** half does the tail of the WHERE loop.  An instance of
   129039 ** this structure is returned by the first half and passed
   129040 ** into the second half to give some continuity.
   129041 **
   129042 ** An instance of this object holds the complete state of the query
   129043 ** planner.
   129044 */
   129045 struct WhereInfo {
   129046   Parse *pParse;            /* Parsing and code generating context */
   129047   SrcList *pTabList;        /* List of tables in the join */
   129048   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
   129049   ExprList *pResultSet;     /* Result set of the query */
   129050   Expr *pWhere;             /* The complete WHERE clause */
   129051   LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
   129052   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
   129053   int iContinue;            /* Jump here to continue with next record */
   129054   int iBreak;               /* Jump here to break out of the loop */
   129055   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
   129056   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
   129057   u8 nLevel;                /* Number of nested loop */
   129058   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
   129059   u8 sorted;                /* True if really sorted (not just grouped) */
   129060   u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
   129061   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
   129062   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
   129063   u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
   129064   int iTop;                 /* The very beginning of the WHERE loop */
   129065   WhereLoop *pLoops;        /* List of all WhereLoop objects */
   129066   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
   129067   LogEst nRowOut;           /* Estimated number of output rows */
   129068   WhereClause sWC;          /* Decomposition of the WHERE clause */
   129069   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
   129070   WhereLevel a[1];          /* Information about each nest loop in WHERE */
   129071 };
   129072 
   129073 /*
   129074 ** Private interfaces - callable only by other where.c routines.
   129075 **
   129076 ** where.c:
   129077 */
   129078 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
   129079 #ifdef WHERETRACE_ENABLED
   129080 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
   129081 #endif
   129082 SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
   129083   WhereClause *pWC,     /* The WHERE clause to be searched */
   129084   int iCur,             /* Cursor number of LHS */
   129085   int iColumn,          /* Column number of LHS */
   129086   Bitmask notReady,     /* RHS must not overlap with this mask */
   129087   u32 op,               /* Mask of WO_xx values describing operator */
   129088   Index *pIdx           /* Must be compatible with this index, if not NULL */
   129089 );
   129090 
   129091 /* wherecode.c: */
   129092 #ifndef SQLITE_OMIT_EXPLAIN
   129093 SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
   129094   Parse *pParse,                  /* Parse context */
   129095   SrcList *pTabList,              /* Table list this loop refers to */
   129096   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   129097   int iLevel,                     /* Value for "level" column of output */
   129098   int iFrom,                      /* Value for "from" column of output */
   129099   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
   129100 );
   129101 #else
   129102 # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
   129103 #endif /* SQLITE_OMIT_EXPLAIN */
   129104 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   129105 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
   129106   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
   129107   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
   129108   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
   129109   int addrExplain                 /* Address of OP_Explain (or 0) */
   129110 );
   129111 #else
   129112 # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
   129113 #endif
   129114 SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
   129115   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   129116   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   129117   Bitmask notReady     /* Which tables are currently available */
   129118 );
   129119 
   129120 /* whereexpr.c: */
   129121 SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
   129122 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
   129123 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
   129124 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
   129125 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
   129126 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
   129127 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
   129128 
   129129 
   129130 
   129131 
   129132 
   129133 /*
   129134 ** Bitmasks for the operators on WhereTerm objects.  These are all
   129135 ** operators that are of interest to the query planner.  An
   129136 ** OR-ed combination of these values can be used when searching for
   129137 ** particular WhereTerms within a WhereClause.
   129138 **
   129139 ** Value constraints:
   129140 **     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
   129141 **     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
   129142 **     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
   129143 **     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
   129144 **     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
   129145 */
   129146 #define WO_IN     0x0001
   129147 #define WO_EQ     0x0002
   129148 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
   129149 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
   129150 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
   129151 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
   129152 #define WO_AUX    0x0040       /* Op useful to virtual tables only */
   129153 #define WO_IS     0x0080
   129154 #define WO_ISNULL 0x0100
   129155 #define WO_OR     0x0200       /* Two or more OR-connected terms */
   129156 #define WO_AND    0x0400       /* Two or more AND-connected terms */
   129157 #define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
   129158 #define WO_NOOP   0x1000       /* This term does not restrict search space */
   129159 
   129160 #define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
   129161 #define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
   129162 
   129163 /*
   129164 ** These are definitions of bits in the WhereLoop.wsFlags field.
   129165 ** The particular combination of bits in each WhereLoop help to
   129166 ** determine the algorithm that WhereLoop represents.
   129167 */
   129168 #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
   129169 #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
   129170 #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
   129171 #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
   129172 #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
   129173 #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
   129174 #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
   129175 #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
   129176 #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
   129177 #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
   129178 #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
   129179 #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
   129180 #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
   129181 #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
   129182 #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
   129183 #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
   129184 #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
   129185 #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
   129186 #define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
   129187 
   129188 /************** End of whereInt.h ********************************************/
   129189 /************** Continuing where we left off in wherecode.c ******************/
   129190 
   129191 #ifndef SQLITE_OMIT_EXPLAIN
   129192 
   129193 /*
   129194 ** Return the name of the i-th column of the pIdx index.
   129195 */
   129196 static const char *explainIndexColumnName(Index *pIdx, int i){
   129197   i = pIdx->aiColumn[i];
   129198   if( i==XN_EXPR ) return "<expr>";
   129199   if( i==XN_ROWID ) return "rowid";
   129200   return pIdx->pTable->aCol[i].zName;
   129201 }
   129202 
   129203 /*
   129204 ** This routine is a helper for explainIndexRange() below
   129205 **
   129206 ** pStr holds the text of an expression that we are building up one term
   129207 ** at a time.  This routine adds a new term to the end of the expression.
   129208 ** Terms are separated by AND so add the "AND" text for second and subsequent
   129209 ** terms only.
   129210 */
   129211 static void explainAppendTerm(
   129212   StrAccum *pStr,             /* The text expression being built */
   129213   Index *pIdx,                /* Index to read column names from */
   129214   int nTerm,                  /* Number of terms */
   129215   int iTerm,                  /* Zero-based index of first term. */
   129216   int bAnd,                   /* Non-zero to append " AND " */
   129217   const char *zOp             /* Name of the operator */
   129218 ){
   129219   int i;
   129220 
   129221   assert( nTerm>=1 );
   129222   if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
   129223 
   129224   if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
   129225   for(i=0; i<nTerm; i++){
   129226     if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
   129227     sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
   129228   }
   129229   if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
   129230 
   129231   sqlite3StrAccumAppend(pStr, zOp, 1);
   129232 
   129233   if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
   129234   for(i=0; i<nTerm; i++){
   129235     if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
   129236     sqlite3StrAccumAppend(pStr, "?", 1);
   129237   }
   129238   if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
   129239 }
   129240 
   129241 /*
   129242 ** Argument pLevel describes a strategy for scanning table pTab. This
   129243 ** function appends text to pStr that describes the subset of table
   129244 ** rows scanned by the strategy in the form of an SQL expression.
   129245 **
   129246 ** For example, if the query:
   129247 **
   129248 **   SELECT * FROM t1 WHERE a=1 AND b>2;
   129249 **
   129250 ** is run and there is an index on (a, b), then this function returns a
   129251 ** string similar to:
   129252 **
   129253 **   "a=? AND b>?"
   129254 */
   129255 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
   129256   Index *pIndex = pLoop->u.btree.pIndex;
   129257   u16 nEq = pLoop->u.btree.nEq;
   129258   u16 nSkip = pLoop->nSkip;
   129259   int i, j;
   129260 
   129261   if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
   129262   sqlite3StrAccumAppend(pStr, " (", 2);
   129263   for(i=0; i<nEq; i++){
   129264     const char *z = explainIndexColumnName(pIndex, i);
   129265     if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
   129266     sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
   129267   }
   129268 
   129269   j = i;
   129270   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
   129271     explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
   129272     i = 1;
   129273   }
   129274   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
   129275     explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
   129276   }
   129277   sqlite3StrAccumAppend(pStr, ")", 1);
   129278 }
   129279 
   129280 /*
   129281 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
   129282 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
   129283 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
   129284 ** is added to the output to describe the table scan strategy in pLevel.
   129285 **
   129286 ** If an OP_Explain opcode is added to the VM, its address is returned.
   129287 ** Otherwise, if no OP_Explain is coded, zero is returned.
   129288 */
   129289 SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
   129290   Parse *pParse,                  /* Parse context */
   129291   SrcList *pTabList,              /* Table list this loop refers to */
   129292   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   129293   int iLevel,                     /* Value for "level" column of output */
   129294   int iFrom,                      /* Value for "from" column of output */
   129295   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
   129296 ){
   129297   int ret = 0;
   129298 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
   129299   if( sqlite3ParseToplevel(pParse)->explain==2 )
   129300 #endif
   129301   {
   129302     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
   129303     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
   129304     sqlite3 *db = pParse->db;     /* Database handle */
   129305     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
   129306     int isSearch;                 /* True for a SEARCH. False for SCAN. */
   129307     WhereLoop *pLoop;             /* The controlling WhereLoop object */
   129308     u32 flags;                    /* Flags that describe this loop */
   129309     char *zMsg;                   /* Text to add to EQP output */
   129310     StrAccum str;                 /* EQP output string */
   129311     char zBuf[100];               /* Initial space for EQP output string */
   129312 
   129313     pLoop = pLevel->pWLoop;
   129314     flags = pLoop->wsFlags;
   129315     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
   129316 
   129317     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
   129318             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
   129319             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
   129320 
   129321     sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
   129322     sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
   129323     if( pItem->pSelect ){
   129324       sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
   129325     }else{
   129326       sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
   129327     }
   129328 
   129329     if( pItem->zAlias ){
   129330       sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
   129331     }
   129332     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
   129333       const char *zFmt = 0;
   129334       Index *pIdx;
   129335 
   129336       assert( pLoop->u.btree.pIndex!=0 );
   129337       pIdx = pLoop->u.btree.pIndex;
   129338       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
   129339       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
   129340         if( isSearch ){
   129341           zFmt = "PRIMARY KEY";
   129342         }
   129343       }else if( flags & WHERE_PARTIALIDX ){
   129344         zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
   129345       }else if( flags & WHERE_AUTO_INDEX ){
   129346         zFmt = "AUTOMATIC COVERING INDEX";
   129347       }else if( flags & WHERE_IDX_ONLY ){
   129348         zFmt = "COVERING INDEX %s";
   129349       }else{
   129350         zFmt = "INDEX %s";
   129351       }
   129352       if( zFmt ){
   129353         sqlite3StrAccumAppend(&str, " USING ", 7);
   129354         sqlite3XPrintf(&str, zFmt, pIdx->zName);
   129355         explainIndexRange(&str, pLoop);
   129356       }
   129357     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
   129358       const char *zRangeOp;
   129359       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
   129360         zRangeOp = "=";
   129361       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
   129362         zRangeOp = ">? AND rowid<";
   129363       }else if( flags&WHERE_BTM_LIMIT ){
   129364         zRangeOp = ">";
   129365       }else{
   129366         assert( flags&WHERE_TOP_LIMIT);
   129367         zRangeOp = "<";
   129368       }
   129369       sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
   129370     }
   129371 #ifndef SQLITE_OMIT_VIRTUALTABLE
   129372     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
   129373       sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
   129374                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
   129375     }
   129376 #endif
   129377 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
   129378     if( pLoop->nOut>=10 ){
   129379       sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
   129380     }else{
   129381       sqlite3StrAccumAppend(&str, " (~1 row)", 9);
   129382     }
   129383 #endif
   129384     zMsg = sqlite3StrAccumFinish(&str);
   129385     ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
   129386   }
   129387   return ret;
   129388 }
   129389 #endif /* SQLITE_OMIT_EXPLAIN */
   129390 
   129391 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   129392 /*
   129393 ** Configure the VM passed as the first argument with an
   129394 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
   129395 ** implement level pLvl. Argument pSrclist is a pointer to the FROM
   129396 ** clause that the scan reads data from.
   129397 **
   129398 ** If argument addrExplain is not 0, it must be the address of an
   129399 ** OP_Explain instruction that describes the same loop.
   129400 */
   129401 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
   129402   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
   129403   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
   129404   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
   129405   int addrExplain                 /* Address of OP_Explain (or 0) */
   129406 ){
   129407   const char *zObj = 0;
   129408   WhereLoop *pLoop = pLvl->pWLoop;
   129409   if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
   129410     zObj = pLoop->u.btree.pIndex->zName;
   129411   }else{
   129412     zObj = pSrclist->a[pLvl->iFrom].zName;
   129413   }
   129414   sqlite3VdbeScanStatus(
   129415       v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
   129416   );
   129417 }
   129418 #endif
   129419 
   129420 
   129421 /*
   129422 ** Disable a term in the WHERE clause.  Except, do not disable the term
   129423 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
   129424 ** or USING clause of that join.
   129425 **
   129426 ** Consider the term t2.z='ok' in the following queries:
   129427 **
   129428 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
   129429 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
   129430 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
   129431 **
   129432 ** The t2.z='ok' is disabled in the in (2) because it originates
   129433 ** in the ON clause.  The term is disabled in (3) because it is not part
   129434 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
   129435 **
   129436 ** Disabling a term causes that term to not be tested in the inner loop
   129437 ** of the join.  Disabling is an optimization.  When terms are satisfied
   129438 ** by indices, we disable them to prevent redundant tests in the inner
   129439 ** loop.  We would get the correct results if nothing were ever disabled,
   129440 ** but joins might run a little slower.  The trick is to disable as much
   129441 ** as we can without disabling too much.  If we disabled in (1), we'd get
   129442 ** the wrong answer.  See ticket #813.
   129443 **
   129444 ** If all the children of a term are disabled, then that term is also
   129445 ** automatically disabled.  In this way, terms get disabled if derived
   129446 ** virtual terms are tested first.  For example:
   129447 **
   129448 **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
   129449 **      \___________/     \______/     \_____/
   129450 **         parent          child1       child2
   129451 **
   129452 ** Only the parent term was in the original WHERE clause.  The child1
   129453 ** and child2 terms were added by the LIKE optimization.  If both of
   129454 ** the virtual child terms are valid, then testing of the parent can be
   129455 ** skipped.
   129456 **
   129457 ** Usually the parent term is marked as TERM_CODED.  But if the parent
   129458 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
   129459 ** The TERM_LIKECOND marking indicates that the term should be coded inside
   129460 ** a conditional such that is only evaluated on the second pass of a
   129461 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
   129462 */
   129463 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
   129464   int nLoop = 0;
   129465   assert( pTerm!=0 );
   129466   while( (pTerm->wtFlags & TERM_CODED)==0
   129467       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   129468       && (pLevel->notReady & pTerm->prereqAll)==0
   129469   ){
   129470     if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
   129471       pTerm->wtFlags |= TERM_LIKECOND;
   129472     }else{
   129473       pTerm->wtFlags |= TERM_CODED;
   129474     }
   129475     if( pTerm->iParent<0 ) break;
   129476     pTerm = &pTerm->pWC->a[pTerm->iParent];
   129477     assert( pTerm!=0 );
   129478     pTerm->nChild--;
   129479     if( pTerm->nChild!=0 ) break;
   129480     nLoop++;
   129481   }
   129482 }
   129483 
   129484 /*
   129485 ** Code an OP_Affinity opcode to apply the column affinity string zAff
   129486 ** to the n registers starting at base.
   129487 **
   129488 ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
   129489 ** beginning and end of zAff are ignored.  If all entries in zAff are
   129490 ** SQLITE_AFF_BLOB, then no code gets generated.
   129491 **
   129492 ** This routine makes its own copy of zAff so that the caller is free
   129493 ** to modify zAff after this routine returns.
   129494 */
   129495 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
   129496   Vdbe *v = pParse->pVdbe;
   129497   if( zAff==0 ){
   129498     assert( pParse->db->mallocFailed );
   129499     return;
   129500   }
   129501   assert( v!=0 );
   129502 
   129503   /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
   129504   ** and end of the affinity string.
   129505   */
   129506   while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
   129507     n--;
   129508     base++;
   129509     zAff++;
   129510   }
   129511   while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
   129512     n--;
   129513   }
   129514 
   129515   /* Code the OP_Affinity opcode if there is anything left to do. */
   129516   if( n>0 ){
   129517     sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
   129518     sqlite3ExprCacheAffinityChange(pParse, base, n);
   129519   }
   129520 }
   129521 
   129522 /*
   129523 ** Expression pRight, which is the RHS of a comparison operation, is
   129524 ** either a vector of n elements or, if n==1, a scalar expression.
   129525 ** Before the comparison operation, affinity zAff is to be applied
   129526 ** to the pRight values. This function modifies characters within the
   129527 ** affinity string to SQLITE_AFF_BLOB if either:
   129528 **
   129529 **   * the comparison will be performed with no affinity, or
   129530 **   * the affinity change in zAff is guaranteed not to change the value.
   129531 */
   129532 static void updateRangeAffinityStr(
   129533   Expr *pRight,                   /* RHS of comparison */
   129534   int n,                          /* Number of vector elements in comparison */
   129535   char *zAff                      /* Affinity string to modify */
   129536 ){
   129537   int i;
   129538   for(i=0; i<n; i++){
   129539     Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
   129540     if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
   129541      || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
   129542     ){
   129543       zAff[i] = SQLITE_AFF_BLOB;
   129544     }
   129545   }
   129546 }
   129547 
   129548 
   129549 /*
   129550 ** pX is an expression of the form:  (vector) IN (SELECT ...)
   129551 ** In other words, it is a vector IN operator with a SELECT clause on the
   129552 ** LHS.  But not all terms in the vector are indexable and the terms might
   129553 ** not be in the correct order for indexing.
   129554 **
   129555 ** This routine makes a copy of the input pX expression and then adjusts
   129556 ** the vector on the LHS with corresponding changes to the SELECT so that
   129557 ** the vector contains only index terms and those terms are in the correct
   129558 ** order.  The modified IN expression is returned.  The caller is responsible
   129559 ** for deleting the returned expression.
   129560 **
   129561 ** Example:
   129562 **
   129563 **    CREATE TABLE t1(a,b,c,d,e,f);
   129564 **    CREATE INDEX t1x1 ON t1(e,c);
   129565 **    SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
   129566 **                           \_______________________________________/
   129567 **                                     The pX expression
   129568 **
   129569 ** Since only columns e and c can be used with the index, in that order,
   129570 ** the modified IN expression that is returned will be:
   129571 **
   129572 **        (e,c) IN (SELECT z,x FROM t2)
   129573 **
   129574 ** The reduced pX is different from the original (obviously) and thus is
   129575 ** only used for indexing, to improve performance.  The original unaltered
   129576 ** IN expression must also be run on each output row for correctness.
   129577 */
   129578 static Expr *removeUnindexableInClauseTerms(
   129579   Parse *pParse,        /* The parsing context */
   129580   int iEq,              /* Look at loop terms starting here */
   129581   WhereLoop *pLoop,     /* The current loop */
   129582   Expr *pX              /* The IN expression to be reduced */
   129583 ){
   129584   sqlite3 *db = pParse->db;
   129585   Expr *pNew = sqlite3ExprDup(db, pX, 0);
   129586   if( db->mallocFailed==0 ){
   129587     ExprList *pOrigRhs = pNew->x.pSelect->pEList;  /* Original unmodified RHS */
   129588     ExprList *pOrigLhs = pNew->pLeft->x.pList;     /* Original unmodified LHS */
   129589     ExprList *pRhs = 0;         /* New RHS after modifications */
   129590     ExprList *pLhs = 0;         /* New LHS after mods */
   129591     int i;                      /* Loop counter */
   129592     Select *pSelect;            /* Pointer to the SELECT on the RHS */
   129593 
   129594     for(i=iEq; i<pLoop->nLTerm; i++){
   129595       if( pLoop->aLTerm[i]->pExpr==pX ){
   129596         int iField = pLoop->aLTerm[i]->iField - 1;
   129597         assert( pOrigRhs->a[iField].pExpr!=0 );
   129598         pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
   129599         pOrigRhs->a[iField].pExpr = 0;
   129600         assert( pOrigLhs->a[iField].pExpr!=0 );
   129601         pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
   129602         pOrigLhs->a[iField].pExpr = 0;
   129603       }
   129604     }
   129605     sqlite3ExprListDelete(db, pOrigRhs);
   129606     sqlite3ExprListDelete(db, pOrigLhs);
   129607     pNew->pLeft->x.pList = pLhs;
   129608     pNew->x.pSelect->pEList = pRhs;
   129609     if( pLhs && pLhs->nExpr==1 ){
   129610       /* Take care here not to generate a TK_VECTOR containing only a
   129611       ** single value. Since the parser never creates such a vector, some
   129612       ** of the subroutines do not handle this case.  */
   129613       Expr *p = pLhs->a[0].pExpr;
   129614       pLhs->a[0].pExpr = 0;
   129615       sqlite3ExprDelete(db, pNew->pLeft);
   129616       pNew->pLeft = p;
   129617     }
   129618     pSelect = pNew->x.pSelect;
   129619     if( pSelect->pOrderBy ){
   129620       /* If the SELECT statement has an ORDER BY clause, zero the
   129621       ** iOrderByCol variables. These are set to non-zero when an
   129622       ** ORDER BY term exactly matches one of the terms of the
   129623       ** result-set. Since the result-set of the SELECT statement may
   129624       ** have been modified or reordered, these variables are no longer
   129625       ** set correctly.  Since setting them is just an optimization,
   129626       ** it's easiest just to zero them here.  */
   129627       ExprList *pOrderBy = pSelect->pOrderBy;
   129628       for(i=0; i<pOrderBy->nExpr; i++){
   129629         pOrderBy->a[i].u.x.iOrderByCol = 0;
   129630       }
   129631     }
   129632 
   129633 #if 0
   129634     printf("For indexing, change the IN expr:\n");
   129635     sqlite3TreeViewExpr(0, pX, 0);
   129636     printf("Into:\n");
   129637     sqlite3TreeViewExpr(0, pNew, 0);
   129638 #endif
   129639   }
   129640   return pNew;
   129641 }
   129642 
   129643 
   129644 /*
   129645 ** Generate code for a single equality term of the WHERE clause.  An equality
   129646 ** term can be either X=expr or X IN (...).   pTerm is the term to be
   129647 ** coded.
   129648 **
   129649 ** The current value for the constraint is left in a register, the index
   129650 ** of which is returned.  An attempt is made store the result in iTarget but
   129651 ** this is only guaranteed for TK_ISNULL and TK_IN constraints.  If the
   129652 ** constraint is a TK_EQ or TK_IS, then the current value might be left in
   129653 ** some other register and it is the caller's responsibility to compensate.
   129654 **
   129655 ** For a constraint of the form X=expr, the expression is evaluated in
   129656 ** straight-line code.  For constraints of the form X IN (...)
   129657 ** this routine sets up a loop that will iterate over all values of X.
   129658 */
   129659 static int codeEqualityTerm(
   129660   Parse *pParse,      /* The parsing context */
   129661   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
   129662   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
   129663   int iEq,            /* Index of the equality term within this level */
   129664   int bRev,           /* True for reverse-order IN operations */
   129665   int iTarget         /* Attempt to leave results in this register */
   129666 ){
   129667   Expr *pX = pTerm->pExpr;
   129668   Vdbe *v = pParse->pVdbe;
   129669   int iReg;                  /* Register holding results */
   129670 
   129671   assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
   129672   assert( iTarget>0 );
   129673   if( pX->op==TK_EQ || pX->op==TK_IS ){
   129674     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
   129675   }else if( pX->op==TK_ISNULL ){
   129676     iReg = iTarget;
   129677     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
   129678 #ifndef SQLITE_OMIT_SUBQUERY
   129679   }else{
   129680     int eType = IN_INDEX_NOOP;
   129681     int iTab;
   129682     struct InLoop *pIn;
   129683     WhereLoop *pLoop = pLevel->pWLoop;
   129684     int i;
   129685     int nEq = 0;
   129686     int *aiMap = 0;
   129687 
   129688     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
   129689       && pLoop->u.btree.pIndex!=0
   129690       && pLoop->u.btree.pIndex->aSortOrder[iEq]
   129691     ){
   129692       testcase( iEq==0 );
   129693       testcase( bRev );
   129694       bRev = !bRev;
   129695     }
   129696     assert( pX->op==TK_IN );
   129697     iReg = iTarget;
   129698 
   129699     for(i=0; i<iEq; i++){
   129700       if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
   129701         disableTerm(pLevel, pTerm);
   129702         return iTarget;
   129703       }
   129704     }
   129705     for(i=iEq;i<pLoop->nLTerm; i++){
   129706       assert( pLoop->aLTerm[i]!=0 );
   129707       if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
   129708     }
   129709 
   129710     if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
   129711       eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
   129712     }else{
   129713       sqlite3 *db = pParse->db;
   129714       pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
   129715 
   129716       if( !db->mallocFailed ){
   129717         aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
   129718         eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
   129719         pTerm->pExpr->iTable = pX->iTable;
   129720       }
   129721       sqlite3ExprDelete(db, pX);
   129722       pX = pTerm->pExpr;
   129723     }
   129724 
   129725     if( eType==IN_INDEX_INDEX_DESC ){
   129726       testcase( bRev );
   129727       bRev = !bRev;
   129728     }
   129729     iTab = pX->iTable;
   129730     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
   129731     VdbeCoverageIf(v, bRev);
   129732     VdbeCoverageIf(v, !bRev);
   129733     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
   129734 
   129735     pLoop->wsFlags |= WHERE_IN_ABLE;
   129736     if( pLevel->u.in.nIn==0 ){
   129737       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   129738     }
   129739 
   129740     i = pLevel->u.in.nIn;
   129741     pLevel->u.in.nIn += nEq;
   129742     pLevel->u.in.aInLoop =
   129743        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
   129744                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
   129745     pIn = pLevel->u.in.aInLoop;
   129746     if( pIn ){
   129747       int iMap = 0;               /* Index in aiMap[] */
   129748       pIn += i;
   129749       for(i=iEq;i<pLoop->nLTerm; i++){
   129750         if( pLoop->aLTerm[i]->pExpr==pX ){
   129751           int iOut = iReg + i - iEq;
   129752           if( eType==IN_INDEX_ROWID ){
   129753             testcase( nEq>1 );  /* Happens with a UNIQUE index on ROWID */
   129754             pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
   129755           }else{
   129756             int iCol = aiMap ? aiMap[iMap++] : 0;
   129757             pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
   129758           }
   129759           sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
   129760           if( i==iEq ){
   129761             pIn->iCur = iTab;
   129762             pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
   129763           }else{
   129764             pIn->eEndLoopOp = OP_Noop;
   129765           }
   129766           pIn++;
   129767         }
   129768       }
   129769     }else{
   129770       pLevel->u.in.nIn = 0;
   129771     }
   129772     sqlite3DbFree(pParse->db, aiMap);
   129773 #endif
   129774   }
   129775   disableTerm(pLevel, pTerm);
   129776   return iReg;
   129777 }
   129778 
   129779 /*
   129780 ** Generate code that will evaluate all == and IN constraints for an
   129781 ** index scan.
   129782 **
   129783 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
   129784 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
   129785 ** The index has as many as three equality constraints, but in this
   129786 ** example, the third "c" value is an inequality.  So only two
   129787 ** constraints are coded.  This routine will generate code to evaluate
   129788 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
   129789 ** in consecutive registers and the index of the first register is returned.
   129790 **
   129791 ** In the example above nEq==2.  But this subroutine works for any value
   129792 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
   129793 ** The only thing it does is allocate the pLevel->iMem memory cell and
   129794 ** compute the affinity string.
   129795 **
   129796 ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
   129797 ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
   129798 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
   129799 ** occurs after the nEq quality constraints.
   129800 **
   129801 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
   129802 ** the index of the first memory cell in that range. The code that
   129803 ** calls this routine will use that memory range to store keys for
   129804 ** start and termination conditions of the loop.
   129805 ** key value of the loop.  If one or more IN operators appear, then
   129806 ** this routine allocates an additional nEq memory cells for internal
   129807 ** use.
   129808 **
   129809 ** Before returning, *pzAff is set to point to a buffer containing a
   129810 ** copy of the column affinity string of the index allocated using
   129811 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
   129812 ** with equality constraints that use BLOB or NONE affinity are set to
   129813 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
   129814 **
   129815 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
   129816 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
   129817 **
   129818 ** In the example above, the index on t1(a) has TEXT affinity. But since
   129819 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
   129820 ** no conversion should be attempted before using a t2.b value as part of
   129821 ** a key to search the index. Hence the first byte in the returned affinity
   129822 ** string in this example would be set to SQLITE_AFF_BLOB.
   129823 */
   129824 static int codeAllEqualityTerms(
   129825   Parse *pParse,        /* Parsing context */
   129826   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
   129827   int bRev,             /* Reverse the order of IN operators */
   129828   int nExtraReg,        /* Number of extra registers to allocate */
   129829   char **pzAff          /* OUT: Set to point to affinity string */
   129830 ){
   129831   u16 nEq;                      /* The number of == or IN constraints to code */
   129832   u16 nSkip;                    /* Number of left-most columns to skip */
   129833   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
   129834   Index *pIdx;                  /* The index being used for this loop */
   129835   WhereTerm *pTerm;             /* A single constraint term */
   129836   WhereLoop *pLoop;             /* The WhereLoop object */
   129837   int j;                        /* Loop counter */
   129838   int regBase;                  /* Base register */
   129839   int nReg;                     /* Number of registers to allocate */
   129840   char *zAff;                   /* Affinity string to return */
   129841 
   129842   /* This module is only called on query plans that use an index. */
   129843   pLoop = pLevel->pWLoop;
   129844   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
   129845   nEq = pLoop->u.btree.nEq;
   129846   nSkip = pLoop->nSkip;
   129847   pIdx = pLoop->u.btree.pIndex;
   129848   assert( pIdx!=0 );
   129849 
   129850   /* Figure out how many memory cells we will need then allocate them.
   129851   */
   129852   regBase = pParse->nMem + 1;
   129853   nReg = pLoop->u.btree.nEq + nExtraReg;
   129854   pParse->nMem += nReg;
   129855 
   129856   zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
   129857   assert( zAff!=0 || pParse->db->mallocFailed );
   129858 
   129859   if( nSkip ){
   129860     int iIdxCur = pLevel->iIdxCur;
   129861     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
   129862     VdbeCoverageIf(v, bRev==0);
   129863     VdbeCoverageIf(v, bRev!=0);
   129864     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
   129865     j = sqlite3VdbeAddOp0(v, OP_Goto);
   129866     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
   129867                             iIdxCur, 0, regBase, nSkip);
   129868     VdbeCoverageIf(v, bRev==0);
   129869     VdbeCoverageIf(v, bRev!=0);
   129870     sqlite3VdbeJumpHere(v, j);
   129871     for(j=0; j<nSkip; j++){
   129872       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
   129873       testcase( pIdx->aiColumn[j]==XN_EXPR );
   129874       VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
   129875     }
   129876   }
   129877 
   129878   /* Evaluate the equality constraints
   129879   */
   129880   assert( zAff==0 || (int)strlen(zAff)>=nEq );
   129881   for(j=nSkip; j<nEq; j++){
   129882     int r1;
   129883     pTerm = pLoop->aLTerm[j];
   129884     assert( pTerm!=0 );
   129885     /* The following testcase is true for indices with redundant columns.
   129886     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
   129887     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
   129888     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   129889     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
   129890     if( r1!=regBase+j ){
   129891       if( nReg==1 ){
   129892         sqlite3ReleaseTempReg(pParse, regBase);
   129893         regBase = r1;
   129894       }else{
   129895         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
   129896       }
   129897     }
   129898     if( pTerm->eOperator & WO_IN ){
   129899       if( pTerm->pExpr->flags & EP_xIsSelect ){
   129900         /* No affinity ever needs to be (or should be) applied to a value
   129901         ** from the RHS of an "? IN (SELECT ...)" expression. The
   129902         ** sqlite3FindInIndex() routine has already ensured that the
   129903         ** affinity of the comparison has been applied to the value.  */
   129904         if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
   129905       }
   129906     }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
   129907       Expr *pRight = pTerm->pExpr->pRight;
   129908       if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
   129909         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
   129910         VdbeCoverage(v);
   129911       }
   129912       if( zAff ){
   129913         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
   129914           zAff[j] = SQLITE_AFF_BLOB;
   129915         }
   129916         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
   129917           zAff[j] = SQLITE_AFF_BLOB;
   129918         }
   129919       }
   129920     }
   129921   }
   129922   *pzAff = zAff;
   129923   return regBase;
   129924 }
   129925 
   129926 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   129927 /*
   129928 ** If the most recently coded instruction is a constant range constraint
   129929 ** (a string literal) that originated from the LIKE optimization, then
   129930 ** set P3 and P5 on the OP_String opcode so that the string will be cast
   129931 ** to a BLOB at appropriate times.
   129932 **
   129933 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
   129934 ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
   129935 ** scan loop run twice, once for strings and a second time for BLOBs.
   129936 ** The OP_String opcodes on the second pass convert the upper and lower
   129937 ** bound string constants to blobs.  This routine makes the necessary changes
   129938 ** to the OP_String opcodes for that to happen.
   129939 **
   129940 ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
   129941 ** only the one pass through the string space is required, so this routine
   129942 ** becomes a no-op.
   129943 */
   129944 static void whereLikeOptimizationStringFixup(
   129945   Vdbe *v,                /* prepared statement under construction */
   129946   WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
   129947   WhereTerm *pTerm        /* The upper or lower bound just coded */
   129948 ){
   129949   if( pTerm->wtFlags & TERM_LIKEOPT ){
   129950     VdbeOp *pOp;
   129951     assert( pLevel->iLikeRepCntr>0 );
   129952     pOp = sqlite3VdbeGetOp(v, -1);
   129953     assert( pOp!=0 );
   129954     assert( pOp->opcode==OP_String8
   129955             || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
   129956     pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
   129957     pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
   129958   }
   129959 }
   129960 #else
   129961 # define whereLikeOptimizationStringFixup(A,B,C)
   129962 #endif
   129963 
   129964 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   129965 /*
   129966 ** Information is passed from codeCursorHint() down to individual nodes of
   129967 ** the expression tree (by sqlite3WalkExpr()) using an instance of this
   129968 ** structure.
   129969 */
   129970 struct CCurHint {
   129971   int iTabCur;    /* Cursor for the main table */
   129972   int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
   129973   Index *pIdx;    /* The index used to access the table */
   129974 };
   129975 
   129976 /*
   129977 ** This function is called for every node of an expression that is a candidate
   129978 ** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
   129979 ** the table CCurHint.iTabCur, verify that the same column can be
   129980 ** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
   129981 */
   129982 static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
   129983   struct CCurHint *pHint = pWalker->u.pCCurHint;
   129984   assert( pHint->pIdx!=0 );
   129985   if( pExpr->op==TK_COLUMN
   129986    && pExpr->iTable==pHint->iTabCur
   129987    && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
   129988   ){
   129989     pWalker->eCode = 1;
   129990   }
   129991   return WRC_Continue;
   129992 }
   129993 
   129994 /*
   129995 ** Test whether or not expression pExpr, which was part of a WHERE clause,
   129996 ** should be included in the cursor-hint for a table that is on the rhs
   129997 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
   129998 ** expression is not suitable.
   129999 **
   130000 ** An expression is unsuitable if it might evaluate to non NULL even if
   130001 ** a TK_COLUMN node that does affect the value of the expression is set
   130002 ** to NULL. For example:
   130003 **
   130004 **   col IS NULL
   130005 **   col IS NOT NULL
   130006 **   coalesce(col, 1)
   130007 **   CASE WHEN col THEN 0 ELSE 1 END
   130008 */
   130009 static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
   130010   if( pExpr->op==TK_IS
   130011    || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
   130012    || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
   130013   ){
   130014     pWalker->eCode = 1;
   130015   }else if( pExpr->op==TK_FUNCTION ){
   130016     int d1;
   130017     char d2[4];
   130018     if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
   130019       pWalker->eCode = 1;
   130020     }
   130021   }
   130022 
   130023   return WRC_Continue;
   130024 }
   130025 
   130026 
   130027 /*
   130028 ** This function is called on every node of an expression tree used as an
   130029 ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
   130030 ** that accesses any table other than the one identified by
   130031 ** CCurHint.iTabCur, then do the following:
   130032 **
   130033 **   1) allocate a register and code an OP_Column instruction to read
   130034 **      the specified column into the new register, and
   130035 **
   130036 **   2) transform the expression node to a TK_REGISTER node that reads
   130037 **      from the newly populated register.
   130038 **
   130039 ** Also, if the node is a TK_COLUMN that does access the table idenified
   130040 ** by pCCurHint.iTabCur, and an index is being used (which we will
   130041 ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
   130042 ** an access of the index rather than the original table.
   130043 */
   130044 static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
   130045   int rc = WRC_Continue;
   130046   struct CCurHint *pHint = pWalker->u.pCCurHint;
   130047   if( pExpr->op==TK_COLUMN ){
   130048     if( pExpr->iTable!=pHint->iTabCur ){
   130049       Vdbe *v = pWalker->pParse->pVdbe;
   130050       int reg = ++pWalker->pParse->nMem;   /* Register for column value */
   130051       sqlite3ExprCodeGetColumnOfTable(
   130052           v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
   130053       );
   130054       pExpr->op = TK_REGISTER;
   130055       pExpr->iTable = reg;
   130056     }else if( pHint->pIdx!=0 ){
   130057       pExpr->iTable = pHint->iIdxCur;
   130058       pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
   130059       assert( pExpr->iColumn>=0 );
   130060     }
   130061   }else if( pExpr->op==TK_AGG_FUNCTION ){
   130062     /* An aggregate function in the WHERE clause of a query means this must
   130063     ** be a correlated sub-query, and expression pExpr is an aggregate from
   130064     ** the parent context. Do not walk the function arguments in this case.
   130065     **
   130066     ** todo: It should be possible to replace this node with a TK_REGISTER
   130067     ** expression, as the result of the expression must be stored in a
   130068     ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
   130069     rc = WRC_Prune;
   130070   }
   130071   return rc;
   130072 }
   130073 
   130074 /*
   130075 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
   130076 */
   130077 static void codeCursorHint(
   130078   struct SrcList_item *pTabItem,  /* FROM clause item */
   130079   WhereInfo *pWInfo,    /* The where clause */
   130080   WhereLevel *pLevel,   /* Which loop to provide hints for */
   130081   WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
   130082 ){
   130083   Parse *pParse = pWInfo->pParse;
   130084   sqlite3 *db = pParse->db;
   130085   Vdbe *v = pParse->pVdbe;
   130086   Expr *pExpr = 0;
   130087   WhereLoop *pLoop = pLevel->pWLoop;
   130088   int iCur;
   130089   WhereClause *pWC;
   130090   WhereTerm *pTerm;
   130091   int i, j;
   130092   struct CCurHint sHint;
   130093   Walker sWalker;
   130094 
   130095   if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
   130096   iCur = pLevel->iTabCur;
   130097   assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
   130098   sHint.iTabCur = iCur;
   130099   sHint.iIdxCur = pLevel->iIdxCur;
   130100   sHint.pIdx = pLoop->u.btree.pIndex;
   130101   memset(&sWalker, 0, sizeof(sWalker));
   130102   sWalker.pParse = pParse;
   130103   sWalker.u.pCCurHint = &sHint;
   130104   pWC = &pWInfo->sWC;
   130105   for(i=0; i<pWC->nTerm; i++){
   130106     pTerm = &pWC->a[i];
   130107     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   130108     if( pTerm->prereqAll & pLevel->notReady ) continue;
   130109 
   130110     /* Any terms specified as part of the ON(...) clause for any LEFT
   130111     ** JOIN for which the current table is not the rhs are omitted
   130112     ** from the cursor-hint.
   130113     **
   130114     ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
   130115     ** that were specified as part of the WHERE clause must be excluded.
   130116     ** This is to address the following:
   130117     **
   130118     **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
   130119     **
   130120     ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
   130121     ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
   130122     ** pushed down to the cursor, this row is filtered out, causing
   130123     ** SQLite to synthesize a row of NULL values. Which does match the
   130124     ** WHERE clause, and so the query returns a row. Which is incorrect.
   130125     **
   130126     ** For the same reason, WHERE terms such as:
   130127     **
   130128     **   WHERE 1 = (t2.c IS NULL)
   130129     **
   130130     ** are also excluded. See codeCursorHintIsOrFunction() for details.
   130131     */
   130132     if( pTabItem->fg.jointype & JT_LEFT ){
   130133       Expr *pExpr = pTerm->pExpr;
   130134       if( !ExprHasProperty(pExpr, EP_FromJoin)
   130135        || pExpr->iRightJoinTable!=pTabItem->iCursor
   130136       ){
   130137         sWalker.eCode = 0;
   130138         sWalker.xExprCallback = codeCursorHintIsOrFunction;
   130139         sqlite3WalkExpr(&sWalker, pTerm->pExpr);
   130140         if( sWalker.eCode ) continue;
   130141       }
   130142     }else{
   130143       if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
   130144     }
   130145 
   130146     /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
   130147     ** the cursor.  These terms are not needed as hints for a pure range
   130148     ** scan (that has no == terms) so omit them. */
   130149     if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
   130150       for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
   130151       if( j<pLoop->nLTerm ) continue;
   130152     }
   130153 
   130154     /* No subqueries or non-deterministic functions allowed */
   130155     if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
   130156 
   130157     /* For an index scan, make sure referenced columns are actually in
   130158     ** the index. */
   130159     if( sHint.pIdx!=0 ){
   130160       sWalker.eCode = 0;
   130161       sWalker.xExprCallback = codeCursorHintCheckExpr;
   130162       sqlite3WalkExpr(&sWalker, pTerm->pExpr);
   130163       if( sWalker.eCode ) continue;
   130164     }
   130165 
   130166     /* If we survive all prior tests, that means this term is worth hinting */
   130167     pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
   130168   }
   130169   if( pExpr!=0 ){
   130170     sWalker.xExprCallback = codeCursorHintFixExpr;
   130171     sqlite3WalkExpr(&sWalker, pExpr);
   130172     sqlite3VdbeAddOp4(v, OP_CursorHint,
   130173                       (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
   130174                       (const char*)pExpr, P4_EXPR);
   130175   }
   130176 }
   130177 #else
   130178 # define codeCursorHint(A,B,C,D)  /* No-op */
   130179 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
   130180 
   130181 /*
   130182 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
   130183 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
   130184 ** function generates code to do a deferred seek of cursor iCur to the
   130185 ** rowid stored in register iRowid.
   130186 **
   130187 ** Normally, this is just:
   130188 **
   130189 **   OP_DeferredSeek $iCur $iRowid
   130190 **
   130191 ** However, if the scan currently being coded is a branch of an OR-loop and
   130192 ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
   130193 ** is set to iIdxCur and P4 is set to point to an array of integers
   130194 ** containing one entry for each column of the table cursor iCur is open
   130195 ** on. For each table column, if the column is the i'th column of the
   130196 ** index, then the corresponding array entry is set to (i+1). If the column
   130197 ** does not appear in the index at all, the array entry is set to 0.
   130198 */
   130199 static void codeDeferredSeek(
   130200   WhereInfo *pWInfo,              /* Where clause context */
   130201   Index *pIdx,                    /* Index scan is using */
   130202   int iCur,                       /* Cursor for IPK b-tree */
   130203   int iIdxCur                     /* Index cursor */
   130204 ){
   130205   Parse *pParse = pWInfo->pParse; /* Parse context */
   130206   Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
   130207 
   130208   assert( iIdxCur>0 );
   130209   assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
   130210 
   130211   sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
   130212   if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
   130213    && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
   130214   ){
   130215     int i;
   130216     Table *pTab = pIdx->pTable;
   130217     int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
   130218     if( ai ){
   130219       ai[0] = pTab->nCol;
   130220       for(i=0; i<pIdx->nColumn-1; i++){
   130221         assert( pIdx->aiColumn[i]<pTab->nCol );
   130222         if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
   130223       }
   130224       sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
   130225     }
   130226   }
   130227 }
   130228 
   130229 /*
   130230 ** If the expression passed as the second argument is a vector, generate
   130231 ** code to write the first nReg elements of the vector into an array
   130232 ** of registers starting with iReg.
   130233 **
   130234 ** If the expression is not a vector, then nReg must be passed 1. In
   130235 ** this case, generate code to evaluate the expression and leave the
   130236 ** result in register iReg.
   130237 */
   130238 static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
   130239   assert( nReg>0 );
   130240   if( p && sqlite3ExprIsVector(p) ){
   130241 #ifndef SQLITE_OMIT_SUBQUERY
   130242     if( (p->flags & EP_xIsSelect) ){
   130243       Vdbe *v = pParse->pVdbe;
   130244       int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
   130245       sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
   130246     }else
   130247 #endif
   130248     {
   130249       int i;
   130250       ExprList *pList = p->x.pList;
   130251       assert( nReg<=pList->nExpr );
   130252       for(i=0; i<nReg; i++){
   130253         sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
   130254       }
   130255     }
   130256   }else{
   130257     assert( nReg==1 );
   130258     sqlite3ExprCode(pParse, p, iReg);
   130259   }
   130260 }
   130261 
   130262 /* An instance of the IdxExprTrans object carries information about a
   130263 ** mapping from an expression on table columns into a column in an index
   130264 ** down through the Walker.
   130265 */
   130266 typedef struct IdxExprTrans {
   130267   Expr *pIdxExpr;    /* The index expression */
   130268   int iTabCur;       /* The cursor of the corresponding table */
   130269   int iIdxCur;       /* The cursor for the index */
   130270   int iIdxCol;       /* The column for the index */
   130271 } IdxExprTrans;
   130272 
   130273 /* The walker node callback used to transform matching expressions into
   130274 ** a reference to an index column for an index on an expression.
   130275 **
   130276 ** If pExpr matches, then transform it into a reference to the index column
   130277 ** that contains the value of pExpr.
   130278 */
   130279 static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
   130280   IdxExprTrans *pX = p->u.pIdxTrans;
   130281   if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
   130282     pExpr->op = TK_COLUMN;
   130283     pExpr->iTable = pX->iIdxCur;
   130284     pExpr->iColumn = pX->iIdxCol;
   130285     pExpr->pTab = 0;
   130286     return WRC_Prune;
   130287   }else{
   130288     return WRC_Continue;
   130289   }
   130290 }
   130291 
   130292 /*
   130293 ** For an indexes on expression X, locate every instance of expression X
   130294 ** in pExpr and change that subexpression into a reference to the appropriate
   130295 ** column of the index.
   130296 */
   130297 static void whereIndexExprTrans(
   130298   Index *pIdx,      /* The Index */
   130299   int iTabCur,      /* Cursor of the table that is being indexed */
   130300   int iIdxCur,      /* Cursor of the index itself */
   130301   WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
   130302 ){
   130303   int iIdxCol;               /* Column number of the index */
   130304   ExprList *aColExpr;        /* Expressions that are indexed */
   130305   Walker w;
   130306   IdxExprTrans x;
   130307   aColExpr = pIdx->aColExpr;
   130308   if( aColExpr==0 ) return;  /* Not an index on expressions */
   130309   memset(&w, 0, sizeof(w));
   130310   w.xExprCallback = whereIndexExprTransNode;
   130311   w.u.pIdxTrans = &x;
   130312   x.iTabCur = iTabCur;
   130313   x.iIdxCur = iIdxCur;
   130314   for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
   130315     if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
   130316     assert( aColExpr->a[iIdxCol].pExpr!=0 );
   130317     x.iIdxCol = iIdxCol;
   130318     x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
   130319     sqlite3WalkExpr(&w, pWInfo->pWhere);
   130320     sqlite3WalkExprList(&w, pWInfo->pOrderBy);
   130321     sqlite3WalkExprList(&w, pWInfo->pResultSet);
   130322   }
   130323 }
   130324 
   130325 /*
   130326 ** Generate code for the start of the iLevel-th loop in the WHERE clause
   130327 ** implementation described by pWInfo.
   130328 */
   130329 SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
   130330   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   130331   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   130332   Bitmask notReady     /* Which tables are currently available */
   130333 ){
   130334   int j, k;            /* Loop counters */
   130335   int iCur;            /* The VDBE cursor for the table */
   130336   int addrNxt;         /* Where to jump to continue with the next IN case */
   130337   int omitTable;       /* True if we use the index only */
   130338   int bRev;            /* True if we need to scan in reverse order */
   130339   WhereLevel *pLevel;  /* The where level to be coded */
   130340   WhereLoop *pLoop;    /* The WhereLoop object being coded */
   130341   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   130342   WhereTerm *pTerm;               /* A WHERE clause term */
   130343   Parse *pParse;                  /* Parsing context */
   130344   sqlite3 *db;                    /* Database connection */
   130345   Vdbe *v;                        /* The prepared stmt under constructions */
   130346   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
   130347   int addrBrk;                    /* Jump here to break out of the loop */
   130348   int addrHalt;                   /* addrBrk for the outermost loop */
   130349   int addrCont;                   /* Jump here to continue with next cycle */
   130350   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
   130351   int iReleaseReg = 0;      /* Temp register to free before returning */
   130352   Index *pIdx = 0;          /* Index used by loop (if any) */
   130353   int iLoop;                /* Iteration of constraint generator loop */
   130354 
   130355   pParse = pWInfo->pParse;
   130356   v = pParse->pVdbe;
   130357   pWC = &pWInfo->sWC;
   130358   db = pParse->db;
   130359   pLevel = &pWInfo->a[iLevel];
   130360   pLoop = pLevel->pWLoop;
   130361   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
   130362   iCur = pTabItem->iCursor;
   130363   pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
   130364   bRev = (pWInfo->revMask>>iLevel)&1;
   130365   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
   130366            && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
   130367   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
   130368 
   130369   /* Create labels for the "break" and "continue" instructions
   130370   ** for the current loop.  Jump to addrBrk to break out of a loop.
   130371   ** Jump to cont to go immediately to the next iteration of the
   130372   ** loop.
   130373   **
   130374   ** When there is an IN operator, we also have a "addrNxt" label that
   130375   ** means to continue with the next IN value combination.  When
   130376   ** there are no IN operators in the constraints, the "addrNxt" label
   130377   ** is the same as "addrBrk".
   130378   */
   130379   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   130380   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
   130381 
   130382   /* If this is the right table of a LEFT OUTER JOIN, allocate and
   130383   ** initialize a memory cell that records if this table matches any
   130384   ** row of the left table of the join.
   130385   */
   130386   if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
   130387     pLevel->iLeftJoin = ++pParse->nMem;
   130388     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
   130389     VdbeComment((v, "init LEFT JOIN no-match flag"));
   130390   }
   130391 
   130392   /* Compute a safe address to jump to if we discover that the table for
   130393   ** this loop is empty and can never contribute content. */
   130394   for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
   130395   addrHalt = pWInfo->a[j].addrBrk;
   130396 
   130397   /* Special case of a FROM clause subquery implemented as a co-routine */
   130398   if( pTabItem->fg.viaCoroutine ){
   130399     int regYield = pTabItem->regReturn;
   130400     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
   130401     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
   130402     VdbeCoverage(v);
   130403     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
   130404     pLevel->op = OP_Goto;
   130405   }else
   130406 
   130407 #ifndef SQLITE_OMIT_VIRTUALTABLE
   130408   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   130409     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
   130410     **          to access the data.
   130411     */
   130412     int iReg;   /* P3 Value for OP_VFilter */
   130413     int addrNotFound;
   130414     int nConstraint = pLoop->nLTerm;
   130415     int iIn;    /* Counter for IN constraints */
   130416 
   130417     sqlite3ExprCachePush(pParse);
   130418     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
   130419     addrNotFound = pLevel->addrBrk;
   130420     for(j=0; j<nConstraint; j++){
   130421       int iTarget = iReg+j+2;
   130422       pTerm = pLoop->aLTerm[j];
   130423       if( NEVER(pTerm==0) ) continue;
   130424       if( pTerm->eOperator & WO_IN ){
   130425         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
   130426         addrNotFound = pLevel->addrNxt;
   130427       }else{
   130428         Expr *pRight = pTerm->pExpr->pRight;
   130429         codeExprOrVector(pParse, pRight, iTarget, 1);
   130430       }
   130431     }
   130432     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
   130433     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
   130434     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
   130435                       pLoop->u.vtab.idxStr,
   130436                       pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
   130437     VdbeCoverage(v);
   130438     pLoop->u.vtab.needFree = 0;
   130439     pLevel->p1 = iCur;
   130440     pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
   130441     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   130442     iIn = pLevel->u.in.nIn;
   130443     for(j=nConstraint-1; j>=0; j--){
   130444       pTerm = pLoop->aLTerm[j];
   130445       if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
   130446         disableTerm(pLevel, pTerm);
   130447       }else if( (pTerm->eOperator & WO_IN)!=0 ){
   130448         Expr *pCompare;  /* The comparison operator */
   130449         Expr *pRight;    /* RHS of the comparison */
   130450         VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
   130451 
   130452         /* Reload the constraint value into reg[iReg+j+2].  The same value
   130453         ** was loaded into the same register prior to the OP_VFilter, but
   130454         ** the xFilter implementation might have changed the datatype or
   130455         ** encoding of the value in the register, so it *must* be reloaded. */
   130456         assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
   130457         if( !db->mallocFailed ){
   130458           assert( iIn>0 );
   130459           pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
   130460           assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
   130461           assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
   130462           assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
   130463           testcase( pOp->opcode==OP_Rowid );
   130464           sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
   130465         }
   130466 
   130467         /* Generate code that will continue to the next row if
   130468         ** the IN constraint is not satisfied */
   130469         pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
   130470         assert( pCompare!=0 || db->mallocFailed );
   130471         if( pCompare ){
   130472           pCompare->pLeft = pTerm->pExpr->pLeft;
   130473           pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
   130474           if( pRight ){
   130475             pRight->iTable = iReg+j+2;
   130476             sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
   130477           }
   130478           pCompare->pLeft = 0;
   130479           sqlite3ExprDelete(db, pCompare);
   130480         }
   130481       }
   130482     }
   130483     /* These registers need to be preserved in case there is an IN operator
   130484     ** loop.  So we could deallocate the registers here (and potentially
   130485     ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
   130486     ** simpler and safer to simply not reuse the registers.
   130487     **
   130488     **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
   130489     */
   130490     sqlite3ExprCachePop(pParse);
   130491   }else
   130492 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   130493 
   130494   if( (pLoop->wsFlags & WHERE_IPK)!=0
   130495    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
   130496   ){
   130497     /* Case 2:  We can directly reference a single row using an
   130498     **          equality comparison against the ROWID field.  Or
   130499     **          we reference multiple rows using a "rowid IN (...)"
   130500     **          construct.
   130501     */
   130502     assert( pLoop->u.btree.nEq==1 );
   130503     pTerm = pLoop->aLTerm[0];
   130504     assert( pTerm!=0 );
   130505     assert( pTerm->pExpr!=0 );
   130506     assert( omitTable==0 );
   130507     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   130508     iReleaseReg = ++pParse->nMem;
   130509     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
   130510     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
   130511     addrNxt = pLevel->addrNxt;
   130512     sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
   130513     VdbeCoverage(v);
   130514     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
   130515     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   130516     VdbeComment((v, "pk"));
   130517     pLevel->op = OP_Noop;
   130518   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
   130519          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
   130520   ){
   130521     /* Case 3:  We have an inequality comparison against the ROWID field.
   130522     */
   130523     int testOp = OP_Noop;
   130524     int start;
   130525     int memEndValue = 0;
   130526     WhereTerm *pStart, *pEnd;
   130527 
   130528     assert( omitTable==0 );
   130529     j = 0;
   130530     pStart = pEnd = 0;
   130531     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
   130532     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
   130533     assert( pStart!=0 || pEnd!=0 );
   130534     if( bRev ){
   130535       pTerm = pStart;
   130536       pStart = pEnd;
   130537       pEnd = pTerm;
   130538     }
   130539     codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
   130540     if( pStart ){
   130541       Expr *pX;             /* The expression that defines the start bound */
   130542       int r1, rTemp;        /* Registers for holding the start boundary */
   130543       int op;               /* Cursor seek operation */
   130544 
   130545       /* The following constant maps TK_xx codes into corresponding
   130546       ** seek opcodes.  It depends on a particular ordering of TK_xx
   130547       */
   130548       const u8 aMoveOp[] = {
   130549            /* TK_GT */  OP_SeekGT,
   130550            /* TK_LE */  OP_SeekLE,
   130551            /* TK_LT */  OP_SeekLT,
   130552            /* TK_GE */  OP_SeekGE
   130553       };
   130554       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
   130555       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
   130556       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
   130557 
   130558       assert( (pStart->wtFlags & TERM_VNULL)==0 );
   130559       testcase( pStart->wtFlags & TERM_VIRTUAL );
   130560       pX = pStart->pExpr;
   130561       assert( pX!=0 );
   130562       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
   130563       if( sqlite3ExprIsVector(pX->pRight) ){
   130564         r1 = rTemp = sqlite3GetTempReg(pParse);
   130565         codeExprOrVector(pParse, pX->pRight, r1, 1);
   130566         op = aMoveOp[(pX->op - TK_GT) | 0x0001];
   130567       }else{
   130568         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
   130569         disableTerm(pLevel, pStart);
   130570         op = aMoveOp[(pX->op - TK_GT)];
   130571       }
   130572       sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
   130573       VdbeComment((v, "pk"));
   130574       VdbeCoverageIf(v, pX->op==TK_GT);
   130575       VdbeCoverageIf(v, pX->op==TK_LE);
   130576       VdbeCoverageIf(v, pX->op==TK_LT);
   130577       VdbeCoverageIf(v, pX->op==TK_GE);
   130578       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
   130579       sqlite3ReleaseTempReg(pParse, rTemp);
   130580     }else{
   130581       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
   130582       VdbeCoverageIf(v, bRev==0);
   130583       VdbeCoverageIf(v, bRev!=0);
   130584     }
   130585     if( pEnd ){
   130586       Expr *pX;
   130587       pX = pEnd->pExpr;
   130588       assert( pX!=0 );
   130589       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
   130590       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
   130591       testcase( pEnd->wtFlags & TERM_VIRTUAL );
   130592       memEndValue = ++pParse->nMem;
   130593       codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
   130594       if( 0==sqlite3ExprIsVector(pX->pRight)
   130595        && (pX->op==TK_LT || pX->op==TK_GT)
   130596       ){
   130597         testOp = bRev ? OP_Le : OP_Ge;
   130598       }else{
   130599         testOp = bRev ? OP_Lt : OP_Gt;
   130600       }
   130601       if( 0==sqlite3ExprIsVector(pX->pRight) ){
   130602         disableTerm(pLevel, pEnd);
   130603       }
   130604     }
   130605     start = sqlite3VdbeCurrentAddr(v);
   130606     pLevel->op = bRev ? OP_Prev : OP_Next;
   130607     pLevel->p1 = iCur;
   130608     pLevel->p2 = start;
   130609     assert( pLevel->p5==0 );
   130610     if( testOp!=OP_Noop ){
   130611       iRowidReg = ++pParse->nMem;
   130612       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
   130613       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   130614       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
   130615       VdbeCoverageIf(v, testOp==OP_Le);
   130616       VdbeCoverageIf(v, testOp==OP_Lt);
   130617       VdbeCoverageIf(v, testOp==OP_Ge);
   130618       VdbeCoverageIf(v, testOp==OP_Gt);
   130619       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
   130620     }
   130621   }else if( pLoop->wsFlags & WHERE_INDEXED ){
   130622     /* Case 4: A scan using an index.
   130623     **
   130624     **         The WHERE clause may contain zero or more equality
   130625     **         terms ("==" or "IN" operators) that refer to the N
   130626     **         left-most columns of the index. It may also contain
   130627     **         inequality constraints (>, <, >= or <=) on the indexed
   130628     **         column that immediately follows the N equalities. Only
   130629     **         the right-most column can be an inequality - the rest must
   130630     **         use the "==" and "IN" operators. For example, if the
   130631     **         index is on (x,y,z), then the following clauses are all
   130632     **         optimized:
   130633     **
   130634     **            x=5
   130635     **            x=5 AND y=10
   130636     **            x=5 AND y<10
   130637     **            x=5 AND y>5 AND y<10
   130638     **            x=5 AND y=5 AND z<=10
   130639     **
   130640     **         The z<10 term of the following cannot be used, only
   130641     **         the x=5 term:
   130642     **
   130643     **            x=5 AND z<10
   130644     **
   130645     **         N may be zero if there are inequality constraints.
   130646     **         If there are no inequality constraints, then N is at
   130647     **         least one.
   130648     **
   130649     **         This case is also used when there are no WHERE clause
   130650     **         constraints but an index is selected anyway, in order
   130651     **         to force the output order to conform to an ORDER BY.
   130652     */
   130653     static const u8 aStartOp[] = {
   130654       0,
   130655       0,
   130656       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
   130657       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
   130658       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
   130659       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
   130660       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
   130661       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
   130662     };
   130663     static const u8 aEndOp[] = {
   130664       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
   130665       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
   130666       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
   130667       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
   130668     };
   130669     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
   130670     u16 nBtm = pLoop->u.btree.nBtm;   /* Length of BTM vector */
   130671     u16 nTop = pLoop->u.btree.nTop;   /* Length of TOP vector */
   130672     int regBase;                 /* Base register holding constraint values */
   130673     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
   130674     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
   130675     int startEq;                 /* True if range start uses ==, >= or <= */
   130676     int endEq;                   /* True if range end uses ==, >= or <= */
   130677     int start_constraints;       /* Start of range is constrained */
   130678     int nConstraint;             /* Number of constraint terms */
   130679     int iIdxCur;                 /* The VDBE cursor for the index */
   130680     int nExtraReg = 0;           /* Number of extra registers needed */
   130681     int op;                      /* Instruction opcode */
   130682     char *zStartAff;             /* Affinity for start of range constraint */
   130683     char *zEndAff = 0;           /* Affinity for end of range constraint */
   130684     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
   130685     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
   130686 
   130687     pIdx = pLoop->u.btree.pIndex;
   130688     iIdxCur = pLevel->iIdxCur;
   130689     assert( nEq>=pLoop->nSkip );
   130690 
   130691     /* If this loop satisfies a sort order (pOrderBy) request that
   130692     ** was passed to this function to implement a "SELECT min(x) ..."
   130693     ** query, then the caller will only allow the loop to run for
   130694     ** a single iteration. This means that the first row returned
   130695     ** should not have a NULL value stored in 'x'. If column 'x' is
   130696     ** the first one after the nEq equality constraints in the index,
   130697     ** this requires some special handling.
   130698     */
   130699     assert( pWInfo->pOrderBy==0
   130700          || pWInfo->pOrderBy->nExpr==1
   130701          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
   130702     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
   130703      && pWInfo->nOBSat>0
   130704      && (pIdx->nKeyCol>nEq)
   130705     ){
   130706       assert( pLoop->nSkip==0 );
   130707       bSeekPastNull = 1;
   130708       nExtraReg = 1;
   130709     }
   130710 
   130711     /* Find any inequality constraint terms for the start and end
   130712     ** of the range.
   130713     */
   130714     j = nEq;
   130715     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
   130716       pRangeStart = pLoop->aLTerm[j++];
   130717       nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
   130718       /* Like optimization range constraints always occur in pairs */
   130719       assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
   130720               (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
   130721     }
   130722     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
   130723       pRangeEnd = pLoop->aLTerm[j++];
   130724       nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
   130725 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   130726       if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
   130727         assert( pRangeStart!=0 );                     /* LIKE opt constraints */
   130728         assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
   130729         pLevel->iLikeRepCntr = (u32)++pParse->nMem;
   130730         sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
   130731         VdbeComment((v, "LIKE loop counter"));
   130732         pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
   130733         /* iLikeRepCntr actually stores 2x the counter register number.  The
   130734         ** bottom bit indicates whether the search order is ASC or DESC. */
   130735         testcase( bRev );
   130736         testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
   130737         assert( (bRev & ~1)==0 );
   130738         pLevel->iLikeRepCntr <<=1;
   130739         pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
   130740       }
   130741 #endif
   130742       if( pRangeStart==0 ){
   130743         j = pIdx->aiColumn[nEq];
   130744         if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
   130745           bSeekPastNull = 1;
   130746         }
   130747       }
   130748     }
   130749     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
   130750 
   130751     /* If we are doing a reverse order scan on an ascending index, or
   130752     ** a forward order scan on a descending index, interchange the
   130753     ** start and end terms (pRangeStart and pRangeEnd).
   130754     */
   130755     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
   130756      || (bRev && pIdx->nKeyCol==nEq)
   130757     ){
   130758       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
   130759       SWAP(u8, bSeekPastNull, bStopAtNull);
   130760       SWAP(u8, nBtm, nTop);
   130761     }
   130762 
   130763     /* Generate code to evaluate all constraint terms using == or IN
   130764     ** and store the values of those terms in an array of registers
   130765     ** starting at regBase.
   130766     */
   130767     codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
   130768     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
   130769     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
   130770     if( zStartAff && nTop ){
   130771       zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
   130772     }
   130773     addrNxt = pLevel->addrNxt;
   130774 
   130775     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
   130776     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
   130777     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
   130778     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
   130779     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
   130780     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
   130781     start_constraints = pRangeStart || nEq>0;
   130782 
   130783     /* Seek the index cursor to the start of the range. */
   130784     nConstraint = nEq;
   130785     if( pRangeStart ){
   130786       Expr *pRight = pRangeStart->pExpr->pRight;
   130787       codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
   130788       whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
   130789       if( (pRangeStart->wtFlags & TERM_VNULL)==0
   130790        && sqlite3ExprCanBeNull(pRight)
   130791       ){
   130792         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
   130793         VdbeCoverage(v);
   130794       }
   130795       if( zStartAff ){
   130796         updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
   130797       }
   130798       nConstraint += nBtm;
   130799       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
   130800       if( sqlite3ExprIsVector(pRight)==0 ){
   130801         disableTerm(pLevel, pRangeStart);
   130802       }else{
   130803         startEq = 1;
   130804       }
   130805       bSeekPastNull = 0;
   130806     }else if( bSeekPastNull ){
   130807       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   130808       nConstraint++;
   130809       startEq = 0;
   130810       start_constraints = 1;
   130811     }
   130812     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
   130813     if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
   130814       /* The skip-scan logic inside the call to codeAllEqualityConstraints()
   130815       ** above has already left the cursor sitting on the correct row,
   130816       ** so no further seeking is needed */
   130817     }else{
   130818       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
   130819       assert( op!=0 );
   130820       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   130821       VdbeCoverage(v);
   130822       VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
   130823       VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
   130824       VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
   130825       VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
   130826       VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
   130827       VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
   130828     }
   130829 
   130830     /* Load the value for the inequality constraint at the end of the
   130831     ** range (if any).
   130832     */
   130833     nConstraint = nEq;
   130834     if( pRangeEnd ){
   130835       Expr *pRight = pRangeEnd->pExpr->pRight;
   130836       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   130837       codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
   130838       whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
   130839       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
   130840        && sqlite3ExprCanBeNull(pRight)
   130841       ){
   130842         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
   130843         VdbeCoverage(v);
   130844       }
   130845       if( zEndAff ){
   130846         updateRangeAffinityStr(pRight, nTop, zEndAff);
   130847         codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
   130848       }else{
   130849         assert( pParse->db->mallocFailed );
   130850       }
   130851       nConstraint += nTop;
   130852       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
   130853 
   130854       if( sqlite3ExprIsVector(pRight)==0 ){
   130855         disableTerm(pLevel, pRangeEnd);
   130856       }else{
   130857         endEq = 1;
   130858       }
   130859     }else if( bStopAtNull ){
   130860       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   130861       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   130862       endEq = 0;
   130863       nConstraint++;
   130864     }
   130865     sqlite3DbFree(db, zStartAff);
   130866     sqlite3DbFree(db, zEndAff);
   130867 
   130868     /* Top of the loop body */
   130869     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   130870 
   130871     /* Check if the index cursor is past the end of the range. */
   130872     if( nConstraint ){
   130873       op = aEndOp[bRev*2 + endEq];
   130874       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   130875       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
   130876       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
   130877       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
   130878       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
   130879     }
   130880 
   130881     /* Seek the table cursor, if required */
   130882     if( omitTable ){
   130883       /* pIdx is a covering index.  No need to access the main table. */
   130884     }else if( HasRowid(pIdx->pTable) ){
   130885       if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
   130886           (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
   130887        && (pWInfo->eOnePass==ONEPASS_SINGLE)
   130888       )){
   130889         iRowidReg = ++pParse->nMem;
   130890         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
   130891         sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   130892         sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
   130893         VdbeCoverage(v);
   130894       }else{
   130895         codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
   130896       }
   130897     }else if( iCur!=iIdxCur ){
   130898       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
   130899       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
   130900       for(j=0; j<pPk->nKeyCol; j++){
   130901         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
   130902         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
   130903       }
   130904       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
   130905                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
   130906     }
   130907 
   130908     /* If pIdx is an index on one or more expressions, then look through
   130909     ** all the expressions in pWInfo and try to transform matching expressions
   130910     ** into reference to index columns.
   130911     */
   130912     whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
   130913 
   130914 
   130915     /* Record the instruction used to terminate the loop. */
   130916     if( pLoop->wsFlags & WHERE_ONEROW ){
   130917       pLevel->op = OP_Noop;
   130918     }else if( bRev ){
   130919       pLevel->op = OP_Prev;
   130920     }else{
   130921       pLevel->op = OP_Next;
   130922     }
   130923     pLevel->p1 = iIdxCur;
   130924     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
   130925     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
   130926       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   130927     }else{
   130928       assert( pLevel->p5==0 );
   130929     }
   130930     if( omitTable ) pIdx = 0;
   130931   }else
   130932 
   130933 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   130934   if( pLoop->wsFlags & WHERE_MULTI_OR ){
   130935     /* Case 5:  Two or more separately indexed terms connected by OR
   130936     **
   130937     ** Example:
   130938     **
   130939     **   CREATE TABLE t1(a,b,c,d);
   130940     **   CREATE INDEX i1 ON t1(a);
   130941     **   CREATE INDEX i2 ON t1(b);
   130942     **   CREATE INDEX i3 ON t1(c);
   130943     **
   130944     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
   130945     **
   130946     ** In the example, there are three indexed terms connected by OR.
   130947     ** The top of the loop looks like this:
   130948     **
   130949     **          Null       1                # Zero the rowset in reg 1
   130950     **
   130951     ** Then, for each indexed term, the following. The arguments to
   130952     ** RowSetTest are such that the rowid of the current row is inserted
   130953     ** into the RowSet. If it is already present, control skips the
   130954     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
   130955     **
   130956     **        sqlite3WhereBegin(<term>)
   130957     **          RowSetTest                  # Insert rowid into rowset
   130958     **          Gosub      2 A
   130959     **        sqlite3WhereEnd()
   130960     **
   130961     ** Following the above, code to terminate the loop. Label A, the target
   130962     ** of the Gosub above, jumps to the instruction right after the Goto.
   130963     **
   130964     **          Null       1                # Zero the rowset in reg 1
   130965     **          Goto       B                # The loop is finished.
   130966     **
   130967     **       A: <loop body>                 # Return data, whatever.
   130968     **
   130969     **          Return     2                # Jump back to the Gosub
   130970     **
   130971     **       B: <after the loop>
   130972     **
   130973     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
   130974     ** use an ephemeral index instead of a RowSet to record the primary
   130975     ** keys of the rows we have already seen.
   130976     **
   130977     */
   130978     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
   130979     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
   130980     Index *pCov = 0;             /* Potential covering index (or NULL) */
   130981     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
   130982 
   130983     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
   130984     int regRowset = 0;                        /* Register for RowSet object */
   130985     int regRowid = 0;                         /* Register holding rowid */
   130986     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
   130987     int iRetInit;                             /* Address of regReturn init */
   130988     int untestedTerms = 0;             /* Some terms not completely tested */
   130989     int ii;                            /* Loop counter */
   130990     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
   130991     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
   130992     Table *pTab = pTabItem->pTab;
   130993 
   130994     pTerm = pLoop->aLTerm[0];
   130995     assert( pTerm!=0 );
   130996     assert( pTerm->eOperator & WO_OR );
   130997     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
   130998     pOrWc = &pTerm->u.pOrInfo->wc;
   130999     pLevel->op = OP_Return;
   131000     pLevel->p1 = regReturn;
   131001 
   131002     /* Set up a new SrcList in pOrTab containing the table being scanned
   131003     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
   131004     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
   131005     */
   131006     if( pWInfo->nLevel>1 ){
   131007       int nNotReady;                 /* The number of notReady tables */
   131008       struct SrcList_item *origSrc;     /* Original list of tables */
   131009       nNotReady = pWInfo->nLevel - iLevel - 1;
   131010       pOrTab = sqlite3StackAllocRaw(db,
   131011                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
   131012       if( pOrTab==0 ) return notReady;
   131013       pOrTab->nAlloc = (u8)(nNotReady + 1);
   131014       pOrTab->nSrc = pOrTab->nAlloc;
   131015       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
   131016       origSrc = pWInfo->pTabList->a;
   131017       for(k=1; k<=nNotReady; k++){
   131018         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
   131019       }
   131020     }else{
   131021       pOrTab = pWInfo->pTabList;
   131022     }
   131023 
   131024     /* Initialize the rowset register to contain NULL. An SQL NULL is
   131025     ** equivalent to an empty rowset.  Or, create an ephemeral index
   131026     ** capable of holding primary keys in the case of a WITHOUT ROWID.
   131027     **
   131028     ** Also initialize regReturn to contain the address of the instruction
   131029     ** immediately following the OP_Return at the bottom of the loop. This
   131030     ** is required in a few obscure LEFT JOIN cases where control jumps
   131031     ** over the top of the loop into the body of it. In this case the
   131032     ** correct response for the end-of-loop code (the OP_Return) is to
   131033     ** fall through to the next instruction, just as an OP_Next does if
   131034     ** called on an uninitialized cursor.
   131035     */
   131036     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   131037       if( HasRowid(pTab) ){
   131038         regRowset = ++pParse->nMem;
   131039         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
   131040       }else{
   131041         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   131042         regRowset = pParse->nTab++;
   131043         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
   131044         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
   131045       }
   131046       regRowid = ++pParse->nMem;
   131047     }
   131048     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
   131049 
   131050     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
   131051     ** Then for every term xN, evaluate as the subexpression: xN AND z
   131052     ** That way, terms in y that are factored into the disjunction will
   131053     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
   131054     **
   131055     ** Actually, each subexpression is converted to "xN AND w" where w is
   131056     ** the "interesting" terms of z - terms that did not originate in the
   131057     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
   131058     ** indices.
   131059     **
   131060     ** This optimization also only applies if the (x1 OR x2 OR ...) term
   131061     ** is not contained in the ON clause of a LEFT JOIN.
   131062     ** See ticket http://www.sqlite.org/src/info/f2369304e4
   131063     */
   131064     if( pWC->nTerm>1 ){
   131065       int iTerm;
   131066       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
   131067         Expr *pExpr = pWC->a[iTerm].pExpr;
   131068         if( &pWC->a[iTerm] == pTerm ) continue;
   131069         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
   131070         testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
   131071         testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
   131072         if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
   131073         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
   131074         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
   131075         pExpr = sqlite3ExprDup(db, pExpr, 0);
   131076         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
   131077       }
   131078       if( pAndExpr ){
   131079         pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
   131080       }
   131081     }
   131082 
   131083     /* Run a separate WHERE clause for each term of the OR clause.  After
   131084     ** eliminating duplicates from other WHERE clauses, the action for each
   131085     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
   131086     */
   131087     wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
   131088     for(ii=0; ii<pOrWc->nTerm; ii++){
   131089       WhereTerm *pOrTerm = &pOrWc->a[ii];
   131090       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
   131091         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
   131092         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
   131093         int jmp1 = 0;                   /* Address of jump operation */
   131094         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
   131095           pAndExpr->pLeft = pOrExpr;
   131096           pOrExpr = pAndExpr;
   131097         }
   131098         /* Loop through table entries that match term pOrTerm. */
   131099         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
   131100         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
   131101                                       wctrlFlags, iCovCur);
   131102         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
   131103         if( pSubWInfo ){
   131104           WhereLoop *pSubLoop;
   131105           int addrExplain = sqlite3WhereExplainOneScan(
   131106               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
   131107           );
   131108           sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
   131109 
   131110           /* This is the sub-WHERE clause body.  First skip over
   131111           ** duplicate rows from prior sub-WHERE clauses, and record the
   131112           ** rowid (or PRIMARY KEY) for the current row so that the same
   131113           ** row will be skipped in subsequent sub-WHERE clauses.
   131114           */
   131115           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   131116             int r;
   131117             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
   131118             if( HasRowid(pTab) ){
   131119               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
   131120               jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
   131121                                            r,iSet);
   131122               VdbeCoverage(v);
   131123             }else{
   131124               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   131125               int nPk = pPk->nKeyCol;
   131126               int iPk;
   131127 
   131128               /* Read the PK into an array of temp registers. */
   131129               r = sqlite3GetTempRange(pParse, nPk);
   131130               for(iPk=0; iPk<nPk; iPk++){
   131131                 int iCol = pPk->aiColumn[iPk];
   131132                 sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
   131133               }
   131134 
   131135               /* Check if the temp table already contains this key. If so,
   131136               ** the row has already been included in the result set and
   131137               ** can be ignored (by jumping past the Gosub below). Otherwise,
   131138               ** insert the key into the temp table and proceed with processing
   131139               ** the row.
   131140               **
   131141               ** Use some of the same optimizations as OP_RowSetTest: If iSet
   131142               ** is zero, assume that the key cannot already be present in
   131143               ** the temp table. And if iSet is -1, assume that there is no
   131144               ** need to insert the key into the temp table, as it will never
   131145               ** be tested for.  */
   131146               if( iSet ){
   131147                 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
   131148                 VdbeCoverage(v);
   131149               }
   131150               if( iSet>=0 ){
   131151                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
   131152                 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
   131153                                      r, nPk);
   131154                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   131155               }
   131156 
   131157               /* Release the array of temp registers */
   131158               sqlite3ReleaseTempRange(pParse, r, nPk);
   131159             }
   131160           }
   131161 
   131162           /* Invoke the main loop body as a subroutine */
   131163           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
   131164 
   131165           /* Jump here (skipping the main loop body subroutine) if the
   131166           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
   131167           if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
   131168 
   131169           /* The pSubWInfo->untestedTerms flag means that this OR term
   131170           ** contained one or more AND term from a notReady table.  The
   131171           ** terms from the notReady table could not be tested and will
   131172           ** need to be tested later.
   131173           */
   131174           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
   131175 
   131176           /* If all of the OR-connected terms are optimized using the same
   131177           ** index, and the index is opened using the same cursor number
   131178           ** by each call to sqlite3WhereBegin() made by this loop, it may
   131179           ** be possible to use that index as a covering index.
   131180           **
   131181           ** If the call to sqlite3WhereBegin() above resulted in a scan that
   131182           ** uses an index, and this is either the first OR-connected term
   131183           ** processed or the index is the same as that used by all previous
   131184           ** terms, set pCov to the candidate covering index. Otherwise, set
   131185           ** pCov to NULL to indicate that no candidate covering index will
   131186           ** be available.
   131187           */
   131188           pSubLoop = pSubWInfo->a[0].pWLoop;
   131189           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
   131190           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
   131191            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
   131192            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
   131193           ){
   131194             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
   131195             pCov = pSubLoop->u.btree.pIndex;
   131196           }else{
   131197             pCov = 0;
   131198           }
   131199 
   131200           /* Finish the loop through table entries that match term pOrTerm. */
   131201           sqlite3WhereEnd(pSubWInfo);
   131202         }
   131203       }
   131204     }
   131205     pLevel->u.pCovidx = pCov;
   131206     if( pCov ) pLevel->iIdxCur = iCovCur;
   131207     if( pAndExpr ){
   131208       pAndExpr->pLeft = 0;
   131209       sqlite3ExprDelete(db, pAndExpr);
   131210     }
   131211     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
   131212     sqlite3VdbeGoto(v, pLevel->addrBrk);
   131213     sqlite3VdbeResolveLabel(v, iLoopBody);
   131214 
   131215     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
   131216     if( !untestedTerms ) disableTerm(pLevel, pTerm);
   131217   }else
   131218 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   131219 
   131220   {
   131221     /* Case 6:  There is no usable index.  We must do a complete
   131222     **          scan of the entire table.
   131223     */
   131224     static const u8 aStep[] = { OP_Next, OP_Prev };
   131225     static const u8 aStart[] = { OP_Rewind, OP_Last };
   131226     assert( bRev==0 || bRev==1 );
   131227     if( pTabItem->fg.isRecursive ){
   131228       /* Tables marked isRecursive have only a single row that is stored in
   131229       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
   131230       pLevel->op = OP_Noop;
   131231     }else{
   131232       codeCursorHint(pTabItem, pWInfo, pLevel, 0);
   131233       pLevel->op = aStep[bRev];
   131234       pLevel->p1 = iCur;
   131235       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
   131236       VdbeCoverageIf(v, bRev==0);
   131237       VdbeCoverageIf(v, bRev!=0);
   131238       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   131239     }
   131240   }
   131241 
   131242 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   131243   pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
   131244 #endif
   131245 
   131246   /* Insert code to test every subexpression that can be completely
   131247   ** computed using the current set of tables.
   131248   **
   131249   ** This loop may run between one and three times, depending on the
   131250   ** constraints to be generated. The value of stack variable iLoop
   131251   ** determines the constraints coded by each iteration, as follows:
   131252   **
   131253   ** iLoop==1: Code only expressions that are entirely covered by pIdx.
   131254   ** iLoop==2: Code remaining expressions that do not contain correlated
   131255   **           sub-queries.
   131256   ** iLoop==3: Code all remaining expressions.
   131257   **
   131258   ** An effort is made to skip unnecessary iterations of the loop.
   131259   */
   131260   iLoop = (pIdx ? 1 : 2);
   131261   do{
   131262     int iNext = 0;                /* Next value for iLoop */
   131263     for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   131264       Expr *pE;
   131265       int skipLikeAddr = 0;
   131266       testcase( pTerm->wtFlags & TERM_VIRTUAL );
   131267       testcase( pTerm->wtFlags & TERM_CODED );
   131268       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   131269       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
   131270         testcase( pWInfo->untestedTerms==0
   131271             && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
   131272         pWInfo->untestedTerms = 1;
   131273         continue;
   131274       }
   131275       pE = pTerm->pExpr;
   131276       assert( pE!=0 );
   131277       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
   131278         continue;
   131279       }
   131280 
   131281       if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
   131282         iNext = 2;
   131283         continue;
   131284       }
   131285       if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
   131286         if( iNext==0 ) iNext = 3;
   131287         continue;
   131288       }
   131289 
   131290       if( pTerm->wtFlags & TERM_LIKECOND ){
   131291         /* If the TERM_LIKECOND flag is set, that means that the range search
   131292         ** is sufficient to guarantee that the LIKE operator is true, so we
   131293         ** can skip the call to the like(A,B) function.  But this only works
   131294         ** for strings.  So do not skip the call to the function on the pass
   131295         ** that compares BLOBs. */
   131296 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   131297         continue;
   131298 #else
   131299         u32 x = pLevel->iLikeRepCntr;
   131300         assert( x>0 );
   131301         skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1));
   131302         VdbeCoverage(v);
   131303 #endif
   131304       }
   131305 #ifdef WHERETRACE_ENABLED /* 0xffff */
   131306       if( sqlite3WhereTrace ){
   131307         VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
   131308                          pWC->nTerm-j, pTerm, iLoop));
   131309       }
   131310 #endif
   131311       sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
   131312       if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
   131313       pTerm->wtFlags |= TERM_CODED;
   131314     }
   131315     iLoop = iNext;
   131316   }while( iLoop>0 );
   131317 
   131318   /* Insert code to test for implied constraints based on transitivity
   131319   ** of the "==" operator.
   131320   **
   131321   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
   131322   ** and we are coding the t1 loop and the t2 loop has not yet coded,
   131323   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
   131324   ** the implied "t1.a=123" constraint.
   131325   */
   131326   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   131327     Expr *pE, sEAlt;
   131328     WhereTerm *pAlt;
   131329     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   131330     if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
   131331     if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
   131332     if( pTerm->leftCursor!=iCur ) continue;
   131333     if( pLevel->iLeftJoin ) continue;
   131334     pE = pTerm->pExpr;
   131335     assert( !ExprHasProperty(pE, EP_FromJoin) );
   131336     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
   131337     pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
   131338                     WO_EQ|WO_IN|WO_IS, 0);
   131339     if( pAlt==0 ) continue;
   131340     if( pAlt->wtFlags & (TERM_CODED) ) continue;
   131341     testcase( pAlt->eOperator & WO_EQ );
   131342     testcase( pAlt->eOperator & WO_IS );
   131343     testcase( pAlt->eOperator & WO_IN );
   131344     VdbeModuleComment((v, "begin transitive constraint"));
   131345     sEAlt = *pAlt->pExpr;
   131346     sEAlt.pLeft = pE->pLeft;
   131347     sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
   131348   }
   131349 
   131350   /* For a LEFT OUTER JOIN, generate code that will record the fact that
   131351   ** at least one row of the right table has matched the left table.
   131352   */
   131353   if( pLevel->iLeftJoin ){
   131354     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
   131355     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
   131356     VdbeComment((v, "record LEFT JOIN hit"));
   131357     sqlite3ExprCacheClear(pParse);
   131358     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
   131359       testcase( pTerm->wtFlags & TERM_VIRTUAL );
   131360       testcase( pTerm->wtFlags & TERM_CODED );
   131361       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   131362       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
   131363         assert( pWInfo->untestedTerms );
   131364         continue;
   131365       }
   131366       assert( pTerm->pExpr );
   131367       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
   131368       pTerm->wtFlags |= TERM_CODED;
   131369     }
   131370   }
   131371 
   131372   return pLevel->notReady;
   131373 }
   131374 
   131375 /************** End of wherecode.c *******************************************/
   131376 /************** Begin file whereexpr.c ***************************************/
   131377 /*
   131378 ** 2015-06-08
   131379 **
   131380 ** The author disclaims copyright to this source code.  In place of
   131381 ** a legal notice, here is a blessing:
   131382 **
   131383 **    May you do good and not evil.
   131384 **    May you find forgiveness for yourself and forgive others.
   131385 **    May you share freely, never taking more than you give.
   131386 **
   131387 *************************************************************************
   131388 ** This module contains C code that generates VDBE code used to process
   131389 ** the WHERE clause of SQL statements.
   131390 **
   131391 ** This file was originally part of where.c but was split out to improve
   131392 ** readability and editabiliity.  This file contains utility routines for
   131393 ** analyzing Expr objects in the WHERE clause.
   131394 */
   131395 /* #include "sqliteInt.h" */
   131396 /* #include "whereInt.h" */
   131397 
   131398 /* Forward declarations */
   131399 static void exprAnalyze(SrcList*, WhereClause*, int);
   131400 
   131401 /*
   131402 ** Deallocate all memory associated with a WhereOrInfo object.
   131403 */
   131404 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
   131405   sqlite3WhereClauseClear(&p->wc);
   131406   sqlite3DbFree(db, p);
   131407 }
   131408 
   131409 /*
   131410 ** Deallocate all memory associated with a WhereAndInfo object.
   131411 */
   131412 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
   131413   sqlite3WhereClauseClear(&p->wc);
   131414   sqlite3DbFree(db, p);
   131415 }
   131416 
   131417 /*
   131418 ** Add a single new WhereTerm entry to the WhereClause object pWC.
   131419 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
   131420 ** The index in pWC->a[] of the new WhereTerm is returned on success.
   131421 ** 0 is returned if the new WhereTerm could not be added due to a memory
   131422 ** allocation error.  The memory allocation failure will be recorded in
   131423 ** the db->mallocFailed flag so that higher-level functions can detect it.
   131424 **
   131425 ** This routine will increase the size of the pWC->a[] array as necessary.
   131426 **
   131427 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
   131428 ** for freeing the expression p is assumed by the WhereClause object pWC.
   131429 ** This is true even if this routine fails to allocate a new WhereTerm.
   131430 **
   131431 ** WARNING:  This routine might reallocate the space used to store
   131432 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   131433 ** calling this routine.  Such pointers may be reinitialized by referencing
   131434 ** the pWC->a[] array.
   131435 */
   131436 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
   131437   WhereTerm *pTerm;
   131438   int idx;
   131439   testcase( wtFlags & TERM_VIRTUAL );
   131440   if( pWC->nTerm>=pWC->nSlot ){
   131441     WhereTerm *pOld = pWC->a;
   131442     sqlite3 *db = pWC->pWInfo->pParse->db;
   131443     pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   131444     if( pWC->a==0 ){
   131445       if( wtFlags & TERM_DYNAMIC ){
   131446         sqlite3ExprDelete(db, p);
   131447       }
   131448       pWC->a = pOld;
   131449       return 0;
   131450     }
   131451     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
   131452     if( pOld!=pWC->aStatic ){
   131453       sqlite3DbFree(db, pOld);
   131454     }
   131455     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   131456   }
   131457   pTerm = &pWC->a[idx = pWC->nTerm++];
   131458   if( p && ExprHasProperty(p, EP_Unlikely) ){
   131459     pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
   131460   }else{
   131461     pTerm->truthProb = 1;
   131462   }
   131463   pTerm->pExpr = sqlite3ExprSkipCollate(p);
   131464   pTerm->wtFlags = wtFlags;
   131465   pTerm->pWC = pWC;
   131466   pTerm->iParent = -1;
   131467   memset(&pTerm->eOperator, 0,
   131468          sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
   131469   return idx;
   131470 }
   131471 
   131472 /*
   131473 ** Return TRUE if the given operator is one of the operators that is
   131474 ** allowed for an indexable WHERE clause term.  The allowed operators are
   131475 ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
   131476 */
   131477 static int allowedOp(int op){
   131478   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   131479   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   131480   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   131481   assert( TK_GE==TK_EQ+4 );
   131482   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
   131483 }
   131484 
   131485 /*
   131486 ** Commute a comparison operator.  Expressions of the form "X op Y"
   131487 ** are converted into "Y op X".
   131488 **
   131489 ** If left/right precedence rules come into play when determining the
   131490 ** collating sequence, then COLLATE operators are adjusted to ensure
   131491 ** that the collating sequence does not change.  For example:
   131492 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
   131493 ** the left hand side of a comparison overrides any collation sequence
   131494 ** attached to the right. For the same reason the EP_Collate flag
   131495 ** is not commuted.
   131496 */
   131497 static void exprCommute(Parse *pParse, Expr *pExpr){
   131498   u16 expRight = (pExpr->pRight->flags & EP_Collate);
   131499   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
   131500   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
   131501   if( expRight==expLeft ){
   131502     /* Either X and Y both have COLLATE operator or neither do */
   131503     if( expRight ){
   131504       /* Both X and Y have COLLATE operators.  Make sure X is always
   131505       ** used by clearing the EP_Collate flag from Y. */
   131506       pExpr->pRight->flags &= ~EP_Collate;
   131507     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
   131508       /* Neither X nor Y have COLLATE operators, but X has a non-default
   131509       ** collating sequence.  So add the EP_Collate marker on X to cause
   131510       ** it to be searched first. */
   131511       pExpr->pLeft->flags |= EP_Collate;
   131512     }
   131513   }
   131514   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   131515   if( pExpr->op>=TK_GT ){
   131516     assert( TK_LT==TK_GT+2 );
   131517     assert( TK_GE==TK_LE+2 );
   131518     assert( TK_GT>TK_EQ );
   131519     assert( TK_GT<TK_LE );
   131520     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
   131521     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   131522   }
   131523 }
   131524 
   131525 /*
   131526 ** Translate from TK_xx operator to WO_xx bitmask.
   131527 */
   131528 static u16 operatorMask(int op){
   131529   u16 c;
   131530   assert( allowedOp(op) );
   131531   if( op==TK_IN ){
   131532     c = WO_IN;
   131533   }else if( op==TK_ISNULL ){
   131534     c = WO_ISNULL;
   131535   }else if( op==TK_IS ){
   131536     c = WO_IS;
   131537   }else{
   131538     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
   131539     c = (u16)(WO_EQ<<(op-TK_EQ));
   131540   }
   131541   assert( op!=TK_ISNULL || c==WO_ISNULL );
   131542   assert( op!=TK_IN || c==WO_IN );
   131543   assert( op!=TK_EQ || c==WO_EQ );
   131544   assert( op!=TK_LT || c==WO_LT );
   131545   assert( op!=TK_LE || c==WO_LE );
   131546   assert( op!=TK_GT || c==WO_GT );
   131547   assert( op!=TK_GE || c==WO_GE );
   131548   assert( op!=TK_IS || c==WO_IS );
   131549   return c;
   131550 }
   131551 
   131552 
   131553 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   131554 /*
   131555 ** Check to see if the given expression is a LIKE or GLOB operator that
   131556 ** can be optimized using inequality constraints.  Return TRUE if it is
   131557 ** so and false if not.
   131558 **
   131559 ** In order for the operator to be optimizible, the RHS must be a string
   131560 ** literal that does not begin with a wildcard.  The LHS must be a column
   131561 ** that may only be NULL, a string, or a BLOB, never a number. (This means
   131562 ** that virtual tables cannot participate in the LIKE optimization.)  The
   131563 ** collating sequence for the column on the LHS must be appropriate for
   131564 ** the operator.
   131565 */
   131566 static int isLikeOrGlob(
   131567   Parse *pParse,    /* Parsing and code generating context */
   131568   Expr *pExpr,      /* Test this expression */
   131569   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
   131570   int *pisComplete, /* True if the only wildcard is % in the last character */
   131571   int *pnoCase      /* True if uppercase is equivalent to lowercase */
   131572 ){
   131573   const u8 *z = 0;         /* String on RHS of LIKE operator */
   131574   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
   131575   ExprList *pList;           /* List of operands to the LIKE operator */
   131576   int c;                     /* One character in z[] */
   131577   int cnt;                   /* Number of non-wildcard prefix characters */
   131578   char wc[4];                /* Wildcard characters */
   131579   sqlite3 *db = pParse->db;  /* Database connection */
   131580   sqlite3_value *pVal = 0;
   131581   int op;                    /* Opcode of pRight */
   131582   int rc;                    /* Result code to return */
   131583 
   131584   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
   131585     return 0;
   131586   }
   131587 #ifdef SQLITE_EBCDIC
   131588   if( *pnoCase ) return 0;
   131589 #endif
   131590   pList = pExpr->x.pList;
   131591   pLeft = pList->a[1].pExpr;
   131592 
   131593   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
   131594   op = pRight->op;
   131595   if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
   131596     Vdbe *pReprepare = pParse->pReprepare;
   131597     int iCol = pRight->iColumn;
   131598     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
   131599     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   131600       z = sqlite3_value_text(pVal);
   131601     }
   131602     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
   131603     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   131604   }else if( op==TK_STRING ){
   131605     z = (u8*)pRight->u.zToken;
   131606   }
   131607   if( z ){
   131608 
   131609     /* If the RHS begins with a digit or a minus sign, then the LHS must
   131610     ** be an ordinary column (not a virtual table column) with TEXT affinity.
   131611     ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
   131612     ** even though "lhs LIKE rhs" is true.  But if the RHS does not start
   131613     ** with a digit or '-', then "lhs LIKE rhs" will always be false if
   131614     ** the LHS is numeric and so the optimization still works.
   131615     */
   131616     if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
   131617       if( pLeft->op!=TK_COLUMN
   131618        || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
   131619        || IsVirtual(pLeft->pTab)  /* Value might be numeric */
   131620       ){
   131621         sqlite3ValueFree(pVal);
   131622         return 0;
   131623       }
   131624     }
   131625 
   131626     /* Count the number of prefix characters prior to the first wildcard */
   131627     cnt = 0;
   131628     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
   131629       cnt++;
   131630       if( c==wc[3] && z[cnt]!=0 ) cnt++;
   131631     }
   131632 
   131633     /* The optimization is possible only if (1) the pattern does not begin
   131634     ** with a wildcard and if (2) the non-wildcard prefix does not end with
   131635     ** an (illegal 0xff) character.  The second condition is necessary so
   131636     ** that we can increment the prefix key to find an upper bound for the
   131637     ** range search.
   131638     */
   131639     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
   131640       Expr *pPrefix;
   131641 
   131642       /* A "complete" match if the pattern ends with "*" or "%" */
   131643       *pisComplete = c==wc[0] && z[cnt+1]==0;
   131644 
   131645       /* Get the pattern prefix.  Remove all escapes from the prefix. */
   131646       pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
   131647       if( pPrefix ){
   131648         int iFrom, iTo;
   131649         char *zNew = pPrefix->u.zToken;
   131650         zNew[cnt] = 0;
   131651         for(iFrom=iTo=0; iFrom<cnt; iFrom++){
   131652           if( zNew[iFrom]==wc[3] ) iFrom++;
   131653           zNew[iTo++] = zNew[iFrom];
   131654         }
   131655         zNew[iTo] = 0;
   131656       }
   131657       *ppPrefix = pPrefix;
   131658 
   131659       /* If the RHS pattern is a bound parameter, make arrangements to
   131660       ** reprepare the statement when that parameter is rebound */
   131661       if( op==TK_VARIABLE ){
   131662         Vdbe *v = pParse->pVdbe;
   131663         sqlite3VdbeSetVarmask(v, pRight->iColumn);
   131664         if( *pisComplete && pRight->u.zToken[1] ){
   131665           /* If the rhs of the LIKE expression is a variable, and the current
   131666           ** value of the variable means there is no need to invoke the LIKE
   131667           ** function, then no OP_Variable will be added to the program.
   131668           ** This causes problems for the sqlite3_bind_parameter_name()
   131669           ** API. To work around them, add a dummy OP_Variable here.
   131670           */
   131671           int r1 = sqlite3GetTempReg(pParse);
   131672           sqlite3ExprCodeTarget(pParse, pRight, r1);
   131673           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
   131674           sqlite3ReleaseTempReg(pParse, r1);
   131675         }
   131676       }
   131677     }else{
   131678       z = 0;
   131679     }
   131680   }
   131681 
   131682   rc = (z!=0);
   131683   sqlite3ValueFree(pVal);
   131684   return rc;
   131685 }
   131686 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   131687 
   131688 
   131689 #ifndef SQLITE_OMIT_VIRTUALTABLE
   131690 /*
   131691 ** Check to see if the pExpr expression is a form that needs to be passed
   131692 ** to the xBestIndex method of virtual tables.  Forms of interest include:
   131693 **
   131694 **          Expression                   Virtual Table Operator
   131695 **          -----------------------      ---------------------------------
   131696 **      1.  column MATCH expr            SQLITE_INDEX_CONSTRAINT_MATCH
   131697 **      2.  column GLOB expr             SQLITE_INDEX_CONSTRAINT_GLOB
   131698 **      3.  column LIKE expr             SQLITE_INDEX_CONSTRAINT_LIKE
   131699 **      4.  column REGEXP expr           SQLITE_INDEX_CONSTRAINT_REGEXP
   131700 **      5.  column != expr               SQLITE_INDEX_CONSTRAINT_NE
   131701 **      6.  expr != column               SQLITE_INDEX_CONSTRAINT_NE
   131702 **      7.  column IS NOT expr           SQLITE_INDEX_CONSTRAINT_ISNOT
   131703 **      8.  expr IS NOT column           SQLITE_INDEX_CONSTRAINT_ISNOT
   131704 **      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL
   131705 **
   131706 ** In every case, "column" must be a column of a virtual table.  If there
   131707 ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
   131708 ** "expr" expression (even though in forms (6) and (8) the column is on the
   131709 ** right and the expression is on the left).  Also set *peOp2 to the
   131710 ** appropriate virtual table operator.  The return value is 1 or 2 if there
   131711 ** is a match.  The usual return is 1, but if the RHS is also a column
   131712 ** of virtual table in forms (5) or (7) then return 2.
   131713 **
   131714 ** If the expression matches none of the patterns above, return 0.
   131715 */
   131716 static int isAuxiliaryVtabOperator(
   131717   Expr *pExpr,                    /* Test this expression */
   131718   unsigned char *peOp2,           /* OUT: 0 for MATCH, or else an op2 value */
   131719   Expr **ppLeft,                  /* Column expression to left of MATCH/op2 */
   131720   Expr **ppRight                  /* Expression to left of MATCH/op2 */
   131721 ){
   131722   if( pExpr->op==TK_FUNCTION ){
   131723     static const struct Op2 {
   131724       const char *zOp;
   131725       unsigned char eOp2;
   131726     } aOp[] = {
   131727       { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
   131728       { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
   131729       { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
   131730       { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
   131731     };
   131732     ExprList *pList;
   131733     Expr *pCol;                     /* Column reference */
   131734     int i;
   131735 
   131736     pList = pExpr->x.pList;
   131737     if( pList==0 || pList->nExpr!=2 ){
   131738       return 0;
   131739     }
   131740     pCol = pList->a[1].pExpr;
   131741     if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
   131742       return 0;
   131743     }
   131744     for(i=0; i<ArraySize(aOp); i++){
   131745       if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
   131746         *peOp2 = aOp[i].eOp2;
   131747         *ppRight = pList->a[0].pExpr;
   131748         *ppLeft = pCol;
   131749         return 1;
   131750       }
   131751     }
   131752   }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
   131753     int res = 0;
   131754     Expr *pLeft = pExpr->pLeft;
   131755     Expr *pRight = pExpr->pRight;
   131756     if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
   131757       res++;
   131758     }
   131759     if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
   131760       res++;
   131761       SWAP(Expr*, pLeft, pRight);
   131762     }
   131763     *ppLeft = pLeft;
   131764     *ppRight = pRight;
   131765     if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
   131766     if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
   131767     if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
   131768     return res;
   131769   }
   131770   return 0;
   131771 }
   131772 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   131773 
   131774 /*
   131775 ** If the pBase expression originated in the ON or USING clause of
   131776 ** a join, then transfer the appropriate markings over to derived.
   131777 */
   131778 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   131779   if( pDerived ){
   131780     pDerived->flags |= pBase->flags & EP_FromJoin;
   131781     pDerived->iRightJoinTable = pBase->iRightJoinTable;
   131782   }
   131783 }
   131784 
   131785 /*
   131786 ** Mark term iChild as being a child of term iParent
   131787 */
   131788 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
   131789   pWC->a[iChild].iParent = iParent;
   131790   pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
   131791   pWC->a[iParent].nChild++;
   131792 }
   131793 
   131794 /*
   131795 ** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
   131796 ** a conjunction, then return just pTerm when N==0.  If N is exceeds
   131797 ** the number of available subterms, return NULL.
   131798 */
   131799 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
   131800   if( pTerm->eOperator!=WO_AND ){
   131801     return N==0 ? pTerm : 0;
   131802   }
   131803   if( N<pTerm->u.pAndInfo->wc.nTerm ){
   131804     return &pTerm->u.pAndInfo->wc.a[N];
   131805   }
   131806   return 0;
   131807 }
   131808 
   131809 /*
   131810 ** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
   131811 ** two subterms are in disjunction - they are OR-ed together.
   131812 **
   131813 ** If these two terms are both of the form:  "A op B" with the same
   131814 ** A and B values but different operators and if the operators are
   131815 ** compatible (if one is = and the other is <, for example) then
   131816 ** add a new virtual AND term to pWC that is the combination of the
   131817 ** two.
   131818 **
   131819 ** Some examples:
   131820 **
   131821 **    x<y OR x=y    -->     x<=y
   131822 **    x=y OR x=y    -->     x=y
   131823 **    x<=y OR x<y   -->     x<=y
   131824 **
   131825 ** The following is NOT generated:
   131826 **
   131827 **    x<y OR x>y    -->     x!=y
   131828 */
   131829 static void whereCombineDisjuncts(
   131830   SrcList *pSrc,         /* the FROM clause */
   131831   WhereClause *pWC,      /* The complete WHERE clause */
   131832   WhereTerm *pOne,       /* First disjunct */
   131833   WhereTerm *pTwo        /* Second disjunct */
   131834 ){
   131835   u16 eOp = pOne->eOperator | pTwo->eOperator;
   131836   sqlite3 *db;           /* Database connection (for malloc) */
   131837   Expr *pNew;            /* New virtual expression */
   131838   int op;                /* Operator for the combined expression */
   131839   int idxNew;            /* Index in pWC of the next virtual term */
   131840 
   131841   if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
   131842   if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
   131843   if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
   131844    && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
   131845   assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
   131846   assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
   131847   if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
   131848   if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
   131849   /* If we reach this point, it means the two subterms can be combined */
   131850   if( (eOp & (eOp-1))!=0 ){
   131851     if( eOp & (WO_LT|WO_LE) ){
   131852       eOp = WO_LE;
   131853     }else{
   131854       assert( eOp & (WO_GT|WO_GE) );
   131855       eOp = WO_GE;
   131856     }
   131857   }
   131858   db = pWC->pWInfo->pParse->db;
   131859   pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
   131860   if( pNew==0 ) return;
   131861   for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
   131862   pNew->op = op;
   131863   idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   131864   exprAnalyze(pSrc, pWC, idxNew);
   131865 }
   131866 
   131867 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   131868 /*
   131869 ** Analyze a term that consists of two or more OR-connected
   131870 ** subterms.  So in:
   131871 **
   131872 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
   131873 **                          ^^^^^^^^^^^^^^^^^^^^
   131874 **
   131875 ** This routine analyzes terms such as the middle term in the above example.
   131876 ** A WhereOrTerm object is computed and attached to the term under
   131877 ** analysis, regardless of the outcome of the analysis.  Hence:
   131878 **
   131879 **     WhereTerm.wtFlags   |=  TERM_ORINFO
   131880 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
   131881 **
   131882 ** The term being analyzed must have two or more of OR-connected subterms.
   131883 ** A single subterm might be a set of AND-connected sub-subterms.
   131884 ** Examples of terms under analysis:
   131885 **
   131886 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
   131887 **     (B)     x=expr1 OR expr2=x OR x=expr3
   131888 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
   131889 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
   131890 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
   131891 **     (F)     x>A OR (x=A AND y>=B)
   131892 **
   131893 ** CASE 1:
   131894 **
   131895 ** If all subterms are of the form T.C=expr for some single column of C and
   131896 ** a single table T (as shown in example B above) then create a new virtual
   131897 ** term that is an equivalent IN expression.  In other words, if the term
   131898 ** being analyzed is:
   131899 **
   131900 **      x = expr1  OR  expr2 = x  OR  x = expr3
   131901 **
   131902 ** then create a new virtual term like this:
   131903 **
   131904 **      x IN (expr1,expr2,expr3)
   131905 **
   131906 ** CASE 2:
   131907 **
   131908 ** If there are exactly two disjuncts and one side has x>A and the other side
   131909 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
   131910 ** WHERE clause of the form "x>=A".  Example:
   131911 **
   131912 **      x>A OR (x=A AND y>B)    adds:    x>=A
   131913 **
   131914 ** The added conjunct can sometimes be helpful in query planning.
   131915 **
   131916 ** CASE 3:
   131917 **
   131918 ** If all subterms are indexable by a single table T, then set
   131919 **
   131920 **     WhereTerm.eOperator              =  WO_OR
   131921 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
   131922 **
   131923 ** A subterm is "indexable" if it is of the form
   131924 ** "T.C <op> <expr>" where C is any column of table T and
   131925 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
   131926 ** A subterm is also indexable if it is an AND of two or more
   131927 ** subsubterms at least one of which is indexable.  Indexable AND
   131928 ** subterms have their eOperator set to WO_AND and they have
   131929 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
   131930 **
   131931 ** From another point of view, "indexable" means that the subterm could
   131932 ** potentially be used with an index if an appropriate index exists.
   131933 ** This analysis does not consider whether or not the index exists; that
   131934 ** is decided elsewhere.  This analysis only looks at whether subterms
   131935 ** appropriate for indexing exist.
   131936 **
   131937 ** All examples A through E above satisfy case 3.  But if a term
   131938 ** also satisfies case 1 (such as B) we know that the optimizer will
   131939 ** always prefer case 1, so in that case we pretend that case 3 is not
   131940 ** satisfied.
   131941 **
   131942 ** It might be the case that multiple tables are indexable.  For example,
   131943 ** (E) above is indexable on tables P, Q, and R.
   131944 **
   131945 ** Terms that satisfy case 3 are candidates for lookup by using
   131946 ** separate indices to find rowids for each subterm and composing
   131947 ** the union of all rowids using a RowSet object.  This is similar
   131948 ** to "bitmap indices" in other database engines.
   131949 **
   131950 ** OTHERWISE:
   131951 **
   131952 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
   131953 ** zero.  This term is not useful for search.
   131954 */
   131955 static void exprAnalyzeOrTerm(
   131956   SrcList *pSrc,            /* the FROM clause */
   131957   WhereClause *pWC,         /* the complete WHERE clause */
   131958   int idxTerm               /* Index of the OR-term to be analyzed */
   131959 ){
   131960   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
   131961   Parse *pParse = pWInfo->pParse;         /* Parser context */
   131962   sqlite3 *db = pParse->db;               /* Database connection */
   131963   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
   131964   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
   131965   int i;                                  /* Loop counters */
   131966   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
   131967   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
   131968   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
   131969   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
   131970   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
   131971 
   131972   /*
   131973   ** Break the OR clause into its separate subterms.  The subterms are
   131974   ** stored in a WhereClause structure containing within the WhereOrInfo
   131975   ** object that is attached to the original OR clause term.
   131976   */
   131977   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
   131978   assert( pExpr->op==TK_OR );
   131979   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
   131980   if( pOrInfo==0 ) return;
   131981   pTerm->wtFlags |= TERM_ORINFO;
   131982   pOrWc = &pOrInfo->wc;
   131983   memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
   131984   sqlite3WhereClauseInit(pOrWc, pWInfo);
   131985   sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
   131986   sqlite3WhereExprAnalyze(pSrc, pOrWc);
   131987   if( db->mallocFailed ) return;
   131988   assert( pOrWc->nTerm>=2 );
   131989 
   131990   /*
   131991   ** Compute the set of tables that might satisfy cases 1 or 3.
   131992   */
   131993   indexable = ~(Bitmask)0;
   131994   chngToIN = ~(Bitmask)0;
   131995   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   131996     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   131997       WhereAndInfo *pAndInfo;
   131998       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   131999       chngToIN = 0;
   132000       pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
   132001       if( pAndInfo ){
   132002         WhereClause *pAndWC;
   132003         WhereTerm *pAndTerm;
   132004         int j;
   132005         Bitmask b = 0;
   132006         pOrTerm->u.pAndInfo = pAndInfo;
   132007         pOrTerm->wtFlags |= TERM_ANDINFO;
   132008         pOrTerm->eOperator = WO_AND;
   132009         pAndWC = &pAndInfo->wc;
   132010         memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
   132011         sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
   132012         sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   132013         sqlite3WhereExprAnalyze(pSrc, pAndWC);
   132014         pAndWC->pOuter = pWC;
   132015         if( !db->mallocFailed ){
   132016           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   132017             assert( pAndTerm->pExpr );
   132018             if( allowedOp(pAndTerm->pExpr->op)
   132019              || pAndTerm->eOperator==WO_AUX
   132020             ){
   132021               b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
   132022             }
   132023           }
   132024         }
   132025         indexable &= b;
   132026       }
   132027     }else if( pOrTerm->wtFlags & TERM_COPIED ){
   132028       /* Skip this term for now.  We revisit it when we process the
   132029       ** corresponding TERM_VIRTUAL term */
   132030     }else{
   132031       Bitmask b;
   132032       b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
   132033       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
   132034         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
   132035         b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
   132036       }
   132037       indexable &= b;
   132038       if( (pOrTerm->eOperator & WO_EQ)==0 ){
   132039         chngToIN = 0;
   132040       }else{
   132041         chngToIN &= b;
   132042       }
   132043     }
   132044   }
   132045 
   132046   /*
   132047   ** Record the set of tables that satisfy case 3.  The set might be
   132048   ** empty.
   132049   */
   132050   pOrInfo->indexable = indexable;
   132051   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
   132052 
   132053   /* For a two-way OR, attempt to implementation case 2.
   132054   */
   132055   if( indexable && pOrWc->nTerm==2 ){
   132056     int iOne = 0;
   132057     WhereTerm *pOne;
   132058     while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
   132059       int iTwo = 0;
   132060       WhereTerm *pTwo;
   132061       while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
   132062         whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
   132063       }
   132064     }
   132065   }
   132066 
   132067   /*
   132068   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
   132069   ** we have to do some additional checking to see if case 1 really
   132070   ** is satisfied.
   132071   **
   132072   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
   132073   ** that there is no possibility of transforming the OR clause into an
   132074   ** IN operator because one or more terms in the OR clause contain
   132075   ** something other than == on a column in the single table.  The 1-bit
   132076   ** case means that every term of the OR clause is of the form
   132077   ** "table.column=expr" for some single table.  The one bit that is set
   132078   ** will correspond to the common table.  We still need to check to make
   132079   ** sure the same column is used on all terms.  The 2-bit case is when
   132080   ** the all terms are of the form "table1.column=table2.column".  It
   132081   ** might be possible to form an IN operator with either table1.column
   132082   ** or table2.column as the LHS if either is common to every term of
   132083   ** the OR clause.
   132084   **
   132085   ** Note that terms of the form "table.column1=table.column2" (the
   132086   ** same table on both sizes of the ==) cannot be optimized.
   132087   */
   132088   if( chngToIN ){
   132089     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
   132090     int iColumn = -1;         /* Column index on lhs of IN operator */
   132091     int iCursor = -1;         /* Table cursor common to all terms */
   132092     int j = 0;                /* Loop counter */
   132093 
   132094     /* Search for a table and column that appears on one side or the
   132095     ** other of the == operator in every subterm.  That table and column
   132096     ** will be recorded in iCursor and iColumn.  There might not be any
   132097     ** such table and column.  Set okToChngToIN if an appropriate table
   132098     ** and column is found but leave okToChngToIN false if not found.
   132099     */
   132100     for(j=0; j<2 && !okToChngToIN; j++){
   132101       pOrTerm = pOrWc->a;
   132102       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
   132103         assert( pOrTerm->eOperator & WO_EQ );
   132104         pOrTerm->wtFlags &= ~TERM_OR_OK;
   132105         if( pOrTerm->leftCursor==iCursor ){
   132106           /* This is the 2-bit case and we are on the second iteration and
   132107           ** current term is from the first iteration.  So skip this term. */
   132108           assert( j==1 );
   132109           continue;
   132110         }
   132111         if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
   132112                                             pOrTerm->leftCursor))==0 ){
   132113           /* This term must be of the form t1.a==t2.b where t2 is in the
   132114           ** chngToIN set but t1 is not.  This term will be either preceded
   132115           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
   132116           ** and use its inversion. */
   132117           testcase( pOrTerm->wtFlags & TERM_COPIED );
   132118           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
   132119           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
   132120           continue;
   132121         }
   132122         iColumn = pOrTerm->u.leftColumn;
   132123         iCursor = pOrTerm->leftCursor;
   132124         break;
   132125       }
   132126       if( i<0 ){
   132127         /* No candidate table+column was found.  This can only occur
   132128         ** on the second iteration */
   132129         assert( j==1 );
   132130         assert( IsPowerOfTwo(chngToIN) );
   132131         assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
   132132         break;
   132133       }
   132134       testcase( j==1 );
   132135 
   132136       /* We have found a candidate table and column.  Check to see if that
   132137       ** table and column is common to every term in the OR clause */
   132138       okToChngToIN = 1;
   132139       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
   132140         assert( pOrTerm->eOperator & WO_EQ );
   132141         if( pOrTerm->leftCursor!=iCursor ){
   132142           pOrTerm->wtFlags &= ~TERM_OR_OK;
   132143         }else if( pOrTerm->u.leftColumn!=iColumn ){
   132144           okToChngToIN = 0;
   132145         }else{
   132146           int affLeft, affRight;
   132147           /* If the right-hand side is also a column, then the affinities
   132148           ** of both right and left sides must be such that no type
   132149           ** conversions are required on the right.  (Ticket #2249)
   132150           */
   132151           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
   132152           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
   132153           if( affRight!=0 && affRight!=affLeft ){
   132154             okToChngToIN = 0;
   132155           }else{
   132156             pOrTerm->wtFlags |= TERM_OR_OK;
   132157           }
   132158         }
   132159       }
   132160     }
   132161 
   132162     /* At this point, okToChngToIN is true if original pTerm satisfies
   132163     ** case 1.  In that case, construct a new virtual term that is
   132164     ** pTerm converted into an IN operator.
   132165     */
   132166     if( okToChngToIN ){
   132167       Expr *pDup;            /* A transient duplicate expression */
   132168       ExprList *pList = 0;   /* The RHS of the IN operator */
   132169       Expr *pLeft = 0;       /* The LHS of the IN operator */
   132170       Expr *pNew;            /* The complete IN operator */
   132171 
   132172       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
   132173         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
   132174         assert( pOrTerm->eOperator & WO_EQ );
   132175         assert( pOrTerm->leftCursor==iCursor );
   132176         assert( pOrTerm->u.leftColumn==iColumn );
   132177         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
   132178         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
   132179         pLeft = pOrTerm->pExpr->pLeft;
   132180       }
   132181       assert( pLeft!=0 );
   132182       pDup = sqlite3ExprDup(db, pLeft, 0);
   132183       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
   132184       if( pNew ){
   132185         int idxNew;
   132186         transferJoinMarkings(pNew, pExpr);
   132187         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   132188         pNew->x.pList = pList;
   132189         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   132190         testcase( idxNew==0 );
   132191         exprAnalyze(pSrc, pWC, idxNew);
   132192         pTerm = &pWC->a[idxTerm];
   132193         markTermAsChild(pWC, idxNew, idxTerm);
   132194       }else{
   132195         sqlite3ExprListDelete(db, pList);
   132196       }
   132197       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
   132198     }
   132199   }
   132200 }
   132201 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
   132202 
   132203 /*
   132204 ** We already know that pExpr is a binary operator where both operands are
   132205 ** column references.  This routine checks to see if pExpr is an equivalence
   132206 ** relation:
   132207 **   1.  The SQLITE_Transitive optimization must be enabled
   132208 **   2.  Must be either an == or an IS operator
   132209 **   3.  Not originating in the ON clause of an OUTER JOIN
   132210 **   4.  The affinities of A and B must be compatible
   132211 **   5a. Both operands use the same collating sequence OR
   132212 **   5b. The overall collating sequence is BINARY
   132213 ** If this routine returns TRUE, that means that the RHS can be substituted
   132214 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
   132215 ** This is an optimization.  No harm comes from returning 0.  But if 1 is
   132216 ** returned when it should not be, then incorrect answers might result.
   132217 */
   132218 static int termIsEquivalence(Parse *pParse, Expr *pExpr){
   132219   char aff1, aff2;
   132220   CollSeq *pColl;
   132221   if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
   132222   if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
   132223   if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
   132224   aff1 = sqlite3ExprAffinity(pExpr->pLeft);
   132225   aff2 = sqlite3ExprAffinity(pExpr->pRight);
   132226   if( aff1!=aff2
   132227    && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
   132228   ){
   132229     return 0;
   132230   }
   132231   pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
   132232   if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
   132233   return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
   132234 }
   132235 
   132236 /*
   132237 ** Recursively walk the expressions of a SELECT statement and generate
   132238 ** a bitmask indicating which tables are used in that expression
   132239 ** tree.
   132240 */
   132241 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
   132242   Bitmask mask = 0;
   132243   while( pS ){
   132244     SrcList *pSrc = pS->pSrc;
   132245     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
   132246     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
   132247     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
   132248     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
   132249     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
   132250     if( ALWAYS(pSrc!=0) ){
   132251       int i;
   132252       for(i=0; i<pSrc->nSrc; i++){
   132253         mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
   132254         mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
   132255       }
   132256     }
   132257     pS = pS->pPrior;
   132258   }
   132259   return mask;
   132260 }
   132261 
   132262 /*
   132263 ** Expression pExpr is one operand of a comparison operator that might
   132264 ** be useful for indexing.  This routine checks to see if pExpr appears
   132265 ** in any index.  Return TRUE (1) if pExpr is an indexed term and return
   132266 ** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor
   132267 ** number of the table that is indexed and aiCurCol[1] to the column number
   132268 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
   132269 ** indexed.
   132270 **
   132271 ** If pExpr is a TK_COLUMN column reference, then this routine always returns
   132272 ** true even if that particular column is not indexed, because the column
   132273 ** might be added to an automatic index later.
   132274 */
   132275 static SQLITE_NOINLINE int exprMightBeIndexed2(
   132276   SrcList *pFrom,        /* The FROM clause */
   132277   Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
   132278   int *aiCurCol,         /* Write the referenced table cursor and column here */
   132279   Expr *pExpr            /* An operand of a comparison operator */
   132280 ){
   132281   Index *pIdx;
   132282   int i;
   132283   int iCur;
   132284   for(i=0; mPrereq>1; i++, mPrereq>>=1){}
   132285   iCur = pFrom->a[i].iCursor;
   132286   for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   132287     if( pIdx->aColExpr==0 ) continue;
   132288     for(i=0; i<pIdx->nKeyCol; i++){
   132289       if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
   132290       if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
   132291         aiCurCol[0] = iCur;
   132292         aiCurCol[1] = XN_EXPR;
   132293         return 1;
   132294       }
   132295     }
   132296   }
   132297   return 0;
   132298 }
   132299 static int exprMightBeIndexed(
   132300   SrcList *pFrom,        /* The FROM clause */
   132301   Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
   132302   int *aiCurCol,         /* Write the referenced table cursor & column here */
   132303   Expr *pExpr,           /* An operand of a comparison operator */
   132304   int op                 /* The specific comparison operator */
   132305 ){
   132306   /* If this expression is a vector to the left or right of a
   132307   ** inequality constraint (>, <, >= or <=), perform the processing
   132308   ** on the first element of the vector.  */
   132309   assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
   132310   assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
   132311   assert( op<=TK_GE );
   132312   if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
   132313     pExpr = pExpr->x.pList->a[0].pExpr;
   132314   }
   132315 
   132316   if( pExpr->op==TK_COLUMN ){
   132317     aiCurCol[0] = pExpr->iTable;
   132318     aiCurCol[1] = pExpr->iColumn;
   132319     return 1;
   132320   }
   132321   if( mPrereq==0 ) return 0;                 /* No table references */
   132322   if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
   132323   return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
   132324 }
   132325 
   132326 /*
   132327 ** The input to this routine is an WhereTerm structure with only the
   132328 ** "pExpr" field filled in.  The job of this routine is to analyze the
   132329 ** subexpression and populate all the other fields of the WhereTerm
   132330 ** structure.
   132331 **
   132332 ** If the expression is of the form "<expr> <op> X" it gets commuted
   132333 ** to the standard form of "X <op> <expr>".
   132334 **
   132335 ** If the expression is of the form "X <op> Y" where both X and Y are
   132336 ** columns, then the original expression is unchanged and a new virtual
   132337 ** term of the form "Y <op> X" is added to the WHERE clause and
   132338 ** analyzed separately.  The original term is marked with TERM_COPIED
   132339 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
   132340 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
   132341 ** is a commuted copy of a prior term.)  The original term has nChild=1
   132342 ** and the copy has idxParent set to the index of the original term.
   132343 */
   132344 static void exprAnalyze(
   132345   SrcList *pSrc,            /* the FROM clause */
   132346   WhereClause *pWC,         /* the WHERE clause */
   132347   int idxTerm               /* Index of the term to be analyzed */
   132348 ){
   132349   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
   132350   WhereTerm *pTerm;                /* The term to be analyzed */
   132351   WhereMaskSet *pMaskSet;          /* Set of table index masks */
   132352   Expr *pExpr;                     /* The expression to be analyzed */
   132353   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
   132354   Bitmask prereqAll;               /* Prerequesites of pExpr */
   132355   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
   132356   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
   132357   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
   132358   int noCase = 0;                  /* uppercase equivalent to lowercase */
   132359   int op;                          /* Top-level operator.  pExpr->op */
   132360   Parse *pParse = pWInfo->pParse;  /* Parsing context */
   132361   sqlite3 *db = pParse->db;        /* Database connection */
   132362   unsigned char eOp2 = 0;          /* op2 value for LIKE/REGEXP/GLOB */
   132363   int nLeft;                       /* Number of elements on left side vector */
   132364 
   132365   if( db->mallocFailed ){
   132366     return;
   132367   }
   132368   pTerm = &pWC->a[idxTerm];
   132369   pMaskSet = &pWInfo->sMaskSet;
   132370   pExpr = pTerm->pExpr;
   132371   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
   132372   prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
   132373   op = pExpr->op;
   132374   if( op==TK_IN ){
   132375     assert( pExpr->pRight==0 );
   132376     if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
   132377     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   132378       pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
   132379     }else{
   132380       pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
   132381     }
   132382   }else if( op==TK_ISNULL ){
   132383     pTerm->prereqRight = 0;
   132384   }else{
   132385     pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
   132386   }
   132387   pMaskSet->bVarSelect = 0;
   132388   prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
   132389   if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
   132390   if( ExprHasProperty(pExpr, EP_FromJoin) ){
   132391     Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
   132392     prereqAll |= x;
   132393     extraRight = x-1;  /* ON clause terms may not be used with an index
   132394                        ** on left table of a LEFT JOIN.  Ticket #3015 */
   132395     if( (prereqAll>>1)>=x ){
   132396       sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
   132397       return;
   132398     }
   132399   }
   132400   pTerm->prereqAll = prereqAll;
   132401   pTerm->leftCursor = -1;
   132402   pTerm->iParent = -1;
   132403   pTerm->eOperator = 0;
   132404   if( allowedOp(op) ){
   132405     int aiCurCol[2];
   132406     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
   132407     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
   132408     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
   132409 
   132410     if( pTerm->iField>0 ){
   132411       assert( op==TK_IN );
   132412       assert( pLeft->op==TK_VECTOR );
   132413       pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
   132414     }
   132415 
   132416     if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
   132417       pTerm->leftCursor = aiCurCol[0];
   132418       pTerm->u.leftColumn = aiCurCol[1];
   132419       pTerm->eOperator = operatorMask(op) & opMask;
   132420     }
   132421     if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
   132422     if( pRight
   132423      && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
   132424     ){
   132425       WhereTerm *pNew;
   132426       Expr *pDup;
   132427       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
   132428       assert( pTerm->iField==0 );
   132429       if( pTerm->leftCursor>=0 ){
   132430         int idxNew;
   132431         pDup = sqlite3ExprDup(db, pExpr, 0);
   132432         if( db->mallocFailed ){
   132433           sqlite3ExprDelete(db, pDup);
   132434           return;
   132435         }
   132436         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
   132437         if( idxNew==0 ) return;
   132438         pNew = &pWC->a[idxNew];
   132439         markTermAsChild(pWC, idxNew, idxTerm);
   132440         if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
   132441         pTerm = &pWC->a[idxTerm];
   132442         pTerm->wtFlags |= TERM_COPIED;
   132443 
   132444         if( termIsEquivalence(pParse, pDup) ){
   132445           pTerm->eOperator |= WO_EQUIV;
   132446           eExtraOp = WO_EQUIV;
   132447         }
   132448       }else{
   132449         pDup = pExpr;
   132450         pNew = pTerm;
   132451       }
   132452       exprCommute(pParse, pDup);
   132453       pNew->leftCursor = aiCurCol[0];
   132454       pNew->u.leftColumn = aiCurCol[1];
   132455       testcase( (prereqLeft | extraRight) != prereqLeft );
   132456       pNew->prereqRight = prereqLeft | extraRight;
   132457       pNew->prereqAll = prereqAll;
   132458       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
   132459     }
   132460   }
   132461 
   132462 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   132463   /* If a term is the BETWEEN operator, create two new virtual terms
   132464   ** that define the range that the BETWEEN implements.  For example:
   132465   **
   132466   **      a BETWEEN b AND c
   132467   **
   132468   ** is converted into:
   132469   **
   132470   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
   132471   **
   132472   ** The two new terms are added onto the end of the WhereClause object.
   132473   ** The new terms are "dynamic" and are children of the original BETWEEN
   132474   ** term.  That means that if the BETWEEN term is coded, the children are
   132475   ** skipped.  Or, if the children are satisfied by an index, the original
   132476   ** BETWEEN term is skipped.
   132477   */
   132478   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
   132479     ExprList *pList = pExpr->x.pList;
   132480     int i;
   132481     static const u8 ops[] = {TK_GE, TK_LE};
   132482     assert( pList!=0 );
   132483     assert( pList->nExpr==2 );
   132484     for(i=0; i<2; i++){
   132485       Expr *pNewExpr;
   132486       int idxNew;
   132487       pNewExpr = sqlite3PExpr(pParse, ops[i],
   132488                              sqlite3ExprDup(db, pExpr->pLeft, 0),
   132489                              sqlite3ExprDup(db, pList->a[i].pExpr, 0));
   132490       transferJoinMarkings(pNewExpr, pExpr);
   132491       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   132492       testcase( idxNew==0 );
   132493       exprAnalyze(pSrc, pWC, idxNew);
   132494       pTerm = &pWC->a[idxTerm];
   132495       markTermAsChild(pWC, idxNew, idxTerm);
   132496     }
   132497   }
   132498 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
   132499 
   132500 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   132501   /* Analyze a term that is composed of two or more subterms connected by
   132502   ** an OR operator.
   132503   */
   132504   else if( pExpr->op==TK_OR ){
   132505     assert( pWC->op==TK_AND );
   132506     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
   132507     pTerm = &pWC->a[idxTerm];
   132508   }
   132509 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   132510 
   132511 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   132512   /* Add constraints to reduce the search space on a LIKE or GLOB
   132513   ** operator.
   132514   **
   132515   ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
   132516   **
   132517   **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
   132518   **
   132519   ** The last character of the prefix "abc" is incremented to form the
   132520   ** termination condition "abd".  If case is not significant (the default
   132521   ** for LIKE) then the lower-bound is made all uppercase and the upper-
   132522   ** bound is made all lowercase so that the bounds also work when comparing
   132523   ** BLOBs.
   132524   */
   132525   if( pWC->op==TK_AND
   132526    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   132527   ){
   132528     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
   132529     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
   132530     Expr *pNewExpr1;
   132531     Expr *pNewExpr2;
   132532     int idxNew1;
   132533     int idxNew2;
   132534     const char *zCollSeqName;     /* Name of collating sequence */
   132535     const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
   132536 
   132537     pLeft = pExpr->x.pList->a[1].pExpr;
   132538     pStr2 = sqlite3ExprDup(db, pStr1, 0);
   132539 
   132540     /* Convert the lower bound to upper-case and the upper bound to
   132541     ** lower-case (upper-case is less than lower-case in ASCII) so that
   132542     ** the range constraints also work for BLOBs
   132543     */
   132544     if( noCase && !pParse->db->mallocFailed ){
   132545       int i;
   132546       char c;
   132547       pTerm->wtFlags |= TERM_LIKE;
   132548       for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
   132549         pStr1->u.zToken[i] = sqlite3Toupper(c);
   132550         pStr2->u.zToken[i] = sqlite3Tolower(c);
   132551       }
   132552     }
   132553 
   132554     if( !db->mallocFailed ){
   132555       u8 c, *pC;       /* Last character before the first wildcard */
   132556       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
   132557       c = *pC;
   132558       if( noCase ){
   132559         /* The point is to increment the last character before the first
   132560         ** wildcard.  But if we increment '@', that will push it into the
   132561         ** alphabetic range where case conversions will mess up the
   132562         ** inequality.  To avoid this, make sure to also run the full
   132563         ** LIKE on all candidate expressions by clearing the isComplete flag
   132564         */
   132565         if( c=='A'-1 ) isComplete = 0;
   132566         c = sqlite3UpperToLower[c];
   132567       }
   132568       *pC = c + 1;
   132569     }
   132570     zCollSeqName = noCase ? "NOCASE" : "BINARY";
   132571     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
   132572     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
   132573            sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
   132574            pStr1);
   132575     transferJoinMarkings(pNewExpr1, pExpr);
   132576     idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
   132577     testcase( idxNew1==0 );
   132578     exprAnalyze(pSrc, pWC, idxNew1);
   132579     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
   132580     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
   132581            sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
   132582            pStr2);
   132583     transferJoinMarkings(pNewExpr2, pExpr);
   132584     idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
   132585     testcase( idxNew2==0 );
   132586     exprAnalyze(pSrc, pWC, idxNew2);
   132587     pTerm = &pWC->a[idxTerm];
   132588     if( isComplete ){
   132589       markTermAsChild(pWC, idxNew1, idxTerm);
   132590       markTermAsChild(pWC, idxNew2, idxTerm);
   132591     }
   132592   }
   132593 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   132594 
   132595 #ifndef SQLITE_OMIT_VIRTUALTABLE
   132596   /* Add a WO_AUX auxiliary term to the constraint set if the
   132597   ** current expression is of the form "column OP expr" where OP
   132598   ** is an operator that gets passed into virtual tables but which is
   132599   ** not normally optimized for ordinary tables.  In other words, OP
   132600   ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
   132601   ** This information is used by the xBestIndex methods of
   132602   ** virtual tables.  The native query optimizer does not attempt
   132603   ** to do anything with MATCH functions.
   132604   */
   132605   if( pWC->op==TK_AND ){
   132606     Expr *pRight = 0, *pLeft = 0;
   132607     int res = isAuxiliaryVtabOperator(pExpr, &eOp2, &pLeft, &pRight);
   132608     while( res-- > 0 ){
   132609       int idxNew;
   132610       WhereTerm *pNewTerm;
   132611       Bitmask prereqColumn, prereqExpr;
   132612 
   132613       prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
   132614       prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
   132615       if( (prereqExpr & prereqColumn)==0 ){
   132616         Expr *pNewExpr;
   132617         pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
   132618             0, sqlite3ExprDup(db, pRight, 0));
   132619         if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
   132620           ExprSetProperty(pNewExpr, EP_FromJoin);
   132621         }
   132622         idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   132623         testcase( idxNew==0 );
   132624         pNewTerm = &pWC->a[idxNew];
   132625         pNewTerm->prereqRight = prereqExpr;
   132626         pNewTerm->leftCursor = pLeft->iTable;
   132627         pNewTerm->u.leftColumn = pLeft->iColumn;
   132628         pNewTerm->eOperator = WO_AUX;
   132629         pNewTerm->eMatchOp = eOp2;
   132630         markTermAsChild(pWC, idxNew, idxTerm);
   132631         pTerm = &pWC->a[idxTerm];
   132632         pTerm->wtFlags |= TERM_COPIED;
   132633         pNewTerm->prereqAll = pTerm->prereqAll;
   132634       }
   132635       SWAP(Expr*, pLeft, pRight);
   132636     }
   132637   }
   132638 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   132639 
   132640   /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
   132641   ** new terms for each component comparison - "a = ?" and "b = ?".  The
   132642   ** new terms completely replace the original vector comparison, which is
   132643   ** no longer used.
   132644   **
   132645   ** This is only required if at least one side of the comparison operation
   132646   ** is not a sub-select.  */
   132647   if( pWC->op==TK_AND
   132648   && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
   132649   && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
   132650   && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
   132651   && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
   132652     || (pExpr->pRight->flags & EP_xIsSelect)==0)
   132653   ){
   132654     int i;
   132655     for(i=0; i<nLeft; i++){
   132656       int idxNew;
   132657       Expr *pNew;
   132658       Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
   132659       Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
   132660 
   132661       pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
   132662       transferJoinMarkings(pNew, pExpr);
   132663       idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
   132664       exprAnalyze(pSrc, pWC, idxNew);
   132665     }
   132666     pTerm = &pWC->a[idxTerm];
   132667     pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
   132668     pTerm->eOperator = 0;
   132669   }
   132670 
   132671   /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
   132672   ** a virtual term for each vector component. The expression object
   132673   ** used by each such virtual term is pExpr (the full vector IN(...)
   132674   ** expression). The WhereTerm.iField variable identifies the index within
   132675   ** the vector on the LHS that the virtual term represents.
   132676   **
   132677   ** This only works if the RHS is a simple SELECT, not a compound
   132678   */
   132679   if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
   132680    && pExpr->pLeft->op==TK_VECTOR
   132681    && pExpr->x.pSelect->pPrior==0
   132682   ){
   132683     int i;
   132684     for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
   132685       int idxNew;
   132686       idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
   132687       pWC->a[idxNew].iField = i+1;
   132688       exprAnalyze(pSrc, pWC, idxNew);
   132689       markTermAsChild(pWC, idxNew, idxTerm);
   132690     }
   132691   }
   132692 
   132693 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   132694   /* When sqlite_stat3 histogram data is available an operator of the
   132695   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
   132696   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
   132697   ** virtual term of that form.
   132698   **
   132699   ** Note that the virtual term must be tagged with TERM_VNULL.
   132700   */
   132701   if( pExpr->op==TK_NOTNULL
   132702    && pExpr->pLeft->op==TK_COLUMN
   132703    && pExpr->pLeft->iColumn>=0
   132704    && OptimizationEnabled(db, SQLITE_Stat34)
   132705   ){
   132706     Expr *pNewExpr;
   132707     Expr *pLeft = pExpr->pLeft;
   132708     int idxNew;
   132709     WhereTerm *pNewTerm;
   132710 
   132711     pNewExpr = sqlite3PExpr(pParse, TK_GT,
   132712                             sqlite3ExprDup(db, pLeft, 0),
   132713                             sqlite3ExprAlloc(db, TK_NULL, 0, 0));
   132714 
   132715     idxNew = whereClauseInsert(pWC, pNewExpr,
   132716                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
   132717     if( idxNew ){
   132718       pNewTerm = &pWC->a[idxNew];
   132719       pNewTerm->prereqRight = 0;
   132720       pNewTerm->leftCursor = pLeft->iTable;
   132721       pNewTerm->u.leftColumn = pLeft->iColumn;
   132722       pNewTerm->eOperator = WO_GT;
   132723       markTermAsChild(pWC, idxNew, idxTerm);
   132724       pTerm = &pWC->a[idxTerm];
   132725       pTerm->wtFlags |= TERM_COPIED;
   132726       pNewTerm->prereqAll = pTerm->prereqAll;
   132727     }
   132728   }
   132729 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   132730 
   132731   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   132732   ** an index for tables to the left of the join.
   132733   */
   132734   testcase( pTerm!=&pWC->a[idxTerm] );
   132735   pTerm = &pWC->a[idxTerm];
   132736   pTerm->prereqRight |= extraRight;
   132737 }
   132738 
   132739 /***************************************************************************
   132740 ** Routines with file scope above.  Interface to the rest of the where.c
   132741 ** subsystem follows.
   132742 ***************************************************************************/
   132743 
   132744 /*
   132745 ** This routine identifies subexpressions in the WHERE clause where
   132746 ** each subexpression is separated by the AND operator or some other
   132747 ** operator specified in the op parameter.  The WhereClause structure
   132748 ** is filled with pointers to subexpressions.  For example:
   132749 **
   132750 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
   132751 **           \________/     \_______________/     \________________/
   132752 **            slot[0]            slot[1]               slot[2]
   132753 **
   132754 ** The original WHERE clause in pExpr is unaltered.  All this routine
   132755 ** does is make slot[] entries point to substructure within pExpr.
   132756 **
   132757 ** In the previous sentence and in the diagram, "slot[]" refers to
   132758 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
   132759 ** all terms of the WHERE clause.
   132760 */
   132761 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
   132762   Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
   132763   pWC->op = op;
   132764   if( pE2==0 ) return;
   132765   if( pE2->op!=op ){
   132766     whereClauseInsert(pWC, pExpr, 0);
   132767   }else{
   132768     sqlite3WhereSplit(pWC, pE2->pLeft, op);
   132769     sqlite3WhereSplit(pWC, pE2->pRight, op);
   132770   }
   132771 }
   132772 
   132773 /*
   132774 ** Initialize a preallocated WhereClause structure.
   132775 */
   132776 SQLITE_PRIVATE void sqlite3WhereClauseInit(
   132777   WhereClause *pWC,        /* The WhereClause to be initialized */
   132778   WhereInfo *pWInfo        /* The WHERE processing context */
   132779 ){
   132780   pWC->pWInfo = pWInfo;
   132781   pWC->pOuter = 0;
   132782   pWC->nTerm = 0;
   132783   pWC->nSlot = ArraySize(pWC->aStatic);
   132784   pWC->a = pWC->aStatic;
   132785 }
   132786 
   132787 /*
   132788 ** Deallocate a WhereClause structure.  The WhereClause structure
   132789 ** itself is not freed.  This routine is the inverse of
   132790 ** sqlite3WhereClauseInit().
   132791 */
   132792 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
   132793   int i;
   132794   WhereTerm *a;
   132795   sqlite3 *db = pWC->pWInfo->pParse->db;
   132796   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
   132797     if( a->wtFlags & TERM_DYNAMIC ){
   132798       sqlite3ExprDelete(db, a->pExpr);
   132799     }
   132800     if( a->wtFlags & TERM_ORINFO ){
   132801       whereOrInfoDelete(db, a->u.pOrInfo);
   132802     }else if( a->wtFlags & TERM_ANDINFO ){
   132803       whereAndInfoDelete(db, a->u.pAndInfo);
   132804     }
   132805   }
   132806   if( pWC->a!=pWC->aStatic ){
   132807     sqlite3DbFree(db, pWC->a);
   132808   }
   132809 }
   132810 
   132811 
   132812 /*
   132813 ** These routines walk (recursively) an expression tree and generate
   132814 ** a bitmask indicating which tables are used in that expression
   132815 ** tree.
   132816 */
   132817 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
   132818   Bitmask mask;
   132819   if( p==0 ) return 0;
   132820   if( p->op==TK_COLUMN ){
   132821     return sqlite3WhereGetMask(pMaskSet, p->iTable);
   132822   }
   132823   mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
   132824   assert( !ExprHasProperty(p, EP_TokenOnly) );
   132825   if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
   132826   if( p->pRight ){
   132827     mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
   132828     assert( p->x.pList==0 );
   132829   }else if( ExprHasProperty(p, EP_xIsSelect) ){
   132830     if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
   132831     mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
   132832   }else if( p->x.pList ){
   132833     mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
   132834   }
   132835   return mask;
   132836 }
   132837 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
   132838   int i;
   132839   Bitmask mask = 0;
   132840   if( pList ){
   132841     for(i=0; i<pList->nExpr; i++){
   132842       mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
   132843     }
   132844   }
   132845   return mask;
   132846 }
   132847 
   132848 
   132849 /*
   132850 ** Call exprAnalyze on all terms in a WHERE clause.
   132851 **
   132852 ** Note that exprAnalyze() might add new virtual terms onto the
   132853 ** end of the WHERE clause.  We do not want to analyze these new
   132854 ** virtual terms, so start analyzing at the end and work forward
   132855 ** so that the added virtual terms are never processed.
   132856 */
   132857 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
   132858   SrcList *pTabList,       /* the FROM clause */
   132859   WhereClause *pWC         /* the WHERE clause to be analyzed */
   132860 ){
   132861   int i;
   132862   for(i=pWC->nTerm-1; i>=0; i--){
   132863     exprAnalyze(pTabList, pWC, i);
   132864   }
   132865 }
   132866 
   132867 /*
   132868 ** For table-valued-functions, transform the function arguments into
   132869 ** new WHERE clause terms.
   132870 **
   132871 ** Each function argument translates into an equality constraint against
   132872 ** a HIDDEN column in the table.
   132873 */
   132874 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
   132875   Parse *pParse,                    /* Parsing context */
   132876   struct SrcList_item *pItem,       /* The FROM clause term to process */
   132877   WhereClause *pWC                  /* Xfer function arguments to here */
   132878 ){
   132879   Table *pTab;
   132880   int j, k;
   132881   ExprList *pArgs;
   132882   Expr *pColRef;
   132883   Expr *pTerm;
   132884   if( pItem->fg.isTabFunc==0 ) return;
   132885   pTab = pItem->pTab;
   132886   assert( pTab!=0 );
   132887   pArgs = pItem->u1.pFuncArg;
   132888   if( pArgs==0 ) return;
   132889   for(j=k=0; j<pArgs->nExpr; j++){
   132890     while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
   132891     if( k>=pTab->nCol ){
   132892       sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
   132893                       pTab->zName, j);
   132894       return;
   132895     }
   132896     pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
   132897     if( pColRef==0 ) return;
   132898     pColRef->iTable = pItem->iCursor;
   132899     pColRef->iColumn = k++;
   132900     pColRef->pTab = pTab;
   132901     pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
   132902                          sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
   132903     whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
   132904   }
   132905 }
   132906 
   132907 /************** End of whereexpr.c *******************************************/
   132908 /************** Begin file where.c *******************************************/
   132909 /*
   132910 ** 2001 September 15
   132911 **
   132912 ** The author disclaims copyright to this source code.  In place of
   132913 ** a legal notice, here is a blessing:
   132914 **
   132915 **    May you do good and not evil.
   132916 **    May you find forgiveness for yourself and forgive others.
   132917 **    May you share freely, never taking more than you give.
   132918 **
   132919 *************************************************************************
   132920 ** This module contains C code that generates VDBE code used to process
   132921 ** the WHERE clause of SQL statements.  This module is responsible for
   132922 ** generating the code that loops through a table looking for applicable
   132923 ** rows.  Indices are selected and used to speed the search when doing
   132924 ** so is applicable.  Because this module is responsible for selecting
   132925 ** indices, you might also think of this module as the "query optimizer".
   132926 */
   132927 /* #include "sqliteInt.h" */
   132928 /* #include "whereInt.h" */
   132929 
   132930 /*
   132931 ** Extra information appended to the end of sqlite3_index_info but not
   132932 ** visible to the xBestIndex function, at least not directly.  The
   132933 ** sqlite3_vtab_collation() interface knows how to reach it, however.
   132934 **
   132935 ** This object is not an API and can be changed from one release to the
   132936 ** next.  As long as allocateIndexInfo() and sqlite3_vtab_collation()
   132937 ** agree on the structure, all will be well.
   132938 */
   132939 typedef struct HiddenIndexInfo HiddenIndexInfo;
   132940 struct HiddenIndexInfo {
   132941   WhereClause *pWC;   /* The Where clause being analyzed */
   132942   Parse *pParse;      /* The parsing context */
   132943 };
   132944 
   132945 /* Forward declaration of methods */
   132946 static int whereLoopResize(sqlite3*, WhereLoop*, int);
   132947 
   132948 /* Test variable that can be set to enable WHERE tracing */
   132949 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   132950 /***/ int sqlite3WhereTrace = 0;
   132951 #endif
   132952 
   132953 
   132954 /*
   132955 ** Return the estimated number of output rows from a WHERE clause
   132956 */
   132957 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
   132958   return pWInfo->nRowOut;
   132959 }
   132960 
   132961 /*
   132962 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
   132963 ** WHERE clause returns outputs for DISTINCT processing.
   132964 */
   132965 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
   132966   return pWInfo->eDistinct;
   132967 }
   132968 
   132969 /*
   132970 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
   132971 ** Return FALSE if the output needs to be sorted.
   132972 */
   132973 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
   132974   return pWInfo->nOBSat;
   132975 }
   132976 
   132977 /*
   132978 ** Return TRUE if the innermost loop of the WHERE clause implementation
   132979 ** returns rows in ORDER BY order for complete run of the inner loop.
   132980 **
   132981 ** Across multiple iterations of outer loops, the output rows need not be
   132982 ** sorted.  As long as rows are sorted for just the innermost loop, this
   132983 ** routine can return TRUE.
   132984 */
   132985 SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
   132986   return pWInfo->bOrderedInnerLoop;
   132987 }
   132988 
   132989 /*
   132990 ** Return the VDBE address or label to jump to in order to continue
   132991 ** immediately with the next row of a WHERE clause.
   132992 */
   132993 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
   132994   assert( pWInfo->iContinue!=0 );
   132995   return pWInfo->iContinue;
   132996 }
   132997 
   132998 /*
   132999 ** Return the VDBE address or label to jump to in order to break
   133000 ** out of a WHERE loop.
   133001 */
   133002 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
   133003   return pWInfo->iBreak;
   133004 }
   133005 
   133006 /*
   133007 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
   133008 ** operate directly on the rowis returned by a WHERE clause.  Return
   133009 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
   133010 ** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
   133011 ** optimization can be used on multiple
   133012 **
   133013 ** If the ONEPASS optimization is used (if this routine returns true)
   133014 ** then also write the indices of open cursors used by ONEPASS
   133015 ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
   133016 ** table and iaCur[1] gets the cursor used by an auxiliary index.
   133017 ** Either value may be -1, indicating that cursor is not used.
   133018 ** Any cursors returned will have been opened for writing.
   133019 **
   133020 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
   133021 ** unable to use the ONEPASS optimization.
   133022 */
   133023 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
   133024   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
   133025 #ifdef WHERETRACE_ENABLED
   133026   if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
   133027     sqlite3DebugPrintf("%s cursors: %d %d\n",
   133028          pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
   133029          aiCur[0], aiCur[1]);
   133030   }
   133031 #endif
   133032   return pWInfo->eOnePass;
   133033 }
   133034 
   133035 /*
   133036 ** Move the content of pSrc into pDest
   133037 */
   133038 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
   133039   pDest->n = pSrc->n;
   133040   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
   133041 }
   133042 
   133043 /*
   133044 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
   133045 **
   133046 ** The new entry might overwrite an existing entry, or it might be
   133047 ** appended, or it might be discarded.  Do whatever is the right thing
   133048 ** so that pSet keeps the N_OR_COST best entries seen so far.
   133049 */
   133050 static int whereOrInsert(
   133051   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
   133052   Bitmask prereq,        /* Prerequisites of the new entry */
   133053   LogEst rRun,           /* Run-cost of the new entry */
   133054   LogEst nOut            /* Number of outputs for the new entry */
   133055 ){
   133056   u16 i;
   133057   WhereOrCost *p;
   133058   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
   133059     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
   133060       goto whereOrInsert_done;
   133061     }
   133062     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
   133063       return 0;
   133064     }
   133065   }
   133066   if( pSet->n<N_OR_COST ){
   133067     p = &pSet->a[pSet->n++];
   133068     p->nOut = nOut;
   133069   }else{
   133070     p = pSet->a;
   133071     for(i=1; i<pSet->n; i++){
   133072       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
   133073     }
   133074     if( p->rRun<=rRun ) return 0;
   133075   }
   133076 whereOrInsert_done:
   133077   p->prereq = prereq;
   133078   p->rRun = rRun;
   133079   if( p->nOut>nOut ) p->nOut = nOut;
   133080   return 1;
   133081 }
   133082 
   133083 /*
   133084 ** Return the bitmask for the given cursor number.  Return 0 if
   133085 ** iCursor is not in the set.
   133086 */
   133087 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
   133088   int i;
   133089   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
   133090   for(i=0; i<pMaskSet->n; i++){
   133091     if( pMaskSet->ix[i]==iCursor ){
   133092       return MASKBIT(i);
   133093     }
   133094   }
   133095   return 0;
   133096 }
   133097 
   133098 /*
   133099 ** Create a new mask for cursor iCursor.
   133100 **
   133101 ** There is one cursor per table in the FROM clause.  The number of
   133102 ** tables in the FROM clause is limited by a test early in the
   133103 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
   133104 ** array will never overflow.
   133105 */
   133106 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   133107   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   133108   pMaskSet->ix[pMaskSet->n++] = iCursor;
   133109 }
   133110 
   133111 /*
   133112 ** Advance to the next WhereTerm that matches according to the criteria
   133113 ** established when the pScan object was initialized by whereScanInit().
   133114 ** Return NULL if there are no more matching WhereTerms.
   133115 */
   133116 static WhereTerm *whereScanNext(WhereScan *pScan){
   133117   int iCur;            /* The cursor on the LHS of the term */
   133118   i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
   133119   Expr *pX;            /* An expression being tested */
   133120   WhereClause *pWC;    /* Shorthand for pScan->pWC */
   133121   WhereTerm *pTerm;    /* The term being tested */
   133122   int k = pScan->k;    /* Where to start scanning */
   133123 
   133124   assert( pScan->iEquiv<=pScan->nEquiv );
   133125   pWC = pScan->pWC;
   133126   while(1){
   133127     iColumn = pScan->aiColumn[pScan->iEquiv-1];
   133128     iCur = pScan->aiCur[pScan->iEquiv-1];
   133129     assert( pWC!=0 );
   133130     do{
   133131       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
   133132         if( pTerm->leftCursor==iCur
   133133          && pTerm->u.leftColumn==iColumn
   133134          && (iColumn!=XN_EXPR
   133135              || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
   133136                                        pScan->pIdxExpr,iCur)==0)
   133137          && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   133138         ){
   133139           if( (pTerm->eOperator & WO_EQUIV)!=0
   133140            && pScan->nEquiv<ArraySize(pScan->aiCur)
   133141            && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
   133142           ){
   133143             int j;
   133144             for(j=0; j<pScan->nEquiv; j++){
   133145               if( pScan->aiCur[j]==pX->iTable
   133146                && pScan->aiColumn[j]==pX->iColumn ){
   133147                   break;
   133148               }
   133149             }
   133150             if( j==pScan->nEquiv ){
   133151               pScan->aiCur[j] = pX->iTable;
   133152               pScan->aiColumn[j] = pX->iColumn;
   133153               pScan->nEquiv++;
   133154             }
   133155           }
   133156           if( (pTerm->eOperator & pScan->opMask)!=0 ){
   133157             /* Verify the affinity and collating sequence match */
   133158             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
   133159               CollSeq *pColl;
   133160               Parse *pParse = pWC->pWInfo->pParse;
   133161               pX = pTerm->pExpr;
   133162               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
   133163                 continue;
   133164               }
   133165               assert(pX->pLeft);
   133166               pColl = sqlite3BinaryCompareCollSeq(pParse,
   133167                                                   pX->pLeft, pX->pRight);
   133168               if( pColl==0 ) pColl = pParse->db->pDfltColl;
   133169               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
   133170                 continue;
   133171               }
   133172             }
   133173             if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
   133174              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
   133175              && pX->iTable==pScan->aiCur[0]
   133176              && pX->iColumn==pScan->aiColumn[0]
   133177             ){
   133178               testcase( pTerm->eOperator & WO_IS );
   133179               continue;
   133180             }
   133181             pScan->pWC = pWC;
   133182             pScan->k = k+1;
   133183             return pTerm;
   133184           }
   133185         }
   133186       }
   133187       pWC = pWC->pOuter;
   133188       k = 0;
   133189     }while( pWC!=0 );
   133190     if( pScan->iEquiv>=pScan->nEquiv ) break;
   133191     pWC = pScan->pOrigWC;
   133192     k = 0;
   133193     pScan->iEquiv++;
   133194   }
   133195   return 0;
   133196 }
   133197 
   133198 /*
   133199 ** Initialize a WHERE clause scanner object.  Return a pointer to the
   133200 ** first match.  Return NULL if there are no matches.
   133201 **
   133202 ** The scanner will be searching the WHERE clause pWC.  It will look
   133203 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
   133204 ** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
   133205 ** must be one of the indexes of table iCur.
   133206 **
   133207 ** The <op> must be one of the operators described by opMask.
   133208 **
   133209 ** If the search is for X and the WHERE clause contains terms of the
   133210 ** form X=Y then this routine might also return terms of the form
   133211 ** "Y <op> <expr>".  The number of levels of transitivity is limited,
   133212 ** but is enough to handle most commonly occurring SQL statements.
   133213 **
   133214 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
   133215 ** index pIdx.
   133216 */
   133217 static WhereTerm *whereScanInit(
   133218   WhereScan *pScan,       /* The WhereScan object being initialized */
   133219   WhereClause *pWC,       /* The WHERE clause to be scanned */
   133220   int iCur,               /* Cursor to scan for */
   133221   int iColumn,            /* Column to scan for */
   133222   u32 opMask,             /* Operator(s) to scan for */
   133223   Index *pIdx             /* Must be compatible with this index */
   133224 ){
   133225   pScan->pOrigWC = pWC;
   133226   pScan->pWC = pWC;
   133227   pScan->pIdxExpr = 0;
   133228   pScan->idxaff = 0;
   133229   pScan->zCollName = 0;
   133230   if( pIdx ){
   133231     int j = iColumn;
   133232     iColumn = pIdx->aiColumn[j];
   133233     if( iColumn==XN_EXPR ){
   133234       pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
   133235       pScan->zCollName = pIdx->azColl[j];
   133236     }else if( iColumn==pIdx->pTable->iPKey ){
   133237       iColumn = XN_ROWID;
   133238     }else if( iColumn>=0 ){
   133239       pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
   133240       pScan->zCollName = pIdx->azColl[j];
   133241     }
   133242   }else if( iColumn==XN_EXPR ){
   133243     return 0;
   133244   }
   133245   pScan->opMask = opMask;
   133246   pScan->k = 0;
   133247   pScan->aiCur[0] = iCur;
   133248   pScan->aiColumn[0] = iColumn;
   133249   pScan->nEquiv = 1;
   133250   pScan->iEquiv = 1;
   133251   return whereScanNext(pScan);
   133252 }
   133253 
   133254 /*
   133255 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
   133256 ** where X is a reference to the iColumn of table iCur or of index pIdx
   133257 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
   133258 ** the op parameter.  Return a pointer to the term.  Return 0 if not found.
   133259 **
   133260 ** If pIdx!=0 then it must be one of the indexes of table iCur.
   133261 ** Search for terms matching the iColumn-th column of pIdx
   133262 ** rather than the iColumn-th column of table iCur.
   133263 **
   133264 ** The term returned might by Y=<expr> if there is another constraint in
   133265 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
   133266 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
   133267 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
   133268 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
   133269 ** other equivalent values.  Hence a search for X will return <expr> if X=A1
   133270 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
   133271 **
   133272 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
   133273 ** then try for the one with no dependencies on <expr> - in other words where
   133274 ** <expr> is a constant expression of some kind.  Only return entries of
   133275 ** the form "X <op> Y" where Y is a column in another table if no terms of
   133276 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
   133277 ** exist, try to return a term that does not use WO_EQUIV.
   133278 */
   133279 SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
   133280   WhereClause *pWC,     /* The WHERE clause to be searched */
   133281   int iCur,             /* Cursor number of LHS */
   133282   int iColumn,          /* Column number of LHS */
   133283   Bitmask notReady,     /* RHS must not overlap with this mask */
   133284   u32 op,               /* Mask of WO_xx values describing operator */
   133285   Index *pIdx           /* Must be compatible with this index, if not NULL */
   133286 ){
   133287   WhereTerm *pResult = 0;
   133288   WhereTerm *p;
   133289   WhereScan scan;
   133290 
   133291   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
   133292   op &= WO_EQ|WO_IS;
   133293   while( p ){
   133294     if( (p->prereqRight & notReady)==0 ){
   133295       if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
   133296         testcase( p->eOperator & WO_IS );
   133297         return p;
   133298       }
   133299       if( pResult==0 ) pResult = p;
   133300     }
   133301     p = whereScanNext(&scan);
   133302   }
   133303   return pResult;
   133304 }
   133305 
   133306 /*
   133307 ** This function searches pList for an entry that matches the iCol-th column
   133308 ** of index pIdx.
   133309 **
   133310 ** If such an expression is found, its index in pList->a[] is returned. If
   133311 ** no expression is found, -1 is returned.
   133312 */
   133313 static int findIndexCol(
   133314   Parse *pParse,                  /* Parse context */
   133315   ExprList *pList,                /* Expression list to search */
   133316   int iBase,                      /* Cursor for table associated with pIdx */
   133317   Index *pIdx,                    /* Index to match column of */
   133318   int iCol                        /* Column of index to match */
   133319 ){
   133320   int i;
   133321   const char *zColl = pIdx->azColl[iCol];
   133322 
   133323   for(i=0; i<pList->nExpr; i++){
   133324     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
   133325     if( p->op==TK_COLUMN
   133326      && p->iColumn==pIdx->aiColumn[iCol]
   133327      && p->iTable==iBase
   133328     ){
   133329       CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
   133330       if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
   133331         return i;
   133332       }
   133333     }
   133334   }
   133335 
   133336   return -1;
   133337 }
   133338 
   133339 /*
   133340 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
   133341 */
   133342 static int indexColumnNotNull(Index *pIdx, int iCol){
   133343   int j;
   133344   assert( pIdx!=0 );
   133345   assert( iCol>=0 && iCol<pIdx->nColumn );
   133346   j = pIdx->aiColumn[iCol];
   133347   if( j>=0 ){
   133348     return pIdx->pTable->aCol[j].notNull;
   133349   }else if( j==(-1) ){
   133350     return 1;
   133351   }else{
   133352     assert( j==(-2) );
   133353     return 0;  /* Assume an indexed expression can always yield a NULL */
   133354 
   133355   }
   133356 }
   133357 
   133358 /*
   133359 ** Return true if the DISTINCT expression-list passed as the third argument
   133360 ** is redundant.
   133361 **
   133362 ** A DISTINCT list is redundant if any subset of the columns in the
   133363 ** DISTINCT list are collectively unique and individually non-null.
   133364 */
   133365 static int isDistinctRedundant(
   133366   Parse *pParse,            /* Parsing context */
   133367   SrcList *pTabList,        /* The FROM clause */
   133368   WhereClause *pWC,         /* The WHERE clause */
   133369   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
   133370 ){
   133371   Table *pTab;
   133372   Index *pIdx;
   133373   int i;
   133374   int iBase;
   133375 
   133376   /* If there is more than one table or sub-select in the FROM clause of
   133377   ** this query, then it will not be possible to show that the DISTINCT
   133378   ** clause is redundant. */
   133379   if( pTabList->nSrc!=1 ) return 0;
   133380   iBase = pTabList->a[0].iCursor;
   133381   pTab = pTabList->a[0].pTab;
   133382 
   133383   /* If any of the expressions is an IPK column on table iBase, then return
   133384   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
   133385   ** current SELECT is a correlated sub-query.
   133386   */
   133387   for(i=0; i<pDistinct->nExpr; i++){
   133388     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
   133389     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
   133390   }
   133391 
   133392   /* Loop through all indices on the table, checking each to see if it makes
   133393   ** the DISTINCT qualifier redundant. It does so if:
   133394   **
   133395   **   1. The index is itself UNIQUE, and
   133396   **
   133397   **   2. All of the columns in the index are either part of the pDistinct
   133398   **      list, or else the WHERE clause contains a term of the form "col=X",
   133399   **      where X is a constant value. The collation sequences of the
   133400   **      comparison and select-list expressions must match those of the index.
   133401   **
   133402   **   3. All of those index columns for which the WHERE clause does not
   133403   **      contain a "col=X" term are subject to a NOT NULL constraint.
   133404   */
   133405   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   133406     if( !IsUniqueIndex(pIdx) ) continue;
   133407     for(i=0; i<pIdx->nKeyCol; i++){
   133408       if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
   133409         if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
   133410         if( indexColumnNotNull(pIdx, i)==0 ) break;
   133411       }
   133412     }
   133413     if( i==pIdx->nKeyCol ){
   133414       /* This index implies that the DISTINCT qualifier is redundant. */
   133415       return 1;
   133416     }
   133417   }
   133418 
   133419   return 0;
   133420 }
   133421 
   133422 
   133423 /*
   133424 ** Estimate the logarithm of the input value to base 2.
   133425 */
   133426 static LogEst estLog(LogEst N){
   133427   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
   133428 }
   133429 
   133430 /*
   133431 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
   133432 **
   133433 ** This routine runs over generated VDBE code and translates OP_Column
   133434 ** opcodes into OP_Copy when the table is being accessed via co-routine
   133435 ** instead of via table lookup.
   133436 **
   133437 ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
   133438 ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
   133439 ** then each OP_Rowid is transformed into an instruction to increment the
   133440 ** value stored in its output register.
   133441 */
   133442 static void translateColumnToCopy(
   133443   Parse *pParse,      /* Parsing context */
   133444   int iStart,         /* Translate from this opcode to the end */
   133445   int iTabCur,        /* OP_Column/OP_Rowid references to this table */
   133446   int iRegister,      /* The first column is in this register */
   133447   int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
   133448 ){
   133449   Vdbe *v = pParse->pVdbe;
   133450   VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
   133451   int iEnd = sqlite3VdbeCurrentAddr(v);
   133452   if( pParse->db->mallocFailed ) return;
   133453   for(; iStart<iEnd; iStart++, pOp++){
   133454     if( pOp->p1!=iTabCur ) continue;
   133455     if( pOp->opcode==OP_Column ){
   133456       pOp->opcode = OP_Copy;
   133457       pOp->p1 = pOp->p2 + iRegister;
   133458       pOp->p2 = pOp->p3;
   133459       pOp->p3 = 0;
   133460     }else if( pOp->opcode==OP_Rowid ){
   133461       if( bIncrRowid ){
   133462         /* Increment the value stored in the P2 operand of the OP_Rowid. */
   133463         pOp->opcode = OP_AddImm;
   133464         pOp->p1 = pOp->p2;
   133465         pOp->p2 = 1;
   133466       }else{
   133467         pOp->opcode = OP_Null;
   133468         pOp->p1 = 0;
   133469         pOp->p3 = 0;
   133470       }
   133471     }
   133472   }
   133473 }
   133474 
   133475 /*
   133476 ** Two routines for printing the content of an sqlite3_index_info
   133477 ** structure.  Used for testing and debugging only.  If neither
   133478 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
   133479 ** are no-ops.
   133480 */
   133481 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
   133482 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
   133483   int i;
   133484   if( !sqlite3WhereTrace ) return;
   133485   for(i=0; i<p->nConstraint; i++){
   133486     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
   133487        i,
   133488        p->aConstraint[i].iColumn,
   133489        p->aConstraint[i].iTermOffset,
   133490        p->aConstraint[i].op,
   133491        p->aConstraint[i].usable);
   133492   }
   133493   for(i=0; i<p->nOrderBy; i++){
   133494     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
   133495        i,
   133496        p->aOrderBy[i].iColumn,
   133497        p->aOrderBy[i].desc);
   133498   }
   133499 }
   133500 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   133501   int i;
   133502   if( !sqlite3WhereTrace ) return;
   133503   for(i=0; i<p->nConstraint; i++){
   133504     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
   133505        i,
   133506        p->aConstraintUsage[i].argvIndex,
   133507        p->aConstraintUsage[i].omit);
   133508   }
   133509   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
   133510   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
   133511   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
   133512   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
   133513   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
   133514 }
   133515 #else
   133516 #define TRACE_IDX_INPUTS(A)
   133517 #define TRACE_IDX_OUTPUTS(A)
   133518 #endif
   133519 
   133520 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   133521 /*
   133522 ** Return TRUE if the WHERE clause term pTerm is of a form where it
   133523 ** could be used with an index to access pSrc, assuming an appropriate
   133524 ** index existed.
   133525 */
   133526 static int termCanDriveIndex(
   133527   WhereTerm *pTerm,              /* WHERE clause term to check */
   133528   struct SrcList_item *pSrc,     /* Table we are trying to access */
   133529   Bitmask notReady               /* Tables in outer loops of the join */
   133530 ){
   133531   char aff;
   133532   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
   133533   if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
   133534   if( (pSrc->fg.jointype & JT_LEFT)
   133535    && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
   133536    && (pTerm->eOperator & WO_IS)
   133537   ){
   133538     /* Cannot use an IS term from the WHERE clause as an index driver for
   133539     ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
   133540     ** the ON clause.  */
   133541     return 0;
   133542   }
   133543   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
   133544   if( pTerm->u.leftColumn<0 ) return 0;
   133545   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
   133546   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
   133547   testcase( pTerm->pExpr->op==TK_IS );
   133548   return 1;
   133549 }
   133550 #endif
   133551 
   133552 
   133553 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   133554 /*
   133555 ** Generate code to construct the Index object for an automatic index
   133556 ** and to set up the WhereLevel object pLevel so that the code generator
   133557 ** makes use of the automatic index.
   133558 */
   133559 static void constructAutomaticIndex(
   133560   Parse *pParse,              /* The parsing context */
   133561   WhereClause *pWC,           /* The WHERE clause */
   133562   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
   133563   Bitmask notReady,           /* Mask of cursors that are not available */
   133564   WhereLevel *pLevel          /* Write new index here */
   133565 ){
   133566   int nKeyCol;                /* Number of columns in the constructed index */
   133567   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   133568   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   133569   Index *pIdx;                /* Object describing the transient index */
   133570   Vdbe *v;                    /* Prepared statement under construction */
   133571   int addrInit;               /* Address of the initialization bypass jump */
   133572   Table *pTable;              /* The table being indexed */
   133573   int addrTop;                /* Top of the index fill loop */
   133574   int regRecord;              /* Register holding an index record */
   133575   int n;                      /* Column counter */
   133576   int i;                      /* Loop counter */
   133577   int mxBitCol;               /* Maximum column in pSrc->colUsed */
   133578   CollSeq *pColl;             /* Collating sequence to on a column */
   133579   WhereLoop *pLoop;           /* The Loop object */
   133580   char *zNotUsed;             /* Extra space on the end of pIdx */
   133581   Bitmask idxCols;            /* Bitmap of columns used for indexing */
   133582   Bitmask extraCols;          /* Bitmap of additional columns */
   133583   u8 sentWarning = 0;         /* True if a warnning has been issued */
   133584   Expr *pPartial = 0;         /* Partial Index Expression */
   133585   int iContinue = 0;          /* Jump here to skip excluded rows */
   133586   struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
   133587   int addrCounter = 0;        /* Address where integer counter is initialized */
   133588   int regBase;                /* Array of registers where record is assembled */
   133589 
   133590   /* Generate code to skip over the creation and initialization of the
   133591   ** transient index on 2nd and subsequent iterations of the loop. */
   133592   v = pParse->pVdbe;
   133593   assert( v!=0 );
   133594   addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   133595 
   133596   /* Count the number of columns that will be added to the index
   133597   ** and used to match WHERE clause constraints */
   133598   nKeyCol = 0;
   133599   pTable = pSrc->pTab;
   133600   pWCEnd = &pWC->a[pWC->nTerm];
   133601   pLoop = pLevel->pWLoop;
   133602   idxCols = 0;
   133603   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   133604     Expr *pExpr = pTerm->pExpr;
   133605     assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
   133606          || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
   133607          || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
   133608     if( pLoop->prereq==0
   133609      && (pTerm->wtFlags & TERM_VIRTUAL)==0
   133610      && !ExprHasProperty(pExpr, EP_FromJoin)
   133611      && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
   133612       pPartial = sqlite3ExprAnd(pParse->db, pPartial,
   133613                                 sqlite3ExprDup(pParse->db, pExpr, 0));
   133614     }
   133615     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   133616       int iCol = pTerm->u.leftColumn;
   133617       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
   133618       testcase( iCol==BMS );
   133619       testcase( iCol==BMS-1 );
   133620       if( !sentWarning ){
   133621         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
   133622             "automatic index on %s(%s)", pTable->zName,
   133623             pTable->aCol[iCol].zName);
   133624         sentWarning = 1;
   133625       }
   133626       if( (idxCols & cMask)==0 ){
   133627         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
   133628           goto end_auto_index_create;
   133629         }
   133630         pLoop->aLTerm[nKeyCol++] = pTerm;
   133631         idxCols |= cMask;
   133632       }
   133633     }
   133634   }
   133635   assert( nKeyCol>0 );
   133636   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
   133637   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
   133638                      | WHERE_AUTO_INDEX;
   133639 
   133640   /* Count the number of additional columns needed to create a
   133641   ** covering index.  A "covering index" is an index that contains all
   133642   ** columns that are needed by the query.  With a covering index, the
   133643   ** original table never needs to be accessed.  Automatic indices must
   133644   ** be a covering index because the index will not be updated if the
   133645   ** original table changes and the index and table cannot both be used
   133646   ** if they go out of sync.
   133647   */
   133648   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
   133649   mxBitCol = MIN(BMS-1,pTable->nCol);
   133650   testcase( pTable->nCol==BMS-1 );
   133651   testcase( pTable->nCol==BMS-2 );
   133652   for(i=0; i<mxBitCol; i++){
   133653     if( extraCols & MASKBIT(i) ) nKeyCol++;
   133654   }
   133655   if( pSrc->colUsed & MASKBIT(BMS-1) ){
   133656     nKeyCol += pTable->nCol - BMS + 1;
   133657   }
   133658 
   133659   /* Construct the Index object to describe this index */
   133660   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
   133661   if( pIdx==0 ) goto end_auto_index_create;
   133662   pLoop->u.btree.pIndex = pIdx;
   133663   pIdx->zName = "auto-index";
   133664   pIdx->pTable = pTable;
   133665   n = 0;
   133666   idxCols = 0;
   133667   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   133668     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   133669       int iCol = pTerm->u.leftColumn;
   133670       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
   133671       testcase( iCol==BMS-1 );
   133672       testcase( iCol==BMS );
   133673       if( (idxCols & cMask)==0 ){
   133674         Expr *pX = pTerm->pExpr;
   133675         idxCols |= cMask;
   133676         pIdx->aiColumn[n] = pTerm->u.leftColumn;
   133677         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   133678         pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
   133679         n++;
   133680       }
   133681     }
   133682   }
   133683   assert( (u32)n==pLoop->u.btree.nEq );
   133684 
   133685   /* Add additional columns needed to make the automatic index into
   133686   ** a covering index */
   133687   for(i=0; i<mxBitCol; i++){
   133688     if( extraCols & MASKBIT(i) ){
   133689       pIdx->aiColumn[n] = i;
   133690       pIdx->azColl[n] = sqlite3StrBINARY;
   133691       n++;
   133692     }
   133693   }
   133694   if( pSrc->colUsed & MASKBIT(BMS-1) ){
   133695     for(i=BMS-1; i<pTable->nCol; i++){
   133696       pIdx->aiColumn[n] = i;
   133697       pIdx->azColl[n] = sqlite3StrBINARY;
   133698       n++;
   133699     }
   133700   }
   133701   assert( n==nKeyCol );
   133702   pIdx->aiColumn[n] = XN_ROWID;
   133703   pIdx->azColl[n] = sqlite3StrBINARY;
   133704 
   133705   /* Create the automatic index */
   133706   assert( pLevel->iIdxCur>=0 );
   133707   pLevel->iIdxCur = pParse->nTab++;
   133708   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
   133709   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   133710   VdbeComment((v, "for %s", pTable->zName));
   133711 
   133712   /* Fill the automatic index with content */
   133713   sqlite3ExprCachePush(pParse);
   133714   pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
   133715   if( pTabItem->fg.viaCoroutine ){
   133716     int regYield = pTabItem->regReturn;
   133717     addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
   133718     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
   133719     addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
   133720     VdbeCoverage(v);
   133721     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
   133722   }else{
   133723     addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
   133724   }
   133725   if( pPartial ){
   133726     iContinue = sqlite3VdbeMakeLabel(v);
   133727     sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
   133728     pLoop->wsFlags |= WHERE_PARTIALIDX;
   133729   }
   133730   regRecord = sqlite3GetTempReg(pParse);
   133731   regBase = sqlite3GenerateIndexKey(
   133732       pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
   133733   );
   133734   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
   133735   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   133736   if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
   133737   if( pTabItem->fg.viaCoroutine ){
   133738     sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
   133739     testcase( pParse->db->mallocFailed );
   133740     translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
   133741                           pTabItem->regResult, 1);
   133742     sqlite3VdbeGoto(v, addrTop);
   133743     pTabItem->fg.viaCoroutine = 0;
   133744   }else{
   133745     sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
   133746   }
   133747   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   133748   sqlite3VdbeJumpHere(v, addrTop);
   133749   sqlite3ReleaseTempReg(pParse, regRecord);
   133750   sqlite3ExprCachePop(pParse);
   133751 
   133752   /* Jump here when skipping the initialization */
   133753   sqlite3VdbeJumpHere(v, addrInit);
   133754 
   133755 end_auto_index_create:
   133756   sqlite3ExprDelete(pParse->db, pPartial);
   133757 }
   133758 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   133759 
   133760 #ifndef SQLITE_OMIT_VIRTUALTABLE
   133761 /*
   133762 ** Allocate and populate an sqlite3_index_info structure. It is the
   133763 ** responsibility of the caller to eventually release the structure
   133764 ** by passing the pointer returned by this function to sqlite3_free().
   133765 */
   133766 static sqlite3_index_info *allocateIndexInfo(
   133767   Parse *pParse,                  /* The parsing context */
   133768   WhereClause *pWC,               /* The WHERE clause being analyzed */
   133769   Bitmask mUnusable,              /* Ignore terms with these prereqs */
   133770   struct SrcList_item *pSrc,      /* The FROM clause term that is the vtab */
   133771   ExprList *pOrderBy,             /* The ORDER BY clause */
   133772   u16 *pmNoOmit                   /* Mask of terms not to omit */
   133773 ){
   133774   int i, j;
   133775   int nTerm;
   133776   struct sqlite3_index_constraint *pIdxCons;
   133777   struct sqlite3_index_orderby *pIdxOrderBy;
   133778   struct sqlite3_index_constraint_usage *pUsage;
   133779   struct HiddenIndexInfo *pHidden;
   133780   WhereTerm *pTerm;
   133781   int nOrderBy;
   133782   sqlite3_index_info *pIdxInfo;
   133783   u16 mNoOmit = 0;
   133784 
   133785   /* Count the number of possible WHERE clause constraints referring
   133786   ** to this virtual table */
   133787   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   133788     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   133789     if( pTerm->prereqRight & mUnusable ) continue;
   133790     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
   133791     testcase( pTerm->eOperator & WO_IN );
   133792     testcase( pTerm->eOperator & WO_ISNULL );
   133793     testcase( pTerm->eOperator & WO_IS );
   133794     testcase( pTerm->eOperator & WO_ALL );
   133795     if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
   133796     if( pTerm->wtFlags & TERM_VNULL ) continue;
   133797     assert( pTerm->u.leftColumn>=(-1) );
   133798     nTerm++;
   133799   }
   133800 
   133801   /* If the ORDER BY clause contains only columns in the current
   133802   ** virtual table then allocate space for the aOrderBy part of
   133803   ** the sqlite3_index_info structure.
   133804   */
   133805   nOrderBy = 0;
   133806   if( pOrderBy ){
   133807     int n = pOrderBy->nExpr;
   133808     for(i=0; i<n; i++){
   133809       Expr *pExpr = pOrderBy->a[i].pExpr;
   133810       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
   133811     }
   133812     if( i==n){
   133813       nOrderBy = n;
   133814     }
   133815   }
   133816 
   133817   /* Allocate the sqlite3_index_info structure
   133818   */
   133819   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
   133820                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
   133821                            + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
   133822   if( pIdxInfo==0 ){
   133823     sqlite3ErrorMsg(pParse, "out of memory");
   133824     return 0;
   133825   }
   133826 
   133827   /* Initialize the structure.  The sqlite3_index_info structure contains
   133828   ** many fields that are declared "const" to prevent xBestIndex from
   133829   ** changing them.  We have to do some funky casting in order to
   133830   ** initialize those fields.
   133831   */
   133832   pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
   133833   pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
   133834   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   133835   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
   133836   *(int*)&pIdxInfo->nConstraint = nTerm;
   133837   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
   133838   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
   133839   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
   133840   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
   133841                                                                    pUsage;
   133842 
   133843   pHidden->pWC = pWC;
   133844   pHidden->pParse = pParse;
   133845   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   133846     u16 op;
   133847     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   133848     if( pTerm->prereqRight & mUnusable ) continue;
   133849     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
   133850     testcase( pTerm->eOperator & WO_IN );
   133851     testcase( pTerm->eOperator & WO_IS );
   133852     testcase( pTerm->eOperator & WO_ISNULL );
   133853     testcase( pTerm->eOperator & WO_ALL );
   133854     if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
   133855     if( pTerm->wtFlags & TERM_VNULL ) continue;
   133856     assert( pTerm->u.leftColumn>=(-1) );
   133857     pIdxCons[j].iColumn = pTerm->u.leftColumn;
   133858     pIdxCons[j].iTermOffset = i;
   133859     op = pTerm->eOperator & WO_ALL;
   133860     if( op==WO_IN ) op = WO_EQ;
   133861     if( op==WO_AUX ){
   133862       pIdxCons[j].op = pTerm->eMatchOp;
   133863     }else if( op & (WO_ISNULL|WO_IS) ){
   133864       if( op==WO_ISNULL ){
   133865         pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
   133866       }else{
   133867         pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
   133868       }
   133869     }else{
   133870       pIdxCons[j].op = (u8)op;
   133871       /* The direct assignment in the previous line is possible only because
   133872       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
   133873       ** following asserts verify this fact. */
   133874       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
   133875       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
   133876       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
   133877       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
   133878       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
   133879       assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
   133880 
   133881       if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
   133882        && sqlite3ExprIsVector(pTerm->pExpr->pRight)
   133883       ){
   133884         if( i<16 ) mNoOmit |= (1 << i);
   133885         if( op==WO_LT ) pIdxCons[j].op = WO_LE;
   133886         if( op==WO_GT ) pIdxCons[j].op = WO_GE;
   133887       }
   133888     }
   133889 
   133890     j++;
   133891   }
   133892   for(i=0; i<nOrderBy; i++){
   133893     Expr *pExpr = pOrderBy->a[i].pExpr;
   133894     pIdxOrderBy[i].iColumn = pExpr->iColumn;
   133895     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
   133896   }
   133897 
   133898   *pmNoOmit = mNoOmit;
   133899   return pIdxInfo;
   133900 }
   133901 
   133902 /*
   133903 ** The table object reference passed as the second argument to this function
   133904 ** must represent a virtual table. This function invokes the xBestIndex()
   133905 ** method of the virtual table with the sqlite3_index_info object that
   133906 ** comes in as the 3rd argument to this function.
   133907 **
   133908 ** If an error occurs, pParse is populated with an error message and a
   133909 ** non-zero value is returned. Otherwise, 0 is returned and the output
   133910 ** part of the sqlite3_index_info structure is left populated.
   133911 **
   133912 ** Whether or not an error is returned, it is the responsibility of the
   133913 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
   133914 ** that this is required.
   133915 */
   133916 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   133917   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   133918   int rc;
   133919 
   133920   TRACE_IDX_INPUTS(p);
   133921   rc = pVtab->pModule->xBestIndex(pVtab, p);
   133922   TRACE_IDX_OUTPUTS(p);
   133923 
   133924   if( rc!=SQLITE_OK ){
   133925     if( rc==SQLITE_NOMEM ){
   133926       sqlite3OomFault(pParse->db);
   133927     }else if( !pVtab->zErrMsg ){
   133928       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   133929     }else{
   133930       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   133931     }
   133932   }
   133933   sqlite3_free(pVtab->zErrMsg);
   133934   pVtab->zErrMsg = 0;
   133935 
   133936 #if 0
   133937   /* This error is now caught by the caller.
   133938   ** Search for "xBestIndex malfunction" below */
   133939   for(i=0; i<p->nConstraint; i++){
   133940     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
   133941       sqlite3ErrorMsg(pParse,
   133942           "table %s: xBestIndex returned an invalid plan", pTab->zName);
   133943     }
   133944   }
   133945 #endif
   133946 
   133947   return pParse->nErr;
   133948 }
   133949 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
   133950 
   133951 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   133952 /*
   133953 ** Estimate the location of a particular key among all keys in an
   133954 ** index.  Store the results in aStat as follows:
   133955 **
   133956 **    aStat[0]      Est. number of rows less than pRec
   133957 **    aStat[1]      Est. number of rows equal to pRec
   133958 **
   133959 ** Return the index of the sample that is the smallest sample that
   133960 ** is greater than or equal to pRec. Note that this index is not an index
   133961 ** into the aSample[] array - it is an index into a virtual set of samples
   133962 ** based on the contents of aSample[] and the number of fields in record
   133963 ** pRec.
   133964 */
   133965 static int whereKeyStats(
   133966   Parse *pParse,              /* Database connection */
   133967   Index *pIdx,                /* Index to consider domain of */
   133968   UnpackedRecord *pRec,       /* Vector of values to consider */
   133969   int roundUp,                /* Round up if true.  Round down if false */
   133970   tRowcnt *aStat              /* OUT: stats written here */
   133971 ){
   133972   IndexSample *aSample = pIdx->aSample;
   133973   int iCol;                   /* Index of required stats in anEq[] etc. */
   133974   int i;                      /* Index of first sample >= pRec */
   133975   int iSample;                /* Smallest sample larger than or equal to pRec */
   133976   int iMin = 0;               /* Smallest sample not yet tested */
   133977   int iTest;                  /* Next sample to test */
   133978   int res;                    /* Result of comparison operation */
   133979   int nField;                 /* Number of fields in pRec */
   133980   tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
   133981 
   133982 #ifndef SQLITE_DEBUG
   133983   UNUSED_PARAMETER( pParse );
   133984 #endif
   133985   assert( pRec!=0 );
   133986   assert( pIdx->nSample>0 );
   133987   assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
   133988 
   133989   /* Do a binary search to find the first sample greater than or equal
   133990   ** to pRec. If pRec contains a single field, the set of samples to search
   133991   ** is simply the aSample[] array. If the samples in aSample[] contain more
   133992   ** than one fields, all fields following the first are ignored.
   133993   **
   133994   ** If pRec contains N fields, where N is more than one, then as well as the
   133995   ** samples in aSample[] (truncated to N fields), the search also has to
   133996   ** consider prefixes of those samples. For example, if the set of samples
   133997   ** in aSample is:
   133998   **
   133999   **     aSample[0] = (a, 5)
   134000   **     aSample[1] = (a, 10)
   134001   **     aSample[2] = (b, 5)
   134002   **     aSample[3] = (c, 100)
   134003   **     aSample[4] = (c, 105)
   134004   **
   134005   ** Then the search space should ideally be the samples above and the
   134006   ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
   134007   ** the code actually searches this set:
   134008   **
   134009   **     0: (a)
   134010   **     1: (a, 5)
   134011   **     2: (a, 10)
   134012   **     3: (a, 10)
   134013   **     4: (b)
   134014   **     5: (b, 5)
   134015   **     6: (c)
   134016   **     7: (c, 100)
   134017   **     8: (c, 105)
   134018   **     9: (c, 105)
   134019   **
   134020   ** For each sample in the aSample[] array, N samples are present in the
   134021   ** effective sample array. In the above, samples 0 and 1 are based on
   134022   ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
   134023   **
   134024   ** Often, sample i of each block of N effective samples has (i+1) fields.
   134025   ** Except, each sample may be extended to ensure that it is greater than or
   134026   ** equal to the previous sample in the array. For example, in the above,
   134027   ** sample 2 is the first sample of a block of N samples, so at first it
   134028   ** appears that it should be 1 field in size. However, that would make it
   134029   ** smaller than sample 1, so the binary search would not work. As a result,
   134030   ** it is extended to two fields. The duplicates that this creates do not
   134031   ** cause any problems.
   134032   */
   134033   nField = pRec->nField;
   134034   iCol = 0;
   134035   iSample = pIdx->nSample * nField;
   134036   do{
   134037     int iSamp;                    /* Index in aSample[] of test sample */
   134038     int n;                        /* Number of fields in test sample */
   134039 
   134040     iTest = (iMin+iSample)/2;
   134041     iSamp = iTest / nField;
   134042     if( iSamp>0 ){
   134043       /* The proposed effective sample is a prefix of sample aSample[iSamp].
   134044       ** Specifically, the shortest prefix of at least (1 + iTest%nField)
   134045       ** fields that is greater than the previous effective sample.  */
   134046       for(n=(iTest % nField) + 1; n<nField; n++){
   134047         if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
   134048       }
   134049     }else{
   134050       n = iTest + 1;
   134051     }
   134052 
   134053     pRec->nField = n;
   134054     res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
   134055     if( res<0 ){
   134056       iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
   134057       iMin = iTest+1;
   134058     }else if( res==0 && n<nField ){
   134059       iLower = aSample[iSamp].anLt[n-1];
   134060       iMin = iTest+1;
   134061       res = -1;
   134062     }else{
   134063       iSample = iTest;
   134064       iCol = n-1;
   134065     }
   134066   }while( res && iMin<iSample );
   134067   i = iSample / nField;
   134068 
   134069 #ifdef SQLITE_DEBUG
   134070   /* The following assert statements check that the binary search code
   134071   ** above found the right answer. This block serves no purpose other
   134072   ** than to invoke the asserts.  */
   134073   if( pParse->db->mallocFailed==0 ){
   134074     if( res==0 ){
   134075       /* If (res==0) is true, then pRec must be equal to sample i. */
   134076       assert( i<pIdx->nSample );
   134077       assert( iCol==nField-1 );
   134078       pRec->nField = nField;
   134079       assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
   134080            || pParse->db->mallocFailed
   134081       );
   134082     }else{
   134083       /* Unless i==pIdx->nSample, indicating that pRec is larger than
   134084       ** all samples in the aSample[] array, pRec must be smaller than the
   134085       ** (iCol+1) field prefix of sample i.  */
   134086       assert( i<=pIdx->nSample && i>=0 );
   134087       pRec->nField = iCol+1;
   134088       assert( i==pIdx->nSample
   134089            || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
   134090            || pParse->db->mallocFailed );
   134091 
   134092       /* if i==0 and iCol==0, then record pRec is smaller than all samples
   134093       ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
   134094       ** be greater than or equal to the (iCol) field prefix of sample i.
   134095       ** If (i>0), then pRec must also be greater than sample (i-1).  */
   134096       if( iCol>0 ){
   134097         pRec->nField = iCol;
   134098         assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
   134099              || pParse->db->mallocFailed );
   134100       }
   134101       if( i>0 ){
   134102         pRec->nField = nField;
   134103         assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
   134104              || pParse->db->mallocFailed );
   134105       }
   134106     }
   134107   }
   134108 #endif /* ifdef SQLITE_DEBUG */
   134109 
   134110   if( res==0 ){
   134111     /* Record pRec is equal to sample i */
   134112     assert( iCol==nField-1 );
   134113     aStat[0] = aSample[i].anLt[iCol];
   134114     aStat[1] = aSample[i].anEq[iCol];
   134115   }else{
   134116     /* At this point, the (iCol+1) field prefix of aSample[i] is the first
   134117     ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
   134118     ** is larger than all samples in the array. */
   134119     tRowcnt iUpper, iGap;
   134120     if( i>=pIdx->nSample ){
   134121       iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
   134122     }else{
   134123       iUpper = aSample[i].anLt[iCol];
   134124     }
   134125 
   134126     if( iLower>=iUpper ){
   134127       iGap = 0;
   134128     }else{
   134129       iGap = iUpper - iLower;
   134130     }
   134131     if( roundUp ){
   134132       iGap = (iGap*2)/3;
   134133     }else{
   134134       iGap = iGap/3;
   134135     }
   134136     aStat[0] = iLower + iGap;
   134137     aStat[1] = pIdx->aAvgEq[nField-1];
   134138   }
   134139 
   134140   /* Restore the pRec->nField value before returning.  */
   134141   pRec->nField = nField;
   134142   return i;
   134143 }
   134144 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   134145 
   134146 /*
   134147 ** If it is not NULL, pTerm is a term that provides an upper or lower
   134148 ** bound on a range scan. Without considering pTerm, it is estimated
   134149 ** that the scan will visit nNew rows. This function returns the number
   134150 ** estimated to be visited after taking pTerm into account.
   134151 **
   134152 ** If the user explicitly specified a likelihood() value for this term,
   134153 ** then the return value is the likelihood multiplied by the number of
   134154 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
   134155 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
   134156 */
   134157 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
   134158   LogEst nRet = nNew;
   134159   if( pTerm ){
   134160     if( pTerm->truthProb<=0 ){
   134161       nRet += pTerm->truthProb;
   134162     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
   134163       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
   134164     }
   134165   }
   134166   return nRet;
   134167 }
   134168 
   134169 
   134170 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   134171 /*
   134172 ** Return the affinity for a single column of an index.
   134173 */
   134174 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
   134175   assert( iCol>=0 && iCol<pIdx->nColumn );
   134176   if( !pIdx->zColAff ){
   134177     if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
   134178   }
   134179   return pIdx->zColAff[iCol];
   134180 }
   134181 #endif
   134182 
   134183 
   134184 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   134185 /*
   134186 ** This function is called to estimate the number of rows visited by a
   134187 ** range-scan on a skip-scan index. For example:
   134188 **
   134189 **   CREATE INDEX i1 ON t1(a, b, c);
   134190 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
   134191 **
   134192 ** Value pLoop->nOut is currently set to the estimated number of rows
   134193 ** visited for scanning (a=? AND b=?). This function reduces that estimate
   134194 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
   134195 ** on the stat4 data for the index. this scan will be peformed multiple
   134196 ** times (once for each (a,b) combination that matches a=?) is dealt with
   134197 ** by the caller.
   134198 **
   134199 ** It does this by scanning through all stat4 samples, comparing values
   134200 ** extracted from pLower and pUpper with the corresponding column in each
   134201 ** sample. If L and U are the number of samples found to be less than or
   134202 ** equal to the values extracted from pLower and pUpper respectively, and
   134203 ** N is the total number of samples, the pLoop->nOut value is adjusted
   134204 ** as follows:
   134205 **
   134206 **   nOut = nOut * ( min(U - L, 1) / N )
   134207 **
   134208 ** If pLower is NULL, or a value cannot be extracted from the term, L is
   134209 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
   134210 ** U is set to N.
   134211 **
   134212 ** Normally, this function sets *pbDone to 1 before returning. However,
   134213 ** if no value can be extracted from either pLower or pUpper (and so the
   134214 ** estimate of the number of rows delivered remains unchanged), *pbDone
   134215 ** is left as is.
   134216 **
   134217 ** If an error occurs, an SQLite error code is returned. Otherwise,
   134218 ** SQLITE_OK.
   134219 */
   134220 static int whereRangeSkipScanEst(
   134221   Parse *pParse,       /* Parsing & code generating context */
   134222   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   134223   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   134224   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
   134225   int *pbDone          /* Set to true if at least one expr. value extracted */
   134226 ){
   134227   Index *p = pLoop->u.btree.pIndex;
   134228   int nEq = pLoop->u.btree.nEq;
   134229   sqlite3 *db = pParse->db;
   134230   int nLower = -1;
   134231   int nUpper = p->nSample+1;
   134232   int rc = SQLITE_OK;
   134233   u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
   134234   CollSeq *pColl;
   134235 
   134236   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
   134237   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
   134238   sqlite3_value *pVal = 0;        /* Value extracted from record */
   134239 
   134240   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
   134241   if( pLower ){
   134242     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
   134243     nLower = 0;
   134244   }
   134245   if( pUpper && rc==SQLITE_OK ){
   134246     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
   134247     nUpper = p2 ? 0 : p->nSample;
   134248   }
   134249 
   134250   if( p1 || p2 ){
   134251     int i;
   134252     int nDiff;
   134253     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
   134254       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
   134255       if( rc==SQLITE_OK && p1 ){
   134256         int res = sqlite3MemCompare(p1, pVal, pColl);
   134257         if( res>=0 ) nLower++;
   134258       }
   134259       if( rc==SQLITE_OK && p2 ){
   134260         int res = sqlite3MemCompare(p2, pVal, pColl);
   134261         if( res>=0 ) nUpper++;
   134262       }
   134263     }
   134264     nDiff = (nUpper - nLower);
   134265     if( nDiff<=0 ) nDiff = 1;
   134266 
   134267     /* If there is both an upper and lower bound specified, and the
   134268     ** comparisons indicate that they are close together, use the fallback
   134269     ** method (assume that the scan visits 1/64 of the rows) for estimating
   134270     ** the number of rows visited. Otherwise, estimate the number of rows
   134271     ** using the method described in the header comment for this function. */
   134272     if( nDiff!=1 || pUpper==0 || pLower==0 ){
   134273       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
   134274       pLoop->nOut -= nAdjust;
   134275       *pbDone = 1;
   134276       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
   134277                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
   134278     }
   134279 
   134280   }else{
   134281     assert( *pbDone==0 );
   134282   }
   134283 
   134284   sqlite3ValueFree(p1);
   134285   sqlite3ValueFree(p2);
   134286   sqlite3ValueFree(pVal);
   134287 
   134288   return rc;
   134289 }
   134290 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   134291 
   134292 /*
   134293 ** This function is used to estimate the number of rows that will be visited
   134294 ** by scanning an index for a range of values. The range may have an upper
   134295 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
   134296 ** and lower bounds are represented by pLower and pUpper respectively. For
   134297 ** example, assuming that index p is on t1(a):
   134298 **
   134299 **   ... FROM t1 WHERE a > ? AND a < ? ...
   134300 **                    |_____|   |_____|
   134301 **                       |         |
   134302 **                     pLower    pUpper
   134303 **
   134304 ** If either of the upper or lower bound is not present, then NULL is passed in
   134305 ** place of the corresponding WhereTerm.
   134306 **
   134307 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
   134308 ** column subject to the range constraint. Or, equivalently, the number of
   134309 ** equality constraints optimized by the proposed index scan. For example,
   134310 ** assuming index p is on t1(a, b), and the SQL query is:
   134311 **
   134312 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
   134313 **
   134314 ** then nEq is set to 1 (as the range restricted column, b, is the second
   134315 ** left-most column of the index). Or, if the query is:
   134316 **
   134317 **   ... FROM t1 WHERE a > ? AND a < ? ...
   134318 **
   134319 ** then nEq is set to 0.
   134320 **
   134321 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
   134322 ** number of rows that the index scan is expected to visit without
   134323 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
   134324 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
   134325 ** to account for the range constraints pLower and pUpper.
   134326 **
   134327 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
   134328 ** used, a single range inequality reduces the search space by a factor of 4.
   134329 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
   134330 ** rows visited by a factor of 64.
   134331 */
   134332 static int whereRangeScanEst(
   134333   Parse *pParse,       /* Parsing & code generating context */
   134334   WhereLoopBuilder *pBuilder,
   134335   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   134336   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   134337   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
   134338 ){
   134339   int rc = SQLITE_OK;
   134340   int nOut = pLoop->nOut;
   134341   LogEst nNew;
   134342 
   134343 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   134344   Index *p = pLoop->u.btree.pIndex;
   134345   int nEq = pLoop->u.btree.nEq;
   134346 
   134347   if( p->nSample>0 && nEq<p->nSampleCol ){
   134348     if( nEq==pBuilder->nRecValid ){
   134349       UnpackedRecord *pRec = pBuilder->pRec;
   134350       tRowcnt a[2];
   134351       int nBtm = pLoop->u.btree.nBtm;
   134352       int nTop = pLoop->u.btree.nTop;
   134353 
   134354       /* Variable iLower will be set to the estimate of the number of rows in
   134355       ** the index that are less than the lower bound of the range query. The
   134356       ** lower bound being the concatenation of $P and $L, where $P is the
   134357       ** key-prefix formed by the nEq values matched against the nEq left-most
   134358       ** columns of the index, and $L is the value in pLower.
   134359       **
   134360       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
   134361       ** is not a simple variable or literal value), the lower bound of the
   134362       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
   134363       ** if $L is available, whereKeyStats() is called for both ($P) and
   134364       ** ($P:$L) and the larger of the two returned values is used.
   134365       **
   134366       ** Similarly, iUpper is to be set to the estimate of the number of rows
   134367       ** less than the upper bound of the range query. Where the upper bound
   134368       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
   134369       ** of iUpper are requested of whereKeyStats() and the smaller used.
   134370       **
   134371       ** The number of rows between the two bounds is then just iUpper-iLower.
   134372       */
   134373       tRowcnt iLower;     /* Rows less than the lower bound */
   134374       tRowcnt iUpper;     /* Rows less than the upper bound */
   134375       int iLwrIdx = -2;   /* aSample[] for the lower bound */
   134376       int iUprIdx = -1;   /* aSample[] for the upper bound */
   134377 
   134378       if( pRec ){
   134379         testcase( pRec->nField!=pBuilder->nRecValid );
   134380         pRec->nField = pBuilder->nRecValid;
   134381       }
   134382       /* Determine iLower and iUpper using ($P) only. */
   134383       if( nEq==0 ){
   134384         iLower = 0;
   134385         iUpper = p->nRowEst0;
   134386       }else{
   134387         /* Note: this call could be optimized away - since the same values must
   134388         ** have been requested when testing key $P in whereEqualScanEst().  */
   134389         whereKeyStats(pParse, p, pRec, 0, a);
   134390         iLower = a[0];
   134391         iUpper = a[0] + a[1];
   134392       }
   134393 
   134394       assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
   134395       assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
   134396       assert( p->aSortOrder!=0 );
   134397       if( p->aSortOrder[nEq] ){
   134398         /* The roles of pLower and pUpper are swapped for a DESC index */
   134399         SWAP(WhereTerm*, pLower, pUpper);
   134400         SWAP(int, nBtm, nTop);
   134401       }
   134402 
   134403       /* If possible, improve on the iLower estimate using ($P:$L). */
   134404       if( pLower ){
   134405         int n;                    /* Values extracted from pExpr */
   134406         Expr *pExpr = pLower->pExpr->pRight;
   134407         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
   134408         if( rc==SQLITE_OK && n ){
   134409           tRowcnt iNew;
   134410           u16 mask = WO_GT|WO_LE;
   134411           if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
   134412           iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
   134413           iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
   134414           if( iNew>iLower ) iLower = iNew;
   134415           nOut--;
   134416           pLower = 0;
   134417         }
   134418       }
   134419 
   134420       /* If possible, improve on the iUpper estimate using ($P:$U). */
   134421       if( pUpper ){
   134422         int n;                    /* Values extracted from pExpr */
   134423         Expr *pExpr = pUpper->pExpr->pRight;
   134424         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
   134425         if( rc==SQLITE_OK && n ){
   134426           tRowcnt iNew;
   134427           u16 mask = WO_GT|WO_LE;
   134428           if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
   134429           iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
   134430           iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
   134431           if( iNew<iUpper ) iUpper = iNew;
   134432           nOut--;
   134433           pUpper = 0;
   134434         }
   134435       }
   134436 
   134437       pBuilder->pRec = pRec;
   134438       if( rc==SQLITE_OK ){
   134439         if( iUpper>iLower ){
   134440           nNew = sqlite3LogEst(iUpper - iLower);
   134441           /* TUNING:  If both iUpper and iLower are derived from the same
   134442           ** sample, then assume they are 4x more selective.  This brings
   134443           ** the estimated selectivity more in line with what it would be
   134444           ** if estimated without the use of STAT3/4 tables. */
   134445           if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
   134446         }else{
   134447           nNew = 10;        assert( 10==sqlite3LogEst(2) );
   134448         }
   134449         if( nNew<nOut ){
   134450           nOut = nNew;
   134451         }
   134452         WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
   134453                            (u32)iLower, (u32)iUpper, nOut));
   134454       }
   134455     }else{
   134456       int bDone = 0;
   134457       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
   134458       if( bDone ) return rc;
   134459     }
   134460   }
   134461 #else
   134462   UNUSED_PARAMETER(pParse);
   134463   UNUSED_PARAMETER(pBuilder);
   134464   assert( pLower || pUpper );
   134465 #endif
   134466   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
   134467   nNew = whereRangeAdjust(pLower, nOut);
   134468   nNew = whereRangeAdjust(pUpper, nNew);
   134469 
   134470   /* TUNING: If there is both an upper and lower limit and neither limit
   134471   ** has an application-defined likelihood(), assume the range is
   134472   ** reduced by an additional 75%. This means that, by default, an open-ended
   134473   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
   134474   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
   134475   ** match 1/64 of the index. */
   134476   if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
   134477     nNew -= 20;
   134478   }
   134479 
   134480   nOut -= (pLower!=0) + (pUpper!=0);
   134481   if( nNew<10 ) nNew = 10;
   134482   if( nNew<nOut ) nOut = nNew;
   134483 #if defined(WHERETRACE_ENABLED)
   134484   if( pLoop->nOut>nOut ){
   134485     WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
   134486                     pLoop->nOut, nOut));
   134487   }
   134488 #endif
   134489   pLoop->nOut = (LogEst)nOut;
   134490   return rc;
   134491 }
   134492 
   134493 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   134494 /*
   134495 ** Estimate the number of rows that will be returned based on
   134496 ** an equality constraint x=VALUE and where that VALUE occurs in
   134497 ** the histogram data.  This only works when x is the left-most
   134498 ** column of an index and sqlite_stat3 histogram data is available
   134499 ** for that index.  When pExpr==NULL that means the constraint is
   134500 ** "x IS NULL" instead of "x=VALUE".
   134501 **
   134502 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   134503 ** If unable to make an estimate, leave *pnRow unchanged and return
   134504 ** non-zero.
   134505 **
   134506 ** This routine can fail if it is unable to load a collating sequence
   134507 ** required for string comparison, or if unable to allocate memory
   134508 ** for a UTF conversion required for comparison.  The error is stored
   134509 ** in the pParse structure.
   134510 */
   134511 static int whereEqualScanEst(
   134512   Parse *pParse,       /* Parsing & code generating context */
   134513   WhereLoopBuilder *pBuilder,
   134514   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
   134515   tRowcnt *pnRow       /* Write the revised row estimate here */
   134516 ){
   134517   Index *p = pBuilder->pNew->u.btree.pIndex;
   134518   int nEq = pBuilder->pNew->u.btree.nEq;
   134519   UnpackedRecord *pRec = pBuilder->pRec;
   134520   int rc;                   /* Subfunction return code */
   134521   tRowcnt a[2];             /* Statistics */
   134522   int bOk;
   134523 
   134524   assert( nEq>=1 );
   134525   assert( nEq<=p->nColumn );
   134526   assert( p->aSample!=0 );
   134527   assert( p->nSample>0 );
   134528   assert( pBuilder->nRecValid<nEq );
   134529 
   134530   /* If values are not available for all fields of the index to the left
   134531   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
   134532   if( pBuilder->nRecValid<(nEq-1) ){
   134533     return SQLITE_NOTFOUND;
   134534   }
   134535 
   134536   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
   134537   ** below would return the same value.  */
   134538   if( nEq>=p->nColumn ){
   134539     *pnRow = 1;
   134540     return SQLITE_OK;
   134541   }
   134542 
   134543   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
   134544   pBuilder->pRec = pRec;
   134545   if( rc!=SQLITE_OK ) return rc;
   134546   if( bOk==0 ) return SQLITE_NOTFOUND;
   134547   pBuilder->nRecValid = nEq;
   134548 
   134549   whereKeyStats(pParse, p, pRec, 0, a);
   134550   WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
   134551                    p->zName, nEq-1, (int)a[1]));
   134552   *pnRow = a[1];
   134553 
   134554   return rc;
   134555 }
   134556 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   134557 
   134558 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   134559 /*
   134560 ** Estimate the number of rows that will be returned based on
   134561 ** an IN constraint where the right-hand side of the IN operator
   134562 ** is a list of values.  Example:
   134563 **
   134564 **        WHERE x IN (1,2,3,4)
   134565 **
   134566 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   134567 ** If unable to make an estimate, leave *pnRow unchanged and return
   134568 ** non-zero.
   134569 **
   134570 ** This routine can fail if it is unable to load a collating sequence
   134571 ** required for string comparison, or if unable to allocate memory
   134572 ** for a UTF conversion required for comparison.  The error is stored
   134573 ** in the pParse structure.
   134574 */
   134575 static int whereInScanEst(
   134576   Parse *pParse,       /* Parsing & code generating context */
   134577   WhereLoopBuilder *pBuilder,
   134578   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
   134579   tRowcnt *pnRow       /* Write the revised row estimate here */
   134580 ){
   134581   Index *p = pBuilder->pNew->u.btree.pIndex;
   134582   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
   134583   int nRecValid = pBuilder->nRecValid;
   134584   int rc = SQLITE_OK;     /* Subfunction return code */
   134585   tRowcnt nEst;           /* Number of rows for a single term */
   134586   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
   134587   int i;                  /* Loop counter */
   134588 
   134589   assert( p->aSample!=0 );
   134590   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
   134591     nEst = nRow0;
   134592     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
   134593     nRowEst += nEst;
   134594     pBuilder->nRecValid = nRecValid;
   134595   }
   134596 
   134597   if( rc==SQLITE_OK ){
   134598     if( nRowEst > nRow0 ) nRowEst = nRow0;
   134599     *pnRow = nRowEst;
   134600     WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
   134601   }
   134602   assert( pBuilder->nRecValid==nRecValid );
   134603   return rc;
   134604 }
   134605 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
   134606 
   134607 
   134608 #ifdef WHERETRACE_ENABLED
   134609 /*
   134610 ** Print the content of a WhereTerm object
   134611 */
   134612 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
   134613   if( pTerm==0 ){
   134614     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
   134615   }else{
   134616     char zType[4];
   134617     char zLeft[50];
   134618     memcpy(zType, "...", 4);
   134619     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
   134620     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
   134621     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
   134622     if( pTerm->eOperator & WO_SINGLE ){
   134623       sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
   134624                        pTerm->leftCursor, pTerm->u.leftColumn);
   134625     }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
   134626       sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
   134627                        pTerm->u.pOrInfo->indexable);
   134628     }else{
   134629       sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
   134630     }
   134631     sqlite3DebugPrintf(
   134632        "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
   134633        iTerm, pTerm, zType, zLeft, pTerm->truthProb,
   134634        pTerm->eOperator, pTerm->wtFlags);
   134635     if( pTerm->iField ){
   134636       sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
   134637     }else{
   134638       sqlite3DebugPrintf("\n");
   134639     }
   134640     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
   134641   }
   134642 }
   134643 #endif
   134644 
   134645 #ifdef WHERETRACE_ENABLED
   134646 /*
   134647 ** Show the complete content of a WhereClause
   134648 */
   134649 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
   134650   int i;
   134651   for(i=0; i<pWC->nTerm; i++){
   134652     whereTermPrint(&pWC->a[i], i);
   134653   }
   134654 }
   134655 #endif
   134656 
   134657 #ifdef WHERETRACE_ENABLED
   134658 /*
   134659 ** Print a WhereLoop object for debugging purposes
   134660 */
   134661 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
   134662   WhereInfo *pWInfo = pWC->pWInfo;
   134663   int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
   134664   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
   134665   Table *pTab = pItem->pTab;
   134666   Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
   134667   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
   134668                      p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
   134669   sqlite3DebugPrintf(" %12s",
   134670                      pItem->zAlias ? pItem->zAlias : pTab->zName);
   134671   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
   134672     const char *zName;
   134673     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
   134674       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
   134675         int i = sqlite3Strlen30(zName) - 1;
   134676         while( zName[i]!='_' ) i--;
   134677         zName += i;
   134678       }
   134679       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
   134680     }else{
   134681       sqlite3DebugPrintf("%20s","");
   134682     }
   134683   }else{
   134684     char *z;
   134685     if( p->u.vtab.idxStr ){
   134686       z = sqlite3_mprintf("(%d,\"%s\",%x)",
   134687                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
   134688     }else{
   134689       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
   134690     }
   134691     sqlite3DebugPrintf(" %-19s", z);
   134692     sqlite3_free(z);
   134693   }
   134694   if( p->wsFlags & WHERE_SKIPSCAN ){
   134695     sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
   134696   }else{
   134697     sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
   134698   }
   134699   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
   134700   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
   134701     int i;
   134702     for(i=0; i<p->nLTerm; i++){
   134703       whereTermPrint(p->aLTerm[i], i);
   134704     }
   134705   }
   134706 }
   134707 #endif
   134708 
   134709 /*
   134710 ** Convert bulk memory into a valid WhereLoop that can be passed
   134711 ** to whereLoopClear harmlessly.
   134712 */
   134713 static void whereLoopInit(WhereLoop *p){
   134714   p->aLTerm = p->aLTermSpace;
   134715   p->nLTerm = 0;
   134716   p->nLSlot = ArraySize(p->aLTermSpace);
   134717   p->wsFlags = 0;
   134718 }
   134719 
   134720 /*
   134721 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
   134722 */
   134723 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
   134724   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
   134725     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
   134726       sqlite3_free(p->u.vtab.idxStr);
   134727       p->u.vtab.needFree = 0;
   134728       p->u.vtab.idxStr = 0;
   134729     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
   134730       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
   134731       sqlite3DbFreeNN(db, p->u.btree.pIndex);
   134732       p->u.btree.pIndex = 0;
   134733     }
   134734   }
   134735 }
   134736 
   134737 /*
   134738 ** Deallocate internal memory used by a WhereLoop object
   134739 */
   134740 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
   134741   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
   134742   whereLoopClearUnion(db, p);
   134743   whereLoopInit(p);
   134744 }
   134745 
   134746 /*
   134747 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
   134748 */
   134749 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
   134750   WhereTerm **paNew;
   134751   if( p->nLSlot>=n ) return SQLITE_OK;
   134752   n = (n+7)&~7;
   134753   paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
   134754   if( paNew==0 ) return SQLITE_NOMEM_BKPT;
   134755   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
   134756   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
   134757   p->aLTerm = paNew;
   134758   p->nLSlot = n;
   134759   return SQLITE_OK;
   134760 }
   134761 
   134762 /*
   134763 ** Transfer content from the second pLoop into the first.
   134764 */
   134765 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
   134766   whereLoopClearUnion(db, pTo);
   134767   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
   134768     memset(&pTo->u, 0, sizeof(pTo->u));
   134769     return SQLITE_NOMEM_BKPT;
   134770   }
   134771   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
   134772   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
   134773   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
   134774     pFrom->u.vtab.needFree = 0;
   134775   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
   134776     pFrom->u.btree.pIndex = 0;
   134777   }
   134778   return SQLITE_OK;
   134779 }
   134780 
   134781 /*
   134782 ** Delete a WhereLoop object
   134783 */
   134784 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
   134785   whereLoopClear(db, p);
   134786   sqlite3DbFreeNN(db, p);
   134787 }
   134788 
   134789 /*
   134790 ** Free a WhereInfo structure
   134791 */
   134792 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   134793   int i;
   134794   assert( pWInfo!=0 );
   134795   for(i=0; i<pWInfo->nLevel; i++){
   134796     WhereLevel *pLevel = &pWInfo->a[i];
   134797     if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
   134798       sqlite3DbFree(db, pLevel->u.in.aInLoop);
   134799     }
   134800   }
   134801   sqlite3WhereClauseClear(&pWInfo->sWC);
   134802   while( pWInfo->pLoops ){
   134803     WhereLoop *p = pWInfo->pLoops;
   134804     pWInfo->pLoops = p->pNextLoop;
   134805     whereLoopDelete(db, p);
   134806   }
   134807   sqlite3DbFreeNN(db, pWInfo);
   134808 }
   134809 
   134810 /*
   134811 ** Return TRUE if all of the following are true:
   134812 **
   134813 **   (1)  X has the same or lower cost that Y
   134814 **   (2)  X uses fewer WHERE clause terms than Y
   134815 **   (3)  Every WHERE clause term used by X is also used by Y
   134816 **   (4)  X skips at least as many columns as Y
   134817 **   (5)  If X is a covering index, than Y is too
   134818 **
   134819 ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
   134820 ** If X is a proper subset of Y then Y is a better choice and ought
   134821 ** to have a lower cost.  This routine returns TRUE when that cost
   134822 ** relationship is inverted and needs to be adjusted.  Constraint (4)
   134823 ** was added because if X uses skip-scan less than Y it still might
   134824 ** deserve a lower cost even if it is a proper subset of Y.  Constraint (5)
   134825 ** was added because a covering index probably deserves to have a lower cost
   134826 ** than a non-covering index even if it is a proper subset.
   134827 */
   134828 static int whereLoopCheaperProperSubset(
   134829   const WhereLoop *pX,       /* First WhereLoop to compare */
   134830   const WhereLoop *pY        /* Compare against this WhereLoop */
   134831 ){
   134832   int i, j;
   134833   if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
   134834     return 0; /* X is not a subset of Y */
   134835   }
   134836   if( pY->nSkip > pX->nSkip ) return 0;
   134837   if( pX->rRun >= pY->rRun ){
   134838     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
   134839     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
   134840   }
   134841   for(i=pX->nLTerm-1; i>=0; i--){
   134842     if( pX->aLTerm[i]==0 ) continue;
   134843     for(j=pY->nLTerm-1; j>=0; j--){
   134844       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
   134845     }
   134846     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
   134847   }
   134848   if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
   134849    && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
   134850     return 0;  /* Constraint (5) */
   134851   }
   134852   return 1;  /* All conditions meet */
   134853 }
   134854 
   134855 /*
   134856 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
   134857 ** that:
   134858 **
   134859 **   (1) pTemplate costs less than any other WhereLoops that are a proper
   134860 **       subset of pTemplate
   134861 **
   134862 **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
   134863 **       is a proper subset.
   134864 **
   134865 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
   134866 ** WHERE clause terms than Y and that every WHERE clause term used by X is
   134867 ** also used by Y.
   134868 */
   134869 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
   134870   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
   134871   for(; p; p=p->pNextLoop){
   134872     if( p->iTab!=pTemplate->iTab ) continue;
   134873     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
   134874     if( whereLoopCheaperProperSubset(p, pTemplate) ){
   134875       /* Adjust pTemplate cost downward so that it is cheaper than its
   134876       ** subset p. */
   134877       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
   134878                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
   134879       pTemplate->rRun = p->rRun;
   134880       pTemplate->nOut = p->nOut - 1;
   134881     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
   134882       /* Adjust pTemplate cost upward so that it is costlier than p since
   134883       ** pTemplate is a proper subset of p */
   134884       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
   134885                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
   134886       pTemplate->rRun = p->rRun;
   134887       pTemplate->nOut = p->nOut + 1;
   134888     }
   134889   }
   134890 }
   134891 
   134892 /*
   134893 ** Search the list of WhereLoops in *ppPrev looking for one that can be
   134894 ** replaced by pTemplate.
   134895 **
   134896 ** Return NULL if pTemplate does not belong on the WhereLoop list.
   134897 ** In other words if pTemplate ought to be dropped from further consideration.
   134898 **
   134899 ** If pX is a WhereLoop that pTemplate can replace, then return the
   134900 ** link that points to pX.
   134901 **
   134902 ** If pTemplate cannot replace any existing element of the list but needs
   134903 ** to be added to the list as a new entry, then return a pointer to the
   134904 ** tail of the list.
   134905 */
   134906 static WhereLoop **whereLoopFindLesser(
   134907   WhereLoop **ppPrev,
   134908   const WhereLoop *pTemplate
   134909 ){
   134910   WhereLoop *p;
   134911   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
   134912     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
   134913       /* If either the iTab or iSortIdx values for two WhereLoop are different
   134914       ** then those WhereLoops need to be considered separately.  Neither is
   134915       ** a candidate to replace the other. */
   134916       continue;
   134917     }
   134918     /* In the current implementation, the rSetup value is either zero
   134919     ** or the cost of building an automatic index (NlogN) and the NlogN
   134920     ** is the same for compatible WhereLoops. */
   134921     assert( p->rSetup==0 || pTemplate->rSetup==0
   134922                  || p->rSetup==pTemplate->rSetup );
   134923 
   134924     /* whereLoopAddBtree() always generates and inserts the automatic index
   134925     ** case first.  Hence compatible candidate WhereLoops never have a larger
   134926     ** rSetup. Call this SETUP-INVARIANT */
   134927     assert( p->rSetup>=pTemplate->rSetup );
   134928 
   134929     /* Any loop using an appliation-defined index (or PRIMARY KEY or
   134930     ** UNIQUE constraint) with one or more == constraints is better
   134931     ** than an automatic index. Unless it is a skip-scan. */
   134932     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
   134933      && (pTemplate->nSkip)==0
   134934      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
   134935      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
   134936      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
   134937     ){
   134938       break;
   134939     }
   134940 
   134941     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
   134942     ** discarded.  WhereLoop p is better if:
   134943     **   (1)  p has no more dependencies than pTemplate, and
   134944     **   (2)  p has an equal or lower cost than pTemplate
   134945     */
   134946     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
   134947      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
   134948      && p->rRun<=pTemplate->rRun                      /* (2b) */
   134949      && p->nOut<=pTemplate->nOut                      /* (2c) */
   134950     ){
   134951       return 0;  /* Discard pTemplate */
   134952     }
   134953 
   134954     /* If pTemplate is always better than p, then cause p to be overwritten
   134955     ** with pTemplate.  pTemplate is better than p if:
   134956     **   (1)  pTemplate has no more dependences than p, and
   134957     **   (2)  pTemplate has an equal or lower cost than p.
   134958     */
   134959     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
   134960      && p->rRun>=pTemplate->rRun                             /* (2a) */
   134961      && p->nOut>=pTemplate->nOut                             /* (2b) */
   134962     ){
   134963       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
   134964       break;   /* Cause p to be overwritten by pTemplate */
   134965     }
   134966   }
   134967   return ppPrev;
   134968 }
   134969 
   134970 /*
   134971 ** Insert or replace a WhereLoop entry using the template supplied.
   134972 **
   134973 ** An existing WhereLoop entry might be overwritten if the new template
   134974 ** is better and has fewer dependencies.  Or the template will be ignored
   134975 ** and no insert will occur if an existing WhereLoop is faster and has
   134976 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
   134977 ** added based on the template.
   134978 **
   134979 ** If pBuilder->pOrSet is not NULL then we care about only the
   134980 ** prerequisites and rRun and nOut costs of the N best loops.  That
   134981 ** information is gathered in the pBuilder->pOrSet object.  This special
   134982 ** processing mode is used only for OR clause processing.
   134983 **
   134984 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
   134985 ** still might overwrite similar loops with the new template if the
   134986 ** new template is better.  Loops may be overwritten if the following
   134987 ** conditions are met:
   134988 **
   134989 **    (1)  They have the same iTab.
   134990 **    (2)  They have the same iSortIdx.
   134991 **    (3)  The template has same or fewer dependencies than the current loop
   134992 **    (4)  The template has the same or lower cost than the current loop
   134993 */
   134994 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
   134995   WhereLoop **ppPrev, *p;
   134996   WhereInfo *pWInfo = pBuilder->pWInfo;
   134997   sqlite3 *db = pWInfo->pParse->db;
   134998   int rc;
   134999 
   135000   /* If pBuilder->pOrSet is defined, then only keep track of the costs
   135001   ** and prereqs.
   135002   */
   135003   if( pBuilder->pOrSet!=0 ){
   135004     if( pTemplate->nLTerm ){
   135005 #if WHERETRACE_ENABLED
   135006       u16 n = pBuilder->pOrSet->n;
   135007       int x =
   135008 #endif
   135009       whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
   135010                                     pTemplate->nOut);
   135011 #if WHERETRACE_ENABLED /* 0x8 */
   135012       if( sqlite3WhereTrace & 0x8 ){
   135013         sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
   135014         whereLoopPrint(pTemplate, pBuilder->pWC);
   135015       }
   135016 #endif
   135017     }
   135018     return SQLITE_OK;
   135019   }
   135020 
   135021   /* Look for an existing WhereLoop to replace with pTemplate
   135022   */
   135023   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
   135024   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
   135025 
   135026   if( ppPrev==0 ){
   135027     /* There already exists a WhereLoop on the list that is better
   135028     ** than pTemplate, so just ignore pTemplate */
   135029 #if WHERETRACE_ENABLED /* 0x8 */
   135030     if( sqlite3WhereTrace & 0x8 ){
   135031       sqlite3DebugPrintf("   skip: ");
   135032       whereLoopPrint(pTemplate, pBuilder->pWC);
   135033     }
   135034 #endif
   135035     return SQLITE_OK;
   135036   }else{
   135037     p = *ppPrev;
   135038   }
   135039 
   135040   /* If we reach this point it means that either p[] should be overwritten
   135041   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
   135042   ** WhereLoop and insert it.
   135043   */
   135044 #if WHERETRACE_ENABLED /* 0x8 */
   135045   if( sqlite3WhereTrace & 0x8 ){
   135046     if( p!=0 ){
   135047       sqlite3DebugPrintf("replace: ");
   135048       whereLoopPrint(p, pBuilder->pWC);
   135049       sqlite3DebugPrintf("   with: ");
   135050     }else{
   135051       sqlite3DebugPrintf("    add: ");
   135052     }
   135053     whereLoopPrint(pTemplate, pBuilder->pWC);
   135054   }
   135055 #endif
   135056   if( p==0 ){
   135057     /* Allocate a new WhereLoop to add to the end of the list */
   135058     *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
   135059     if( p==0 ) return SQLITE_NOMEM_BKPT;
   135060     whereLoopInit(p);
   135061     p->pNextLoop = 0;
   135062   }else{
   135063     /* We will be overwriting WhereLoop p[].  But before we do, first
   135064     ** go through the rest of the list and delete any other entries besides
   135065     ** p[] that are also supplated by pTemplate */
   135066     WhereLoop **ppTail = &p->pNextLoop;
   135067     WhereLoop *pToDel;
   135068     while( *ppTail ){
   135069       ppTail = whereLoopFindLesser(ppTail, pTemplate);
   135070       if( ppTail==0 ) break;
   135071       pToDel = *ppTail;
   135072       if( pToDel==0 ) break;
   135073       *ppTail = pToDel->pNextLoop;
   135074 #if WHERETRACE_ENABLED /* 0x8 */
   135075       if( sqlite3WhereTrace & 0x8 ){
   135076         sqlite3DebugPrintf(" delete: ");
   135077         whereLoopPrint(pToDel, pBuilder->pWC);
   135078       }
   135079 #endif
   135080       whereLoopDelete(db, pToDel);
   135081     }
   135082   }
   135083   rc = whereLoopXfer(db, p, pTemplate);
   135084   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
   135085     Index *pIndex = p->u.btree.pIndex;
   135086     if( pIndex && pIndex->tnum==0 ){
   135087       p->u.btree.pIndex = 0;
   135088     }
   135089   }
   135090   return rc;
   135091 }
   135092 
   135093 /*
   135094 ** Adjust the WhereLoop.nOut value downward to account for terms of the
   135095 ** WHERE clause that reference the loop but which are not used by an
   135096 ** index.
   135097 *
   135098 ** For every WHERE clause term that is not used by the index
   135099 ** and which has a truth probability assigned by one of the likelihood(),
   135100 ** likely(), or unlikely() SQL functions, reduce the estimated number
   135101 ** of output rows by the probability specified.
   135102 **
   135103 ** TUNING:  For every WHERE clause term that is not used by the index
   135104 ** and which does not have an assigned truth probability, heuristics
   135105 ** described below are used to try to estimate the truth probability.
   135106 ** TODO --> Perhaps this is something that could be improved by better
   135107 ** table statistics.
   135108 **
   135109 ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
   135110 ** value corresponds to -1 in LogEst notation, so this means decrement
   135111 ** the WhereLoop.nOut field for every such WHERE clause term.
   135112 **
   135113 ** Heuristic 2:  If there exists one or more WHERE clause terms of the
   135114 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
   135115 ** final output row estimate is no greater than 1/4 of the total number
   135116 ** of rows in the table.  In other words, assume that x==EXPR will filter
   135117 ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
   135118 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
   135119 ** on the "x" column and so in that case only cap the output row estimate
   135120 ** at 1/2 instead of 1/4.
   135121 */
   135122 static void whereLoopOutputAdjust(
   135123   WhereClause *pWC,      /* The WHERE clause */
   135124   WhereLoop *pLoop,      /* The loop to adjust downward */
   135125   LogEst nRow            /* Number of rows in the entire table */
   135126 ){
   135127   WhereTerm *pTerm, *pX;
   135128   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
   135129   int i, j, k;
   135130   LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
   135131 
   135132   assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
   135133   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
   135134     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
   135135     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
   135136     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
   135137     for(j=pLoop->nLTerm-1; j>=0; j--){
   135138       pX = pLoop->aLTerm[j];
   135139       if( pX==0 ) continue;
   135140       if( pX==pTerm ) break;
   135141       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
   135142     }
   135143     if( j<0 ){
   135144       if( pTerm->truthProb<=0 ){
   135145         /* If a truth probability is specified using the likelihood() hints,
   135146         ** then use the probability provided by the application. */
   135147         pLoop->nOut += pTerm->truthProb;
   135148       }else{
   135149         /* In the absence of explicit truth probabilities, use heuristics to
   135150         ** guess a reasonable truth probability. */
   135151         pLoop->nOut--;
   135152         if( pTerm->eOperator&(WO_EQ|WO_IS) ){
   135153           Expr *pRight = pTerm->pExpr->pRight;
   135154           testcase( pTerm->pExpr->op==TK_IS );
   135155           if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
   135156             k = 10;
   135157           }else{
   135158             k = 20;
   135159           }
   135160           if( iReduce<k ) iReduce = k;
   135161         }
   135162       }
   135163     }
   135164   }
   135165   if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
   135166 }
   135167 
   135168 /*
   135169 ** Term pTerm is a vector range comparison operation. The first comparison
   135170 ** in the vector can be optimized using column nEq of the index. This
   135171 ** function returns the total number of vector elements that can be used
   135172 ** as part of the range comparison.
   135173 **
   135174 ** For example, if the query is:
   135175 **
   135176 **   WHERE a = ? AND (b, c, d) > (?, ?, ?)
   135177 **
   135178 ** and the index:
   135179 **
   135180 **   CREATE INDEX ... ON (a, b, c, d, e)
   135181 **
   135182 ** then this function would be invoked with nEq=1. The value returned in
   135183 ** this case is 3.
   135184 */
   135185 static int whereRangeVectorLen(
   135186   Parse *pParse,       /* Parsing context */
   135187   int iCur,            /* Cursor open on pIdx */
   135188   Index *pIdx,         /* The index to be used for a inequality constraint */
   135189   int nEq,             /* Number of prior equality constraints on same index */
   135190   WhereTerm *pTerm     /* The vector inequality constraint */
   135191 ){
   135192   int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
   135193   int i;
   135194 
   135195   nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
   135196   for(i=1; i<nCmp; i++){
   135197     /* Test if comparison i of pTerm is compatible with column (i+nEq)
   135198     ** of the index. If not, exit the loop.  */
   135199     char aff;                     /* Comparison affinity */
   135200     char idxaff = 0;              /* Indexed columns affinity */
   135201     CollSeq *pColl;               /* Comparison collation sequence */
   135202     Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
   135203     Expr *pRhs = pTerm->pExpr->pRight;
   135204     if( pRhs->flags & EP_xIsSelect ){
   135205       pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
   135206     }else{
   135207       pRhs = pRhs->x.pList->a[i].pExpr;
   135208     }
   135209 
   135210     /* Check that the LHS of the comparison is a column reference to
   135211     ** the right column of the right source table. And that the sort
   135212     ** order of the index column is the same as the sort order of the
   135213     ** leftmost index column.  */
   135214     if( pLhs->op!=TK_COLUMN
   135215      || pLhs->iTable!=iCur
   135216      || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
   135217      || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
   135218     ){
   135219       break;
   135220     }
   135221 
   135222     testcase( pLhs->iColumn==XN_ROWID );
   135223     aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
   135224     idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
   135225     if( aff!=idxaff ) break;
   135226 
   135227     pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
   135228     if( pColl==0 ) break;
   135229     if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
   135230   }
   135231   return i;
   135232 }
   135233 
   135234 /*
   135235 ** Adjust the cost C by the costMult facter T.  This only occurs if
   135236 ** compiled with -DSQLITE_ENABLE_COSTMULT
   135237 */
   135238 #ifdef SQLITE_ENABLE_COSTMULT
   135239 # define ApplyCostMultiplier(C,T)  C += T
   135240 #else
   135241 # define ApplyCostMultiplier(C,T)
   135242 #endif
   135243 
   135244 /*
   135245 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
   135246 ** index pIndex. Try to match one more.
   135247 **
   135248 ** When this function is called, pBuilder->pNew->nOut contains the
   135249 ** number of rows expected to be visited by filtering using the nEq
   135250 ** terms only. If it is modified, this value is restored before this
   135251 ** function returns.
   135252 **
   135253 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
   135254 ** INTEGER PRIMARY KEY.
   135255 */
   135256 static int whereLoopAddBtreeIndex(
   135257   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
   135258   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
   135259   Index *pProbe,                  /* An index on pSrc */
   135260   LogEst nInMul                   /* log(Number of iterations due to IN) */
   135261 ){
   135262   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
   135263   Parse *pParse = pWInfo->pParse;        /* Parsing context */
   135264   sqlite3 *db = pParse->db;       /* Database connection malloc context */
   135265   WhereLoop *pNew;                /* Template WhereLoop under construction */
   135266   WhereTerm *pTerm;               /* A WhereTerm under consideration */
   135267   int opMask;                     /* Valid operators for constraints */
   135268   WhereScan scan;                 /* Iterator for WHERE terms */
   135269   Bitmask saved_prereq;           /* Original value of pNew->prereq */
   135270   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
   135271   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
   135272   u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */
   135273   u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */
   135274   u16 saved_nSkip;                /* Original value of pNew->nSkip */
   135275   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
   135276   LogEst saved_nOut;              /* Original value of pNew->nOut */
   135277   int rc = SQLITE_OK;             /* Return code */
   135278   LogEst rSize;                   /* Number of rows in the table */
   135279   LogEst rLogSize;                /* Logarithm of table size */
   135280   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
   135281 
   135282   pNew = pBuilder->pNew;
   135283   if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
   135284   WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
   135285                      pProbe->zName, pNew->u.btree.nEq));
   135286 
   135287   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
   135288   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
   135289   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
   135290     opMask = WO_LT|WO_LE;
   135291   }else{
   135292     assert( pNew->u.btree.nBtm==0 );
   135293     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
   135294   }
   135295   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
   135296 
   135297   assert( pNew->u.btree.nEq<pProbe->nColumn );
   135298 
   135299   saved_nEq = pNew->u.btree.nEq;
   135300   saved_nBtm = pNew->u.btree.nBtm;
   135301   saved_nTop = pNew->u.btree.nTop;
   135302   saved_nSkip = pNew->nSkip;
   135303   saved_nLTerm = pNew->nLTerm;
   135304   saved_wsFlags = pNew->wsFlags;
   135305   saved_prereq = pNew->prereq;
   135306   saved_nOut = pNew->nOut;
   135307   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
   135308                         opMask, pProbe);
   135309   pNew->rSetup = 0;
   135310   rSize = pProbe->aiRowLogEst[0];
   135311   rLogSize = estLog(rSize);
   135312   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
   135313     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
   135314     LogEst rCostIdx;
   135315     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
   135316     int nIn = 0;
   135317 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   135318     int nRecValid = pBuilder->nRecValid;
   135319 #endif
   135320     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
   135321      && indexColumnNotNull(pProbe, saved_nEq)
   135322     ){
   135323       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
   135324     }
   135325     if( pTerm->prereqRight & pNew->maskSelf ) continue;
   135326 
   135327     /* Do not allow the upper bound of a LIKE optimization range constraint
   135328     ** to mix with a lower range bound from some other source */
   135329     if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
   135330 
   135331     /* Do not allow IS constraints from the WHERE clause to be used by the
   135332     ** right table of a LEFT JOIN.  Only constraints in the ON clause are
   135333     ** allowed */
   135334     if( (pSrc->fg.jointype & JT_LEFT)!=0
   135335      && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
   135336      && (eOp & (WO_IS|WO_ISNULL))!=0
   135337     ){
   135338       testcase( eOp & WO_IS );
   135339       testcase( eOp & WO_ISNULL );
   135340       continue;
   135341     }
   135342 
   135343     if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
   135344       pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
   135345     }else{
   135346       pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
   135347     }
   135348     pNew->wsFlags = saved_wsFlags;
   135349     pNew->u.btree.nEq = saved_nEq;
   135350     pNew->u.btree.nBtm = saved_nBtm;
   135351     pNew->u.btree.nTop = saved_nTop;
   135352     pNew->nLTerm = saved_nLTerm;
   135353     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
   135354     pNew->aLTerm[pNew->nLTerm++] = pTerm;
   135355     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
   135356 
   135357     assert( nInMul==0
   135358         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
   135359         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
   135360         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
   135361     );
   135362 
   135363     if( eOp & WO_IN ){
   135364       Expr *pExpr = pTerm->pExpr;
   135365       pNew->wsFlags |= WHERE_COLUMN_IN;
   135366       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   135367         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
   135368         int i;
   135369         nIn = 46;  assert( 46==sqlite3LogEst(25) );
   135370 
   135371         /* The expression may actually be of the form (x, y) IN (SELECT...).
   135372         ** In this case there is a separate term for each of (x) and (y).
   135373         ** However, the nIn multiplier should only be applied once, not once
   135374         ** for each such term. The following loop checks that pTerm is the
   135375         ** first such term in use, and sets nIn back to 0 if it is not. */
   135376         for(i=0; i<pNew->nLTerm-1; i++){
   135377           if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
   135378         }
   135379       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
   135380         /* "x IN (value, value, ...)" */
   135381         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
   135382         assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
   135383                           ** changes "x IN (?)" into "x=?". */
   135384       }
   135385     }else if( eOp & (WO_EQ|WO_IS) ){
   135386       int iCol = pProbe->aiColumn[saved_nEq];
   135387       pNew->wsFlags |= WHERE_COLUMN_EQ;
   135388       assert( saved_nEq==pNew->u.btree.nEq );
   135389       if( iCol==XN_ROWID
   135390        || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
   135391       ){
   135392         if( iCol>=0 && pProbe->uniqNotNull==0 ){
   135393           pNew->wsFlags |= WHERE_UNQ_WANTED;
   135394         }else{
   135395           pNew->wsFlags |= WHERE_ONEROW;
   135396         }
   135397       }
   135398     }else if( eOp & WO_ISNULL ){
   135399       pNew->wsFlags |= WHERE_COLUMN_NULL;
   135400     }else if( eOp & (WO_GT|WO_GE) ){
   135401       testcase( eOp & WO_GT );
   135402       testcase( eOp & WO_GE );
   135403       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
   135404       pNew->u.btree.nBtm = whereRangeVectorLen(
   135405           pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
   135406       );
   135407       pBtm = pTerm;
   135408       pTop = 0;
   135409       if( pTerm->wtFlags & TERM_LIKEOPT ){
   135410         /* Range contraints that come from the LIKE optimization are
   135411         ** always used in pairs. */
   135412         pTop = &pTerm[1];
   135413         assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
   135414         assert( pTop->wtFlags & TERM_LIKEOPT );
   135415         assert( pTop->eOperator==WO_LT );
   135416         if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
   135417         pNew->aLTerm[pNew->nLTerm++] = pTop;
   135418         pNew->wsFlags |= WHERE_TOP_LIMIT;
   135419         pNew->u.btree.nTop = 1;
   135420       }
   135421     }else{
   135422       assert( eOp & (WO_LT|WO_LE) );
   135423       testcase( eOp & WO_LT );
   135424       testcase( eOp & WO_LE );
   135425       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
   135426       pNew->u.btree.nTop = whereRangeVectorLen(
   135427           pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
   135428       );
   135429       pTop = pTerm;
   135430       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
   135431                      pNew->aLTerm[pNew->nLTerm-2] : 0;
   135432     }
   135433 
   135434     /* At this point pNew->nOut is set to the number of rows expected to
   135435     ** be visited by the index scan before considering term pTerm, or the
   135436     ** values of nIn and nInMul. In other words, assuming that all
   135437     ** "x IN(...)" terms are replaced with "x = ?". This block updates
   135438     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
   135439     assert( pNew->nOut==saved_nOut );
   135440     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
   135441       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
   135442       ** data, using some other estimate.  */
   135443       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
   135444     }else{
   135445       int nEq = ++pNew->u.btree.nEq;
   135446       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
   135447 
   135448       assert( pNew->nOut==saved_nOut );
   135449       if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
   135450         assert( (eOp & WO_IN) || nIn==0 );
   135451         testcase( eOp & WO_IN );
   135452         pNew->nOut += pTerm->truthProb;
   135453         pNew->nOut -= nIn;
   135454       }else{
   135455 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   135456         tRowcnt nOut = 0;
   135457         if( nInMul==0
   135458          && pProbe->nSample
   135459          && pNew->u.btree.nEq<=pProbe->nSampleCol
   135460          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
   135461         ){
   135462           Expr *pExpr = pTerm->pExpr;
   135463           if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
   135464             testcase( eOp & WO_EQ );
   135465             testcase( eOp & WO_IS );
   135466             testcase( eOp & WO_ISNULL );
   135467             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
   135468           }else{
   135469             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
   135470           }
   135471           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   135472           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
   135473           if( nOut ){
   135474             pNew->nOut = sqlite3LogEst(nOut);
   135475             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
   135476             pNew->nOut -= nIn;
   135477           }
   135478         }
   135479         if( nOut==0 )
   135480 #endif
   135481         {
   135482           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
   135483           if( eOp & WO_ISNULL ){
   135484             /* TUNING: If there is no likelihood() value, assume that a
   135485             ** "col IS NULL" expression matches twice as many rows
   135486             ** as (col=?). */
   135487             pNew->nOut += 10;
   135488           }
   135489         }
   135490       }
   135491     }
   135492 
   135493     /* Set rCostIdx to the cost of visiting selected rows in index. Add
   135494     ** it to pNew->rRun, which is currently set to the cost of the index
   135495     ** seek only. Then, if this is a non-covering index, add the cost of
   135496     ** visiting the rows in the main table.  */
   135497     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
   135498     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
   135499     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
   135500       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
   135501     }
   135502     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
   135503 
   135504     nOutUnadjusted = pNew->nOut;
   135505     pNew->rRun += nInMul + nIn;
   135506     pNew->nOut += nInMul + nIn;
   135507     whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
   135508     rc = whereLoopInsert(pBuilder, pNew);
   135509 
   135510     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
   135511       pNew->nOut = saved_nOut;
   135512     }else{
   135513       pNew->nOut = nOutUnadjusted;
   135514     }
   135515 
   135516     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
   135517      && pNew->u.btree.nEq<pProbe->nColumn
   135518     ){
   135519       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
   135520     }
   135521     pNew->nOut = saved_nOut;
   135522 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   135523     pBuilder->nRecValid = nRecValid;
   135524 #endif
   135525   }
   135526   pNew->prereq = saved_prereq;
   135527   pNew->u.btree.nEq = saved_nEq;
   135528   pNew->u.btree.nBtm = saved_nBtm;
   135529   pNew->u.btree.nTop = saved_nTop;
   135530   pNew->nSkip = saved_nSkip;
   135531   pNew->wsFlags = saved_wsFlags;
   135532   pNew->nOut = saved_nOut;
   135533   pNew->nLTerm = saved_nLTerm;
   135534 
   135535   /* Consider using a skip-scan if there are no WHERE clause constraints
   135536   ** available for the left-most terms of the index, and if the average
   135537   ** number of repeats in the left-most terms is at least 18.
   135538   **
   135539   ** The magic number 18 is selected on the basis that scanning 17 rows
   135540   ** is almost always quicker than an index seek (even though if the index
   135541   ** contains fewer than 2^17 rows we assume otherwise in other parts of
   135542   ** the code). And, even if it is not, it should not be too much slower.
   135543   ** On the other hand, the extra seeks could end up being significantly
   135544   ** more expensive.  */
   135545   assert( 42==sqlite3LogEst(18) );
   135546   if( saved_nEq==saved_nSkip
   135547    && saved_nEq+1<pProbe->nKeyCol
   135548    && pProbe->noSkipScan==0
   135549    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
   135550    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
   135551   ){
   135552     LogEst nIter;
   135553     pNew->u.btree.nEq++;
   135554     pNew->nSkip++;
   135555     pNew->aLTerm[pNew->nLTerm++] = 0;
   135556     pNew->wsFlags |= WHERE_SKIPSCAN;
   135557     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
   135558     pNew->nOut -= nIter;
   135559     /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
   135560     ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
   135561     nIter += 5;
   135562     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
   135563     pNew->nOut = saved_nOut;
   135564     pNew->u.btree.nEq = saved_nEq;
   135565     pNew->nSkip = saved_nSkip;
   135566     pNew->wsFlags = saved_wsFlags;
   135567   }
   135568 
   135569   WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
   135570                       pProbe->zName, saved_nEq, rc));
   135571   return rc;
   135572 }
   135573 
   135574 /*
   135575 ** Return True if it is possible that pIndex might be useful in
   135576 ** implementing the ORDER BY clause in pBuilder.
   135577 **
   135578 ** Return False if pBuilder does not contain an ORDER BY clause or
   135579 ** if there is no way for pIndex to be useful in implementing that
   135580 ** ORDER BY clause.
   135581 */
   135582 static int indexMightHelpWithOrderBy(
   135583   WhereLoopBuilder *pBuilder,
   135584   Index *pIndex,
   135585   int iCursor
   135586 ){
   135587   ExprList *pOB;
   135588   ExprList *aColExpr;
   135589   int ii, jj;
   135590 
   135591   if( pIndex->bUnordered ) return 0;
   135592   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
   135593   for(ii=0; ii<pOB->nExpr; ii++){
   135594     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
   135595     if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
   135596       if( pExpr->iColumn<0 ) return 1;
   135597       for(jj=0; jj<pIndex->nKeyCol; jj++){
   135598         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
   135599       }
   135600     }else if( (aColExpr = pIndex->aColExpr)!=0 ){
   135601       for(jj=0; jj<pIndex->nKeyCol; jj++){
   135602         if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
   135603         if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
   135604           return 1;
   135605         }
   135606       }
   135607     }
   135608   }
   135609   return 0;
   135610 }
   135611 
   135612 /*
   135613 ** Return a bitmask where 1s indicate that the corresponding column of
   135614 ** the table is used by an index.  Only the first 63 columns are considered.
   135615 */
   135616 static Bitmask columnsInIndex(Index *pIdx){
   135617   Bitmask m = 0;
   135618   int j;
   135619   for(j=pIdx->nColumn-1; j>=0; j--){
   135620     int x = pIdx->aiColumn[j];
   135621     if( x>=0 ){
   135622       testcase( x==BMS-1 );
   135623       testcase( x==BMS-2 );
   135624       if( x<BMS-1 ) m |= MASKBIT(x);
   135625     }
   135626   }
   135627   return m;
   135628 }
   135629 
   135630 /* Check to see if a partial index with pPartIndexWhere can be used
   135631 ** in the current query.  Return true if it can be and false if not.
   135632 */
   135633 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
   135634   int i;
   135635   WhereTerm *pTerm;
   135636   Parse *pParse = pWC->pWInfo->pParse;
   135637   while( pWhere->op==TK_AND ){
   135638     if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
   135639     pWhere = pWhere->pRight;
   135640   }
   135641   if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
   135642   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   135643     Expr *pExpr = pTerm->pExpr;
   135644     if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
   135645      && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
   135646     ){
   135647       return 1;
   135648     }
   135649   }
   135650   return 0;
   135651 }
   135652 
   135653 /*
   135654 ** Add all WhereLoop objects for a single table of the join where the table
   135655 ** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
   135656 ** a b-tree table, not a virtual table.
   135657 **
   135658 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
   135659 ** are calculated as follows:
   135660 **
   135661 ** For a full scan, assuming the table (or index) contains nRow rows:
   135662 **
   135663 **     cost = nRow * 3.0                    // full-table scan
   135664 **     cost = nRow * K                      // scan of covering index
   135665 **     cost = nRow * (K+3.0)                // scan of non-covering index
   135666 **
   135667 ** where K is a value between 1.1 and 3.0 set based on the relative
   135668 ** estimated average size of the index and table records.
   135669 **
   135670 ** For an index scan, where nVisit is the number of index rows visited
   135671 ** by the scan, and nSeek is the number of seek operations required on
   135672 ** the index b-tree:
   135673 **
   135674 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
   135675 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
   135676 **
   135677 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
   135678 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
   135679 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
   135680 **
   135681 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
   135682 ** of uncertainty.  For this reason, scoring is designed to pick plans that
   135683 ** "do the least harm" if the estimates are inaccurate.  For example, a
   135684 ** log(nRow) factor is omitted from a non-covering index scan in order to
   135685 ** bias the scoring in favor of using an index, since the worst-case
   135686 ** performance of using an index is far better than the worst-case performance
   135687 ** of a full table scan.
   135688 */
   135689 static int whereLoopAddBtree(
   135690   WhereLoopBuilder *pBuilder, /* WHERE clause information */
   135691   Bitmask mPrereq             /* Extra prerequesites for using this table */
   135692 ){
   135693   WhereInfo *pWInfo;          /* WHERE analysis context */
   135694   Index *pProbe;              /* An index we are evaluating */
   135695   Index sPk;                  /* A fake index object for the primary key */
   135696   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
   135697   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   135698   SrcList *pTabList;          /* The FROM clause */
   135699   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
   135700   WhereLoop *pNew;            /* Template WhereLoop object */
   135701   int rc = SQLITE_OK;         /* Return code */
   135702   int iSortIdx = 1;           /* Index number */
   135703   int b;                      /* A boolean value */
   135704   LogEst rSize;               /* number of rows in the table */
   135705   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
   135706   WhereClause *pWC;           /* The parsed WHERE clause */
   135707   Table *pTab;                /* Table being queried */
   135708 
   135709   pNew = pBuilder->pNew;
   135710   pWInfo = pBuilder->pWInfo;
   135711   pTabList = pWInfo->pTabList;
   135712   pSrc = pTabList->a + pNew->iTab;
   135713   pTab = pSrc->pTab;
   135714   pWC = pBuilder->pWC;
   135715   assert( !IsVirtual(pSrc->pTab) );
   135716 
   135717   if( pSrc->pIBIndex ){
   135718     /* An INDEXED BY clause specifies a particular index to use */
   135719     pProbe = pSrc->pIBIndex;
   135720   }else if( !HasRowid(pTab) ){
   135721     pProbe = pTab->pIndex;
   135722   }else{
   135723     /* There is no INDEXED BY clause.  Create a fake Index object in local
   135724     ** variable sPk to represent the rowid primary key index.  Make this
   135725     ** fake index the first in a chain of Index objects with all of the real
   135726     ** indices to follow */
   135727     Index *pFirst;                  /* First of real indices on the table */
   135728     memset(&sPk, 0, sizeof(Index));
   135729     sPk.nKeyCol = 1;
   135730     sPk.nColumn = 1;
   135731     sPk.aiColumn = &aiColumnPk;
   135732     sPk.aiRowLogEst = aiRowEstPk;
   135733     sPk.onError = OE_Replace;
   135734     sPk.pTable = pTab;
   135735     sPk.szIdxRow = pTab->szTabRow;
   135736     aiRowEstPk[0] = pTab->nRowLogEst;
   135737     aiRowEstPk[1] = 0;
   135738     pFirst = pSrc->pTab->pIndex;
   135739     if( pSrc->fg.notIndexed==0 ){
   135740       /* The real indices of the table are only considered if the
   135741       ** NOT INDEXED qualifier is omitted from the FROM clause */
   135742       sPk.pNext = pFirst;
   135743     }
   135744     pProbe = &sPk;
   135745   }
   135746   rSize = pTab->nRowLogEst;
   135747   rLogSize = estLog(rSize);
   135748 
   135749 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   135750   /* Automatic indexes */
   135751   if( !pBuilder->pOrSet      /* Not part of an OR optimization */
   135752    && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
   135753    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
   135754    && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
   135755    && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
   135756    && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
   135757    && !pSrc->fg.isCorrelated /* Not a correlated subquery */
   135758    && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
   135759   ){
   135760     /* Generate auto-index WhereLoops */
   135761     WhereTerm *pTerm;
   135762     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
   135763     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
   135764       if( pTerm->prereqRight & pNew->maskSelf ) continue;
   135765       if( termCanDriveIndex(pTerm, pSrc, 0) ){
   135766         pNew->u.btree.nEq = 1;
   135767         pNew->nSkip = 0;
   135768         pNew->u.btree.pIndex = 0;
   135769         pNew->nLTerm = 1;
   135770         pNew->aLTerm[0] = pTerm;
   135771         /* TUNING: One-time cost for computing the automatic index is
   135772         ** estimated to be X*N*log2(N) where N is the number of rows in
   135773         ** the table being indexed and where X is 7 (LogEst=28) for normal
   135774         ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
   135775         ** of X is smaller for views and subqueries so that the query planner
   135776         ** will be more aggressive about generating automatic indexes for
   135777         ** those objects, since there is no opportunity to add schema
   135778         ** indexes on subqueries and views. */
   135779         pNew->rSetup = rLogSize + rSize + 4;
   135780         if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
   135781           pNew->rSetup += 24;
   135782         }
   135783         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
   135784         if( pNew->rSetup<0 ) pNew->rSetup = 0;
   135785         /* TUNING: Each index lookup yields 20 rows in the table.  This
   135786         ** is more than the usual guess of 10 rows, since we have no way
   135787         ** of knowing how selective the index will ultimately be.  It would
   135788         ** not be unreasonable to make this value much larger. */
   135789         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
   135790         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
   135791         pNew->wsFlags = WHERE_AUTO_INDEX;
   135792         pNew->prereq = mPrereq | pTerm->prereqRight;
   135793         rc = whereLoopInsert(pBuilder, pNew);
   135794       }
   135795     }
   135796   }
   135797 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   135798 
   135799   /* Loop over all indices. If there was an INDEXED BY clause, then only
   135800   ** consider index pProbe.  */
   135801   for(; rc==SQLITE_OK && pProbe;
   135802       pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
   135803   ){
   135804     if( pProbe->pPartIdxWhere!=0
   135805      && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
   135806       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
   135807       continue;  /* Partial index inappropriate for this query */
   135808     }
   135809     if( pProbe->bNoQuery ) continue;
   135810     rSize = pProbe->aiRowLogEst[0];
   135811     pNew->u.btree.nEq = 0;
   135812     pNew->u.btree.nBtm = 0;
   135813     pNew->u.btree.nTop = 0;
   135814     pNew->nSkip = 0;
   135815     pNew->nLTerm = 0;
   135816     pNew->iSortIdx = 0;
   135817     pNew->rSetup = 0;
   135818     pNew->prereq = mPrereq;
   135819     pNew->nOut = rSize;
   135820     pNew->u.btree.pIndex = pProbe;
   135821     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
   135822     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
   135823     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
   135824     if( pProbe->tnum<=0 ){
   135825       /* Integer primary key index */
   135826       pNew->wsFlags = WHERE_IPK;
   135827 
   135828       /* Full table scan */
   135829       pNew->iSortIdx = b ? iSortIdx : 0;
   135830       /* TUNING: Cost of full table scan is (N*3.0). */
   135831       pNew->rRun = rSize + 16;
   135832       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
   135833       whereLoopOutputAdjust(pWC, pNew, rSize);
   135834       rc = whereLoopInsert(pBuilder, pNew);
   135835       pNew->nOut = rSize;
   135836       if( rc ) break;
   135837     }else{
   135838       Bitmask m;
   135839       if( pProbe->isCovering ){
   135840         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
   135841         m = 0;
   135842       }else{
   135843         m = pSrc->colUsed & ~columnsInIndex(pProbe);
   135844         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
   135845       }
   135846 
   135847       /* Full scan via index */
   135848       if( b
   135849        || !HasRowid(pTab)
   135850        || pProbe->pPartIdxWhere!=0
   135851        || ( m==0
   135852          && pProbe->bUnordered==0
   135853          && (pProbe->szIdxRow<pTab->szTabRow)
   135854          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
   135855          && sqlite3GlobalConfig.bUseCis
   135856          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
   135857           )
   135858       ){
   135859         pNew->iSortIdx = b ? iSortIdx : 0;
   135860 
   135861         /* The cost of visiting the index rows is N*K, where K is
   135862         ** between 1.1 and 3.0, depending on the relative sizes of the
   135863         ** index and table rows. */
   135864         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
   135865         if( m!=0 ){
   135866           /* If this is a non-covering index scan, add in the cost of
   135867           ** doing table lookups.  The cost will be 3x the number of
   135868           ** lookups.  Take into account WHERE clause terms that can be
   135869           ** satisfied using just the index, and that do not require a
   135870           ** table lookup. */
   135871           LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
   135872           int ii;
   135873           int iCur = pSrc->iCursor;
   135874           WhereClause *pWC2 = &pWInfo->sWC;
   135875           for(ii=0; ii<pWC2->nTerm; ii++){
   135876             WhereTerm *pTerm = &pWC2->a[ii];
   135877             if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
   135878               break;
   135879             }
   135880             /* pTerm can be evaluated using just the index.  So reduce
   135881             ** the expected number of table lookups accordingly */
   135882             if( pTerm->truthProb<=0 ){
   135883               nLookup += pTerm->truthProb;
   135884             }else{
   135885               nLookup--;
   135886               if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
   135887             }
   135888           }
   135889 
   135890           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
   135891         }
   135892         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
   135893         whereLoopOutputAdjust(pWC, pNew, rSize);
   135894         rc = whereLoopInsert(pBuilder, pNew);
   135895         pNew->nOut = rSize;
   135896         if( rc ) break;
   135897       }
   135898     }
   135899 
   135900     pBuilder->bldFlags = 0;
   135901     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
   135902     if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
   135903       /* If a non-unique index is used, or if a prefix of the key for
   135904       ** unique index is used (making the index functionally non-unique)
   135905       ** then the sqlite_stat1 data becomes important for scoring the
   135906       ** plan */
   135907       pTab->tabFlags |= TF_StatsUsed;
   135908     }
   135909 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   135910     sqlite3Stat4ProbeFree(pBuilder->pRec);
   135911     pBuilder->nRecValid = 0;
   135912     pBuilder->pRec = 0;
   135913 #endif
   135914   }
   135915   return rc;
   135916 }
   135917 
   135918 #ifndef SQLITE_OMIT_VIRTUALTABLE
   135919 
   135920 /*
   135921 ** Argument pIdxInfo is already populated with all constraints that may
   135922 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
   135923 ** function marks a subset of those constraints usable, invokes the
   135924 ** xBestIndex method and adds the returned plan to pBuilder.
   135925 **
   135926 ** A constraint is marked usable if:
   135927 **
   135928 **   * Argument mUsable indicates that its prerequisites are available, and
   135929 **
   135930 **   * It is not one of the operators specified in the mExclude mask passed
   135931 **     as the fourth argument (which in practice is either WO_IN or 0).
   135932 **
   135933 ** Argument mPrereq is a mask of tables that must be scanned before the
   135934 ** virtual table in question. These are added to the plans prerequisites
   135935 ** before it is added to pBuilder.
   135936 **
   135937 ** Output parameter *pbIn is set to true if the plan added to pBuilder
   135938 ** uses one or more WO_IN terms, or false otherwise.
   135939 */
   135940 static int whereLoopAddVirtualOne(
   135941   WhereLoopBuilder *pBuilder,
   135942   Bitmask mPrereq,                /* Mask of tables that must be used. */
   135943   Bitmask mUsable,                /* Mask of usable tables */
   135944   u16 mExclude,                   /* Exclude terms using these operators */
   135945   sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
   135946   u16 mNoOmit,                    /* Do not omit these constraints */
   135947   int *pbIn                       /* OUT: True if plan uses an IN(...) op */
   135948 ){
   135949   WhereClause *pWC = pBuilder->pWC;
   135950   struct sqlite3_index_constraint *pIdxCons;
   135951   struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
   135952   int i;
   135953   int mxTerm;
   135954   int rc = SQLITE_OK;
   135955   WhereLoop *pNew = pBuilder->pNew;
   135956   Parse *pParse = pBuilder->pWInfo->pParse;
   135957   struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
   135958   int nConstraint = pIdxInfo->nConstraint;
   135959 
   135960   assert( (mUsable & mPrereq)==mPrereq );
   135961   *pbIn = 0;
   135962   pNew->prereq = mPrereq;
   135963 
   135964   /* Set the usable flag on the subset of constraints identified by
   135965   ** arguments mUsable and mExclude. */
   135966   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   135967   for(i=0; i<nConstraint; i++, pIdxCons++){
   135968     WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
   135969     pIdxCons->usable = 0;
   135970     if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
   135971      && (pTerm->eOperator & mExclude)==0
   135972     ){
   135973       pIdxCons->usable = 1;
   135974     }
   135975   }
   135976 
   135977   /* Initialize the output fields of the sqlite3_index_info structure */
   135978   memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
   135979   assert( pIdxInfo->needToFreeIdxStr==0 );
   135980   pIdxInfo->idxStr = 0;
   135981   pIdxInfo->idxNum = 0;
   135982   pIdxInfo->orderByConsumed = 0;
   135983   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
   135984   pIdxInfo->estimatedRows = 25;
   135985   pIdxInfo->idxFlags = 0;
   135986   pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
   135987 
   135988   /* Invoke the virtual table xBestIndex() method */
   135989   rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
   135990   if( rc ) return rc;
   135991 
   135992   mxTerm = -1;
   135993   assert( pNew->nLSlot>=nConstraint );
   135994   for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
   135995   pNew->u.vtab.omitMask = 0;
   135996   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   135997   for(i=0; i<nConstraint; i++, pIdxCons++){
   135998     int iTerm;
   135999     if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
   136000       WhereTerm *pTerm;
   136001       int j = pIdxCons->iTermOffset;
   136002       if( iTerm>=nConstraint
   136003        || j<0
   136004        || j>=pWC->nTerm
   136005        || pNew->aLTerm[iTerm]!=0
   136006        || pIdxCons->usable==0
   136007       ){
   136008         rc = SQLITE_ERROR;
   136009         sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
   136010         return rc;
   136011       }
   136012       testcase( iTerm==nConstraint-1 );
   136013       testcase( j==0 );
   136014       testcase( j==pWC->nTerm-1 );
   136015       pTerm = &pWC->a[j];
   136016       pNew->prereq |= pTerm->prereqRight;
   136017       assert( iTerm<pNew->nLSlot );
   136018       pNew->aLTerm[iTerm] = pTerm;
   136019       if( iTerm>mxTerm ) mxTerm = iTerm;
   136020       testcase( iTerm==15 );
   136021       testcase( iTerm==16 );
   136022       if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
   136023       if( (pTerm->eOperator & WO_IN)!=0 ){
   136024         /* A virtual table that is constrained by an IN clause may not
   136025         ** consume the ORDER BY clause because (1) the order of IN terms
   136026         ** is not necessarily related to the order of output terms and
   136027         ** (2) Multiple outputs from a single IN value will not merge
   136028         ** together.  */
   136029         pIdxInfo->orderByConsumed = 0;
   136030         pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
   136031         *pbIn = 1; assert( (mExclude & WO_IN)==0 );
   136032       }
   136033     }
   136034   }
   136035   pNew->u.vtab.omitMask &= ~mNoOmit;
   136036 
   136037   pNew->nLTerm = mxTerm+1;
   136038   assert( pNew->nLTerm<=pNew->nLSlot );
   136039   pNew->u.vtab.idxNum = pIdxInfo->idxNum;
   136040   pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
   136041   pIdxInfo->needToFreeIdxStr = 0;
   136042   pNew->u.vtab.idxStr = pIdxInfo->idxStr;
   136043   pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
   136044       pIdxInfo->nOrderBy : 0);
   136045   pNew->rSetup = 0;
   136046   pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
   136047   pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
   136048 
   136049   /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
   136050   ** that the scan will visit at most one row. Clear it otherwise. */
   136051   if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
   136052     pNew->wsFlags |= WHERE_ONEROW;
   136053   }else{
   136054     pNew->wsFlags &= ~WHERE_ONEROW;
   136055   }
   136056   rc = whereLoopInsert(pBuilder, pNew);
   136057   if( pNew->u.vtab.needFree ){
   136058     sqlite3_free(pNew->u.vtab.idxStr);
   136059     pNew->u.vtab.needFree = 0;
   136060   }
   136061   WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
   136062                       *pbIn, (sqlite3_uint64)mPrereq,
   136063                       (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
   136064 
   136065   return rc;
   136066 }
   136067 
   136068 /*
   136069 ** If this function is invoked from within an xBestIndex() callback, it
   136070 ** returns a pointer to a buffer containing the name of the collation
   136071 ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
   136072 ** array. Or, if iCons is out of range or there is no active xBestIndex
   136073 ** call, return NULL.
   136074 */
   136075 SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
   136076   HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
   136077   const char *zRet = 0;
   136078   if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
   136079     CollSeq *pC = 0;
   136080     int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
   136081     Expr *pX = pHidden->pWC->a[iTerm].pExpr;
   136082     if( pX->pLeft ){
   136083       pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
   136084     }
   136085     zRet = (pC ? pC->zName : "BINARY");
   136086   }
   136087   return zRet;
   136088 }
   136089 
   136090 /*
   136091 ** Add all WhereLoop objects for a table of the join identified by
   136092 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
   136093 **
   136094 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
   136095 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
   136096 ** entries that occur before the virtual table in the FROM clause and are
   136097 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
   136098 ** mUnusable mask contains all FROM clause entries that occur after the
   136099 ** virtual table and are separated from it by at least one LEFT or
   136100 ** CROSS JOIN.
   136101 **
   136102 ** For example, if the query were:
   136103 **
   136104 **   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
   136105 **
   136106 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
   136107 **
   136108 ** All the tables in mPrereq must be scanned before the current virtual
   136109 ** table. So any terms for which all prerequisites are satisfied by
   136110 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
   136111 ** Conversely, all tables in mUnusable must be scanned after the current
   136112 ** virtual table, so any terms for which the prerequisites overlap with
   136113 ** mUnusable should always be configured as "not-usable" for xBestIndex.
   136114 */
   136115 static int whereLoopAddVirtual(
   136116   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
   136117   Bitmask mPrereq,             /* Tables that must be scanned before this one */
   136118   Bitmask mUnusable            /* Tables that must be scanned after this one */
   136119 ){
   136120   int rc = SQLITE_OK;          /* Return code */
   136121   WhereInfo *pWInfo;           /* WHERE analysis context */
   136122   Parse *pParse;               /* The parsing context */
   136123   WhereClause *pWC;            /* The WHERE clause */
   136124   struct SrcList_item *pSrc;   /* The FROM clause term to search */
   136125   sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
   136126   int nConstraint;             /* Number of constraints in p */
   136127   int bIn;                     /* True if plan uses IN(...) operator */
   136128   WhereLoop *pNew;
   136129   Bitmask mBest;               /* Tables used by best possible plan */
   136130   u16 mNoOmit;
   136131 
   136132   assert( (mPrereq & mUnusable)==0 );
   136133   pWInfo = pBuilder->pWInfo;
   136134   pParse = pWInfo->pParse;
   136135   pWC = pBuilder->pWC;
   136136   pNew = pBuilder->pNew;
   136137   pSrc = &pWInfo->pTabList->a[pNew->iTab];
   136138   assert( IsVirtual(pSrc->pTab) );
   136139   p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
   136140       &mNoOmit);
   136141   if( p==0 ) return SQLITE_NOMEM_BKPT;
   136142   pNew->rSetup = 0;
   136143   pNew->wsFlags = WHERE_VIRTUALTABLE;
   136144   pNew->nLTerm = 0;
   136145   pNew->u.vtab.needFree = 0;
   136146   nConstraint = p->nConstraint;
   136147   if( whereLoopResize(pParse->db, pNew, nConstraint) ){
   136148     sqlite3DbFree(pParse->db, p);
   136149     return SQLITE_NOMEM_BKPT;
   136150   }
   136151 
   136152   /* First call xBestIndex() with all constraints usable. */
   136153   WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
   136154   rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
   136155 
   136156   /* If the call to xBestIndex() with all terms enabled produced a plan
   136157   ** that does not require any source tables (IOW: a plan with mBest==0),
   136158   ** then there is no point in making any further calls to xBestIndex()
   136159   ** since they will all return the same result (if the xBestIndex()
   136160   ** implementation is sane). */
   136161   if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
   136162     int seenZero = 0;             /* True if a plan with no prereqs seen */
   136163     int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
   136164     Bitmask mPrev = 0;
   136165     Bitmask mBestNoIn = 0;
   136166 
   136167     /* If the plan produced by the earlier call uses an IN(...) term, call
   136168     ** xBestIndex again, this time with IN(...) terms disabled. */
   136169     if( bIn ){
   136170       WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
   136171       rc = whereLoopAddVirtualOne(
   136172           pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
   136173       assert( bIn==0 );
   136174       mBestNoIn = pNew->prereq & ~mPrereq;
   136175       if( mBestNoIn==0 ){
   136176         seenZero = 1;
   136177         seenZeroNoIN = 1;
   136178       }
   136179     }
   136180 
   136181     /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
   136182     ** in the set of terms that apply to the current virtual table.  */
   136183     while( rc==SQLITE_OK ){
   136184       int i;
   136185       Bitmask mNext = ALLBITS;
   136186       assert( mNext>0 );
   136187       for(i=0; i<nConstraint; i++){
   136188         Bitmask mThis = (
   136189             pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
   136190         );
   136191         if( mThis>mPrev && mThis<mNext ) mNext = mThis;
   136192       }
   136193       mPrev = mNext;
   136194       if( mNext==ALLBITS ) break;
   136195       if( mNext==mBest || mNext==mBestNoIn ) continue;
   136196       WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
   136197                        (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
   136198       rc = whereLoopAddVirtualOne(
   136199           pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
   136200       if( pNew->prereq==mPrereq ){
   136201         seenZero = 1;
   136202         if( bIn==0 ) seenZeroNoIN = 1;
   136203       }
   136204     }
   136205 
   136206     /* If the calls to xBestIndex() in the above loop did not find a plan
   136207     ** that requires no source tables at all (i.e. one guaranteed to be
   136208     ** usable), make a call here with all source tables disabled */
   136209     if( rc==SQLITE_OK && seenZero==0 ){
   136210       WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
   136211       rc = whereLoopAddVirtualOne(
   136212           pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
   136213       if( bIn==0 ) seenZeroNoIN = 1;
   136214     }
   136215 
   136216     /* If the calls to xBestIndex() have so far failed to find a plan
   136217     ** that requires no source tables at all and does not use an IN(...)
   136218     ** operator, make a final call to obtain one here.  */
   136219     if( rc==SQLITE_OK && seenZeroNoIN==0 ){
   136220       WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
   136221       rc = whereLoopAddVirtualOne(
   136222           pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
   136223     }
   136224   }
   136225 
   136226   if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
   136227   sqlite3DbFreeNN(pParse->db, p);
   136228   return rc;
   136229 }
   136230 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   136231 
   136232 /*
   136233 ** Add WhereLoop entries to handle OR terms.  This works for either
   136234 ** btrees or virtual tables.
   136235 */
   136236 static int whereLoopAddOr(
   136237   WhereLoopBuilder *pBuilder,
   136238   Bitmask mPrereq,
   136239   Bitmask mUnusable
   136240 ){
   136241   WhereInfo *pWInfo = pBuilder->pWInfo;
   136242   WhereClause *pWC;
   136243   WhereLoop *pNew;
   136244   WhereTerm *pTerm, *pWCEnd;
   136245   int rc = SQLITE_OK;
   136246   int iCur;
   136247   WhereClause tempWC;
   136248   WhereLoopBuilder sSubBuild;
   136249   WhereOrSet sSum, sCur;
   136250   struct SrcList_item *pItem;
   136251 
   136252   pWC = pBuilder->pWC;
   136253   pWCEnd = pWC->a + pWC->nTerm;
   136254   pNew = pBuilder->pNew;
   136255   memset(&sSum, 0, sizeof(sSum));
   136256   pItem = pWInfo->pTabList->a + pNew->iTab;
   136257   iCur = pItem->iCursor;
   136258 
   136259   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
   136260     if( (pTerm->eOperator & WO_OR)!=0
   136261      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
   136262     ){
   136263       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
   136264       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
   136265       WhereTerm *pOrTerm;
   136266       int once = 1;
   136267       int i, j;
   136268 
   136269       sSubBuild = *pBuilder;
   136270       sSubBuild.pOrderBy = 0;
   136271       sSubBuild.pOrSet = &sCur;
   136272 
   136273       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
   136274       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
   136275         if( (pOrTerm->eOperator & WO_AND)!=0 ){
   136276           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
   136277         }else if( pOrTerm->leftCursor==iCur ){
   136278           tempWC.pWInfo = pWC->pWInfo;
   136279           tempWC.pOuter = pWC;
   136280           tempWC.op = TK_AND;
   136281           tempWC.nTerm = 1;
   136282           tempWC.a = pOrTerm;
   136283           sSubBuild.pWC = &tempWC;
   136284         }else{
   136285           continue;
   136286         }
   136287         sCur.n = 0;
   136288 #ifdef WHERETRACE_ENABLED
   136289         WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
   136290                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
   136291         if( sqlite3WhereTrace & 0x400 ){
   136292           sqlite3WhereClausePrint(sSubBuild.pWC);
   136293         }
   136294 #endif
   136295 #ifndef SQLITE_OMIT_VIRTUALTABLE
   136296         if( IsVirtual(pItem->pTab) ){
   136297           rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
   136298         }else
   136299 #endif
   136300         {
   136301           rc = whereLoopAddBtree(&sSubBuild, mPrereq);
   136302         }
   136303         if( rc==SQLITE_OK ){
   136304           rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
   136305         }
   136306         assert( rc==SQLITE_OK || sCur.n==0 );
   136307         if( sCur.n==0 ){
   136308           sSum.n = 0;
   136309           break;
   136310         }else if( once ){
   136311           whereOrMove(&sSum, &sCur);
   136312           once = 0;
   136313         }else{
   136314           WhereOrSet sPrev;
   136315           whereOrMove(&sPrev, &sSum);
   136316           sSum.n = 0;
   136317           for(i=0; i<sPrev.n; i++){
   136318             for(j=0; j<sCur.n; j++){
   136319               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
   136320                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
   136321                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
   136322             }
   136323           }
   136324         }
   136325       }
   136326       pNew->nLTerm = 1;
   136327       pNew->aLTerm[0] = pTerm;
   136328       pNew->wsFlags = WHERE_MULTI_OR;
   136329       pNew->rSetup = 0;
   136330       pNew->iSortIdx = 0;
   136331       memset(&pNew->u, 0, sizeof(pNew->u));
   136332       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
   136333         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
   136334         ** of all sub-scans required by the OR-scan. However, due to rounding
   136335         ** errors, it may be that the cost of the OR-scan is equal to its
   136336         ** most expensive sub-scan. Add the smallest possible penalty
   136337         ** (equivalent to multiplying the cost by 1.07) to ensure that
   136338         ** this does not happen. Otherwise, for WHERE clauses such as the
   136339         ** following where there is an index on "y":
   136340         **
   136341         **     WHERE likelihood(x=?, 0.99) OR y=?
   136342         **
   136343         ** the planner may elect to "OR" together a full-table scan and an
   136344         ** index lookup. And other similarly odd results.  */
   136345         pNew->rRun = sSum.a[i].rRun + 1;
   136346         pNew->nOut = sSum.a[i].nOut;
   136347         pNew->prereq = sSum.a[i].prereq;
   136348         rc = whereLoopInsert(pBuilder, pNew);
   136349       }
   136350       WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
   136351     }
   136352   }
   136353   return rc;
   136354 }
   136355 
   136356 /*
   136357 ** Add all WhereLoop objects for all tables
   136358 */
   136359 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
   136360   WhereInfo *pWInfo = pBuilder->pWInfo;
   136361   Bitmask mPrereq = 0;
   136362   Bitmask mPrior = 0;
   136363   int iTab;
   136364   SrcList *pTabList = pWInfo->pTabList;
   136365   struct SrcList_item *pItem;
   136366   struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
   136367   sqlite3 *db = pWInfo->pParse->db;
   136368   int rc = SQLITE_OK;
   136369   WhereLoop *pNew;
   136370   u8 priorJointype = 0;
   136371 
   136372   /* Loop over the tables in the join, from left to right */
   136373   pNew = pBuilder->pNew;
   136374   whereLoopInit(pNew);
   136375   for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
   136376     Bitmask mUnusable = 0;
   136377     pNew->iTab = iTab;
   136378     pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
   136379     if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
   136380       /* This condition is true when pItem is the FROM clause term on the
   136381       ** right-hand-side of a LEFT or CROSS JOIN.  */
   136382       mPrereq = mPrior;
   136383     }
   136384     priorJointype = pItem->fg.jointype;
   136385 #ifndef SQLITE_OMIT_VIRTUALTABLE
   136386     if( IsVirtual(pItem->pTab) ){
   136387       struct SrcList_item *p;
   136388       for(p=&pItem[1]; p<pEnd; p++){
   136389         if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
   136390           mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
   136391         }
   136392       }
   136393       rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
   136394     }else
   136395 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   136396     {
   136397       rc = whereLoopAddBtree(pBuilder, mPrereq);
   136398     }
   136399     if( rc==SQLITE_OK ){
   136400       rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
   136401     }
   136402     mPrior |= pNew->maskSelf;
   136403     if( rc || db->mallocFailed ) break;
   136404   }
   136405 
   136406   whereLoopClear(db, pNew);
   136407   return rc;
   136408 }
   136409 
   136410 /*
   136411 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
   136412 ** parameters) to see if it outputs rows in the requested ORDER BY
   136413 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
   136414 **
   136415 **   N>0:   N terms of the ORDER BY clause are satisfied
   136416 **   N==0:  No terms of the ORDER BY clause are satisfied
   136417 **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
   136418 **
   136419 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
   136420 ** strict.  With GROUP BY and DISTINCT the only requirement is that
   136421 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
   136422 ** and DISTINCT do not require rows to appear in any particular order as long
   136423 ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
   136424 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
   136425 ** pOrderBy terms must be matched in strict left-to-right order.
   136426 */
   136427 static i8 wherePathSatisfiesOrderBy(
   136428   WhereInfo *pWInfo,    /* The WHERE clause */
   136429   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
   136430   WherePath *pPath,     /* The WherePath to check */
   136431   u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
   136432   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
   136433   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
   136434   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
   136435 ){
   136436   u8 revSet;            /* True if rev is known */
   136437   u8 rev;               /* Composite sort order */
   136438   u8 revIdx;            /* Index sort order */
   136439   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
   136440   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
   136441   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
   136442   u16 eqOpMask;         /* Allowed equality operators */
   136443   u16 nKeyCol;          /* Number of key columns in pIndex */
   136444   u16 nColumn;          /* Total number of ordered columns in the index */
   136445   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
   136446   int iLoop;            /* Index of WhereLoop in pPath being processed */
   136447   int i, j;             /* Loop counters */
   136448   int iCur;             /* Cursor number for current WhereLoop */
   136449   int iColumn;          /* A column number within table iCur */
   136450   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
   136451   WhereTerm *pTerm;     /* A single term of the WHERE clause */
   136452   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
   136453   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
   136454   Index *pIndex;        /* The index associated with pLoop */
   136455   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
   136456   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
   136457   Bitmask obDone;       /* Mask of all ORDER BY terms */
   136458   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
   136459   Bitmask ready;              /* Mask of inner loops */
   136460 
   136461   /*
   136462   ** We say the WhereLoop is "one-row" if it generates no more than one
   136463   ** row of output.  A WhereLoop is one-row if all of the following are true:
   136464   **  (a) All index columns match with WHERE_COLUMN_EQ.
   136465   **  (b) The index is unique
   136466   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
   136467   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
   136468   **
   136469   ** We say the WhereLoop is "order-distinct" if the set of columns from
   136470   ** that WhereLoop that are in the ORDER BY clause are different for every
   136471   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
   136472   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
   136473   ** is not order-distinct. To be order-distinct is not quite the same as being
   136474   ** UNIQUE since a UNIQUE column or index can have multiple rows that
   136475   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
   136476   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
   136477   **
   136478   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
   136479   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
   136480   ** automatically order-distinct.
   136481   */
   136482 
   136483   assert( pOrderBy!=0 );
   136484   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
   136485 
   136486   nOrderBy = pOrderBy->nExpr;
   136487   testcase( nOrderBy==BMS-1 );
   136488   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
   136489   isOrderDistinct = 1;
   136490   obDone = MASKBIT(nOrderBy)-1;
   136491   orderDistinctMask = 0;
   136492   ready = 0;
   136493   eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
   136494   if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
   136495   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
   136496     if( iLoop>0 ) ready |= pLoop->maskSelf;
   136497     if( iLoop<nLoop ){
   136498       pLoop = pPath->aLoop[iLoop];
   136499       if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
   136500     }else{
   136501       pLoop = pLast;
   136502     }
   136503     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
   136504       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
   136505       break;
   136506     }else{
   136507       pLoop->u.btree.nIdxCol = 0;
   136508     }
   136509     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
   136510 
   136511     /* Mark off any ORDER BY term X that is a column in the table of
   136512     ** the current loop for which there is term in the WHERE
   136513     ** clause of the form X IS NULL or X=? that reference only outer
   136514     ** loops.
   136515     */
   136516     for(i=0; i<nOrderBy; i++){
   136517       if( MASKBIT(i) & obSat ) continue;
   136518       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
   136519       if( pOBExpr->op!=TK_COLUMN ) continue;
   136520       if( pOBExpr->iTable!=iCur ) continue;
   136521       pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
   136522                        ~ready, eqOpMask, 0);
   136523       if( pTerm==0 ) continue;
   136524       if( pTerm->eOperator==WO_IN ){
   136525         /* IN terms are only valid for sorting in the ORDER BY LIMIT
   136526         ** optimization, and then only if they are actually used
   136527         ** by the query plan */
   136528         assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
   136529         for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
   136530         if( j>=pLoop->nLTerm ) continue;
   136531       }
   136532       if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
   136533         if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
   136534                   pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
   136535           continue;
   136536         }
   136537         testcase( pTerm->pExpr->op==TK_IS );
   136538       }
   136539       obSat |= MASKBIT(i);
   136540     }
   136541 
   136542     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
   136543       if( pLoop->wsFlags & WHERE_IPK ){
   136544         pIndex = 0;
   136545         nKeyCol = 0;
   136546         nColumn = 1;
   136547       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
   136548         return 0;
   136549       }else{
   136550         nKeyCol = pIndex->nKeyCol;
   136551         nColumn = pIndex->nColumn;
   136552         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
   136553         assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
   136554                           || !HasRowid(pIndex->pTable));
   136555         isOrderDistinct = IsUniqueIndex(pIndex);
   136556       }
   136557 
   136558       /* Loop through all columns of the index and deal with the ones
   136559       ** that are not constrained by == or IN.
   136560       */
   136561       rev = revSet = 0;
   136562       distinctColumns = 0;
   136563       for(j=0; j<nColumn; j++){
   136564         u8 bOnce = 1; /* True to run the ORDER BY search loop */
   136565 
   136566         assert( j>=pLoop->u.btree.nEq
   136567             || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
   136568         );
   136569         if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
   136570           u16 eOp = pLoop->aLTerm[j]->eOperator;
   136571 
   136572           /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when
   136573           ** doing WHERE_ORDERBY_LIMIT processing).
   136574           **
   136575           ** If the current term is a column of an ((?,?) IN (SELECT...))
   136576           ** expression for which the SELECT returns more than one column,
   136577           ** check that it is the only column used by this loop. Otherwise,
   136578           ** if it is one of two or more, none of the columns can be
   136579           ** considered to match an ORDER BY term.  */
   136580           if( (eOp & eqOpMask)!=0 ){
   136581             if( eOp & WO_ISNULL ){
   136582               testcase( isOrderDistinct );
   136583               isOrderDistinct = 0;
   136584             }
   136585             continue;
   136586           }else if( ALWAYS(eOp & WO_IN) ){
   136587             /* ALWAYS() justification: eOp is an equality operator due to the
   136588             ** j<pLoop->u.btree.nEq constraint above.  Any equality other
   136589             ** than WO_IN is captured by the previous "if".  So this one
   136590             ** always has to be WO_IN. */
   136591             Expr *pX = pLoop->aLTerm[j]->pExpr;
   136592             for(i=j+1; i<pLoop->u.btree.nEq; i++){
   136593               if( pLoop->aLTerm[i]->pExpr==pX ){
   136594                 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
   136595                 bOnce = 0;
   136596                 break;
   136597               }
   136598             }
   136599           }
   136600         }
   136601 
   136602         /* Get the column number in the table (iColumn) and sort order
   136603         ** (revIdx) for the j-th column of the index.
   136604         */
   136605         if( pIndex ){
   136606           iColumn = pIndex->aiColumn[j];
   136607           revIdx = pIndex->aSortOrder[j];
   136608           if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
   136609         }else{
   136610           iColumn = XN_ROWID;
   136611           revIdx = 0;
   136612         }
   136613 
   136614         /* An unconstrained column that might be NULL means that this
   136615         ** WhereLoop is not well-ordered
   136616         */
   136617         if( isOrderDistinct
   136618          && iColumn>=0
   136619          && j>=pLoop->u.btree.nEq
   136620          && pIndex->pTable->aCol[iColumn].notNull==0
   136621         ){
   136622           isOrderDistinct = 0;
   136623         }
   136624 
   136625         /* Find the ORDER BY term that corresponds to the j-th column
   136626         ** of the index and mark that ORDER BY term off
   136627         */
   136628         isMatch = 0;
   136629         for(i=0; bOnce && i<nOrderBy; i++){
   136630           if( MASKBIT(i) & obSat ) continue;
   136631           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
   136632           testcase( wctrlFlags & WHERE_GROUPBY );
   136633           testcase( wctrlFlags & WHERE_DISTINCTBY );
   136634           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
   136635           if( iColumn>=XN_ROWID ){
   136636             if( pOBExpr->op!=TK_COLUMN ) continue;
   136637             if( pOBExpr->iTable!=iCur ) continue;
   136638             if( pOBExpr->iColumn!=iColumn ) continue;
   136639           }else{
   136640             Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
   136641             if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
   136642               continue;
   136643             }
   136644           }
   136645           if( iColumn!=XN_ROWID ){
   136646             pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
   136647             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
   136648           }
   136649           pLoop->u.btree.nIdxCol = j+1;
   136650           isMatch = 1;
   136651           break;
   136652         }
   136653         if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
   136654           /* Make sure the sort order is compatible in an ORDER BY clause.
   136655           ** Sort order is irrelevant for a GROUP BY clause. */
   136656           if( revSet ){
   136657             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
   136658           }else{
   136659             rev = revIdx ^ pOrderBy->a[i].sortOrder;
   136660             if( rev ) *pRevMask |= MASKBIT(iLoop);
   136661             revSet = 1;
   136662           }
   136663         }
   136664         if( isMatch ){
   136665           if( iColumn==XN_ROWID ){
   136666             testcase( distinctColumns==0 );
   136667             distinctColumns = 1;
   136668           }
   136669           obSat |= MASKBIT(i);
   136670         }else{
   136671           /* No match found */
   136672           if( j==0 || j<nKeyCol ){
   136673             testcase( isOrderDistinct!=0 );
   136674             isOrderDistinct = 0;
   136675           }
   136676           break;
   136677         }
   136678       } /* end Loop over all index columns */
   136679       if( distinctColumns ){
   136680         testcase( isOrderDistinct==0 );
   136681         isOrderDistinct = 1;
   136682       }
   136683     } /* end-if not one-row */
   136684 
   136685     /* Mark off any other ORDER BY terms that reference pLoop */
   136686     if( isOrderDistinct ){
   136687       orderDistinctMask |= pLoop->maskSelf;
   136688       for(i=0; i<nOrderBy; i++){
   136689         Expr *p;
   136690         Bitmask mTerm;
   136691         if( MASKBIT(i) & obSat ) continue;
   136692         p = pOrderBy->a[i].pExpr;
   136693         mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
   136694         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
   136695         if( (mTerm&~orderDistinctMask)==0 ){
   136696           obSat |= MASKBIT(i);
   136697         }
   136698       }
   136699     }
   136700   } /* End the loop over all WhereLoops from outer-most down to inner-most */
   136701   if( obSat==obDone ) return (i8)nOrderBy;
   136702   if( !isOrderDistinct ){
   136703     for(i=nOrderBy-1; i>0; i--){
   136704       Bitmask m = MASKBIT(i) - 1;
   136705       if( (obSat&m)==m ) return i;
   136706     }
   136707     return 0;
   136708   }
   136709   return -1;
   136710 }
   136711 
   136712 
   136713 /*
   136714 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
   136715 ** the planner assumes that the specified pOrderBy list is actually a GROUP
   136716 ** BY clause - and so any order that groups rows as required satisfies the
   136717 ** request.
   136718 **
   136719 ** Normally, in this case it is not possible for the caller to determine
   136720 ** whether or not the rows are really being delivered in sorted order, or
   136721 ** just in some other order that provides the required grouping. However,
   136722 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
   136723 ** this function may be called on the returned WhereInfo object. It returns
   136724 ** true if the rows really will be sorted in the specified order, or false
   136725 ** otherwise.
   136726 **
   136727 ** For example, assuming:
   136728 **
   136729 **   CREATE INDEX i1 ON t1(x, Y);
   136730 **
   136731 ** then
   136732 **
   136733 **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
   136734 **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
   136735 */
   136736 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
   136737   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
   136738   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
   136739   return pWInfo->sorted;
   136740 }
   136741 
   136742 #ifdef WHERETRACE_ENABLED
   136743 /* For debugging use only: */
   136744 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
   136745   static char zName[65];
   136746   int i;
   136747   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
   136748   if( pLast ) zName[i++] = pLast->cId;
   136749   zName[i] = 0;
   136750   return zName;
   136751 }
   136752 #endif
   136753 
   136754 /*
   136755 ** Return the cost of sorting nRow rows, assuming that the keys have
   136756 ** nOrderby columns and that the first nSorted columns are already in
   136757 ** order.
   136758 */
   136759 static LogEst whereSortingCost(
   136760   WhereInfo *pWInfo,
   136761   LogEst nRow,
   136762   int nOrderBy,
   136763   int nSorted
   136764 ){
   136765   /* TUNING: Estimated cost of a full external sort, where N is
   136766   ** the number of rows to sort is:
   136767   **
   136768   **   cost = (3.0 * N * log(N)).
   136769   **
   136770   ** Or, if the order-by clause has X terms but only the last Y
   136771   ** terms are out of order, then block-sorting will reduce the
   136772   ** sorting cost to:
   136773   **
   136774   **   cost = (3.0 * N * log(N)) * (Y/X)
   136775   **
   136776   ** The (Y/X) term is implemented using stack variable rScale
   136777   ** below.  */
   136778   LogEst rScale, rSortCost;
   136779   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
   136780   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
   136781   rSortCost = nRow + rScale + 16;
   136782 
   136783   /* Multiple by log(M) where M is the number of output rows.
   136784   ** Use the LIMIT for M if it is smaller */
   136785   if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
   136786     nRow = pWInfo->iLimit;
   136787   }
   136788   rSortCost += estLog(nRow);
   136789   return rSortCost;
   136790 }
   136791 
   136792 /*
   136793 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
   136794 ** attempts to find the lowest cost path that visits each WhereLoop
   136795 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
   136796 **
   136797 ** Assume that the total number of output rows that will need to be sorted
   136798 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
   136799 ** costs if nRowEst==0.
   136800 **
   136801 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
   136802 ** error occurs.
   136803 */
   136804 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
   136805   int mxChoice;             /* Maximum number of simultaneous paths tracked */
   136806   int nLoop;                /* Number of terms in the join */
   136807   Parse *pParse;            /* Parsing context */
   136808   sqlite3 *db;              /* The database connection */
   136809   int iLoop;                /* Loop counter over the terms of the join */
   136810   int ii, jj;               /* Loop counters */
   136811   int mxI = 0;              /* Index of next entry to replace */
   136812   int nOrderBy;             /* Number of ORDER BY clause terms */
   136813   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
   136814   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
   136815   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
   136816   WherePath *aFrom;         /* All nFrom paths at the previous level */
   136817   WherePath *aTo;           /* The nTo best paths at the current level */
   136818   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
   136819   WherePath *pTo;           /* An element of aTo[] that we are working on */
   136820   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
   136821   WhereLoop **pX;           /* Used to divy up the pSpace memory */
   136822   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
   136823   char *pSpace;             /* Temporary memory used by this routine */
   136824   int nSpace;               /* Bytes of space allocated at pSpace */
   136825 
   136826   pParse = pWInfo->pParse;
   136827   db = pParse->db;
   136828   nLoop = pWInfo->nLevel;
   136829   /* TUNING: For simple queries, only the best path is tracked.
   136830   ** For 2-way joins, the 5 best paths are followed.
   136831   ** For joins of 3 or more tables, track the 10 best paths */
   136832   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
   136833   assert( nLoop<=pWInfo->pTabList->nSrc );
   136834   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
   136835 
   136836   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
   136837   ** case the purpose of this call is to estimate the number of rows returned
   136838   ** by the overall query. Once this estimate has been obtained, the caller
   136839   ** will invoke this function a second time, passing the estimate as the
   136840   ** nRowEst parameter.  */
   136841   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
   136842     nOrderBy = 0;
   136843   }else{
   136844     nOrderBy = pWInfo->pOrderBy->nExpr;
   136845   }
   136846 
   136847   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
   136848   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
   136849   nSpace += sizeof(LogEst) * nOrderBy;
   136850   pSpace = sqlite3DbMallocRawNN(db, nSpace);
   136851   if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
   136852   aTo = (WherePath*)pSpace;
   136853   aFrom = aTo+mxChoice;
   136854   memset(aFrom, 0, sizeof(aFrom[0]));
   136855   pX = (WhereLoop**)(aFrom+mxChoice);
   136856   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
   136857     pFrom->aLoop = pX;
   136858   }
   136859   if( nOrderBy ){
   136860     /* If there is an ORDER BY clause and it is not being ignored, set up
   136861     ** space for the aSortCost[] array. Each element of the aSortCost array
   136862     ** is either zero - meaning it has not yet been initialized - or the
   136863     ** cost of sorting nRowEst rows of data where the first X terms of
   136864     ** the ORDER BY clause are already in order, where X is the array
   136865     ** index.  */
   136866     aSortCost = (LogEst*)pX;
   136867     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
   136868   }
   136869   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
   136870   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
   136871 
   136872   /* Seed the search with a single WherePath containing zero WhereLoops.
   136873   **
   136874   ** TUNING: Do not let the number of iterations go above 28.  If the cost
   136875   ** of computing an automatic index is not paid back within the first 28
   136876   ** rows, then do not use the automatic index. */
   136877   aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
   136878   nFrom = 1;
   136879   assert( aFrom[0].isOrdered==0 );
   136880   if( nOrderBy ){
   136881     /* If nLoop is zero, then there are no FROM terms in the query. Since
   136882     ** in this case the query may return a maximum of one row, the results
   136883     ** are already in the requested order. Set isOrdered to nOrderBy to
   136884     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
   136885     ** -1, indicating that the result set may or may not be ordered,
   136886     ** depending on the loops added to the current plan.  */
   136887     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
   136888   }
   136889 
   136890   /* Compute successively longer WherePaths using the previous generation
   136891   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
   136892   ** best paths at each generation */
   136893   for(iLoop=0; iLoop<nLoop; iLoop++){
   136894     nTo = 0;
   136895     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
   136896       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
   136897         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
   136898         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
   136899         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
   136900         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
   136901         Bitmask maskNew;                  /* Mask of src visited by (..) */
   136902         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
   136903 
   136904         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
   136905         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
   136906         if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
   136907           /* Do not use an automatic index if the this loop is expected
   136908           ** to run less than 2 times. */
   136909           assert( 10==sqlite3LogEst(2) );
   136910           continue;
   136911         }
   136912         /* At this point, pWLoop is a candidate to be the next loop.
   136913         ** Compute its cost */
   136914         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
   136915         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
   136916         nOut = pFrom->nRow + pWLoop->nOut;
   136917         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
   136918         if( isOrdered<0 ){
   136919           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
   136920                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
   136921                        iLoop, pWLoop, &revMask);
   136922         }else{
   136923           revMask = pFrom->revLoop;
   136924         }
   136925         if( isOrdered>=0 && isOrdered<nOrderBy ){
   136926           if( aSortCost[isOrdered]==0 ){
   136927             aSortCost[isOrdered] = whereSortingCost(
   136928                 pWInfo, nRowEst, nOrderBy, isOrdered
   136929             );
   136930           }
   136931           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
   136932 
   136933           WHERETRACE(0x002,
   136934               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
   136935                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
   136936                rUnsorted, rCost));
   136937         }else{
   136938           rCost = rUnsorted;
   136939           rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */
   136940         }
   136941 
   136942         /* Check to see if pWLoop should be added to the set of
   136943         ** mxChoice best-so-far paths.
   136944         **
   136945         ** First look for an existing path among best-so-far paths
   136946         ** that covers the same set of loops and has the same isOrdered
   136947         ** setting as the current path candidate.
   136948         **
   136949         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
   136950         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
   136951         ** of legal values for isOrdered, -1..64.
   136952         */
   136953         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
   136954           if( pTo->maskLoop==maskNew
   136955            && ((pTo->isOrdered^isOrdered)&0x80)==0
   136956           ){
   136957             testcase( jj==nTo-1 );
   136958             break;
   136959           }
   136960         }
   136961         if( jj>=nTo ){
   136962           /* None of the existing best-so-far paths match the candidate. */
   136963           if( nTo>=mxChoice
   136964            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
   136965           ){
   136966             /* The current candidate is no better than any of the mxChoice
   136967             ** paths currently in the best-so-far buffer.  So discard
   136968             ** this candidate as not viable. */
   136969 #ifdef WHERETRACE_ENABLED /* 0x4 */
   136970             if( sqlite3WhereTrace&0x4 ){
   136971               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d,%3d order=%c\n",
   136972                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
   136973                   isOrdered>=0 ? isOrdered+'0' : '?');
   136974             }
   136975 #endif
   136976             continue;
   136977           }
   136978           /* If we reach this points it means that the new candidate path
   136979           ** needs to be added to the set of best-so-far paths. */
   136980           if( nTo<mxChoice ){
   136981             /* Increase the size of the aTo set by one */
   136982             jj = nTo++;
   136983           }else{
   136984             /* New path replaces the prior worst to keep count below mxChoice */
   136985             jj = mxI;
   136986           }
   136987           pTo = &aTo[jj];
   136988 #ifdef WHERETRACE_ENABLED /* 0x4 */
   136989           if( sqlite3WhereTrace&0x4 ){
   136990             sqlite3DebugPrintf("New    %s cost=%-3d,%3d,%3d order=%c\n",
   136991                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
   136992                 isOrdered>=0 ? isOrdered+'0' : '?');
   136993           }
   136994 #endif
   136995         }else{
   136996           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
   136997           ** same set of loops and has the same isOrdered setting as the
   136998           ** candidate path.  Check to see if the candidate should replace
   136999           ** pTo or if the candidate should be skipped.
   137000           **
   137001           ** The conditional is an expanded vector comparison equivalent to:
   137002           **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
   137003           */
   137004           if( pTo->rCost<rCost
   137005            || (pTo->rCost==rCost
   137006                && (pTo->nRow<nOut
   137007                    || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
   137008                   )
   137009               )
   137010           ){
   137011 #ifdef WHERETRACE_ENABLED /* 0x4 */
   137012             if( sqlite3WhereTrace&0x4 ){
   137013               sqlite3DebugPrintf(
   137014                   "Skip   %s cost=%-3d,%3d,%3d order=%c",
   137015                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
   137016                   isOrdered>=0 ? isOrdered+'0' : '?');
   137017               sqlite3DebugPrintf("   vs %s cost=%-3d,%3d,%3d order=%c\n",
   137018                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   137019                   pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
   137020             }
   137021 #endif
   137022             /* Discard the candidate path from further consideration */
   137023             testcase( pTo->rCost==rCost );
   137024             continue;
   137025           }
   137026           testcase( pTo->rCost==rCost+1 );
   137027           /* Control reaches here if the candidate path is better than the
   137028           ** pTo path.  Replace pTo with the candidate. */
   137029 #ifdef WHERETRACE_ENABLED /* 0x4 */
   137030           if( sqlite3WhereTrace&0x4 ){
   137031             sqlite3DebugPrintf(
   137032                 "Update %s cost=%-3d,%3d,%3d order=%c",
   137033                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
   137034                 isOrdered>=0 ? isOrdered+'0' : '?');
   137035             sqlite3DebugPrintf("  was %s cost=%-3d,%3d,%3d order=%c\n",
   137036                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   137037                 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
   137038           }
   137039 #endif
   137040         }
   137041         /* pWLoop is a winner.  Add it to the set of best so far */
   137042         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
   137043         pTo->revLoop = revMask;
   137044         pTo->nRow = nOut;
   137045         pTo->rCost = rCost;
   137046         pTo->rUnsorted = rUnsorted;
   137047         pTo->isOrdered = isOrdered;
   137048         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
   137049         pTo->aLoop[iLoop] = pWLoop;
   137050         if( nTo>=mxChoice ){
   137051           mxI = 0;
   137052           mxCost = aTo[0].rCost;
   137053           mxUnsorted = aTo[0].nRow;
   137054           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
   137055             if( pTo->rCost>mxCost
   137056              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
   137057             ){
   137058               mxCost = pTo->rCost;
   137059               mxUnsorted = pTo->rUnsorted;
   137060               mxI = jj;
   137061             }
   137062           }
   137063         }
   137064       }
   137065     }
   137066 
   137067 #ifdef WHERETRACE_ENABLED  /* >=2 */
   137068     if( sqlite3WhereTrace & 0x02 ){
   137069       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
   137070       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
   137071         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
   137072            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
   137073            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
   137074         if( pTo->isOrdered>0 ){
   137075           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
   137076         }else{
   137077           sqlite3DebugPrintf("\n");
   137078         }
   137079       }
   137080     }
   137081 #endif
   137082 
   137083     /* Swap the roles of aFrom and aTo for the next generation */
   137084     pFrom = aTo;
   137085     aTo = aFrom;
   137086     aFrom = pFrom;
   137087     nFrom = nTo;
   137088   }
   137089 
   137090   if( nFrom==0 ){
   137091     sqlite3ErrorMsg(pParse, "no query solution");
   137092     sqlite3DbFreeNN(db, pSpace);
   137093     return SQLITE_ERROR;
   137094   }
   137095 
   137096   /* Find the lowest cost path.  pFrom will be left pointing to that path */
   137097   pFrom = aFrom;
   137098   for(ii=1; ii<nFrom; ii++){
   137099     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
   137100   }
   137101   assert( pWInfo->nLevel==nLoop );
   137102   /* Load the lowest cost path into pWInfo */
   137103   for(iLoop=0; iLoop<nLoop; iLoop++){
   137104     WhereLevel *pLevel = pWInfo->a + iLoop;
   137105     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
   137106     pLevel->iFrom = pWLoop->iTab;
   137107     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
   137108   }
   137109   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
   137110    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
   137111    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
   137112    && nRowEst
   137113   ){
   137114     Bitmask notUsed;
   137115     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
   137116                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
   137117     if( rc==pWInfo->pResultSet->nExpr ){
   137118       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   137119     }
   137120   }
   137121   if( pWInfo->pOrderBy ){
   137122     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
   137123       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
   137124         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   137125       }
   137126     }else{
   137127       pWInfo->nOBSat = pFrom->isOrdered;
   137128       pWInfo->revMask = pFrom->revLoop;
   137129       if( pWInfo->nOBSat<=0 ){
   137130         pWInfo->nOBSat = 0;
   137131         if( nLoop>0 ){
   137132           u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
   137133           if( (wsFlags & WHERE_ONEROW)==0
   137134            && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
   137135           ){
   137136             Bitmask m = 0;
   137137             int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
   137138                       WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
   137139             testcase( wsFlags & WHERE_IPK );
   137140             testcase( wsFlags & WHERE_COLUMN_IN );
   137141             if( rc==pWInfo->pOrderBy->nExpr ){
   137142               pWInfo->bOrderedInnerLoop = 1;
   137143               pWInfo->revMask = m;
   137144             }
   137145           }
   137146         }
   137147       }
   137148     }
   137149     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
   137150         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
   137151     ){
   137152       Bitmask revMask = 0;
   137153       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
   137154           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
   137155       );
   137156       assert( pWInfo->sorted==0 );
   137157       if( nOrder==pWInfo->pOrderBy->nExpr ){
   137158         pWInfo->sorted = 1;
   137159         pWInfo->revMask = revMask;
   137160       }
   137161     }
   137162   }
   137163 
   137164 
   137165   pWInfo->nRowOut = pFrom->nRow;
   137166 
   137167   /* Free temporary memory and return success */
   137168   sqlite3DbFreeNN(db, pSpace);
   137169   return SQLITE_OK;
   137170 }
   137171 
   137172 /*
   137173 ** Most queries use only a single table (they are not joins) and have
   137174 ** simple == constraints against indexed fields.  This routine attempts
   137175 ** to plan those simple cases using much less ceremony than the
   137176 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
   137177 ** times for the common case.
   137178 **
   137179 ** Return non-zero on success, if this query can be handled by this
   137180 ** no-frills query planner.  Return zero if this query needs the
   137181 ** general-purpose query planner.
   137182 */
   137183 static int whereShortCut(WhereLoopBuilder *pBuilder){
   137184   WhereInfo *pWInfo;
   137185   struct SrcList_item *pItem;
   137186   WhereClause *pWC;
   137187   WhereTerm *pTerm;
   137188   WhereLoop *pLoop;
   137189   int iCur;
   137190   int j;
   137191   Table *pTab;
   137192   Index *pIdx;
   137193 
   137194   pWInfo = pBuilder->pWInfo;
   137195   if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
   137196   assert( pWInfo->pTabList->nSrc>=1 );
   137197   pItem = pWInfo->pTabList->a;
   137198   pTab = pItem->pTab;
   137199   if( IsVirtual(pTab) ) return 0;
   137200   if( pItem->fg.isIndexedBy ) return 0;
   137201   iCur = pItem->iCursor;
   137202   pWC = &pWInfo->sWC;
   137203   pLoop = pBuilder->pNew;
   137204   pLoop->wsFlags = 0;
   137205   pLoop->nSkip = 0;
   137206   pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
   137207   if( pTerm ){
   137208     testcase( pTerm->eOperator & WO_IS );
   137209     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
   137210     pLoop->aLTerm[0] = pTerm;
   137211     pLoop->nLTerm = 1;
   137212     pLoop->u.btree.nEq = 1;
   137213     /* TUNING: Cost of a rowid lookup is 10 */
   137214     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
   137215   }else{
   137216     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   137217       int opMask;
   137218       assert( pLoop->aLTermSpace==pLoop->aLTerm );
   137219       if( !IsUniqueIndex(pIdx)
   137220        || pIdx->pPartIdxWhere!=0
   137221        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
   137222       ) continue;
   137223       opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
   137224       for(j=0; j<pIdx->nKeyCol; j++){
   137225         pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
   137226         if( pTerm==0 ) break;
   137227         testcase( pTerm->eOperator & WO_IS );
   137228         pLoop->aLTerm[j] = pTerm;
   137229       }
   137230       if( j!=pIdx->nKeyCol ) continue;
   137231       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
   137232       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
   137233         pLoop->wsFlags |= WHERE_IDX_ONLY;
   137234       }
   137235       pLoop->nLTerm = j;
   137236       pLoop->u.btree.nEq = j;
   137237       pLoop->u.btree.pIndex = pIdx;
   137238       /* TUNING: Cost of a unique index lookup is 15 */
   137239       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
   137240       break;
   137241     }
   137242   }
   137243   if( pLoop->wsFlags ){
   137244     pLoop->nOut = (LogEst)1;
   137245     pWInfo->a[0].pWLoop = pLoop;
   137246     assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
   137247     pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
   137248     pWInfo->a[0].iTabCur = iCur;
   137249     pWInfo->nRowOut = 1;
   137250     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
   137251     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
   137252       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   137253     }
   137254 #ifdef SQLITE_DEBUG
   137255     pLoop->cId = '0';
   137256 #endif
   137257     return 1;
   137258   }
   137259   return 0;
   137260 }
   137261 
   137262 /*
   137263 ** Helper function for exprIsDeterministic().
   137264 */
   137265 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
   137266   if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
   137267     pWalker->eCode = 0;
   137268     return WRC_Abort;
   137269   }
   137270   return WRC_Continue;
   137271 }
   137272 
   137273 /*
   137274 ** Return true if the expression contains no non-deterministic SQL
   137275 ** functions. Do not consider non-deterministic SQL functions that are
   137276 ** part of sub-select statements.
   137277 */
   137278 static int exprIsDeterministic(Expr *p){
   137279   Walker w;
   137280   memset(&w, 0, sizeof(w));
   137281   w.eCode = 1;
   137282   w.xExprCallback = exprNodeIsDeterministic;
   137283   w.xSelectCallback = sqlite3SelectWalkFail;
   137284   sqlite3WalkExpr(&w, p);
   137285   return w.eCode;
   137286 }
   137287 
   137288 /*
   137289 ** Generate the beginning of the loop used for WHERE clause processing.
   137290 ** The return value is a pointer to an opaque structure that contains
   137291 ** information needed to terminate the loop.  Later, the calling routine
   137292 ** should invoke sqlite3WhereEnd() with the return value of this function
   137293 ** in order to complete the WHERE clause processing.
   137294 **
   137295 ** If an error occurs, this routine returns NULL.
   137296 **
   137297 ** The basic idea is to do a nested loop, one loop for each table in
   137298 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
   137299 ** same as a SELECT with only a single table in the FROM clause.)  For
   137300 ** example, if the SQL is this:
   137301 **
   137302 **       SELECT * FROM t1, t2, t3 WHERE ...;
   137303 **
   137304 ** Then the code generated is conceptually like the following:
   137305 **
   137306 **      foreach row1 in t1 do       \    Code generated
   137307 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
   137308 **          foreach row3 in t3 do   /
   137309 **            ...
   137310 **          end                     \    Code generated
   137311 **        end                        |-- by sqlite3WhereEnd()
   137312 **      end                         /
   137313 **
   137314 ** Note that the loops might not be nested in the order in which they
   137315 ** appear in the FROM clause if a different order is better able to make
   137316 ** use of indices.  Note also that when the IN operator appears in
   137317 ** the WHERE clause, it might result in additional nested loops for
   137318 ** scanning through all values on the right-hand side of the IN.
   137319 **
   137320 ** There are Btree cursors associated with each table.  t1 uses cursor
   137321 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
   137322 ** And so forth.  This routine generates code to open those VDBE cursors
   137323 ** and sqlite3WhereEnd() generates the code to close them.
   137324 **
   137325 ** The code that sqlite3WhereBegin() generates leaves the cursors named
   137326 ** in pTabList pointing at their appropriate entries.  The [...] code
   137327 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
   137328 ** data from the various tables of the loop.
   137329 **
   137330 ** If the WHERE clause is empty, the foreach loops must each scan their
   137331 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
   137332 ** the tables have indices and there are terms in the WHERE clause that
   137333 ** refer to those indices, a complete table scan can be avoided and the
   137334 ** code will run much faster.  Most of the work of this routine is checking
   137335 ** to see if there are indices that can be used to speed up the loop.
   137336 **
   137337 ** Terms of the WHERE clause are also used to limit which rows actually
   137338 ** make it to the "..." in the middle of the loop.  After each "foreach",
   137339 ** terms of the WHERE clause that use only terms in that loop and outer
   137340 ** loops are evaluated and if false a jump is made around all subsequent
   137341 ** inner loops (or around the "..." if the test occurs within the inner-
   137342 ** most loop)
   137343 **
   137344 ** OUTER JOINS
   137345 **
   137346 ** An outer join of tables t1 and t2 is conceptally coded as follows:
   137347 **
   137348 **    foreach row1 in t1 do
   137349 **      flag = 0
   137350 **      foreach row2 in t2 do
   137351 **        start:
   137352 **          ...
   137353 **          flag = 1
   137354 **      end
   137355 **      if flag==0 then
   137356 **        move the row2 cursor to a null row
   137357 **        goto start
   137358 **      fi
   137359 **    end
   137360 **
   137361 ** ORDER BY CLAUSE PROCESSING
   137362 **
   137363 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
   137364 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
   137365 ** if there is one.  If there is no ORDER BY clause or if this routine
   137366 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
   137367 **
   137368 ** The iIdxCur parameter is the cursor number of an index.  If
   137369 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
   137370 ** to use for OR clause processing.  The WHERE clause should use this
   137371 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
   137372 ** the first cursor in an array of cursors for all indices.  iIdxCur should
   137373 ** be used to compute the appropriate cursor depending on which index is
   137374 ** used.
   137375 */
   137376 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   137377   Parse *pParse,          /* The parser context */
   137378   SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
   137379   Expr *pWhere,           /* The WHERE clause */
   137380   ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
   137381   ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
   137382   u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
   137383   int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
   137384                           ** If WHERE_USE_LIMIT, then the limit amount */
   137385 ){
   137386   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
   137387   int nTabList;              /* Number of elements in pTabList */
   137388   WhereInfo *pWInfo;         /* Will become the return value of this function */
   137389   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
   137390   Bitmask notReady;          /* Cursors that are not yet positioned */
   137391   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
   137392   WhereMaskSet *pMaskSet;    /* The expression mask set */
   137393   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
   137394   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
   137395   int ii;                    /* Loop counter */
   137396   sqlite3 *db;               /* Database connection */
   137397   int rc;                    /* Return code */
   137398   u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
   137399 
   137400   assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
   137401         (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
   137402      && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
   137403   ));
   137404 
   137405   /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
   137406   assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
   137407             || (wctrlFlags & WHERE_USE_LIMIT)==0 );
   137408 
   137409   /* Variable initialization */
   137410   db = pParse->db;
   137411   memset(&sWLB, 0, sizeof(sWLB));
   137412 
   137413   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
   137414   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
   137415   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
   137416   sWLB.pOrderBy = pOrderBy;
   137417 
   137418   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
   137419   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
   137420   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
   137421     wctrlFlags &= ~WHERE_WANT_DISTINCT;
   137422   }
   137423 
   137424   /* The number of tables in the FROM clause is limited by the number of
   137425   ** bits in a Bitmask
   137426   */
   137427   testcase( pTabList->nSrc==BMS );
   137428   if( pTabList->nSrc>BMS ){
   137429     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
   137430     return 0;
   137431   }
   137432 
   137433   /* This function normally generates a nested loop for all tables in
   137434   ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
   137435   ** only generate code for the first table in pTabList and assume that
   137436   ** any cursors associated with subsequent tables are uninitialized.
   137437   */
   137438   nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
   137439 
   137440   /* Allocate and initialize the WhereInfo structure that will become the
   137441   ** return value. A single allocation is used to store the WhereInfo
   137442   ** struct, the contents of WhereInfo.a[], the WhereClause structure
   137443   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
   137444   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
   137445   ** some architectures. Hence the ROUND8() below.
   137446   */
   137447   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
   137448   pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
   137449   if( db->mallocFailed ){
   137450     sqlite3DbFree(db, pWInfo);
   137451     pWInfo = 0;
   137452     goto whereBeginError;
   137453   }
   137454   pWInfo->pParse = pParse;
   137455   pWInfo->pTabList = pTabList;
   137456   pWInfo->pOrderBy = pOrderBy;
   137457   pWInfo->pWhere = pWhere;
   137458   pWInfo->pResultSet = pResultSet;
   137459   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
   137460   pWInfo->nLevel = nTabList;
   137461   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
   137462   pWInfo->wctrlFlags = wctrlFlags;
   137463   pWInfo->iLimit = iAuxArg;
   137464   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
   137465   memset(&pWInfo->nOBSat, 0,
   137466          offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
   137467   memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
   137468   assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
   137469   pMaskSet = &pWInfo->sMaskSet;
   137470   sWLB.pWInfo = pWInfo;
   137471   sWLB.pWC = &pWInfo->sWC;
   137472   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
   137473   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
   137474   whereLoopInit(sWLB.pNew);
   137475 #ifdef SQLITE_DEBUG
   137476   sWLB.pNew->cId = '*';
   137477 #endif
   137478 
   137479   /* Split the WHERE clause into separate subexpressions where each
   137480   ** subexpression is separated by an AND operator.
   137481   */
   137482   initMaskSet(pMaskSet);
   137483   sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
   137484   sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
   137485 
   137486   /* Special case: No FROM clause
   137487   */
   137488   if( nTabList==0 ){
   137489     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
   137490     if( wctrlFlags & WHERE_WANT_DISTINCT ){
   137491       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   137492     }
   137493   }else{
   137494     /* Assign a bit from the bitmask to every term in the FROM clause.
   137495     **
   137496     ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
   137497     **
   137498     ** The rule of the previous sentence ensures thta if X is the bitmask for
   137499     ** a table T, then X-1 is the bitmask for all other tables to the left of T.
   137500     ** Knowing the bitmask for all tables to the left of a left join is
   137501     ** important.  Ticket #3015.
   137502     **
   137503     ** Note that bitmasks are created for all pTabList->nSrc tables in
   137504     ** pTabList, not just the first nTabList tables.  nTabList is normally
   137505     ** equal to pTabList->nSrc but might be shortened to 1 if the
   137506     ** WHERE_OR_SUBCLAUSE flag is set.
   137507     */
   137508     ii = 0;
   137509     do{
   137510       createMask(pMaskSet, pTabList->a[ii].iCursor);
   137511       sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
   137512     }while( (++ii)<pTabList->nSrc );
   137513   #ifdef SQLITE_DEBUG
   137514     {
   137515       Bitmask mx = 0;
   137516       for(ii=0; ii<pTabList->nSrc; ii++){
   137517         Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
   137518         assert( m>=mx );
   137519         mx = m;
   137520       }
   137521     }
   137522   #endif
   137523   }
   137524 
   137525   /* Analyze all of the subexpressions. */
   137526   sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
   137527   if( db->mallocFailed ) goto whereBeginError;
   137528 
   137529   /* Special case: WHERE terms that do not refer to any tables in the join
   137530   ** (constant expressions). Evaluate each such term, and jump over all the
   137531   ** generated code if the result is not true.
   137532   **
   137533   ** Do not do this if the expression contains non-deterministic functions
   137534   ** that are not within a sub-select. This is not strictly required, but
   137535   ** preserves SQLite's legacy behaviour in the following two cases:
   137536   **
   137537   **   FROM ... WHERE random()>0;           -- eval random() once per row
   137538   **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall
   137539   */
   137540   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
   137541     WhereTerm *pT = &sWLB.pWC->a[ii];
   137542     if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
   137543       sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
   137544       pT->wtFlags |= TERM_CODED;
   137545     }
   137546   }
   137547 
   137548   if( wctrlFlags & WHERE_WANT_DISTINCT ){
   137549     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
   137550       /* The DISTINCT marking is pointless.  Ignore it. */
   137551       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   137552     }else if( pOrderBy==0 ){
   137553       /* Try to ORDER BY the result set to make distinct processing easier */
   137554       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
   137555       pWInfo->pOrderBy = pResultSet;
   137556     }
   137557   }
   137558 
   137559   /* Construct the WhereLoop objects */
   137560 #if defined(WHERETRACE_ENABLED)
   137561   if( sqlite3WhereTrace & 0xffff ){
   137562     sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
   137563     if( wctrlFlags & WHERE_USE_LIMIT ){
   137564       sqlite3DebugPrintf(", limit: %d", iAuxArg);
   137565     }
   137566     sqlite3DebugPrintf(")\n");
   137567   }
   137568   if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
   137569     sqlite3WhereClausePrint(sWLB.pWC);
   137570   }
   137571 #endif
   137572 
   137573   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
   137574     rc = whereLoopAddAll(&sWLB);
   137575     if( rc ) goto whereBeginError;
   137576 
   137577 #ifdef WHERETRACE_ENABLED
   137578     if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
   137579       WhereLoop *p;
   137580       int i;
   137581       static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
   137582                                              "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
   137583       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
   137584         p->cId = zLabel[i%(sizeof(zLabel)-1)];
   137585         whereLoopPrint(p, sWLB.pWC);
   137586       }
   137587     }
   137588 #endif
   137589 
   137590     wherePathSolver(pWInfo, 0);
   137591     if( db->mallocFailed ) goto whereBeginError;
   137592     if( pWInfo->pOrderBy ){
   137593        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
   137594        if( db->mallocFailed ) goto whereBeginError;
   137595     }
   137596   }
   137597   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
   137598      pWInfo->revMask = ALLBITS;
   137599   }
   137600   if( pParse->nErr || NEVER(db->mallocFailed) ){
   137601     goto whereBeginError;
   137602   }
   137603 #ifdef WHERETRACE_ENABLED
   137604   if( sqlite3WhereTrace ){
   137605     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
   137606     if( pWInfo->nOBSat>0 ){
   137607       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
   137608     }
   137609     switch( pWInfo->eDistinct ){
   137610       case WHERE_DISTINCT_UNIQUE: {
   137611         sqlite3DebugPrintf("  DISTINCT=unique");
   137612         break;
   137613       }
   137614       case WHERE_DISTINCT_ORDERED: {
   137615         sqlite3DebugPrintf("  DISTINCT=ordered");
   137616         break;
   137617       }
   137618       case WHERE_DISTINCT_UNORDERED: {
   137619         sqlite3DebugPrintf("  DISTINCT=unordered");
   137620         break;
   137621       }
   137622     }
   137623     sqlite3DebugPrintf("\n");
   137624     for(ii=0; ii<pWInfo->nLevel; ii++){
   137625       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
   137626     }
   137627   }
   137628 #endif
   137629 
   137630   /* Attempt to omit tables from the join that do not affect the result.
   137631   ** For a table to not affect the result, the following must be true:
   137632   **
   137633   **   1) The query must not be an aggregate.
   137634   **   2) The table must be the RHS of a LEFT JOIN.
   137635   **   3) Either the query must be DISTINCT, or else the ON or USING clause
   137636   **      must contain a constraint that limits the scan of the table to
   137637   **      at most a single row.
   137638   **   4) The table must not be referenced by any part of the query apart
   137639   **      from its own USING or ON clause.
   137640   **
   137641   ** For example, given:
   137642   **
   137643   **     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
   137644   **     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
   137645   **     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
   137646   **
   137647   ** then table t2 can be omitted from the following:
   137648   **
   137649   **     SELECT v1, v3 FROM t1
   137650   **       LEFT JOIN t2 USING (t1.ipk=t2.ipk)
   137651   **       LEFT JOIN t3 USING (t1.ipk=t3.ipk)
   137652   **
   137653   ** or from:
   137654   **
   137655   **     SELECT DISTINCT v1, v3 FROM t1
   137656   **       LEFT JOIN t2
   137657   **       LEFT JOIN t3 USING (t1.ipk=t3.ipk)
   137658   */
   137659   notReady = ~(Bitmask)0;
   137660   if( pWInfo->nLevel>=2
   137661    && pResultSet!=0               /* guarantees condition (1) above */
   137662    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
   137663   ){
   137664     int i;
   137665     Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
   137666     if( sWLB.pOrderBy ){
   137667       tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
   137668     }
   137669     for(i=pWInfo->nLevel-1; i>=1; i--){
   137670       WhereTerm *pTerm, *pEnd;
   137671       struct SrcList_item *pItem;
   137672       pLoop = pWInfo->a[i].pWLoop;
   137673       pItem = &pWInfo->pTabList->a[pLoop->iTab];
   137674       if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
   137675       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
   137676        && (pLoop->wsFlags & WHERE_ONEROW)==0
   137677       ){
   137678         continue;
   137679       }
   137680       if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
   137681       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
   137682       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
   137683         if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
   137684           if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
   137685            || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
   137686           ){
   137687             break;
   137688           }
   137689         }
   137690       }
   137691       if( pTerm<pEnd ) continue;
   137692       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
   137693       notReady &= ~pLoop->maskSelf;
   137694       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
   137695         if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
   137696           pTerm->wtFlags |= TERM_CODED;
   137697         }
   137698       }
   137699       if( i!=pWInfo->nLevel-1 ){
   137700         int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
   137701         memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
   137702       }
   137703       pWInfo->nLevel--;
   137704       nTabList--;
   137705     }
   137706   }
   137707   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
   137708   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
   137709 
   137710   /* If the caller is an UPDATE or DELETE statement that is requesting
   137711   ** to use a one-pass algorithm, determine if this is appropriate.
   137712   **
   137713   ** A one-pass approach can be used if the caller has requested one
   137714   ** and either (a) the scan visits at most one row or (b) each
   137715   ** of the following are true:
   137716   **
   137717   **   * the caller has indicated that a one-pass approach can be used
   137718   **     with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
   137719   **   * the table is not a virtual table, and
   137720   **   * either the scan does not use the OR optimization or the caller
   137721   **     is a DELETE operation (WHERE_DUPLICATES_OK is only specified
   137722   **     for DELETE).
   137723   **
   137724   ** The last qualification is because an UPDATE statement uses
   137725   ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
   137726   ** use a one-pass approach, and this is not set accurately for scans
   137727   ** that use the OR optimization.
   137728   */
   137729   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
   137730   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
   137731     int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
   137732     int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
   137733     if( bOnerow || (
   137734         0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
   137735      && 0==(wsFlags & WHERE_VIRTUALTABLE)
   137736      && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
   137737     )){
   137738       pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
   137739       if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
   137740         if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
   137741           bFordelete = OPFLAG_FORDELETE;
   137742         }
   137743         pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
   137744       }
   137745     }
   137746   }
   137747 
   137748   /* Open all tables in the pTabList and any indices selected for
   137749   ** searching those tables.
   137750   */
   137751   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
   137752     Table *pTab;     /* Table to open */
   137753     int iDb;         /* Index of database containing table/index */
   137754     struct SrcList_item *pTabItem;
   137755 
   137756     pTabItem = &pTabList->a[pLevel->iFrom];
   137757     pTab = pTabItem->pTab;
   137758     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   137759     pLoop = pLevel->pWLoop;
   137760     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
   137761       /* Do nothing */
   137762     }else
   137763 #ifndef SQLITE_OMIT_VIRTUALTABLE
   137764     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   137765       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   137766       int iCur = pTabItem->iCursor;
   137767       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
   137768     }else if( IsVirtual(pTab) ){
   137769       /* noop */
   137770     }else
   137771 #endif
   137772     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
   137773          && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
   137774       int op = OP_OpenRead;
   137775       if( pWInfo->eOnePass!=ONEPASS_OFF ){
   137776         op = OP_OpenWrite;
   137777         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
   137778       };
   137779       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
   137780       assert( pTabItem->iCursor==pLevel->iTabCur );
   137781       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
   137782       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
   137783       if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
   137784         Bitmask b = pTabItem->colUsed;
   137785         int n = 0;
   137786         for(; b; b=b>>1, n++){}
   137787         sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
   137788         assert( n<=pTab->nCol );
   137789       }
   137790 #ifdef SQLITE_ENABLE_CURSOR_HINTS
   137791       if( pLoop->u.btree.pIndex!=0 ){
   137792         sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
   137793       }else
   137794 #endif
   137795       {
   137796         sqlite3VdbeChangeP5(v, bFordelete);
   137797       }
   137798 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
   137799       sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
   137800                             (const u8*)&pTabItem->colUsed, P4_INT64);
   137801 #endif
   137802     }else{
   137803       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   137804     }
   137805     if( pLoop->wsFlags & WHERE_INDEXED ){
   137806       Index *pIx = pLoop->u.btree.pIndex;
   137807       int iIndexCur;
   137808       int op = OP_OpenRead;
   137809       /* iAuxArg is always set to a positive value if ONEPASS is possible */
   137810       assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
   137811       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
   137812        && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
   137813       ){
   137814         /* This is one term of an OR-optimization using the PRIMARY KEY of a
   137815         ** WITHOUT ROWID table.  No need for a separate index */
   137816         iIndexCur = pLevel->iTabCur;
   137817         op = 0;
   137818       }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
   137819         Index *pJ = pTabItem->pTab->pIndex;
   137820         iIndexCur = iAuxArg;
   137821         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
   137822         while( ALWAYS(pJ) && pJ!=pIx ){
   137823           iIndexCur++;
   137824           pJ = pJ->pNext;
   137825         }
   137826         op = OP_OpenWrite;
   137827         pWInfo->aiCurOnePass[1] = iIndexCur;
   137828       }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
   137829         iIndexCur = iAuxArg;
   137830         op = OP_ReopenIdx;
   137831       }else{
   137832         iIndexCur = pParse->nTab++;
   137833       }
   137834       pLevel->iIdxCur = iIndexCur;
   137835       assert( pIx->pSchema==pTab->pSchema );
   137836       assert( iIndexCur>=0 );
   137837       if( op ){
   137838         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
   137839         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
   137840         if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
   137841          && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
   137842          && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
   137843          && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
   137844         ){
   137845           sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
   137846         }
   137847         VdbeComment((v, "%s", pIx->zName));
   137848 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
   137849         {
   137850           u64 colUsed = 0;
   137851           int ii, jj;
   137852           for(ii=0; ii<pIx->nColumn; ii++){
   137853             jj = pIx->aiColumn[ii];
   137854             if( jj<0 ) continue;
   137855             if( jj>63 ) jj = 63;
   137856             if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
   137857             colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
   137858           }
   137859           sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
   137860                                 (u8*)&colUsed, P4_INT64);
   137861         }
   137862 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
   137863       }
   137864     }
   137865     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
   137866   }
   137867   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
   137868   if( db->mallocFailed ) goto whereBeginError;
   137869 
   137870   /* Generate the code to do the search.  Each iteration of the for
   137871   ** loop below generates code for a single nested loop of the VM
   137872   ** program.
   137873   */
   137874   for(ii=0; ii<nTabList; ii++){
   137875     int addrExplain;
   137876     int wsFlags;
   137877     pLevel = &pWInfo->a[ii];
   137878     wsFlags = pLevel->pWLoop->wsFlags;
   137879 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   137880     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
   137881       constructAutomaticIndex(pParse, &pWInfo->sWC,
   137882                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
   137883       if( db->mallocFailed ) goto whereBeginError;
   137884     }
   137885 #endif
   137886     addrExplain = sqlite3WhereExplainOneScan(
   137887         pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
   137888     );
   137889     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
   137890     notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
   137891     pWInfo->iContinue = pLevel->addrCont;
   137892     if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
   137893       sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
   137894     }
   137895   }
   137896 
   137897   /* Done. */
   137898   VdbeModuleComment((v, "Begin WHERE-core"));
   137899   return pWInfo;
   137900 
   137901   /* Jump here if malloc fails */
   137902 whereBeginError:
   137903   if( pWInfo ){
   137904     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   137905     whereInfoFree(db, pWInfo);
   137906   }
   137907   return 0;
   137908 }
   137909 
   137910 /*
   137911 ** Generate the end of the WHERE loop.  See comments on
   137912 ** sqlite3WhereBegin() for additional information.
   137913 */
   137914 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   137915   Parse *pParse = pWInfo->pParse;
   137916   Vdbe *v = pParse->pVdbe;
   137917   int i;
   137918   WhereLevel *pLevel;
   137919   WhereLoop *pLoop;
   137920   SrcList *pTabList = pWInfo->pTabList;
   137921   sqlite3 *db = pParse->db;
   137922 
   137923   /* Generate loop termination code.
   137924   */
   137925   VdbeModuleComment((v, "End WHERE-core"));
   137926   sqlite3ExprCacheClear(pParse);
   137927   for(i=pWInfo->nLevel-1; i>=0; i--){
   137928     int addr;
   137929     pLevel = &pWInfo->a[i];
   137930     pLoop = pLevel->pWLoop;
   137931     if( pLevel->op!=OP_Noop ){
   137932 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
   137933       int addrSeek = 0;
   137934       Index *pIdx;
   137935       int n;
   137936       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
   137937        && i==pWInfo->nLevel-1  /* Ticket [ef9318757b152e3] 2017-10-21 */
   137938        && (pLoop->wsFlags & WHERE_INDEXED)!=0
   137939        && (pIdx = pLoop->u.btree.pIndex)->hasStat1
   137940        && (n = pLoop->u.btree.nIdxCol)>0
   137941        && pIdx->aiRowLogEst[n]>=36
   137942       ){
   137943         int r1 = pParse->nMem+1;
   137944         int j, op;
   137945         for(j=0; j<n; j++){
   137946           sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
   137947         }
   137948         pParse->nMem += n+1;
   137949         op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
   137950         addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
   137951         VdbeCoverageIf(v, op==OP_SeekLT);
   137952         VdbeCoverageIf(v, op==OP_SeekGT);
   137953         sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
   137954       }
   137955 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
   137956       /* The common case: Advance to the next row */
   137957       sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   137958       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
   137959       sqlite3VdbeChangeP5(v, pLevel->p5);
   137960       VdbeCoverage(v);
   137961       VdbeCoverageIf(v, pLevel->op==OP_Next);
   137962       VdbeCoverageIf(v, pLevel->op==OP_Prev);
   137963       VdbeCoverageIf(v, pLevel->op==OP_VNext);
   137964 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
   137965       if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
   137966 #endif
   137967     }else{
   137968       sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   137969     }
   137970     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
   137971       struct InLoop *pIn;
   137972       int j;
   137973       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
   137974       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
   137975         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
   137976         if( pIn->eEndLoopOp!=OP_Noop ){
   137977           sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
   137978           VdbeCoverage(v);
   137979           VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
   137980           VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
   137981         }
   137982         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
   137983       }
   137984     }
   137985     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
   137986     if( pLevel->addrSkip ){
   137987       sqlite3VdbeGoto(v, pLevel->addrSkip);
   137988       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
   137989       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
   137990       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
   137991     }
   137992 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   137993     if( pLevel->addrLikeRep ){
   137994       sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
   137995                         pLevel->addrLikeRep);
   137996       VdbeCoverage(v);
   137997     }
   137998 #endif
   137999     if( pLevel->iLeftJoin ){
   138000       int ws = pLoop->wsFlags;
   138001       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
   138002       assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
   138003       if( (ws & WHERE_IDX_ONLY)==0 ){
   138004         assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
   138005         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
   138006       }
   138007       if( (ws & WHERE_INDEXED)
   138008        || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
   138009       ){
   138010         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
   138011       }
   138012       if( pLevel->op==OP_Return ){
   138013         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
   138014       }else{
   138015         sqlite3VdbeGoto(v, pLevel->addrFirst);
   138016       }
   138017       sqlite3VdbeJumpHere(v, addr);
   138018     }
   138019     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
   138020                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
   138021   }
   138022 
   138023   /* The "break" point is here, just past the end of the outer loop.
   138024   ** Set it.
   138025   */
   138026   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
   138027 
   138028   assert( pWInfo->nLevel<=pTabList->nSrc );
   138029   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
   138030     int k, last;
   138031     VdbeOp *pOp;
   138032     Index *pIdx = 0;
   138033     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
   138034     Table *pTab = pTabItem->pTab;
   138035     assert( pTab!=0 );
   138036     pLoop = pLevel->pWLoop;
   138037 
   138038     /* For a co-routine, change all OP_Column references to the table of
   138039     ** the co-routine into OP_Copy of result contained in a register.
   138040     ** OP_Rowid becomes OP_Null.
   138041     */
   138042     if( pTabItem->fg.viaCoroutine ){
   138043       testcase( pParse->db->mallocFailed );
   138044       translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
   138045                             pTabItem->regResult, 0);
   138046       continue;
   138047     }
   138048 
   138049     /* If this scan uses an index, make VDBE code substitutions to read data
   138050     ** from the index instead of from the table where possible.  In some cases
   138051     ** this optimization prevents the table from ever being read, which can
   138052     ** yield a significant performance boost.
   138053     **
   138054     ** Calls to the code generator in between sqlite3WhereBegin and
   138055     ** sqlite3WhereEnd will have created code that references the table
   138056     ** directly.  This loop scans all that code looking for opcodes
   138057     ** that reference the table and converts them into opcodes that
   138058     ** reference the index.
   138059     */
   138060     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
   138061       pIdx = pLoop->u.btree.pIndex;
   138062     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
   138063       pIdx = pLevel->u.pCovidx;
   138064     }
   138065     if( pIdx
   138066      && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
   138067      && !db->mallocFailed
   138068     ){
   138069       last = sqlite3VdbeCurrentAddr(v);
   138070       k = pLevel->addrBody;
   138071       pOp = sqlite3VdbeGetOp(v, k);
   138072       for(; k<last; k++, pOp++){
   138073         if( pOp->p1!=pLevel->iTabCur ) continue;
   138074         if( pOp->opcode==OP_Column
   138075 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
   138076          || pOp->opcode==OP_Offset
   138077 #endif
   138078         ){
   138079           int x = pOp->p2;
   138080           assert( pIdx->pTable==pTab );
   138081           if( !HasRowid(pTab) ){
   138082             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
   138083             x = pPk->aiColumn[x];
   138084             assert( x>=0 );
   138085           }
   138086           x = sqlite3ColumnOfIndex(pIdx, x);
   138087           if( x>=0 ){
   138088             pOp->p2 = x;
   138089             pOp->p1 = pLevel->iIdxCur;
   138090           }
   138091           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
   138092               || pWInfo->eOnePass );
   138093         }else if( pOp->opcode==OP_Rowid ){
   138094           pOp->p1 = pLevel->iIdxCur;
   138095           pOp->opcode = OP_IdxRowid;
   138096         }else if( pOp->opcode==OP_IfNullRow ){
   138097           pOp->p1 = pLevel->iIdxCur;
   138098         }
   138099       }
   138100     }
   138101   }
   138102 
   138103   /* Final cleanup
   138104   */
   138105   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   138106   whereInfoFree(db, pWInfo);
   138107   return;
   138108 }
   138109 
   138110 /************** End of where.c ***********************************************/
   138111 /************** Begin file parse.c *******************************************/
   138112 /*
   138113 ** 2000-05-29
   138114 **
   138115 ** The author disclaims copyright to this source code.  In place of
   138116 ** a legal notice, here is a blessing:
   138117 **
   138118 **    May you do good and not evil.
   138119 **    May you find forgiveness for yourself and forgive others.
   138120 **    May you share freely, never taking more than you give.
   138121 **
   138122 *************************************************************************
   138123 ** Driver template for the LEMON parser generator.
   138124 **
   138125 ** The "lemon" program processes an LALR(1) input grammar file, then uses
   138126 ** this template to construct a parser.  The "lemon" program inserts text
   138127 ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
   138128 ** interstitial "-" characters) contained in this template is changed into
   138129 ** the value of the %name directive from the grammar.  Otherwise, the content
   138130 ** of this template is copied straight through into the generate parser
   138131 ** source file.
   138132 **
   138133 ** The following is the concatenation of all %include directives from the
   138134 ** input grammar file:
   138135 */
   138136 /* #include <stdio.h> */
   138137 /************ Begin %include sections from the grammar ************************/
   138138 
   138139 /* #include "sqliteInt.h" */
   138140 
   138141 /*
   138142 ** Disable all error recovery processing in the parser push-down
   138143 ** automaton.
   138144 */
   138145 #define YYNOERRORRECOVERY 1
   138146 
   138147 /*
   138148 ** Make yytestcase() the same as testcase()
   138149 */
   138150 #define yytestcase(X) testcase(X)
   138151 
   138152 /*
   138153 ** Indicate that sqlite3ParserFree() will never be called with a null
   138154 ** pointer.
   138155 */
   138156 #define YYPARSEFREENEVERNULL 1
   138157 
   138158 /*
   138159 ** In the amalgamation, the parse.c file generated by lemon and the
   138160 ** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
   138161 ** has access to the the size of the yyParser object and so the parser
   138162 ** engine can be allocated from stack.  In that case, only the
   138163 ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
   138164 ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
   138165 ** omitted.
   138166 */
   138167 #ifdef SQLITE_AMALGAMATION
   138168 # define sqlite3Parser_ENGINEALWAYSONSTACK 1
   138169 #endif
   138170 
   138171 /*
   138172 ** Alternative datatype for the argument to the malloc() routine passed
   138173 ** into sqlite3ParserAlloc().  The default is size_t.
   138174 */
   138175 #define YYMALLOCARGTYPE  u64
   138176 
   138177 /*
   138178 ** An instance of the following structure describes the event of a
   138179 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
   138180 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
   138181 **
   138182 **      UPDATE ON (a,b,c)
   138183 **
   138184 ** Then the "b" IdList records the list "a,b,c".
   138185 */
   138186 struct TrigEvent { int a; IdList * b; };
   138187 
   138188 /*
   138189 ** Disable lookaside memory allocation for objects that might be
   138190 ** shared across database connections.
   138191 */
   138192 static void disableLookaside(Parse *pParse){
   138193   pParse->disableLookaside++;
   138194   pParse->db->lookaside.bDisable++;
   138195 }
   138196 
   138197 
   138198   /*
   138199   ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
   138200   ** all elements in the list.  And make sure list length does not exceed
   138201   ** SQLITE_LIMIT_COMPOUND_SELECT.
   138202   */
   138203   static void parserDoubleLinkSelect(Parse *pParse, Select *p){
   138204     if( p->pPrior ){
   138205       Select *pNext = 0, *pLoop;
   138206       int mxSelect, cnt = 0;
   138207       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
   138208         pLoop->pNext = pNext;
   138209         pLoop->selFlags |= SF_Compound;
   138210       }
   138211       if( (p->selFlags & SF_MultiValue)==0 &&
   138212         (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
   138213         cnt>mxSelect
   138214       ){
   138215         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
   138216       }
   138217     }
   138218   }
   138219 
   138220 
   138221   /* Construct a new Expr object from a single identifier.  Use the
   138222   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
   138223   ** that created the expression.
   138224   */
   138225   static Expr *tokenExpr(Parse *pParse, int op, Token t){
   138226     Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
   138227     if( p ){
   138228       memset(p, 0, sizeof(Expr));
   138229       p->op = (u8)op;
   138230       p->flags = EP_Leaf;
   138231       p->iAgg = -1;
   138232       p->u.zToken = (char*)&p[1];
   138233       memcpy(p->u.zToken, t.z, t.n);
   138234       p->u.zToken[t.n] = 0;
   138235       if( sqlite3Isquote(p->u.zToken[0]) ){
   138236         if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
   138237         sqlite3Dequote(p->u.zToken);
   138238       }
   138239 #if SQLITE_MAX_EXPR_DEPTH>0
   138240       p->nHeight = 1;
   138241 #endif
   138242     }
   138243     return p;
   138244   }
   138245 
   138246   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
   138247   ** unary TK_ISNULL or TK_NOTNULL expression. */
   138248   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
   138249     sqlite3 *db = pParse->db;
   138250     if( pA && pY && pY->op==TK_NULL ){
   138251       pA->op = (u8)op;
   138252       sqlite3ExprDelete(db, pA->pRight);
   138253       pA->pRight = 0;
   138254     }
   138255   }
   138256 
   138257   /* Add a single new term to an ExprList that is used to store a
   138258   ** list of identifiers.  Report an error if the ID list contains
   138259   ** a COLLATE clause or an ASC or DESC keyword, except ignore the
   138260   ** error while parsing a legacy schema.
   138261   */
   138262   static ExprList *parserAddExprIdListTerm(
   138263     Parse *pParse,
   138264     ExprList *pPrior,
   138265     Token *pIdToken,
   138266     int hasCollate,
   138267     int sortOrder
   138268   ){
   138269     ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
   138270     if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
   138271         && pParse->db->init.busy==0
   138272     ){
   138273       sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
   138274                          pIdToken->n, pIdToken->z);
   138275     }
   138276     sqlite3ExprListSetName(pParse, p, pIdToken, 1);
   138277     return p;
   138278   }
   138279 /**************** End of %include directives **********************************/
   138280 /* These constants specify the various numeric values for terminal symbols
   138281 ** in a format understandable to "makeheaders".  This section is blank unless
   138282 ** "lemon" is run with the "-m" command-line option.
   138283 ***************** Begin makeheaders token definitions *************************/
   138284 /**************** End makeheaders token definitions ***************************/
   138285 
   138286 /* The next sections is a series of control #defines.
   138287 ** various aspects of the generated parser.
   138288 **    YYCODETYPE         is the data type used to store the integer codes
   138289 **                       that represent terminal and non-terminal symbols.
   138290 **                       "unsigned char" is used if there are fewer than
   138291 **                       256 symbols.  Larger types otherwise.
   138292 **    YYNOCODE           is a number of type YYCODETYPE that is not used for
   138293 **                       any terminal or nonterminal symbol.
   138294 **    YYFALLBACK         If defined, this indicates that one or more tokens
   138295 **                       (also known as: "terminal symbols") have fall-back
   138296 **                       values which should be used if the original symbol
   138297 **                       would not parse.  This permits keywords to sometimes
   138298 **                       be used as identifiers, for example.
   138299 **    YYACTIONTYPE       is the data type used for "action codes" - numbers
   138300 **                       that indicate what to do in response to the next
   138301 **                       token.
   138302 **    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
   138303 **                       symbols.  Background: A "minor type" is a semantic
   138304 **                       value associated with a terminal or non-terminal
   138305 **                       symbols.  For example, for an "ID" terminal symbol,
   138306 **                       the minor type might be the name of the identifier.
   138307 **                       Each non-terminal can have a different minor type.
   138308 **                       Terminal symbols all have the same minor type, though.
   138309 **                       This macros defines the minor type for terminal
   138310 **                       symbols.
   138311 **    YYMINORTYPE        is the data type used for all minor types.
   138312 **                       This is typically a union of many types, one of
   138313 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
   138314 **                       for terminal symbols is called "yy0".
   138315 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   138316 **                       zero the stack is dynamically sized using realloc()
   138317 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
   138318 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
   138319 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
   138320 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
   138321 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
   138322 **                       defined, then do no error processing.
   138323 **    YYNSTATE           the combined number of states.
   138324 **    YYNRULE            the number of rules in the grammar
   138325 **    YYNTOKEN           Number of terminal symbols
   138326 **    YY_MAX_SHIFT       Maximum value for shift actions
   138327 **    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
   138328 **    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
   138329 **    YY_ERROR_ACTION    The yy_action[] code for syntax error
   138330 **    YY_ACCEPT_ACTION   The yy_action[] code for accept
   138331 **    YY_NO_ACTION       The yy_action[] code for no-op
   138332 **    YY_MIN_REDUCE      Minimum value for reduce actions
   138333 **    YY_MAX_REDUCE      Maximum value for reduce actions
   138334 */
   138335 #ifndef INTERFACE
   138336 # define INTERFACE 1
   138337 #endif
   138338 /************* Begin control #defines *****************************************/
   138339 #define YYCODETYPE unsigned char
   138340 #define YYNOCODE 253
   138341 #define YYACTIONTYPE unsigned short int
   138342 #define YYWILDCARD 83
   138343 #define sqlite3ParserTOKENTYPE Token
   138344 typedef union {
   138345   int yyinit;
   138346   sqlite3ParserTOKENTYPE yy0;
   138347   int yy4;
   138348   struct TrigEvent yy90;
   138349   TriggerStep* yy203;
   138350   struct {int value; int mask;} yy215;
   138351   SrcList* yy259;
   138352   Expr* yy314;
   138353   ExprList* yy322;
   138354   const char* yy336;
   138355   IdList* yy384;
   138356   Select* yy387;
   138357   With* yy451;
   138358 } YYMINORTYPE;
   138359 #ifndef YYSTACKDEPTH
   138360 #define YYSTACKDEPTH 100
   138361 #endif
   138362 #define sqlite3ParserARG_SDECL Parse *pParse;
   138363 #define sqlite3ParserARG_PDECL ,Parse *pParse
   138364 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
   138365 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
   138366 #define YYFALLBACK 1
   138367 #define YYNSTATE             466
   138368 #define YYNRULE              330
   138369 #define YYNTOKEN             143
   138370 #define YY_MAX_SHIFT         465
   138371 #define YY_MIN_SHIFTREDUCE   675
   138372 #define YY_MAX_SHIFTREDUCE   1004
   138373 #define YY_ERROR_ACTION      1005
   138374 #define YY_ACCEPT_ACTION     1006
   138375 #define YY_NO_ACTION         1007
   138376 #define YY_MIN_REDUCE        1008
   138377 #define YY_MAX_REDUCE        1337
   138378 /************* End control #defines *******************************************/
   138379 
   138380 /* Define the yytestcase() macro to be a no-op if is not already defined
   138381 ** otherwise.
   138382 **
   138383 ** Applications can choose to define yytestcase() in the %include section
   138384 ** to a macro that can assist in verifying code coverage.  For production
   138385 ** code the yytestcase() macro should be turned off.  But it is useful
   138386 ** for testing.
   138387 */
   138388 #ifndef yytestcase
   138389 # define yytestcase(X)
   138390 #endif
   138391 
   138392 
   138393 /* Next are the tables used to determine what action to take based on the
   138394 ** current state and lookahead token.  These tables are used to implement
   138395 ** functions that take a state number and lookahead value and return an
   138396 ** action integer.
   138397 **
   138398 ** Suppose the action integer is N.  Then the action is determined as
   138399 ** follows
   138400 **
   138401 **   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
   138402 **                                      token onto the stack and goto state N.
   138403 **
   138404 **   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
   138405 **     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
   138406 **
   138407 **   N == YY_ERROR_ACTION               A syntax error has occurred.
   138408 **
   138409 **   N == YY_ACCEPT_ACTION              The parser accepts its input.
   138410 **
   138411 **   N == YY_NO_ACTION                  No such action.  Denotes unused
   138412 **                                      slots in the yy_action[] table.
   138413 **
   138414 **   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
   138415 **     and YY_MAX_REDUCE
   138416 **
   138417 ** The action table is constructed as a single large table named yy_action[].
   138418 ** Given state S and lookahead X, the action is computed as either:
   138419 **
   138420 **    (A)   N = yy_action[ yy_shift_ofst[S] + X ]
   138421 **    (B)   N = yy_default[S]
   138422 **
   138423 ** The (A) formula is preferred.  The B formula is used instead if
   138424 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
   138425 **
   138426 ** The formulas above are for computing the action when the lookahead is
   138427 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   138428 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   138429 ** the yy_shift_ofst[] array.
   138430 **
   138431 ** The following are the tables generated in this section:
   138432 **
   138433 **  yy_action[]        A single table containing all actions.
   138434 **  yy_lookahead[]     A table containing the lookahead for each entry in
   138435 **                     yy_action.  Used to detect hash collisions.
   138436 **  yy_shift_ofst[]    For each state, the offset into yy_action for
   138437 **                     shifting terminals.
   138438 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
   138439 **                     shifting non-terminals after a reduce.
   138440 **  yy_default[]       Default action for each state.
   138441 **
   138442 *********** Begin parsing tables **********************************************/
   138443 #define YY_ACTTAB_COUNT (1541)
   138444 static const YYACTIONTYPE yy_action[] = {
   138445  /*     0 */  1006,  156,  156,    2, 1302,   90,   87,  179,   90,   87,
   138446  /*    10 */   179,  460, 1048,  460,  465, 1010,  460,  333, 1130,  335,
   138447  /*    20 */   246,  330,  112,  303,  439, 1258,  304,  419, 1129, 1087,
   138448  /*    30 */    72,  798,   50,   50,   50,   50,  331,   30,   30,  799,
   138449  /*    40 */   951,  364,  371,   97,   98,   88,  983,  983,  859,  862,
   138450  /*    50 */   851,  851,   95,   95,   96,   96,   96,   96,  120,  371,
   138451  /*    60 */   370,  120,  348,   22,   90,   87,  179,  438,  423,  438,
   138452  /*    70 */   440,  335,  420,  385,   90,   87,  179,  116,   73,  163,
   138453  /*    80 */   848,  848,  860,  863,   94,   94,   94,   94,   93,   93,
   138454  /*    90 */    92,   92,   92,   91,  361,   97,   98,   88,  983,  983,
   138455  /*   100 */   859,  862,  851,  851,   95,   95,   96,   96,   96,   96,
   138456  /*   110 */   718,  365,  339,   93,   93,   92,   92,   92,   91,  361,
   138457  /*   120 */    99,  371,  453,  335,   94,   94,   94,   94,   93,   93,
   138458  /*   130 */    92,   92,   92,   91,  361,  852,   94,   94,   94,   94,
   138459  /*   140 */    93,   93,   92,   92,   92,   91,  361,   97,   98,   88,
   138460  /*   150 */   983,  983,  859,  862,  851,  851,   95,   95,   96,   96,
   138461  /*   160 */    96,   96,   92,   92,   92,   91,  361,  838,  132,  195,
   138462  /*   170 */    58,  244,  412,  409,  408,  335,  457,  457,  457,  304,
   138463  /*   180 */    59,  332,  831,  407,  394,  962,  830,  391,   94,   94,
   138464  /*   190 */    94,   94,   93,   93,   92,   92,   92,   91,  361,   97,
   138465  /*   200 */    98,   88,  983,  983,  859,  862,  851,  851,   95,   95,
   138466  /*   210 */    96,   96,   96,   96,  426,  357,  460,  830,  830,  832,
   138467  /*   220 */    91,  361,  962,  963,  964,  195,  459,  335,  412,  409,
   138468  /*   230 */   408,  280,  361,  820,  132,   11,   11,   50,   50,  407,
   138469  /*   240 */    94,   94,   94,   94,   93,   93,   92,   92,   92,   91,
   138470  /*   250 */   361,   97,   98,   88,  983,  983,  859,  862,  851,  851,
   138471  /*   260 */    95,   95,   96,   96,   96,   96,  460,  221,  460,  264,
   138472  /*   270 */   375,  254,  438,  428, 1276, 1276,  383, 1074, 1053,  335,
   138473  /*   280 */   245,  422,  299,  713,  271,  271, 1074,   50,   50,   50,
   138474  /*   290 */    50,  962,   94,   94,   94,   94,   93,   93,   92,   92,
   138475  /*   300 */    92,   91,  361,   97,   98,   88,  983,  983,  859,  862,
   138476  /*   310 */   851,  851,   95,   95,   96,   96,   96,   96,   90,   87,
   138477  /*   320 */   179, 1306,  438,  437,  438,  418,  368,  253,  962,  963,
   138478  /*   330 */   964,  335,  360,  360,  360,  706,  359,  358,  324,  962,
   138479  /*   340 */  1281,  951,  364,  230,   94,   94,   94,   94,   93,   93,
   138480  /*   350 */    92,   92,   92,   91,  361,   97,   98,   88,  983,  983,
   138481  /*   360 */   859,  862,  851,  851,   95,   95,   96,   96,   96,   96,
   138482  /*   370 */   769,  460,  120,  226,  226,  366,  962,  963,  964, 1089,
   138483  /*   380 */   990,  900,  990,  335, 1057,  425,  421,  839,  759,  759,
   138484  /*   390 */   425,  427,   50,   50,  432,  381,   94,   94,   94,   94,
   138485  /*   400 */    93,   93,   92,   92,   92,   91,  361,   97,   98,   88,
   138486  /*   410 */   983,  983,  859,  862,  851,  851,   95,   95,   96,   96,
   138487  /*   420 */    96,   96,  460,  259,  460,  120,  117,  354,  942, 1332,
   138488  /*   430 */   942, 1333, 1332,  278, 1333,  335,  680,  681,  682,  825,
   138489  /*   440 */   201,  176,  303,   50,   50,   49,   49,  404,   94,   94,
   138490  /*   450 */    94,   94,   93,   93,   92,   92,   92,   91,  361,   97,
   138491  /*   460 */    98,   88,  983,  983,  859,  862,  851,  851,   95,   95,
   138492  /*   470 */    96,   96,   96,   96,  199,  460,  380,  265,  433,  380,
   138493  /*   480 */   265,  383,  256,  158,  258,  319, 1003,  335,  155,  940,
   138494  /*   490 */   177,  940,  273,  379,  276,  322,   34,   34,  302,  962,
   138495  /*   500 */    94,   94,   94,   94,   93,   93,   92,   92,   92,   91,
   138496  /*   510 */   361,   97,   98,   88,  983,  983,  859,  862,  851,  851,
   138497  /*   520 */    95,   95,   96,   96,   96,   96,  905,  905,  397,  460,
   138498  /*   530 */   301,  158,  101,  319,  941,  340,  962,  963,  964,  313,
   138499  /*   540 */   283,  449,  335,  327,  146, 1266, 1004,  257,  234,  248,
   138500  /*   550 */    35,   35,   94,   94,   94,   94,   93,   93,   92,   92,
   138501  /*   560 */    92,   91,  361,  709,  785, 1227,   97,   98,   88,  983,
   138502  /*   570 */   983,  859,  862,  851,  851,   95,   95,   96,   96,   96,
   138503  /*   580 */    96,  962, 1227, 1229,  245,  422,  838,  198,  197,  196,
   138504  /*   590 */  1079, 1079, 1077, 1077, 1004, 1334,  320,  335,  172,  171,
   138505  /*   600 */   709,  831,  159,  271,  271,  830,   76,   94,   94,   94,
   138506  /*   610 */    94,   93,   93,   92,   92,   92,   91,  361,  962,  963,
   138507  /*   620 */   964,   97,   98,   88,  983,  983,  859,  862,  851,  851,
   138508  /*   630 */    95,   95,   96,   96,   96,   96,  830,  830,  832, 1157,
   138509  /*   640 */  1157,  199, 1157,  173, 1227,  231,  232, 1282,    2,  335,
   138510  /*   650 */   271,  764,  271,  820,  271,  271,  763,  389,  389,  389,
   138511  /*   660 */   132,   79,   94,   94,   94,   94,   93,   93,   92,   92,
   138512  /*   670 */    92,   91,  361,   97,   98,   88,  983,  983,  859,  862,
   138513  /*   680 */   851,  851,   95,   95,   96,   96,   96,   96,  460,  264,
   138514  /*   690 */   223,  460, 1257,  783, 1223, 1157, 1086, 1082,   80,  271,
   138515  /*   700 */    78,  335,  340, 1031,  341,  344,  345,  902,  346,   10,
   138516  /*   710 */    10,  902,   25,   25,   94,   94,   94,   94,   93,   93,
   138517  /*   720 */    92,   92,   92,   91,  361,   97,   86,   88,  983,  983,
   138518  /*   730 */   859,  862,  851,  851,   95,   95,   96,   96,   96,   96,
   138519  /*   740 */  1157,  270,  395,  117,  233,  263,  235,   70,  456,  341,
   138520  /*   750 */   225,  176,  335, 1305,  342,  133,  736,  966,  980,  249,
   138521  /*   760 */  1150,  396,  325, 1085, 1028,  178,   94,   94,   94,   94,
   138522  /*   770 */    93,   93,   92,   92,   92,   91,  361,   98,   88,  983,
   138523  /*   780 */   983,  859,  862,  851,  851,   95,   95,   96,   96,   96,
   138524  /*   790 */    96,  783,  783,  132,  120,  966,  120,  120,  120,  798,
   138525  /*   800 */   252,  937,  335,  353,  321,  429,  355,  799,  822,  692,
   138526  /*   810 */   390,  203,  446,  450,  372,  716,  454,   94,   94,   94,
   138527  /*   820 */    94,   93,   93,   92,   92,   92,   91,  361,   88,  983,
   138528  /*   830 */   983,  859,  862,  851,  851,   95,   95,   96,   96,   96,
   138529  /*   840 */    96,   84,  455, 1225,    3, 1209,  120,  120,  382,  387,
   138530  /*   850 */   120,  203, 1271,  716,  384,  168,  266,  203,  458,   72,
   138531  /*   860 */   260, 1246,   84,  455,  178,    3,  378,   94,   94,   94,
   138532  /*   870 */    94,   93,   93,   92,   92,   92,   91,  361,  350,  458,
   138533  /*   880 */  1245,  362,  430,  213,  228,  290,  415,  285,  414,  200,
   138534  /*   890 */   783,  882,  444,  726,  725,  405,  283,  921,  209,  921,
   138535  /*   900 */   281,  132,  362,   72,  838,  289,  147,  733,  734,  392,
   138536  /*   910 */    81,   82,  922,  444,  922,  267,  288,   83,  362,  462,
   138537  /*   920 */   461,  272,  132,  830,   23,  838,  388,  923, 1216,  923,
   138538  /*   930 */  1056,   81,   82,   84,  455,  899,    3,  899,   83,  362,
   138539  /*   940 */   462,  461,  761,  962,  830,   75,    1,  443,  275,  747,
   138540  /*   950 */   458,    5,  962,  204,  830,  830,  832,  833,   18,  748,
   138541  /*   960 */   229,  962,  277,   19,  153,  317,  317,  316,  216,  314,
   138542  /*   970 */   279,  460,  689,  362, 1055,  830,  830,  832,  833,   18,
   138543  /*   980 */   962,  963,  964,  962,  444,  181,  460,  251,  981,  962,
   138544  /*   990 */   963,  964,    8,    8,   20,  250,  838, 1070,  962,  963,
   138545  /*  1000 */   964,  417,   81,   82,  768,  204,  347,   36,   36,   83,
   138546  /*  1010 */   362,  462,  461, 1054,  284,  830,   84,  455, 1123,    3,
   138547  /*  1020 */   962,  963,  964,  460,  183,  962,  981,  764,  889, 1107,
   138548  /*  1030 */   460,  184,  763,  458,  132,  182,   74,  455,  460,    3,
   138549  /*  1040 */   981,  898,  834,  898,    8,    8,  830,  830,  832,  833,
   138550  /*  1050 */    18,    8,    8,  458,  219, 1156,  362, 1103,  349,    8,
   138551  /*  1060 */     8,  240,  962,  963,  964,  236,  889,  444,  792,  336,
   138552  /*  1070 */   158,  203,  885,  435,  700,  209,  362,  114,  981,  838,
   138553  /*  1080 */   834,  227,  334, 1114,  441,   81,   82,  444,  442,  305,
   138554  /*  1090 */   784,  306,   83,  362,  462,  461,  369, 1162,  830,  838,
   138555  /*  1100 */   460, 1037,  237, 1030,  237,   81,   82,    7,   96,   96,
   138556  /*  1110 */    96,   96,   83,  362,  462,  461, 1019, 1018,  830, 1020,
   138557  /*  1120 */  1289,   37,   37,  400,   96,   96,   96,   96,   89,  830,
   138558  /*  1130 */   830,  832,  833,   18, 1100,  318,  962,  292,   94,   94,
   138559  /*  1140 */    94,   94,   93,   93,   92,   92,   92,   91,  361,  830,
   138560  /*  1150 */   830,  832,  833,   18,   94,   94,   94,   94,   93,   93,
   138561  /*  1160 */    92,   92,   92,   91,  361,  359,  358,  226,  226,  727,
   138562  /*  1170 */   294,  296,  460,  962,  963,  964,  460,  989,  160,  425,
   138563  /*  1180 */   170, 1295,  262,  460,  987,  374,  988,  386, 1145,  255,
   138564  /*  1190 */   326,  460,  373,   38,   38,  410,  174,   39,   39,  413,
   138565  /*  1200 */   460,  287,  460, 1053,   40,   40,  298,  728, 1220,  990,
   138566  /*  1210 */   445,  990,   26,   26, 1219,  460,  311,  460,  169, 1292,
   138567  /*  1220 */   460,   27,   27,   29,   29,  998,  460,  206,  135,  995,
   138568  /*  1230 */  1265, 1263,  460,   57,   60,  460,   41,   41,   42,   42,
   138569  /*  1240 */   460,   43,   43,  460,  343,  351,  460,    9,    9,  460,
   138570  /*  1250 */   144,  460,  130,   44,   44,  460,  103,  103,  460,  137,
   138571  /*  1260 */    70,   45,   45,  460,   46,   46,  460,   31,   31, 1142,
   138572  /*  1270 */    47,   47,   48,   48,  460,  376,   32,   32,  460,  122,
   138573  /*  1280 */   122,  460,  157,  460,  123,  123,  139,  124,  124,  460,
   138574  /*  1290 */   186,  460,  377,  460,  115,   54,   54,  460,  403,   33,
   138575  /*  1300 */    33,  460,  104,  104,   51,   51,  460,  161,  460,  140,
   138576  /*  1310 */   105,  105,  106,  106,  102,  102,  460,  141,  121,  121,
   138577  /*  1320 */   460,  142,  119,  119,  190,  460, 1152,  110,  110,  109,
   138578  /*  1330 */   109,  702,  460,  148,  393,   65,  460,  107,  107,  460,
   138579  /*  1340 */   323,  108,  108,  399,  460, 1234,   53,   53, 1214,  269,
   138580  /*  1350 */   154,  416, 1115,   55,   55,  220,  401,   52,   52,  191,
   138581  /*  1360 */    24,   24,  274,  192,  193,   28,   28, 1021,  328,  702,
   138582  /*  1370 */  1073,  352, 1072,  718, 1071,  431, 1111, 1064,  329, 1045,
   138583  /*  1380 */    69,  205,    6,  291, 1044,  286, 1112, 1043, 1304, 1110,
   138584  /*  1390 */   293,  300,  295,  297, 1063, 1200, 1109,   77,  241,  448,
   138585  /*  1400 */   356,  452,  436,  100,  214,   71,  434, 1027, 1093,   21,
   138586  /*  1410 */   463,  242,  243,  957,  215,  217,  218,  464,  309,  307,
   138587  /*  1420 */   308,  310, 1016,  125, 1250, 1251, 1011, 1249,  126,  127,
   138588  /*  1430 */  1248,  113,  676,  337,  238,  338,  134,  363,  167, 1041,
   138589  /*  1440 */  1040,   56,  247,  367,  180,  897,  111,  895,  136, 1038,
   138590  /*  1450 */   818,  128,  138,  750,  261,  911,  185,  143,  145,   61,
   138591  /*  1460 */    62,   63,   64,  129,  914,  187,  188,  910,  118,   12,
   138592  /*  1470 */   189,  903,  268,  992,  203,  162,  398,  150,  149,  691,
   138593  /*  1480 */   402,  288,  194,  406,  151,  411,   66,   13,  729,  239,
   138594  /*  1490 */   282,   14,   67,  131,  837,  836,  865,  758,   15,    4,
   138595  /*  1500 */    68,  762,  175,  222,  224,  424,  152,  869,  791,  202,
   138596  /*  1510 */   786,   75,   72,  880,  866,  864,   16,   17,  920,  207,
   138597  /*  1520 */   919,  208,  447,  946,  164,  211,  947,  210,  165,  451,
   138598  /*  1530 */   868,  166,  315,  835,  701,   85,  212, 1297,  312,  952,
   138599  /*  1540 */  1296,
   138600 };
   138601 static const YYCODETYPE yy_lookahead[] = {
   138602  /*     0 */   144,  145,  146,  147,  172,  222,  223,  224,  222,  223,
   138603  /*    10 */   224,  152,  180,  152,  148,  149,  152,  173,  176,   19,
   138604  /*    20 */   154,  173,  156,  152,  163,  242,  152,  163,  176,  163,
   138605  /*    30 */    26,   31,  173,  174,  173,  174,  173,  173,  174,   39,
   138606  /*    40 */     1,    2,  152,   43,   44,   45,   46,   47,   48,   49,
   138607  /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  197,  169,
   138608  /*    60 */   170,  197,  188,  197,  222,  223,  224,  208,  209,  208,
   138609  /*    70 */   209,   19,  208,  152,  222,  223,  224,   22,   26,   24,
   138610  /*    80 */    46,   47,   48,   49,   84,   85,   86,   87,   88,   89,
   138611  /*    90 */    90,   91,   92,   93,   94,   43,   44,   45,   46,   47,
   138612  /*   100 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
   138613  /*   110 */   106,  245,  157,   88,   89,   90,   91,   92,   93,   94,
   138614  /*   120 */    68,  231,  251,   19,   84,   85,   86,   87,   88,   89,
   138615  /*   130 */    90,   91,   92,   93,   94,  101,   84,   85,   86,   87,
   138616  /*   140 */    88,   89,   90,   91,   92,   93,   94,   43,   44,   45,
   138617  /*   150 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
   138618  /*   160 */    56,   57,   90,   91,   92,   93,   94,   82,   79,   99,
   138619  /*   170 */    66,  200,  102,  103,  104,   19,  168,  169,  170,  152,
   138620  /*   180 */    24,  210,   97,  113,  229,   59,  101,  232,   84,   85,
   138621  /*   190 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   43,
   138622  /*   200 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
   138623  /*   210 */    54,   55,   56,   57,  152,  188,  152,  132,  133,  134,
   138624  /*   220 */    93,   94,   96,   97,   98,   99,  152,   19,  102,  103,
   138625  /*   230 */   104,   23,   94,   72,   79,  173,  174,  173,  174,  113,
   138626  /*   240 */    84,   85,   86,   87,   88,   89,   90,   91,   92,   93,
   138627  /*   250 */    94,   43,   44,   45,   46,   47,   48,   49,   50,   51,
   138628  /*   260 */    52,   53,   54,   55,   56,   57,  152,  171,  152,  108,
   138629  /*   270 */   109,  110,  208,  209,  119,  120,  152,  180,  181,   19,
   138630  /*   280 */   119,  120,  152,   23,  152,  152,  189,  173,  174,  173,
   138631  /*   290 */   174,   59,   84,   85,   86,   87,   88,   89,   90,   91,
   138632  /*   300 */    92,   93,   94,   43,   44,   45,   46,   47,   48,   49,
   138633  /*   310 */    50,   51,   52,   53,   54,   55,   56,   57,  222,  223,
   138634  /*   320 */   224,  186,  208,  209,  208,  209,  194,  194,   96,   97,
   138635  /*   330 */    98,   19,  168,  169,  170,   23,   88,   89,  163,   59,
   138636  /*   340 */     0,    1,    2,  219,   84,   85,   86,   87,   88,   89,
   138637  /*   350 */    90,   91,   92,   93,   94,   43,   44,   45,   46,   47,
   138638  /*   360 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
   138639  /*   370 */    90,  152,  197,  195,  196,  243,   96,   97,   98,  196,
   138640  /*   380 */   132,   11,  134,   19,  182,  207,  115,   23,  117,  118,
   138641  /*   390 */   207,  163,  173,  174,  152,  220,   84,   85,   86,   87,
   138642  /*   400 */    88,   89,   90,   91,   92,   93,   94,   43,   44,   45,
   138643  /*   410 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
   138644  /*   420 */    56,   57,  152,   16,  152,  197,  171,  208,   22,   23,
   138645  /*   430 */    22,   23,   26,   16,   26,   19,    7,    8,    9,   23,
   138646  /*   440 */   212,  213,  152,  173,  174,  173,  174,   19,   84,   85,
   138647  /*   450 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   43,
   138648  /*   460 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
   138649  /*   470 */    54,   55,   56,   57,   46,  152,  109,  110,  208,  109,
   138650  /*   480 */   110,  152,   75,  152,   77,   22,   23,   19,  233,   83,
   138651  /*   490 */   152,   83,   75,  238,   77,  164,  173,  174,  226,   59,
   138652  /*   500 */    84,   85,   86,   87,   88,   89,   90,   91,   92,   93,
   138653  /*   510 */    94,   43,   44,   45,   46,   47,   48,   49,   50,   51,
   138654  /*   520 */    52,   53,   54,   55,   56,   57,  108,  109,  110,  152,
   138655  /*   530 */   152,  152,   22,   22,   23,  107,   96,   97,   98,  160,
   138656  /*   540 */   112,  251,   19,  164,   22,  152,   83,  140,  219,  152,
   138657  /*   550 */   173,  174,   84,   85,   86,   87,   88,   89,   90,   91,
   138658  /*   560 */    92,   93,   94,   59,  124,  152,   43,   44,   45,   46,
   138659  /*   570 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
   138660  /*   580 */    57,   59,  169,  170,  119,  120,   82,  108,  109,  110,
   138661  /*   590 */   191,  192,  191,  192,   83,  248,  249,   19,   88,   89,
   138662  /*   600 */    96,   97,   24,  152,  152,  101,  138,   84,   85,   86,
   138663  /*   610 */    87,   88,   89,   90,   91,   92,   93,   94,   96,   97,
   138664  /*   620 */    98,   43,   44,   45,   46,   47,   48,   49,   50,   51,
   138665  /*   630 */    52,   53,   54,   55,   56,   57,  132,  133,  134,  152,
   138666  /*   640 */   152,   46,  152,   26,  231,  194,  194,  146,  147,   19,
   138667  /*   650 */   152,  116,  152,   72,  152,  152,  121,  152,  152,  152,
   138668  /*   660 */    79,  138,   84,   85,   86,   87,   88,   89,   90,   91,
   138669  /*   670 */    92,   93,   94,   43,   44,   45,   46,   47,   48,   49,
   138670  /*   680 */    50,   51,   52,   53,   54,   55,   56,   57,  152,  108,
   138671  /*   690 */    23,  152,  194,   26,  194,  152,  194,  194,  137,  152,
   138672  /*   700 */   139,   19,  107,  166,  167,  218,  218,   29,  218,  173,
   138673  /*   710 */   174,   33,  173,  174,   84,   85,   86,   87,   88,   89,
   138674  /*   720 */    90,   91,   92,   93,   94,   43,   44,   45,   46,   47,
   138675  /*   730 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
   138676  /*   740 */   152,  194,   64,  171,  239,  239,  239,  130,  166,  167,
   138677  /*   750 */   212,  213,   19,   23,  246,  247,   26,   59,   26,  152,
   138678  /*   760 */   163,  218,  163,  163,  163,   98,   84,   85,   86,   87,
   138679  /*   770 */    88,   89,   90,   91,   92,   93,   94,   44,   45,   46,
   138680  /*   780 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
   138681  /*   790 */    57,  124,   26,   79,  197,   97,  197,  197,  197,   31,
   138682  /*   800 */   152,   23,   19,   19,   26,   19,  218,   39,   23,   21,
   138683  /*   810 */   238,   26,  163,  163,  100,   59,  163,   84,   85,   86,
   138684  /*   820 */    87,   88,   89,   90,   91,   92,   93,   94,   45,   46,
   138685  /*   830 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
   138686  /*   840 */    57,   19,   20,  152,   22,   23,  197,  197,   23,   19,
   138687  /*   850 */   197,   26,  152,   97,   23,  123,   23,   26,   36,   26,
   138688  /*   860 */   152,  152,   19,   20,   98,   22,   78,   84,   85,   86,
   138689  /*   870 */    87,   88,   89,   90,   91,   92,   93,   94,   94,   36,
   138690  /*   880 */   152,   59,   96,   99,  100,  101,  102,  103,  104,  105,
   138691  /*   890 */   124,  103,   70,  100,  101,   23,  112,   12,   26,   12,
   138692  /*   900 */    23,   79,   59,   26,   82,  101,   22,    7,    8,  152,
   138693  /*   910 */    88,   89,   27,   70,   27,  152,  112,   95,   96,   97,
   138694  /*   920 */    98,  152,   79,  101,   22,   82,   96,   42,  140,   42,
   138695  /*   930 */   182,   88,   89,   19,   20,  132,   22,  134,   95,   96,
   138696  /*   940 */    97,   98,   23,   59,  101,   26,   22,   62,  152,   62,
   138697  /*   950 */    36,   22,   59,   24,  132,  133,  134,  135,  136,   72,
   138698  /*   960 */     5,   59,  152,   22,   71,   10,   11,   12,   13,   14,
   138699  /*   970 */   152,  152,   17,   59,  182,  132,  133,  134,  135,  136,
   138700  /*   980 */    96,   97,   98,   59,   70,   30,  152,   32,   59,   96,
   138701  /*   990 */    97,   98,  173,  174,   53,   40,   82,  152,   96,   97,
   138702  /*  1000 */    98,   90,   88,   89,   90,   24,  187,  173,  174,   95,
   138703  /*  1010 */    96,   97,   98,  152,  152,  101,   19,   20,  152,   22,
   138704  /*  1020 */    96,   97,   98,  152,   69,   59,   97,  116,   59,  214,
   138705  /*  1030 */   152,   76,  121,   36,   79,   80,   19,   20,  152,   22,
   138706  /*  1040 */    59,  132,   59,  134,  173,  174,  132,  133,  134,  135,
   138707  /*  1050 */   136,  173,  174,   36,  234,  152,   59,  152,  187,  173,
   138708  /*  1060 */   174,  211,   96,   97,   98,  187,   97,   70,   23,  114,
   138709  /*  1070 */   152,   26,   23,  187,   23,   26,   59,   26,   97,   82,
   138710  /*  1080 */    97,   22,  164,  152,  152,   88,   89,   70,  192,  152,
   138711  /*  1090 */   124,  152,   95,   96,   97,   98,  141,  152,  101,   82,
   138712  /*  1100 */   152,  152,  184,  152,  186,   88,   89,  199,   54,   55,
   138713  /*  1110 */    56,   57,   95,   96,   97,   98,  152,  152,  101,  152,
   138714  /*  1120 */   152,  173,  174,  235,   54,   55,   56,   57,   58,  132,
   138715  /*  1130 */   133,  134,  135,  136,  211,  150,   59,  211,   84,   85,
   138716  /*  1140 */    86,   87,   88,   89,   90,   91,   92,   93,   94,  132,
   138717  /*  1150 */   133,  134,  135,  136,   84,   85,   86,   87,   88,   89,
   138718  /*  1160 */    90,   91,   92,   93,   94,   88,   89,  195,  196,   35,
   138719  /*  1170 */   211,  211,  152,   96,   97,   98,  152,  100,  198,  207,
   138720  /*  1180 */   171,  122,  240,  152,  107,  215,  109,  240,  202,  215,
   138721  /*  1190 */   202,  152,  220,  173,  174,  177,  185,  173,  174,   65,
   138722  /*  1200 */   152,  176,  152,  181,  173,  174,  215,   73,  176,  132,
   138723  /*  1210 */   228,  134,  173,  174,  176,  152,  201,  152,  199,  155,
   138724  /*  1220 */   152,  173,  174,  173,  174,   60,  152,  122,  244,   38,
   138725  /*  1230 */   159,  159,  152,  241,  241,  152,  173,  174,  173,  174,
   138726  /*  1240 */   152,  173,  174,  152,  159,  111,  152,  173,  174,  152,
   138727  /*  1250 */    22,  152,   43,  173,  174,  152,  173,  174,  152,  190,
   138728  /*  1260 */   130,  173,  174,  152,  173,  174,  152,  173,  174,  202,
   138729  /*  1270 */   173,  174,  173,  174,  152,   18,  173,  174,  152,  173,
   138730  /*  1280 */   174,  152,  221,  152,  173,  174,  193,  173,  174,  152,
   138731  /*  1290 */   158,  152,  159,  152,   22,  173,  174,  152,   18,  173,
   138732  /*  1300 */   174,  152,  173,  174,  173,  174,  152,  221,  152,  193,
   138733  /*  1310 */   173,  174,  173,  174,  173,  174,  152,  193,  173,  174,
   138734  /*  1320 */   152,  193,  173,  174,  158,  152,  190,  173,  174,  173,
   138735  /*  1330 */   174,   59,  152,  190,  159,  137,  152,  173,  174,  152,
   138736  /*  1340 */   202,  173,  174,   61,  152,  237,  173,  174,  202,  236,
   138737  /*  1350 */    22,  107,  159,  173,  174,  159,  178,  173,  174,  158,
   138738  /*  1360 */   173,  174,  159,  158,  158,  173,  174,  159,  178,   97,
   138739  /*  1370 */   175,   63,  175,  106,  175,  125,  217,  183,  178,  175,
   138740  /*  1380 */   107,  159,   22,  216,  177,  175,  217,  175,  175,  217,
   138741  /*  1390 */   216,  159,  216,  216,  183,  225,  217,  137,  227,  178,
   138742  /*  1400 */    94,  178,  126,  129,   25,  128,  127,  162,  206,   26,
   138743  /*  1410 */   161,  230,  230,   13,  153,  153,    6,  151,  203,  205,
   138744  /*  1420 */   204,  202,  151,  165,  171,  171,  151,  171,  165,  165,
   138745  /*  1430 */   171,  179,    4,  250,  179,  250,  247,    3,   22,  171,
   138746  /*  1440 */   171,  171,  142,   81,   15,   23,   16,   23,  131,  171,
   138747  /*  1450 */   120,  111,  123,   20,   16,    1,  125,  123,  131,   53,
   138748  /*  1460 */    53,   53,   53,  111,   96,   34,  122,    1,    5,   22,
   138749  /*  1470 */   107,   67,  140,   74,   26,   24,   41,  107,   67,   20,
   138750  /*  1480 */    19,  112,  105,   66,   22,   66,   22,   22,   28,   66,
   138751  /*  1490 */    23,   22,   22,   37,   23,   23,   23,  116,   22,   22,
   138752  /*  1500 */    26,   23,  122,   23,   23,   26,   22,   11,   96,   34,
   138753  /*  1510 */   124,   26,   26,   23,   23,   23,   34,   34,   23,   26,
   138754  /*  1520 */    23,   22,   24,   23,   22,  122,   23,   26,   22,   24,
   138755  /*  1530 */    23,   22,   15,   23,   23,   22,  122,  122,   23,    1,
   138756  /*  1540 */   122,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138757  /*  1550 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138758  /*  1560 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138759  /*  1570 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138760  /*  1580 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138761  /*  1590 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138762  /*  1600 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138763  /*  1610 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138764  /*  1620 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138765  /*  1630 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138766  /*  1640 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138767  /*  1650 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138768  /*  1660 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138769  /*  1670 */   252,  252,  252,  252,  252,  252,  252,  252,  252,  252,
   138770  /*  1680 */   252,  252,  252,  252,
   138771 };
   138772 #define YY_SHIFT_COUNT    (465)
   138773 #define YY_SHIFT_MIN      (0)
   138774 #define YY_SHIFT_MAX      (1538)
   138775 static const unsigned short int yy_shift_ofst[] = {
   138776  /*     0 */    39,  822,  955,  843,  997,  997,  997,  997,    0,    0,
   138777  /*    10 */   104,  630,  997,  997,  997,  997,  997,  997,  997, 1077,
   138778  /*    20 */  1077,  126,  161,  155,   52,  156,  208,  260,  312,  364,
   138779  /*    30 */   416,  468,  523,  578,  630,  630,  630,  630,  630,  630,
   138780  /*    40 */   630,  630,  630,  630,  630,  630,  630,  630,  630,  630,
   138781  /*    50 */   630,  682,  630,  733,  783,  783,  914,  997,  997,  997,
   138782  /*    60 */   997,  997,  997,  997,  997,  997,  997,  997,  997,  997,
   138783  /*    70 */   997,  997,  997,  997,  997,  997,  997,  997,  997,  997,
   138784  /*    80 */   997,  997,  997,  997,  997,  997,  997,  997, 1017,  997,
   138785  /*    90 */   997,  997,  997,  997,  997,  997,  997,  997,  997,  997,
   138786  /*   100 */   997,  997, 1070, 1054, 1054, 1054, 1054, 1054,   40,   25,
   138787  /*   110 */    72,  232,  788,  428,  248,  248,  232,  581,  367,  127,
   138788  /*   120 */   465,  138, 1541, 1541, 1541,  784,  784,  784,  522,  522,
   138789  /*   130 */   887,  887,  893,  406,  408,  232,  232,  232,  232,  232,
   138790  /*   140 */   232,  232,  232,  232,  232,  232,  232,  232,  232,  232,
   138791  /*   150 */   232,  232,  232,  232,  232,  370,  340,  714,  698,  698,
   138792  /*   160 */   465,   89,   89,   89,   89,   89,   89, 1541, 1541, 1541,
   138793  /*   170 */   504,   85,   85,  884,   70,  280,  902,  440,  966,  924,
   138794  /*   180 */   232,  232,  232,  232,  232,  232,  232,  232,  232,  232,
   138795  /*   190 */   232,  232,  232,  232,  232,  232, 1134, 1134, 1134,  232,
   138796  /*   200 */   232,  667,  232,  232,  232,  929,  232,  232,  885,  232,
   138797  /*   210 */   232,  232,  232,  232,  232,  232,  232,  232,  232,  418,
   138798  /*   220 */   678,  981,  981,  981,  981,  766,  271,  911,  510,  429,
   138799  /*   230 */   617,  786,  786,  830,  617,  830,    4,  730,  595,  768,
   138800  /*   240 */   786,  561,  768,  768,  732,  535,   55, 1165, 1105, 1105,
   138801  /*   250 */  1191, 1191, 1105, 1228, 1209, 1130, 1257, 1257, 1257, 1257,
   138802  /*   260 */  1105, 1280, 1130, 1228, 1209, 1209, 1130, 1105, 1280, 1198,
   138803  /*   270 */  1282, 1105, 1105, 1280, 1328, 1105, 1280, 1105, 1280, 1328,
   138804  /*   280 */  1244, 1244, 1244, 1308, 1328, 1244, 1267, 1244, 1308, 1244,
   138805  /*   290 */  1244, 1250, 1273, 1250, 1273, 1250, 1273, 1250, 1273, 1105,
   138806  /*   300 */  1360, 1105, 1260, 1328, 1306, 1306, 1328, 1274, 1276, 1277,
   138807  /*   310 */  1279, 1130, 1379, 1383, 1400, 1400, 1410, 1410, 1410, 1541,
   138808  /*   320 */  1541, 1541, 1541, 1541, 1541, 1541, 1541, 1541, 1541, 1541,
   138809  /*   330 */  1541, 1541, 1541, 1541, 1541,   34,  407,  463,  511,  417,
   138810  /*   340 */   479, 1272,  778,  941,  785,  825,  831,  833,  872,  877,
   138811  /*   350 */   756,  793,  900,  804,  919, 1045,  969, 1049,  803,  909,
   138812  /*   360 */  1051,  983, 1059, 1428, 1434, 1416, 1300, 1429, 1362, 1430,
   138813  /*   370 */  1422, 1424, 1330, 1317, 1340, 1329, 1433, 1331, 1438, 1454,
   138814  /*   380 */  1334, 1327, 1406, 1407, 1408, 1409, 1352, 1368, 1431, 1344,
   138815  /*   390 */  1466, 1463, 1447, 1363, 1332, 1404, 1448, 1411, 1399, 1435,
   138816  /*   400 */  1370, 1451, 1459, 1461, 1369, 1377, 1462, 1417, 1464, 1465,
   138817  /*   410 */  1467, 1469, 1419, 1460, 1470, 1423, 1456, 1471, 1472, 1473,
   138818  /*   420 */  1474, 1381, 1476, 1478, 1477, 1479, 1380, 1480, 1481, 1412,
   138819  /*   430 */  1475, 1484, 1386, 1485, 1482, 1486, 1483, 1490, 1485, 1491,
   138820  /*   440 */  1492, 1495, 1493, 1497, 1499, 1496, 1500, 1502, 1498, 1501,
   138821  /*   450 */  1503, 1506, 1505, 1501, 1507, 1509, 1510, 1511, 1513, 1403,
   138822  /*   460 */  1414, 1415, 1418, 1515, 1517, 1538,
   138823 };
   138824 #define YY_REDUCE_COUNT (334)
   138825 #define YY_REDUCE_MIN   (-217)
   138826 #define YY_REDUCE_MAX   (1278)
   138827 static const short yy_reduce_ofst[] = {
   138828  /*     0 */  -144, -139, -134, -136, -141,   64,  114,  116, -158, -148,
   138829  /*    10 */  -217,   96,  819,  871,  878,  219,  270,  886,  272, -110,
   138830  /*    20 */   413,  918,  972,  228, -214, -214, -214, -214, -214, -214,
   138831  /*    30 */  -214, -214, -214, -214, -214, -214, -214, -214, -214, -214,
   138832  /*    40 */  -214, -214, -214, -214, -214, -214, -214, -214, -214, -214,
   138833  /*    50 */  -214, -214, -214, -214, -214, -214,   62,  323,  377,  536,
   138834  /*    60 */   539,  834,  948, 1020, 1024, 1031, 1039, 1048, 1050, 1063,
   138835  /*    70 */  1065, 1068, 1074, 1080, 1083, 1088, 1091, 1094, 1097, 1099,
   138836  /*    80 */  1103, 1106, 1111, 1114, 1122, 1126, 1129, 1131, 1137, 1139,
   138837  /*    90 */  1141, 1145, 1149, 1154, 1156, 1164, 1168, 1173, 1180, 1184,
   138838  /*   100 */  1187, 1192, -214, -214, -214, -214, -214, -214, -214, -214,
   138839  /*   110 */  -214,  132,  -45,   97,    8,  164,  379,  175,  255, -214,
   138840  /*   120 */   178, -214, -214, -214, -214, -168, -168, -168,  124,  329,
   138841  /*   130 */   399,  401, -129,  347,  347,  331,  133,  451,  452,  498,
   138842  /*   140 */   500,  502,  503,  505,  487,  506,  488,  490,  507,  543,
   138843  /*   150 */   547, -126,  588,  290,   27,  572,  501,  597,  537,  582,
   138844  /*   160 */   183,  599,  600,  601,  649,  650,  653,  508,  538,  -29,
   138845  /*   170 */  -156, -152, -137,  -79,  135,   74,  130,  242,  338,  378,
   138846  /*   180 */   393,  397,  607,  648,  691,  700,  708,  709,  728,  757,
   138847  /*   190 */   763,  769,  796,  810,  818,  845,  202,  748,  792,  861,
   138848  /*   200 */   862,  815,  866,  903,  905,  850,  931,  932,  896,  937,
   138849  /*   210 */   939,  945,   74,  949,  951,  964,  965,  967,  968,  888,
   138850  /*   220 */   820,  923,  926,  959,  960,  815,  980,  908, 1009,  985,
   138851  /*   230 */   986,  970,  974,  942,  988,  947, 1018, 1011, 1022, 1025,
   138852  /*   240 */   991,  982, 1032, 1038, 1015, 1019, 1064,  984, 1071, 1072,
   138853  /*   250 */   992,  993, 1085, 1061, 1069, 1067, 1093, 1116, 1124, 1128,
   138854  /*   260 */  1133, 1132, 1138, 1086, 1136, 1143, 1146, 1175, 1166, 1108,
   138855  /*   270 */  1113, 1193, 1196, 1201, 1178, 1203, 1205, 1208, 1206, 1190,
   138856  /*   280 */  1195, 1197, 1199, 1194, 1200, 1204, 1207, 1210, 1211, 1212,
   138857  /*   290 */  1213, 1159, 1167, 1169, 1174, 1172, 1176, 1179, 1177, 1222,
   138858  /*   300 */  1170, 1232, 1171, 1221, 1181, 1182, 1223, 1202, 1214, 1216,
   138859  /*   310 */  1215, 1219, 1245, 1249, 1261, 1262, 1266, 1271, 1275, 1183,
   138860  /*   320 */  1185, 1189, 1258, 1253, 1254, 1256, 1259, 1263, 1252, 1255,
   138861  /*   330 */  1268, 1269, 1270, 1278, 1264,
   138862 };
   138863 static const YYACTIONTYPE yy_default[] = {
   138864  /*     0 */  1286, 1276, 1276, 1276, 1209, 1209, 1209, 1209, 1133, 1133,
   138865  /*    10 */  1260, 1036, 1005, 1005, 1005, 1005, 1005, 1005, 1208, 1005,
   138866  /*    20 */  1005, 1005, 1005, 1108, 1139, 1005, 1005, 1005, 1005, 1210,
   138867  /*    30 */  1211, 1005, 1005, 1005, 1259, 1261, 1149, 1148, 1147, 1146,
   138868  /*    40 */  1242, 1120, 1144, 1137, 1141, 1210, 1204, 1205, 1203, 1207,
   138869  /*    50 */  1211, 1005, 1140, 1174, 1188, 1173, 1005, 1005, 1005, 1005,
   138870  /*    60 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138871  /*    70 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138872  /*    80 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138873  /*    90 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138874  /*   100 */  1005, 1005, 1182, 1187, 1194, 1186, 1183, 1176, 1175, 1177,
   138875  /*   110 */  1178, 1005, 1026, 1075, 1005, 1005, 1005, 1276, 1036, 1179,
   138876  /*   120 */  1005, 1180, 1191, 1190, 1189, 1267, 1294, 1293, 1005, 1005,
   138877  /*   130 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138878  /*   140 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138879  /*   150 */  1005, 1005, 1005, 1005, 1005, 1036, 1286, 1276, 1032, 1032,
   138880  /*   160 */  1005, 1276, 1276, 1276, 1276, 1276, 1276, 1272, 1108, 1099,
   138881  /*   170 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138882  /*   180 */  1005, 1264, 1262, 1005, 1224, 1005, 1005, 1005, 1005, 1005,
   138883  /*   190 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138884  /*   200 */  1005, 1005, 1005, 1005, 1005, 1104, 1005, 1005, 1005, 1005,
   138885  /*   210 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1288, 1005,
   138886  /*   220 */  1237, 1104, 1104, 1104, 1104, 1106, 1088, 1098, 1036, 1012,
   138887  /*   230 */  1143, 1122, 1122, 1327, 1143, 1327, 1050, 1308, 1047, 1133,
   138888  /*   240 */  1122, 1206, 1133, 1133, 1105, 1098, 1005, 1330, 1113, 1113,
   138889  /*   250 */  1329, 1329, 1113, 1154, 1078, 1143, 1084, 1084, 1084, 1084,
   138890  /*   260 */  1113, 1023, 1143, 1154, 1078, 1078, 1143, 1113, 1023, 1241,
   138891  /*   270 */  1324, 1113, 1113, 1023, 1217, 1113, 1023, 1113, 1023, 1217,
   138892  /*   280 */  1076, 1076, 1076, 1065, 1217, 1076, 1050, 1076, 1065, 1076,
   138893  /*   290 */  1076, 1126, 1121, 1126, 1121, 1126, 1121, 1126, 1121, 1113,
   138894  /*   300 */  1212, 1113, 1005, 1217, 1221, 1221, 1217, 1138, 1127, 1136,
   138895  /*   310 */  1134, 1143, 1029, 1068, 1291, 1291, 1287, 1287, 1287, 1335,
   138896  /*   320 */  1335, 1272, 1303, 1036, 1036, 1036, 1036, 1303, 1052, 1052,
   138897  /*   330 */  1036, 1036, 1036, 1036, 1303, 1005, 1005, 1005, 1005, 1005,
   138898  /*   340 */  1005, 1298, 1005, 1226, 1005, 1005, 1005, 1005, 1005, 1005,
   138899  /*   350 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138900  /*   360 */  1005, 1005, 1159, 1005, 1008, 1269, 1005, 1005, 1268, 1005,
   138901  /*   370 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138902  /*   380 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1326,
   138903  /*   390 */  1005, 1005, 1005, 1005, 1005, 1005, 1240, 1239, 1005, 1005,
   138904  /*   400 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138905  /*   410 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005,
   138906  /*   420 */  1005, 1090, 1005, 1005, 1005, 1312, 1005, 1005, 1005, 1005,
   138907  /*   430 */  1005, 1005, 1005, 1135, 1005, 1128, 1005, 1005, 1317, 1005,
   138908  /*   440 */  1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1005, 1278,
   138909  /*   450 */  1005, 1005, 1005, 1277, 1005, 1005, 1005, 1005, 1005, 1161,
   138910  /*   460 */  1005, 1160, 1164, 1005, 1017, 1005,
   138911 };
   138912 /********** End of lemon-generated parsing tables *****************************/
   138913 
   138914 /* The next table maps tokens (terminal symbols) into fallback tokens.
   138915 ** If a construct like the following:
   138916 **
   138917 **      %fallback ID X Y Z.
   138918 **
   138919 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   138920 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   138921 ** but it does not parse, the type of the token is changed to ID and
   138922 ** the parse is retried before an error is thrown.
   138923 **
   138924 ** This feature can be used, for example, to cause some keywords in a language
   138925 ** to revert to identifiers if they keyword does not apply in the context where
   138926 ** it appears.
   138927 */
   138928 #ifdef YYFALLBACK
   138929 static const YYCODETYPE yyFallback[] = {
   138930     0,  /*          $ => nothing */
   138931     0,  /*       SEMI => nothing */
   138932    59,  /*    EXPLAIN => ID */
   138933    59,  /*      QUERY => ID */
   138934    59,  /*       PLAN => ID */
   138935    59,  /*      BEGIN => ID */
   138936     0,  /* TRANSACTION => nothing */
   138937    59,  /*   DEFERRED => ID */
   138938    59,  /*  IMMEDIATE => ID */
   138939    59,  /*  EXCLUSIVE => ID */
   138940     0,  /*     COMMIT => nothing */
   138941    59,  /*        END => ID */
   138942    59,  /*   ROLLBACK => ID */
   138943    59,  /*  SAVEPOINT => ID */
   138944    59,  /*    RELEASE => ID */
   138945     0,  /*         TO => nothing */
   138946     0,  /*      TABLE => nothing */
   138947     0,  /*     CREATE => nothing */
   138948    59,  /*         IF => ID */
   138949     0,  /*        NOT => nothing */
   138950     0,  /*     EXISTS => nothing */
   138951    59,  /*       TEMP => ID */
   138952     0,  /*         LP => nothing */
   138953     0,  /*         RP => nothing */
   138954     0,  /*         AS => nothing */
   138955    59,  /*    WITHOUT => ID */
   138956     0,  /*      COMMA => nothing */
   138957    59,  /*      ABORT => ID */
   138958    59,  /*     ACTION => ID */
   138959    59,  /*      AFTER => ID */
   138960    59,  /*    ANALYZE => ID */
   138961    59,  /*        ASC => ID */
   138962    59,  /*     ATTACH => ID */
   138963    59,  /*     BEFORE => ID */
   138964    59,  /*         BY => ID */
   138965    59,  /*    CASCADE => ID */
   138966    59,  /*       CAST => ID */
   138967    59,  /*   CONFLICT => ID */
   138968    59,  /*   DATABASE => ID */
   138969    59,  /*       DESC => ID */
   138970    59,  /*     DETACH => ID */
   138971    59,  /*       EACH => ID */
   138972    59,  /*       FAIL => ID */
   138973     0,  /*         OR => nothing */
   138974     0,  /*        AND => nothing */
   138975     0,  /*         IS => nothing */
   138976    59,  /*      MATCH => ID */
   138977    59,  /*    LIKE_KW => ID */
   138978     0,  /*    BETWEEN => nothing */
   138979     0,  /*         IN => nothing */
   138980     0,  /*     ISNULL => nothing */
   138981     0,  /*    NOTNULL => nothing */
   138982     0,  /*         NE => nothing */
   138983     0,  /*         EQ => nothing */
   138984     0,  /*         GT => nothing */
   138985     0,  /*         LE => nothing */
   138986     0,  /*         LT => nothing */
   138987     0,  /*         GE => nothing */
   138988     0,  /*     ESCAPE => nothing */
   138989     0,  /*         ID => nothing */
   138990    59,  /*   COLUMNKW => ID */
   138991    59,  /*        FOR => ID */
   138992    59,  /*     IGNORE => ID */
   138993    59,  /*  INITIALLY => ID */
   138994    59,  /*    INSTEAD => ID */
   138995    59,  /*         NO => ID */
   138996    59,  /*        KEY => ID */
   138997    59,  /*         OF => ID */
   138998    59,  /*     OFFSET => ID */
   138999    59,  /*     PRAGMA => ID */
   139000    59,  /*      RAISE => ID */
   139001    59,  /*  RECURSIVE => ID */
   139002    59,  /*    REPLACE => ID */
   139003    59,  /*   RESTRICT => ID */
   139004    59,  /*        ROW => ID */
   139005    59,  /*    TRIGGER => ID */
   139006    59,  /*     VACUUM => ID */
   139007    59,  /*       VIEW => ID */
   139008    59,  /*    VIRTUAL => ID */
   139009    59,  /*       WITH => ID */
   139010    59,  /*    REINDEX => ID */
   139011    59,  /*     RENAME => ID */
   139012    59,  /*   CTIME_KW => ID */
   139013 };
   139014 #endif /* YYFALLBACK */
   139015 
   139016 /* The following structure represents a single element of the
   139017 ** parser's stack.  Information stored includes:
   139018 **
   139019 **   +  The state number for the parser at this level of the stack.
   139020 **
   139021 **   +  The value of the token stored at this level of the stack.
   139022 **      (In other words, the "major" token.)
   139023 **
   139024 **   +  The semantic value stored at this level of the stack.  This is
   139025 **      the information used by the action routines in the grammar.
   139026 **      It is sometimes called the "minor" token.
   139027 **
   139028 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
   139029 ** actually contains the reduce action for the second half of the
   139030 ** SHIFTREDUCE.
   139031 */
   139032 struct yyStackEntry {
   139033   YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
   139034   YYCODETYPE major;      /* The major token value.  This is the code
   139035                          ** number for the token at this stack level */
   139036   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   139037                          ** is the value of the token  */
   139038 };
   139039 typedef struct yyStackEntry yyStackEntry;
   139040 
   139041 /* The state of the parser is completely contained in an instance of
   139042 ** the following structure */
   139043 struct yyParser {
   139044   yyStackEntry *yytos;          /* Pointer to top element of the stack */
   139045 #ifdef YYTRACKMAXSTACKDEPTH
   139046   int yyhwm;                    /* High-water mark of the stack */
   139047 #endif
   139048 #ifndef YYNOERRORRECOVERY
   139049   int yyerrcnt;                 /* Shifts left before out of the error */
   139050 #endif
   139051   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
   139052 #if YYSTACKDEPTH<=0
   139053   int yystksz;                  /* Current side of the stack */
   139054   yyStackEntry *yystack;        /* The parser's stack */
   139055   yyStackEntry yystk0;          /* First stack entry */
   139056 #else
   139057   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
   139058   yyStackEntry *yystackEnd;            /* Last entry in the stack */
   139059 #endif
   139060 };
   139061 typedef struct yyParser yyParser;
   139062 
   139063 #ifndef NDEBUG
   139064 /* #include <stdio.h> */
   139065 static FILE *yyTraceFILE = 0;
   139066 static char *yyTracePrompt = 0;
   139067 #endif /* NDEBUG */
   139068 
   139069 #ifndef NDEBUG
   139070 /*
   139071 ** Turn parser tracing on by giving a stream to which to write the trace
   139072 ** and a prompt to preface each trace message.  Tracing is turned off
   139073 ** by making either argument NULL
   139074 **
   139075 ** Inputs:
   139076 ** <ul>
   139077 ** <li> A FILE* to which trace output should be written.
   139078 **      If NULL, then tracing is turned off.
   139079 ** <li> A prefix string written at the beginning of every
   139080 **      line of trace output.  If NULL, then tracing is
   139081 **      turned off.
   139082 ** </ul>
   139083 **
   139084 ** Outputs:
   139085 ** None.
   139086 */
   139087 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   139088   yyTraceFILE = TraceFILE;
   139089   yyTracePrompt = zTracePrompt;
   139090   if( yyTraceFILE==0 ) yyTracePrompt = 0;
   139091   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
   139092 }
   139093 #endif /* NDEBUG */
   139094 
   139095 #if defined(YYCOVERAGE) || !defined(NDEBUG)
   139096 /* For tracing shifts, the names of all terminals and nonterminals
   139097 ** are required.  The following table supplies these names */
   139098 static const char *const yyTokenName[] = {
   139099   /*    0 */ "$",
   139100   /*    1 */ "SEMI",
   139101   /*    2 */ "EXPLAIN",
   139102   /*    3 */ "QUERY",
   139103   /*    4 */ "PLAN",
   139104   /*    5 */ "BEGIN",
   139105   /*    6 */ "TRANSACTION",
   139106   /*    7 */ "DEFERRED",
   139107   /*    8 */ "IMMEDIATE",
   139108   /*    9 */ "EXCLUSIVE",
   139109   /*   10 */ "COMMIT",
   139110   /*   11 */ "END",
   139111   /*   12 */ "ROLLBACK",
   139112   /*   13 */ "SAVEPOINT",
   139113   /*   14 */ "RELEASE",
   139114   /*   15 */ "TO",
   139115   /*   16 */ "TABLE",
   139116   /*   17 */ "CREATE",
   139117   /*   18 */ "IF",
   139118   /*   19 */ "NOT",
   139119   /*   20 */ "EXISTS",
   139120   /*   21 */ "TEMP",
   139121   /*   22 */ "LP",
   139122   /*   23 */ "RP",
   139123   /*   24 */ "AS",
   139124   /*   25 */ "WITHOUT",
   139125   /*   26 */ "COMMA",
   139126   /*   27 */ "ABORT",
   139127   /*   28 */ "ACTION",
   139128   /*   29 */ "AFTER",
   139129   /*   30 */ "ANALYZE",
   139130   /*   31 */ "ASC",
   139131   /*   32 */ "ATTACH",
   139132   /*   33 */ "BEFORE",
   139133   /*   34 */ "BY",
   139134   /*   35 */ "CASCADE",
   139135   /*   36 */ "CAST",
   139136   /*   37 */ "CONFLICT",
   139137   /*   38 */ "DATABASE",
   139138   /*   39 */ "DESC",
   139139   /*   40 */ "DETACH",
   139140   /*   41 */ "EACH",
   139141   /*   42 */ "FAIL",
   139142   /*   43 */ "OR",
   139143   /*   44 */ "AND",
   139144   /*   45 */ "IS",
   139145   /*   46 */ "MATCH",
   139146   /*   47 */ "LIKE_KW",
   139147   /*   48 */ "BETWEEN",
   139148   /*   49 */ "IN",
   139149   /*   50 */ "ISNULL",
   139150   /*   51 */ "NOTNULL",
   139151   /*   52 */ "NE",
   139152   /*   53 */ "EQ",
   139153   /*   54 */ "GT",
   139154   /*   55 */ "LE",
   139155   /*   56 */ "LT",
   139156   /*   57 */ "GE",
   139157   /*   58 */ "ESCAPE",
   139158   /*   59 */ "ID",
   139159   /*   60 */ "COLUMNKW",
   139160   /*   61 */ "FOR",
   139161   /*   62 */ "IGNORE",
   139162   /*   63 */ "INITIALLY",
   139163   /*   64 */ "INSTEAD",
   139164   /*   65 */ "NO",
   139165   /*   66 */ "KEY",
   139166   /*   67 */ "OF",
   139167   /*   68 */ "OFFSET",
   139168   /*   69 */ "PRAGMA",
   139169   /*   70 */ "RAISE",
   139170   /*   71 */ "RECURSIVE",
   139171   /*   72 */ "REPLACE",
   139172   /*   73 */ "RESTRICT",
   139173   /*   74 */ "ROW",
   139174   /*   75 */ "TRIGGER",
   139175   /*   76 */ "VACUUM",
   139176   /*   77 */ "VIEW",
   139177   /*   78 */ "VIRTUAL",
   139178   /*   79 */ "WITH",
   139179   /*   80 */ "REINDEX",
   139180   /*   81 */ "RENAME",
   139181   /*   82 */ "CTIME_KW",
   139182   /*   83 */ "ANY",
   139183   /*   84 */ "BITAND",
   139184   /*   85 */ "BITOR",
   139185   /*   86 */ "LSHIFT",
   139186   /*   87 */ "RSHIFT",
   139187   /*   88 */ "PLUS",
   139188   /*   89 */ "MINUS",
   139189   /*   90 */ "STAR",
   139190   /*   91 */ "SLASH",
   139191   /*   92 */ "REM",
   139192   /*   93 */ "CONCAT",
   139193   /*   94 */ "COLLATE",
   139194   /*   95 */ "BITNOT",
   139195   /*   96 */ "INDEXED",
   139196   /*   97 */ "STRING",
   139197   /*   98 */ "JOIN_KW",
   139198   /*   99 */ "CONSTRAINT",
   139199   /*  100 */ "DEFAULT",
   139200   /*  101 */ "NULL",
   139201   /*  102 */ "PRIMARY",
   139202   /*  103 */ "UNIQUE",
   139203   /*  104 */ "CHECK",
   139204   /*  105 */ "REFERENCES",
   139205   /*  106 */ "AUTOINCR",
   139206   /*  107 */ "ON",
   139207   /*  108 */ "INSERT",
   139208   /*  109 */ "DELETE",
   139209   /*  110 */ "UPDATE",
   139210   /*  111 */ "SET",
   139211   /*  112 */ "DEFERRABLE",
   139212   /*  113 */ "FOREIGN",
   139213   /*  114 */ "DROP",
   139214   /*  115 */ "UNION",
   139215   /*  116 */ "ALL",
   139216   /*  117 */ "EXCEPT",
   139217   /*  118 */ "INTERSECT",
   139218   /*  119 */ "SELECT",
   139219   /*  120 */ "VALUES",
   139220   /*  121 */ "DISTINCT",
   139221   /*  122 */ "DOT",
   139222   /*  123 */ "FROM",
   139223   /*  124 */ "JOIN",
   139224   /*  125 */ "USING",
   139225   /*  126 */ "ORDER",
   139226   /*  127 */ "GROUP",
   139227   /*  128 */ "HAVING",
   139228   /*  129 */ "LIMIT",
   139229   /*  130 */ "WHERE",
   139230   /*  131 */ "INTO",
   139231   /*  132 */ "FLOAT",
   139232   /*  133 */ "BLOB",
   139233   /*  134 */ "INTEGER",
   139234   /*  135 */ "VARIABLE",
   139235   /*  136 */ "CASE",
   139236   /*  137 */ "WHEN",
   139237   /*  138 */ "THEN",
   139238   /*  139 */ "ELSE",
   139239   /*  140 */ "INDEX",
   139240   /*  141 */ "ALTER",
   139241   /*  142 */ "ADD",
   139242   /*  143 */ "error",
   139243   /*  144 */ "input",
   139244   /*  145 */ "cmdlist",
   139245   /*  146 */ "ecmd",
   139246   /*  147 */ "explain",
   139247   /*  148 */ "cmdx",
   139248   /*  149 */ "cmd",
   139249   /*  150 */ "transtype",
   139250   /*  151 */ "trans_opt",
   139251   /*  152 */ "nm",
   139252   /*  153 */ "savepoint_opt",
   139253   /*  154 */ "create_table",
   139254   /*  155 */ "create_table_args",
   139255   /*  156 */ "createkw",
   139256   /*  157 */ "temp",
   139257   /*  158 */ "ifnotexists",
   139258   /*  159 */ "dbnm",
   139259   /*  160 */ "columnlist",
   139260   /*  161 */ "conslist_opt",
   139261   /*  162 */ "table_options",
   139262   /*  163 */ "select",
   139263   /*  164 */ "columnname",
   139264   /*  165 */ "carglist",
   139265   /*  166 */ "typetoken",
   139266   /*  167 */ "typename",
   139267   /*  168 */ "signed",
   139268   /*  169 */ "plus_num",
   139269   /*  170 */ "minus_num",
   139270   /*  171 */ "scanpt",
   139271   /*  172 */ "ccons",
   139272   /*  173 */ "term",
   139273   /*  174 */ "expr",
   139274   /*  175 */ "onconf",
   139275   /*  176 */ "sortorder",
   139276   /*  177 */ "autoinc",
   139277   /*  178 */ "eidlist_opt",
   139278   /*  179 */ "refargs",
   139279   /*  180 */ "defer_subclause",
   139280   /*  181 */ "refarg",
   139281   /*  182 */ "refact",
   139282   /*  183 */ "init_deferred_pred_opt",
   139283   /*  184 */ "conslist",
   139284   /*  185 */ "tconscomma",
   139285   /*  186 */ "tcons",
   139286   /*  187 */ "sortlist",
   139287   /*  188 */ "eidlist",
   139288   /*  189 */ "defer_subclause_opt",
   139289   /*  190 */ "orconf",
   139290   /*  191 */ "resolvetype",
   139291   /*  192 */ "raisetype",
   139292   /*  193 */ "ifexists",
   139293   /*  194 */ "fullname",
   139294   /*  195 */ "selectnowith",
   139295   /*  196 */ "oneselect",
   139296   /*  197 */ "with",
   139297   /*  198 */ "multiselect_op",
   139298   /*  199 */ "distinct",
   139299   /*  200 */ "selcollist",
   139300   /*  201 */ "from",
   139301   /*  202 */ "where_opt",
   139302   /*  203 */ "groupby_opt",
   139303   /*  204 */ "having_opt",
   139304   /*  205 */ "orderby_opt",
   139305   /*  206 */ "limit_opt",
   139306   /*  207 */ "values",
   139307   /*  208 */ "nexprlist",
   139308   /*  209 */ "exprlist",
   139309   /*  210 */ "sclp",
   139310   /*  211 */ "as",
   139311   /*  212 */ "seltablist",
   139312   /*  213 */ "stl_prefix",
   139313   /*  214 */ "joinop",
   139314   /*  215 */ "indexed_opt",
   139315   /*  216 */ "on_opt",
   139316   /*  217 */ "using_opt",
   139317   /*  218 */ "idlist",
   139318   /*  219 */ "setlist",
   139319   /*  220 */ "insert_cmd",
   139320   /*  221 */ "idlist_opt",
   139321   /*  222 */ "likeop",
   139322   /*  223 */ "between_op",
   139323   /*  224 */ "in_op",
   139324   /*  225 */ "paren_exprlist",
   139325   /*  226 */ "case_operand",
   139326   /*  227 */ "case_exprlist",
   139327   /*  228 */ "case_else",
   139328   /*  229 */ "uniqueflag",
   139329   /*  230 */ "collate",
   139330   /*  231 */ "nmnum",
   139331   /*  232 */ "trigger_decl",
   139332   /*  233 */ "trigger_cmd_list",
   139333   /*  234 */ "trigger_time",
   139334   /*  235 */ "trigger_event",
   139335   /*  236 */ "foreach_clause",
   139336   /*  237 */ "when_clause",
   139337   /*  238 */ "trigger_cmd",
   139338   /*  239 */ "trnm",
   139339   /*  240 */ "tridxby",
   139340   /*  241 */ "database_kw_opt",
   139341   /*  242 */ "key_opt",
   139342   /*  243 */ "add_column_fullname",
   139343   /*  244 */ "kwcolumn_opt",
   139344   /*  245 */ "create_vtab",
   139345   /*  246 */ "vtabarglist",
   139346   /*  247 */ "vtabarg",
   139347   /*  248 */ "vtabargtoken",
   139348   /*  249 */ "lp",
   139349   /*  250 */ "anylist",
   139350   /*  251 */ "wqlist",
   139351 };
   139352 #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
   139353 
   139354 #ifndef NDEBUG
   139355 /* For tracing reduce actions, the names of all rules are required.
   139356 */
   139357 static const char *const yyRuleName[] = {
   139358  /*   0 */ "explain ::= EXPLAIN",
   139359  /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
   139360  /*   2 */ "cmdx ::= cmd",
   139361  /*   3 */ "cmd ::= BEGIN transtype trans_opt",
   139362  /*   4 */ "transtype ::=",
   139363  /*   5 */ "transtype ::= DEFERRED",
   139364  /*   6 */ "transtype ::= IMMEDIATE",
   139365  /*   7 */ "transtype ::= EXCLUSIVE",
   139366  /*   8 */ "cmd ::= COMMIT|END trans_opt",
   139367  /*   9 */ "cmd ::= ROLLBACK trans_opt",
   139368  /*  10 */ "cmd ::= SAVEPOINT nm",
   139369  /*  11 */ "cmd ::= RELEASE savepoint_opt nm",
   139370  /*  12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
   139371  /*  13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
   139372  /*  14 */ "createkw ::= CREATE",
   139373  /*  15 */ "ifnotexists ::=",
   139374  /*  16 */ "ifnotexists ::= IF NOT EXISTS",
   139375  /*  17 */ "temp ::= TEMP",
   139376  /*  18 */ "temp ::=",
   139377  /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
   139378  /*  20 */ "create_table_args ::= AS select",
   139379  /*  21 */ "table_options ::=",
   139380  /*  22 */ "table_options ::= WITHOUT nm",
   139381  /*  23 */ "columnname ::= nm typetoken",
   139382  /*  24 */ "typetoken ::=",
   139383  /*  25 */ "typetoken ::= typename LP signed RP",
   139384  /*  26 */ "typetoken ::= typename LP signed COMMA signed RP",
   139385  /*  27 */ "typename ::= typename ID|STRING",
   139386  /*  28 */ "scanpt ::=",
   139387  /*  29 */ "ccons ::= CONSTRAINT nm",
   139388  /*  30 */ "ccons ::= DEFAULT scanpt term scanpt",
   139389  /*  31 */ "ccons ::= DEFAULT LP expr RP",
   139390  /*  32 */ "ccons ::= DEFAULT PLUS term scanpt",
   139391  /*  33 */ "ccons ::= DEFAULT MINUS term scanpt",
   139392  /*  34 */ "ccons ::= DEFAULT scanpt ID|INDEXED",
   139393  /*  35 */ "ccons ::= NOT NULL onconf",
   139394  /*  36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
   139395  /*  37 */ "ccons ::= UNIQUE onconf",
   139396  /*  38 */ "ccons ::= CHECK LP expr RP",
   139397  /*  39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
   139398  /*  40 */ "ccons ::= defer_subclause",
   139399  /*  41 */ "ccons ::= COLLATE ID|STRING",
   139400  /*  42 */ "autoinc ::=",
   139401  /*  43 */ "autoinc ::= AUTOINCR",
   139402  /*  44 */ "refargs ::=",
   139403  /*  45 */ "refargs ::= refargs refarg",
   139404  /*  46 */ "refarg ::= MATCH nm",
   139405  /*  47 */ "refarg ::= ON INSERT refact",
   139406  /*  48 */ "refarg ::= ON DELETE refact",
   139407  /*  49 */ "refarg ::= ON UPDATE refact",
   139408  /*  50 */ "refact ::= SET NULL",
   139409  /*  51 */ "refact ::= SET DEFAULT",
   139410  /*  52 */ "refact ::= CASCADE",
   139411  /*  53 */ "refact ::= RESTRICT",
   139412  /*  54 */ "refact ::= NO ACTION",
   139413  /*  55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
   139414  /*  56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
   139415  /*  57 */ "init_deferred_pred_opt ::=",
   139416  /*  58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
   139417  /*  59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
   139418  /*  60 */ "conslist_opt ::=",
   139419  /*  61 */ "tconscomma ::= COMMA",
   139420  /*  62 */ "tcons ::= CONSTRAINT nm",
   139421  /*  63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
   139422  /*  64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
   139423  /*  65 */ "tcons ::= CHECK LP expr RP onconf",
   139424  /*  66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
   139425  /*  67 */ "defer_subclause_opt ::=",
   139426  /*  68 */ "onconf ::=",
   139427  /*  69 */ "onconf ::= ON CONFLICT resolvetype",
   139428  /*  70 */ "orconf ::=",
   139429  /*  71 */ "orconf ::= OR resolvetype",
   139430  /*  72 */ "resolvetype ::= IGNORE",
   139431  /*  73 */ "resolvetype ::= REPLACE",
   139432  /*  74 */ "cmd ::= DROP TABLE ifexists fullname",
   139433  /*  75 */ "ifexists ::= IF EXISTS",
   139434  /*  76 */ "ifexists ::=",
   139435  /*  77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
   139436  /*  78 */ "cmd ::= DROP VIEW ifexists fullname",
   139437  /*  79 */ "cmd ::= select",
   139438  /*  80 */ "select ::= with selectnowith",
   139439  /*  81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
   139440  /*  82 */ "multiselect_op ::= UNION",
   139441  /*  83 */ "multiselect_op ::= UNION ALL",
   139442  /*  84 */ "multiselect_op ::= EXCEPT|INTERSECT",
   139443  /*  85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
   139444  /*  86 */ "values ::= VALUES LP nexprlist RP",
   139445  /*  87 */ "values ::= values COMMA LP exprlist RP",
   139446  /*  88 */ "distinct ::= DISTINCT",
   139447  /*  89 */ "distinct ::= ALL",
   139448  /*  90 */ "distinct ::=",
   139449  /*  91 */ "sclp ::=",
   139450  /*  92 */ "selcollist ::= sclp scanpt expr scanpt as",
   139451  /*  93 */ "selcollist ::= sclp scanpt STAR",
   139452  /*  94 */ "selcollist ::= sclp scanpt nm DOT STAR",
   139453  /*  95 */ "as ::= AS nm",
   139454  /*  96 */ "as ::=",
   139455  /*  97 */ "from ::=",
   139456  /*  98 */ "from ::= FROM seltablist",
   139457  /*  99 */ "stl_prefix ::= seltablist joinop",
   139458  /* 100 */ "stl_prefix ::=",
   139459  /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
   139460  /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
   139461  /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
   139462  /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
   139463  /* 105 */ "dbnm ::=",
   139464  /* 106 */ "dbnm ::= DOT nm",
   139465  /* 107 */ "fullname ::= nm dbnm",
   139466  /* 108 */ "joinop ::= COMMA|JOIN",
   139467  /* 109 */ "joinop ::= JOIN_KW JOIN",
   139468  /* 110 */ "joinop ::= JOIN_KW nm JOIN",
   139469  /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
   139470  /* 112 */ "on_opt ::= ON expr",
   139471  /* 113 */ "on_opt ::=",
   139472  /* 114 */ "indexed_opt ::=",
   139473  /* 115 */ "indexed_opt ::= INDEXED BY nm",
   139474  /* 116 */ "indexed_opt ::= NOT INDEXED",
   139475  /* 117 */ "using_opt ::= USING LP idlist RP",
   139476  /* 118 */ "using_opt ::=",
   139477  /* 119 */ "orderby_opt ::=",
   139478  /* 120 */ "orderby_opt ::= ORDER BY sortlist",
   139479  /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
   139480  /* 122 */ "sortlist ::= expr sortorder",
   139481  /* 123 */ "sortorder ::= ASC",
   139482  /* 124 */ "sortorder ::= DESC",
   139483  /* 125 */ "sortorder ::=",
   139484  /* 126 */ "groupby_opt ::=",
   139485  /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
   139486  /* 128 */ "having_opt ::=",
   139487  /* 129 */ "having_opt ::= HAVING expr",
   139488  /* 130 */ "limit_opt ::=",
   139489  /* 131 */ "limit_opt ::= LIMIT expr",
   139490  /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
   139491  /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
   139492  /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
   139493  /* 135 */ "where_opt ::=",
   139494  /* 136 */ "where_opt ::= WHERE expr",
   139495  /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
   139496  /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
   139497  /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
   139498  /* 140 */ "setlist ::= nm EQ expr",
   139499  /* 141 */ "setlist ::= LP idlist RP EQ expr",
   139500  /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
   139501  /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
   139502  /* 144 */ "insert_cmd ::= INSERT orconf",
   139503  /* 145 */ "insert_cmd ::= REPLACE",
   139504  /* 146 */ "idlist_opt ::=",
   139505  /* 147 */ "idlist_opt ::= LP idlist RP",
   139506  /* 148 */ "idlist ::= idlist COMMA nm",
   139507  /* 149 */ "idlist ::= nm",
   139508  /* 150 */ "expr ::= LP expr RP",
   139509  /* 151 */ "expr ::= ID|INDEXED",
   139510  /* 152 */ "expr ::= JOIN_KW",
   139511  /* 153 */ "expr ::= nm DOT nm",
   139512  /* 154 */ "expr ::= nm DOT nm DOT nm",
   139513  /* 155 */ "term ::= NULL|FLOAT|BLOB",
   139514  /* 156 */ "term ::= STRING",
   139515  /* 157 */ "term ::= INTEGER",
   139516  /* 158 */ "expr ::= VARIABLE",
   139517  /* 159 */ "expr ::= expr COLLATE ID|STRING",
   139518  /* 160 */ "expr ::= CAST LP expr AS typetoken RP",
   139519  /* 161 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
   139520  /* 162 */ "expr ::= ID|INDEXED LP STAR RP",
   139521  /* 163 */ "term ::= CTIME_KW",
   139522  /* 164 */ "expr ::= LP nexprlist COMMA expr RP",
   139523  /* 165 */ "expr ::= expr AND expr",
   139524  /* 166 */ "expr ::= expr OR expr",
   139525  /* 167 */ "expr ::= expr LT|GT|GE|LE expr",
   139526  /* 168 */ "expr ::= expr EQ|NE expr",
   139527  /* 169 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
   139528  /* 170 */ "expr ::= expr PLUS|MINUS expr",
   139529  /* 171 */ "expr ::= expr STAR|SLASH|REM expr",
   139530  /* 172 */ "expr ::= expr CONCAT expr",
   139531  /* 173 */ "likeop ::= NOT LIKE_KW|MATCH",
   139532  /* 174 */ "expr ::= expr likeop expr",
   139533  /* 175 */ "expr ::= expr likeop expr ESCAPE expr",
   139534  /* 176 */ "expr ::= expr ISNULL|NOTNULL",
   139535  /* 177 */ "expr ::= expr NOT NULL",
   139536  /* 178 */ "expr ::= expr IS expr",
   139537  /* 179 */ "expr ::= expr IS NOT expr",
   139538  /* 180 */ "expr ::= NOT expr",
   139539  /* 181 */ "expr ::= BITNOT expr",
   139540  /* 182 */ "expr ::= MINUS expr",
   139541  /* 183 */ "expr ::= PLUS expr",
   139542  /* 184 */ "between_op ::= BETWEEN",
   139543  /* 185 */ "between_op ::= NOT BETWEEN",
   139544  /* 186 */ "expr ::= expr between_op expr AND expr",
   139545  /* 187 */ "in_op ::= IN",
   139546  /* 188 */ "in_op ::= NOT IN",
   139547  /* 189 */ "expr ::= expr in_op LP exprlist RP",
   139548  /* 190 */ "expr ::= LP select RP",
   139549  /* 191 */ "expr ::= expr in_op LP select RP",
   139550  /* 192 */ "expr ::= expr in_op nm dbnm paren_exprlist",
   139551  /* 193 */ "expr ::= EXISTS LP select RP",
   139552  /* 194 */ "expr ::= CASE case_operand case_exprlist case_else END",
   139553  /* 195 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
   139554  /* 196 */ "case_exprlist ::= WHEN expr THEN expr",
   139555  /* 197 */ "case_else ::= ELSE expr",
   139556  /* 198 */ "case_else ::=",
   139557  /* 199 */ "case_operand ::= expr",
   139558  /* 200 */ "case_operand ::=",
   139559  /* 201 */ "exprlist ::=",
   139560  /* 202 */ "nexprlist ::= nexprlist COMMA expr",
   139561  /* 203 */ "nexprlist ::= expr",
   139562  /* 204 */ "paren_exprlist ::=",
   139563  /* 205 */ "paren_exprlist ::= LP exprlist RP",
   139564  /* 206 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
   139565  /* 207 */ "uniqueflag ::= UNIQUE",
   139566  /* 208 */ "uniqueflag ::=",
   139567  /* 209 */ "eidlist_opt ::=",
   139568  /* 210 */ "eidlist_opt ::= LP eidlist RP",
   139569  /* 211 */ "eidlist ::= eidlist COMMA nm collate sortorder",
   139570  /* 212 */ "eidlist ::= nm collate sortorder",
   139571  /* 213 */ "collate ::=",
   139572  /* 214 */ "collate ::= COLLATE ID|STRING",
   139573  /* 215 */ "cmd ::= DROP INDEX ifexists fullname",
   139574  /* 216 */ "cmd ::= VACUUM",
   139575  /* 217 */ "cmd ::= VACUUM nm",
   139576  /* 218 */ "cmd ::= PRAGMA nm dbnm",
   139577  /* 219 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
   139578  /* 220 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
   139579  /* 221 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
   139580  /* 222 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
   139581  /* 223 */ "plus_num ::= PLUS INTEGER|FLOAT",
   139582  /* 224 */ "minus_num ::= MINUS INTEGER|FLOAT",
   139583  /* 225 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
   139584  /* 226 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
   139585  /* 227 */ "trigger_time ::= BEFORE|AFTER",
   139586  /* 228 */ "trigger_time ::= INSTEAD OF",
   139587  /* 229 */ "trigger_time ::=",
   139588  /* 230 */ "trigger_event ::= DELETE|INSERT",
   139589  /* 231 */ "trigger_event ::= UPDATE",
   139590  /* 232 */ "trigger_event ::= UPDATE OF idlist",
   139591  /* 233 */ "when_clause ::=",
   139592  /* 234 */ "when_clause ::= WHEN expr",
   139593  /* 235 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
   139594  /* 236 */ "trigger_cmd_list ::= trigger_cmd SEMI",
   139595  /* 237 */ "trnm ::= nm DOT nm",
   139596  /* 238 */ "tridxby ::= INDEXED BY nm",
   139597  /* 239 */ "tridxby ::= NOT INDEXED",
   139598  /* 240 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
   139599  /* 241 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select scanpt",
   139600  /* 242 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
   139601  /* 243 */ "trigger_cmd ::= scanpt select scanpt",
   139602  /* 244 */ "expr ::= RAISE LP IGNORE RP",
   139603  /* 245 */ "expr ::= RAISE LP raisetype COMMA nm RP",
   139604  /* 246 */ "raisetype ::= ROLLBACK",
   139605  /* 247 */ "raisetype ::= ABORT",
   139606  /* 248 */ "raisetype ::= FAIL",
   139607  /* 249 */ "cmd ::= DROP TRIGGER ifexists fullname",
   139608  /* 250 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
   139609  /* 251 */ "cmd ::= DETACH database_kw_opt expr",
   139610  /* 252 */ "key_opt ::=",
   139611  /* 253 */ "key_opt ::= KEY expr",
   139612  /* 254 */ "cmd ::= REINDEX",
   139613  /* 255 */ "cmd ::= REINDEX nm dbnm",
   139614  /* 256 */ "cmd ::= ANALYZE",
   139615  /* 257 */ "cmd ::= ANALYZE nm dbnm",
   139616  /* 258 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
   139617  /* 259 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
   139618  /* 260 */ "add_column_fullname ::= fullname",
   139619  /* 261 */ "cmd ::= create_vtab",
   139620  /* 262 */ "cmd ::= create_vtab LP vtabarglist RP",
   139621  /* 263 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
   139622  /* 264 */ "vtabarg ::=",
   139623  /* 265 */ "vtabargtoken ::= ANY",
   139624  /* 266 */ "vtabargtoken ::= lp anylist RP",
   139625  /* 267 */ "lp ::= LP",
   139626  /* 268 */ "with ::=",
   139627  /* 269 */ "with ::= WITH wqlist",
   139628  /* 270 */ "with ::= WITH RECURSIVE wqlist",
   139629  /* 271 */ "wqlist ::= nm eidlist_opt AS LP select RP",
   139630  /* 272 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
   139631  /* 273 */ "input ::= cmdlist",
   139632  /* 274 */ "cmdlist ::= cmdlist ecmd",
   139633  /* 275 */ "cmdlist ::= ecmd",
   139634  /* 276 */ "ecmd ::= SEMI",
   139635  /* 277 */ "ecmd ::= explain cmdx SEMI",
   139636  /* 278 */ "explain ::=",
   139637  /* 279 */ "trans_opt ::=",
   139638  /* 280 */ "trans_opt ::= TRANSACTION",
   139639  /* 281 */ "trans_opt ::= TRANSACTION nm",
   139640  /* 282 */ "savepoint_opt ::= SAVEPOINT",
   139641  /* 283 */ "savepoint_opt ::=",
   139642  /* 284 */ "cmd ::= create_table create_table_args",
   139643  /* 285 */ "columnlist ::= columnlist COMMA columnname carglist",
   139644  /* 286 */ "columnlist ::= columnname carglist",
   139645  /* 287 */ "nm ::= ID|INDEXED",
   139646  /* 288 */ "nm ::= STRING",
   139647  /* 289 */ "nm ::= JOIN_KW",
   139648  /* 290 */ "typetoken ::= typename",
   139649  /* 291 */ "typename ::= ID|STRING",
   139650  /* 292 */ "signed ::= plus_num",
   139651  /* 293 */ "signed ::= minus_num",
   139652  /* 294 */ "carglist ::= carglist ccons",
   139653  /* 295 */ "carglist ::=",
   139654  /* 296 */ "ccons ::= NULL onconf",
   139655  /* 297 */ "conslist_opt ::= COMMA conslist",
   139656  /* 298 */ "conslist ::= conslist tconscomma tcons",
   139657  /* 299 */ "conslist ::= tcons",
   139658  /* 300 */ "tconscomma ::=",
   139659  /* 301 */ "defer_subclause_opt ::= defer_subclause",
   139660  /* 302 */ "resolvetype ::= raisetype",
   139661  /* 303 */ "selectnowith ::= oneselect",
   139662  /* 304 */ "oneselect ::= values",
   139663  /* 305 */ "sclp ::= selcollist COMMA",
   139664  /* 306 */ "as ::= ID|STRING",
   139665  /* 307 */ "expr ::= term",
   139666  /* 308 */ "likeop ::= LIKE_KW|MATCH",
   139667  /* 309 */ "exprlist ::= nexprlist",
   139668  /* 310 */ "nmnum ::= plus_num",
   139669  /* 311 */ "nmnum ::= nm",
   139670  /* 312 */ "nmnum ::= ON",
   139671  /* 313 */ "nmnum ::= DELETE",
   139672  /* 314 */ "nmnum ::= DEFAULT",
   139673  /* 315 */ "plus_num ::= INTEGER|FLOAT",
   139674  /* 316 */ "foreach_clause ::=",
   139675  /* 317 */ "foreach_clause ::= FOR EACH ROW",
   139676  /* 318 */ "trnm ::= nm",
   139677  /* 319 */ "tridxby ::=",
   139678  /* 320 */ "database_kw_opt ::= DATABASE",
   139679  /* 321 */ "database_kw_opt ::=",
   139680  /* 322 */ "kwcolumn_opt ::=",
   139681  /* 323 */ "kwcolumn_opt ::= COLUMNKW",
   139682  /* 324 */ "vtabarglist ::= vtabarg",
   139683  /* 325 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
   139684  /* 326 */ "vtabarg ::= vtabarg vtabargtoken",
   139685  /* 327 */ "anylist ::=",
   139686  /* 328 */ "anylist ::= anylist LP anylist RP",
   139687  /* 329 */ "anylist ::= anylist ANY",
   139688 };
   139689 #endif /* NDEBUG */
   139690 
   139691 
   139692 #if YYSTACKDEPTH<=0
   139693 /*
   139694 ** Try to increase the size of the parser stack.  Return the number
   139695 ** of errors.  Return 0 on success.
   139696 */
   139697 static int yyGrowStack(yyParser *p){
   139698   int newSize;
   139699   int idx;
   139700   yyStackEntry *pNew;
   139701 
   139702   newSize = p->yystksz*2 + 100;
   139703   idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
   139704   if( p->yystack==&p->yystk0 ){
   139705     pNew = malloc(newSize*sizeof(pNew[0]));
   139706     if( pNew ) pNew[0] = p->yystk0;
   139707   }else{
   139708     pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
   139709   }
   139710   if( pNew ){
   139711     p->yystack = pNew;
   139712     p->yytos = &p->yystack[idx];
   139713 #ifndef NDEBUG
   139714     if( yyTraceFILE ){
   139715       fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
   139716               yyTracePrompt, p->yystksz, newSize);
   139717     }
   139718 #endif
   139719     p->yystksz = newSize;
   139720   }
   139721   return pNew==0;
   139722 }
   139723 #endif
   139724 
   139725 /* Datatype of the argument to the memory allocated passed as the
   139726 ** second argument to sqlite3ParserAlloc() below.  This can be changed by
   139727 ** putting an appropriate #define in the %include section of the input
   139728 ** grammar.
   139729 */
   139730 #ifndef YYMALLOCARGTYPE
   139731 # define YYMALLOCARGTYPE size_t
   139732 #endif
   139733 
   139734 /* Initialize a new parser that has already been allocated.
   139735 */
   139736 SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
   139737   yyParser *pParser = (yyParser*)yypParser;
   139738 #ifdef YYTRACKMAXSTACKDEPTH
   139739   pParser->yyhwm = 0;
   139740 #endif
   139741 #if YYSTACKDEPTH<=0
   139742   pParser->yytos = NULL;
   139743   pParser->yystack = NULL;
   139744   pParser->yystksz = 0;
   139745   if( yyGrowStack(pParser) ){
   139746     pParser->yystack = &pParser->yystk0;
   139747     pParser->yystksz = 1;
   139748   }
   139749 #endif
   139750 #ifndef YYNOERRORRECOVERY
   139751   pParser->yyerrcnt = -1;
   139752 #endif
   139753   pParser->yytos = pParser->yystack;
   139754   pParser->yystack[0].stateno = 0;
   139755   pParser->yystack[0].major = 0;
   139756 #if YYSTACKDEPTH>0
   139757   pParser->yystackEnd = &pParser->yystack[YYSTACKDEPTH-1];
   139758 #endif
   139759 }
   139760 
   139761 #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
   139762 /*
   139763 ** This function allocates a new parser.
   139764 ** The only argument is a pointer to a function which works like
   139765 ** malloc.
   139766 **
   139767 ** Inputs:
   139768 ** A pointer to the function used to allocate memory.
   139769 **
   139770 ** Outputs:
   139771 ** A pointer to a parser.  This pointer is used in subsequent calls
   139772 ** to sqlite3Parser and sqlite3ParserFree.
   139773 */
   139774 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
   139775   yyParser *pParser;
   139776   pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
   139777   if( pParser ) sqlite3ParserInit(pParser);
   139778   return pParser;
   139779 }
   139780 #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
   139781 
   139782 
   139783 /* The following function deletes the "minor type" or semantic value
   139784 ** associated with a symbol.  The symbol can be either a terminal
   139785 ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
   139786 ** a pointer to the value to be deleted.  The code used to do the
   139787 ** deletions is derived from the %destructor and/or %token_destructor
   139788 ** directives of the input grammar.
   139789 */
   139790 static void yy_destructor(
   139791   yyParser *yypParser,    /* The parser */
   139792   YYCODETYPE yymajor,     /* Type code for object to destroy */
   139793   YYMINORTYPE *yypminor   /* The object to be destroyed */
   139794 ){
   139795   sqlite3ParserARG_FETCH;
   139796   switch( yymajor ){
   139797     /* Here is inserted the actions which take place when a
   139798     ** terminal or non-terminal is destroyed.  This can happen
   139799     ** when the symbol is popped from the stack during a
   139800     ** reduce or during error processing or when a parser is
   139801     ** being destroyed before it is finished parsing.
   139802     **
   139803     ** Note: during a reduce, the only symbols destroyed are those
   139804     ** which appear on the RHS of the rule, but which are *not* used
   139805     ** inside the C code.
   139806     */
   139807 /********* Begin destructor definitions ***************************************/
   139808     case 163: /* select */
   139809     case 195: /* selectnowith */
   139810     case 196: /* oneselect */
   139811     case 207: /* values */
   139812 {
   139813 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
   139814 }
   139815       break;
   139816     case 173: /* term */
   139817     case 174: /* expr */
   139818     case 202: /* where_opt */
   139819     case 204: /* having_opt */
   139820     case 216: /* on_opt */
   139821     case 226: /* case_operand */
   139822     case 228: /* case_else */
   139823     case 237: /* when_clause */
   139824     case 242: /* key_opt */
   139825 {
   139826 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
   139827 }
   139828       break;
   139829     case 178: /* eidlist_opt */
   139830     case 187: /* sortlist */
   139831     case 188: /* eidlist */
   139832     case 200: /* selcollist */
   139833     case 203: /* groupby_opt */
   139834     case 205: /* orderby_opt */
   139835     case 208: /* nexprlist */
   139836     case 209: /* exprlist */
   139837     case 210: /* sclp */
   139838     case 219: /* setlist */
   139839     case 225: /* paren_exprlist */
   139840     case 227: /* case_exprlist */
   139841 {
   139842 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
   139843 }
   139844       break;
   139845     case 194: /* fullname */
   139846     case 201: /* from */
   139847     case 212: /* seltablist */
   139848     case 213: /* stl_prefix */
   139849 {
   139850 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
   139851 }
   139852       break;
   139853     case 197: /* with */
   139854     case 251: /* wqlist */
   139855 {
   139856 sqlite3WithDelete(pParse->db, (yypminor->yy451));
   139857 }
   139858       break;
   139859     case 217: /* using_opt */
   139860     case 218: /* idlist */
   139861     case 221: /* idlist_opt */
   139862 {
   139863 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
   139864 }
   139865       break;
   139866     case 233: /* trigger_cmd_list */
   139867     case 238: /* trigger_cmd */
   139868 {
   139869 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
   139870 }
   139871       break;
   139872     case 235: /* trigger_event */
   139873 {
   139874 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
   139875 }
   139876       break;
   139877 /********* End destructor definitions *****************************************/
   139878     default:  break;   /* If no destructor action specified: do nothing */
   139879   }
   139880 }
   139881 
   139882 /*
   139883 ** Pop the parser's stack once.
   139884 **
   139885 ** If there is a destructor routine associated with the token which
   139886 ** is popped from the stack, then call it.
   139887 */
   139888 static void yy_pop_parser_stack(yyParser *pParser){
   139889   yyStackEntry *yytos;
   139890   assert( pParser->yytos!=0 );
   139891   assert( pParser->yytos > pParser->yystack );
   139892   yytos = pParser->yytos--;
   139893 #ifndef NDEBUG
   139894   if( yyTraceFILE ){
   139895     fprintf(yyTraceFILE,"%sPopping %s\n",
   139896       yyTracePrompt,
   139897       yyTokenName[yytos->major]);
   139898   }
   139899 #endif
   139900   yy_destructor(pParser, yytos->major, &yytos->minor);
   139901 }
   139902 
   139903 /*
   139904 ** Clear all secondary memory allocations from the parser
   139905 */
   139906 SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
   139907   yyParser *pParser = (yyParser*)p;
   139908   while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
   139909 #if YYSTACKDEPTH<=0
   139910   if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
   139911 #endif
   139912 }
   139913 
   139914 #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
   139915 /*
   139916 ** Deallocate and destroy a parser.  Destructors are called for
   139917 ** all stack elements before shutting the parser down.
   139918 **
   139919 ** If the YYPARSEFREENEVERNULL macro exists (for example because it
   139920 ** is defined in a %include section of the input grammar) then it is
   139921 ** assumed that the input pointer is never NULL.
   139922 */
   139923 SQLITE_PRIVATE void sqlite3ParserFree(
   139924   void *p,                    /* The parser to be deleted */
   139925   void (*freeProc)(void*)     /* Function used to reclaim memory */
   139926 ){
   139927 #ifndef YYPARSEFREENEVERNULL
   139928   if( p==0 ) return;
   139929 #endif
   139930   sqlite3ParserFinalize(p);
   139931   (*freeProc)(p);
   139932 }
   139933 #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
   139934 
   139935 /*
   139936 ** Return the peak depth of the stack for a parser.
   139937 */
   139938 #ifdef YYTRACKMAXSTACKDEPTH
   139939 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
   139940   yyParser *pParser = (yyParser*)p;
   139941   return pParser->yyhwm;
   139942 }
   139943 #endif
   139944 
   139945 /* This array of booleans keeps track of the parser statement
   139946 ** coverage.  The element yycoverage[X][Y] is set when the parser
   139947 ** is in state X and has a lookahead token Y.  In a well-tested
   139948 ** systems, every element of this matrix should end up being set.
   139949 */
   139950 #if defined(YYCOVERAGE)
   139951 static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
   139952 #endif
   139953 
   139954 /*
   139955 ** Write into out a description of every state/lookahead combination that
   139956 **
   139957 **   (1)  has not been used by the parser, and
   139958 **   (2)  is not a syntax error.
   139959 **
   139960 ** Return the number of missed state/lookahead combinations.
   139961 */
   139962 #if defined(YYCOVERAGE)
   139963 SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
   139964   int stateno, iLookAhead, i;
   139965   int nMissed = 0;
   139966   for(stateno=0; stateno<YYNSTATE; stateno++){
   139967     i = yy_shift_ofst[stateno];
   139968     for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
   139969       if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
   139970       if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
   139971       if( out ){
   139972         fprintf(out,"State %d lookahead %s %s\n", stateno,
   139973                 yyTokenName[iLookAhead],
   139974                 yycoverage[stateno][iLookAhead] ? "ok" : "missed");
   139975       }
   139976     }
   139977   }
   139978   return nMissed;
   139979 }
   139980 #endif
   139981 
   139982 /*
   139983 ** Find the appropriate action for a parser given the terminal
   139984 ** look-ahead token iLookAhead.
   139985 */
   139986 static unsigned int yy_find_shift_action(
   139987   yyParser *pParser,        /* The parser */
   139988   YYCODETYPE iLookAhead     /* The look-ahead token */
   139989 ){
   139990   int i;
   139991   int stateno = pParser->yytos->stateno;
   139992 
   139993   if( stateno>YY_MAX_SHIFT ) return stateno;
   139994   assert( stateno <= YY_SHIFT_COUNT );
   139995 #if defined(YYCOVERAGE)
   139996   yycoverage[stateno][iLookAhead] = 1;
   139997 #endif
   139998   do{
   139999     i = yy_shift_ofst[stateno];
   140000     assert( i>=0 && i+YYNTOKEN<=sizeof(yy_lookahead)/sizeof(yy_lookahead[0]) );
   140001     assert( iLookAhead!=YYNOCODE );
   140002     assert( iLookAhead < YYNTOKEN );
   140003     i += iLookAhead;
   140004     if( yy_lookahead[i]!=iLookAhead ){
   140005 #ifdef YYFALLBACK
   140006       YYCODETYPE iFallback;            /* Fallback token */
   140007       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   140008              && (iFallback = yyFallback[iLookAhead])!=0 ){
   140009 #ifndef NDEBUG
   140010         if( yyTraceFILE ){
   140011           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
   140012              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
   140013         }
   140014 #endif
   140015         assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
   140016         iLookAhead = iFallback;
   140017         continue;
   140018       }
   140019 #endif
   140020 #ifdef YYWILDCARD
   140021       {
   140022         int j = i - iLookAhead + YYWILDCARD;
   140023         if(
   140024 #if YY_SHIFT_MIN+YYWILDCARD<0
   140025           j>=0 &&
   140026 #endif
   140027 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   140028           j<YY_ACTTAB_COUNT &&
   140029 #endif
   140030           yy_lookahead[j]==YYWILDCARD && iLookAhead>0
   140031         ){
   140032 #ifndef NDEBUG
   140033           if( yyTraceFILE ){
   140034             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   140035                yyTracePrompt, yyTokenName[iLookAhead],
   140036                yyTokenName[YYWILDCARD]);
   140037           }
   140038 #endif /* NDEBUG */
   140039           return yy_action[j];
   140040         }
   140041       }
   140042 #endif /* YYWILDCARD */
   140043       return yy_default[stateno];
   140044     }else{
   140045       return yy_action[i];
   140046     }
   140047   }while(1);
   140048 }
   140049 
   140050 /*
   140051 ** Find the appropriate action for a parser given the non-terminal
   140052 ** look-ahead token iLookAhead.
   140053 */
   140054 static int yy_find_reduce_action(
   140055   int stateno,              /* Current state number */
   140056   YYCODETYPE iLookAhead     /* The look-ahead token */
   140057 ){
   140058   int i;
   140059 #ifdef YYERRORSYMBOL
   140060   if( stateno>YY_REDUCE_COUNT ){
   140061     return yy_default[stateno];
   140062   }
   140063 #else
   140064   assert( stateno<=YY_REDUCE_COUNT );
   140065 #endif
   140066   i = yy_reduce_ofst[stateno];
   140067   assert( iLookAhead!=YYNOCODE );
   140068   i += iLookAhead;
   140069 #ifdef YYERRORSYMBOL
   140070   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   140071     return yy_default[stateno];
   140072   }
   140073 #else
   140074   assert( i>=0 && i<YY_ACTTAB_COUNT );
   140075   assert( yy_lookahead[i]==iLookAhead );
   140076 #endif
   140077   return yy_action[i];
   140078 }
   140079 
   140080 /*
   140081 ** The following routine is called if the stack overflows.
   140082 */
   140083 static void yyStackOverflow(yyParser *yypParser){
   140084    sqlite3ParserARG_FETCH;
   140085 #ifndef NDEBUG
   140086    if( yyTraceFILE ){
   140087      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   140088    }
   140089 #endif
   140090    while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
   140091    /* Here code is inserted which will execute if the parser
   140092    ** stack every overflows */
   140093 /******** Begin %stack_overflow code ******************************************/
   140094 
   140095   sqlite3ErrorMsg(pParse, "parser stack overflow");
   140096 /******** End %stack_overflow code ********************************************/
   140097    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   140098 }
   140099 
   140100 /*
   140101 ** Print tracing information for a SHIFT action
   140102 */
   140103 #ifndef NDEBUG
   140104 static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
   140105   if( yyTraceFILE ){
   140106     if( yyNewState<YYNSTATE ){
   140107       fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
   140108          yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
   140109          yyNewState);
   140110     }else{
   140111       fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
   140112          yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
   140113          yyNewState - YY_MIN_REDUCE);
   140114     }
   140115   }
   140116 }
   140117 #else
   140118 # define yyTraceShift(X,Y,Z)
   140119 #endif
   140120 
   140121 /*
   140122 ** Perform a shift action.
   140123 */
   140124 static void yy_shift(
   140125   yyParser *yypParser,          /* The parser to be shifted */
   140126   int yyNewState,               /* The new state to shift in */
   140127   int yyMajor,                  /* The major token to shift in */
   140128   sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
   140129 ){
   140130   yyStackEntry *yytos;
   140131   yypParser->yytos++;
   140132 #ifdef YYTRACKMAXSTACKDEPTH
   140133   if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
   140134     yypParser->yyhwm++;
   140135     assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
   140136   }
   140137 #endif
   140138 #if YYSTACKDEPTH>0
   140139   if( yypParser->yytos>yypParser->yystackEnd ){
   140140     yypParser->yytos--;
   140141     yyStackOverflow(yypParser);
   140142     return;
   140143   }
   140144 #else
   140145   if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
   140146     if( yyGrowStack(yypParser) ){
   140147       yypParser->yytos--;
   140148       yyStackOverflow(yypParser);
   140149       return;
   140150     }
   140151   }
   140152 #endif
   140153   if( yyNewState > YY_MAX_SHIFT ){
   140154     yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
   140155   }
   140156   yytos = yypParser->yytos;
   140157   yytos->stateno = (YYACTIONTYPE)yyNewState;
   140158   yytos->major = (YYCODETYPE)yyMajor;
   140159   yytos->minor.yy0 = yyMinor;
   140160   yyTraceShift(yypParser, yyNewState, "Shift");
   140161 }
   140162 
   140163 /* The following table contains information about every rule that
   140164 ** is used during the reduce.
   140165 */
   140166 static const struct {
   140167   YYCODETYPE lhs;       /* Symbol on the left-hand side of the rule */
   140168   signed char nrhs;     /* Negative of the number of RHS symbols in the rule */
   140169 } yyRuleInfo[] = {
   140170   {  147,   -1 }, /* (0) explain ::= EXPLAIN */
   140171   {  147,   -3 }, /* (1) explain ::= EXPLAIN QUERY PLAN */
   140172   {  148,   -1 }, /* (2) cmdx ::= cmd */
   140173   {  149,   -3 }, /* (3) cmd ::= BEGIN transtype trans_opt */
   140174   {  150,    0 }, /* (4) transtype ::= */
   140175   {  150,   -1 }, /* (5) transtype ::= DEFERRED */
   140176   {  150,   -1 }, /* (6) transtype ::= IMMEDIATE */
   140177   {  150,   -1 }, /* (7) transtype ::= EXCLUSIVE */
   140178   {  149,   -2 }, /* (8) cmd ::= COMMIT|END trans_opt */
   140179   {  149,   -2 }, /* (9) cmd ::= ROLLBACK trans_opt */
   140180   {  149,   -2 }, /* (10) cmd ::= SAVEPOINT nm */
   140181   {  149,   -3 }, /* (11) cmd ::= RELEASE savepoint_opt nm */
   140182   {  149,   -5 }, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   140183   {  154,   -6 }, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   140184   {  156,   -1 }, /* (14) createkw ::= CREATE */
   140185   {  158,    0 }, /* (15) ifnotexists ::= */
   140186   {  158,   -3 }, /* (16) ifnotexists ::= IF NOT EXISTS */
   140187   {  157,   -1 }, /* (17) temp ::= TEMP */
   140188   {  157,    0 }, /* (18) temp ::= */
   140189   {  155,   -5 }, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
   140190   {  155,   -2 }, /* (20) create_table_args ::= AS select */
   140191   {  162,    0 }, /* (21) table_options ::= */
   140192   {  162,   -2 }, /* (22) table_options ::= WITHOUT nm */
   140193   {  164,   -2 }, /* (23) columnname ::= nm typetoken */
   140194   {  166,    0 }, /* (24) typetoken ::= */
   140195   {  166,   -4 }, /* (25) typetoken ::= typename LP signed RP */
   140196   {  166,   -6 }, /* (26) typetoken ::= typename LP signed COMMA signed RP */
   140197   {  167,   -2 }, /* (27) typename ::= typename ID|STRING */
   140198   {  171,    0 }, /* (28) scanpt ::= */
   140199   {  172,   -2 }, /* (29) ccons ::= CONSTRAINT nm */
   140200   {  172,   -4 }, /* (30) ccons ::= DEFAULT scanpt term scanpt */
   140201   {  172,   -4 }, /* (31) ccons ::= DEFAULT LP expr RP */
   140202   {  172,   -4 }, /* (32) ccons ::= DEFAULT PLUS term scanpt */
   140203   {  172,   -4 }, /* (33) ccons ::= DEFAULT MINUS term scanpt */
   140204   {  172,   -3 }, /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
   140205   {  172,   -3 }, /* (35) ccons ::= NOT NULL onconf */
   140206   {  172,   -5 }, /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
   140207   {  172,   -2 }, /* (37) ccons ::= UNIQUE onconf */
   140208   {  172,   -4 }, /* (38) ccons ::= CHECK LP expr RP */
   140209   {  172,   -4 }, /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
   140210   {  172,   -1 }, /* (40) ccons ::= defer_subclause */
   140211   {  172,   -2 }, /* (41) ccons ::= COLLATE ID|STRING */
   140212   {  177,    0 }, /* (42) autoinc ::= */
   140213   {  177,   -1 }, /* (43) autoinc ::= AUTOINCR */
   140214   {  179,    0 }, /* (44) refargs ::= */
   140215   {  179,   -2 }, /* (45) refargs ::= refargs refarg */
   140216   {  181,   -2 }, /* (46) refarg ::= MATCH nm */
   140217   {  181,   -3 }, /* (47) refarg ::= ON INSERT refact */
   140218   {  181,   -3 }, /* (48) refarg ::= ON DELETE refact */
   140219   {  181,   -3 }, /* (49) refarg ::= ON UPDATE refact */
   140220   {  182,   -2 }, /* (50) refact ::= SET NULL */
   140221   {  182,   -2 }, /* (51) refact ::= SET DEFAULT */
   140222   {  182,   -1 }, /* (52) refact ::= CASCADE */
   140223   {  182,   -1 }, /* (53) refact ::= RESTRICT */
   140224   {  182,   -2 }, /* (54) refact ::= NO ACTION */
   140225   {  180,   -3 }, /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
   140226   {  180,   -2 }, /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   140227   {  183,    0 }, /* (57) init_deferred_pred_opt ::= */
   140228   {  183,   -2 }, /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
   140229   {  183,   -2 }, /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
   140230   {  161,    0 }, /* (60) conslist_opt ::= */
   140231   {  185,   -1 }, /* (61) tconscomma ::= COMMA */
   140232   {  186,   -2 }, /* (62) tcons ::= CONSTRAINT nm */
   140233   {  186,   -7 }, /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
   140234   {  186,   -5 }, /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
   140235   {  186,   -5 }, /* (65) tcons ::= CHECK LP expr RP onconf */
   140236   {  186,  -10 }, /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
   140237   {  189,    0 }, /* (67) defer_subclause_opt ::= */
   140238   {  175,    0 }, /* (68) onconf ::= */
   140239   {  175,   -3 }, /* (69) onconf ::= ON CONFLICT resolvetype */
   140240   {  190,    0 }, /* (70) orconf ::= */
   140241   {  190,   -2 }, /* (71) orconf ::= OR resolvetype */
   140242   {  191,   -1 }, /* (72) resolvetype ::= IGNORE */
   140243   {  191,   -1 }, /* (73) resolvetype ::= REPLACE */
   140244   {  149,   -4 }, /* (74) cmd ::= DROP TABLE ifexists fullname */
   140245   {  193,   -2 }, /* (75) ifexists ::= IF EXISTS */
   140246   {  193,    0 }, /* (76) ifexists ::= */
   140247   {  149,   -9 }, /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
   140248   {  149,   -4 }, /* (78) cmd ::= DROP VIEW ifexists fullname */
   140249   {  149,   -1 }, /* (79) cmd ::= select */
   140250   {  163,   -2 }, /* (80) select ::= with selectnowith */
   140251   {  195,   -3 }, /* (81) selectnowith ::= selectnowith multiselect_op oneselect */
   140252   {  198,   -1 }, /* (82) multiselect_op ::= UNION */
   140253   {  198,   -2 }, /* (83) multiselect_op ::= UNION ALL */
   140254   {  198,   -1 }, /* (84) multiselect_op ::= EXCEPT|INTERSECT */
   140255   {  196,   -9 }, /* (85) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   140256   {  207,   -4 }, /* (86) values ::= VALUES LP nexprlist RP */
   140257   {  207,   -5 }, /* (87) values ::= values COMMA LP exprlist RP */
   140258   {  199,   -1 }, /* (88) distinct ::= DISTINCT */
   140259   {  199,   -1 }, /* (89) distinct ::= ALL */
   140260   {  199,    0 }, /* (90) distinct ::= */
   140261   {  210,    0 }, /* (91) sclp ::= */
   140262   {  200,   -5 }, /* (92) selcollist ::= sclp scanpt expr scanpt as */
   140263   {  200,   -3 }, /* (93) selcollist ::= sclp scanpt STAR */
   140264   {  200,   -5 }, /* (94) selcollist ::= sclp scanpt nm DOT STAR */
   140265   {  211,   -2 }, /* (95) as ::= AS nm */
   140266   {  211,    0 }, /* (96) as ::= */
   140267   {  201,    0 }, /* (97) from ::= */
   140268   {  201,   -2 }, /* (98) from ::= FROM seltablist */
   140269   {  213,   -2 }, /* (99) stl_prefix ::= seltablist joinop */
   140270   {  213,    0 }, /* (100) stl_prefix ::= */
   140271   {  212,   -7 }, /* (101) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   140272   {  212,   -9 }, /* (102) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
   140273   {  212,   -7 }, /* (103) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   140274   {  212,   -7 }, /* (104) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   140275   {  159,    0 }, /* (105) dbnm ::= */
   140276   {  159,   -2 }, /* (106) dbnm ::= DOT nm */
   140277   {  194,   -2 }, /* (107) fullname ::= nm dbnm */
   140278   {  214,   -1 }, /* (108) joinop ::= COMMA|JOIN */
   140279   {  214,   -2 }, /* (109) joinop ::= JOIN_KW JOIN */
   140280   {  214,   -3 }, /* (110) joinop ::= JOIN_KW nm JOIN */
   140281   {  214,   -4 }, /* (111) joinop ::= JOIN_KW nm nm JOIN */
   140282   {  216,   -2 }, /* (112) on_opt ::= ON expr */
   140283   {  216,    0 }, /* (113) on_opt ::= */
   140284   {  215,    0 }, /* (114) indexed_opt ::= */
   140285   {  215,   -3 }, /* (115) indexed_opt ::= INDEXED BY nm */
   140286   {  215,   -2 }, /* (116) indexed_opt ::= NOT INDEXED */
   140287   {  217,   -4 }, /* (117) using_opt ::= USING LP idlist RP */
   140288   {  217,    0 }, /* (118) using_opt ::= */
   140289   {  205,    0 }, /* (119) orderby_opt ::= */
   140290   {  205,   -3 }, /* (120) orderby_opt ::= ORDER BY sortlist */
   140291   {  187,   -4 }, /* (121) sortlist ::= sortlist COMMA expr sortorder */
   140292   {  187,   -2 }, /* (122) sortlist ::= expr sortorder */
   140293   {  176,   -1 }, /* (123) sortorder ::= ASC */
   140294   {  176,   -1 }, /* (124) sortorder ::= DESC */
   140295   {  176,    0 }, /* (125) sortorder ::= */
   140296   {  203,    0 }, /* (126) groupby_opt ::= */
   140297   {  203,   -3 }, /* (127) groupby_opt ::= GROUP BY nexprlist */
   140298   {  204,    0 }, /* (128) having_opt ::= */
   140299   {  204,   -2 }, /* (129) having_opt ::= HAVING expr */
   140300   {  206,    0 }, /* (130) limit_opt ::= */
   140301   {  206,   -2 }, /* (131) limit_opt ::= LIMIT expr */
   140302   {  206,   -4 }, /* (132) limit_opt ::= LIMIT expr OFFSET expr */
   140303   {  206,   -4 }, /* (133) limit_opt ::= LIMIT expr COMMA expr */
   140304   {  149,   -6 }, /* (134) cmd ::= with DELETE FROM fullname indexed_opt where_opt */
   140305   {  202,    0 }, /* (135) where_opt ::= */
   140306   {  202,   -2 }, /* (136) where_opt ::= WHERE expr */
   140307   {  149,   -8 }, /* (137) cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
   140308   {  219,   -5 }, /* (138) setlist ::= setlist COMMA nm EQ expr */
   140309   {  219,   -7 }, /* (139) setlist ::= setlist COMMA LP idlist RP EQ expr */
   140310   {  219,   -3 }, /* (140) setlist ::= nm EQ expr */
   140311   {  219,   -5 }, /* (141) setlist ::= LP idlist RP EQ expr */
   140312   {  149,   -6 }, /* (142) cmd ::= with insert_cmd INTO fullname idlist_opt select */
   140313   {  149,   -7 }, /* (143) cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
   140314   {  220,   -2 }, /* (144) insert_cmd ::= INSERT orconf */
   140315   {  220,   -1 }, /* (145) insert_cmd ::= REPLACE */
   140316   {  221,    0 }, /* (146) idlist_opt ::= */
   140317   {  221,   -3 }, /* (147) idlist_opt ::= LP idlist RP */
   140318   {  218,   -3 }, /* (148) idlist ::= idlist COMMA nm */
   140319   {  218,   -1 }, /* (149) idlist ::= nm */
   140320   {  174,   -3 }, /* (150) expr ::= LP expr RP */
   140321   {  174,   -1 }, /* (151) expr ::= ID|INDEXED */
   140322   {  174,   -1 }, /* (152) expr ::= JOIN_KW */
   140323   {  174,   -3 }, /* (153) expr ::= nm DOT nm */
   140324   {  174,   -5 }, /* (154) expr ::= nm DOT nm DOT nm */
   140325   {  173,   -1 }, /* (155) term ::= NULL|FLOAT|BLOB */
   140326   {  173,   -1 }, /* (156) term ::= STRING */
   140327   {  173,   -1 }, /* (157) term ::= INTEGER */
   140328   {  174,   -1 }, /* (158) expr ::= VARIABLE */
   140329   {  174,   -3 }, /* (159) expr ::= expr COLLATE ID|STRING */
   140330   {  174,   -6 }, /* (160) expr ::= CAST LP expr AS typetoken RP */
   140331   {  174,   -5 }, /* (161) expr ::= ID|INDEXED LP distinct exprlist RP */
   140332   {  174,   -4 }, /* (162) expr ::= ID|INDEXED LP STAR RP */
   140333   {  173,   -1 }, /* (163) term ::= CTIME_KW */
   140334   {  174,   -5 }, /* (164) expr ::= LP nexprlist COMMA expr RP */
   140335   {  174,   -3 }, /* (165) expr ::= expr AND expr */
   140336   {  174,   -3 }, /* (166) expr ::= expr OR expr */
   140337   {  174,   -3 }, /* (167) expr ::= expr LT|GT|GE|LE expr */
   140338   {  174,   -3 }, /* (168) expr ::= expr EQ|NE expr */
   140339   {  174,   -3 }, /* (169) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
   140340   {  174,   -3 }, /* (170) expr ::= expr PLUS|MINUS expr */
   140341   {  174,   -3 }, /* (171) expr ::= expr STAR|SLASH|REM expr */
   140342   {  174,   -3 }, /* (172) expr ::= expr CONCAT expr */
   140343   {  222,   -2 }, /* (173) likeop ::= NOT LIKE_KW|MATCH */
   140344   {  174,   -3 }, /* (174) expr ::= expr likeop expr */
   140345   {  174,   -5 }, /* (175) expr ::= expr likeop expr ESCAPE expr */
   140346   {  174,   -2 }, /* (176) expr ::= expr ISNULL|NOTNULL */
   140347   {  174,   -3 }, /* (177) expr ::= expr NOT NULL */
   140348   {  174,   -3 }, /* (178) expr ::= expr IS expr */
   140349   {  174,   -4 }, /* (179) expr ::= expr IS NOT expr */
   140350   {  174,   -2 }, /* (180) expr ::= NOT expr */
   140351   {  174,   -2 }, /* (181) expr ::= BITNOT expr */
   140352   {  174,   -2 }, /* (182) expr ::= MINUS expr */
   140353   {  174,   -2 }, /* (183) expr ::= PLUS expr */
   140354   {  223,   -1 }, /* (184) between_op ::= BETWEEN */
   140355   {  223,   -2 }, /* (185) between_op ::= NOT BETWEEN */
   140356   {  174,   -5 }, /* (186) expr ::= expr between_op expr AND expr */
   140357   {  224,   -1 }, /* (187) in_op ::= IN */
   140358   {  224,   -2 }, /* (188) in_op ::= NOT IN */
   140359   {  174,   -5 }, /* (189) expr ::= expr in_op LP exprlist RP */
   140360   {  174,   -3 }, /* (190) expr ::= LP select RP */
   140361   {  174,   -5 }, /* (191) expr ::= expr in_op LP select RP */
   140362   {  174,   -5 }, /* (192) expr ::= expr in_op nm dbnm paren_exprlist */
   140363   {  174,   -4 }, /* (193) expr ::= EXISTS LP select RP */
   140364   {  174,   -5 }, /* (194) expr ::= CASE case_operand case_exprlist case_else END */
   140365   {  227,   -5 }, /* (195) case_exprlist ::= case_exprlist WHEN expr THEN expr */
   140366   {  227,   -4 }, /* (196) case_exprlist ::= WHEN expr THEN expr */
   140367   {  228,   -2 }, /* (197) case_else ::= ELSE expr */
   140368   {  228,    0 }, /* (198) case_else ::= */
   140369   {  226,   -1 }, /* (199) case_operand ::= expr */
   140370   {  226,    0 }, /* (200) case_operand ::= */
   140371   {  209,    0 }, /* (201) exprlist ::= */
   140372   {  208,   -3 }, /* (202) nexprlist ::= nexprlist COMMA expr */
   140373   {  208,   -1 }, /* (203) nexprlist ::= expr */
   140374   {  225,    0 }, /* (204) paren_exprlist ::= */
   140375   {  225,   -3 }, /* (205) paren_exprlist ::= LP exprlist RP */
   140376   {  149,  -12 }, /* (206) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
   140377   {  229,   -1 }, /* (207) uniqueflag ::= UNIQUE */
   140378   {  229,    0 }, /* (208) uniqueflag ::= */
   140379   {  178,    0 }, /* (209) eidlist_opt ::= */
   140380   {  178,   -3 }, /* (210) eidlist_opt ::= LP eidlist RP */
   140381   {  188,   -5 }, /* (211) eidlist ::= eidlist COMMA nm collate sortorder */
   140382   {  188,   -3 }, /* (212) eidlist ::= nm collate sortorder */
   140383   {  230,    0 }, /* (213) collate ::= */
   140384   {  230,   -2 }, /* (214) collate ::= COLLATE ID|STRING */
   140385   {  149,   -4 }, /* (215) cmd ::= DROP INDEX ifexists fullname */
   140386   {  149,   -1 }, /* (216) cmd ::= VACUUM */
   140387   {  149,   -2 }, /* (217) cmd ::= VACUUM nm */
   140388   {  149,   -3 }, /* (218) cmd ::= PRAGMA nm dbnm */
   140389   {  149,   -5 }, /* (219) cmd ::= PRAGMA nm dbnm EQ nmnum */
   140390   {  149,   -6 }, /* (220) cmd ::= PRAGMA nm dbnm LP nmnum RP */
   140391   {  149,   -5 }, /* (221) cmd ::= PRAGMA nm dbnm EQ minus_num */
   140392   {  149,   -6 }, /* (222) cmd ::= PRAGMA nm dbnm LP minus_num RP */
   140393   {  169,   -2 }, /* (223) plus_num ::= PLUS INTEGER|FLOAT */
   140394   {  170,   -2 }, /* (224) minus_num ::= MINUS INTEGER|FLOAT */
   140395   {  149,   -5 }, /* (225) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   140396   {  232,  -11 }, /* (226) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   140397   {  234,   -1 }, /* (227) trigger_time ::= BEFORE|AFTER */
   140398   {  234,   -2 }, /* (228) trigger_time ::= INSTEAD OF */
   140399   {  234,    0 }, /* (229) trigger_time ::= */
   140400   {  235,   -1 }, /* (230) trigger_event ::= DELETE|INSERT */
   140401   {  235,   -1 }, /* (231) trigger_event ::= UPDATE */
   140402   {  235,   -3 }, /* (232) trigger_event ::= UPDATE OF idlist */
   140403   {  237,    0 }, /* (233) when_clause ::= */
   140404   {  237,   -2 }, /* (234) when_clause ::= WHEN expr */
   140405   {  233,   -3 }, /* (235) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   140406   {  233,   -2 }, /* (236) trigger_cmd_list ::= trigger_cmd SEMI */
   140407   {  239,   -3 }, /* (237) trnm ::= nm DOT nm */
   140408   {  240,   -3 }, /* (238) tridxby ::= INDEXED BY nm */
   140409   {  240,   -2 }, /* (239) tridxby ::= NOT INDEXED */
   140410   {  238,   -8 }, /* (240) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
   140411   {  238,   -7 }, /* (241) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select scanpt */
   140412   {  238,   -6 }, /* (242) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
   140413   {  238,   -3 }, /* (243) trigger_cmd ::= scanpt select scanpt */
   140414   {  174,   -4 }, /* (244) expr ::= RAISE LP IGNORE RP */
   140415   {  174,   -6 }, /* (245) expr ::= RAISE LP raisetype COMMA nm RP */
   140416   {  192,   -1 }, /* (246) raisetype ::= ROLLBACK */
   140417   {  192,   -1 }, /* (247) raisetype ::= ABORT */
   140418   {  192,   -1 }, /* (248) raisetype ::= FAIL */
   140419   {  149,   -4 }, /* (249) cmd ::= DROP TRIGGER ifexists fullname */
   140420   {  149,   -6 }, /* (250) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   140421   {  149,   -3 }, /* (251) cmd ::= DETACH database_kw_opt expr */
   140422   {  242,    0 }, /* (252) key_opt ::= */
   140423   {  242,   -2 }, /* (253) key_opt ::= KEY expr */
   140424   {  149,   -1 }, /* (254) cmd ::= REINDEX */
   140425   {  149,   -3 }, /* (255) cmd ::= REINDEX nm dbnm */
   140426   {  149,   -1 }, /* (256) cmd ::= ANALYZE */
   140427   {  149,   -3 }, /* (257) cmd ::= ANALYZE nm dbnm */
   140428   {  149,   -6 }, /* (258) cmd ::= ALTER TABLE fullname RENAME TO nm */
   140429   {  149,   -7 }, /* (259) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
   140430   {  243,   -1 }, /* (260) add_column_fullname ::= fullname */
   140431   {  149,   -1 }, /* (261) cmd ::= create_vtab */
   140432   {  149,   -4 }, /* (262) cmd ::= create_vtab LP vtabarglist RP */
   140433   {  245,   -8 }, /* (263) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   140434   {  247,    0 }, /* (264) vtabarg ::= */
   140435   {  248,   -1 }, /* (265) vtabargtoken ::= ANY */
   140436   {  248,   -3 }, /* (266) vtabargtoken ::= lp anylist RP */
   140437   {  249,   -1 }, /* (267) lp ::= LP */
   140438   {  197,    0 }, /* (268) with ::= */
   140439   {  197,   -2 }, /* (269) with ::= WITH wqlist */
   140440   {  197,   -3 }, /* (270) with ::= WITH RECURSIVE wqlist */
   140441   {  251,   -6 }, /* (271) wqlist ::= nm eidlist_opt AS LP select RP */
   140442   {  251,   -8 }, /* (272) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
   140443   {  144,   -1 }, /* (273) input ::= cmdlist */
   140444   {  145,   -2 }, /* (274) cmdlist ::= cmdlist ecmd */
   140445   {  145,   -1 }, /* (275) cmdlist ::= ecmd */
   140446   {  146,   -1 }, /* (276) ecmd ::= SEMI */
   140447   {  146,   -3 }, /* (277) ecmd ::= explain cmdx SEMI */
   140448   {  147,    0 }, /* (278) explain ::= */
   140449   {  151,    0 }, /* (279) trans_opt ::= */
   140450   {  151,   -1 }, /* (280) trans_opt ::= TRANSACTION */
   140451   {  151,   -2 }, /* (281) trans_opt ::= TRANSACTION nm */
   140452   {  153,   -1 }, /* (282) savepoint_opt ::= SAVEPOINT */
   140453   {  153,    0 }, /* (283) savepoint_opt ::= */
   140454   {  149,   -2 }, /* (284) cmd ::= create_table create_table_args */
   140455   {  160,   -4 }, /* (285) columnlist ::= columnlist COMMA columnname carglist */
   140456   {  160,   -2 }, /* (286) columnlist ::= columnname carglist */
   140457   {  152,   -1 }, /* (287) nm ::= ID|INDEXED */
   140458   {  152,   -1 }, /* (288) nm ::= STRING */
   140459   {  152,   -1 }, /* (289) nm ::= JOIN_KW */
   140460   {  166,   -1 }, /* (290) typetoken ::= typename */
   140461   {  167,   -1 }, /* (291) typename ::= ID|STRING */
   140462   {  168,   -1 }, /* (292) signed ::= plus_num */
   140463   {  168,   -1 }, /* (293) signed ::= minus_num */
   140464   {  165,   -2 }, /* (294) carglist ::= carglist ccons */
   140465   {  165,    0 }, /* (295) carglist ::= */
   140466   {  172,   -2 }, /* (296) ccons ::= NULL onconf */
   140467   {  161,   -2 }, /* (297) conslist_opt ::= COMMA conslist */
   140468   {  184,   -3 }, /* (298) conslist ::= conslist tconscomma tcons */
   140469   {  184,   -1 }, /* (299) conslist ::= tcons */
   140470   {  185,    0 }, /* (300) tconscomma ::= */
   140471   {  189,   -1 }, /* (301) defer_subclause_opt ::= defer_subclause */
   140472   {  191,   -1 }, /* (302) resolvetype ::= raisetype */
   140473   {  195,   -1 }, /* (303) selectnowith ::= oneselect */
   140474   {  196,   -1 }, /* (304) oneselect ::= values */
   140475   {  210,   -2 }, /* (305) sclp ::= selcollist COMMA */
   140476   {  211,   -1 }, /* (306) as ::= ID|STRING */
   140477   {  174,   -1 }, /* (307) expr ::= term */
   140478   {  222,   -1 }, /* (308) likeop ::= LIKE_KW|MATCH */
   140479   {  209,   -1 }, /* (309) exprlist ::= nexprlist */
   140480   {  231,   -1 }, /* (310) nmnum ::= plus_num */
   140481   {  231,   -1 }, /* (311) nmnum ::= nm */
   140482   {  231,   -1 }, /* (312) nmnum ::= ON */
   140483   {  231,   -1 }, /* (313) nmnum ::= DELETE */
   140484   {  231,   -1 }, /* (314) nmnum ::= DEFAULT */
   140485   {  169,   -1 }, /* (315) plus_num ::= INTEGER|FLOAT */
   140486   {  236,    0 }, /* (316) foreach_clause ::= */
   140487   {  236,   -3 }, /* (317) foreach_clause ::= FOR EACH ROW */
   140488   {  239,   -1 }, /* (318) trnm ::= nm */
   140489   {  240,    0 }, /* (319) tridxby ::= */
   140490   {  241,   -1 }, /* (320) database_kw_opt ::= DATABASE */
   140491   {  241,    0 }, /* (321) database_kw_opt ::= */
   140492   {  244,    0 }, /* (322) kwcolumn_opt ::= */
   140493   {  244,   -1 }, /* (323) kwcolumn_opt ::= COLUMNKW */
   140494   {  246,   -1 }, /* (324) vtabarglist ::= vtabarg */
   140495   {  246,   -3 }, /* (325) vtabarglist ::= vtabarglist COMMA vtabarg */
   140496   {  247,   -2 }, /* (326) vtabarg ::= vtabarg vtabargtoken */
   140497   {  250,    0 }, /* (327) anylist ::= */
   140498   {  250,   -4 }, /* (328) anylist ::= anylist LP anylist RP */
   140499   {  250,   -2 }, /* (329) anylist ::= anylist ANY */
   140500 };
   140501 
   140502 static void yy_accept(yyParser*);  /* Forward Declaration */
   140503 
   140504 /*
   140505 ** Perform a reduce action and the shift that must immediately
   140506 ** follow the reduce.
   140507 **
   140508 ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
   140509 ** access to the lookahead token (if any).  The yyLookahead will be YYNOCODE
   140510 ** if the lookahead token has already been consumed.  As this procedure is
   140511 ** only called from one place, optimizing compilers will in-line it, which
   140512 ** means that the extra parameters have no performance impact.
   140513 */
   140514 static void yy_reduce(
   140515   yyParser *yypParser,         /* The parser */
   140516   unsigned int yyruleno,       /* Number of the rule by which to reduce */
   140517   int yyLookahead,             /* Lookahead token, or YYNOCODE if none */
   140518   sqlite3ParserTOKENTYPE yyLookaheadToken  /* Value of the lookahead token */
   140519 ){
   140520   int yygoto;                     /* The next state */
   140521   int yyact;                      /* The next action */
   140522   yyStackEntry *yymsp;            /* The top of the parser's stack */
   140523   int yysize;                     /* Amount to pop the stack */
   140524   sqlite3ParserARG_FETCH;
   140525   (void)yyLookahead;
   140526   (void)yyLookaheadToken;
   140527   yymsp = yypParser->yytos;
   140528 #ifndef NDEBUG
   140529   if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
   140530     yysize = yyRuleInfo[yyruleno].nrhs;
   140531     if( yysize ){
   140532       fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
   140533         yyTracePrompt,
   140534         yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
   140535     }else{
   140536       fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
   140537         yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
   140538     }
   140539   }
   140540 #endif /* NDEBUG */
   140541 
   140542   /* Check that the stack is large enough to grow by a single entry
   140543   ** if the RHS of the rule is empty.  This ensures that there is room
   140544   ** enough on the stack to push the LHS value */
   140545   if( yyRuleInfo[yyruleno].nrhs==0 ){
   140546 #ifdef YYTRACKMAXSTACKDEPTH
   140547     if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
   140548       yypParser->yyhwm++;
   140549       assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
   140550     }
   140551 #endif
   140552 #if YYSTACKDEPTH>0
   140553     if( yypParser->yytos>=yypParser->yystackEnd ){
   140554       yyStackOverflow(yypParser);
   140555       return;
   140556     }
   140557 #else
   140558     if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
   140559       if( yyGrowStack(yypParser) ){
   140560         yyStackOverflow(yypParser);
   140561         return;
   140562       }
   140563       yymsp = yypParser->yytos;
   140564     }
   140565 #endif
   140566   }
   140567 
   140568   switch( yyruleno ){
   140569   /* Beginning here are the reduction cases.  A typical example
   140570   ** follows:
   140571   **   case 0:
   140572   **  #line <lineno> <grammarfile>
   140573   **     { ... }           // User supplied code
   140574   **  #line <lineno> <thisfile>
   140575   **     break;
   140576   */
   140577 /********** Begin reduce actions **********************************************/
   140578         YYMINORTYPE yylhsminor;
   140579       case 0: /* explain ::= EXPLAIN */
   140580 { pParse->explain = 1; }
   140581         break;
   140582       case 1: /* explain ::= EXPLAIN QUERY PLAN */
   140583 { pParse->explain = 2; }
   140584         break;
   140585       case 2: /* cmdx ::= cmd */
   140586 { sqlite3FinishCoding(pParse); }
   140587         break;
   140588       case 3: /* cmd ::= BEGIN transtype trans_opt */
   140589 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
   140590         break;
   140591       case 4: /* transtype ::= */
   140592 {yymsp[1].minor.yy4 = TK_DEFERRED;}
   140593         break;
   140594       case 5: /* transtype ::= DEFERRED */
   140595       case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
   140596       case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
   140597 {yymsp[0].minor.yy4 = yymsp[0].major; /*A-overwrites-X*/}
   140598         break;
   140599       case 8: /* cmd ::= COMMIT|END trans_opt */
   140600       case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
   140601 {sqlite3EndTransaction(pParse,yymsp[-1].major);}
   140602         break;
   140603       case 10: /* cmd ::= SAVEPOINT nm */
   140604 {
   140605   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
   140606 }
   140607         break;
   140608       case 11: /* cmd ::= RELEASE savepoint_opt nm */
   140609 {
   140610   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
   140611 }
   140612         break;
   140613       case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   140614 {
   140615   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
   140616 }
   140617         break;
   140618       case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   140619 {
   140620    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
   140621 }
   140622         break;
   140623       case 14: /* createkw ::= CREATE */
   140624 {disableLookaside(pParse);}
   140625         break;
   140626       case 15: /* ifnotexists ::= */
   140627       case 18: /* temp ::= */ yytestcase(yyruleno==18);
   140628       case 21: /* table_options ::= */ yytestcase(yyruleno==21);
   140629       case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
   140630       case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
   140631       case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
   140632       case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
   140633       case 90: /* distinct ::= */ yytestcase(yyruleno==90);
   140634       case 213: /* collate ::= */ yytestcase(yyruleno==213);
   140635 {yymsp[1].minor.yy4 = 0;}
   140636         break;
   140637       case 16: /* ifnotexists ::= IF NOT EXISTS */
   140638 {yymsp[-2].minor.yy4 = 1;}
   140639         break;
   140640       case 17: /* temp ::= TEMP */
   140641       case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
   140642 {yymsp[0].minor.yy4 = 1;}
   140643         break;
   140644       case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
   140645 {
   140646   sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy4,0);
   140647 }
   140648         break;
   140649       case 20: /* create_table_args ::= AS select */
   140650 {
   140651   sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy387);
   140652   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
   140653 }
   140654         break;
   140655       case 22: /* table_options ::= WITHOUT nm */
   140656 {
   140657   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
   140658     yymsp[-1].minor.yy4 = TF_WithoutRowid | TF_NoVisibleRowid;
   140659   }else{
   140660     yymsp[-1].minor.yy4 = 0;
   140661     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
   140662   }
   140663 }
   140664         break;
   140665       case 23: /* columnname ::= nm typetoken */
   140666 {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
   140667         break;
   140668       case 24: /* typetoken ::= */
   140669       case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
   140670       case 96: /* as ::= */ yytestcase(yyruleno==96);
   140671 {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
   140672         break;
   140673       case 25: /* typetoken ::= typename LP signed RP */
   140674 {
   140675   yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
   140676 }
   140677         break;
   140678       case 26: /* typetoken ::= typename LP signed COMMA signed RP */
   140679 {
   140680   yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
   140681 }
   140682         break;
   140683       case 27: /* typename ::= typename ID|STRING */
   140684 {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
   140685         break;
   140686       case 28: /* scanpt ::= */
   140687 {
   140688   assert( yyLookahead!=YYNOCODE );
   140689   yymsp[1].minor.yy336 = yyLookaheadToken.z;
   140690 }
   140691         break;
   140692       case 29: /* ccons ::= CONSTRAINT nm */
   140693       case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
   140694 {pParse->constraintName = yymsp[0].minor.yy0;}
   140695         break;
   140696       case 30: /* ccons ::= DEFAULT scanpt term scanpt */
   140697 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy314,yymsp[-2].minor.yy336,yymsp[0].minor.yy336);}
   140698         break;
   140699       case 31: /* ccons ::= DEFAULT LP expr RP */
   140700 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy314,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
   140701         break;
   140702       case 32: /* ccons ::= DEFAULT PLUS term scanpt */
   140703 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy314,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy336);}
   140704         break;
   140705       case 33: /* ccons ::= DEFAULT MINUS term scanpt */
   140706 {
   140707   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[-1].minor.yy314, 0);
   140708   sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy336);
   140709 }
   140710         break;
   140711       case 34: /* ccons ::= DEFAULT scanpt ID|INDEXED */
   140712 {
   140713   Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
   140714   sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
   140715 }
   140716         break;
   140717       case 35: /* ccons ::= NOT NULL onconf */
   140718 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
   140719         break;
   140720       case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
   140721 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
   140722         break;
   140723       case 37: /* ccons ::= UNIQUE onconf */
   140724 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0,
   140725                                    SQLITE_IDXTYPE_UNIQUE);}
   140726         break;
   140727       case 38: /* ccons ::= CHECK LP expr RP */
   140728 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy314);}
   140729         break;
   140730       case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
   140731 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
   140732         break;
   140733       case 40: /* ccons ::= defer_subclause */
   140734 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
   140735         break;
   140736       case 41: /* ccons ::= COLLATE ID|STRING */
   140737 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
   140738         break;
   140739       case 44: /* refargs ::= */
   140740 { yymsp[1].minor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
   140741         break;
   140742       case 45: /* refargs ::= refargs refarg */
   140743 { yymsp[-1].minor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
   140744         break;
   140745       case 46: /* refarg ::= MATCH nm */
   140746 { yymsp[-1].minor.yy215.value = 0;     yymsp[-1].minor.yy215.mask = 0x000000; }
   140747         break;
   140748       case 47: /* refarg ::= ON INSERT refact */
   140749 { yymsp[-2].minor.yy215.value = 0;     yymsp[-2].minor.yy215.mask = 0x000000; }
   140750         break;
   140751       case 48: /* refarg ::= ON DELETE refact */
   140752 { yymsp[-2].minor.yy215.value = yymsp[0].minor.yy4;     yymsp[-2].minor.yy215.mask = 0x0000ff; }
   140753         break;
   140754       case 49: /* refarg ::= ON UPDATE refact */
   140755 { yymsp[-2].minor.yy215.value = yymsp[0].minor.yy4<<8;  yymsp[-2].minor.yy215.mask = 0x00ff00; }
   140756         break;
   140757       case 50: /* refact ::= SET NULL */
   140758 { yymsp[-1].minor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
   140759         break;
   140760       case 51: /* refact ::= SET DEFAULT */
   140761 { yymsp[-1].minor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
   140762         break;
   140763       case 52: /* refact ::= CASCADE */
   140764 { yymsp[0].minor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
   140765         break;
   140766       case 53: /* refact ::= RESTRICT */
   140767 { yymsp[0].minor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
   140768         break;
   140769       case 54: /* refact ::= NO ACTION */
   140770 { yymsp[-1].minor.yy4 = OE_None;     /* EV: R-33326-45252 */}
   140771         break;
   140772       case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
   140773 {yymsp[-2].minor.yy4 = 0;}
   140774         break;
   140775       case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   140776       case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
   140777       case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144);
   140778 {yymsp[-1].minor.yy4 = yymsp[0].minor.yy4;}
   140779         break;
   140780       case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
   140781       case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
   140782       case 185: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==185);
   140783       case 188: /* in_op ::= NOT IN */ yytestcase(yyruleno==188);
   140784       case 214: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==214);
   140785 {yymsp[-1].minor.yy4 = 1;}
   140786         break;
   140787       case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
   140788 {yymsp[-1].minor.yy4 = 0;}
   140789         break;
   140790       case 61: /* tconscomma ::= COMMA */
   140791 {pParse->constraintName.n = 0;}
   140792         break;
   140793       case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
   140794 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
   140795         break;
   140796       case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
   140797 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0,
   140798                                        SQLITE_IDXTYPE_UNIQUE);}
   140799         break;
   140800       case 65: /* tcons ::= CHECK LP expr RP onconf */
   140801 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy314);}
   140802         break;
   140803       case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
   140804 {
   140805     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
   140806     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
   140807 }
   140808         break;
   140809       case 68: /* onconf ::= */
   140810       case 70: /* orconf ::= */ yytestcase(yyruleno==70);
   140811 {yymsp[1].minor.yy4 = OE_Default;}
   140812         break;
   140813       case 69: /* onconf ::= ON CONFLICT resolvetype */
   140814 {yymsp[-2].minor.yy4 = yymsp[0].minor.yy4;}
   140815         break;
   140816       case 72: /* resolvetype ::= IGNORE */
   140817 {yymsp[0].minor.yy4 = OE_Ignore;}
   140818         break;
   140819       case 73: /* resolvetype ::= REPLACE */
   140820       case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145);
   140821 {yymsp[0].minor.yy4 = OE_Replace;}
   140822         break;
   140823       case 74: /* cmd ::= DROP TABLE ifexists fullname */
   140824 {
   140825   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
   140826 }
   140827         break;
   140828       case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
   140829 {
   140830   sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[0].minor.yy387, yymsp[-7].minor.yy4, yymsp[-5].minor.yy4);
   140831 }
   140832         break;
   140833       case 78: /* cmd ::= DROP VIEW ifexists fullname */
   140834 {
   140835   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
   140836 }
   140837         break;
   140838       case 79: /* cmd ::= select */
   140839 {
   140840   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
   140841   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
   140842   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
   140843 }
   140844         break;
   140845       case 80: /* select ::= with selectnowith */
   140846 {
   140847   Select *p = yymsp[0].minor.yy387;
   140848   if( p ){
   140849     p->pWith = yymsp[-1].minor.yy451;
   140850     parserDoubleLinkSelect(pParse, p);
   140851   }else{
   140852     sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy451);
   140853   }
   140854   yymsp[-1].minor.yy387 = p; /*A-overwrites-W*/
   140855 }
   140856         break;
   140857       case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
   140858 {
   140859   Select *pRhs = yymsp[0].minor.yy387;
   140860   Select *pLhs = yymsp[-2].minor.yy387;
   140861   if( pRhs && pRhs->pPrior ){
   140862     SrcList *pFrom;
   140863     Token x;
   140864     x.n = 0;
   140865     parserDoubleLinkSelect(pParse, pRhs);
   140866     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
   140867     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
   140868   }
   140869   if( pRhs ){
   140870     pRhs->op = (u8)yymsp[-1].minor.yy4;
   140871     pRhs->pPrior = pLhs;
   140872     if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
   140873     pRhs->selFlags &= ~SF_MultiValue;
   140874     if( yymsp[-1].minor.yy4!=TK_ALL ) pParse->hasCompound = 1;
   140875   }else{
   140876     sqlite3SelectDelete(pParse->db, pLhs);
   140877   }
   140878   yymsp[-2].minor.yy387 = pRhs;
   140879 }
   140880         break;
   140881       case 82: /* multiselect_op ::= UNION */
   140882       case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
   140883 {yymsp[0].minor.yy4 = yymsp[0].major; /*A-overwrites-OP*/}
   140884         break;
   140885       case 83: /* multiselect_op ::= UNION ALL */
   140886 {yymsp[-1].minor.yy4 = TK_ALL;}
   140887         break;
   140888       case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   140889 {
   140890 #if SELECTTRACE_ENABLED
   140891   Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
   140892 #endif
   140893   yymsp[-8].minor.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.yy314);
   140894 #if SELECTTRACE_ENABLED
   140895   /* Populate the Select.zSelName[] string that is used to help with
   140896   ** query planner debugging, to differentiate between multiple Select
   140897   ** objects in a complex query.
   140898   **
   140899   ** If the SELECT keyword is immediately followed by a C-style comment
   140900   ** then extract the first few alphanumeric characters from within that
   140901   ** comment to be the zSelName value.  Otherwise, the label is #N where
   140902   ** is an integer that is incremented with each SELECT statement seen.
   140903   */
   140904   if( yymsp[-8].minor.yy387!=0 ){
   140905     const char *z = s.z+6;
   140906     int i;
   140907     sqlite3_snprintf(sizeof(yymsp[-8].minor.yy387->zSelName), yymsp[-8].minor.yy387->zSelName, "#%d",
   140908                      ++pParse->nSelect);
   140909     while( z[0]==' ' ) z++;
   140910     if( z[0]=='/' && z[1]=='*' ){
   140911       z += 2;
   140912       while( z[0]==' ' ) z++;
   140913       for(i=0; sqlite3Isalnum(z[i]); i++){}
   140914       sqlite3_snprintf(sizeof(yymsp[-8].minor.yy387->zSelName), yymsp[-8].minor.yy387->zSelName, "%.*s", i, z);
   140915     }
   140916   }
   140917 #endif /* SELECTRACE_ENABLED */
   140918 }
   140919         break;
   140920       case 86: /* values ::= VALUES LP nexprlist RP */
   140921 {
   140922   yymsp[-3].minor.yy387 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values,0);
   140923 }
   140924         break;
   140925       case 87: /* values ::= values COMMA LP exprlist RP */
   140926 {
   140927   Select *pRight, *pLeft = yymsp[-4].minor.yy387;
   140928   pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values|SF_MultiValue,0);
   140929   if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
   140930   if( pRight ){
   140931     pRight->op = TK_ALL;
   140932     pRight->pPrior = pLeft;
   140933     yymsp[-4].minor.yy387 = pRight;
   140934   }else{
   140935     yymsp[-4].minor.yy387 = pLeft;
   140936   }
   140937 }
   140938         break;
   140939       case 88: /* distinct ::= DISTINCT */
   140940 {yymsp[0].minor.yy4 = SF_Distinct;}
   140941         break;
   140942       case 89: /* distinct ::= ALL */
   140943 {yymsp[0].minor.yy4 = SF_All;}
   140944         break;
   140945       case 91: /* sclp ::= */
   140946       case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
   140947       case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
   140948       case 201: /* exprlist ::= */ yytestcase(yyruleno==201);
   140949       case 204: /* paren_exprlist ::= */ yytestcase(yyruleno==204);
   140950       case 209: /* eidlist_opt ::= */ yytestcase(yyruleno==209);
   140951 {yymsp[1].minor.yy322 = 0;}
   140952         break;
   140953       case 92: /* selcollist ::= sclp scanpt expr scanpt as */
   140954 {
   140955    yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[-2].minor.yy314);
   140956    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[0].minor.yy0, 1);
   140957    sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy322,yymsp[-3].minor.yy336,yymsp[-1].minor.yy336);
   140958 }
   140959         break;
   140960       case 93: /* selcollist ::= sclp scanpt STAR */
   140961 {
   140962   Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
   140963   yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, p);
   140964 }
   140965         break;
   140966       case 94: /* selcollist ::= sclp scanpt nm DOT STAR */
   140967 {
   140968   Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
   140969   Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
   140970   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
   140971   yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, pDot);
   140972 }
   140973         break;
   140974       case 95: /* as ::= AS nm */
   140975       case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
   140976       case 223: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==223);
   140977       case 224: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==224);
   140978 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
   140979         break;
   140980       case 97: /* from ::= */
   140981 {yymsp[1].minor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy259));}
   140982         break;
   140983       case 98: /* from ::= FROM seltablist */
   140984 {
   140985   yymsp[-1].minor.yy259 = yymsp[0].minor.yy259;
   140986   sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy259);
   140987 }
   140988         break;
   140989       case 99: /* stl_prefix ::= seltablist joinop */
   140990 {
   140991    if( ALWAYS(yymsp[-1].minor.yy259 && yymsp[-1].minor.yy259->nSrc>0) ) yymsp[-1].minor.yy259->a[yymsp[-1].minor.yy259->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy4;
   140992 }
   140993         break;
   140994       case 100: /* stl_prefix ::= */
   140995 {yymsp[1].minor.yy259 = 0;}
   140996         break;
   140997       case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   140998 {
   140999   yymsp[-6].minor.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);
   141000   sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy259, &yymsp[-2].minor.yy0);
   141001 }
   141002         break;
   141003       case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
   141004 {
   141005   yymsp[-8].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy259,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
   141006   sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy259, yymsp[-4].minor.yy322);
   141007 }
   141008         break;
   141009       case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   141010 {
   141011     yymsp[-6].minor.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);
   141012   }
   141013         break;
   141014       case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   141015 {
   141016     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
   141017       yymsp[-6].minor.yy259 = yymsp[-4].minor.yy259;
   141018     }else if( yymsp[-4].minor.yy259->nSrc==1 ){
   141019       yymsp[-6].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
   141020       if( yymsp[-6].minor.yy259 ){
   141021         struct SrcList_item *pNew = &yymsp[-6].minor.yy259->a[yymsp[-6].minor.yy259->nSrc-1];
   141022         struct SrcList_item *pOld = yymsp[-4].minor.yy259->a;
   141023         pNew->zName = pOld->zName;
   141024         pNew->zDatabase = pOld->zDatabase;
   141025         pNew->pSelect = pOld->pSelect;
   141026         pOld->zName = pOld->zDatabase = 0;
   141027         pOld->pSelect = 0;
   141028       }
   141029       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy259);
   141030     }else{
   141031       Select *pSubquery;
   141032       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
   141033       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,SF_NestedFrom,0);
   141034       yymsp[-6].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
   141035     }
   141036   }
   141037         break;
   141038       case 105: /* dbnm ::= */
   141039       case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
   141040 {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
   141041         break;
   141042       case 107: /* fullname ::= nm dbnm */
   141043 {yymsp[-1].minor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
   141044         break;
   141045       case 108: /* joinop ::= COMMA|JOIN */
   141046 { yymsp[0].minor.yy4 = JT_INNER; }
   141047         break;
   141048       case 109: /* joinop ::= JOIN_KW JOIN */
   141049 {yymsp[-1].minor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
   141050         break;
   141051       case 110: /* joinop ::= JOIN_KW nm JOIN */
   141052 {yymsp[-2].minor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
   141053         break;
   141054       case 111: /* joinop ::= JOIN_KW nm nm JOIN */
   141055 {yymsp[-3].minor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
   141056         break;
   141057       case 112: /* on_opt ::= ON expr */
   141058       case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
   141059       case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
   141060       case 197: /* case_else ::= ELSE expr */ yytestcase(yyruleno==197);
   141061 {yymsp[-1].minor.yy314 = yymsp[0].minor.yy314;}
   141062         break;
   141063       case 113: /* on_opt ::= */
   141064       case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
   141065       case 130: /* limit_opt ::= */ yytestcase(yyruleno==130);
   141066       case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
   141067       case 198: /* case_else ::= */ yytestcase(yyruleno==198);
   141068       case 200: /* case_operand ::= */ yytestcase(yyruleno==200);
   141069 {yymsp[1].minor.yy314 = 0;}
   141070         break;
   141071       case 115: /* indexed_opt ::= INDEXED BY nm */
   141072 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
   141073         break;
   141074       case 116: /* indexed_opt ::= NOT INDEXED */
   141075 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
   141076         break;
   141077       case 117: /* using_opt ::= USING LP idlist RP */
   141078 {yymsp[-3].minor.yy384 = yymsp[-1].minor.yy384;}
   141079         break;
   141080       case 118: /* using_opt ::= */
   141081       case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146);
   141082 {yymsp[1].minor.yy384 = 0;}
   141083         break;
   141084       case 120: /* orderby_opt ::= ORDER BY sortlist */
   141085       case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
   141086 {yymsp[-2].minor.yy322 = yymsp[0].minor.yy322;}
   141087         break;
   141088       case 121: /* sortlist ::= sortlist COMMA expr sortorder */
   141089 {
   141090   yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
   141091   sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy322,yymsp[0].minor.yy4);
   141092 }
   141093         break;
   141094       case 122: /* sortlist ::= expr sortorder */
   141095 {
   141096   yymsp[-1].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314); /*A-overwrites-Y*/
   141097   sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy322,yymsp[0].minor.yy4);
   141098 }
   141099         break;
   141100       case 123: /* sortorder ::= ASC */
   141101 {yymsp[0].minor.yy4 = SQLITE_SO_ASC;}
   141102         break;
   141103       case 124: /* sortorder ::= DESC */
   141104 {yymsp[0].minor.yy4 = SQLITE_SO_DESC;}
   141105         break;
   141106       case 125: /* sortorder ::= */
   141107 {yymsp[1].minor.yy4 = SQLITE_SO_UNDEFINED;}
   141108         break;
   141109       case 131: /* limit_opt ::= LIMIT expr */
   141110 {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy314,0);}
   141111         break;
   141112       case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
   141113 {yymsp[-3].minor.yy314 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy314,yymsp[0].minor.yy314);}
   141114         break;
   141115       case 133: /* limit_opt ::= LIMIT expr COMMA expr */
   141116 {yymsp[-3].minor.yy314 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy314,yymsp[-2].minor.yy314);}
   141117         break;
   141118       case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
   141119 {
   141120   sqlite3WithPush(pParse, yymsp[-5].minor.yy451, 1);
   141121   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
   141122   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314,0,0);
   141123 }
   141124         break;
   141125       case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
   141126 {
   141127   sqlite3WithPush(pParse, yymsp[-7].minor.yy451, 1);
   141128   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
   141129   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
   141130   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy4,0,0);
   141131 }
   141132         break;
   141133       case 138: /* setlist ::= setlist COMMA nm EQ expr */
   141134 {
   141135   yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy314);
   141136   sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, 1);
   141137 }
   141138         break;
   141139       case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
   141140 {
   141141   yymsp[-6].minor.yy322 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy322, yymsp[-3].minor.yy384, yymsp[0].minor.yy314);
   141142 }
   141143         break;
   141144       case 140: /* setlist ::= nm EQ expr */
   141145 {
   141146   yylhsminor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy314);
   141147   sqlite3ExprListSetName(pParse, yylhsminor.yy322, &yymsp[-2].minor.yy0, 1);
   141148 }
   141149   yymsp[-2].minor.yy322 = yylhsminor.yy322;
   141150         break;
   141151       case 141: /* setlist ::= LP idlist RP EQ expr */
   141152 {
   141153   yymsp[-4].minor.yy322 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy384, yymsp[0].minor.yy314);
   141154 }
   141155         break;
   141156       case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
   141157 {
   141158   sqlite3WithPush(pParse, yymsp[-5].minor.yy451, 1);
   141159   sqlite3Insert(pParse, yymsp[-2].minor.yy259, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy4);
   141160 }
   141161         break;
   141162       case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
   141163 {
   141164   sqlite3WithPush(pParse, yymsp[-6].minor.yy451, 1);
   141165   sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy4);
   141166 }
   141167         break;
   141168       case 147: /* idlist_opt ::= LP idlist RP */
   141169 {yymsp[-2].minor.yy384 = yymsp[-1].minor.yy384;}
   141170         break;
   141171       case 148: /* idlist ::= idlist COMMA nm */
   141172 {yymsp[-2].minor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
   141173         break;
   141174       case 149: /* idlist ::= nm */
   141175 {yymsp[0].minor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
   141176         break;
   141177       case 150: /* expr ::= LP expr RP */
   141178 {yymsp[-2].minor.yy314 = yymsp[-1].minor.yy314;}
   141179         break;
   141180       case 151: /* expr ::= ID|INDEXED */
   141181       case 152: /* expr ::= JOIN_KW */ yytestcase(yyruleno==152);
   141182 {yymsp[0].minor.yy314=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
   141183         break;
   141184       case 153: /* expr ::= nm DOT nm */
   141185 {
   141186   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
   141187   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
   141188   yylhsminor.yy314 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
   141189 }
   141190   yymsp[-2].minor.yy314 = yylhsminor.yy314;
   141191         break;
   141192       case 154: /* expr ::= nm DOT nm DOT nm */
   141193 {
   141194   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
   141195   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
   141196   Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
   141197   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
   141198   yylhsminor.yy314 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
   141199 }
   141200   yymsp[-4].minor.yy314 = yylhsminor.yy314;
   141201         break;
   141202       case 155: /* term ::= NULL|FLOAT|BLOB */
   141203       case 156: /* term ::= STRING */ yytestcase(yyruleno==156);
   141204 {yymsp[0].minor.yy314=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
   141205         break;
   141206       case 157: /* term ::= INTEGER */
   141207 {
   141208   yylhsminor.yy314 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
   141209 }
   141210   yymsp[0].minor.yy314 = yylhsminor.yy314;
   141211         break;
   141212       case 158: /* expr ::= VARIABLE */
   141213 {
   141214   if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
   141215     u32 n = yymsp[0].minor.yy0.n;
   141216     yymsp[0].minor.yy314 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
   141217     sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy314, n);
   141218   }else{
   141219     /* When doing a nested parse, one can include terms in an expression
   141220     ** that look like this:   #1 #2 ...  These terms refer to registers
   141221     ** in the virtual machine.  #N is the N-th register. */
   141222     Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
   141223     assert( t.n>=2 );
   141224     if( pParse->nested==0 ){
   141225       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
   141226       yymsp[0].minor.yy314 = 0;
   141227     }else{
   141228       yymsp[0].minor.yy314 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
   141229       if( yymsp[0].minor.yy314 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy314->iTable);
   141230     }
   141231   }
   141232 }
   141233         break;
   141234       case 159: /* expr ::= expr COLLATE ID|STRING */
   141235 {
   141236   yymsp[-2].minor.yy314 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy314, &yymsp[0].minor.yy0, 1);
   141237 }
   141238         break;
   141239       case 160: /* expr ::= CAST LP expr AS typetoken RP */
   141240 {
   141241   yymsp[-5].minor.yy314 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
   141242   sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy314, yymsp[-3].minor.yy314, 0);
   141243 }
   141244         break;
   141245       case 161: /* expr ::= ID|INDEXED LP distinct exprlist RP */
   141246 {
   141247   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
   141248     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
   141249   }
   141250   yylhsminor.yy314 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
   141251   if( yymsp[-2].minor.yy4==SF_Distinct && yylhsminor.yy314 ){
   141252     yylhsminor.yy314->flags |= EP_Distinct;
   141253   }
   141254 }
   141255   yymsp[-4].minor.yy314 = yylhsminor.yy314;
   141256         break;
   141257       case 162: /* expr ::= ID|INDEXED LP STAR RP */
   141258 {
   141259   yylhsminor.yy314 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
   141260 }
   141261   yymsp[-3].minor.yy314 = yylhsminor.yy314;
   141262         break;
   141263       case 163: /* term ::= CTIME_KW */
   141264 {
   141265   yylhsminor.yy314 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
   141266 }
   141267   yymsp[0].minor.yy314 = yylhsminor.yy314;
   141268         break;
   141269       case 164: /* expr ::= LP nexprlist COMMA expr RP */
   141270 {
   141271   ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy314);
   141272   yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
   141273   if( yymsp[-4].minor.yy314 ){
   141274     yymsp[-4].minor.yy314->x.pList = pList;
   141275   }else{
   141276     sqlite3ExprListDelete(pParse->db, pList);
   141277   }
   141278 }
   141279         break;
   141280       case 165: /* expr ::= expr AND expr */
   141281       case 166: /* expr ::= expr OR expr */ yytestcase(yyruleno==166);
   141282       case 167: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==167);
   141283       case 168: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==168);
   141284       case 169: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==169);
   141285       case 170: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==170);
   141286       case 171: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==171);
   141287       case 172: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==172);
   141288 {yymsp[-2].minor.yy314=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy314,yymsp[0].minor.yy314);}
   141289         break;
   141290       case 173: /* likeop ::= NOT LIKE_KW|MATCH */
   141291 {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
   141292         break;
   141293       case 174: /* expr ::= expr likeop expr */
   141294 {
   141295   ExprList *pList;
   141296   int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
   141297   yymsp[-1].minor.yy0.n &= 0x7fffffff;
   141298   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy314);
   141299   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy314);
   141300   yymsp[-2].minor.yy314 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
   141301   if( bNot ) yymsp[-2].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy314, 0);
   141302   if( yymsp[-2].minor.yy314 ) yymsp[-2].minor.yy314->flags |= EP_InfixFunc;
   141303 }
   141304         break;
   141305       case 175: /* expr ::= expr likeop expr ESCAPE expr */
   141306 {
   141307   ExprList *pList;
   141308   int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
   141309   yymsp[-3].minor.yy0.n &= 0x7fffffff;
   141310   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy314);
   141311   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy314);
   141312   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy314);
   141313   yymsp[-4].minor.yy314 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
   141314   if( bNot ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
   141315   if( yymsp[-4].minor.yy314 ) yymsp[-4].minor.yy314->flags |= EP_InfixFunc;
   141316 }
   141317         break;
   141318       case 176: /* expr ::= expr ISNULL|NOTNULL */
   141319 {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy314,0);}
   141320         break;
   141321       case 177: /* expr ::= expr NOT NULL */
   141322 {yymsp[-2].minor.yy314 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy314,0);}
   141323         break;
   141324       case 178: /* expr ::= expr IS expr */
   141325 {
   141326   yymsp[-2].minor.yy314 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy314,yymsp[0].minor.yy314);
   141327   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy314, yymsp[-2].minor.yy314, TK_ISNULL);
   141328 }
   141329         break;
   141330       case 179: /* expr ::= expr IS NOT expr */
   141331 {
   141332   yymsp[-3].minor.yy314 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy314,yymsp[0].minor.yy314);
   141333   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy314, yymsp[-3].minor.yy314, TK_NOTNULL);
   141334 }
   141335         break;
   141336       case 180: /* expr ::= NOT expr */
   141337       case 181: /* expr ::= BITNOT expr */ yytestcase(yyruleno==181);
   141338 {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy314, 0);/*A-overwrites-B*/}
   141339         break;
   141340       case 182: /* expr ::= MINUS expr */
   141341 {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy314, 0);}
   141342         break;
   141343       case 183: /* expr ::= PLUS expr */
   141344 {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy314, 0);}
   141345         break;
   141346       case 184: /* between_op ::= BETWEEN */
   141347       case 187: /* in_op ::= IN */ yytestcase(yyruleno==187);
   141348 {yymsp[0].minor.yy4 = 0;}
   141349         break;
   141350       case 186: /* expr ::= expr between_op expr AND expr */
   141351 {
   141352   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy314);
   141353   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy314);
   141354   yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy314, 0);
   141355   if( yymsp[-4].minor.yy314 ){
   141356     yymsp[-4].minor.yy314->x.pList = pList;
   141357   }else{
   141358     sqlite3ExprListDelete(pParse->db, pList);
   141359   }
   141360   if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
   141361 }
   141362         break;
   141363       case 189: /* expr ::= expr in_op LP exprlist RP */
   141364 {
   141365     if( yymsp[-1].minor.yy322==0 ){
   141366       /* Expressions of the form
   141367       **
   141368       **      expr1 IN ()
   141369       **      expr1 NOT IN ()
   141370       **
   141371       ** simplify to constants 0 (false) and 1 (true), respectively,
   141372       ** regardless of the value of expr1.
   141373       */
   141374       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy314);
   141375       yymsp[-4].minor.yy314 = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy4],1);
   141376     }else if( yymsp[-1].minor.yy322->nExpr==1 ){
   141377       /* Expressions of the form:
   141378       **
   141379       **      expr1 IN (?1)
   141380       **      expr1 NOT IN (?2)
   141381       **
   141382       ** with exactly one value on the RHS can be simplified to something
   141383       ** like this:
   141384       **
   141385       **      expr1 == ?1
   141386       **      expr1 <> ?2
   141387       **
   141388       ** But, the RHS of the == or <> is marked with the EP_Generic flag
   141389       ** so that it may not contribute to the computation of comparison
   141390       ** affinity or the collating sequence to use for comparison.  Otherwise,
   141391       ** the semantics would be subtly different from IN or NOT IN.
   141392       */
   141393       Expr *pRHS = yymsp[-1].minor.yy322->a[0].pExpr;
   141394       yymsp[-1].minor.yy322->a[0].pExpr = 0;
   141395       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
   141396       /* pRHS cannot be NULL because a malloc error would have been detected
   141397       ** before now and control would have never reached this point */
   141398       if( ALWAYS(pRHS) ){
   141399         pRHS->flags &= ~EP_Collate;
   141400         pRHS->flags |= EP_Generic;
   141401       }
   141402       yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, yymsp[-3].minor.yy4 ? TK_NE : TK_EQ, yymsp[-4].minor.yy314, pRHS);
   141403     }else{
   141404       yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy314, 0);
   141405       if( yymsp[-4].minor.yy314 ){
   141406         yymsp[-4].minor.yy314->x.pList = yymsp[-1].minor.yy322;
   141407         sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy314);
   141408       }else{
   141409         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
   141410       }
   141411       if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
   141412     }
   141413   }
   141414         break;
   141415       case 190: /* expr ::= LP select RP */
   141416 {
   141417     yymsp[-2].minor.yy314 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
   141418     sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy314, yymsp[-1].minor.yy387);
   141419   }
   141420         break;
   141421       case 191: /* expr ::= expr in_op LP select RP */
   141422 {
   141423     yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy314, 0);
   141424     sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy314, yymsp[-1].minor.yy387);
   141425     if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
   141426   }
   141427         break;
   141428       case 192: /* expr ::= expr in_op nm dbnm paren_exprlist */
   141429 {
   141430     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
   141431     Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
   141432     if( yymsp[0].minor.yy322 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy322);
   141433     yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy314, 0);
   141434     sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy314, pSelect);
   141435     if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
   141436   }
   141437         break;
   141438       case 193: /* expr ::= EXISTS LP select RP */
   141439 {
   141440     Expr *p;
   141441     p = yymsp[-3].minor.yy314 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
   141442     sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy387);
   141443   }
   141444         break;
   141445       case 194: /* expr ::= CASE case_operand case_exprlist case_else END */
   141446 {
   141447   yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, 0);
   141448   if( yymsp[-4].minor.yy314 ){
   141449     yymsp[-4].minor.yy314->x.pList = yymsp[-1].minor.yy314 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[-1].minor.yy314) : yymsp[-2].minor.yy322;
   141450     sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy314);
   141451   }else{
   141452     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
   141453     sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy314);
   141454   }
   141455 }
   141456         break;
   141457       case 195: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
   141458 {
   141459   yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy314);
   141460   yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[0].minor.yy314);
   141461 }
   141462         break;
   141463       case 196: /* case_exprlist ::= WHEN expr THEN expr */
   141464 {
   141465   yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy314);
   141466   yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, yymsp[0].minor.yy314);
   141467 }
   141468         break;
   141469       case 199: /* case_operand ::= expr */
   141470 {yymsp[0].minor.yy314 = yymsp[0].minor.yy314; /*A-overwrites-X*/}
   141471         break;
   141472       case 202: /* nexprlist ::= nexprlist COMMA expr */
   141473 {yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy314);}
   141474         break;
   141475       case 203: /* nexprlist ::= expr */
   141476 {yymsp[0].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy314); /*A-overwrites-Y*/}
   141477         break;
   141478       case 205: /* paren_exprlist ::= LP exprlist RP */
   141479       case 210: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==210);
   141480 {yymsp[-2].minor.yy322 = yymsp[-1].minor.yy322;}
   141481         break;
   141482       case 206: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
   141483 {
   141484   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
   141485                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy4,
   141486                       &yymsp[-11].minor.yy0, yymsp[0].minor.yy314, SQLITE_SO_ASC, yymsp[-8].minor.yy4, SQLITE_IDXTYPE_APPDEF);
   141487 }
   141488         break;
   141489       case 207: /* uniqueflag ::= UNIQUE */
   141490       case 247: /* raisetype ::= ABORT */ yytestcase(yyruleno==247);
   141491 {yymsp[0].minor.yy4 = OE_Abort;}
   141492         break;
   141493       case 208: /* uniqueflag ::= */
   141494 {yymsp[1].minor.yy4 = OE_None;}
   141495         break;
   141496       case 211: /* eidlist ::= eidlist COMMA nm collate sortorder */
   141497 {
   141498   yymsp[-4].minor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4);
   141499 }
   141500         break;
   141501       case 212: /* eidlist ::= nm collate sortorder */
   141502 {
   141503   yymsp[-2].minor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4); /*A-overwrites-Y*/
   141504 }
   141505         break;
   141506       case 215: /* cmd ::= DROP INDEX ifexists fullname */
   141507 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
   141508         break;
   141509       case 216: /* cmd ::= VACUUM */
   141510 {sqlite3Vacuum(pParse,0);}
   141511         break;
   141512       case 217: /* cmd ::= VACUUM nm */
   141513 {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
   141514         break;
   141515       case 218: /* cmd ::= PRAGMA nm dbnm */
   141516 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
   141517         break;
   141518       case 219: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
   141519 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
   141520         break;
   141521       case 220: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
   141522 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
   141523         break;
   141524       case 221: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
   141525 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
   141526         break;
   141527       case 222: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
   141528 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
   141529         break;
   141530       case 225: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   141531 {
   141532   Token all;
   141533   all.z = yymsp[-3].minor.yy0.z;
   141534   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
   141535   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
   141536 }
   141537         break;
   141538       case 226: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   141539 {
   141540   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);
   141541   yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
   141542 }
   141543         break;
   141544       case 227: /* trigger_time ::= BEFORE|AFTER */
   141545 { yymsp[0].minor.yy4 = yymsp[0].major; /*A-overwrites-X*/ }
   141546         break;
   141547       case 228: /* trigger_time ::= INSTEAD OF */
   141548 { yymsp[-1].minor.yy4 = TK_INSTEAD;}
   141549         break;
   141550       case 229: /* trigger_time ::= */
   141551 { yymsp[1].minor.yy4 = TK_BEFORE; }
   141552         break;
   141553       case 230: /* trigger_event ::= DELETE|INSERT */
   141554       case 231: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==231);
   141555 {yymsp[0].minor.yy90.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy90.b = 0;}
   141556         break;
   141557       case 232: /* trigger_event ::= UPDATE OF idlist */
   141558 {yymsp[-2].minor.yy90.a = TK_UPDATE; yymsp[-2].minor.yy90.b = yymsp[0].minor.yy384;}
   141559         break;
   141560       case 233: /* when_clause ::= */
   141561       case 252: /* key_opt ::= */ yytestcase(yyruleno==252);
   141562 { yymsp[1].minor.yy314 = 0; }
   141563         break;
   141564       case 234: /* when_clause ::= WHEN expr */
   141565       case 253: /* key_opt ::= KEY expr */ yytestcase(yyruleno==253);
   141566 { yymsp[-1].minor.yy314 = yymsp[0].minor.yy314; }
   141567         break;
   141568       case 235: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   141569 {
   141570   assert( yymsp[-2].minor.yy203!=0 );
   141571   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
   141572   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
   141573 }
   141574         break;
   141575       case 236: /* trigger_cmd_list ::= trigger_cmd SEMI */
   141576 {
   141577   assert( yymsp[-1].minor.yy203!=0 );
   141578   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
   141579 }
   141580         break;
   141581       case 237: /* trnm ::= nm DOT nm */
   141582 {
   141583   yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
   141584   sqlite3ErrorMsg(pParse,
   141585         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
   141586         "statements within triggers");
   141587 }
   141588         break;
   141589       case 238: /* tridxby ::= INDEXED BY nm */
   141590 {
   141591   sqlite3ErrorMsg(pParse,
   141592         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
   141593         "within triggers");
   141594 }
   141595         break;
   141596       case 239: /* tridxby ::= NOT INDEXED */
   141597 {
   141598   sqlite3ErrorMsg(pParse,
   141599         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
   141600         "within triggers");
   141601 }
   141602         break;
   141603       case 240: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
   141604 {yylhsminor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy314, yymsp[-6].minor.yy4, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy336);}
   141605   yymsp[-7].minor.yy203 = yylhsminor.yy203;
   141606         break;
   141607       case 241: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select scanpt */
   141608 {yylhsminor.yy203 = sqlite3TriggerInsertStep(pParse->db,&yymsp[-3].minor.yy0,yymsp[-2].minor.yy384,yymsp[-1].minor.yy387,yymsp[-5].minor.yy4,yymsp[-6].minor.yy336,yymsp[0].minor.yy336);/*yylhsminor.yy203-overwrites-yymsp[-5].minor.yy4*/}
   141609   yymsp[-6].minor.yy203 = yylhsminor.yy203;
   141610         break;
   141611       case 242: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
   141612 {yylhsminor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy314, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy336);}
   141613   yymsp[-5].minor.yy203 = yylhsminor.yy203;
   141614         break;
   141615       case 243: /* trigger_cmd ::= scanpt select scanpt */
   141616 {yylhsminor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy387, yymsp[-2].minor.yy336, yymsp[0].minor.yy336); /*yylhsminor.yy203-overwrites-yymsp[-1].minor.yy387*/}
   141617   yymsp[-2].minor.yy203 = yylhsminor.yy203;
   141618         break;
   141619       case 244: /* expr ::= RAISE LP IGNORE RP */
   141620 {
   141621   yymsp[-3].minor.yy314 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
   141622   if( yymsp[-3].minor.yy314 ){
   141623     yymsp[-3].minor.yy314->affinity = OE_Ignore;
   141624   }
   141625 }
   141626         break;
   141627       case 245: /* expr ::= RAISE LP raisetype COMMA nm RP */
   141628 {
   141629   yymsp[-5].minor.yy314 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
   141630   if( yymsp[-5].minor.yy314 ) {
   141631     yymsp[-5].minor.yy314->affinity = (char)yymsp[-3].minor.yy4;
   141632   }
   141633 }
   141634         break;
   141635       case 246: /* raisetype ::= ROLLBACK */
   141636 {yymsp[0].minor.yy4 = OE_Rollback;}
   141637         break;
   141638       case 248: /* raisetype ::= FAIL */
   141639 {yymsp[0].minor.yy4 = OE_Fail;}
   141640         break;
   141641       case 249: /* cmd ::= DROP TRIGGER ifexists fullname */
   141642 {
   141643   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
   141644 }
   141645         break;
   141646       case 250: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   141647 {
   141648   sqlite3Attach(pParse, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, yymsp[0].minor.yy314);
   141649 }
   141650         break;
   141651       case 251: /* cmd ::= DETACH database_kw_opt expr */
   141652 {
   141653   sqlite3Detach(pParse, yymsp[0].minor.yy314);
   141654 }
   141655         break;
   141656       case 254: /* cmd ::= REINDEX */
   141657 {sqlite3Reindex(pParse, 0, 0);}
   141658         break;
   141659       case 255: /* cmd ::= REINDEX nm dbnm */
   141660 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   141661         break;
   141662       case 256: /* cmd ::= ANALYZE */
   141663 {sqlite3Analyze(pParse, 0, 0);}
   141664         break;
   141665       case 257: /* cmd ::= ANALYZE nm dbnm */
   141666 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   141667         break;
   141668       case 258: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
   141669 {
   141670   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
   141671 }
   141672         break;
   141673       case 259: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
   141674 {
   141675   yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
   141676   sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
   141677 }
   141678         break;
   141679       case 260: /* add_column_fullname ::= fullname */
   141680 {
   141681   disableLookaside(pParse);
   141682   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
   141683 }
   141684         break;
   141685       case 261: /* cmd ::= create_vtab */
   141686 {sqlite3VtabFinishParse(pParse,0);}
   141687         break;
   141688       case 262: /* cmd ::= create_vtab LP vtabarglist RP */
   141689 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
   141690         break;
   141691       case 263: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   141692 {
   141693     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy4);
   141694 }
   141695         break;
   141696       case 264: /* vtabarg ::= */
   141697 {sqlite3VtabArgInit(pParse);}
   141698         break;
   141699       case 265: /* vtabargtoken ::= ANY */
   141700       case 266: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==266);
   141701       case 267: /* lp ::= LP */ yytestcase(yyruleno==267);
   141702 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
   141703         break;
   141704       case 268: /* with ::= */
   141705 {yymsp[1].minor.yy451 = 0;}
   141706         break;
   141707       case 269: /* with ::= WITH wqlist */
   141708 { yymsp[-1].minor.yy451 = yymsp[0].minor.yy451; }
   141709         break;
   141710       case 270: /* with ::= WITH RECURSIVE wqlist */
   141711 { yymsp[-2].minor.yy451 = yymsp[0].minor.yy451; }
   141712         break;
   141713       case 271: /* wqlist ::= nm eidlist_opt AS LP select RP */
   141714 {
   141715   yymsp[-5].minor.yy451 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387); /*A-overwrites-X*/
   141716 }
   141717         break;
   141718       case 272: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
   141719 {
   141720   yymsp[-7].minor.yy451 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy451, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387);
   141721 }
   141722         break;
   141723       default:
   141724       /* (273) input ::= cmdlist */ yytestcase(yyruleno==273);
   141725       /* (274) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==274);
   141726       /* (275) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=275);
   141727       /* (276) ecmd ::= SEMI */ yytestcase(yyruleno==276);
   141728       /* (277) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==277);
   141729       /* (278) explain ::= */ yytestcase(yyruleno==278);
   141730       /* (279) trans_opt ::= */ yytestcase(yyruleno==279);
   141731       /* (280) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==280);
   141732       /* (281) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==281);
   141733       /* (282) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==282);
   141734       /* (283) savepoint_opt ::= */ yytestcase(yyruleno==283);
   141735       /* (284) cmd ::= create_table create_table_args */ yytestcase(yyruleno==284);
   141736       /* (285) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==285);
   141737       /* (286) columnlist ::= columnname carglist */ yytestcase(yyruleno==286);
   141738       /* (287) nm ::= ID|INDEXED */ yytestcase(yyruleno==287);
   141739       /* (288) nm ::= STRING */ yytestcase(yyruleno==288);
   141740       /* (289) nm ::= JOIN_KW */ yytestcase(yyruleno==289);
   141741       /* (290) typetoken ::= typename */ yytestcase(yyruleno==290);
   141742       /* (291) typename ::= ID|STRING */ yytestcase(yyruleno==291);
   141743       /* (292) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
   141744       /* (293) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=293);
   141745       /* (294) carglist ::= carglist ccons */ yytestcase(yyruleno==294);
   141746       /* (295) carglist ::= */ yytestcase(yyruleno==295);
   141747       /* (296) ccons ::= NULL onconf */ yytestcase(yyruleno==296);
   141748       /* (297) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==297);
   141749       /* (298) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==298);
   141750       /* (299) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=299);
   141751       /* (300) tconscomma ::= */ yytestcase(yyruleno==300);
   141752       /* (301) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=301);
   141753       /* (302) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=302);
   141754       /* (303) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=303);
   141755       /* (304) oneselect ::= values */ yytestcase(yyruleno==304);
   141756       /* (305) sclp ::= selcollist COMMA */ yytestcase(yyruleno==305);
   141757       /* (306) as ::= ID|STRING */ yytestcase(yyruleno==306);
   141758       /* (307) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=307);
   141759       /* (308) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==308);
   141760       /* (309) exprlist ::= nexprlist */ yytestcase(yyruleno==309);
   141761       /* (310) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=310);
   141762       /* (311) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=311);
   141763       /* (312) nmnum ::= ON */ yytestcase(yyruleno==312);
   141764       /* (313) nmnum ::= DELETE */ yytestcase(yyruleno==313);
   141765       /* (314) nmnum ::= DEFAULT */ yytestcase(yyruleno==314);
   141766       /* (315) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==315);
   141767       /* (316) foreach_clause ::= */ yytestcase(yyruleno==316);
   141768       /* (317) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==317);
   141769       /* (318) trnm ::= nm */ yytestcase(yyruleno==318);
   141770       /* (319) tridxby ::= */ yytestcase(yyruleno==319);
   141771       /* (320) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==320);
   141772       /* (321) database_kw_opt ::= */ yytestcase(yyruleno==321);
   141773       /* (322) kwcolumn_opt ::= */ yytestcase(yyruleno==322);
   141774       /* (323) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==323);
   141775       /* (324) vtabarglist ::= vtabarg */ yytestcase(yyruleno==324);
   141776       /* (325) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==325);
   141777       /* (326) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==326);
   141778       /* (327) anylist ::= */ yytestcase(yyruleno==327);
   141779       /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
   141780       /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
   141781         break;
   141782 /********** End reduce actions ************************************************/
   141783   };
   141784   assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
   141785   yygoto = yyRuleInfo[yyruleno].lhs;
   141786   yysize = yyRuleInfo[yyruleno].nrhs;
   141787   yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
   141788 
   141789   /* There are no SHIFTREDUCE actions on nonterminals because the table
   141790   ** generator has simplified them to pure REDUCE actions. */
   141791   assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
   141792 
   141793   /* It is not possible for a REDUCE to be followed by an error */
   141794   assert( yyact!=YY_ERROR_ACTION );
   141795 
   141796   yymsp += yysize+1;
   141797   yypParser->yytos = yymsp;
   141798   yymsp->stateno = (YYACTIONTYPE)yyact;
   141799   yymsp->major = (YYCODETYPE)yygoto;
   141800   yyTraceShift(yypParser, yyact, "... then shift");
   141801 }
   141802 
   141803 /*
   141804 ** The following code executes when the parse fails
   141805 */
   141806 #ifndef YYNOERRORRECOVERY
   141807 static void yy_parse_failed(
   141808   yyParser *yypParser           /* The parser */
   141809 ){
   141810   sqlite3ParserARG_FETCH;
   141811 #ifndef NDEBUG
   141812   if( yyTraceFILE ){
   141813     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
   141814   }
   141815 #endif
   141816   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
   141817   /* Here code is inserted which will be executed whenever the
   141818   ** parser fails */
   141819 /************ Begin %parse_failure code ***************************************/
   141820 /************ End %parse_failure code *****************************************/
   141821   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   141822 }
   141823 #endif /* YYNOERRORRECOVERY */
   141824 
   141825 /*
   141826 ** The following code executes when a syntax error first occurs.
   141827 */
   141828 static void yy_syntax_error(
   141829   yyParser *yypParser,           /* The parser */
   141830   int yymajor,                   /* The major type of the error token */
   141831   sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
   141832 ){
   141833   sqlite3ParserARG_FETCH;
   141834 #define TOKEN yyminor
   141835 /************ Begin %syntax_error code ****************************************/
   141836 
   141837   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
   141838   if( TOKEN.z[0] ){
   141839     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
   141840   }else{
   141841     sqlite3ErrorMsg(pParse, "incomplete input");
   141842   }
   141843 /************ End %syntax_error code ******************************************/
   141844   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   141845 }
   141846 
   141847 /*
   141848 ** The following is executed when the parser accepts
   141849 */
   141850 static void yy_accept(
   141851   yyParser *yypParser           /* The parser */
   141852 ){
   141853   sqlite3ParserARG_FETCH;
   141854 #ifndef NDEBUG
   141855   if( yyTraceFILE ){
   141856     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
   141857   }
   141858 #endif
   141859 #ifndef YYNOERRORRECOVERY
   141860   yypParser->yyerrcnt = -1;
   141861 #endif
   141862   assert( yypParser->yytos==yypParser->yystack );
   141863   /* Here code is inserted which will be executed whenever the
   141864   ** parser accepts */
   141865 /*********** Begin %parse_accept code *****************************************/
   141866 /*********** End %parse_accept code *******************************************/
   141867   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   141868 }
   141869 
   141870 /* The main parser program.
   141871 ** The first argument is a pointer to a structure obtained from
   141872 ** "sqlite3ParserAlloc" which describes the current state of the parser.
   141873 ** The second argument is the major token number.  The third is
   141874 ** the minor token.  The fourth optional argument is whatever the
   141875 ** user wants (and specified in the grammar) and is available for
   141876 ** use by the action routines.
   141877 **
   141878 ** Inputs:
   141879 ** <ul>
   141880 ** <li> A pointer to the parser (an opaque structure.)
   141881 ** <li> The major token number.
   141882 ** <li> The minor token number.
   141883 ** <li> An option argument of a grammar-specified type.
   141884 ** </ul>
   141885 **
   141886 ** Outputs:
   141887 ** None.
   141888 */
   141889 SQLITE_PRIVATE void sqlite3Parser(
   141890   void *yyp,                   /* The parser */
   141891   int yymajor,                 /* The major token code number */
   141892   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
   141893   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
   141894 ){
   141895   YYMINORTYPE yyminorunion;
   141896   unsigned int yyact;   /* The parser action. */
   141897 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   141898   int yyendofinput;     /* True if we are at the end of input */
   141899 #endif
   141900 #ifdef YYERRORSYMBOL
   141901   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
   141902 #endif
   141903   yyParser *yypParser;  /* The parser */
   141904 
   141905   yypParser = (yyParser*)yyp;
   141906   assert( yypParser->yytos!=0 );
   141907 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   141908   yyendofinput = (yymajor==0);
   141909 #endif
   141910   sqlite3ParserARG_STORE;
   141911 
   141912 #ifndef NDEBUG
   141913   if( yyTraceFILE ){
   141914     int stateno = yypParser->yytos->stateno;
   141915     if( stateno < YY_MIN_REDUCE ){
   141916       fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
   141917               yyTracePrompt,yyTokenName[yymajor],stateno);
   141918     }else{
   141919       fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
   141920               yyTracePrompt,yyTokenName[yymajor],stateno-YY_MIN_REDUCE);
   141921     }
   141922   }
   141923 #endif
   141924 
   141925   do{
   141926     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
   141927     if( yyact >= YY_MIN_REDUCE ){
   141928       yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,yyminor);
   141929     }else if( yyact <= YY_MAX_SHIFTREDUCE ){
   141930       yy_shift(yypParser,yyact,yymajor,yyminor);
   141931 #ifndef YYNOERRORRECOVERY
   141932       yypParser->yyerrcnt--;
   141933 #endif
   141934       yymajor = YYNOCODE;
   141935     }else if( yyact==YY_ACCEPT_ACTION ){
   141936       yypParser->yytos--;
   141937       yy_accept(yypParser);
   141938       return;
   141939     }else{
   141940       assert( yyact == YY_ERROR_ACTION );
   141941       yyminorunion.yy0 = yyminor;
   141942 #ifdef YYERRORSYMBOL
   141943       int yymx;
   141944 #endif
   141945 #ifndef NDEBUG
   141946       if( yyTraceFILE ){
   141947         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
   141948       }
   141949 #endif
   141950 #ifdef YYERRORSYMBOL
   141951       /* A syntax error has occurred.
   141952       ** The response to an error depends upon whether or not the
   141953       ** grammar defines an error token "ERROR".
   141954       **
   141955       ** This is what we do if the grammar does define ERROR:
   141956       **
   141957       **  * Call the %syntax_error function.
   141958       **
   141959       **  * Begin popping the stack until we enter a state where
   141960       **    it is legal to shift the error symbol, then shift
   141961       **    the error symbol.
   141962       **
   141963       **  * Set the error count to three.
   141964       **
   141965       **  * Begin accepting and shifting new tokens.  No new error
   141966       **    processing will occur until three tokens have been
   141967       **    shifted successfully.
   141968       **
   141969       */
   141970       if( yypParser->yyerrcnt<0 ){
   141971         yy_syntax_error(yypParser,yymajor,yyminor);
   141972       }
   141973       yymx = yypParser->yytos->major;
   141974       if( yymx==YYERRORSYMBOL || yyerrorhit ){
   141975 #ifndef NDEBUG
   141976         if( yyTraceFILE ){
   141977           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
   141978              yyTracePrompt,yyTokenName[yymajor]);
   141979         }
   141980 #endif
   141981         yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
   141982         yymajor = YYNOCODE;
   141983       }else{
   141984         while( yypParser->yytos >= yypParser->yystack
   141985             && yymx != YYERRORSYMBOL
   141986             && (yyact = yy_find_reduce_action(
   141987                         yypParser->yytos->stateno,
   141988                         YYERRORSYMBOL)) >= YY_MIN_REDUCE
   141989         ){
   141990           yy_pop_parser_stack(yypParser);
   141991         }
   141992         if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
   141993           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   141994           yy_parse_failed(yypParser);
   141995 #ifndef YYNOERRORRECOVERY
   141996           yypParser->yyerrcnt = -1;
   141997 #endif
   141998           yymajor = YYNOCODE;
   141999         }else if( yymx!=YYERRORSYMBOL ){
   142000           yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
   142001         }
   142002       }
   142003       yypParser->yyerrcnt = 3;
   142004       yyerrorhit = 1;
   142005 #elif defined(YYNOERRORRECOVERY)
   142006       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
   142007       ** do any kind of error recovery.  Instead, simply invoke the syntax
   142008       ** error routine and continue going as if nothing had happened.
   142009       **
   142010       ** Applications can set this macro (for example inside %include) if
   142011       ** they intend to abandon the parse upon the first syntax error seen.
   142012       */
   142013       yy_syntax_error(yypParser,yymajor, yyminor);
   142014       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   142015       yymajor = YYNOCODE;
   142016 
   142017 #else  /* YYERRORSYMBOL is not defined */
   142018       /* This is what we do if the grammar does not define ERROR:
   142019       **
   142020       **  * Report an error message, and throw away the input token.
   142021       **
   142022       **  * If the input token is $, then fail the parse.
   142023       **
   142024       ** As before, subsequent error messages are suppressed until
   142025       ** three input tokens have been successfully shifted.
   142026       */
   142027       if( yypParser->yyerrcnt<=0 ){
   142028         yy_syntax_error(yypParser,yymajor, yyminor);
   142029       }
   142030       yypParser->yyerrcnt = 3;
   142031       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   142032       if( yyendofinput ){
   142033         yy_parse_failed(yypParser);
   142034 #ifndef YYNOERRORRECOVERY
   142035         yypParser->yyerrcnt = -1;
   142036 #endif
   142037       }
   142038       yymajor = YYNOCODE;
   142039 #endif
   142040     }
   142041   }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
   142042 #ifndef NDEBUG
   142043   if( yyTraceFILE ){
   142044     yyStackEntry *i;
   142045     char cDiv = '[';
   142046     fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
   142047     for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
   142048       fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
   142049       cDiv = ' ';
   142050     }
   142051     fprintf(yyTraceFILE,"]\n");
   142052   }
   142053 #endif
   142054   return;
   142055 }
   142056 
   142057 /************** End of parse.c ***********************************************/
   142058 /************** Begin file tokenize.c ****************************************/
   142059 /*
   142060 ** 2001 September 15
   142061 **
   142062 ** The author disclaims copyright to this source code.  In place of
   142063 ** a legal notice, here is a blessing:
   142064 **
   142065 **    May you do good and not evil.
   142066 **    May you find forgiveness for yourself and forgive others.
   142067 **    May you share freely, never taking more than you give.
   142068 **
   142069 *************************************************************************
   142070 ** An tokenizer for SQL
   142071 **
   142072 ** This file contains C code that splits an SQL input string up into
   142073 ** individual tokens and sends those tokens one-by-one over to the
   142074 ** parser for analysis.
   142075 */
   142076 /* #include "sqliteInt.h" */
   142077 /* #include <stdlib.h> */
   142078 
   142079 /* Character classes for tokenizing
   142080 **
   142081 ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
   142082 ** using a lookup table, whereas a switch() directly on c uses a binary search.
   142083 ** The lookup table is much faster.  To maximize speed, and to ensure that
   142084 ** a lookup table is used, all of the classes need to be small integers and
   142085 ** all of them need to be used within the switch.
   142086 */
   142087 #define CC_X          0    /* The letter 'x', or start of BLOB literal */
   142088 #define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
   142089 #define CC_ID         2    /* unicode characters usable in IDs */
   142090 #define CC_DIGIT      3    /* Digits */
   142091 #define CC_DOLLAR     4    /* '$' */
   142092 #define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
   142093 #define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
   142094 #define CC_SPACE      7    /* Space characters */
   142095 #define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
   142096 #define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
   142097 #define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
   142098 #define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
   142099 #define CC_LT        12    /* '<'.  Part of < or <= or <> */
   142100 #define CC_GT        13    /* '>'.  Part of > or >= */
   142101 #define CC_EQ        14    /* '='.  Part of = or == */
   142102 #define CC_BANG      15    /* '!'.  Part of != */
   142103 #define CC_SLASH     16    /* '/'.  / or c-style comment */
   142104 #define CC_LP        17    /* '(' */
   142105 #define CC_RP        18    /* ')' */
   142106 #define CC_SEMI      19    /* ';' */
   142107 #define CC_PLUS      20    /* '+' */
   142108 #define CC_STAR      21    /* '*' */
   142109 #define CC_PERCENT   22    /* '%' */
   142110 #define CC_COMMA     23    /* ',' */
   142111 #define CC_AND       24    /* '&' */
   142112 #define CC_TILDA     25    /* '~' */
   142113 #define CC_DOT       26    /* '.' */
   142114 #define CC_ILLEGAL   27    /* Illegal character */
   142115 
   142116 static const unsigned char aiClass[] = {
   142117 #ifdef SQLITE_ASCII
   142118 /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
   142119 /* 0x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
   142120 /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
   142121 /* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
   142122 /* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
   142123 /* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
   142124 /* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
   142125 /* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
   142126 /* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
   142127 /* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   142128 /* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   142129 /* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   142130 /* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   142131 /* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   142132 /* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   142133 /* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   142134 /* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
   142135 #endif
   142136 #ifdef SQLITE_EBCDIC
   142137 /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
   142138 /* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
   142139 /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
   142140 /* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
   142141 /* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
   142142 /* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
   142143 /* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
   142144 /* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  6,
   142145 /* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
   142146 /* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
   142147 /* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
   142148 /* Ax */   27, 25,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
   142149 /* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
   142150 /* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
   142151 /* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
   142152 /* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
   142153 /* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
   142154 #endif
   142155 };
   142156 
   142157 /*
   142158 ** The charMap() macro maps alphabetic characters (only) into their
   142159 ** lower-case ASCII equivalent.  On ASCII machines, this is just
   142160 ** an upper-to-lower case map.  On EBCDIC machines we also need
   142161 ** to adjust the encoding.  The mapping is only valid for alphabetics
   142162 ** which are the only characters for which this feature is used.
   142163 **
   142164 ** Used by keywordhash.h
   142165 */
   142166 #ifdef SQLITE_ASCII
   142167 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
   142168 #endif
   142169 #ifdef SQLITE_EBCDIC
   142170 # define charMap(X) ebcdicToAscii[(unsigned char)X]
   142171 const unsigned char ebcdicToAscii[] = {
   142172 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   142173    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   142174    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   142175    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   142176    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   142177    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   142178    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   142179    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   142180    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   142181    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   142182    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   142183    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   142184    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   142185    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   142186    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   142187    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   142188    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
   142189 };
   142190 #endif
   142191 
   142192 /*
   142193 ** The sqlite3KeywordCode function looks up an identifier to determine if
   142194 ** it is a keyword.  If it is a keyword, the token code of that keyword is
   142195 ** returned.  If the input is not a keyword, TK_ID is returned.
   142196 **
   142197 ** The implementation of this routine was generated by a program,
   142198 ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
   142199 ** The output of the mkkeywordhash.c program is written into a file
   142200 ** named keywordhash.h and then included into this source file by
   142201 ** the #include below.
   142202 */
   142203 /************** Include keywordhash.h in the middle of tokenize.c ************/
   142204 /************** Begin file keywordhash.h *************************************/
   142205 /***** This file contains automatically generated code ******
   142206 **
   142207 ** The code in this file has been automatically generated by
   142208 **
   142209 **   sqlite/tool/mkkeywordhash.c
   142210 **
   142211 ** The code in this file implements a function that determines whether
   142212 ** or not a given identifier is really an SQL keyword.  The same thing
   142213 ** might be implemented more directly using a hand-written hash table.
   142214 ** But by using this automatically generated code, the size of the code
   142215 ** is substantially reduced.  This is important for embedded applications
   142216 ** on platforms with limited memory.
   142217 */
   142218 /* Hash score: 182 */
   142219 /* zKWText[] encodes 834 bytes of keyword text in 554 bytes */
   142220 /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
   142221 /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
   142222 /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
   142223 /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
   142224 /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
   142225 /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
   142226 /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
   142227 /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
   142228 /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
   142229 /*   VACUUMVIEWINITIALLY                                                */
   142230 static const char zKWText[553] = {
   142231   'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   142232   'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   142233   'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
   142234   'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
   142235   'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
   142236   'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
   142237   'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
   142238   'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
   142239   'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
   142240   'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
   142241   'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
   142242   'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
   142243   'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
   142244   'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
   142245   'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
   142246   'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
   142247   'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
   142248   'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
   142249   'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
   142250   'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
   142251   'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
   142252   'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
   142253   'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
   142254   'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
   142255   'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
   142256   'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
   142257   'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
   142258   'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
   142259   'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
   142260   'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
   142261   'V','I','E','W','I','N','I','T','I','A','L','L','Y',
   142262 };
   142263 /* aKWHash[i] is the hash value for the i-th keyword */
   142264 static const unsigned char aKWHash[127] = {
   142265     76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
   142266     42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
   142267    121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
   142268      0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
   142269      0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
   142270     96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
   142271    100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
   142272     39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
   142273     62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
   142274     29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
   142275 };
   142276 /* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
   142277 ** then the i-th keyword has no more hash collisions.  Otherwise,
   142278 ** the next keyword with the same hash is aKWHash[i]-1. */
   142279 static const unsigned char aKWNext[124] = {
   142280      0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
   142281      0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
   142282      0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
   142283      0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
   142284      0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
   142285      0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
   142286      0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
   142287     10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
   142288      0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
   142289     73,  83,   0,  35,  68,   0,   0,
   142290 };
   142291 /* aKWLen[i] is the length (in bytes) of the i-th keyword */
   142292 static const unsigned char aKWLen[124] = {
   142293      7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
   142294      7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
   142295     11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
   142296      4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
   142297      6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
   142298      7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
   142299      7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
   142300     13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
   142301      2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
   142302      3,   5,   5,   6,   4,   9,   3,
   142303 };
   142304 /* aKWOffset[i] is the index into zKWText[] of the start of
   142305 ** the text for the i-th keyword. */
   142306 static const unsigned short int aKWOffset[124] = {
   142307      0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
   142308     36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
   142309     86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
   142310    159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
   142311    199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
   142312    250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
   142313    320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
   142314    387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
   142315    460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
   142316    521, 524, 529, 534, 540, 544, 549,
   142317 };
   142318 /* aKWCode[i] is the parser symbol code for the i-th keyword */
   142319 static const unsigned char aKWCode[124] = {
   142320   TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
   142321   TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
   142322   TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
   142323   TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
   142324   TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
   142325   TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
   142326   TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
   142327   TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
   142328   TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
   142329   TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
   142330   TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
   142331   TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
   142332   TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
   142333   TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
   142334   TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
   142335   TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
   142336   TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
   142337   TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
   142338   TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
   142339   TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
   142340   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
   142341   TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
   142342   TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
   142343   TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
   142344   TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
   142345 };
   142346 /* Check to see if z[0..n-1] is a keyword. If it is, write the
   142347 ** parser symbol code for that keyword into *pType.  Always
   142348 ** return the integer n (the length of the token). */
   142349 static int keywordCode(const char *z, int n, int *pType){
   142350   int i, j;
   142351   const char *zKW;
   142352   if( n>=2 ){
   142353     i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
   142354     for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
   142355       if( aKWLen[i]!=n ) continue;
   142356       j = 0;
   142357       zKW = &zKWText[aKWOffset[i]];
   142358 #ifdef SQLITE_ASCII
   142359       while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
   142360 #endif
   142361 #ifdef SQLITE_EBCDIC
   142362       while( j<n && toupper(z[j])==zKW[j] ){ j++; }
   142363 #endif
   142364       if( j<n ) continue;
   142365       testcase( i==0 ); /* REINDEX */
   142366       testcase( i==1 ); /* INDEXED */
   142367       testcase( i==2 ); /* INDEX */
   142368       testcase( i==3 ); /* DESC */
   142369       testcase( i==4 ); /* ESCAPE */
   142370       testcase( i==5 ); /* EACH */
   142371       testcase( i==6 ); /* CHECK */
   142372       testcase( i==7 ); /* KEY */
   142373       testcase( i==8 ); /* BEFORE */
   142374       testcase( i==9 ); /* FOREIGN */
   142375       testcase( i==10 ); /* FOR */
   142376       testcase( i==11 ); /* IGNORE */
   142377       testcase( i==12 ); /* REGEXP */
   142378       testcase( i==13 ); /* EXPLAIN */
   142379       testcase( i==14 ); /* INSTEAD */
   142380       testcase( i==15 ); /* ADD */
   142381       testcase( i==16 ); /* DATABASE */
   142382       testcase( i==17 ); /* AS */
   142383       testcase( i==18 ); /* SELECT */
   142384       testcase( i==19 ); /* TABLE */
   142385       testcase( i==20 ); /* LEFT */
   142386       testcase( i==21 ); /* THEN */
   142387       testcase( i==22 ); /* END */
   142388       testcase( i==23 ); /* DEFERRABLE */
   142389       testcase( i==24 ); /* ELSE */
   142390       testcase( i==25 ); /* EXCEPT */
   142391       testcase( i==26 ); /* TRANSACTION */
   142392       testcase( i==27 ); /* ACTION */
   142393       testcase( i==28 ); /* ON */
   142394       testcase( i==29 ); /* NATURAL */
   142395       testcase( i==30 ); /* ALTER */
   142396       testcase( i==31 ); /* RAISE */
   142397       testcase( i==32 ); /* EXCLUSIVE */
   142398       testcase( i==33 ); /* EXISTS */
   142399       testcase( i==34 ); /* SAVEPOINT */
   142400       testcase( i==35 ); /* INTERSECT */
   142401       testcase( i==36 ); /* TRIGGER */
   142402       testcase( i==37 ); /* REFERENCES */
   142403       testcase( i==38 ); /* CONSTRAINT */
   142404       testcase( i==39 ); /* INTO */
   142405       testcase( i==40 ); /* OFFSET */
   142406       testcase( i==41 ); /* OF */
   142407       testcase( i==42 ); /* SET */
   142408       testcase( i==43 ); /* TEMPORARY */
   142409       testcase( i==44 ); /* TEMP */
   142410       testcase( i==45 ); /* OR */
   142411       testcase( i==46 ); /* UNIQUE */
   142412       testcase( i==47 ); /* QUERY */
   142413       testcase( i==48 ); /* WITHOUT */
   142414       testcase( i==49 ); /* WITH */
   142415       testcase( i==50 ); /* OUTER */
   142416       testcase( i==51 ); /* RELEASE */
   142417       testcase( i==52 ); /* ATTACH */
   142418       testcase( i==53 ); /* HAVING */
   142419       testcase( i==54 ); /* GROUP */
   142420       testcase( i==55 ); /* UPDATE */
   142421       testcase( i==56 ); /* BEGIN */
   142422       testcase( i==57 ); /* INNER */
   142423       testcase( i==58 ); /* RECURSIVE */
   142424       testcase( i==59 ); /* BETWEEN */
   142425       testcase( i==60 ); /* NOTNULL */
   142426       testcase( i==61 ); /* NOT */
   142427       testcase( i==62 ); /* NO */
   142428       testcase( i==63 ); /* NULL */
   142429       testcase( i==64 ); /* LIKE */
   142430       testcase( i==65 ); /* CASCADE */
   142431       testcase( i==66 ); /* ASC */
   142432       testcase( i==67 ); /* DELETE */
   142433       testcase( i==68 ); /* CASE */
   142434       testcase( i==69 ); /* COLLATE */
   142435       testcase( i==70 ); /* CREATE */
   142436       testcase( i==71 ); /* CURRENT_DATE */
   142437       testcase( i==72 ); /* DETACH */
   142438       testcase( i==73 ); /* IMMEDIATE */
   142439       testcase( i==74 ); /* JOIN */
   142440       testcase( i==75 ); /* INSERT */
   142441       testcase( i==76 ); /* MATCH */
   142442       testcase( i==77 ); /* PLAN */
   142443       testcase( i==78 ); /* ANALYZE */
   142444       testcase( i==79 ); /* PRAGMA */
   142445       testcase( i==80 ); /* ABORT */
   142446       testcase( i==81 ); /* VALUES */
   142447       testcase( i==82 ); /* VIRTUAL */
   142448       testcase( i==83 ); /* LIMIT */
   142449       testcase( i==84 ); /* WHEN */
   142450       testcase( i==85 ); /* WHERE */
   142451       testcase( i==86 ); /* RENAME */
   142452       testcase( i==87 ); /* AFTER */
   142453       testcase( i==88 ); /* REPLACE */
   142454       testcase( i==89 ); /* AND */
   142455       testcase( i==90 ); /* DEFAULT */
   142456       testcase( i==91 ); /* AUTOINCREMENT */
   142457       testcase( i==92 ); /* TO */
   142458       testcase( i==93 ); /* IN */
   142459       testcase( i==94 ); /* CAST */
   142460       testcase( i==95 ); /* COLUMN */
   142461       testcase( i==96 ); /* COMMIT */
   142462       testcase( i==97 ); /* CONFLICT */
   142463       testcase( i==98 ); /* CROSS */
   142464       testcase( i==99 ); /* CURRENT_TIMESTAMP */
   142465       testcase( i==100 ); /* CURRENT_TIME */
   142466       testcase( i==101 ); /* PRIMARY */
   142467       testcase( i==102 ); /* DEFERRED */
   142468       testcase( i==103 ); /* DISTINCT */
   142469       testcase( i==104 ); /* IS */
   142470       testcase( i==105 ); /* DROP */
   142471       testcase( i==106 ); /* FAIL */
   142472       testcase( i==107 ); /* FROM */
   142473       testcase( i==108 ); /* FULL */
   142474       testcase( i==109 ); /* GLOB */
   142475       testcase( i==110 ); /* BY */
   142476       testcase( i==111 ); /* IF */
   142477       testcase( i==112 ); /* ISNULL */
   142478       testcase( i==113 ); /* ORDER */
   142479       testcase( i==114 ); /* RESTRICT */
   142480       testcase( i==115 ); /* RIGHT */
   142481       testcase( i==116 ); /* ROLLBACK */
   142482       testcase( i==117 ); /* ROW */
   142483       testcase( i==118 ); /* UNION */
   142484       testcase( i==119 ); /* USING */
   142485       testcase( i==120 ); /* VACUUM */
   142486       testcase( i==121 ); /* VIEW */
   142487       testcase( i==122 ); /* INITIALLY */
   142488       testcase( i==123 ); /* ALL */
   142489       *pType = aKWCode[i];
   142490       break;
   142491     }
   142492   }
   142493   return n;
   142494 }
   142495 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   142496   int id = TK_ID;
   142497   keywordCode((char*)z, n, &id);
   142498   return id;
   142499 }
   142500 #define SQLITE_N_KEYWORD 124
   142501 
   142502 /************** End of keywordhash.h *****************************************/
   142503 /************** Continuing where we left off in tokenize.c *******************/
   142504 
   142505 
   142506 /*
   142507 ** If X is a character that can be used in an identifier then
   142508 ** IdChar(X) will be true.  Otherwise it is false.
   142509 **
   142510 ** For ASCII, any character with the high-order bit set is
   142511 ** allowed in an identifier.  For 7-bit characters,
   142512 ** sqlite3IsIdChar[X] must be 1.
   142513 **
   142514 ** For EBCDIC, the rules are more complex but have the same
   142515 ** end result.
   142516 **
   142517 ** Ticket #1066.  the SQL standard does not allow '$' in the
   142518 ** middle of identifiers.  But many SQL implementations do.
   142519 ** SQLite will allow '$' in identifiers for compatibility.
   142520 ** But the feature is undocumented.
   142521 */
   142522 #ifdef SQLITE_ASCII
   142523 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   142524 #endif
   142525 #ifdef SQLITE_EBCDIC
   142526 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
   142527 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   142528     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
   142529     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
   142530     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
   142531     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
   142532     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
   142533     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
   142534     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
   142535     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
   142536     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
   142537     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   142538     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   142539     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   142540 };
   142541 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   142542 #endif
   142543 
   142544 /* Make the IdChar function accessible from ctime.c */
   142545 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   142546 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
   142547 #endif
   142548 
   142549 
   142550 /*
   142551 ** Return the length (in bytes) of the token that begins at z[0].
   142552 ** Store the token type in *tokenType before returning.
   142553 */
   142554 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
   142555   int i, c;
   142556   switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
   142557                           ** of the token. See the comment on the CC_ defines
   142558                           ** above. */
   142559     case CC_SPACE: {
   142560       testcase( z[0]==' ' );
   142561       testcase( z[0]=='\t' );
   142562       testcase( z[0]=='\n' );
   142563       testcase( z[0]=='\f' );
   142564       testcase( z[0]=='\r' );
   142565       for(i=1; sqlite3Isspace(z[i]); i++){}
   142566       *tokenType = TK_SPACE;
   142567       return i;
   142568     }
   142569     case CC_MINUS: {
   142570       if( z[1]=='-' ){
   142571         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   142572         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   142573         return i;
   142574       }
   142575       *tokenType = TK_MINUS;
   142576       return 1;
   142577     }
   142578     case CC_LP: {
   142579       *tokenType = TK_LP;
   142580       return 1;
   142581     }
   142582     case CC_RP: {
   142583       *tokenType = TK_RP;
   142584       return 1;
   142585     }
   142586     case CC_SEMI: {
   142587       *tokenType = TK_SEMI;
   142588       return 1;
   142589     }
   142590     case CC_PLUS: {
   142591       *tokenType = TK_PLUS;
   142592       return 1;
   142593     }
   142594     case CC_STAR: {
   142595       *tokenType = TK_STAR;
   142596       return 1;
   142597     }
   142598     case CC_SLASH: {
   142599       if( z[1]!='*' || z[2]==0 ){
   142600         *tokenType = TK_SLASH;
   142601         return 1;
   142602       }
   142603       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   142604       if( c ) i++;
   142605       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   142606       return i;
   142607     }
   142608     case CC_PERCENT: {
   142609       *tokenType = TK_REM;
   142610       return 1;
   142611     }
   142612     case CC_EQ: {
   142613       *tokenType = TK_EQ;
   142614       return 1 + (z[1]=='=');
   142615     }
   142616     case CC_LT: {
   142617       if( (c=z[1])=='=' ){
   142618         *tokenType = TK_LE;
   142619         return 2;
   142620       }else if( c=='>' ){
   142621         *tokenType = TK_NE;
   142622         return 2;
   142623       }else if( c=='<' ){
   142624         *tokenType = TK_LSHIFT;
   142625         return 2;
   142626       }else{
   142627         *tokenType = TK_LT;
   142628         return 1;
   142629       }
   142630     }
   142631     case CC_GT: {
   142632       if( (c=z[1])=='=' ){
   142633         *tokenType = TK_GE;
   142634         return 2;
   142635       }else if( c=='>' ){
   142636         *tokenType = TK_RSHIFT;
   142637         return 2;
   142638       }else{
   142639         *tokenType = TK_GT;
   142640         return 1;
   142641       }
   142642     }
   142643     case CC_BANG: {
   142644       if( z[1]!='=' ){
   142645         *tokenType = TK_ILLEGAL;
   142646         return 1;
   142647       }else{
   142648         *tokenType = TK_NE;
   142649         return 2;
   142650       }
   142651     }
   142652     case CC_PIPE: {
   142653       if( z[1]!='|' ){
   142654         *tokenType = TK_BITOR;
   142655         return 1;
   142656       }else{
   142657         *tokenType = TK_CONCAT;
   142658         return 2;
   142659       }
   142660     }
   142661     case CC_COMMA: {
   142662       *tokenType = TK_COMMA;
   142663       return 1;
   142664     }
   142665     case CC_AND: {
   142666       *tokenType = TK_BITAND;
   142667       return 1;
   142668     }
   142669     case CC_TILDA: {
   142670       *tokenType = TK_BITNOT;
   142671       return 1;
   142672     }
   142673     case CC_QUOTE: {
   142674       int delim = z[0];
   142675       testcase( delim=='`' );
   142676       testcase( delim=='\'' );
   142677       testcase( delim=='"' );
   142678       for(i=1; (c=z[i])!=0; i++){
   142679         if( c==delim ){
   142680           if( z[i+1]==delim ){
   142681             i++;
   142682           }else{
   142683             break;
   142684           }
   142685         }
   142686       }
   142687       if( c=='\'' ){
   142688         *tokenType = TK_STRING;
   142689         return i+1;
   142690       }else if( c!=0 ){
   142691         *tokenType = TK_ID;
   142692         return i+1;
   142693       }else{
   142694         *tokenType = TK_ILLEGAL;
   142695         return i;
   142696       }
   142697     }
   142698     case CC_DOT: {
   142699 #ifndef SQLITE_OMIT_FLOATING_POINT
   142700       if( !sqlite3Isdigit(z[1]) )
   142701 #endif
   142702       {
   142703         *tokenType = TK_DOT;
   142704         return 1;
   142705       }
   142706       /* If the next character is a digit, this is a floating point
   142707       ** number that begins with ".".  Fall thru into the next case */
   142708     }
   142709     case CC_DIGIT: {
   142710       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
   142711       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
   142712       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
   142713       testcase( z[0]=='9' );
   142714       *tokenType = TK_INTEGER;
   142715 #ifndef SQLITE_OMIT_HEX_INTEGER
   142716       if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
   142717         for(i=3; sqlite3Isxdigit(z[i]); i++){}
   142718         return i;
   142719       }
   142720 #endif
   142721       for(i=0; sqlite3Isdigit(z[i]); i++){}
   142722 #ifndef SQLITE_OMIT_FLOATING_POINT
   142723       if( z[i]=='.' ){
   142724         i++;
   142725         while( sqlite3Isdigit(z[i]) ){ i++; }
   142726         *tokenType = TK_FLOAT;
   142727       }
   142728       if( (z[i]=='e' || z[i]=='E') &&
   142729            ( sqlite3Isdigit(z[i+1])
   142730             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
   142731            )
   142732       ){
   142733         i += 2;
   142734         while( sqlite3Isdigit(z[i]) ){ i++; }
   142735         *tokenType = TK_FLOAT;
   142736       }
   142737 #endif
   142738       while( IdChar(z[i]) ){
   142739         *tokenType = TK_ILLEGAL;
   142740         i++;
   142741       }
   142742       return i;
   142743     }
   142744     case CC_QUOTE2: {
   142745       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
   142746       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
   142747       return i;
   142748     }
   142749     case CC_VARNUM: {
   142750       *tokenType = TK_VARIABLE;
   142751       for(i=1; sqlite3Isdigit(z[i]); i++){}
   142752       return i;
   142753     }
   142754     case CC_DOLLAR:
   142755     case CC_VARALPHA: {
   142756       int n = 0;
   142757       testcase( z[0]=='$' );  testcase( z[0]=='@' );
   142758       testcase( z[0]==':' );  testcase( z[0]=='#' );
   142759       *tokenType = TK_VARIABLE;
   142760       for(i=1; (c=z[i])!=0; i++){
   142761         if( IdChar(c) ){
   142762           n++;
   142763 #ifndef SQLITE_OMIT_TCL_VARIABLE
   142764         }else if( c=='(' && n>0 ){
   142765           do{
   142766             i++;
   142767           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
   142768           if( c==')' ){
   142769             i++;
   142770           }else{
   142771             *tokenType = TK_ILLEGAL;
   142772           }
   142773           break;
   142774         }else if( c==':' && z[i+1]==':' ){
   142775           i++;
   142776 #endif
   142777         }else{
   142778           break;
   142779         }
   142780       }
   142781       if( n==0 ) *tokenType = TK_ILLEGAL;
   142782       return i;
   142783     }
   142784     case CC_KYWD: {
   142785       for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
   142786       if( IdChar(z[i]) ){
   142787         /* This token started out using characters that can appear in keywords,
   142788         ** but z[i] is a character not allowed within keywords, so this must
   142789         ** be an identifier instead */
   142790         i++;
   142791         break;
   142792       }
   142793       *tokenType = TK_ID;
   142794       return keywordCode((char*)z, i, tokenType);
   142795     }
   142796     case CC_X: {
   142797 #ifndef SQLITE_OMIT_BLOB_LITERAL
   142798       testcase( z[0]=='x' ); testcase( z[0]=='X' );
   142799       if( z[1]=='\'' ){
   142800         *tokenType = TK_BLOB;
   142801         for(i=2; sqlite3Isxdigit(z[i]); i++){}
   142802         if( z[i]!='\'' || i%2 ){
   142803           *tokenType = TK_ILLEGAL;
   142804           while( z[i] && z[i]!='\'' ){ i++; }
   142805         }
   142806         if( z[i] ) i++;
   142807         return i;
   142808       }
   142809 #endif
   142810       /* If it is not a BLOB literal, then it must be an ID, since no
   142811       ** SQL keywords start with the letter 'x'.  Fall through */
   142812     }
   142813     case CC_ID: {
   142814       i = 1;
   142815       break;
   142816     }
   142817     default: {
   142818       *tokenType = TK_ILLEGAL;
   142819       return 1;
   142820     }
   142821   }
   142822   while( IdChar(z[i]) ){ i++; }
   142823   *tokenType = TK_ID;
   142824   return i;
   142825 }
   142826 
   142827 /*
   142828 ** Run the parser on the given SQL string.  The parser structure is
   142829 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
   142830 ** then an and attempt is made to write an error message into
   142831 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
   142832 ** error message.
   142833 */
   142834 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   142835   int nErr = 0;                   /* Number of errors encountered */
   142836   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   142837   int n = 0;                      /* Length of the next token token */
   142838   int tokenType;                  /* type of the next token */
   142839   int lastTokenParsed = -1;       /* type of the previous token */
   142840   sqlite3 *db = pParse->db;       /* The database connection */
   142841   int mxSqlLen;                   /* Max length of an SQL string */
   142842 #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
   142843   yyParser sEngine;    /* Space to hold the Lemon-generated Parser object */
   142844 #endif
   142845 
   142846   assert( zSql!=0 );
   142847   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   142848   if( db->nVdbeActive==0 ){
   142849     db->u1.isInterrupted = 0;
   142850   }
   142851   pParse->rc = SQLITE_OK;
   142852   pParse->zTail = zSql;
   142853   assert( pzErrMsg!=0 );
   142854   /* sqlite3ParserTrace(stdout, "parser: "); */
   142855 #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
   142856   pEngine = &sEngine;
   142857   sqlite3ParserInit(pEngine);
   142858 #else
   142859   pEngine = sqlite3ParserAlloc(sqlite3Malloc);
   142860   if( pEngine==0 ){
   142861     sqlite3OomFault(db);
   142862     return SQLITE_NOMEM_BKPT;
   142863   }
   142864 #endif
   142865   assert( pParse->pNewTable==0 );
   142866   assert( pParse->pNewTrigger==0 );
   142867   assert( pParse->nVar==0 );
   142868   assert( pParse->pVList==0 );
   142869   while( 1 ){
   142870     if( zSql[0]!=0 ){
   142871       n = sqlite3GetToken((u8*)zSql, &tokenType);
   142872       mxSqlLen -= n;
   142873       if( mxSqlLen<0 ){
   142874         pParse->rc = SQLITE_TOOBIG;
   142875         break;
   142876       }
   142877     }else{
   142878       /* Upon reaching the end of input, call the parser two more times
   142879       ** with tokens TK_SEMI and 0, in that order. */
   142880       if( lastTokenParsed==TK_SEMI ){
   142881         tokenType = 0;
   142882       }else if( lastTokenParsed==0 ){
   142883         break;
   142884       }else{
   142885         tokenType = TK_SEMI;
   142886       }
   142887       n = 0;
   142888     }
   142889     if( tokenType>=TK_SPACE ){
   142890       assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
   142891       if( db->u1.isInterrupted ){
   142892         pParse->rc = SQLITE_INTERRUPT;
   142893         break;
   142894       }
   142895       if( tokenType==TK_ILLEGAL ){
   142896         sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
   142897         break;
   142898       }
   142899       zSql += n;
   142900     }else{
   142901       pParse->sLastToken.z = zSql;
   142902       pParse->sLastToken.n = n;
   142903       sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   142904       lastTokenParsed = tokenType;
   142905       zSql += n;
   142906       if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
   142907     }
   142908   }
   142909   assert( nErr==0 );
   142910   pParse->zTail = zSql;
   142911 #ifdef YYTRACKMAXSTACKDEPTH
   142912   sqlite3_mutex_enter(sqlite3MallocMutex());
   142913   sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
   142914       sqlite3ParserStackPeak(pEngine)
   142915   );
   142916   sqlite3_mutex_leave(sqlite3MallocMutex());
   142917 #endif /* YYDEBUG */
   142918 #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
   142919   sqlite3ParserFinalize(pEngine);
   142920 #else
   142921   sqlite3ParserFree(pEngine, sqlite3_free);
   142922 #endif
   142923   if( db->mallocFailed ){
   142924     pParse->rc = SQLITE_NOMEM_BKPT;
   142925   }
   142926   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   142927     pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
   142928   }
   142929   assert( pzErrMsg!=0 );
   142930   if( pParse->zErrMsg ){
   142931     *pzErrMsg = pParse->zErrMsg;
   142932     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
   142933     pParse->zErrMsg = 0;
   142934     nErr++;
   142935   }
   142936   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
   142937     sqlite3VdbeDelete(pParse->pVdbe);
   142938     pParse->pVdbe = 0;
   142939   }
   142940 #ifndef SQLITE_OMIT_SHARED_CACHE
   142941   if( pParse->nested==0 ){
   142942     sqlite3DbFree(db, pParse->aTableLock);
   142943     pParse->aTableLock = 0;
   142944     pParse->nTableLock = 0;
   142945   }
   142946 #endif
   142947 #ifndef SQLITE_OMIT_VIRTUALTABLE
   142948   sqlite3_free(pParse->apVtabLock);
   142949 #endif
   142950 
   142951   if( !IN_DECLARE_VTAB ){
   142952     /* If the pParse->declareVtab flag is set, do not delete any table
   142953     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
   142954     ** will take responsibility for freeing the Table structure.
   142955     */
   142956     sqlite3DeleteTable(db, pParse->pNewTable);
   142957   }
   142958 
   142959   if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
   142960   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   142961   sqlite3DbFree(db, pParse->pVList);
   142962   while( pParse->pAinc ){
   142963     AutoincInfo *p = pParse->pAinc;
   142964     pParse->pAinc = p->pNext;
   142965     sqlite3DbFreeNN(db, p);
   142966   }
   142967   while( pParse->pZombieTab ){
   142968     Table *p = pParse->pZombieTab;
   142969     pParse->pZombieTab = p->pNextZombie;
   142970     sqlite3DeleteTable(db, p);
   142971   }
   142972   assert( nErr==0 || pParse->rc!=SQLITE_OK );
   142973   return nErr;
   142974 }
   142975 
   142976 /************** End of tokenize.c ********************************************/
   142977 /************** Begin file complete.c ****************************************/
   142978 /*
   142979 ** 2001 September 15
   142980 **
   142981 ** The author disclaims copyright to this source code.  In place of
   142982 ** a legal notice, here is a blessing:
   142983 **
   142984 **    May you do good and not evil.
   142985 **    May you find forgiveness for yourself and forgive others.
   142986 **    May you share freely, never taking more than you give.
   142987 **
   142988 *************************************************************************
   142989 ** An tokenizer for SQL
   142990 **
   142991 ** This file contains C code that implements the sqlite3_complete() API.
   142992 ** This code used to be part of the tokenizer.c source file.  But by
   142993 ** separating it out, the code will be automatically omitted from
   142994 ** static links that do not use it.
   142995 */
   142996 /* #include "sqliteInt.h" */
   142997 #ifndef SQLITE_OMIT_COMPLETE
   142998 
   142999 /*
   143000 ** This is defined in tokenize.c.  We just have to import the definition.
   143001 */
   143002 #ifndef SQLITE_AMALGAMATION
   143003 #ifdef SQLITE_ASCII
   143004 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   143005 #endif
   143006 #ifdef SQLITE_EBCDIC
   143007 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
   143008 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   143009 #endif
   143010 #endif /* SQLITE_AMALGAMATION */
   143011 
   143012 
   143013 /*
   143014 ** Token types used by the sqlite3_complete() routine.  See the header
   143015 ** comments on that procedure for additional information.
   143016 */
   143017 #define tkSEMI    0
   143018 #define tkWS      1
   143019 #define tkOTHER   2
   143020 #ifndef SQLITE_OMIT_TRIGGER
   143021 #define tkEXPLAIN 3
   143022 #define tkCREATE  4
   143023 #define tkTEMP    5
   143024 #define tkTRIGGER 6
   143025 #define tkEND     7
   143026 #endif
   143027 
   143028 /*
   143029 ** Return TRUE if the given SQL string ends in a semicolon.
   143030 **
   143031 ** Special handling is require for CREATE TRIGGER statements.
   143032 ** Whenever the CREATE TRIGGER keywords are seen, the statement
   143033 ** must end with ";END;".
   143034 **
   143035 ** This implementation uses a state machine with 8 states:
   143036 **
   143037 **   (0) INVALID   We have not yet seen a non-whitespace character.
   143038 **
   143039 **   (1) START     At the beginning or end of an SQL statement.  This routine
   143040 **                 returns 1 if it ends in the START state and 0 if it ends
   143041 **                 in any other state.
   143042 **
   143043 **   (2) NORMAL    We are in the middle of statement which ends with a single
   143044 **                 semicolon.
   143045 **
   143046 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
   143047 **                 a statement.
   143048 **
   143049 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
   143050 **                 statement, possibly preceded by EXPLAIN and/or followed by
   143051 **                 TEMP or TEMPORARY
   143052 **
   143053 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
   143054 **                 ended by a semicolon, the keyword END, and another semicolon.
   143055 **
   143056 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
   143057 **                 the end of a trigger definition.
   143058 **
   143059 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
   143060 **                 of a trigger definition.
   143061 **
   143062 ** Transitions between states above are determined by tokens extracted
   143063 ** from the input.  The following tokens are significant:
   143064 **
   143065 **   (0) tkSEMI      A semicolon.
   143066 **   (1) tkWS        Whitespace.
   143067 **   (2) tkOTHER     Any other SQL token.
   143068 **   (3) tkEXPLAIN   The "explain" keyword.
   143069 **   (4) tkCREATE    The "create" keyword.
   143070 **   (5) tkTEMP      The "temp" or "temporary" keyword.
   143071 **   (6) tkTRIGGER   The "trigger" keyword.
   143072 **   (7) tkEND       The "end" keyword.
   143073 **
   143074 ** Whitespace never causes a state transition and is always ignored.
   143075 ** This means that a SQL string of all whitespace is invalid.
   143076 **
   143077 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
   143078 ** to recognize the end of a trigger can be omitted.  All we have to do
   143079 ** is look for a semicolon that is not part of an string or comment.
   143080 */
   143081 SQLITE_API int sqlite3_complete(const char *zSql){
   143082   u8 state = 0;   /* Current state, using numbers defined in header comment */
   143083   u8 token;       /* Value of the next token */
   143084 
   143085 #ifndef SQLITE_OMIT_TRIGGER
   143086   /* A complex statement machine used to detect the end of a CREATE TRIGGER
   143087   ** statement.  This is the normal case.
   143088   */
   143089   static const u8 trans[8][8] = {
   143090                      /* Token:                                                */
   143091      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
   143092      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
   143093      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
   143094      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
   143095      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
   143096      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
   143097      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
   143098      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
   143099      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
   143100   };
   143101 #else
   143102   /* If triggers are not supported by this compile then the statement machine
   143103   ** used to detect the end of a statement is much simpler
   143104   */
   143105   static const u8 trans[3][3] = {
   143106                      /* Token:           */
   143107      /* State:       **  SEMI  WS  OTHER */
   143108      /* 0 INVALID: */ {    1,  0,     2, },
   143109      /* 1   START: */ {    1,  1,     2, },
   143110      /* 2  NORMAL: */ {    1,  2,     2, },
   143111   };
   143112 #endif /* SQLITE_OMIT_TRIGGER */
   143113 
   143114 #ifdef SQLITE_ENABLE_API_ARMOR
   143115   if( zSql==0 ){
   143116     (void)SQLITE_MISUSE_BKPT;
   143117     return 0;
   143118   }
   143119 #endif
   143120 
   143121   while( *zSql ){
   143122     switch( *zSql ){
   143123       case ';': {  /* A semicolon */
   143124         token = tkSEMI;
   143125         break;
   143126       }
   143127       case ' ':
   143128       case '\r':
   143129       case '\t':
   143130       case '\n':
   143131       case '\f': {  /* White space is ignored */
   143132         token = tkWS;
   143133         break;
   143134       }
   143135       case '/': {   /* C-style comments */
   143136         if( zSql[1]!='*' ){
   143137           token = tkOTHER;
   143138           break;
   143139         }
   143140         zSql += 2;
   143141         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
   143142         if( zSql[0]==0 ) return 0;
   143143         zSql++;
   143144         token = tkWS;
   143145         break;
   143146       }
   143147       case '-': {   /* SQL-style comments from "--" to end of line */
   143148         if( zSql[1]!='-' ){
   143149           token = tkOTHER;
   143150           break;
   143151         }
   143152         while( *zSql && *zSql!='\n' ){ zSql++; }
   143153         if( *zSql==0 ) return state==1;
   143154         token = tkWS;
   143155         break;
   143156       }
   143157       case '[': {   /* Microsoft-style identifiers in [...] */
   143158         zSql++;
   143159         while( *zSql && *zSql!=']' ){ zSql++; }
   143160         if( *zSql==0 ) return 0;
   143161         token = tkOTHER;
   143162         break;
   143163       }
   143164       case '`':     /* Grave-accent quoted symbols used by MySQL */
   143165       case '"':     /* single- and double-quoted strings */
   143166       case '\'': {
   143167         int c = *zSql;
   143168         zSql++;
   143169         while( *zSql && *zSql!=c ){ zSql++; }
   143170         if( *zSql==0 ) return 0;
   143171         token = tkOTHER;
   143172         break;
   143173       }
   143174       default: {
   143175 #ifdef SQLITE_EBCDIC
   143176         unsigned char c;
   143177 #endif
   143178         if( IdChar((u8)*zSql) ){
   143179           /* Keywords and unquoted identifiers */
   143180           int nId;
   143181           for(nId=1; IdChar(zSql[nId]); nId++){}
   143182 #ifdef SQLITE_OMIT_TRIGGER
   143183           token = tkOTHER;
   143184 #else
   143185           switch( *zSql ){
   143186             case 'c': case 'C': {
   143187               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
   143188                 token = tkCREATE;
   143189               }else{
   143190                 token = tkOTHER;
   143191               }
   143192               break;
   143193             }
   143194             case 't': case 'T': {
   143195               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
   143196                 token = tkTRIGGER;
   143197               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
   143198                 token = tkTEMP;
   143199               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
   143200                 token = tkTEMP;
   143201               }else{
   143202                 token = tkOTHER;
   143203               }
   143204               break;
   143205             }
   143206             case 'e':  case 'E': {
   143207               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
   143208                 token = tkEND;
   143209               }else
   143210 #ifndef SQLITE_OMIT_EXPLAIN
   143211               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
   143212                 token = tkEXPLAIN;
   143213               }else
   143214 #endif
   143215               {
   143216                 token = tkOTHER;
   143217               }
   143218               break;
   143219             }
   143220             default: {
   143221               token = tkOTHER;
   143222               break;
   143223             }
   143224           }
   143225 #endif /* SQLITE_OMIT_TRIGGER */
   143226           zSql += nId-1;
   143227         }else{
   143228           /* Operators and special symbols */
   143229           token = tkOTHER;
   143230         }
   143231         break;
   143232       }
   143233     }
   143234     state = trans[state][token];
   143235     zSql++;
   143236   }
   143237   return state==1;
   143238 }
   143239 
   143240 #ifndef SQLITE_OMIT_UTF16
   143241 /*
   143242 ** This routine is the same as the sqlite3_complete() routine described
   143243 ** above, except that the parameter is required to be UTF-16 encoded, not
   143244 ** UTF-8.
   143245 */
   143246 SQLITE_API int sqlite3_complete16(const void *zSql){
   143247   sqlite3_value *pVal;
   143248   char const *zSql8;
   143249   int rc;
   143250 
   143251 #ifndef SQLITE_OMIT_AUTOINIT
   143252   rc = sqlite3_initialize();
   143253   if( rc ) return rc;
   143254 #endif
   143255   pVal = sqlite3ValueNew(0);
   143256   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   143257   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   143258   if( zSql8 ){
   143259     rc = sqlite3_complete(zSql8);
   143260   }else{
   143261     rc = SQLITE_NOMEM_BKPT;
   143262   }
   143263   sqlite3ValueFree(pVal);
   143264   return rc & 0xff;
   143265 }
   143266 #endif /* SQLITE_OMIT_UTF16 */
   143267 #endif /* SQLITE_OMIT_COMPLETE */
   143268 
   143269 /************** End of complete.c ********************************************/
   143270 /************** Begin file main.c ********************************************/
   143271 /*
   143272 ** 2001 September 15
   143273 **
   143274 ** The author disclaims copyright to this source code.  In place of
   143275 ** a legal notice, here is a blessing:
   143276 **
   143277 **    May you do good and not evil.
   143278 **    May you find forgiveness for yourself and forgive others.
   143279 **    May you share freely, never taking more than you give.
   143280 **
   143281 *************************************************************************
   143282 ** Main file for the SQLite library.  The routines in this file
   143283 ** implement the programmer interface to the library.  Routines in
   143284 ** other files are for internal use by SQLite and should not be
   143285 ** accessed by users of the library.
   143286 */
   143287 /* #include "sqliteInt.h" */
   143288 
   143289 #ifdef SQLITE_ENABLE_FTS3
   143290 /************** Include fts3.h in the middle of main.c ***********************/
   143291 /************** Begin file fts3.h ********************************************/
   143292 /*
   143293 ** 2006 Oct 10
   143294 **
   143295 ** The author disclaims copyright to this source code.  In place of
   143296 ** a legal notice, here is a blessing:
   143297 **
   143298 **    May you do good and not evil.
   143299 **    May you find forgiveness for yourself and forgive others.
   143300 **    May you share freely, never taking more than you give.
   143301 **
   143302 ******************************************************************************
   143303 **
   143304 ** This header file is used by programs that want to link against the
   143305 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
   143306 */
   143307 /* #include "sqlite3.h" */
   143308 
   143309 #if 0
   143310 extern "C" {
   143311 #endif  /* __cplusplus */
   143312 
   143313 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
   143314 
   143315 #if 0
   143316 }  /* extern "C" */
   143317 #endif  /* __cplusplus */
   143318 
   143319 /************** End of fts3.h ************************************************/
   143320 /************** Continuing where we left off in main.c ***********************/
   143321 #endif
   143322 #ifdef SQLITE_ENABLE_RTREE
   143323 /************** Include rtree.h in the middle of main.c **********************/
   143324 /************** Begin file rtree.h *******************************************/
   143325 /*
   143326 ** 2008 May 26
   143327 **
   143328 ** The author disclaims copyright to this source code.  In place of
   143329 ** a legal notice, here is a blessing:
   143330 **
   143331 **    May you do good and not evil.
   143332 **    May you find forgiveness for yourself and forgive others.
   143333 **    May you share freely, never taking more than you give.
   143334 **
   143335 ******************************************************************************
   143336 **
   143337 ** This header file is used by programs that want to link against the
   143338 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
   143339 */
   143340 /* #include "sqlite3.h" */
   143341 
   143342 #ifdef SQLITE_OMIT_VIRTUALTABLE
   143343 # undef SQLITE_ENABLE_RTREE
   143344 #endif
   143345 
   143346 #if 0
   143347 extern "C" {
   143348 #endif  /* __cplusplus */
   143349 
   143350 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
   143351 
   143352 #if 0
   143353 }  /* extern "C" */
   143354 #endif  /* __cplusplus */
   143355 
   143356 /************** End of rtree.h ***********************************************/
   143357 /************** Continuing where we left off in main.c ***********************/
   143358 #endif
   143359 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
   143360 /************** Include sqliteicu.h in the middle of main.c ******************/
   143361 /************** Begin file sqliteicu.h ***************************************/
   143362 /*
   143363 ** 2008 May 26
   143364 **
   143365 ** The author disclaims copyright to this source code.  In place of
   143366 ** a legal notice, here is a blessing:
   143367 **
   143368 **    May you do good and not evil.
   143369 **    May you find forgiveness for yourself and forgive others.
   143370 **    May you share freely, never taking more than you give.
   143371 **
   143372 ******************************************************************************
   143373 **
   143374 ** This header file is used by programs that want to link against the
   143375 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
   143376 */
   143377 /* #include "sqlite3.h" */
   143378 
   143379 #if 0
   143380 extern "C" {
   143381 #endif  /* __cplusplus */
   143382 
   143383 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
   143384 
   143385 #if 0
   143386 }  /* extern "C" */
   143387 #endif  /* __cplusplus */
   143388 
   143389 
   143390 /************** End of sqliteicu.h *******************************************/
   143391 /************** Continuing where we left off in main.c ***********************/
   143392 #endif
   143393 #ifdef SQLITE_ENABLE_JSON1
   143394 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
   143395 #endif
   143396 #ifdef SQLITE_ENABLE_STMTVTAB
   143397 SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
   143398 #endif
   143399 #ifdef SQLITE_ENABLE_FTS5
   143400 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
   143401 #endif
   143402 
   143403 #ifndef SQLITE_AMALGAMATION
   143404 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
   143405 ** contains the text of SQLITE_VERSION macro.
   143406 */
   143407 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   143408 #endif
   143409 
   143410 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
   143411 ** a pointer to the to the sqlite3_version[] string constant.
   143412 */
   143413 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
   143414 
   143415 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
   143416 ** pointer to a string constant whose value is the same as the
   143417 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
   143418 ** an edited copy of the amalgamation, then the last four characters of
   143419 ** the hash might be different from SQLITE_SOURCE_ID.
   143420 */
   143421 /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
   143422 
   143423 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
   143424 ** returns an integer equal to SQLITE_VERSION_NUMBER.
   143425 */
   143426 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
   143427 
   143428 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
   143429 ** zero if and only if SQLite was compiled with mutexing code omitted due to
   143430 ** the SQLITE_THREADSAFE compile-time option being set to 0.
   143431 */
   143432 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
   143433 
   143434 /*
   143435 ** When compiling the test fixture or with debugging enabled (on Win32),
   143436 ** this variable being set to non-zero will cause OSTRACE macros to emit
   143437 ** extra diagnostic information.
   143438 */
   143439 #ifdef SQLITE_HAVE_OS_TRACE
   143440 # ifndef SQLITE_DEBUG_OS_TRACE
   143441 #   define SQLITE_DEBUG_OS_TRACE 0
   143442 # endif
   143443   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   143444 #endif
   143445 
   143446 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   143447 /*
   143448 ** If the following function pointer is not NULL and if
   143449 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
   143450 ** I/O active are written using this function.  These messages
   143451 ** are intended for debugging activity only.
   143452 */
   143453 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
   143454 #endif
   143455 
   143456 /*
   143457 ** If the following global variable points to a string which is the
   143458 ** name of a directory, then that directory will be used to store
   143459 ** temporary files.
   143460 **
   143461 ** See also the "PRAGMA temp_store_directory" SQL command.
   143462 */
   143463 SQLITE_API char *sqlite3_temp_directory = 0;
   143464 
   143465 /*
   143466 ** If the following global variable points to a string which is the
   143467 ** name of a directory, then that directory will be used to store
   143468 ** all database files specified with a relative pathname.
   143469 **
   143470 ** See also the "PRAGMA data_store_directory" SQL command.
   143471 */
   143472 SQLITE_API char *sqlite3_data_directory = 0;
   143473 
   143474 /*
   143475 ** Initialize SQLite.
   143476 **
   143477 ** This routine must be called to initialize the memory allocation,
   143478 ** VFS, and mutex subsystems prior to doing any serious work with
   143479 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
   143480 ** this routine will be called automatically by key routines such as
   143481 ** sqlite3_open().
   143482 **
   143483 ** This routine is a no-op except on its very first call for the process,
   143484 ** or for the first call after a call to sqlite3_shutdown.
   143485 **
   143486 ** The first thread to call this routine runs the initialization to
   143487 ** completion.  If subsequent threads call this routine before the first
   143488 ** thread has finished the initialization process, then the subsequent
   143489 ** threads must block until the first thread finishes with the initialization.
   143490 **
   143491 ** The first thread might call this routine recursively.  Recursive
   143492 ** calls to this routine should not block, of course.  Otherwise the
   143493 ** initialization process would never complete.
   143494 **
   143495 ** Let X be the first thread to enter this routine.  Let Y be some other
   143496 ** thread.  Then while the initial invocation of this routine by X is
   143497 ** incomplete, it is required that:
   143498 **
   143499 **    *  Calls to this routine from Y must block until the outer-most
   143500 **       call by X completes.
   143501 **
   143502 **    *  Recursive calls to this routine from thread X return immediately
   143503 **       without blocking.
   143504 */
   143505 SQLITE_API int sqlite3_initialize(void){
   143506   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
   143507   int rc;                                      /* Result code */
   143508 #ifdef SQLITE_EXTRA_INIT
   143509   int bRunExtraInit = 0;                       /* Extra initialization needed */
   143510 #endif
   143511 
   143512 #ifdef SQLITE_OMIT_WSD
   143513   rc = sqlite3_wsd_init(4096, 24);
   143514   if( rc!=SQLITE_OK ){
   143515     return rc;
   143516   }
   143517 #endif
   143518 
   143519   /* If the following assert() fails on some obscure processor/compiler
   143520   ** combination, the work-around is to set the correct pointer
   143521   ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
   143522   assert( SQLITE_PTRSIZE==sizeof(char*) );
   143523 
   143524   /* If SQLite is already completely initialized, then this call
   143525   ** to sqlite3_initialize() should be a no-op.  But the initialization
   143526   ** must be complete.  So isInit must not be set until the very end
   143527   ** of this routine.
   143528   */
   143529   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
   143530 
   143531   /* Make sure the mutex subsystem is initialized.  If unable to
   143532   ** initialize the mutex subsystem, return early with the error.
   143533   ** If the system is so sick that we are unable to allocate a mutex,
   143534   ** there is not much SQLite is going to be able to do.
   143535   **
   143536   ** The mutex subsystem must take care of serializing its own
   143537   ** initialization.
   143538   */
   143539   rc = sqlite3MutexInit();
   143540   if( rc ) return rc;
   143541 
   143542   /* Initialize the malloc() system and the recursive pInitMutex mutex.
   143543   ** This operation is protected by the STATIC_MASTER mutex.  Note that
   143544   ** MutexAlloc() is called for a static mutex prior to initializing the
   143545   ** malloc subsystem - this implies that the allocation of a static
   143546   ** mutex must not require support from the malloc subsystem.
   143547   */
   143548   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   143549   sqlite3_mutex_enter(pMaster);
   143550   sqlite3GlobalConfig.isMutexInit = 1;
   143551   if( !sqlite3GlobalConfig.isMallocInit ){
   143552     rc = sqlite3MallocInit();
   143553   }
   143554   if( rc==SQLITE_OK ){
   143555     sqlite3GlobalConfig.isMallocInit = 1;
   143556     if( !sqlite3GlobalConfig.pInitMutex ){
   143557       sqlite3GlobalConfig.pInitMutex =
   143558            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   143559       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
   143560         rc = SQLITE_NOMEM_BKPT;
   143561       }
   143562     }
   143563   }
   143564   if( rc==SQLITE_OK ){
   143565     sqlite3GlobalConfig.nRefInitMutex++;
   143566   }
   143567   sqlite3_mutex_leave(pMaster);
   143568 
   143569   /* If rc is not SQLITE_OK at this point, then either the malloc
   143570   ** subsystem could not be initialized or the system failed to allocate
   143571   ** the pInitMutex mutex. Return an error in either case.  */
   143572   if( rc!=SQLITE_OK ){
   143573     return rc;
   143574   }
   143575 
   143576   /* Do the rest of the initialization under the recursive mutex so
   143577   ** that we will be able to handle recursive calls into
   143578   ** sqlite3_initialize().  The recursive calls normally come through
   143579   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
   143580   ** recursive calls might also be possible.
   143581   **
   143582   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
   143583   ** to the xInit method, so the xInit method need not be threadsafe.
   143584   **
   143585   ** The following mutex is what serializes access to the appdef pcache xInit
   143586   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
   143587   ** call to sqlite3PcacheInitialize().
   143588   */
   143589   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
   143590   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
   143591     sqlite3GlobalConfig.inProgress = 1;
   143592 #ifdef SQLITE_ENABLE_SQLLOG
   143593     {
   143594       extern void sqlite3_init_sqllog(void);
   143595       sqlite3_init_sqllog();
   143596     }
   143597 #endif
   143598     memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
   143599     sqlite3RegisterBuiltinFunctions();
   143600     if( sqlite3GlobalConfig.isPCacheInit==0 ){
   143601       rc = sqlite3PcacheInitialize();
   143602     }
   143603     if( rc==SQLITE_OK ){
   143604       sqlite3GlobalConfig.isPCacheInit = 1;
   143605       rc = sqlite3OsInit();
   143606     }
   143607     if( rc==SQLITE_OK ){
   143608       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
   143609           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
   143610       sqlite3GlobalConfig.isInit = 1;
   143611 #ifdef SQLITE_EXTRA_INIT
   143612       bRunExtraInit = 1;
   143613 #endif
   143614     }
   143615     sqlite3GlobalConfig.inProgress = 0;
   143616   }
   143617   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
   143618 
   143619   /* Go back under the static mutex and clean up the recursive
   143620   ** mutex to prevent a resource leak.
   143621   */
   143622   sqlite3_mutex_enter(pMaster);
   143623   sqlite3GlobalConfig.nRefInitMutex--;
   143624   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
   143625     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
   143626     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
   143627     sqlite3GlobalConfig.pInitMutex = 0;
   143628   }
   143629   sqlite3_mutex_leave(pMaster);
   143630 
   143631   /* The following is just a sanity check to make sure SQLite has
   143632   ** been compiled correctly.  It is important to run this code, but
   143633   ** we don't want to run it too often and soak up CPU cycles for no
   143634   ** reason.  So we run it once during initialization.
   143635   */
   143636 #ifndef NDEBUG
   143637 #ifndef SQLITE_OMIT_FLOATING_POINT
   143638   /* This section of code's only "output" is via assert() statements. */
   143639   if ( rc==SQLITE_OK ){
   143640     u64 x = (((u64)1)<<63)-1;
   143641     double y;
   143642     assert(sizeof(x)==8);
   143643     assert(sizeof(x)==sizeof(y));
   143644     memcpy(&y, &x, 8);
   143645     assert( sqlite3IsNaN(y) );
   143646   }
   143647 #endif
   143648 #endif
   143649 
   143650   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
   143651   ** compile-time option.
   143652   */
   143653 #ifdef SQLITE_EXTRA_INIT
   143654   if( bRunExtraInit ){
   143655     int SQLITE_EXTRA_INIT(const char*);
   143656     rc = SQLITE_EXTRA_INIT(0);
   143657   }
   143658 #endif
   143659 
   143660   return rc;
   143661 }
   143662 
   143663 /*
   143664 ** Undo the effects of sqlite3_initialize().  Must not be called while
   143665 ** there are outstanding database connections or memory allocations or
   143666 ** while any part of SQLite is otherwise in use in any thread.  This
   143667 ** routine is not threadsafe.  But it is safe to invoke this routine
   143668 ** on when SQLite is already shut down.  If SQLite is already shut down
   143669 ** when this routine is invoked, then this routine is a harmless no-op.
   143670 */
   143671 SQLITE_API int sqlite3_shutdown(void){
   143672 #ifdef SQLITE_OMIT_WSD
   143673   int rc = sqlite3_wsd_init(4096, 24);
   143674   if( rc!=SQLITE_OK ){
   143675     return rc;
   143676   }
   143677 #endif
   143678 
   143679   if( sqlite3GlobalConfig.isInit ){
   143680 #ifdef SQLITE_EXTRA_SHUTDOWN
   143681     void SQLITE_EXTRA_SHUTDOWN(void);
   143682     SQLITE_EXTRA_SHUTDOWN();
   143683 #endif
   143684     sqlite3_os_end();
   143685     sqlite3_reset_auto_extension();
   143686     sqlite3GlobalConfig.isInit = 0;
   143687   }
   143688   if( sqlite3GlobalConfig.isPCacheInit ){
   143689     sqlite3PcacheShutdown();
   143690     sqlite3GlobalConfig.isPCacheInit = 0;
   143691   }
   143692   if( sqlite3GlobalConfig.isMallocInit ){
   143693     sqlite3MallocEnd();
   143694     sqlite3GlobalConfig.isMallocInit = 0;
   143695 
   143696 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
   143697     /* The heap subsystem has now been shutdown and these values are supposed
   143698     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
   143699     ** which would rely on that heap subsystem; therefore, make sure these
   143700     ** values cannot refer to heap memory that was just invalidated when the
   143701     ** heap subsystem was shutdown.  This is only done if the current call to
   143702     ** this function resulted in the heap subsystem actually being shutdown.
   143703     */
   143704     sqlite3_data_directory = 0;
   143705     sqlite3_temp_directory = 0;
   143706 #endif
   143707   }
   143708   if( sqlite3GlobalConfig.isMutexInit ){
   143709     sqlite3MutexEnd();
   143710     sqlite3GlobalConfig.isMutexInit = 0;
   143711   }
   143712 
   143713   return SQLITE_OK;
   143714 }
   143715 
   143716 /*
   143717 ** This API allows applications to modify the global configuration of
   143718 ** the SQLite library at run-time.
   143719 **
   143720 ** This routine should only be called when there are no outstanding
   143721 ** database connections or memory allocations.  This routine is not
   143722 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
   143723 ** behavior.
   143724 */
   143725 SQLITE_API int sqlite3_config(int op, ...){
   143726   va_list ap;
   143727   int rc = SQLITE_OK;
   143728 
   143729   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
   143730   ** the SQLite library is in use. */
   143731   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
   143732 
   143733   va_start(ap, op);
   143734   switch( op ){
   143735 
   143736     /* Mutex configuration options are only available in a threadsafe
   143737     ** compile.
   143738     */
   143739 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
   143740     case SQLITE_CONFIG_SINGLETHREAD: {
   143741       /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
   143742       ** Single-thread. */
   143743       sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
   143744       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
   143745       break;
   143746     }
   143747 #endif
   143748 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
   143749     case SQLITE_CONFIG_MULTITHREAD: {
   143750       /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
   143751       ** Multi-thread. */
   143752       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
   143753       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
   143754       break;
   143755     }
   143756 #endif
   143757 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
   143758     case SQLITE_CONFIG_SERIALIZED: {
   143759       /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
   143760       ** Serialized. */
   143761       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
   143762       sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
   143763       break;
   143764     }
   143765 #endif
   143766 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
   143767     case SQLITE_CONFIG_MUTEX: {
   143768       /* Specify an alternative mutex implementation */
   143769       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
   143770       break;
   143771     }
   143772 #endif
   143773 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
   143774     case SQLITE_CONFIG_GETMUTEX: {
   143775       /* Retrieve the current mutex implementation */
   143776       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
   143777       break;
   143778     }
   143779 #endif
   143780 
   143781     case SQLITE_CONFIG_MALLOC: {
   143782       /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
   143783       ** single argument which is a pointer to an instance of the
   143784       ** sqlite3_mem_methods structure. The argument specifies alternative
   143785       ** low-level memory allocation routines to be used in place of the memory
   143786       ** allocation routines built into SQLite. */
   143787       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
   143788       break;
   143789     }
   143790     case SQLITE_CONFIG_GETMALLOC: {
   143791       /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
   143792       ** single argument which is a pointer to an instance of the
   143793       ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
   143794       ** filled with the currently defined memory allocation routines. */
   143795       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
   143796       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
   143797       break;
   143798     }
   143799     case SQLITE_CONFIG_MEMSTATUS: {
   143800       /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
   143801       ** single argument of type int, interpreted as a boolean, which enables
   143802       ** or disables the collection of memory allocation statistics. */
   143803       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
   143804       break;
   143805     }
   143806     case SQLITE_CONFIG_SMALL_MALLOC: {
   143807       sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
   143808       break;
   143809     }
   143810     case SQLITE_CONFIG_PAGECACHE: {
   143811       /* EVIDENCE-OF: R-18761-36601 There are three arguments to
   143812       ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
   143813       ** the size of each page cache line (sz), and the number of cache lines
   143814       ** (N). */
   143815       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   143816       sqlite3GlobalConfig.szPage = va_arg(ap, int);
   143817       sqlite3GlobalConfig.nPage = va_arg(ap, int);
   143818       break;
   143819     }
   143820     case SQLITE_CONFIG_PCACHE_HDRSZ: {
   143821       /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
   143822       ** a single parameter which is a pointer to an integer and writes into
   143823       ** that integer the number of extra bytes per page required for each page
   143824       ** in SQLITE_CONFIG_PAGECACHE. */
   143825       *va_arg(ap, int*) =
   143826           sqlite3HeaderSizeBtree() +
   143827           sqlite3HeaderSizePcache() +
   143828           sqlite3HeaderSizePcache1();
   143829       break;
   143830     }
   143831 
   143832     case SQLITE_CONFIG_PCACHE: {
   143833       /* no-op */
   143834       break;
   143835     }
   143836     case SQLITE_CONFIG_GETPCACHE: {
   143837       /* now an error */
   143838       rc = SQLITE_ERROR;
   143839       break;
   143840     }
   143841 
   143842     case SQLITE_CONFIG_PCACHE2: {
   143843       /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
   143844       ** single argument which is a pointer to an sqlite3_pcache_methods2
   143845       ** object. This object specifies the interface to a custom page cache
   143846       ** implementation. */
   143847       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
   143848       break;
   143849     }
   143850     case SQLITE_CONFIG_GETPCACHE2: {
   143851       /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
   143852       ** single argument which is a pointer to an sqlite3_pcache_methods2
   143853       ** object. SQLite copies of the current page cache implementation into
   143854       ** that object. */
   143855       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   143856         sqlite3PCacheSetDefault();
   143857       }
   143858       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
   143859       break;
   143860     }
   143861 
   143862 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
   143863 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
   143864 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
   143865 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   143866     case SQLITE_CONFIG_HEAP: {
   143867       /* EVIDENCE-OF: R-19854-42126 There are three arguments to
   143868       ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
   143869       ** number of bytes in the memory buffer, and the minimum allocation size.
   143870       */
   143871       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
   143872       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   143873       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
   143874 
   143875       if( sqlite3GlobalConfig.mnReq<1 ){
   143876         sqlite3GlobalConfig.mnReq = 1;
   143877       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
   143878         /* cap min request size at 2^12 */
   143879         sqlite3GlobalConfig.mnReq = (1<<12);
   143880       }
   143881 
   143882       if( sqlite3GlobalConfig.pHeap==0 ){
   143883         /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
   143884         ** is NULL, then SQLite reverts to using its default memory allocator
   143885         ** (the system malloc() implementation), undoing any prior invocation of
   143886         ** SQLITE_CONFIG_MALLOC.
   143887         **
   143888         ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
   143889         ** revert to its default implementation when sqlite3_initialize() is run
   143890         */
   143891         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
   143892       }else{
   143893         /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
   143894         ** alternative memory allocator is engaged to handle all of SQLites
   143895         ** memory allocation needs. */
   143896 #ifdef SQLITE_ENABLE_MEMSYS3
   143897         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
   143898 #endif
   143899 #ifdef SQLITE_ENABLE_MEMSYS5
   143900         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
   143901 #endif
   143902       }
   143903       break;
   143904     }
   143905 #endif
   143906 
   143907     case SQLITE_CONFIG_LOOKASIDE: {
   143908       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
   143909       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
   143910       break;
   143911     }
   143912 
   143913     /* Record a pointer to the logger function and its first argument.
   143914     ** The default is NULL.  Logging is disabled if the function pointer is
   143915     ** NULL.
   143916     */
   143917     case SQLITE_CONFIG_LOG: {
   143918       /* MSVC is picky about pulling func ptrs from va lists.
   143919       ** http://support.microsoft.com/kb/47961
   143920       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
   143921       */
   143922       typedef void(*LOGFUNC_t)(void*,int,const char*);
   143923       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
   143924       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
   143925       break;
   143926     }
   143927 
   143928     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
   143929     ** can be changed at start-time using the
   143930     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
   143931     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
   143932     */
   143933     case SQLITE_CONFIG_URI: {
   143934       /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
   143935       ** argument of type int. If non-zero, then URI handling is globally
   143936       ** enabled. If the parameter is zero, then URI handling is globally
   143937       ** disabled. */
   143938       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
   143939       break;
   143940     }
   143941 
   143942     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
   143943       /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
   143944       ** option takes a single integer argument which is interpreted as a
   143945       ** boolean in order to enable or disable the use of covering indices for
   143946       ** full table scans in the query optimizer. */
   143947       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
   143948       break;
   143949     }
   143950 
   143951 #ifdef SQLITE_ENABLE_SQLLOG
   143952     case SQLITE_CONFIG_SQLLOG: {
   143953       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
   143954       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
   143955       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
   143956       break;
   143957     }
   143958 #endif
   143959 
   143960     case SQLITE_CONFIG_MMAP_SIZE: {
   143961       /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
   143962       ** integer (sqlite3_int64) values that are the default mmap size limit
   143963       ** (the default setting for PRAGMA mmap_size) and the maximum allowed
   143964       ** mmap size limit. */
   143965       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
   143966       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
   143967       /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
   143968       ** negative, then that argument is changed to its compile-time default.
   143969       **
   143970       ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
   143971       ** silently truncated if necessary so that it does not exceed the
   143972       ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
   143973       ** compile-time option.
   143974       */
   143975       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
   143976         mxMmap = SQLITE_MAX_MMAP_SIZE;
   143977       }
   143978       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
   143979       if( szMmap>mxMmap) szMmap = mxMmap;
   143980       sqlite3GlobalConfig.mxMmap = mxMmap;
   143981       sqlite3GlobalConfig.szMmap = szMmap;
   143982       break;
   143983     }
   143984 
   143985 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
   143986     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
   143987       /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
   143988       ** unsigned integer value that specifies the maximum size of the created
   143989       ** heap. */
   143990       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   143991       break;
   143992     }
   143993 #endif
   143994 
   143995     case SQLITE_CONFIG_PMASZ: {
   143996       sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
   143997       break;
   143998     }
   143999 
   144000     case SQLITE_CONFIG_STMTJRNL_SPILL: {
   144001       sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
   144002       break;
   144003     }
   144004 
   144005     default: {
   144006       rc = SQLITE_ERROR;
   144007       break;
   144008     }
   144009   }
   144010   va_end(ap);
   144011   return rc;
   144012 }
   144013 
   144014 /*
   144015 ** Set up the lookaside buffers for a database connection.
   144016 ** Return SQLITE_OK on success.
   144017 ** If lookaside is already active, return SQLITE_BUSY.
   144018 **
   144019 ** The sz parameter is the number of bytes in each lookaside slot.
   144020 ** The cnt parameter is the number of slots.  If pStart is NULL the
   144021 ** space for the lookaside memory is obtained from sqlite3_malloc().
   144022 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
   144023 ** the lookaside memory.
   144024 */
   144025 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
   144026 #ifndef SQLITE_OMIT_LOOKASIDE
   144027   void *pStart;
   144028 
   144029   if( sqlite3LookasideUsed(db,0)>0 ){
   144030     return SQLITE_BUSY;
   144031   }
   144032   /* Free any existing lookaside buffer for this handle before
   144033   ** allocating a new one so we don't have to have space for
   144034   ** both at the same time.
   144035   */
   144036   if( db->lookaside.bMalloced ){
   144037     sqlite3_free(db->lookaside.pStart);
   144038   }
   144039   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
   144040   ** than a pointer to be useful.
   144041   */
   144042   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
   144043   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   144044   if( cnt<0 ) cnt = 0;
   144045   if( sz==0 || cnt==0 ){
   144046     sz = 0;
   144047     pStart = 0;
   144048   }else if( pBuf==0 ){
   144049     sqlite3BeginBenignMalloc();
   144050     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
   144051     sqlite3EndBenignMalloc();
   144052     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
   144053   }else{
   144054     pStart = pBuf;
   144055   }
   144056   db->lookaside.pStart = pStart;
   144057   db->lookaside.pInit = 0;
   144058   db->lookaside.pFree = 0;
   144059   db->lookaside.sz = (u16)sz;
   144060   if( pStart ){
   144061     int i;
   144062     LookasideSlot *p;
   144063     assert( sz > (int)sizeof(LookasideSlot*) );
   144064     db->lookaside.nSlot = cnt;
   144065     p = (LookasideSlot*)pStart;
   144066     for(i=cnt-1; i>=0; i--){
   144067       p->pNext = db->lookaside.pInit;
   144068       db->lookaside.pInit = p;
   144069       p = (LookasideSlot*)&((u8*)p)[sz];
   144070     }
   144071     db->lookaside.pEnd = p;
   144072     db->lookaside.bDisable = 0;
   144073     db->lookaside.bMalloced = pBuf==0 ?1:0;
   144074   }else{
   144075     db->lookaside.pStart = db;
   144076     db->lookaside.pEnd = db;
   144077     db->lookaside.bDisable = 1;
   144078     db->lookaside.bMalloced = 0;
   144079     db->lookaside.nSlot = 0;
   144080   }
   144081 #endif /* SQLITE_OMIT_LOOKASIDE */
   144082   return SQLITE_OK;
   144083 }
   144084 
   144085 /*
   144086 ** Return the mutex associated with a database connection.
   144087 */
   144088 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   144089 #ifdef SQLITE_ENABLE_API_ARMOR
   144090   if( !sqlite3SafetyCheckOk(db) ){
   144091     (void)SQLITE_MISUSE_BKPT;
   144092     return 0;
   144093   }
   144094 #endif
   144095   return db->mutex;
   144096 }
   144097 
   144098 /*
   144099 ** Free up as much memory as we can from the given database
   144100 ** connection.
   144101 */
   144102 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
   144103   int i;
   144104 
   144105 #ifdef SQLITE_ENABLE_API_ARMOR
   144106   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   144107 #endif
   144108   sqlite3_mutex_enter(db->mutex);
   144109   sqlite3BtreeEnterAll(db);
   144110   for(i=0; i<db->nDb; i++){
   144111     Btree *pBt = db->aDb[i].pBt;
   144112     if( pBt ){
   144113       Pager *pPager = sqlite3BtreePager(pBt);
   144114       sqlite3PagerShrink(pPager);
   144115     }
   144116   }
   144117   sqlite3BtreeLeaveAll(db);
   144118   sqlite3_mutex_leave(db->mutex);
   144119   return SQLITE_OK;
   144120 }
   144121 
   144122 /*
   144123 ** Flush any dirty pages in the pager-cache for any attached database
   144124 ** to disk.
   144125 */
   144126 SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
   144127   int i;
   144128   int rc = SQLITE_OK;
   144129   int bSeenBusy = 0;
   144130 
   144131 #ifdef SQLITE_ENABLE_API_ARMOR
   144132   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   144133 #endif
   144134   sqlite3_mutex_enter(db->mutex);
   144135   sqlite3BtreeEnterAll(db);
   144136   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   144137     Btree *pBt = db->aDb[i].pBt;
   144138     if( pBt && sqlite3BtreeIsInTrans(pBt) ){
   144139       Pager *pPager = sqlite3BtreePager(pBt);
   144140       rc = sqlite3PagerFlush(pPager);
   144141       if( rc==SQLITE_BUSY ){
   144142         bSeenBusy = 1;
   144143         rc = SQLITE_OK;
   144144       }
   144145     }
   144146   }
   144147   sqlite3BtreeLeaveAll(db);
   144148   sqlite3_mutex_leave(db->mutex);
   144149   return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
   144150 }
   144151 
   144152 /*
   144153 ** Configuration settings for an individual database connection
   144154 */
   144155 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
   144156   va_list ap;
   144157   int rc;
   144158   va_start(ap, op);
   144159   switch( op ){
   144160     case SQLITE_DBCONFIG_MAINDBNAME: {
   144161       /* IMP: R-06824-28531 */
   144162       /* IMP: R-36257-52125 */
   144163       db->aDb[0].zDbSName = va_arg(ap,char*);
   144164       rc = SQLITE_OK;
   144165       break;
   144166     }
   144167     case SQLITE_DBCONFIG_LOOKASIDE: {
   144168       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
   144169       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
   144170       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
   144171       rc = setupLookaside(db, pBuf, sz, cnt);
   144172       break;
   144173     }
   144174     default: {
   144175       static const struct {
   144176         int op;      /* The opcode */
   144177         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
   144178       } aFlagOp[] = {
   144179         { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
   144180         { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
   144181         { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
   144182         { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
   144183         { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
   144184         { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
   144185         { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
   144186       };
   144187       unsigned int i;
   144188       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
   144189       for(i=0; i<ArraySize(aFlagOp); i++){
   144190         if( aFlagOp[i].op==op ){
   144191           int onoff = va_arg(ap, int);
   144192           int *pRes = va_arg(ap, int*);
   144193           u32 oldFlags = db->flags;
   144194           if( onoff>0 ){
   144195             db->flags |= aFlagOp[i].mask;
   144196           }else if( onoff==0 ){
   144197             db->flags &= ~aFlagOp[i].mask;
   144198           }
   144199           if( oldFlags!=db->flags ){
   144200             sqlite3ExpirePreparedStatements(db);
   144201           }
   144202           if( pRes ){
   144203             *pRes = (db->flags & aFlagOp[i].mask)!=0;
   144204           }
   144205           rc = SQLITE_OK;
   144206           break;
   144207         }
   144208       }
   144209       break;
   144210     }
   144211   }
   144212   va_end(ap);
   144213   return rc;
   144214 }
   144215 
   144216 
   144217 /*
   144218 ** Return true if the buffer z[0..n-1] contains all spaces.
   144219 */
   144220 static int allSpaces(const char *z, int n){
   144221   while( n>0 && z[n-1]==' ' ){ n--; }
   144222   return n==0;
   144223 }
   144224 
   144225 /*
   144226 ** This is the default collating function named "BINARY" which is always
   144227 ** available.
   144228 **
   144229 ** If the padFlag argument is not NULL then space padding at the end
   144230 ** of strings is ignored.  This implements the RTRIM collation.
   144231 */
   144232 static int binCollFunc(
   144233   void *padFlag,
   144234   int nKey1, const void *pKey1,
   144235   int nKey2, const void *pKey2
   144236 ){
   144237   int rc, n;
   144238   n = nKey1<nKey2 ? nKey1 : nKey2;
   144239   /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
   144240   ** strings byte by byte using the memcmp() function from the standard C
   144241   ** library. */
   144242   assert( pKey1 && pKey2 );
   144243   rc = memcmp(pKey1, pKey2, n);
   144244   if( rc==0 ){
   144245     if( padFlag
   144246      && allSpaces(((char*)pKey1)+n, nKey1-n)
   144247      && allSpaces(((char*)pKey2)+n, nKey2-n)
   144248     ){
   144249       /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
   144250       ** spaces at the end of either string do not change the result. In other
   144251       ** words, strings will compare equal to one another as long as they
   144252       ** differ only in the number of spaces at the end.
   144253       */
   144254     }else{
   144255       rc = nKey1 - nKey2;
   144256     }
   144257   }
   144258   return rc;
   144259 }
   144260 
   144261 /*
   144262 ** Another built-in collating sequence: NOCASE.
   144263 **
   144264 ** This collating sequence is intended to be used for "case independent
   144265 ** comparison". SQLite's knowledge of upper and lower case equivalents
   144266 ** extends only to the 26 characters used in the English language.
   144267 **
   144268 ** At the moment there is only a UTF-8 implementation.
   144269 */
   144270 static int nocaseCollatingFunc(
   144271   void *NotUsed,
   144272   int nKey1, const void *pKey1,
   144273   int nKey2, const void *pKey2
   144274 ){
   144275   int r = sqlite3StrNICmp(
   144276       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
   144277   UNUSED_PARAMETER(NotUsed);
   144278   if( 0==r ){
   144279     r = nKey1-nKey2;
   144280   }
   144281   return r;
   144282 }
   144283 
   144284 /*
   144285 ** Return the ROWID of the most recent insert
   144286 */
   144287 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
   144288 #ifdef SQLITE_ENABLE_API_ARMOR
   144289   if( !sqlite3SafetyCheckOk(db) ){
   144290     (void)SQLITE_MISUSE_BKPT;
   144291     return 0;
   144292   }
   144293 #endif
   144294   return db->lastRowid;
   144295 }
   144296 
   144297 /*
   144298 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
   144299 */
   144300 SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
   144301 #ifdef SQLITE_ENABLE_API_ARMOR
   144302   if( !sqlite3SafetyCheckOk(db) ){
   144303     (void)SQLITE_MISUSE_BKPT;
   144304     return;
   144305   }
   144306 #endif
   144307   sqlite3_mutex_enter(db->mutex);
   144308   db->lastRowid = iRowid;
   144309   sqlite3_mutex_leave(db->mutex);
   144310 }
   144311 
   144312 /*
   144313 ** Return the number of changes in the most recent call to sqlite3_exec().
   144314 */
   144315 SQLITE_API int sqlite3_changes(sqlite3 *db){
   144316 #ifdef SQLITE_ENABLE_API_ARMOR
   144317   if( !sqlite3SafetyCheckOk(db) ){
   144318     (void)SQLITE_MISUSE_BKPT;
   144319     return 0;
   144320   }
   144321 #endif
   144322   return db->nChange;
   144323 }
   144324 
   144325 /*
   144326 ** Return the number of changes since the database handle was opened.
   144327 */
   144328 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
   144329 #ifdef SQLITE_ENABLE_API_ARMOR
   144330   if( !sqlite3SafetyCheckOk(db) ){
   144331     (void)SQLITE_MISUSE_BKPT;
   144332     return 0;
   144333   }
   144334 #endif
   144335   return db->nTotalChange;
   144336 }
   144337 
   144338 /*
   144339 ** Close all open savepoints. This function only manipulates fields of the
   144340 ** database handle object, it does not close any savepoints that may be open
   144341 ** at the b-tree/pager level.
   144342 */
   144343 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
   144344   while( db->pSavepoint ){
   144345     Savepoint *pTmp = db->pSavepoint;
   144346     db->pSavepoint = pTmp->pNext;
   144347     sqlite3DbFree(db, pTmp);
   144348   }
   144349   db->nSavepoint = 0;
   144350   db->nStatement = 0;
   144351   db->isTransactionSavepoint = 0;
   144352 }
   144353 
   144354 /*
   144355 ** Invoke the destructor function associated with FuncDef p, if any. Except,
   144356 ** if this is not the last copy of the function, do not invoke it. Multiple
   144357 ** copies of a single function are created when create_function() is called
   144358 ** with SQLITE_ANY as the encoding.
   144359 */
   144360 static void functionDestroy(sqlite3 *db, FuncDef *p){
   144361   FuncDestructor *pDestructor = p->u.pDestructor;
   144362   if( pDestructor ){
   144363     pDestructor->nRef--;
   144364     if( pDestructor->nRef==0 ){
   144365       pDestructor->xDestroy(pDestructor->pUserData);
   144366       sqlite3DbFree(db, pDestructor);
   144367     }
   144368   }
   144369 }
   144370 
   144371 /*
   144372 ** Disconnect all sqlite3_vtab objects that belong to database connection
   144373 ** db. This is called when db is being closed.
   144374 */
   144375 static void disconnectAllVtab(sqlite3 *db){
   144376 #ifndef SQLITE_OMIT_VIRTUALTABLE
   144377   int i;
   144378   HashElem *p;
   144379   sqlite3BtreeEnterAll(db);
   144380   for(i=0; i<db->nDb; i++){
   144381     Schema *pSchema = db->aDb[i].pSchema;
   144382     if( db->aDb[i].pSchema ){
   144383       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
   144384         Table *pTab = (Table *)sqliteHashData(p);
   144385         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
   144386       }
   144387     }
   144388   }
   144389   for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
   144390     Module *pMod = (Module *)sqliteHashData(p);
   144391     if( pMod->pEpoTab ){
   144392       sqlite3VtabDisconnect(db, pMod->pEpoTab);
   144393     }
   144394   }
   144395   sqlite3VtabUnlockList(db);
   144396   sqlite3BtreeLeaveAll(db);
   144397 #else
   144398   UNUSED_PARAMETER(db);
   144399 #endif
   144400 }
   144401 
   144402 /*
   144403 ** Return TRUE if database connection db has unfinalized prepared
   144404 ** statements or unfinished sqlite3_backup objects.
   144405 */
   144406 static int connectionIsBusy(sqlite3 *db){
   144407   int j;
   144408   assert( sqlite3_mutex_held(db->mutex) );
   144409   if( db->pVdbe ) return 1;
   144410   for(j=0; j<db->nDb; j++){
   144411     Btree *pBt = db->aDb[j].pBt;
   144412     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
   144413   }
   144414   return 0;
   144415 }
   144416 
   144417 /*
   144418 ** Close an existing SQLite database
   144419 */
   144420 static int sqlite3Close(sqlite3 *db, int forceZombie){
   144421   if( !db ){
   144422     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
   144423     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
   144424     return SQLITE_OK;
   144425   }
   144426   if( !sqlite3SafetyCheckSickOrOk(db) ){
   144427     return SQLITE_MISUSE_BKPT;
   144428   }
   144429   sqlite3_mutex_enter(db->mutex);
   144430   if( db->mTrace & SQLITE_TRACE_CLOSE ){
   144431     db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
   144432   }
   144433 
   144434   /* Force xDisconnect calls on all virtual tables */
   144435   disconnectAllVtab(db);
   144436 
   144437   /* If a transaction is open, the disconnectAllVtab() call above
   144438   ** will not have called the xDisconnect() method on any virtual
   144439   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
   144440   ** call will do so. We need to do this before the check for active
   144441   ** SQL statements below, as the v-table implementation may be storing
   144442   ** some prepared statements internally.
   144443   */
   144444   sqlite3VtabRollback(db);
   144445 
   144446   /* Legacy behavior (sqlite3_close() behavior) is to return
   144447   ** SQLITE_BUSY if the connection can not be closed immediately.
   144448   */
   144449   if( !forceZombie && connectionIsBusy(db) ){
   144450     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
   144451        "statements or unfinished backups");
   144452     sqlite3_mutex_leave(db->mutex);
   144453     return SQLITE_BUSY;
   144454   }
   144455 
   144456 #ifdef SQLITE_ENABLE_SQLLOG
   144457   if( sqlite3GlobalConfig.xSqllog ){
   144458     /* Closing the handle. Fourth parameter is passed the value 2. */
   144459     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
   144460   }
   144461 #endif
   144462 
   144463   /* Convert the connection into a zombie and then close it.
   144464   */
   144465   db->magic = SQLITE_MAGIC_ZOMBIE;
   144466   sqlite3LeaveMutexAndCloseZombie(db);
   144467   return SQLITE_OK;
   144468 }
   144469 
   144470 /*
   144471 ** Two variations on the public interface for closing a database
   144472 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
   144473 ** leaves the connection option if there are unfinalized prepared
   144474 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
   144475 ** version forces the connection to become a zombie if there are
   144476 ** unclosed resources, and arranges for deallocation when the last
   144477 ** prepare statement or sqlite3_backup closes.
   144478 */
   144479 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
   144480 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
   144481 
   144482 
   144483 /*
   144484 ** Close the mutex on database connection db.
   144485 **
   144486 ** Furthermore, if database connection db is a zombie (meaning that there
   144487 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
   144488 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
   144489 ** finished, then free all resources.
   144490 */
   144491 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
   144492   HashElem *i;                    /* Hash table iterator */
   144493   int j;
   144494 
   144495   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
   144496   ** or if the connection has not yet been closed by sqlite3_close_v2(),
   144497   ** then just leave the mutex and return.
   144498   */
   144499   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
   144500     sqlite3_mutex_leave(db->mutex);
   144501     return;
   144502   }
   144503 
   144504   /* If we reach this point, it means that the database connection has
   144505   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
   144506   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
   144507   ** go ahead and free all resources.
   144508   */
   144509 
   144510   /* If a transaction is open, roll it back. This also ensures that if
   144511   ** any database schemas have been modified by an uncommitted transaction
   144512   ** they are reset. And that the required b-tree mutex is held to make
   144513   ** the pager rollback and schema reset an atomic operation. */
   144514   sqlite3RollbackAll(db, SQLITE_OK);
   144515 
   144516   /* Free any outstanding Savepoint structures. */
   144517   sqlite3CloseSavepoints(db);
   144518 
   144519   /* Close all database connections */
   144520   for(j=0; j<db->nDb; j++){
   144521     struct Db *pDb = &db->aDb[j];
   144522     if( pDb->pBt ){
   144523       sqlite3BtreeClose(pDb->pBt);
   144524       pDb->pBt = 0;
   144525       if( j!=1 ){
   144526         pDb->pSchema = 0;
   144527       }
   144528     }
   144529   }
   144530   /* Clear the TEMP schema separately and last */
   144531   if( db->aDb[1].pSchema ){
   144532     sqlite3SchemaClear(db->aDb[1].pSchema);
   144533   }
   144534   sqlite3VtabUnlockList(db);
   144535 
   144536   /* Free up the array of auxiliary databases */
   144537   sqlite3CollapseDatabaseArray(db);
   144538   assert( db->nDb<=2 );
   144539   assert( db->aDb==db->aDbStatic );
   144540 
   144541   /* Tell the code in notify.c that the connection no longer holds any
   144542   ** locks and does not require any further unlock-notify callbacks.
   144543   */
   144544   sqlite3ConnectionClosed(db);
   144545 
   144546   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
   144547     FuncDef *pNext, *p;
   144548     p = sqliteHashData(i);
   144549     do{
   144550       functionDestroy(db, p);
   144551       pNext = p->pNext;
   144552       sqlite3DbFree(db, p);
   144553       p = pNext;
   144554     }while( p );
   144555   }
   144556   sqlite3HashClear(&db->aFunc);
   144557   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
   144558     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   144559     /* Invoke any destructors registered for collation sequence user data. */
   144560     for(j=0; j<3; j++){
   144561       if( pColl[j].xDel ){
   144562         pColl[j].xDel(pColl[j].pUser);
   144563       }
   144564     }
   144565     sqlite3DbFree(db, pColl);
   144566   }
   144567   sqlite3HashClear(&db->aCollSeq);
   144568 #ifndef SQLITE_OMIT_VIRTUALTABLE
   144569   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
   144570     Module *pMod = (Module *)sqliteHashData(i);
   144571     if( pMod->xDestroy ){
   144572       pMod->xDestroy(pMod->pAux);
   144573     }
   144574     sqlite3VtabEponymousTableClear(db, pMod);
   144575     sqlite3DbFree(db, pMod);
   144576   }
   144577   sqlite3HashClear(&db->aModule);
   144578 #endif
   144579 
   144580   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
   144581   sqlite3ValueFree(db->pErr);
   144582   sqlite3CloseExtensions(db);
   144583 #if SQLITE_USER_AUTHENTICATION
   144584   sqlite3_free(db->auth.zAuthUser);
   144585   sqlite3_free(db->auth.zAuthPW);
   144586 #endif
   144587 
   144588   db->magic = SQLITE_MAGIC_ERROR;
   144589 
   144590   /* The temp-database schema is allocated differently from the other schema
   144591   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   144592   ** So it needs to be freed here. Todo: Why not roll the temp schema into
   144593   ** the same sqliteMalloc() as the one that allocates the database
   144594   ** structure?
   144595   */
   144596   sqlite3DbFree(db, db->aDb[1].pSchema);
   144597   sqlite3_mutex_leave(db->mutex);
   144598   db->magic = SQLITE_MAGIC_CLOSED;
   144599   sqlite3_mutex_free(db->mutex);
   144600   assert( sqlite3LookasideUsed(db,0)==0 );
   144601   if( db->lookaside.bMalloced ){
   144602     sqlite3_free(db->lookaside.pStart);
   144603   }
   144604   sqlite3_free(db);
   144605 }
   144606 
   144607 /*
   144608 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
   144609 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
   144610 ** breaker") and made to return tripCode if there are any further
   144611 ** attempts to use that cursor.  Read cursors remain open and valid
   144612 ** but are "saved" in case the table pages are moved around.
   144613 */
   144614 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   144615   int i;
   144616   int inTrans = 0;
   144617   int schemaChange;
   144618   assert( sqlite3_mutex_held(db->mutex) );
   144619   sqlite3BeginBenignMalloc();
   144620 
   144621   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
   144622   ** This is important in case the transaction being rolled back has
   144623   ** modified the database schema. If the b-tree mutexes are not taken
   144624   ** here, then another shared-cache connection might sneak in between
   144625   ** the database rollback and schema reset, which can cause false
   144626   ** corruption reports in some cases.  */
   144627   sqlite3BtreeEnterAll(db);
   144628   schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
   144629 
   144630   for(i=0; i<db->nDb; i++){
   144631     Btree *p = db->aDb[i].pBt;
   144632     if( p ){
   144633       if( sqlite3BtreeIsInTrans(p) ){
   144634         inTrans = 1;
   144635       }
   144636       sqlite3BtreeRollback(p, tripCode, !schemaChange);
   144637     }
   144638   }
   144639   sqlite3VtabRollback(db);
   144640   sqlite3EndBenignMalloc();
   144641 
   144642   if( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
   144643     sqlite3ExpirePreparedStatements(db);
   144644     sqlite3ResetAllSchemasOfConnection(db);
   144645   }
   144646   sqlite3BtreeLeaveAll(db);
   144647 
   144648   /* Any deferred constraint violations have now been resolved. */
   144649   db->nDeferredCons = 0;
   144650   db->nDeferredImmCons = 0;
   144651   db->flags &= ~SQLITE_DeferFKs;
   144652 
   144653   /* If one has been configured, invoke the rollback-hook callback */
   144654   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
   144655     db->xRollbackCallback(db->pRollbackArg);
   144656   }
   144657 }
   144658 
   144659 /*
   144660 ** Return a static string containing the name corresponding to the error code
   144661 ** specified in the argument.
   144662 */
   144663 #if defined(SQLITE_NEED_ERR_NAME)
   144664 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
   144665   const char *zName = 0;
   144666   int i, origRc = rc;
   144667   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
   144668     switch( rc ){
   144669       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
   144670       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
   144671       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
   144672       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
   144673       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
   144674       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
   144675       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
   144676       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
   144677       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
   144678       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
   144679       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
   144680       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
   144681       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
   144682       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
   144683       case SQLITE_READONLY_CANTINIT:  zName = "SQLITE_READONLY_CANTINIT"; break;
   144684       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
   144685       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
   144686       case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
   144687       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
   144688       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
   144689       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
   144690       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
   144691       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
   144692       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
   144693       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
   144694       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
   144695       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
   144696       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
   144697       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
   144698       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
   144699       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
   144700       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
   144701       case SQLITE_IOERR_CHECKRESERVEDLOCK:
   144702                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
   144703       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
   144704       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
   144705       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
   144706       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
   144707       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
   144708       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
   144709       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
   144710       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
   144711       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
   144712       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
   144713       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
   144714       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
   144715       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
   144716       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
   144717       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
   144718       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
   144719       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
   144720       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
   144721       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
   144722       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
   144723       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
   144724       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
   144725       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
   144726       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
   144727       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
   144728       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
   144729       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
   144730       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
   144731       case SQLITE_CONSTRAINT_FOREIGNKEY:
   144732                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
   144733       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
   144734       case SQLITE_CONSTRAINT_PRIMARYKEY:
   144735                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
   144736       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
   144737       case SQLITE_CONSTRAINT_COMMITHOOK:
   144738                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
   144739       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
   144740       case SQLITE_CONSTRAINT_FUNCTION:
   144741                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
   144742       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
   144743       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
   144744       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
   144745       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
   144746       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
   144747       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
   144748       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
   144749       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
   144750       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
   144751       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
   144752       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
   144753       case SQLITE_NOTICE_RECOVER_ROLLBACK:
   144754                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
   144755       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
   144756       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
   144757       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
   144758     }
   144759   }
   144760   if( zName==0 ){
   144761     static char zBuf[50];
   144762     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
   144763     zName = zBuf;
   144764   }
   144765   return zName;
   144766 }
   144767 #endif
   144768 
   144769 /*
   144770 ** Return a static string that describes the kind of error specified in the
   144771 ** argument.
   144772 */
   144773 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
   144774   static const char* const aMsg[] = {
   144775     /* SQLITE_OK          */ "not an error",
   144776     /* SQLITE_ERROR       */ "SQL logic error",
   144777     /* SQLITE_INTERNAL    */ 0,
   144778     /* SQLITE_PERM        */ "access permission denied",
   144779     /* SQLITE_ABORT       */ "query aborted",
   144780     /* SQLITE_BUSY        */ "database is locked",
   144781     /* SQLITE_LOCKED      */ "database table is locked",
   144782     /* SQLITE_NOMEM       */ "out of memory",
   144783     /* SQLITE_READONLY    */ "attempt to write a readonly database",
   144784     /* SQLITE_INTERRUPT   */ "interrupted",
   144785     /* SQLITE_IOERR       */ "disk I/O error",
   144786     /* SQLITE_CORRUPT     */ "database disk image is malformed",
   144787     /* SQLITE_NOTFOUND    */ "unknown operation",
   144788     /* SQLITE_FULL        */ "database or disk is full",
   144789     /* SQLITE_CANTOPEN    */ "unable to open database file",
   144790     /* SQLITE_PROTOCOL    */ "locking protocol",
   144791     /* SQLITE_EMPTY       */ 0,
   144792     /* SQLITE_SCHEMA      */ "database schema has changed",
   144793     /* SQLITE_TOOBIG      */ "string or blob too big",
   144794     /* SQLITE_CONSTRAINT  */ "constraint failed",
   144795     /* SQLITE_MISMATCH    */ "datatype mismatch",
   144796     /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
   144797 #ifdef SQLITE_DISABLE_LFS
   144798     /* SQLITE_NOLFS       */ "large file support is disabled",
   144799 #else
   144800     /* SQLITE_NOLFS       */ 0,
   144801 #endif
   144802     /* SQLITE_AUTH        */ "authorization denied",
   144803     /* SQLITE_FORMAT      */ 0,
   144804     /* SQLITE_RANGE       */ "column index out of range",
   144805     /* SQLITE_NOTADB      */ "file is not a database",
   144806   };
   144807   const char *zErr = "unknown error";
   144808   switch( rc ){
   144809     case SQLITE_ABORT_ROLLBACK: {
   144810       zErr = "abort due to ROLLBACK";
   144811       break;
   144812     }
   144813     default: {
   144814       rc &= 0xff;
   144815       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
   144816         zErr = aMsg[rc];
   144817       }
   144818       break;
   144819     }
   144820   }
   144821   return zErr;
   144822 }
   144823 
   144824 /*
   144825 ** This routine implements a busy callback that sleeps and tries
   144826 ** again until a timeout value is reached.  The timeout value is
   144827 ** an integer number of milliseconds passed in as the first
   144828 ** argument.
   144829 */
   144830 static int sqliteDefaultBusyCallback(
   144831  void *ptr,               /* Database connection */
   144832  int count                /* Number of times table has been busy */
   144833 ){
   144834 #if SQLITE_OS_WIN || HAVE_USLEEP
   144835   static const u8 delays[] =
   144836      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
   144837   static const u8 totals[] =
   144838      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
   144839 # define NDELAY ArraySize(delays)
   144840   sqlite3 *db = (sqlite3 *)ptr;
   144841   int timeout = db->busyTimeout;
   144842   int delay, prior;
   144843 
   144844   assert( count>=0 );
   144845   if( count < NDELAY ){
   144846     delay = delays[count];
   144847     prior = totals[count];
   144848   }else{
   144849     delay = delays[NDELAY-1];
   144850     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
   144851   }
   144852   if( prior + delay > timeout ){
   144853     delay = timeout - prior;
   144854     if( delay<=0 ) return 0;
   144855   }
   144856   sqlite3OsSleep(db->pVfs, delay*1000);
   144857   return 1;
   144858 #else
   144859   sqlite3 *db = (sqlite3 *)ptr;
   144860   int timeout = ((sqlite3 *)ptr)->busyTimeout;
   144861   if( (count+1)*1000 > timeout ){
   144862     return 0;
   144863   }
   144864   sqlite3OsSleep(db->pVfs, 1000000);
   144865   return 1;
   144866 #endif
   144867 }
   144868 
   144869 /*
   144870 ** Invoke the given busy handler.
   144871 **
   144872 ** This routine is called when an operation failed with a lock.
   144873 ** If this routine returns non-zero, the lock is retried.  If it
   144874 ** returns 0, the operation aborts with an SQLITE_BUSY error.
   144875 */
   144876 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   144877   int rc;
   144878   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
   144879   rc = p->xFunc(p->pArg, p->nBusy);
   144880   if( rc==0 ){
   144881     p->nBusy = -1;
   144882   }else{
   144883     p->nBusy++;
   144884   }
   144885   return rc;
   144886 }
   144887 
   144888 /*
   144889 ** This routine sets the busy callback for an Sqlite database to the
   144890 ** given callback function with the given argument.
   144891 */
   144892 SQLITE_API int sqlite3_busy_handler(
   144893   sqlite3 *db,
   144894   int (*xBusy)(void*,int),
   144895   void *pArg
   144896 ){
   144897 #ifdef SQLITE_ENABLE_API_ARMOR
   144898   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   144899 #endif
   144900   sqlite3_mutex_enter(db->mutex);
   144901   db->busyHandler.xFunc = xBusy;
   144902   db->busyHandler.pArg = pArg;
   144903   db->busyHandler.nBusy = 0;
   144904   db->busyTimeout = 0;
   144905   sqlite3_mutex_leave(db->mutex);
   144906   return SQLITE_OK;
   144907 }
   144908 
   144909 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   144910 /*
   144911 ** This routine sets the progress callback for an Sqlite database to the
   144912 ** given callback function with the given argument. The progress callback will
   144913 ** be invoked every nOps opcodes.
   144914 */
   144915 SQLITE_API void sqlite3_progress_handler(
   144916   sqlite3 *db,
   144917   int nOps,
   144918   int (*xProgress)(void*),
   144919   void *pArg
   144920 ){
   144921 #ifdef SQLITE_ENABLE_API_ARMOR
   144922   if( !sqlite3SafetyCheckOk(db) ){
   144923     (void)SQLITE_MISUSE_BKPT;
   144924     return;
   144925   }
   144926 #endif
   144927   sqlite3_mutex_enter(db->mutex);
   144928   if( nOps>0 ){
   144929     db->xProgress = xProgress;
   144930     db->nProgressOps = (unsigned)nOps;
   144931     db->pProgressArg = pArg;
   144932   }else{
   144933     db->xProgress = 0;
   144934     db->nProgressOps = 0;
   144935     db->pProgressArg = 0;
   144936   }
   144937   sqlite3_mutex_leave(db->mutex);
   144938 }
   144939 #endif
   144940 
   144941 
   144942 /*
   144943 ** This routine installs a default busy handler that waits for the
   144944 ** specified number of milliseconds before returning 0.
   144945 */
   144946 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
   144947 #ifdef SQLITE_ENABLE_API_ARMOR
   144948   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   144949 #endif
   144950   if( ms>0 ){
   144951     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
   144952     db->busyTimeout = ms;
   144953   }else{
   144954     sqlite3_busy_handler(db, 0, 0);
   144955   }
   144956   return SQLITE_OK;
   144957 }
   144958 
   144959 /*
   144960 ** Cause any pending operation to stop at its earliest opportunity.
   144961 */
   144962 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
   144963 #ifdef SQLITE_ENABLE_API_ARMOR
   144964   if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
   144965     (void)SQLITE_MISUSE_BKPT;
   144966     return;
   144967   }
   144968 #endif
   144969   db->u1.isInterrupted = 1;
   144970 }
   144971 
   144972 
   144973 /*
   144974 ** This function is exactly the same as sqlite3_create_function(), except
   144975 ** that it is designed to be called by internal code. The difference is
   144976 ** that if a malloc() fails in sqlite3_create_function(), an error code
   144977 ** is returned and the mallocFailed flag cleared.
   144978 */
   144979 SQLITE_PRIVATE int sqlite3CreateFunc(
   144980   sqlite3 *db,
   144981   const char *zFunctionName,
   144982   int nArg,
   144983   int enc,
   144984   void *pUserData,
   144985   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
   144986   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   144987   void (*xFinal)(sqlite3_context*),
   144988   FuncDestructor *pDestructor
   144989 ){
   144990   FuncDef *p;
   144991   int nName;
   144992   int extraFlags;
   144993 
   144994   assert( sqlite3_mutex_held(db->mutex) );
   144995   if( zFunctionName==0 ||
   144996       (xSFunc && (xFinal || xStep)) ||
   144997       (!xSFunc && (xFinal && !xStep)) ||
   144998       (!xSFunc && (!xFinal && xStep)) ||
   144999       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   145000       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   145001     return SQLITE_MISUSE_BKPT;
   145002   }
   145003 
   145004   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
   145005   extraFlags = enc &  SQLITE_DETERMINISTIC;
   145006   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
   145007 
   145008 #ifndef SQLITE_OMIT_UTF16
   145009   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   145010   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   145011   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   145012   **
   145013   ** If SQLITE_ANY is specified, add three versions of the function
   145014   ** to the hash table.
   145015   */
   145016   if( enc==SQLITE_UTF16 ){
   145017     enc = SQLITE_UTF16NATIVE;
   145018   }else if( enc==SQLITE_ANY ){
   145019     int rc;
   145020     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
   145021          pUserData, xSFunc, xStep, xFinal, pDestructor);
   145022     if( rc==SQLITE_OK ){
   145023       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
   145024           pUserData, xSFunc, xStep, xFinal, pDestructor);
   145025     }
   145026     if( rc!=SQLITE_OK ){
   145027       return rc;
   145028     }
   145029     enc = SQLITE_UTF16BE;
   145030   }
   145031 #else
   145032   enc = SQLITE_UTF8;
   145033 #endif
   145034 
   145035   /* Check if an existing function is being overridden or deleted. If so,
   145036   ** and there are active VMs, then return SQLITE_BUSY. If a function
   145037   ** is being overridden/deleted but there are no active VMs, allow the
   145038   ** operation to continue but invalidate all precompiled statements.
   145039   */
   145040   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
   145041   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
   145042     if( db->nVdbeActive ){
   145043       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
   145044         "unable to delete/modify user-function due to active statements");
   145045       assert( !db->mallocFailed );
   145046       return SQLITE_BUSY;
   145047     }else{
   145048       sqlite3ExpirePreparedStatements(db);
   145049     }
   145050   }
   145051 
   145052   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
   145053   assert(p || db->mallocFailed);
   145054   if( !p ){
   145055     return SQLITE_NOMEM_BKPT;
   145056   }
   145057 
   145058   /* If an older version of the function with a configured destructor is
   145059   ** being replaced invoke the destructor function here. */
   145060   functionDestroy(db, p);
   145061 
   145062   if( pDestructor ){
   145063     pDestructor->nRef++;
   145064   }
   145065   p->u.pDestructor = pDestructor;
   145066   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
   145067   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
   145068   p->xSFunc = xSFunc ? xSFunc : xStep;
   145069   p->xFinalize = xFinal;
   145070   p->pUserData = pUserData;
   145071   p->nArg = (u16)nArg;
   145072   return SQLITE_OK;
   145073 }
   145074 
   145075 /*
   145076 ** Create new user functions.
   145077 */
   145078 SQLITE_API int sqlite3_create_function(
   145079   sqlite3 *db,
   145080   const char *zFunc,
   145081   int nArg,
   145082   int enc,
   145083   void *p,
   145084   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
   145085   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   145086   void (*xFinal)(sqlite3_context*)
   145087 ){
   145088   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
   145089                                     xFinal, 0);
   145090 }
   145091 
   145092 SQLITE_API int sqlite3_create_function_v2(
   145093   sqlite3 *db,
   145094   const char *zFunc,
   145095   int nArg,
   145096   int enc,
   145097   void *p,
   145098   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
   145099   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   145100   void (*xFinal)(sqlite3_context*),
   145101   void (*xDestroy)(void *)
   145102 ){
   145103   int rc = SQLITE_ERROR;
   145104   FuncDestructor *pArg = 0;
   145105 
   145106 #ifdef SQLITE_ENABLE_API_ARMOR
   145107   if( !sqlite3SafetyCheckOk(db) ){
   145108     return SQLITE_MISUSE_BKPT;
   145109   }
   145110 #endif
   145111   sqlite3_mutex_enter(db->mutex);
   145112   if( xDestroy ){
   145113     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
   145114     if( !pArg ){
   145115       xDestroy(p);
   145116       goto out;
   145117     }
   145118     pArg->xDestroy = xDestroy;
   145119     pArg->pUserData = p;
   145120   }
   145121   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
   145122   if( pArg && pArg->nRef==0 ){
   145123     assert( rc!=SQLITE_OK );
   145124     xDestroy(p);
   145125     sqlite3DbFree(db, pArg);
   145126   }
   145127 
   145128  out:
   145129   rc = sqlite3ApiExit(db, rc);
   145130   sqlite3_mutex_leave(db->mutex);
   145131   return rc;
   145132 }
   145133 
   145134 #ifndef SQLITE_OMIT_UTF16
   145135 SQLITE_API int sqlite3_create_function16(
   145136   sqlite3 *db,
   145137   const void *zFunctionName,
   145138   int nArg,
   145139   int eTextRep,
   145140   void *p,
   145141   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
   145142   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   145143   void (*xFinal)(sqlite3_context*)
   145144 ){
   145145   int rc;
   145146   char *zFunc8;
   145147 
   145148 #ifdef SQLITE_ENABLE_API_ARMOR
   145149   if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
   145150 #endif
   145151   sqlite3_mutex_enter(db->mutex);
   145152   assert( !db->mallocFailed );
   145153   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
   145154   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
   145155   sqlite3DbFree(db, zFunc8);
   145156   rc = sqlite3ApiExit(db, rc);
   145157   sqlite3_mutex_leave(db->mutex);
   145158   return rc;
   145159 }
   145160 #endif
   145161 
   145162 
   145163 /*
   145164 ** Declare that a function has been overloaded by a virtual table.
   145165 **
   145166 ** If the function already exists as a regular global function, then
   145167 ** this routine is a no-op.  If the function does not exist, then create
   145168 ** a new one that always throws a run-time error.
   145169 **
   145170 ** When virtual tables intend to provide an overloaded function, they
   145171 ** should call this routine to make sure the global function exists.
   145172 ** A global function must exist in order for name resolution to work
   145173 ** properly.
   145174 */
   145175 SQLITE_API int sqlite3_overload_function(
   145176   sqlite3 *db,
   145177   const char *zName,
   145178   int nArg
   145179 ){
   145180   int rc = SQLITE_OK;
   145181 
   145182 #ifdef SQLITE_ENABLE_API_ARMOR
   145183   if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
   145184     return SQLITE_MISUSE_BKPT;
   145185   }
   145186 #endif
   145187   sqlite3_mutex_enter(db->mutex);
   145188   if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
   145189     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   145190                            0, sqlite3InvalidFunction, 0, 0, 0);
   145191   }
   145192   rc = sqlite3ApiExit(db, rc);
   145193   sqlite3_mutex_leave(db->mutex);
   145194   return rc;
   145195 }
   145196 
   145197 #ifndef SQLITE_OMIT_TRACE
   145198 /*
   145199 ** Register a trace function.  The pArg from the previously registered trace
   145200 ** is returned.
   145201 **
   145202 ** A NULL trace function means that no tracing is executes.  A non-NULL
   145203 ** trace is a pointer to a function that is invoked at the start of each
   145204 ** SQL statement.
   145205 */
   145206 #ifndef SQLITE_OMIT_DEPRECATED
   145207 SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
   145208   void *pOld;
   145209 
   145210 #ifdef SQLITE_ENABLE_API_ARMOR
   145211   if( !sqlite3SafetyCheckOk(db) ){
   145212     (void)SQLITE_MISUSE_BKPT;
   145213     return 0;
   145214   }
   145215 #endif
   145216   sqlite3_mutex_enter(db->mutex);
   145217   pOld = db->pTraceArg;
   145218   db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
   145219   db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
   145220   db->pTraceArg = pArg;
   145221   sqlite3_mutex_leave(db->mutex);
   145222   return pOld;
   145223 }
   145224 #endif /* SQLITE_OMIT_DEPRECATED */
   145225 
   145226 /* Register a trace callback using the version-2 interface.
   145227 */
   145228 SQLITE_API int sqlite3_trace_v2(
   145229   sqlite3 *db,                               /* Trace this connection */
   145230   unsigned mTrace,                           /* Mask of events to be traced */
   145231   int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
   145232   void *pArg                                 /* Context */
   145233 ){
   145234 #ifdef SQLITE_ENABLE_API_ARMOR
   145235   if( !sqlite3SafetyCheckOk(db) ){
   145236     return SQLITE_MISUSE_BKPT;
   145237   }
   145238 #endif
   145239   sqlite3_mutex_enter(db->mutex);
   145240   if( mTrace==0 ) xTrace = 0;
   145241   if( xTrace==0 ) mTrace = 0;
   145242   db->mTrace = mTrace;
   145243   db->xTrace = xTrace;
   145244   db->pTraceArg = pArg;
   145245   sqlite3_mutex_leave(db->mutex);
   145246   return SQLITE_OK;
   145247 }
   145248 
   145249 #ifndef SQLITE_OMIT_DEPRECATED
   145250 /*
   145251 ** Register a profile function.  The pArg from the previously registered
   145252 ** profile function is returned.
   145253 **
   145254 ** A NULL profile function means that no profiling is executes.  A non-NULL
   145255 ** profile is a pointer to a function that is invoked at the conclusion of
   145256 ** each SQL statement that is run.
   145257 */
   145258 SQLITE_API void *sqlite3_profile(
   145259   sqlite3 *db,
   145260   void (*xProfile)(void*,const char*,sqlite_uint64),
   145261   void *pArg
   145262 ){
   145263   void *pOld;
   145264 
   145265 #ifdef SQLITE_ENABLE_API_ARMOR
   145266   if( !sqlite3SafetyCheckOk(db) ){
   145267     (void)SQLITE_MISUSE_BKPT;
   145268     return 0;
   145269   }
   145270 #endif
   145271   sqlite3_mutex_enter(db->mutex);
   145272   pOld = db->pProfileArg;
   145273   db->xProfile = xProfile;
   145274   db->pProfileArg = pArg;
   145275   sqlite3_mutex_leave(db->mutex);
   145276   return pOld;
   145277 }
   145278 #endif /* SQLITE_OMIT_DEPRECATED */
   145279 #endif /* SQLITE_OMIT_TRACE */
   145280 
   145281 /*
   145282 ** Register a function to be invoked when a transaction commits.
   145283 ** If the invoked function returns non-zero, then the commit becomes a
   145284 ** rollback.
   145285 */
   145286 SQLITE_API void *sqlite3_commit_hook(
   145287   sqlite3 *db,              /* Attach the hook to this database */
   145288   int (*xCallback)(void*),  /* Function to invoke on each commit */
   145289   void *pArg                /* Argument to the function */
   145290 ){
   145291   void *pOld;
   145292 
   145293 #ifdef SQLITE_ENABLE_API_ARMOR
   145294   if( !sqlite3SafetyCheckOk(db) ){
   145295     (void)SQLITE_MISUSE_BKPT;
   145296     return 0;
   145297   }
   145298 #endif
   145299   sqlite3_mutex_enter(db->mutex);
   145300   pOld = db->pCommitArg;
   145301   db->xCommitCallback = xCallback;
   145302   db->pCommitArg = pArg;
   145303   sqlite3_mutex_leave(db->mutex);
   145304   return pOld;
   145305 }
   145306 
   145307 /*
   145308 ** Register a callback to be invoked each time a row is updated,
   145309 ** inserted or deleted using this database connection.
   145310 */
   145311 SQLITE_API void *sqlite3_update_hook(
   145312   sqlite3 *db,              /* Attach the hook to this database */
   145313   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   145314   void *pArg                /* Argument to the function */
   145315 ){
   145316   void *pRet;
   145317 
   145318 #ifdef SQLITE_ENABLE_API_ARMOR
   145319   if( !sqlite3SafetyCheckOk(db) ){
   145320     (void)SQLITE_MISUSE_BKPT;
   145321     return 0;
   145322   }
   145323 #endif
   145324   sqlite3_mutex_enter(db->mutex);
   145325   pRet = db->pUpdateArg;
   145326   db->xUpdateCallback = xCallback;
   145327   db->pUpdateArg = pArg;
   145328   sqlite3_mutex_leave(db->mutex);
   145329   return pRet;
   145330 }
   145331 
   145332 /*
   145333 ** Register a callback to be invoked each time a transaction is rolled
   145334 ** back by this database connection.
   145335 */
   145336 SQLITE_API void *sqlite3_rollback_hook(
   145337   sqlite3 *db,              /* Attach the hook to this database */
   145338   void (*xCallback)(void*), /* Callback function */
   145339   void *pArg                /* Argument to the function */
   145340 ){
   145341   void *pRet;
   145342 
   145343 #ifdef SQLITE_ENABLE_API_ARMOR
   145344   if( !sqlite3SafetyCheckOk(db) ){
   145345     (void)SQLITE_MISUSE_BKPT;
   145346     return 0;
   145347   }
   145348 #endif
   145349   sqlite3_mutex_enter(db->mutex);
   145350   pRet = db->pRollbackArg;
   145351   db->xRollbackCallback = xCallback;
   145352   db->pRollbackArg = pArg;
   145353   sqlite3_mutex_leave(db->mutex);
   145354   return pRet;
   145355 }
   145356 
   145357 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   145358 /*
   145359 ** Register a callback to be invoked each time a row is updated,
   145360 ** inserted or deleted using this database connection.
   145361 */
   145362 SQLITE_API void *sqlite3_preupdate_hook(
   145363   sqlite3 *db,              /* Attach the hook to this database */
   145364   void(*xCallback)(         /* Callback function */
   145365     void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
   145366   void *pArg                /* First callback argument */
   145367 ){
   145368   void *pRet;
   145369   sqlite3_mutex_enter(db->mutex);
   145370   pRet = db->pPreUpdateArg;
   145371   db->xPreUpdateCallback = xCallback;
   145372   db->pPreUpdateArg = pArg;
   145373   sqlite3_mutex_leave(db->mutex);
   145374   return pRet;
   145375 }
   145376 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   145377 
   145378 #ifndef SQLITE_OMIT_WAL
   145379 /*
   145380 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
   145381 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
   145382 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
   145383 ** wal_autocheckpoint()).
   145384 */
   145385 SQLITE_PRIVATE int sqlite3WalDefaultHook(
   145386   void *pClientData,     /* Argument */
   145387   sqlite3 *db,           /* Connection */
   145388   const char *zDb,       /* Database */
   145389   int nFrame             /* Size of WAL */
   145390 ){
   145391   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
   145392     sqlite3BeginBenignMalloc();
   145393     sqlite3_wal_checkpoint(db, zDb);
   145394     sqlite3EndBenignMalloc();
   145395   }
   145396   return SQLITE_OK;
   145397 }
   145398 #endif /* SQLITE_OMIT_WAL */
   145399 
   145400 /*
   145401 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
   145402 ** a database after committing a transaction if there are nFrame or
   145403 ** more frames in the log file. Passing zero or a negative value as the
   145404 ** nFrame parameter disables automatic checkpoints entirely.
   145405 **
   145406 ** The callback registered by this function replaces any existing callback
   145407 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
   145408 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
   145409 ** configured by this function.
   145410 */
   145411 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
   145412 #ifdef SQLITE_OMIT_WAL
   145413   UNUSED_PARAMETER(db);
   145414   UNUSED_PARAMETER(nFrame);
   145415 #else
   145416 #ifdef SQLITE_ENABLE_API_ARMOR
   145417   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   145418 #endif
   145419   if( nFrame>0 ){
   145420     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
   145421   }else{
   145422     sqlite3_wal_hook(db, 0, 0);
   145423   }
   145424 #endif
   145425   return SQLITE_OK;
   145426 }
   145427 
   145428 /*
   145429 ** Register a callback to be invoked each time a transaction is written
   145430 ** into the write-ahead-log by this database connection.
   145431 */
   145432 SQLITE_API void *sqlite3_wal_hook(
   145433   sqlite3 *db,                    /* Attach the hook to this db handle */
   145434   int(*xCallback)(void *, sqlite3*, const char*, int),
   145435   void *pArg                      /* First argument passed to xCallback() */
   145436 ){
   145437 #ifndef SQLITE_OMIT_WAL
   145438   void *pRet;
   145439 #ifdef SQLITE_ENABLE_API_ARMOR
   145440   if( !sqlite3SafetyCheckOk(db) ){
   145441     (void)SQLITE_MISUSE_BKPT;
   145442     return 0;
   145443   }
   145444 #endif
   145445   sqlite3_mutex_enter(db->mutex);
   145446   pRet = db->pWalArg;
   145447   db->xWalCallback = xCallback;
   145448   db->pWalArg = pArg;
   145449   sqlite3_mutex_leave(db->mutex);
   145450   return pRet;
   145451 #else
   145452   return 0;
   145453 #endif
   145454 }
   145455 
   145456 /*
   145457 ** Checkpoint database zDb.
   145458 */
   145459 SQLITE_API int sqlite3_wal_checkpoint_v2(
   145460   sqlite3 *db,                    /* Database handle */
   145461   const char *zDb,                /* Name of attached database (or NULL) */
   145462   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   145463   int *pnLog,                     /* OUT: Size of WAL log in frames */
   145464   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   145465 ){
   145466 #ifdef SQLITE_OMIT_WAL
   145467   return SQLITE_OK;
   145468 #else
   145469   int rc;                         /* Return code */
   145470   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
   145471 
   145472 #ifdef SQLITE_ENABLE_API_ARMOR
   145473   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   145474 #endif
   145475 
   145476   /* Initialize the output variables to -1 in case an error occurs. */
   145477   if( pnLog ) *pnLog = -1;
   145478   if( pnCkpt ) *pnCkpt = -1;
   145479 
   145480   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
   145481   assert( SQLITE_CHECKPOINT_FULL==1 );
   145482   assert( SQLITE_CHECKPOINT_RESTART==2 );
   145483   assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
   145484   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
   145485     /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
   145486     ** mode: */
   145487     return SQLITE_MISUSE;
   145488   }
   145489 
   145490   sqlite3_mutex_enter(db->mutex);
   145491   if( zDb && zDb[0] ){
   145492     iDb = sqlite3FindDbName(db, zDb);
   145493   }
   145494   if( iDb<0 ){
   145495     rc = SQLITE_ERROR;
   145496     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
   145497   }else{
   145498     db->busyHandler.nBusy = 0;
   145499     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
   145500     sqlite3Error(db, rc);
   145501   }
   145502   rc = sqlite3ApiExit(db, rc);
   145503 
   145504   /* If there are no active statements, clear the interrupt flag at this
   145505   ** point.  */
   145506   if( db->nVdbeActive==0 ){
   145507     db->u1.isInterrupted = 0;
   145508   }
   145509 
   145510   sqlite3_mutex_leave(db->mutex);
   145511   return rc;
   145512 #endif
   145513 }
   145514 
   145515 
   145516 /*
   145517 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
   145518 ** to contains a zero-length string, all attached databases are
   145519 ** checkpointed.
   145520 */
   145521 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
   145522   /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
   145523   ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
   145524   return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
   145525 }
   145526 
   145527 #ifndef SQLITE_OMIT_WAL
   145528 /*
   145529 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
   145530 ** not currently open in WAL mode.
   145531 **
   145532 ** If a transaction is open on the database being checkpointed, this
   145533 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
   145534 ** an error occurs while running the checkpoint, an SQLite error code is
   145535 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
   145536 **
   145537 ** The mutex on database handle db should be held by the caller. The mutex
   145538 ** associated with the specific b-tree being checkpointed is taken by
   145539 ** this function while the checkpoint is running.
   145540 **
   145541 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
   145542 ** checkpointed. If an error is encountered it is returned immediately -
   145543 ** no attempt is made to checkpoint any remaining databases.
   145544 **
   145545 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
   145546 ** or TRUNCATE.
   145547 */
   145548 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
   145549   int rc = SQLITE_OK;             /* Return code */
   145550   int i;                          /* Used to iterate through attached dbs */
   145551   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
   145552 
   145553   assert( sqlite3_mutex_held(db->mutex) );
   145554   assert( !pnLog || *pnLog==-1 );
   145555   assert( !pnCkpt || *pnCkpt==-1 );
   145556 
   145557   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
   145558     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
   145559       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
   145560       pnLog = 0;
   145561       pnCkpt = 0;
   145562       if( rc==SQLITE_BUSY ){
   145563         bBusy = 1;
   145564         rc = SQLITE_OK;
   145565       }
   145566     }
   145567   }
   145568 
   145569   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
   145570 }
   145571 #endif /* SQLITE_OMIT_WAL */
   145572 
   145573 /*
   145574 ** This function returns true if main-memory should be used instead of
   145575 ** a temporary file for transient pager files and statement journals.
   145576 ** The value returned depends on the value of db->temp_store (runtime
   145577 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   145578 ** following table describes the relationship between these two values
   145579 ** and this functions return value.
   145580 **
   145581 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   145582 **   -----------------     --------------     ------------------------------
   145583 **   0                     any                file      (return 0)
   145584 **   1                     1                  file      (return 0)
   145585 **   1                     2                  memory    (return 1)
   145586 **   1                     0                  file      (return 0)
   145587 **   2                     1                  file      (return 0)
   145588 **   2                     2                  memory    (return 1)
   145589 **   2                     0                  memory    (return 1)
   145590 **   3                     any                memory    (return 1)
   145591 */
   145592 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
   145593 #if SQLITE_TEMP_STORE==1
   145594   return ( db->temp_store==2 );
   145595 #endif
   145596 #if SQLITE_TEMP_STORE==2
   145597   return ( db->temp_store!=1 );
   145598 #endif
   145599 #if SQLITE_TEMP_STORE==3
   145600   UNUSED_PARAMETER(db);
   145601   return 1;
   145602 #endif
   145603 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   145604   UNUSED_PARAMETER(db);
   145605   return 0;
   145606 #endif
   145607 }
   145608 
   145609 /*
   145610 ** Return UTF-8 encoded English language explanation of the most recent
   145611 ** error.
   145612 */
   145613 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   145614   const char *z;
   145615   if( !db ){
   145616     return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
   145617   }
   145618   if( !sqlite3SafetyCheckSickOrOk(db) ){
   145619     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   145620   }
   145621   sqlite3_mutex_enter(db->mutex);
   145622   if( db->mallocFailed ){
   145623     z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
   145624   }else{
   145625     testcase( db->pErr==0 );
   145626     z = (char*)sqlite3_value_text(db->pErr);
   145627     assert( !db->mallocFailed );
   145628     if( z==0 ){
   145629       z = sqlite3ErrStr(db->errCode);
   145630     }
   145631   }
   145632   sqlite3_mutex_leave(db->mutex);
   145633   return z;
   145634 }
   145635 
   145636 #ifndef SQLITE_OMIT_UTF16
   145637 /*
   145638 ** Return UTF-16 encoded English language explanation of the most recent
   145639 ** error.
   145640 */
   145641 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
   145642   static const u16 outOfMem[] = {
   145643     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   145644   };
   145645   static const u16 misuse[] = {
   145646     'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
   145647     'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
   145648     'm', 'i', 's', 'u', 's', 'e', 0
   145649   };
   145650 
   145651   const void *z;
   145652   if( !db ){
   145653     return (void *)outOfMem;
   145654   }
   145655   if( !sqlite3SafetyCheckSickOrOk(db) ){
   145656     return (void *)misuse;
   145657   }
   145658   sqlite3_mutex_enter(db->mutex);
   145659   if( db->mallocFailed ){
   145660     z = (void *)outOfMem;
   145661   }else{
   145662     z = sqlite3_value_text16(db->pErr);
   145663     if( z==0 ){
   145664       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
   145665       z = sqlite3_value_text16(db->pErr);
   145666     }
   145667     /* A malloc() may have failed within the call to sqlite3_value_text16()
   145668     ** above. If this is the case, then the db->mallocFailed flag needs to
   145669     ** be cleared before returning. Do this directly, instead of via
   145670     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   145671     */
   145672     sqlite3OomClear(db);
   145673   }
   145674   sqlite3_mutex_leave(db->mutex);
   145675   return z;
   145676 }
   145677 #endif /* SQLITE_OMIT_UTF16 */
   145678 
   145679 /*
   145680 ** Return the most recent error code generated by an SQLite routine. If NULL is
   145681 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   145682 */
   145683 SQLITE_API int sqlite3_errcode(sqlite3 *db){
   145684   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   145685     return SQLITE_MISUSE_BKPT;
   145686   }
   145687   if( !db || db->mallocFailed ){
   145688     return SQLITE_NOMEM_BKPT;
   145689   }
   145690   return db->errCode & db->errMask;
   145691 }
   145692 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
   145693   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   145694     return SQLITE_MISUSE_BKPT;
   145695   }
   145696   if( !db || db->mallocFailed ){
   145697     return SQLITE_NOMEM_BKPT;
   145698   }
   145699   return db->errCode;
   145700 }
   145701 SQLITE_API int sqlite3_system_errno(sqlite3 *db){
   145702   return db ? db->iSysErrno : 0;
   145703 }
   145704 
   145705 /*
   145706 ** Return a string that describes the kind of error specified in the
   145707 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
   145708 ** function.
   145709 */
   145710 SQLITE_API const char *sqlite3_errstr(int rc){
   145711   return sqlite3ErrStr(rc);
   145712 }
   145713 
   145714 /*
   145715 ** Create a new collating function for database "db".  The name is zName
   145716 ** and the encoding is enc.
   145717 */
   145718 static int createCollation(
   145719   sqlite3* db,
   145720   const char *zName,
   145721   u8 enc,
   145722   void* pCtx,
   145723   int(*xCompare)(void*,int,const void*,int,const void*),
   145724   void(*xDel)(void*)
   145725 ){
   145726   CollSeq *pColl;
   145727   int enc2;
   145728 
   145729   assert( sqlite3_mutex_held(db->mutex) );
   145730 
   145731   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   145732   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   145733   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   145734   */
   145735   enc2 = enc;
   145736   testcase( enc2==SQLITE_UTF16 );
   145737   testcase( enc2==SQLITE_UTF16_ALIGNED );
   145738   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   145739     enc2 = SQLITE_UTF16NATIVE;
   145740   }
   145741   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   145742     return SQLITE_MISUSE_BKPT;
   145743   }
   145744 
   145745   /* Check if this call is removing or replacing an existing collation
   145746   ** sequence. If so, and there are active VMs, return busy. If there
   145747   ** are no active VMs, invalidate any pre-compiled statements.
   145748   */
   145749   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   145750   if( pColl && pColl->xCmp ){
   145751     if( db->nVdbeActive ){
   145752       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
   145753         "unable to delete/modify collation sequence due to active statements");
   145754       return SQLITE_BUSY;
   145755     }
   145756     sqlite3ExpirePreparedStatements(db);
   145757 
   145758     /* If collation sequence pColl was created directly by a call to
   145759     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   145760     ** then any copies made by synthCollSeq() need to be invalidated.
   145761     ** Also, collation destructor - CollSeq.xDel() - function may need
   145762     ** to be called.
   145763     */
   145764     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   145765       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
   145766       int j;
   145767       for(j=0; j<3; j++){
   145768         CollSeq *p = &aColl[j];
   145769         if( p->enc==pColl->enc ){
   145770           if( p->xDel ){
   145771             p->xDel(p->pUser);
   145772           }
   145773           p->xCmp = 0;
   145774         }
   145775       }
   145776     }
   145777   }
   145778 
   145779   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   145780   if( pColl==0 ) return SQLITE_NOMEM_BKPT;
   145781   pColl->xCmp = xCompare;
   145782   pColl->pUser = pCtx;
   145783   pColl->xDel = xDel;
   145784   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   145785   sqlite3Error(db, SQLITE_OK);
   145786   return SQLITE_OK;
   145787 }
   145788 
   145789 
   145790 /*
   145791 ** This array defines hard upper bounds on limit values.  The
   145792 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   145793 ** #defines in sqlite3.h.
   145794 */
   145795 static const int aHardLimit[] = {
   145796   SQLITE_MAX_LENGTH,
   145797   SQLITE_MAX_SQL_LENGTH,
   145798   SQLITE_MAX_COLUMN,
   145799   SQLITE_MAX_EXPR_DEPTH,
   145800   SQLITE_MAX_COMPOUND_SELECT,
   145801   SQLITE_MAX_VDBE_OP,
   145802   SQLITE_MAX_FUNCTION_ARG,
   145803   SQLITE_MAX_ATTACHED,
   145804   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   145805   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
   145806   SQLITE_MAX_TRIGGER_DEPTH,
   145807   SQLITE_MAX_WORKER_THREADS,
   145808 };
   145809 
   145810 /*
   145811 ** Make sure the hard limits are set to reasonable values
   145812 */
   145813 #if SQLITE_MAX_LENGTH<100
   145814 # error SQLITE_MAX_LENGTH must be at least 100
   145815 #endif
   145816 #if SQLITE_MAX_SQL_LENGTH<100
   145817 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   145818 #endif
   145819 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   145820 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   145821 #endif
   145822 #if SQLITE_MAX_COMPOUND_SELECT<2
   145823 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   145824 #endif
   145825 #if SQLITE_MAX_VDBE_OP<40
   145826 # error SQLITE_MAX_VDBE_OP must be at least 40
   145827 #endif
   145828 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
   145829 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
   145830 #endif
   145831 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
   145832 # error SQLITE_MAX_ATTACHED must be between 0 and 125
   145833 #endif
   145834 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   145835 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   145836 #endif
   145837 #if SQLITE_MAX_COLUMN>32767
   145838 # error SQLITE_MAX_COLUMN must not exceed 32767
   145839 #endif
   145840 #if SQLITE_MAX_TRIGGER_DEPTH<1
   145841 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   145842 #endif
   145843 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
   145844 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
   145845 #endif
   145846 
   145847 
   145848 /*
   145849 ** Change the value of a limit.  Report the old value.
   145850 ** If an invalid limit index is supplied, report -1.
   145851 ** Make no changes but still report the old value if the
   145852 ** new limit is negative.
   145853 **
   145854 ** A new lower limit does not shrink existing constructs.
   145855 ** It merely prevents new constructs that exceed the limit
   145856 ** from forming.
   145857 */
   145858 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   145859   int oldLimit;
   145860 
   145861 #ifdef SQLITE_ENABLE_API_ARMOR
   145862   if( !sqlite3SafetyCheckOk(db) ){
   145863     (void)SQLITE_MISUSE_BKPT;
   145864     return -1;
   145865   }
   145866 #endif
   145867 
   145868   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
   145869   ** there is a hard upper bound set at compile-time by a C preprocessor
   145870   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
   145871   ** "_MAX_".)
   145872   */
   145873   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
   145874   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
   145875   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
   145876   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
   145877   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
   145878   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
   145879   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
   145880   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
   145881   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
   145882                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
   145883   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
   145884   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
   145885   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
   145886   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
   145887 
   145888 
   145889   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   145890     return -1;
   145891   }
   145892   oldLimit = db->aLimit[limitId];
   145893   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
   145894     if( newLimit>aHardLimit[limitId] ){
   145895       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
   145896     }
   145897     db->aLimit[limitId] = newLimit;
   145898   }
   145899   return oldLimit;                     /* IMP: R-53341-35419 */
   145900 }
   145901 
   145902 /*
   145903 ** This function is used to parse both URIs and non-URI filenames passed by the
   145904 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
   145905 ** URIs specified as part of ATTACH statements.
   145906 **
   145907 ** The first argument to this function is the name of the VFS to use (or
   145908 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
   145909 ** query parameter. The second argument contains the URI (or non-URI filename)
   145910 ** itself. When this function is called the *pFlags variable should contain
   145911 ** the default flags to open the database handle with. The value stored in
   145912 ** *pFlags may be updated before returning if the URI filename contains
   145913 ** "cache=xxx" or "mode=xxx" query parameters.
   145914 **
   145915 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
   145916 ** the VFS that should be used to open the database file. *pzFile is set to
   145917 ** point to a buffer containing the name of the file to open. It is the
   145918 ** responsibility of the caller to eventually call sqlite3_free() to release
   145919 ** this buffer.
   145920 **
   145921 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
   145922 ** may be set to point to a buffer containing an English language error
   145923 ** message. It is the responsibility of the caller to eventually release
   145924 ** this buffer by calling sqlite3_free().
   145925 */
   145926 SQLITE_PRIVATE int sqlite3ParseUri(
   145927   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
   145928   const char *zUri,               /* Nul-terminated URI to parse */
   145929   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
   145930   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
   145931   char **pzFile,                  /* OUT: Filename component of URI */
   145932   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
   145933 ){
   145934   int rc = SQLITE_OK;
   145935   unsigned int flags = *pFlags;
   145936   const char *zVfs = zDefaultVfs;
   145937   char *zFile;
   145938   char c;
   145939   int nUri = sqlite3Strlen30(zUri);
   145940 
   145941   assert( *pzErrMsg==0 );
   145942 
   145943   if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
   145944             || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
   145945    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
   145946   ){
   145947     char *zOpt;
   145948     int eState;                   /* Parser state when parsing URI */
   145949     int iIn;                      /* Input character index */
   145950     int iOut = 0;                 /* Output character index */
   145951     u64 nByte = nUri+2;           /* Bytes of space to allocate */
   145952 
   145953     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
   145954     ** method that there may be extra parameters following the file-name.  */
   145955     flags |= SQLITE_OPEN_URI;
   145956 
   145957     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
   145958     zFile = sqlite3_malloc64(nByte);
   145959     if( !zFile ) return SQLITE_NOMEM_BKPT;
   145960 
   145961     iIn = 5;
   145962 #ifdef SQLITE_ALLOW_URI_AUTHORITY
   145963     if( strncmp(zUri+5, "///", 3)==0 ){
   145964       iIn = 7;
   145965       /* The following condition causes URIs with five leading / characters
   145966       ** like file://///host/path to be converted into UNCs like //host/path.
   145967       ** The correct URI for that UNC has only two or four leading / characters
   145968       ** file://host/path or file:////host/path.  But 5 leading slashes is a
   145969       ** common error, we are told, so we handle it as a special case. */
   145970       if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
   145971     }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
   145972       iIn = 16;
   145973     }
   145974 #else
   145975     /* Discard the scheme and authority segments of the URI. */
   145976     if( zUri[5]=='/' && zUri[6]=='/' ){
   145977       iIn = 7;
   145978       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
   145979       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
   145980         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
   145981             iIn-7, &zUri[7]);
   145982         rc = SQLITE_ERROR;
   145983         goto parse_uri_out;
   145984       }
   145985     }
   145986 #endif
   145987 
   145988     /* Copy the filename and any query parameters into the zFile buffer.
   145989     ** Decode %HH escape codes along the way.
   145990     **
   145991     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
   145992     ** on the parsing context. As follows:
   145993     **
   145994     **   0: Parsing file-name.
   145995     **   1: Parsing name section of a name=value query parameter.
   145996     **   2: Parsing value section of a name=value query parameter.
   145997     */
   145998     eState = 0;
   145999     while( (c = zUri[iIn])!=0 && c!='#' ){
   146000       iIn++;
   146001       if( c=='%'
   146002        && sqlite3Isxdigit(zUri[iIn])
   146003        && sqlite3Isxdigit(zUri[iIn+1])
   146004       ){
   146005         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
   146006         octet += sqlite3HexToInt(zUri[iIn++]);
   146007 
   146008         assert( octet>=0 && octet<256 );
   146009         if( octet==0 ){
   146010 #ifndef SQLITE_ENABLE_URI_00_ERROR
   146011           /* This branch is taken when "%00" appears within the URI. In this
   146012           ** case we ignore all text in the remainder of the path, name or
   146013           ** value currently being parsed. So ignore the current character
   146014           ** and skip to the next "?", "=" or "&", as appropriate. */
   146015           while( (c = zUri[iIn])!=0 && c!='#'
   146016               && (eState!=0 || c!='?')
   146017               && (eState!=1 || (c!='=' && c!='&'))
   146018               && (eState!=2 || c!='&')
   146019           ){
   146020             iIn++;
   146021           }
   146022           continue;
   146023 #else
   146024           /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
   146025           *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
   146026           rc = SQLITE_ERROR;
   146027           goto parse_uri_out;
   146028 #endif
   146029         }
   146030         c = octet;
   146031       }else if( eState==1 && (c=='&' || c=='=') ){
   146032         if( zFile[iOut-1]==0 ){
   146033           /* An empty option name. Ignore this option altogether. */
   146034           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
   146035           continue;
   146036         }
   146037         if( c=='&' ){
   146038           zFile[iOut++] = '\0';
   146039         }else{
   146040           eState = 2;
   146041         }
   146042         c = 0;
   146043       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
   146044         c = 0;
   146045         eState = 1;
   146046       }
   146047       zFile[iOut++] = c;
   146048     }
   146049     if( eState==1 ) zFile[iOut++] = '\0';
   146050     zFile[iOut++] = '\0';
   146051     zFile[iOut++] = '\0';
   146052 
   146053     /* Check if there were any options specified that should be interpreted
   146054     ** here. Options that are interpreted here include "vfs" and those that
   146055     ** correspond to flags that may be passed to the sqlite3_open_v2()
   146056     ** method. */
   146057     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
   146058     while( zOpt[0] ){
   146059       int nOpt = sqlite3Strlen30(zOpt);
   146060       char *zVal = &zOpt[nOpt+1];
   146061       int nVal = sqlite3Strlen30(zVal);
   146062 
   146063       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
   146064         zVfs = zVal;
   146065       }else{
   146066         struct OpenMode {
   146067           const char *z;
   146068           int mode;
   146069         } *aMode = 0;
   146070         char *zModeType = 0;
   146071         int mask = 0;
   146072         int limit = 0;
   146073 
   146074         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
   146075           static struct OpenMode aCacheMode[] = {
   146076             { "shared",  SQLITE_OPEN_SHAREDCACHE },
   146077             { "private", SQLITE_OPEN_PRIVATECACHE },
   146078             { 0, 0 }
   146079           };
   146080 
   146081           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
   146082           aMode = aCacheMode;
   146083           limit = mask;
   146084           zModeType = "cache";
   146085         }
   146086         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
   146087           static struct OpenMode aOpenMode[] = {
   146088             { "ro",  SQLITE_OPEN_READONLY },
   146089             { "rw",  SQLITE_OPEN_READWRITE },
   146090             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
   146091             { "memory", SQLITE_OPEN_MEMORY },
   146092             { 0, 0 }
   146093           };
   146094 
   146095           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
   146096                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
   146097           aMode = aOpenMode;
   146098           limit = mask & flags;
   146099           zModeType = "access";
   146100         }
   146101 
   146102         if( aMode ){
   146103           int i;
   146104           int mode = 0;
   146105           for(i=0; aMode[i].z; i++){
   146106             const char *z = aMode[i].z;
   146107             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
   146108               mode = aMode[i].mode;
   146109               break;
   146110             }
   146111           }
   146112           if( mode==0 ){
   146113             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
   146114             rc = SQLITE_ERROR;
   146115             goto parse_uri_out;
   146116           }
   146117           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
   146118             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
   146119                                         zModeType, zVal);
   146120             rc = SQLITE_PERM;
   146121             goto parse_uri_out;
   146122           }
   146123           flags = (flags & ~mask) | mode;
   146124         }
   146125       }
   146126 
   146127       zOpt = &zVal[nVal+1];
   146128     }
   146129 
   146130   }else{
   146131     zFile = sqlite3_malloc64(nUri+2);
   146132     if( !zFile ) return SQLITE_NOMEM_BKPT;
   146133     if( nUri ){
   146134       memcpy(zFile, zUri, nUri);
   146135     }
   146136     zFile[nUri] = '\0';
   146137     zFile[nUri+1] = '\0';
   146138     flags &= ~SQLITE_OPEN_URI;
   146139   }
   146140 
   146141   *ppVfs = sqlite3_vfs_find(zVfs);
   146142   if( *ppVfs==0 ){
   146143     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
   146144     rc = SQLITE_ERROR;
   146145   }
   146146  parse_uri_out:
   146147   if( rc!=SQLITE_OK ){
   146148     sqlite3_free(zFile);
   146149     zFile = 0;
   146150   }
   146151   *pFlags = flags;
   146152   *pzFile = zFile;
   146153   return rc;
   146154 }
   146155 
   146156 
   146157 /*
   146158 ** This routine does the work of opening a database on behalf of
   146159 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   146160 ** is UTF-8 encoded.
   146161 */
   146162 static int openDatabase(
   146163   const char *zFilename, /* Database filename UTF-8 encoded */
   146164   sqlite3 **ppDb,        /* OUT: Returned database handle */
   146165   unsigned int flags,    /* Operational flags */
   146166   const char *zVfs       /* Name of the VFS to use */
   146167 ){
   146168   sqlite3 *db;                    /* Store allocated handle here */
   146169   int rc;                         /* Return code */
   146170   int isThreadsafe;               /* True for threadsafe connections */
   146171   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
   146172   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
   146173 
   146174 #ifdef SQLITE_ENABLE_API_ARMOR
   146175   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
   146176 #endif
   146177   *ppDb = 0;
   146178 #ifndef SQLITE_OMIT_AUTOINIT
   146179   rc = sqlite3_initialize();
   146180   if( rc ) return rc;
   146181 #endif
   146182 
   146183   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   146184     isThreadsafe = 0;
   146185   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   146186     isThreadsafe = 0;
   146187   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   146188     isThreadsafe = 1;
   146189   }else{
   146190     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   146191   }
   146192 
   146193   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   146194     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   146195   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   146196     flags |= SQLITE_OPEN_SHAREDCACHE;
   146197   }
   146198 
   146199   /* Remove harmful bits from the flags parameter
   146200   **
   146201   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   146202   ** dealt with in the previous code block.  Besides these, the only
   146203   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   146204   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
   146205   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
   146206   ** off all other flags.
   146207   */
   146208   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   146209                SQLITE_OPEN_EXCLUSIVE |
   146210                SQLITE_OPEN_MAIN_DB |
   146211                SQLITE_OPEN_TEMP_DB |
   146212                SQLITE_OPEN_TRANSIENT_DB |
   146213                SQLITE_OPEN_MAIN_JOURNAL |
   146214                SQLITE_OPEN_TEMP_JOURNAL |
   146215                SQLITE_OPEN_SUBJOURNAL |
   146216                SQLITE_OPEN_MASTER_JOURNAL |
   146217                SQLITE_OPEN_NOMUTEX |
   146218                SQLITE_OPEN_FULLMUTEX |
   146219                SQLITE_OPEN_WAL
   146220              );
   146221 
   146222   /* Allocate the sqlite data structure */
   146223   db = sqlite3MallocZero( sizeof(sqlite3) );
   146224   if( db==0 ) goto opendb_out;
   146225   if( isThreadsafe
   146226 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
   146227    || sqlite3GlobalConfig.bCoreMutex
   146228 #endif
   146229   ){
   146230     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   146231     if( db->mutex==0 ){
   146232       sqlite3_free(db);
   146233       db = 0;
   146234       goto opendb_out;
   146235     }
   146236     if( isThreadsafe==0 ){
   146237       sqlite3MutexWarnOnContention(db->mutex);
   146238     }
   146239   }
   146240   sqlite3_mutex_enter(db->mutex);
   146241   db->errMask = 0xff;
   146242   db->nDb = 2;
   146243   db->magic = SQLITE_MAGIC_BUSY;
   146244   db->aDb = db->aDbStatic;
   146245 
   146246   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   146247   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   146248   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
   146249   db->autoCommit = 1;
   146250   db->nextAutovac = -1;
   146251   db->szMmap = sqlite3GlobalConfig.szMmap;
   146252   db->nextPagesize = 0;
   146253   db->nMaxSorterMmap = 0x7FFFFFFF;
   146254   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
   146255 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
   146256                  | SQLITE_AutoIndex
   146257 #endif
   146258 #if SQLITE_DEFAULT_CKPTFULLFSYNC
   146259                  | SQLITE_CkptFullFSync
   146260 #endif
   146261 #if SQLITE_DEFAULT_FILE_FORMAT<4
   146262                  | SQLITE_LegacyFileFmt
   146263 #endif
   146264 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   146265                  | SQLITE_LoadExtension
   146266 #endif
   146267 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   146268                  | SQLITE_RecTriggers
   146269 #endif
   146270 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
   146271                  | SQLITE_ForeignKeys
   146272 #endif
   146273 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
   146274                  | SQLITE_ReverseOrder
   146275 #endif
   146276 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   146277                  | SQLITE_CellSizeCk
   146278 #endif
   146279 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
   146280                  | SQLITE_Fts3Tokenizer
   146281 #endif
   146282 #if defined(SQLITE_ENABLE_QPSG)
   146283                  | SQLITE_EnableQPSG
   146284 #endif
   146285       ;
   146286   sqlite3HashInit(&db->aCollSeq);
   146287 #ifndef SQLITE_OMIT_VIRTUALTABLE
   146288   sqlite3HashInit(&db->aModule);
   146289 #endif
   146290 
   146291   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   146292   ** and UTF-16, so add a version for each to avoid any unnecessary
   146293   ** conversions. The only error that can occur here is a malloc() failure.
   146294   **
   146295   ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
   146296   ** functions:
   146297   */
   146298   createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
   146299   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
   146300   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
   146301   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
   146302   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
   146303   if( db->mallocFailed ){
   146304     goto opendb_out;
   146305   }
   146306   /* EVIDENCE-OF: R-08308-17224 The default collating function for all
   146307   ** strings is BINARY.
   146308   */
   146309   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
   146310   assert( db->pDfltColl!=0 );
   146311 
   146312   /* Parse the filename/URI argument
   146313   **
   146314   ** Only allow sensible combinations of bits in the flags argument.
   146315   ** Throw an error if any non-sense combination is used.  If we
   146316   ** do not block illegal combinations here, it could trigger
   146317   ** assert() statements in deeper layers.  Sensible combinations
   146318   ** are:
   146319   **
   146320   **  1:  SQLITE_OPEN_READONLY
   146321   **  2:  SQLITE_OPEN_READWRITE
   146322   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
   146323   */
   146324   db->openFlags = flags;
   146325   assert( SQLITE_OPEN_READONLY  == 0x01 );
   146326   assert( SQLITE_OPEN_READWRITE == 0x02 );
   146327   assert( SQLITE_OPEN_CREATE    == 0x04 );
   146328   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
   146329   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   146330   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   146331   if( ((1<<(flags&7)) & 0x46)==0 ){
   146332     rc = SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
   146333   }else{
   146334     rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
   146335   }
   146336   if( rc!=SQLITE_OK ){
   146337     if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
   146338     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
   146339     sqlite3_free(zErrMsg);
   146340     goto opendb_out;
   146341   }
   146342 
   146343   /* Open the backend database driver */
   146344   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
   146345                         flags | SQLITE_OPEN_MAIN_DB);
   146346   if( rc!=SQLITE_OK ){
   146347     if( rc==SQLITE_IOERR_NOMEM ){
   146348       rc = SQLITE_NOMEM_BKPT;
   146349     }
   146350     sqlite3Error(db, rc);
   146351     goto opendb_out;
   146352   }
   146353   sqlite3BtreeEnter(db->aDb[0].pBt);
   146354   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   146355   if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
   146356   sqlite3BtreeLeave(db->aDb[0].pBt);
   146357   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   146358 
   146359   /* The default safety_level for the main database is FULL; for the temp
   146360   ** database it is OFF. This matches the pager layer defaults.
   146361   */
   146362   db->aDb[0].zDbSName = "main";
   146363   db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
   146364   db->aDb[1].zDbSName = "temp";
   146365   db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
   146366 
   146367   db->magic = SQLITE_MAGIC_OPEN;
   146368   if( db->mallocFailed ){
   146369     goto opendb_out;
   146370   }
   146371 
   146372   /* Register all built-in functions, but do not attempt to read the
   146373   ** database schema yet. This is delayed until the first time the database
   146374   ** is accessed.
   146375   */
   146376   sqlite3Error(db, SQLITE_OK);
   146377   sqlite3RegisterPerConnectionBuiltinFunctions(db);
   146378   rc = sqlite3_errcode(db);
   146379 
   146380 #ifdef SQLITE_ENABLE_FTS5
   146381   /* Register any built-in FTS5 module before loading the automatic
   146382   ** extensions. This allows automatic extensions to register FTS5
   146383   ** tokenizers and auxiliary functions.  */
   146384   if( !db->mallocFailed && rc==SQLITE_OK ){
   146385     rc = sqlite3Fts5Init(db);
   146386   }
   146387 #endif
   146388 
   146389   /* Load automatic extensions - extensions that have been registered
   146390   ** using the sqlite3_automatic_extension() API.
   146391   */
   146392   if( rc==SQLITE_OK ){
   146393     sqlite3AutoLoadExtensions(db);
   146394     rc = sqlite3_errcode(db);
   146395     if( rc!=SQLITE_OK ){
   146396       goto opendb_out;
   146397     }
   146398   }
   146399 
   146400 #ifdef SQLITE_ENABLE_FTS1
   146401   if( !db->mallocFailed ){
   146402     extern int sqlite3Fts1Init(sqlite3*);
   146403     rc = sqlite3Fts1Init(db);
   146404   }
   146405 #endif
   146406 
   146407 #ifdef SQLITE_ENABLE_FTS2
   146408   if( !db->mallocFailed && rc==SQLITE_OK ){
   146409     extern int sqlite3Fts2Init(sqlite3*);
   146410     rc = sqlite3Fts2Init(db);
   146411   }
   146412 #endif
   146413 
   146414 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
   146415   if( !db->mallocFailed && rc==SQLITE_OK ){
   146416     rc = sqlite3Fts3Init(db);
   146417   }
   146418 #endif
   146419 
   146420 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
   146421   if( !db->mallocFailed && rc==SQLITE_OK ){
   146422     rc = sqlite3IcuInit(db);
   146423   }
   146424 #endif
   146425 
   146426 #ifdef SQLITE_ENABLE_RTREE
   146427   if( !db->mallocFailed && rc==SQLITE_OK){
   146428     rc = sqlite3RtreeInit(db);
   146429   }
   146430 #endif
   146431 
   146432 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
   146433   if( !db->mallocFailed && rc==SQLITE_OK){
   146434     rc = sqlite3DbpageRegister(db);
   146435   }
   146436 #endif
   146437 
   146438 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
   146439   if( !db->mallocFailed && rc==SQLITE_OK){
   146440     rc = sqlite3DbstatRegister(db);
   146441   }
   146442 #endif
   146443 
   146444 #ifdef SQLITE_ENABLE_JSON1
   146445   if( !db->mallocFailed && rc==SQLITE_OK){
   146446     rc = sqlite3Json1Init(db);
   146447   }
   146448 #endif
   146449 
   146450 #ifdef SQLITE_ENABLE_STMTVTAB
   146451   if( !db->mallocFailed && rc==SQLITE_OK){
   146452     rc = sqlite3StmtVtabInit(db);
   146453   }
   146454 #endif
   146455 
   146456   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   146457   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   146458   ** mode.  Doing nothing at all also makes NORMAL the default.
   146459   */
   146460 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   146461   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   146462   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   146463                           SQLITE_DEFAULT_LOCKING_MODE);
   146464 #endif
   146465 
   146466   if( rc ) sqlite3Error(db, rc);
   146467 
   146468   /* Enable the lookaside-malloc subsystem */
   146469   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   146470                         sqlite3GlobalConfig.nLookaside);
   146471 
   146472   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
   146473 
   146474 opendb_out:
   146475   if( db ){
   146476     assert( db->mutex!=0 || isThreadsafe==0
   146477            || sqlite3GlobalConfig.bFullMutex==0 );
   146478     sqlite3_mutex_leave(db->mutex);
   146479   }
   146480   rc = sqlite3_errcode(db);
   146481   assert( db!=0 || rc==SQLITE_NOMEM );
   146482   if( rc==SQLITE_NOMEM ){
   146483     sqlite3_close(db);
   146484     db = 0;
   146485   }else if( rc!=SQLITE_OK ){
   146486     db->magic = SQLITE_MAGIC_SICK;
   146487   }
   146488   *ppDb = db;
   146489 #ifdef SQLITE_ENABLE_SQLLOG
   146490   if( sqlite3GlobalConfig.xSqllog ){
   146491     /* Opening a db handle. Fourth parameter is passed 0. */
   146492     void *pArg = sqlite3GlobalConfig.pSqllogArg;
   146493     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
   146494   }
   146495 #endif
   146496 #if defined(SQLITE_HAS_CODEC)
   146497   if( rc==SQLITE_OK ){
   146498     const char *zKey;
   146499     if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
   146500       u8 iByte;
   146501       int i;
   146502       char zDecoded[40];
   146503       for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
   146504         iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
   146505         if( (i&1)!=0 ) zDecoded[i/2] = iByte;
   146506       }
   146507       sqlite3_key_v2(db, 0, zDecoded, i/2);
   146508     }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
   146509       sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
   146510     }
   146511   }
   146512 #endif
   146513   sqlite3_free(zOpen);
   146514   return rc & 0xff;
   146515 }
   146516 
   146517 /*
   146518 ** Open a new database handle.
   146519 */
   146520 SQLITE_API int sqlite3_open(
   146521   const char *zFilename,
   146522   sqlite3 **ppDb
   146523 ){
   146524   return openDatabase(zFilename, ppDb,
   146525                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   146526 }
   146527 SQLITE_API int sqlite3_open_v2(
   146528   const char *filename,   /* Database filename (UTF-8) */
   146529   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   146530   int flags,              /* Flags */
   146531   const char *zVfs        /* Name of VFS module to use */
   146532 ){
   146533   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
   146534 }
   146535 
   146536 #ifndef SQLITE_OMIT_UTF16
   146537 /*
   146538 ** Open a new database handle.
   146539 */
   146540 SQLITE_API int sqlite3_open16(
   146541   const void *zFilename,
   146542   sqlite3 **ppDb
   146543 ){
   146544   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   146545   sqlite3_value *pVal;
   146546   int rc;
   146547 
   146548 #ifdef SQLITE_ENABLE_API_ARMOR
   146549   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
   146550 #endif
   146551   *ppDb = 0;
   146552 #ifndef SQLITE_OMIT_AUTOINIT
   146553   rc = sqlite3_initialize();
   146554   if( rc ) return rc;
   146555 #endif
   146556   if( zFilename==0 ) zFilename = "\000\000";
   146557   pVal = sqlite3ValueNew(0);
   146558   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   146559   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   146560   if( zFilename8 ){
   146561     rc = openDatabase(zFilename8, ppDb,
   146562                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   146563     assert( *ppDb || rc==SQLITE_NOMEM );
   146564     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   146565       SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
   146566     }
   146567   }else{
   146568     rc = SQLITE_NOMEM_BKPT;
   146569   }
   146570   sqlite3ValueFree(pVal);
   146571 
   146572   return rc & 0xff;
   146573 }
   146574 #endif /* SQLITE_OMIT_UTF16 */
   146575 
   146576 /*
   146577 ** Register a new collation sequence with the database handle db.
   146578 */
   146579 SQLITE_API int sqlite3_create_collation(
   146580   sqlite3* db,
   146581   const char *zName,
   146582   int enc,
   146583   void* pCtx,
   146584   int(*xCompare)(void*,int,const void*,int,const void*)
   146585 ){
   146586   return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
   146587 }
   146588 
   146589 /*
   146590 ** Register a new collation sequence with the database handle db.
   146591 */
   146592 SQLITE_API int sqlite3_create_collation_v2(
   146593   sqlite3* db,
   146594   const char *zName,
   146595   int enc,
   146596   void* pCtx,
   146597   int(*xCompare)(void*,int,const void*,int,const void*),
   146598   void(*xDel)(void*)
   146599 ){
   146600   int rc;
   146601 
   146602 #ifdef SQLITE_ENABLE_API_ARMOR
   146603   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
   146604 #endif
   146605   sqlite3_mutex_enter(db->mutex);
   146606   assert( !db->mallocFailed );
   146607   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
   146608   rc = sqlite3ApiExit(db, rc);
   146609   sqlite3_mutex_leave(db->mutex);
   146610   return rc;
   146611 }
   146612 
   146613 #ifndef SQLITE_OMIT_UTF16
   146614 /*
   146615 ** Register a new collation sequence with the database handle db.
   146616 */
   146617 SQLITE_API int sqlite3_create_collation16(
   146618   sqlite3* db,
   146619   const void *zName,
   146620   int enc,
   146621   void* pCtx,
   146622   int(*xCompare)(void*,int,const void*,int,const void*)
   146623 ){
   146624   int rc = SQLITE_OK;
   146625   char *zName8;
   146626 
   146627 #ifdef SQLITE_ENABLE_API_ARMOR
   146628   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
   146629 #endif
   146630   sqlite3_mutex_enter(db->mutex);
   146631   assert( !db->mallocFailed );
   146632   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
   146633   if( zName8 ){
   146634     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
   146635     sqlite3DbFree(db, zName8);
   146636   }
   146637   rc = sqlite3ApiExit(db, rc);
   146638   sqlite3_mutex_leave(db->mutex);
   146639   return rc;
   146640 }
   146641 #endif /* SQLITE_OMIT_UTF16 */
   146642 
   146643 /*
   146644 ** Register a collation sequence factory callback with the database handle
   146645 ** db. Replace any previously installed collation sequence factory.
   146646 */
   146647 SQLITE_API int sqlite3_collation_needed(
   146648   sqlite3 *db,
   146649   void *pCollNeededArg,
   146650   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   146651 ){
   146652 #ifdef SQLITE_ENABLE_API_ARMOR
   146653   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   146654 #endif
   146655   sqlite3_mutex_enter(db->mutex);
   146656   db->xCollNeeded = xCollNeeded;
   146657   db->xCollNeeded16 = 0;
   146658   db->pCollNeededArg = pCollNeededArg;
   146659   sqlite3_mutex_leave(db->mutex);
   146660   return SQLITE_OK;
   146661 }
   146662 
   146663 #ifndef SQLITE_OMIT_UTF16
   146664 /*
   146665 ** Register a collation sequence factory callback with the database handle
   146666 ** db. Replace any previously installed collation sequence factory.
   146667 */
   146668 SQLITE_API int sqlite3_collation_needed16(
   146669   sqlite3 *db,
   146670   void *pCollNeededArg,
   146671   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   146672 ){
   146673 #ifdef SQLITE_ENABLE_API_ARMOR
   146674   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   146675 #endif
   146676   sqlite3_mutex_enter(db->mutex);
   146677   db->xCollNeeded = 0;
   146678   db->xCollNeeded16 = xCollNeeded16;
   146679   db->pCollNeededArg = pCollNeededArg;
   146680   sqlite3_mutex_leave(db->mutex);
   146681   return SQLITE_OK;
   146682 }
   146683 #endif /* SQLITE_OMIT_UTF16 */
   146684 
   146685 #ifndef SQLITE_OMIT_DEPRECATED
   146686 /*
   146687 ** This function is now an anachronism. It used to be used to recover from a
   146688 ** malloc() failure, but SQLite now does this automatically.
   146689 */
   146690 SQLITE_API int sqlite3_global_recover(void){
   146691   return SQLITE_OK;
   146692 }
   146693 #endif
   146694 
   146695 /*
   146696 ** Test to see whether or not the database connection is in autocommit
   146697 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   146698 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   146699 ** by the next COMMIT or ROLLBACK.
   146700 */
   146701 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
   146702 #ifdef SQLITE_ENABLE_API_ARMOR
   146703   if( !sqlite3SafetyCheckOk(db) ){
   146704     (void)SQLITE_MISUSE_BKPT;
   146705     return 0;
   146706   }
   146707 #endif
   146708   return db->autoCommit;
   146709 }
   146710 
   146711 /*
   146712 ** The following routines are substitutes for constants SQLITE_CORRUPT,
   146713 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
   146714 ** constants.  They serve two purposes:
   146715 **
   146716 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   146717 **       to detect when version error conditions occurs.
   146718 **
   146719 **   2.  Invoke sqlite3_log() to provide the source code location where
   146720 **       a low-level error is first detected.
   146721 */
   146722 SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
   146723   sqlite3_log(iErr, "%s at line %d of [%.10s]",
   146724               zType, lineno, 20+sqlite3_sourceid());
   146725   return iErr;
   146726 }
   146727 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
   146728   testcase( sqlite3GlobalConfig.xLog!=0 );
   146729   return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
   146730 }
   146731 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
   146732   testcase( sqlite3GlobalConfig.xLog!=0 );
   146733   return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
   146734 }
   146735 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   146736   testcase( sqlite3GlobalConfig.xLog!=0 );
   146737   return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
   146738 }
   146739 #ifdef SQLITE_DEBUG
   146740 SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
   146741   char zMsg[100];
   146742   sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
   146743   testcase( sqlite3GlobalConfig.xLog!=0 );
   146744   return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
   146745 }
   146746 SQLITE_PRIVATE int sqlite3NomemError(int lineno){
   146747   testcase( sqlite3GlobalConfig.xLog!=0 );
   146748   return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
   146749 }
   146750 SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
   146751   testcase( sqlite3GlobalConfig.xLog!=0 );
   146752   return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
   146753 }
   146754 #endif
   146755 
   146756 #ifndef SQLITE_OMIT_DEPRECATED
   146757 /*
   146758 ** This is a convenience routine that makes sure that all thread-specific
   146759 ** data for this thread has been deallocated.
   146760 **
   146761 ** SQLite no longer uses thread-specific data so this routine is now a
   146762 ** no-op.  It is retained for historical compatibility.
   146763 */
   146764 SQLITE_API void sqlite3_thread_cleanup(void){
   146765 }
   146766 #endif
   146767 
   146768 /*
   146769 ** Return meta information about a specific column of a database table.
   146770 ** See comment in sqlite3.h (sqlite.h.in) for details.
   146771 */
   146772 SQLITE_API int sqlite3_table_column_metadata(
   146773   sqlite3 *db,                /* Connection handle */
   146774   const char *zDbName,        /* Database name or NULL */
   146775   const char *zTableName,     /* Table name */
   146776   const char *zColumnName,    /* Column name */
   146777   char const **pzDataType,    /* OUTPUT: Declared data type */
   146778   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   146779   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   146780   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   146781   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   146782 ){
   146783   int rc;
   146784   char *zErrMsg = 0;
   146785   Table *pTab = 0;
   146786   Column *pCol = 0;
   146787   int iCol = 0;
   146788   char const *zDataType = 0;
   146789   char const *zCollSeq = 0;
   146790   int notnull = 0;
   146791   int primarykey = 0;
   146792   int autoinc = 0;
   146793 
   146794 
   146795 #ifdef SQLITE_ENABLE_API_ARMOR
   146796   if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
   146797     return SQLITE_MISUSE_BKPT;
   146798   }
   146799 #endif
   146800 
   146801   /* Ensure the database schema has been loaded */
   146802   sqlite3_mutex_enter(db->mutex);
   146803   sqlite3BtreeEnterAll(db);
   146804   rc = sqlite3Init(db, &zErrMsg);
   146805   if( SQLITE_OK!=rc ){
   146806     goto error_out;
   146807   }
   146808 
   146809   /* Locate the table in question */
   146810   pTab = sqlite3FindTable(db, zTableName, zDbName);
   146811   if( !pTab || pTab->pSelect ){
   146812     pTab = 0;
   146813     goto error_out;
   146814   }
   146815 
   146816   /* Find the column for which info is requested */
   146817   if( zColumnName==0 ){
   146818     /* Query for existance of table only */
   146819   }else{
   146820     for(iCol=0; iCol<pTab->nCol; iCol++){
   146821       pCol = &pTab->aCol[iCol];
   146822       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   146823         break;
   146824       }
   146825     }
   146826     if( iCol==pTab->nCol ){
   146827       if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
   146828         iCol = pTab->iPKey;
   146829         pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
   146830       }else{
   146831         pTab = 0;
   146832         goto error_out;
   146833       }
   146834     }
   146835   }
   146836 
   146837   /* The following block stores the meta information that will be returned
   146838   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   146839   ** and autoinc. At this point there are two possibilities:
   146840   **
   146841   **     1. The specified column name was rowid", "oid" or "_rowid_"
   146842   **        and there is no explicitly declared IPK column.
   146843   **
   146844   **     2. The table is not a view and the column name identified an
   146845   **        explicitly declared column. Copy meta information from *pCol.
   146846   */
   146847   if( pCol ){
   146848     zDataType = sqlite3ColumnType(pCol,0);
   146849     zCollSeq = pCol->zColl;
   146850     notnull = pCol->notNull!=0;
   146851     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
   146852     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   146853   }else{
   146854     zDataType = "INTEGER";
   146855     primarykey = 1;
   146856   }
   146857   if( !zCollSeq ){
   146858     zCollSeq = sqlite3StrBINARY;
   146859   }
   146860 
   146861 error_out:
   146862   sqlite3BtreeLeaveAll(db);
   146863 
   146864   /* Whether the function call succeeded or failed, set the output parameters
   146865   ** to whatever their local counterparts contain. If an error did occur,
   146866   ** this has the effect of zeroing all output parameters.
   146867   */
   146868   if( pzDataType ) *pzDataType = zDataType;
   146869   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   146870   if( pNotNull ) *pNotNull = notnull;
   146871   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   146872   if( pAutoinc ) *pAutoinc = autoinc;
   146873 
   146874   if( SQLITE_OK==rc && !pTab ){
   146875     sqlite3DbFree(db, zErrMsg);
   146876     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   146877         zColumnName);
   146878     rc = SQLITE_ERROR;
   146879   }
   146880   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
   146881   sqlite3DbFree(db, zErrMsg);
   146882   rc = sqlite3ApiExit(db, rc);
   146883   sqlite3_mutex_leave(db->mutex);
   146884   return rc;
   146885 }
   146886 
   146887 /*
   146888 ** Sleep for a little while.  Return the amount of time slept.
   146889 */
   146890 SQLITE_API int sqlite3_sleep(int ms){
   146891   sqlite3_vfs *pVfs;
   146892   int rc;
   146893   pVfs = sqlite3_vfs_find(0);
   146894   if( pVfs==0 ) return 0;
   146895 
   146896   /* This function works in milliseconds, but the underlying OsSleep()
   146897   ** API uses microseconds. Hence the 1000's.
   146898   */
   146899   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   146900   return rc;
   146901 }
   146902 
   146903 /*
   146904 ** Enable or disable the extended result codes.
   146905 */
   146906 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   146907 #ifdef SQLITE_ENABLE_API_ARMOR
   146908   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   146909 #endif
   146910   sqlite3_mutex_enter(db->mutex);
   146911   db->errMask = onoff ? 0xffffffff : 0xff;
   146912   sqlite3_mutex_leave(db->mutex);
   146913   return SQLITE_OK;
   146914 }
   146915 
   146916 /*
   146917 ** Invoke the xFileControl method on a particular database.
   146918 */
   146919 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   146920   int rc = SQLITE_ERROR;
   146921   Btree *pBtree;
   146922 
   146923 #ifdef SQLITE_ENABLE_API_ARMOR
   146924   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   146925 #endif
   146926   sqlite3_mutex_enter(db->mutex);
   146927   pBtree = sqlite3DbNameToBtree(db, zDbName);
   146928   if( pBtree ){
   146929     Pager *pPager;
   146930     sqlite3_file *fd;
   146931     sqlite3BtreeEnter(pBtree);
   146932     pPager = sqlite3BtreePager(pBtree);
   146933     assert( pPager!=0 );
   146934     fd = sqlite3PagerFile(pPager);
   146935     assert( fd!=0 );
   146936     if( op==SQLITE_FCNTL_FILE_POINTER ){
   146937       *(sqlite3_file**)pArg = fd;
   146938       rc = SQLITE_OK;
   146939     }else if( op==SQLITE_FCNTL_VFS_POINTER ){
   146940       *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
   146941       rc = SQLITE_OK;
   146942     }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
   146943       *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
   146944       rc = SQLITE_OK;
   146945     }else if( fd->pMethods ){
   146946       rc = sqlite3OsFileControl(fd, op, pArg);
   146947     }else{
   146948       rc = SQLITE_NOTFOUND;
   146949     }
   146950     sqlite3BtreeLeave(pBtree);
   146951   }
   146952   sqlite3_mutex_leave(db->mutex);
   146953   return rc;
   146954 }
   146955 
   146956 /*
   146957 ** Interface to the testing logic.
   146958 */
   146959 SQLITE_API int sqlite3_test_control(int op, ...){
   146960   int rc = 0;
   146961 #ifdef SQLITE_UNTESTABLE
   146962   UNUSED_PARAMETER(op);
   146963 #else
   146964   va_list ap;
   146965   va_start(ap, op);
   146966   switch( op ){
   146967 
   146968     /*
   146969     ** Save the current state of the PRNG.
   146970     */
   146971     case SQLITE_TESTCTRL_PRNG_SAVE: {
   146972       sqlite3PrngSaveState();
   146973       break;
   146974     }
   146975 
   146976     /*
   146977     ** Restore the state of the PRNG to the last state saved using
   146978     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   146979     ** this verb acts like PRNG_RESET.
   146980     */
   146981     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   146982       sqlite3PrngRestoreState();
   146983       break;
   146984     }
   146985 
   146986     /*
   146987     ** Reset the PRNG back to its uninitialized state.  The next call
   146988     ** to sqlite3_randomness() will reseed the PRNG using a single call
   146989     ** to the xRandomness method of the default VFS.
   146990     */
   146991     case SQLITE_TESTCTRL_PRNG_RESET: {
   146992       sqlite3_randomness(0,0);
   146993       break;
   146994     }
   146995 
   146996     /*
   146997     **  sqlite3_test_control(BITVEC_TEST, size, program)
   146998     **
   146999     ** Run a test against a Bitvec object of size.  The program argument
   147000     ** is an array of integers that defines the test.  Return -1 on a
   147001     ** memory allocation error, 0 on success, or non-zero for an error.
   147002     ** See the sqlite3BitvecBuiltinTest() for additional information.
   147003     */
   147004     case SQLITE_TESTCTRL_BITVEC_TEST: {
   147005       int sz = va_arg(ap, int);
   147006       int *aProg = va_arg(ap, int*);
   147007       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   147008       break;
   147009     }
   147010 
   147011     /*
   147012     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
   147013     **
   147014     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
   147015     ** if xCallback is not NULL.
   147016     **
   147017     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
   147018     ** is called immediately after installing the new callback and the return
   147019     ** value from sqlite3FaultSim(0) becomes the return from
   147020     ** sqlite3_test_control().
   147021     */
   147022     case SQLITE_TESTCTRL_FAULT_INSTALL: {
   147023       /* MSVC is picky about pulling func ptrs from va lists.
   147024       ** http://support.microsoft.com/kb/47961
   147025       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
   147026       */
   147027       typedef int(*TESTCALLBACKFUNC_t)(int);
   147028       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
   147029       rc = sqlite3FaultSim(0);
   147030       break;
   147031     }
   147032 
   147033     /*
   147034     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   147035     **
   147036     ** Register hooks to call to indicate which malloc() failures
   147037     ** are benign.
   147038     */
   147039     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   147040       typedef void (*void_function)(void);
   147041       void_function xBenignBegin;
   147042       void_function xBenignEnd;
   147043       xBenignBegin = va_arg(ap, void_function);
   147044       xBenignEnd = va_arg(ap, void_function);
   147045       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   147046       break;
   147047     }
   147048 
   147049     /*
   147050     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   147051     **
   147052     ** Set the PENDING byte to the value in the argument, if X>0.
   147053     ** Make no changes if X==0.  Return the value of the pending byte
   147054     ** as it existing before this routine was called.
   147055     **
   147056     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   147057     ** an incompatible database file format.  Changing the PENDING byte
   147058     ** while any database connection is open results in undefined and
   147059     ** deleterious behavior.
   147060     */
   147061     case SQLITE_TESTCTRL_PENDING_BYTE: {
   147062       rc = PENDING_BYTE;
   147063 #ifndef SQLITE_OMIT_WSD
   147064       {
   147065         unsigned int newVal = va_arg(ap, unsigned int);
   147066         if( newVal ) sqlite3PendingByte = newVal;
   147067       }
   147068 #endif
   147069       break;
   147070     }
   147071 
   147072     /*
   147073     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   147074     **
   147075     ** This action provides a run-time test to see whether or not
   147076     ** assert() was enabled at compile-time.  If X is true and assert()
   147077     ** is enabled, then the return value is true.  If X is true and
   147078     ** assert() is disabled, then the return value is zero.  If X is
   147079     ** false and assert() is enabled, then the assertion fires and the
   147080     ** process aborts.  If X is false and assert() is disabled, then the
   147081     ** return value is zero.
   147082     */
   147083     case SQLITE_TESTCTRL_ASSERT: {
   147084       volatile int x = 0;
   147085       assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
   147086       rc = x;
   147087       break;
   147088     }
   147089 
   147090 
   147091     /*
   147092     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   147093     **
   147094     ** This action provides a run-time test to see how the ALWAYS and
   147095     ** NEVER macros were defined at compile-time.
   147096     **
   147097     ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
   147098     **
   147099     ** The recommended test is X==2.  If the return value is 2, that means
   147100     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   147101     ** default setting.  If the return value is 1, then ALWAYS() is either
   147102     ** hard-coded to true or else it asserts if its argument is false.
   147103     ** The first behavior (hard-coded to true) is the case if
   147104     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   147105     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   147106     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   147107     **
   147108     ** The run-time test procedure might look something like this:
   147109     **
   147110     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   147111     **      // ALWAYS() and NEVER() are no-op pass-through macros
   147112     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   147113     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   147114     **    }else{
   147115     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   147116     **    }
   147117     */
   147118     case SQLITE_TESTCTRL_ALWAYS: {
   147119       int x = va_arg(ap,int);
   147120       rc = x ? ALWAYS(x) : 0;
   147121       break;
   147122     }
   147123 
   147124     /*
   147125     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
   147126     **
   147127     ** The integer returned reveals the byte-order of the computer on which
   147128     ** SQLite is running:
   147129     **
   147130     **       1     big-endian,    determined at run-time
   147131     **      10     little-endian, determined at run-time
   147132     **  432101     big-endian,    determined at compile-time
   147133     **  123410     little-endian, determined at compile-time
   147134     */
   147135     case SQLITE_TESTCTRL_BYTEORDER: {
   147136       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
   147137       break;
   147138     }
   147139 
   147140     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   147141     **
   147142     ** Set the nReserve size to N for the main database on the database
   147143     ** connection db.
   147144     */
   147145     case SQLITE_TESTCTRL_RESERVE: {
   147146       sqlite3 *db = va_arg(ap, sqlite3*);
   147147       int x = va_arg(ap,int);
   147148       sqlite3_mutex_enter(db->mutex);
   147149       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   147150       sqlite3_mutex_leave(db->mutex);
   147151       break;
   147152     }
   147153 
   147154     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   147155     **
   147156     ** Enable or disable various optimizations for testing purposes.  The
   147157     ** argument N is a bitmask of optimizations to be disabled.  For normal
   147158     ** operation N should be 0.  The idea is that a test program (like the
   147159     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   147160     ** with various optimizations disabled to verify that the same answer
   147161     ** is obtained in every case.
   147162     */
   147163     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   147164       sqlite3 *db = va_arg(ap, sqlite3*);
   147165       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
   147166       break;
   147167     }
   147168 
   147169 #ifdef SQLITE_N_KEYWORD
   147170     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   147171     **
   147172     ** If zWord is a keyword recognized by the parser, then return the
   147173     ** number of keywords.  Or if zWord is not a keyword, return 0.
   147174     **
   147175     ** This test feature is only available in the amalgamation since
   147176     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   147177     ** is built using separate source files.
   147178     */
   147179     case SQLITE_TESTCTRL_ISKEYWORD: {
   147180       const char *zWord = va_arg(ap, const char*);
   147181       int n = sqlite3Strlen30(zWord);
   147182       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   147183       break;
   147184     }
   147185 #endif
   147186 
   147187     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
   147188     **
   147189     ** If parameter onoff is non-zero, configure the wrappers so that all
   147190     ** subsequent calls to localtime() and variants fail. If onoff is zero,
   147191     ** undo this setting.
   147192     */
   147193     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
   147194       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
   147195       break;
   147196     }
   147197 
   147198     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
   147199     **
   147200     ** Set or clear a flag that indicates that the database file is always well-
   147201     ** formed and never corrupt.  This flag is clear by default, indicating that
   147202     ** database files might have arbitrary corruption.  Setting the flag during
   147203     ** testing causes certain assert() statements in the code to be activated
   147204     ** that demonstrat invariants on well-formed database files.
   147205     */
   147206     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
   147207       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
   147208       break;
   147209     }
   147210 
   147211     /* Set the threshold at which OP_Once counters reset back to zero.
   147212     ** By default this is 0x7ffffffe (over 2 billion), but that value is
   147213     ** too big to test in a reasonable amount of time, so this control is
   147214     ** provided to set a small and easily reachable reset value.
   147215     */
   147216     case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
   147217       sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
   147218       break;
   147219     }
   147220 
   147221     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
   147222     **
   147223     ** Set the VDBE coverage callback function to xCallback with context
   147224     ** pointer ptr.
   147225     */
   147226     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
   147227 #ifdef SQLITE_VDBE_COVERAGE
   147228       typedef void (*branch_callback)(void*,int,u8,u8);
   147229       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
   147230       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
   147231 #endif
   147232       break;
   147233     }
   147234 
   147235     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
   147236     case SQLITE_TESTCTRL_SORTER_MMAP: {
   147237       sqlite3 *db = va_arg(ap, sqlite3*);
   147238       db->nMaxSorterMmap = va_arg(ap, int);
   147239       break;
   147240     }
   147241 
   147242     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
   147243     **
   147244     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
   147245     ** not.
   147246     */
   147247     case SQLITE_TESTCTRL_ISINIT: {
   147248       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
   147249       break;
   147250     }
   147251 
   147252     /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
   147253     **
   147254     ** This test control is used to create imposter tables.  "db" is a pointer
   147255     ** to the database connection.  dbName is the database name (ex: "main" or
   147256     ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
   147257     ** or off.  "tnum" is the root page of the b-tree to which the imposter
   147258     ** table should connect.
   147259     **
   147260     ** Enable imposter mode only when the schema has already been parsed.  Then
   147261     ** run a single CREATE TABLE statement to construct the imposter table in
   147262     ** the parsed schema.  Then turn imposter mode back off again.
   147263     **
   147264     ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
   147265     ** the schema to be reparsed the next time it is needed.  This has the
   147266     ** effect of erasing all imposter tables.
   147267     */
   147268     case SQLITE_TESTCTRL_IMPOSTER: {
   147269       sqlite3 *db = va_arg(ap, sqlite3*);
   147270       sqlite3_mutex_enter(db->mutex);
   147271       db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
   147272       db->init.busy = db->init.imposterTable = va_arg(ap,int);
   147273       db->init.newTnum = va_arg(ap,int);
   147274       if( db->init.busy==0 && db->init.newTnum>0 ){
   147275         sqlite3ResetAllSchemasOfConnection(db);
   147276       }
   147277       sqlite3_mutex_leave(db->mutex);
   147278       break;
   147279     }
   147280 
   147281 #if defined(YYCOVERAGE)
   147282     /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
   147283     **
   147284     ** This test control (only available when SQLite is compiled with
   147285     ** -DYYCOVERAGE) writes a report onto "out" that shows all
   147286     ** state/lookahead combinations in the parser state machine
   147287     ** which are never exercised.  If any state is missed, make the
   147288     ** return code SQLITE_ERROR.
   147289     */
   147290     case SQLITE_TESTCTRL_PARSER_COVERAGE: {
   147291       FILE *out = va_arg(ap, FILE*);
   147292       if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
   147293       break;
   147294     }
   147295 #endif /* defined(YYCOVERAGE) */
   147296   }
   147297   va_end(ap);
   147298 #endif /* SQLITE_UNTESTABLE */
   147299   return rc;
   147300 }
   147301 
   147302 /*
   147303 ** This is a utility routine, useful to VFS implementations, that checks
   147304 ** to see if a database file was a URI that contained a specific query
   147305 ** parameter, and if so obtains the value of the query parameter.
   147306 **
   147307 ** The zFilename argument is the filename pointer passed into the xOpen()
   147308 ** method of a VFS implementation.  The zParam argument is the name of the
   147309 ** query parameter we seek.  This routine returns the value of the zParam
   147310 ** parameter if it exists.  If the parameter does not exist, this routine
   147311 ** returns a NULL pointer.
   147312 */
   147313 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
   147314   if( zFilename==0 || zParam==0 ) return 0;
   147315   zFilename += sqlite3Strlen30(zFilename) + 1;
   147316   while( zFilename[0] ){
   147317     int x = strcmp(zFilename, zParam);
   147318     zFilename += sqlite3Strlen30(zFilename) + 1;
   147319     if( x==0 ) return zFilename;
   147320     zFilename += sqlite3Strlen30(zFilename) + 1;
   147321   }
   147322   return 0;
   147323 }
   147324 
   147325 /*
   147326 ** Return a boolean value for a query parameter.
   147327 */
   147328 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
   147329   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   147330   bDflt = bDflt!=0;
   147331   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
   147332 }
   147333 
   147334 /*
   147335 ** Return a 64-bit integer value for a query parameter.
   147336 */
   147337 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
   147338   const char *zFilename,    /* Filename as passed to xOpen */
   147339   const char *zParam,       /* URI parameter sought */
   147340   sqlite3_int64 bDflt       /* return if parameter is missing */
   147341 ){
   147342   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   147343   sqlite3_int64 v;
   147344   if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
   147345     bDflt = v;
   147346   }
   147347   return bDflt;
   147348 }
   147349 
   147350 /*
   147351 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
   147352 */
   147353 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
   147354   int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
   147355   return iDb<0 ? 0 : db->aDb[iDb].pBt;
   147356 }
   147357 
   147358 /*
   147359 ** Return the filename of the database associated with a database
   147360 ** connection.
   147361 */
   147362 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
   147363   Btree *pBt;
   147364 #ifdef SQLITE_ENABLE_API_ARMOR
   147365   if( !sqlite3SafetyCheckOk(db) ){
   147366     (void)SQLITE_MISUSE_BKPT;
   147367     return 0;
   147368   }
   147369 #endif
   147370   pBt = sqlite3DbNameToBtree(db, zDbName);
   147371   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
   147372 }
   147373 
   147374 /*
   147375 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
   147376 ** no such database exists.
   147377 */
   147378 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
   147379   Btree *pBt;
   147380 #ifdef SQLITE_ENABLE_API_ARMOR
   147381   if( !sqlite3SafetyCheckOk(db) ){
   147382     (void)SQLITE_MISUSE_BKPT;
   147383     return -1;
   147384   }
   147385 #endif
   147386   pBt = sqlite3DbNameToBtree(db, zDbName);
   147387   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
   147388 }
   147389 
   147390 #ifdef SQLITE_ENABLE_SNAPSHOT
   147391 /*
   147392 ** Obtain a snapshot handle for the snapshot of database zDb currently
   147393 ** being read by handle db.
   147394 */
   147395 SQLITE_API int sqlite3_snapshot_get(
   147396   sqlite3 *db,
   147397   const char *zDb,
   147398   sqlite3_snapshot **ppSnapshot
   147399 ){
   147400   int rc = SQLITE_ERROR;
   147401 #ifndef SQLITE_OMIT_WAL
   147402 
   147403 #ifdef SQLITE_ENABLE_API_ARMOR
   147404   if( !sqlite3SafetyCheckOk(db) ){
   147405     return SQLITE_MISUSE_BKPT;
   147406   }
   147407 #endif
   147408   sqlite3_mutex_enter(db->mutex);
   147409 
   147410   if( db->autoCommit==0 ){
   147411     int iDb = sqlite3FindDbName(db, zDb);
   147412     if( iDb==0 || iDb>1 ){
   147413       Btree *pBt = db->aDb[iDb].pBt;
   147414       if( 0==sqlite3BtreeIsInTrans(pBt) ){
   147415         rc = sqlite3BtreeBeginTrans(pBt, 0);
   147416         if( rc==SQLITE_OK ){
   147417           rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
   147418         }
   147419       }
   147420     }
   147421   }
   147422 
   147423   sqlite3_mutex_leave(db->mutex);
   147424 #endif   /* SQLITE_OMIT_WAL */
   147425   return rc;
   147426 }
   147427 
   147428 /*
   147429 ** Open a read-transaction on the snapshot idendified by pSnapshot.
   147430 */
   147431 SQLITE_API int sqlite3_snapshot_open(
   147432   sqlite3 *db,
   147433   const char *zDb,
   147434   sqlite3_snapshot *pSnapshot
   147435 ){
   147436   int rc = SQLITE_ERROR;
   147437 #ifndef SQLITE_OMIT_WAL
   147438 
   147439 #ifdef SQLITE_ENABLE_API_ARMOR
   147440   if( !sqlite3SafetyCheckOk(db) ){
   147441     return SQLITE_MISUSE_BKPT;
   147442   }
   147443 #endif
   147444   sqlite3_mutex_enter(db->mutex);
   147445   if( db->autoCommit==0 ){
   147446     int iDb;
   147447     iDb = sqlite3FindDbName(db, zDb);
   147448     if( iDb==0 || iDb>1 ){
   147449       Btree *pBt = db->aDb[iDb].pBt;
   147450       if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
   147451         rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
   147452         if( rc==SQLITE_OK ){
   147453           rc = sqlite3BtreeBeginTrans(pBt, 0);
   147454           sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
   147455         }
   147456       }
   147457     }
   147458   }
   147459 
   147460   sqlite3_mutex_leave(db->mutex);
   147461 #endif   /* SQLITE_OMIT_WAL */
   147462   return rc;
   147463 }
   147464 
   147465 /*
   147466 ** Recover as many snapshots as possible from the wal file associated with
   147467 ** schema zDb of database db.
   147468 */
   147469 SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
   147470   int rc = SQLITE_ERROR;
   147471   int iDb;
   147472 #ifndef SQLITE_OMIT_WAL
   147473 
   147474 #ifdef SQLITE_ENABLE_API_ARMOR
   147475   if( !sqlite3SafetyCheckOk(db) ){
   147476     return SQLITE_MISUSE_BKPT;
   147477   }
   147478 #endif
   147479 
   147480   sqlite3_mutex_enter(db->mutex);
   147481   iDb = sqlite3FindDbName(db, zDb);
   147482   if( iDb==0 || iDb>1 ){
   147483     Btree *pBt = db->aDb[iDb].pBt;
   147484     if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
   147485       rc = sqlite3BtreeBeginTrans(pBt, 0);
   147486       if( rc==SQLITE_OK ){
   147487         rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
   147488         sqlite3BtreeCommit(pBt);
   147489       }
   147490     }
   147491   }
   147492   sqlite3_mutex_leave(db->mutex);
   147493 #endif   /* SQLITE_OMIT_WAL */
   147494   return rc;
   147495 }
   147496 
   147497 /*
   147498 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
   147499 */
   147500 SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
   147501   sqlite3_free(pSnapshot);
   147502 }
   147503 #endif /* SQLITE_ENABLE_SNAPSHOT */
   147504 
   147505 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   147506 /*
   147507 ** Given the name of a compile-time option, return true if that option
   147508 ** was used and false if not.
   147509 **
   147510 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
   147511 ** is not required for a match.
   147512 */
   147513 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
   147514   int i, n;
   147515   int nOpt;
   147516   const char **azCompileOpt;
   147517 
   147518 #if SQLITE_ENABLE_API_ARMOR
   147519   if( zOptName==0 ){
   147520     (void)SQLITE_MISUSE_BKPT;
   147521     return 0;
   147522   }
   147523 #endif
   147524 
   147525   azCompileOpt = sqlite3CompileOptions(&nOpt);
   147526 
   147527   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
   147528   n = sqlite3Strlen30(zOptName);
   147529 
   147530   /* Since nOpt is normally in single digits, a linear search is
   147531   ** adequate. No need for a binary search. */
   147532   for(i=0; i<nOpt; i++){
   147533     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
   147534      && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
   147535     ){
   147536       return 1;
   147537     }
   147538   }
   147539   return 0;
   147540 }
   147541 
   147542 /*
   147543 ** Return the N-th compile-time option string.  If N is out of range,
   147544 ** return a NULL pointer.
   147545 */
   147546 SQLITE_API const char *sqlite3_compileoption_get(int N){
   147547   int nOpt;
   147548   const char **azCompileOpt;
   147549   azCompileOpt = sqlite3CompileOptions(&nOpt);
   147550   if( N>=0 && N<nOpt ){
   147551     return azCompileOpt[N];
   147552   }
   147553   return 0;
   147554 }
   147555 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   147556 
   147557 /************** End of main.c ************************************************/
   147558 /************** Begin file notify.c ******************************************/
   147559 /*
   147560 ** 2009 March 3
   147561 **
   147562 ** The author disclaims copyright to this source code.  In place of
   147563 ** a legal notice, here is a blessing:
   147564 **
   147565 **    May you do good and not evil.
   147566 **    May you find forgiveness for yourself and forgive others.
   147567 **    May you share freely, never taking more than you give.
   147568 **
   147569 *************************************************************************
   147570 **
   147571 ** This file contains the implementation of the sqlite3_unlock_notify()
   147572 ** API method and its associated functionality.
   147573 */
   147574 /* #include "sqliteInt.h" */
   147575 /* #include "btreeInt.h" */
   147576 
   147577 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
   147578 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   147579 
   147580 /*
   147581 ** Public interfaces:
   147582 **
   147583 **   sqlite3ConnectionBlocked()
   147584 **   sqlite3ConnectionUnlocked()
   147585 **   sqlite3ConnectionClosed()
   147586 **   sqlite3_unlock_notify()
   147587 */
   147588 
   147589 #define assertMutexHeld() \
   147590   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
   147591 
   147592 /*
   147593 ** Head of a linked list of all sqlite3 objects created by this process
   147594 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
   147595 ** is not NULL. This variable may only accessed while the STATIC_MASTER
   147596 ** mutex is held.
   147597 */
   147598 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
   147599 
   147600 #ifndef NDEBUG
   147601 /*
   147602 ** This function is a complex assert() that verifies the following
   147603 ** properties of the blocked connections list:
   147604 **
   147605 **   1) Each entry in the list has a non-NULL value for either
   147606 **      pUnlockConnection or pBlockingConnection, or both.
   147607 **
   147608 **   2) All entries in the list that share a common value for
   147609 **      xUnlockNotify are grouped together.
   147610 **
   147611 **   3) If the argument db is not NULL, then none of the entries in the
   147612 **      blocked connections list have pUnlockConnection or pBlockingConnection
   147613 **      set to db. This is used when closing connection db.
   147614 */
   147615 static void checkListProperties(sqlite3 *db){
   147616   sqlite3 *p;
   147617   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
   147618     int seen = 0;
   147619     sqlite3 *p2;
   147620 
   147621     /* Verify property (1) */
   147622     assert( p->pUnlockConnection || p->pBlockingConnection );
   147623 
   147624     /* Verify property (2) */
   147625     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
   147626       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
   147627       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
   147628       assert( db==0 || p->pUnlockConnection!=db );
   147629       assert( db==0 || p->pBlockingConnection!=db );
   147630     }
   147631   }
   147632 }
   147633 #else
   147634 # define checkListProperties(x)
   147635 #endif
   147636 
   147637 /*
   147638 ** Remove connection db from the blocked connections list. If connection
   147639 ** db is not currently a part of the list, this function is a no-op.
   147640 */
   147641 static void removeFromBlockedList(sqlite3 *db){
   147642   sqlite3 **pp;
   147643   assertMutexHeld();
   147644   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
   147645     if( *pp==db ){
   147646       *pp = (*pp)->pNextBlocked;
   147647       break;
   147648     }
   147649   }
   147650 }
   147651 
   147652 /*
   147653 ** Add connection db to the blocked connections list. It is assumed
   147654 ** that it is not already a part of the list.
   147655 */
   147656 static void addToBlockedList(sqlite3 *db){
   147657   sqlite3 **pp;
   147658   assertMutexHeld();
   147659   for(
   147660     pp=&sqlite3BlockedList;
   147661     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
   147662     pp=&(*pp)->pNextBlocked
   147663   );
   147664   db->pNextBlocked = *pp;
   147665   *pp = db;
   147666 }
   147667 
   147668 /*
   147669 ** Obtain the STATIC_MASTER mutex.
   147670 */
   147671 static void enterMutex(void){
   147672   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   147673   checkListProperties(0);
   147674 }
   147675 
   147676 /*
   147677 ** Release the STATIC_MASTER mutex.
   147678 */
   147679 static void leaveMutex(void){
   147680   assertMutexHeld();
   147681   checkListProperties(0);
   147682   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   147683 }
   147684 
   147685 /*
   147686 ** Register an unlock-notify callback.
   147687 **
   147688 ** This is called after connection "db" has attempted some operation
   147689 ** but has received an SQLITE_LOCKED error because another connection
   147690 ** (call it pOther) in the same process was busy using the same shared
   147691 ** cache.  pOther is found by looking at db->pBlockingConnection.
   147692 **
   147693 ** If there is no blocking connection, the callback is invoked immediately,
   147694 ** before this routine returns.
   147695 **
   147696 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
   147697 ** a deadlock.
   147698 **
   147699 ** Otherwise, make arrangements to invoke xNotify when pOther drops
   147700 ** its locks.
   147701 **
   147702 ** Each call to this routine overrides any prior callbacks registered
   147703 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
   147704 ** cancelled.
   147705 */
   147706 SQLITE_API int sqlite3_unlock_notify(
   147707   sqlite3 *db,
   147708   void (*xNotify)(void **, int),
   147709   void *pArg
   147710 ){
   147711   int rc = SQLITE_OK;
   147712 
   147713   sqlite3_mutex_enter(db->mutex);
   147714   enterMutex();
   147715 
   147716   if( xNotify==0 ){
   147717     removeFromBlockedList(db);
   147718     db->pBlockingConnection = 0;
   147719     db->pUnlockConnection = 0;
   147720     db->xUnlockNotify = 0;
   147721     db->pUnlockArg = 0;
   147722   }else if( 0==db->pBlockingConnection ){
   147723     /* The blocking transaction has been concluded. Or there never was a
   147724     ** blocking transaction. In either case, invoke the notify callback
   147725     ** immediately.
   147726     */
   147727     xNotify(&pArg, 1);
   147728   }else{
   147729     sqlite3 *p;
   147730 
   147731     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
   147732     if( p ){
   147733       rc = SQLITE_LOCKED;              /* Deadlock detected. */
   147734     }else{
   147735       db->pUnlockConnection = db->pBlockingConnection;
   147736       db->xUnlockNotify = xNotify;
   147737       db->pUnlockArg = pArg;
   147738       removeFromBlockedList(db);
   147739       addToBlockedList(db);
   147740     }
   147741   }
   147742 
   147743   leaveMutex();
   147744   assert( !db->mallocFailed );
   147745   sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
   147746   sqlite3_mutex_leave(db->mutex);
   147747   return rc;
   147748 }
   147749 
   147750 /*
   147751 ** This function is called while stepping or preparing a statement
   147752 ** associated with connection db. The operation will return SQLITE_LOCKED
   147753 ** to the user because it requires a lock that will not be available
   147754 ** until connection pBlocker concludes its current transaction.
   147755 */
   147756 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
   147757   enterMutex();
   147758   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
   147759     addToBlockedList(db);
   147760   }
   147761   db->pBlockingConnection = pBlocker;
   147762   leaveMutex();
   147763 }
   147764 
   147765 /*
   147766 ** This function is called when
   147767 ** the transaction opened by database db has just finished. Locks held
   147768 ** by database connection db have been released.
   147769 **
   147770 ** This function loops through each entry in the blocked connections
   147771 ** list and does the following:
   147772 **
   147773 **   1) If the sqlite3.pBlockingConnection member of a list entry is
   147774 **      set to db, then set pBlockingConnection=0.
   147775 **
   147776 **   2) If the sqlite3.pUnlockConnection member of a list entry is
   147777 **      set to db, then invoke the configured unlock-notify callback and
   147778 **      set pUnlockConnection=0.
   147779 **
   147780 **   3) If the two steps above mean that pBlockingConnection==0 and
   147781 **      pUnlockConnection==0, remove the entry from the blocked connections
   147782 **      list.
   147783 */
   147784 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   147785   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
   147786   int nArg = 0;                            /* Number of entries in aArg[] */
   147787   sqlite3 **pp;                            /* Iterator variable */
   147788   void **aArg;               /* Arguments to the unlock callback */
   147789   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
   147790   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
   147791 
   147792   aArg = aStatic;
   147793   enterMutex();         /* Enter STATIC_MASTER mutex */
   147794 
   147795   /* This loop runs once for each entry in the blocked-connections list. */
   147796   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
   147797     sqlite3 *p = *pp;
   147798 
   147799     /* Step 1. */
   147800     if( p->pBlockingConnection==db ){
   147801       p->pBlockingConnection = 0;
   147802     }
   147803 
   147804     /* Step 2. */
   147805     if( p->pUnlockConnection==db ){
   147806       assert( p->xUnlockNotify );
   147807       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
   147808         xUnlockNotify(aArg, nArg);
   147809         nArg = 0;
   147810       }
   147811 
   147812       sqlite3BeginBenignMalloc();
   147813       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
   147814       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
   147815       if( (!aDyn && nArg==(int)ArraySize(aStatic))
   147816        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
   147817       ){
   147818         /* The aArg[] array needs to grow. */
   147819         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
   147820         if( pNew ){
   147821           memcpy(pNew, aArg, nArg*sizeof(void *));
   147822           sqlite3_free(aDyn);
   147823           aDyn = aArg = pNew;
   147824         }else{
   147825           /* This occurs when the array of context pointers that need to
   147826           ** be passed to the unlock-notify callback is larger than the
   147827           ** aStatic[] array allocated on the stack and the attempt to
   147828           ** allocate a larger array from the heap has failed.
   147829           **
   147830           ** This is a difficult situation to handle. Returning an error
   147831           ** code to the caller is insufficient, as even if an error code
   147832           ** is returned the transaction on connection db will still be
   147833           ** closed and the unlock-notify callbacks on blocked connections
   147834           ** will go unissued. This might cause the application to wait
   147835           ** indefinitely for an unlock-notify callback that will never
   147836           ** arrive.
   147837           **
   147838           ** Instead, invoke the unlock-notify callback with the context
   147839           ** array already accumulated. We can then clear the array and
   147840           ** begin accumulating any further context pointers without
   147841           ** requiring any dynamic allocation. This is sub-optimal because
   147842           ** it means that instead of one callback with a large array of
   147843           ** context pointers the application will receive two or more
   147844           ** callbacks with smaller arrays of context pointers, which will
   147845           ** reduce the applications ability to prioritize multiple
   147846           ** connections. But it is the best that can be done under the
   147847           ** circumstances.
   147848           */
   147849           xUnlockNotify(aArg, nArg);
   147850           nArg = 0;
   147851         }
   147852       }
   147853       sqlite3EndBenignMalloc();
   147854 
   147855       aArg[nArg++] = p->pUnlockArg;
   147856       xUnlockNotify = p->xUnlockNotify;
   147857       p->pUnlockConnection = 0;
   147858       p->xUnlockNotify = 0;
   147859       p->pUnlockArg = 0;
   147860     }
   147861 
   147862     /* Step 3. */
   147863     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
   147864       /* Remove connection p from the blocked connections list. */
   147865       *pp = p->pNextBlocked;
   147866       p->pNextBlocked = 0;
   147867     }else{
   147868       pp = &p->pNextBlocked;
   147869     }
   147870   }
   147871 
   147872   if( nArg!=0 ){
   147873     xUnlockNotify(aArg, nArg);
   147874   }
   147875   sqlite3_free(aDyn);
   147876   leaveMutex();         /* Leave STATIC_MASTER mutex */
   147877 }
   147878 
   147879 /*
   147880 ** This is called when the database connection passed as an argument is
   147881 ** being closed. The connection is removed from the blocked list.
   147882 */
   147883 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
   147884   sqlite3ConnectionUnlocked(db);
   147885   enterMutex();
   147886   removeFromBlockedList(db);
   147887   checkListProperties(db);
   147888   leaveMutex();
   147889 }
   147890 #endif
   147891 
   147892 /************** End of notify.c **********************************************/
   147893 /************** Begin file fts3.c ********************************************/
   147894 /*
   147895 ** 2006 Oct 10
   147896 **
   147897 ** The author disclaims copyright to this source code.  In place of
   147898 ** a legal notice, here is a blessing:
   147899 **
   147900 **    May you do good and not evil.
   147901 **    May you find forgiveness for yourself and forgive others.
   147902 **    May you share freely, never taking more than you give.
   147903 **
   147904 ******************************************************************************
   147905 **
   147906 ** This is an SQLite module implementing full-text search.
   147907 */
   147908 
   147909 /*
   147910 ** The code in this file is only compiled if:
   147911 **
   147912 **     * The FTS3 module is being built as an extension
   147913 **       (in which case SQLITE_CORE is not defined), or
   147914 **
   147915 **     * The FTS3 module is being built into the core of
   147916 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   147917 */
   147918 
   147919 /* The full-text index is stored in a series of b+tree (-like)
   147920 ** structures called segments which map terms to doclists.  The
   147921 ** structures are like b+trees in layout, but are constructed from the
   147922 ** bottom up in optimal fashion and are not updatable.  Since trees
   147923 ** are built from the bottom up, things will be described from the
   147924 ** bottom up.
   147925 **
   147926 **
   147927 **** Varints ****
   147928 ** The basic unit of encoding is a variable-length integer called a
   147929 ** varint.  We encode variable-length integers in little-endian order
   147930 ** using seven bits * per byte as follows:
   147931 **
   147932 ** KEY:
   147933 **         A = 0xxxxxxx    7 bits of data and one flag bit
   147934 **         B = 1xxxxxxx    7 bits of data and one flag bit
   147935 **
   147936 **  7 bits - A
   147937 ** 14 bits - BA
   147938 ** 21 bits - BBA
   147939 ** and so on.
   147940 **
   147941 ** This is similar in concept to how sqlite encodes "varints" but
   147942 ** the encoding is not the same.  SQLite varints are big-endian
   147943 ** are are limited to 9 bytes in length whereas FTS3 varints are
   147944 ** little-endian and can be up to 10 bytes in length (in theory).
   147945 **
   147946 ** Example encodings:
   147947 **
   147948 **     1:    0x01
   147949 **   127:    0x7f
   147950 **   128:    0x81 0x00
   147951 **
   147952 **
   147953 **** Document lists ****
   147954 ** A doclist (document list) holds a docid-sorted list of hits for a
   147955 ** given term.  Doclists hold docids and associated token positions.
   147956 ** A docid is the unique integer identifier for a single document.
   147957 ** A position is the index of a word within the document.  The first
   147958 ** word of the document has a position of 0.
   147959 **
   147960 ** FTS3 used to optionally store character offsets using a compile-time
   147961 ** option.  But that functionality is no longer supported.
   147962 **
   147963 ** A doclist is stored like this:
   147964 **
   147965 ** array {
   147966 **   varint docid;          (delta from previous doclist)
   147967 **   array {                (position list for column 0)
   147968 **     varint position;     (2 more than the delta from previous position)
   147969 **   }
   147970 **   array {
   147971 **     varint POS_COLUMN;   (marks start of position list for new column)
   147972 **     varint column;       (index of new column)
   147973 **     array {
   147974 **       varint position;   (2 more than the delta from previous position)
   147975 **     }
   147976 **   }
   147977 **   varint POS_END;        (marks end of positions for this document.
   147978 ** }
   147979 **
   147980 ** Here, array { X } means zero or more occurrences of X, adjacent in
   147981 ** memory.  A "position" is an index of a token in the token stream
   147982 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
   147983 ** in the same logical place as the position element, and act as sentinals
   147984 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
   147985 ** The positions numbers are not stored literally but rather as two more
   147986 ** than the difference from the prior position, or the just the position plus
   147987 ** 2 for the first position.  Example:
   147988 **
   147989 **   label:       A B C D E  F  G H   I  J K
   147990 **   value:     123 5 9 1 1 14 35 0 234 72 0
   147991 **
   147992 ** The 123 value is the first docid.  For column zero in this document
   147993 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
   147994 ** at D signals the start of a new column; the 1 at E indicates that the
   147995 ** new column is column number 1.  There are two positions at 12 and 45
   147996 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
   147997 ** 234 at I is the delta to next docid (357).  It has one position 70
   147998 ** (72-2) and then terminates with the 0 at K.
   147999 **
   148000 ** A "position-list" is the list of positions for multiple columns for
   148001 ** a single docid.  A "column-list" is the set of positions for a single
   148002 ** column.  Hence, a position-list consists of one or more column-lists,
   148003 ** a document record consists of a docid followed by a position-list and
   148004 ** a doclist consists of one or more document records.
   148005 **
   148006 ** A bare doclist omits the position information, becoming an
   148007 ** array of varint-encoded docids.
   148008 **
   148009 **** Segment leaf nodes ****
   148010 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
   148011 ** nodes are written using LeafWriter, and read using LeafReader (to
   148012 ** iterate through a single leaf node's data) and LeavesReader (to
   148013 ** iterate through a segment's entire leaf layer).  Leaf nodes have
   148014 ** the format:
   148015 **
   148016 ** varint iHeight;             (height from leaf level, always 0)
   148017 ** varint nTerm;               (length of first term)
   148018 ** char pTerm[nTerm];          (content of first term)
   148019 ** varint nDoclist;            (length of term's associated doclist)
   148020 ** char pDoclist[nDoclist];    (content of doclist)
   148021 ** array {
   148022 **                             (further terms are delta-encoded)
   148023 **   varint nPrefix;           (length of prefix shared with previous term)
   148024 **   varint nSuffix;           (length of unshared suffix)
   148025 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
   148026 **   varint nDoclist;          (length of term's associated doclist)
   148027 **   char pDoclist[nDoclist];  (content of doclist)
   148028 ** }
   148029 **
   148030 ** Here, array { X } means zero or more occurrences of X, adjacent in
   148031 ** memory.
   148032 **
   148033 ** Leaf nodes are broken into blocks which are stored contiguously in
   148034 ** the %_segments table in sorted order.  This means that when the end
   148035 ** of a node is reached, the next term is in the node with the next
   148036 ** greater node id.
   148037 **
   148038 ** New data is spilled to a new leaf node when the current node
   148039 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
   148040 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
   148041 ** node (a leaf node with a single term and doclist).  The goal of
   148042 ** these settings is to pack together groups of small doclists while
   148043 ** making it efficient to directly access large doclists.  The
   148044 ** assumption is that large doclists represent terms which are more
   148045 ** likely to be query targets.
   148046 **
   148047 ** TODO(shess) It may be useful for blocking decisions to be more
   148048 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
   148049 ** node rather than splitting into 2k and .5k nodes.  My intuition is
   148050 ** that this might extend through 2x or 4x the pagesize.
   148051 **
   148052 **
   148053 **** Segment interior nodes ****
   148054 ** Segment interior nodes store blockids for subtree nodes and terms
   148055 ** to describe what data is stored by the each subtree.  Interior
   148056 ** nodes are written using InteriorWriter, and read using
   148057 ** InteriorReader.  InteriorWriters are created as needed when
   148058 ** SegmentWriter creates new leaf nodes, or when an interior node
   148059 ** itself grows too big and must be split.  The format of interior
   148060 ** nodes:
   148061 **
   148062 ** varint iHeight;           (height from leaf level, always >0)
   148063 ** varint iBlockid;          (block id of node's leftmost subtree)
   148064 ** optional {
   148065 **   varint nTerm;           (length of first term)
   148066 **   char pTerm[nTerm];      (content of first term)
   148067 **   array {
   148068 **                                (further terms are delta-encoded)
   148069 **     varint nPrefix;            (length of shared prefix with previous term)
   148070 **     varint nSuffix;            (length of unshared suffix)
   148071 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
   148072 **   }
   148073 ** }
   148074 **
   148075 ** Here, optional { X } means an optional element, while array { X }
   148076 ** means zero or more occurrences of X, adjacent in memory.
   148077 **
   148078 ** An interior node encodes n terms separating n+1 subtrees.  The
   148079 ** subtree blocks are contiguous, so only the first subtree's blockid
   148080 ** is encoded.  The subtree at iBlockid will contain all terms less
   148081 ** than the first term encoded (or all terms if no term is encoded).
   148082 ** Otherwise, for terms greater than or equal to pTerm[i] but less
   148083 ** than pTerm[i+1], the subtree for that term will be rooted at
   148084 ** iBlockid+i.  Interior nodes only store enough term data to
   148085 ** distinguish adjacent children (if the rightmost term of the left
   148086 ** child is "something", and the leftmost term of the right child is
   148087 ** "wicked", only "w" is stored).
   148088 **
   148089 ** New data is spilled to a new interior node at the same height when
   148090 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
   148091 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
   148092 ** interior nodes and making the tree too skinny.  The interior nodes
   148093 ** at a given height are naturally tracked by interior nodes at
   148094 ** height+1, and so on.
   148095 **
   148096 **
   148097 **** Segment directory ****
   148098 ** The segment directory in table %_segdir stores meta-information for
   148099 ** merging and deleting segments, and also the root node of the
   148100 ** segment's tree.
   148101 **
   148102 ** The root node is the top node of the segment's tree after encoding
   148103 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
   148104 ** This could be either a leaf node or an interior node.  If the top
   148105 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
   148106 ** and a new root interior node is generated (which should always fit
   148107 ** within ROOT_MAX because it only needs space for 2 varints, the
   148108 ** height and the blockid of the previous root).
   148109 **
   148110 ** The meta-information in the segment directory is:
   148111 **   level               - segment level (see below)
   148112 **   idx                 - index within level
   148113 **                       - (level,idx uniquely identify a segment)
   148114 **   start_block         - first leaf node
   148115 **   leaves_end_block    - last leaf node
   148116 **   end_block           - last block (including interior nodes)
   148117 **   root                - contents of root node
   148118 **
   148119 ** If the root node is a leaf node, then start_block,
   148120 ** leaves_end_block, and end_block are all 0.
   148121 **
   148122 **
   148123 **** Segment merging ****
   148124 ** To amortize update costs, segments are grouped into levels and
   148125 ** merged in batches.  Each increase in level represents exponentially
   148126 ** more documents.
   148127 **
   148128 ** New documents (actually, document updates) are tokenized and
   148129 ** written individually (using LeafWriter) to a level 0 segment, with
   148130 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
   148131 ** level 0 segments are merged into a single level 1 segment.  Level 1
   148132 ** is populated like level 0, and eventually MERGE_COUNT level 1
   148133 ** segments are merged to a single level 2 segment (representing
   148134 ** MERGE_COUNT^2 updates), and so on.
   148135 **
   148136 ** A segment merge traverses all segments at a given level in
   148137 ** parallel, performing a straightforward sorted merge.  Since segment
   148138 ** leaf nodes are written in to the %_segments table in order, this
   148139 ** merge traverses the underlying sqlite disk structures efficiently.
   148140 ** After the merge, all segment blocks from the merged level are
   148141 ** deleted.
   148142 **
   148143 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
   148144 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
   148145 ** very similar performance numbers to 16 on insertion, though they're
   148146 ** a tiny bit slower (perhaps due to more overhead in merge-time
   148147 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
   148148 ** 16, 2 about 66% slower than 16.
   148149 **
   148150 ** At query time, high MERGE_COUNT increases the number of segments
   148151 ** which need to be scanned and merged.  For instance, with 100k docs
   148152 ** inserted:
   148153 **
   148154 **    MERGE_COUNT   segments
   148155 **       16           25
   148156 **        8           12
   148157 **        4           10
   148158 **        2            6
   148159 **
   148160 ** This appears to have only a moderate impact on queries for very
   148161 ** frequent terms (which are somewhat dominated by segment merge
   148162 ** costs), and infrequent and non-existent terms still seem to be fast
   148163 ** even with many segments.
   148164 **
   148165 ** TODO(shess) That said, it would be nice to have a better query-side
   148166 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
   148167 ** optimizations to things like doclist merging will swing the sweet
   148168 ** spot around.
   148169 **
   148170 **
   148171 **
   148172 **** Handling of deletions and updates ****
   148173 ** Since we're using a segmented structure, with no docid-oriented
   148174 ** index into the term index, we clearly cannot simply update the term
   148175 ** index when a document is deleted or updated.  For deletions, we
   148176 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
   148177 ** we simply write the new doclist.  Segment merges overwrite older
   148178 ** data for a particular docid with newer data, so deletes or updates
   148179 ** will eventually overtake the earlier data and knock it out.  The
   148180 ** query logic likewise merges doclists so that newer data knocks out
   148181 ** older data.
   148182 */
   148183 
   148184 /************** Include fts3Int.h in the middle of fts3.c ********************/
   148185 /************** Begin file fts3Int.h *****************************************/
   148186 /*
   148187 ** 2009 Nov 12
   148188 **
   148189 ** The author disclaims copyright to this source code.  In place of
   148190 ** a legal notice, here is a blessing:
   148191 **
   148192 **    May you do good and not evil.
   148193 **    May you find forgiveness for yourself and forgive others.
   148194 **    May you share freely, never taking more than you give.
   148195 **
   148196 ******************************************************************************
   148197 **
   148198 */
   148199 #ifndef _FTSINT_H
   148200 #define _FTSINT_H
   148201 
   148202 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   148203 # define NDEBUG 1
   148204 #endif
   148205 
   148206 /* FTS3/FTS4 require virtual tables */
   148207 #ifdef SQLITE_OMIT_VIRTUALTABLE
   148208 # undef SQLITE_ENABLE_FTS3
   148209 # undef SQLITE_ENABLE_FTS4
   148210 #endif
   148211 
   148212 /*
   148213 ** FTS4 is really an extension for FTS3.  It is enabled using the
   148214 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   148215 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   148216 */
   148217 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   148218 # define SQLITE_ENABLE_FTS3
   148219 #endif
   148220 
   148221 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   148222 
   148223 /* If not building as part of the core, include sqlite3ext.h. */
   148224 #ifndef SQLITE_CORE
   148225 /* # include "sqlite3ext.h"  */
   148226 SQLITE_EXTENSION_INIT3
   148227 #endif
   148228 
   148229 /* #include "sqlite3.h" */
   148230 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
   148231 /************** Begin file fts3_tokenizer.h **********************************/
   148232 /*
   148233 ** 2006 July 10
   148234 **
   148235 ** The author disclaims copyright to this source code.
   148236 **
   148237 *************************************************************************
   148238 ** Defines the interface to tokenizers used by fulltext-search.  There
   148239 ** are three basic components:
   148240 **
   148241 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
   148242 ** interface functions.  This is essentially the class structure for
   148243 ** tokenizers.
   148244 **
   148245 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
   148246 ** including customization information defined at creation time.
   148247 **
   148248 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
   148249 ** tokens from a particular input.
   148250 */
   148251 #ifndef _FTS3_TOKENIZER_H_
   148252 #define _FTS3_TOKENIZER_H_
   148253 
   148254 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
   148255 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
   148256 ** we will need a way to register the API consistently.
   148257 */
   148258 /* #include "sqlite3.h" */
   148259 
   148260 /*
   148261 ** Structures used by the tokenizer interface. When a new tokenizer
   148262 ** implementation is registered, the caller provides a pointer to
   148263 ** an sqlite3_tokenizer_module containing pointers to the callback
   148264 ** functions that make up an implementation.
   148265 **
   148266 ** When an fts3 table is created, it passes any arguments passed to
   148267 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
   148268 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
   148269 ** implementation. The xCreate() function in turn returns an
   148270 ** sqlite3_tokenizer structure representing the specific tokenizer to
   148271 ** be used for the fts3 table (customized by the tokenizer clause arguments).
   148272 **
   148273 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
   148274 ** method is called. It returns an sqlite3_tokenizer_cursor object
   148275 ** that may be used to tokenize a specific input buffer based on
   148276 ** the tokenization rules supplied by a specific sqlite3_tokenizer
   148277 ** object.
   148278 */
   148279 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
   148280 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
   148281 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
   148282 
   148283 struct sqlite3_tokenizer_module {
   148284 
   148285   /*
   148286   ** Structure version. Should always be set to 0 or 1.
   148287   */
   148288   int iVersion;
   148289 
   148290   /*
   148291   ** Create a new tokenizer. The values in the argv[] array are the
   148292   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
   148293   ** TABLE statement that created the fts3 table. For example, if
   148294   ** the following SQL is executed:
   148295   **
   148296   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
   148297   **
   148298   ** then argc is set to 2, and the argv[] array contains pointers
   148299   ** to the strings "arg1" and "arg2".
   148300   **
   148301   ** This method should return either SQLITE_OK (0), or an SQLite error
   148302   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   148303   ** to point at the newly created tokenizer structure. The generic
   148304   ** sqlite3_tokenizer.pModule variable should not be initialized by
   148305   ** this callback. The caller will do so.
   148306   */
   148307   int (*xCreate)(
   148308     int argc,                           /* Size of argv array */
   148309     const char *const*argv,             /* Tokenizer argument strings */
   148310     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
   148311   );
   148312 
   148313   /*
   148314   ** Destroy an existing tokenizer. The fts3 module calls this method
   148315   ** exactly once for each successful call to xCreate().
   148316   */
   148317   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
   148318 
   148319   /*
   148320   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   148321   ** is responsible for ensuring that the input buffer remains valid
   148322   ** until the cursor is closed (using the xClose() method).
   148323   */
   148324   int (*xOpen)(
   148325     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
   148326     const char *pInput, int nBytes,      /* Input buffer */
   148327     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
   148328   );
   148329 
   148330   /*
   148331   ** Destroy an existing tokenizer cursor. The fts3 module calls this
   148332   ** method exactly once for each successful call to xOpen().
   148333   */
   148334   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
   148335 
   148336   /*
   148337   ** Retrieve the next token from the tokenizer cursor pCursor. This
   148338   ** method should either return SQLITE_OK and set the values of the
   148339   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   148340   ** the end of the buffer has been reached, or an SQLite error code.
   148341   **
   148342   ** *ppToken should be set to point at a buffer containing the
   148343   ** normalized version of the token (i.e. after any case-folding and/or
   148344   ** stemming has been performed). *pnBytes should be set to the length
   148345   ** of this buffer in bytes. The input text that generated the token is
   148346   ** identified by the byte offsets returned in *piStartOffset and
   148347   ** *piEndOffset. *piStartOffset should be set to the index of the first
   148348   ** byte of the token in the input buffer. *piEndOffset should be set
   148349   ** to the index of the first byte just past the end of the token in
   148350   ** the input buffer.
   148351   **
   148352   ** The buffer *ppToken is set to point at is managed by the tokenizer
   148353   ** implementation. It is only required to be valid until the next call
   148354   ** to xNext() or xClose().
   148355   */
   148356   /* TODO(shess) current implementation requires pInput to be
   148357   ** nul-terminated.  This should either be fixed, or pInput/nBytes
   148358   ** should be converted to zInput.
   148359   */
   148360   int (*xNext)(
   148361     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
   148362     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
   148363     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
   148364     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
   148365     int *piPosition      /* OUT: Number of tokens returned before this one */
   148366   );
   148367 
   148368   /***********************************************************************
   148369   ** Methods below this point are only available if iVersion>=1.
   148370   */
   148371 
   148372   /*
   148373   ** Configure the language id of a tokenizer cursor.
   148374   */
   148375   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
   148376 };
   148377 
   148378 struct sqlite3_tokenizer {
   148379   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
   148380   /* Tokenizer implementations will typically add additional fields */
   148381 };
   148382 
   148383 struct sqlite3_tokenizer_cursor {
   148384   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
   148385   /* Tokenizer implementations will typically add additional fields */
   148386 };
   148387 
   148388 int fts3_global_term_cnt(int iTerm, int iCol);
   148389 int fts3_term_cnt(int iTerm, int iCol);
   148390 
   148391 
   148392 #endif /* _FTS3_TOKENIZER_H_ */
   148393 
   148394 /************** End of fts3_tokenizer.h **************************************/
   148395 /************** Continuing where we left off in fts3Int.h ********************/
   148396 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
   148397 /************** Begin file fts3_hash.h ***************************************/
   148398 /*
   148399 ** 2001 September 22
   148400 **
   148401 ** The author disclaims copyright to this source code.  In place of
   148402 ** a legal notice, here is a blessing:
   148403 **
   148404 **    May you do good and not evil.
   148405 **    May you find forgiveness for yourself and forgive others.
   148406 **    May you share freely, never taking more than you give.
   148407 **
   148408 *************************************************************************
   148409 ** This is the header file for the generic hash-table implementation
   148410 ** used in SQLite.  We've modified it slightly to serve as a standalone
   148411 ** hash table implementation for the full-text indexing module.
   148412 **
   148413 */
   148414 #ifndef _FTS3_HASH_H_
   148415 #define _FTS3_HASH_H_
   148416 
   148417 /* Forward declarations of structures. */
   148418 typedef struct Fts3Hash Fts3Hash;
   148419 typedef struct Fts3HashElem Fts3HashElem;
   148420 
   148421 /* A complete hash table is an instance of the following structure.
   148422 ** The internals of this structure are intended to be opaque -- client
   148423 ** code should not attempt to access or modify the fields of this structure
   148424 ** directly.  Change this structure only by using the routines below.
   148425 ** However, many of the "procedures" and "functions" for modifying and
   148426 ** accessing this structure are really macros, so we can't really make
   148427 ** this structure opaque.
   148428 */
   148429 struct Fts3Hash {
   148430   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
   148431   char copyKey;           /* True if copy of key made on insert */
   148432   int count;              /* Number of entries in this table */
   148433   Fts3HashElem *first;    /* The first element of the array */
   148434   int htsize;             /* Number of buckets in the hash table */
   148435   struct _fts3ht {        /* the hash table */
   148436     int count;               /* Number of entries with this hash */
   148437     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
   148438   } *ht;
   148439 };
   148440 
   148441 /* Each element in the hash table is an instance of the following
   148442 ** structure.  All elements are stored on a single doubly-linked list.
   148443 **
   148444 ** Again, this structure is intended to be opaque, but it can't really
   148445 ** be opaque because it is used by macros.
   148446 */
   148447 struct Fts3HashElem {
   148448   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
   148449   void *data;                /* Data associated with this element */
   148450   void *pKey; int nKey;      /* Key associated with this element */
   148451 };
   148452 
   148453 /*
   148454 ** There are 2 different modes of operation for a hash table:
   148455 **
   148456 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
   148457 **                           (including the null-terminator, if any).  Case
   148458 **                           is respected in comparisons.
   148459 **
   148460 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
   148461 **                           memcmp() is used to compare keys.
   148462 **
   148463 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
   148464 */
   148465 #define FTS3_HASH_STRING    1
   148466 #define FTS3_HASH_BINARY    2
   148467 
   148468 /*
   148469 ** Access routines.  To delete, insert a NULL pointer.
   148470 */
   148471 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
   148472 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
   148473 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
   148474 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
   148475 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
   148476 
   148477 /*
   148478 ** Shorthand for the functions above
   148479 */
   148480 #define fts3HashInit     sqlite3Fts3HashInit
   148481 #define fts3HashInsert   sqlite3Fts3HashInsert
   148482 #define fts3HashFind     sqlite3Fts3HashFind
   148483 #define fts3HashClear    sqlite3Fts3HashClear
   148484 #define fts3HashFindElem sqlite3Fts3HashFindElem
   148485 
   148486 /*
   148487 ** Macros for looping over all elements of a hash table.  The idiom is
   148488 ** like this:
   148489 **
   148490 **   Fts3Hash h;
   148491 **   Fts3HashElem *p;
   148492 **   ...
   148493 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
   148494 **     SomeStructure *pData = fts3HashData(p);
   148495 **     // do something with pData
   148496 **   }
   148497 */
   148498 #define fts3HashFirst(H)  ((H)->first)
   148499 #define fts3HashNext(E)   ((E)->next)
   148500 #define fts3HashData(E)   ((E)->data)
   148501 #define fts3HashKey(E)    ((E)->pKey)
   148502 #define fts3HashKeysize(E) ((E)->nKey)
   148503 
   148504 /*
   148505 ** Number of entries in a hash table
   148506 */
   148507 #define fts3HashCount(H)  ((H)->count)
   148508 
   148509 #endif /* _FTS3_HASH_H_ */
   148510 
   148511 /************** End of fts3_hash.h *******************************************/
   148512 /************** Continuing where we left off in fts3Int.h ********************/
   148513 
   148514 /*
   148515 ** This constant determines the maximum depth of an FTS expression tree
   148516 ** that the library will create and use. FTS uses recursion to perform
   148517 ** various operations on the query tree, so the disadvantage of a large
   148518 ** limit is that it may allow very large queries to use large amounts
   148519 ** of stack space (perhaps causing a stack overflow).
   148520 */
   148521 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
   148522 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
   148523 #endif
   148524 
   148525 
   148526 /*
   148527 ** This constant controls how often segments are merged. Once there are
   148528 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
   148529 ** segment of level N+1.
   148530 */
   148531 #define FTS3_MERGE_COUNT 16
   148532 
   148533 /*
   148534 ** This is the maximum amount of data (in bytes) to store in the
   148535 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
   148536 ** populated as documents are inserted/updated/deleted in a transaction
   148537 ** and used to create a new segment when the transaction is committed.
   148538 ** However if this limit is reached midway through a transaction, a new
   148539 ** segment is created and the hash table cleared immediately.
   148540 */
   148541 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
   148542 
   148543 /*
   148544 ** Macro to return the number of elements in an array. SQLite has a
   148545 ** similar macro called ArraySize(). Use a different name to avoid
   148546 ** a collision when building an amalgamation with built-in FTS3.
   148547 */
   148548 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
   148549 
   148550 
   148551 #ifndef MIN
   148552 # define MIN(x,y) ((x)<(y)?(x):(y))
   148553 #endif
   148554 #ifndef MAX
   148555 # define MAX(x,y) ((x)>(y)?(x):(y))
   148556 #endif
   148557 
   148558 /*
   148559 ** Maximum length of a varint encoded integer. The varint format is different
   148560 ** from that used by SQLite, so the maximum length is 10, not 9.
   148561 */
   148562 #define FTS3_VARINT_MAX 10
   148563 
   148564 /*
   148565 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
   148566 ** in the document set and zero or more prefix indexes. All indexes are stored
   148567 ** as one or more b+-trees in the %_segments and %_segdir tables.
   148568 **
   148569 ** It is possible to determine which index a b+-tree belongs to based on the
   148570 ** value stored in the "%_segdir.level" column. Given this value L, the index
   148571 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
   148572 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
   148573 ** between 1024 and 2047 to index 1, and so on.
   148574 **
   148575 ** It is considered impossible for an index to use more than 1024 levels. In
   148576 ** theory though this may happen, but only after at least
   148577 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
   148578 */
   148579 #define FTS3_SEGDIR_MAXLEVEL      1024
   148580 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
   148581 
   148582 /*
   148583 ** The testcase() macro is only used by the amalgamation.  If undefined,
   148584 ** make it a no-op.
   148585 */
   148586 #ifndef testcase
   148587 # define testcase(X)
   148588 #endif
   148589 
   148590 /*
   148591 ** Terminator values for position-lists and column-lists.
   148592 */
   148593 #define POS_COLUMN  (1)     /* Column-list terminator */
   148594 #define POS_END     (0)     /* Position-list terminator */
   148595 
   148596 /*
   148597 ** This section provides definitions to allow the
   148598 ** FTS3 extension to be compiled outside of the
   148599 ** amalgamation.
   148600 */
   148601 #ifndef SQLITE_AMALGAMATION
   148602 /*
   148603 ** Macros indicating that conditional expressions are always true or
   148604 ** false.
   148605 */
   148606 #ifdef SQLITE_COVERAGE_TEST
   148607 # define ALWAYS(x) (1)
   148608 # define NEVER(X)  (0)
   148609 #elif defined(SQLITE_DEBUG)
   148610 # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
   148611 # define NEVER(x) sqlite3Fts3Never((x)!=0)
   148612 SQLITE_PRIVATE int sqlite3Fts3Always(int b);
   148613 SQLITE_PRIVATE int sqlite3Fts3Never(int b);
   148614 #else
   148615 # define ALWAYS(x) (x)
   148616 # define NEVER(x)  (x)
   148617 #endif
   148618 
   148619 /*
   148620 ** Internal types used by SQLite.
   148621 */
   148622 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
   148623 typedef short int i16;            /* 2-byte (or larger) signed integer */
   148624 typedef unsigned int u32;         /* 4-byte unsigned integer */
   148625 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
   148626 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
   148627 
   148628 /*
   148629 ** Macro used to suppress compiler warnings for unused parameters.
   148630 */
   148631 #define UNUSED_PARAMETER(x) (void)(x)
   148632 
   148633 /*
   148634 ** Activate assert() only if SQLITE_TEST is enabled.
   148635 */
   148636 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   148637 # define NDEBUG 1
   148638 #endif
   148639 
   148640 /*
   148641 ** The TESTONLY macro is used to enclose variable declarations or
   148642 ** other bits of code that are needed to support the arguments
   148643 ** within testcase() and assert() macros.
   148644 */
   148645 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   148646 # define TESTONLY(X)  X
   148647 #else
   148648 # define TESTONLY(X)
   148649 #endif
   148650 
   148651 #endif /* SQLITE_AMALGAMATION */
   148652 
   148653 #ifdef SQLITE_DEBUG
   148654 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
   148655 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
   148656 #else
   148657 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
   148658 #endif
   148659 
   148660 typedef struct Fts3Table Fts3Table;
   148661 typedef struct Fts3Cursor Fts3Cursor;
   148662 typedef struct Fts3Expr Fts3Expr;
   148663 typedef struct Fts3Phrase Fts3Phrase;
   148664 typedef struct Fts3PhraseToken Fts3PhraseToken;
   148665 
   148666 typedef struct Fts3Doclist Fts3Doclist;
   148667 typedef struct Fts3SegFilter Fts3SegFilter;
   148668 typedef struct Fts3DeferredToken Fts3DeferredToken;
   148669 typedef struct Fts3SegReader Fts3SegReader;
   148670 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
   148671 
   148672 typedef struct MatchinfoBuffer MatchinfoBuffer;
   148673 
   148674 /*
   148675 ** A connection to a fulltext index is an instance of the following
   148676 ** structure. The xCreate and xConnect methods create an instance
   148677 ** of this structure and xDestroy and xDisconnect free that instance.
   148678 ** All other methods receive a pointer to the structure as one of their
   148679 ** arguments.
   148680 */
   148681 struct Fts3Table {
   148682   sqlite3_vtab base;              /* Base class used by SQLite core */
   148683   sqlite3 *db;                    /* The database connection */
   148684   const char *zDb;                /* logical database name */
   148685   const char *zName;              /* virtual table name */
   148686   int nColumn;                    /* number of named columns in virtual table */
   148687   char **azColumn;                /* column names.  malloced */
   148688   u8 *abNotindexed;               /* True for 'notindexed' columns */
   148689   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
   148690   char *zContentTbl;              /* content=xxx option, or NULL */
   148691   char *zLanguageid;              /* languageid=xxx option, or NULL */
   148692   int nAutoincrmerge;             /* Value configured by 'automerge' */
   148693   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
   148694 
   148695   /* Precompiled statements used by the implementation. Each of these
   148696   ** statements is run and reset within a single virtual table API call.
   148697   */
   148698   sqlite3_stmt *aStmt[40];
   148699   sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */
   148700 
   148701   char *zReadExprlist;
   148702   char *zWriteExprlist;
   148703 
   148704   int nNodeSize;                  /* Soft limit for node size */
   148705   u8 bFts4;                       /* True for FTS4, false for FTS3 */
   148706   u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
   148707   u8 bHasDocsize;                 /* True if %_docsize table exists */
   148708   u8 bDescIdx;                    /* True if doclists are in reverse order */
   148709   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
   148710   int nPgsz;                      /* Page size for host database */
   148711   char *zSegmentsTbl;             /* Name of %_segments table */
   148712   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
   148713 
   148714   /*
   148715   ** The following array of hash tables is used to buffer pending index
   148716   ** updates during transactions. All pending updates buffered at any one
   148717   ** time must share a common language-id (see the FTS4 langid= feature).
   148718   ** The current language id is stored in variable iPrevLangid.
   148719   **
   148720   ** A single FTS4 table may have multiple full-text indexes. For each index
   148721   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
   148722   ** terms that appear in the document set. Each subsequent index in aIndex[]
   148723   ** is an index of prefixes of a specific length.
   148724   **
   148725   ** Variable nPendingData contains an estimate the memory consumed by the
   148726   ** pending data structures, including hash table overhead, but not including
   148727   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
   148728   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
   148729   ** recently inserted record.
   148730   */
   148731   int nIndex;                     /* Size of aIndex[] */
   148732   struct Fts3Index {
   148733     int nPrefix;                  /* Prefix length (0 for main terms index) */
   148734     Fts3Hash hPending;            /* Pending terms table for this index */
   148735   } *aIndex;
   148736   int nMaxPendingData;            /* Max pending data before flush to disk */
   148737   int nPendingData;               /* Current bytes of pending data */
   148738   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
   148739   int iPrevLangid;                /* Langid of recently inserted document */
   148740   int bPrevDelete;                /* True if last operation was a delete */
   148741 
   148742 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   148743   /* State variables used for validating that the transaction control
   148744   ** methods of the virtual table are called at appropriate times.  These
   148745   ** values do not contribute to FTS functionality; they are used for
   148746   ** verifying the operation of the SQLite core.
   148747   */
   148748   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
   148749   int mxSavepoint;       /* Largest valid xSavepoint integer */
   148750 #endif
   148751 
   148752 #ifdef SQLITE_TEST
   148753   /* True to disable the incremental doclist optimization. This is controled
   148754   ** by special insert command 'test-no-incr-doclist'.  */
   148755   int bNoIncrDoclist;
   148756 #endif
   148757 };
   148758 
   148759 /*
   148760 ** When the core wants to read from the virtual table, it creates a
   148761 ** virtual table cursor (an instance of the following structure) using
   148762 ** the xOpen method. Cursors are destroyed using the xClose method.
   148763 */
   148764 struct Fts3Cursor {
   148765   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   148766   i16 eSearch;                    /* Search strategy (see below) */
   148767   u8 isEof;                       /* True if at End Of Results */
   148768   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
   148769   u8 bSeekStmt;                   /* True if pStmt is a seek */
   148770   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
   148771   Fts3Expr *pExpr;                /* Parsed MATCH query string */
   148772   int iLangid;                    /* Language being queried for */
   148773   int nPhrase;                    /* Number of matchable phrases in query */
   148774   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
   148775   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
   148776   char *pNextId;                  /* Pointer into the body of aDoclist */
   148777   char *aDoclist;                 /* List of docids for full-text queries */
   148778   int nDoclist;                   /* Size of buffer at aDoclist */
   148779   u8 bDesc;                       /* True to sort in descending order */
   148780   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
   148781   int nRowAvg;                    /* Average size of database rows, in pages */
   148782   sqlite3_int64 nDoc;             /* Documents in table */
   148783   i64 iMinDocid;                  /* Minimum docid to return */
   148784   i64 iMaxDocid;                  /* Maximum docid to return */
   148785   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
   148786   MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
   148787 };
   148788 
   148789 #define FTS3_EVAL_FILTER    0
   148790 #define FTS3_EVAL_NEXT      1
   148791 #define FTS3_EVAL_MATCHINFO 2
   148792 
   148793 /*
   148794 ** The Fts3Cursor.eSearch member is always set to one of the following.
   148795 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
   148796 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
   148797 ** of the column to be searched.  For example, in
   148798 **
   148799 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
   148800 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
   148801 **
   148802 ** Because the LHS of the MATCH operator is 2nd column "b",
   148803 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
   148804 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
   148805 ** indicating that all columns should be searched,
   148806 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
   148807 */
   148808 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
   148809 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
   148810 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
   148811 
   148812 /*
   148813 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
   148814 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
   148815 ** above. The upper 16-bits contain a combination of the following
   148816 ** bits, used to describe extra constraints on full-text searches.
   148817 */
   148818 #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
   148819 #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
   148820 #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
   148821 
   148822 struct Fts3Doclist {
   148823   char *aAll;                    /* Array containing doclist (or NULL) */
   148824   int nAll;                      /* Size of a[] in bytes */
   148825   char *pNextDocid;              /* Pointer to next docid */
   148826 
   148827   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
   148828   int bFreeList;                 /* True if pList should be sqlite3_free()d */
   148829   char *pList;                   /* Pointer to position list following iDocid */
   148830   int nList;                     /* Length of position list */
   148831 };
   148832 
   148833 /*
   148834 ** A "phrase" is a sequence of one or more tokens that must match in
   148835 ** sequence.  A single token is the base case and the most common case.
   148836 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
   148837 ** nToken will be the number of tokens in the string.
   148838 */
   148839 struct Fts3PhraseToken {
   148840   char *z;                        /* Text of the token */
   148841   int n;                          /* Number of bytes in buffer z */
   148842   int isPrefix;                   /* True if token ends with a "*" character */
   148843   int bFirst;                     /* True if token must appear at position 0 */
   148844 
   148845   /* Variables above this point are populated when the expression is
   148846   ** parsed (by code in fts3_expr.c). Below this point the variables are
   148847   ** used when evaluating the expression. */
   148848   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
   148849   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
   148850 };
   148851 
   148852 struct Fts3Phrase {
   148853   /* Cache of doclist for this phrase. */
   148854   Fts3Doclist doclist;
   148855   int bIncr;                 /* True if doclist is loaded incrementally */
   148856   int iDoclistToken;
   148857 
   148858   /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
   148859   ** OR condition.  */
   148860   char *pOrPoslist;
   148861   i64 iOrDocid;
   148862 
   148863   /* Variables below this point are populated by fts3_expr.c when parsing
   148864   ** a MATCH expression. Everything above is part of the evaluation phase.
   148865   */
   148866   int nToken;                /* Number of tokens in the phrase */
   148867   int iColumn;               /* Index of column this phrase must match */
   148868   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
   148869 };
   148870 
   148871 /*
   148872 ** A tree of these objects forms the RHS of a MATCH operator.
   148873 **
   148874 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
   148875 ** points to a malloced buffer, size nDoclist bytes, containing the results
   148876 ** of this phrase query in FTS3 doclist format. As usual, the initial
   148877 ** "Length" field found in doclists stored on disk is omitted from this
   148878 ** buffer.
   148879 **
   148880 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
   148881 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
   148882 ** where nCol is the number of columns in the queried FTS table. The array
   148883 ** is populated as follows:
   148884 **
   148885 **   aMI[iCol*3 + 0] = Undefined
   148886 **   aMI[iCol*3 + 1] = Number of occurrences
   148887 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
   148888 **
   148889 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
   148890 ** when the expression node is.
   148891 */
   148892 struct Fts3Expr {
   148893   int eType;                 /* One of the FTSQUERY_XXX values defined below */
   148894   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
   148895   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
   148896   Fts3Expr *pLeft;           /* Left operand */
   148897   Fts3Expr *pRight;          /* Right operand */
   148898   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
   148899 
   148900   /* The following are used by the fts3_eval.c module. */
   148901   sqlite3_int64 iDocid;      /* Current docid */
   148902   u8 bEof;                   /* True this expression is at EOF already */
   148903   u8 bStart;                 /* True if iDocid is valid */
   148904   u8 bDeferred;              /* True if this expression is entirely deferred */
   148905 
   148906   /* The following are used by the fts3_snippet.c module. */
   148907   int iPhrase;               /* Index of this phrase in matchinfo() results */
   148908   u32 *aMI;                  /* See above */
   148909 };
   148910 
   148911 /*
   148912 ** Candidate values for Fts3Query.eType. Note that the order of the first
   148913 ** four values is in order of precedence when parsing expressions. For
   148914 ** example, the following:
   148915 **
   148916 **   "a OR b AND c NOT d NEAR e"
   148917 **
   148918 ** is equivalent to:
   148919 **
   148920 **   "a OR (b AND (c NOT (d NEAR e)))"
   148921 */
   148922 #define FTSQUERY_NEAR   1
   148923 #define FTSQUERY_NOT    2
   148924 #define FTSQUERY_AND    3
   148925 #define FTSQUERY_OR     4
   148926 #define FTSQUERY_PHRASE 5
   148927 
   148928 
   148929 /* fts3_write.c */
   148930 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
   148931 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
   148932 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
   148933 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
   148934 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
   148935   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
   148936 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   148937   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
   148938 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
   148939 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
   148940 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
   148941 
   148942 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
   148943 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
   148944 
   148945 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   148946 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
   148947 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
   148948 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
   148949 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
   148950 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
   148951 #else
   148952 # define sqlite3Fts3FreeDeferredTokens(x)
   148953 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
   148954 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
   148955 # define sqlite3Fts3FreeDeferredDoclists(x)
   148956 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
   148957 #endif
   148958 
   148959 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
   148960 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
   148961 
   148962 /* Special values interpreted by sqlite3SegReaderCursor() */
   148963 #define FTS3_SEGCURSOR_PENDING        -1
   148964 #define FTS3_SEGCURSOR_ALL            -2
   148965 
   148966 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
   148967 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
   148968 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
   148969 
   148970 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
   148971     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
   148972 
   148973 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
   148974 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
   148975 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
   148976 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
   148977 #define FTS3_SEGMENT_PREFIX        0x00000008
   148978 #define FTS3_SEGMENT_SCAN          0x00000010
   148979 #define FTS3_SEGMENT_FIRST         0x00000020
   148980 
   148981 /* Type passed as 4th argument to SegmentReaderIterate() */
   148982 struct Fts3SegFilter {
   148983   const char *zTerm;
   148984   int nTerm;
   148985   int iCol;
   148986   int flags;
   148987 };
   148988 
   148989 struct Fts3MultiSegReader {
   148990   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
   148991   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
   148992   int nSegment;                   /* Size of apSegment array */
   148993   int nAdvance;                   /* How many seg-readers to advance */
   148994   Fts3SegFilter *pFilter;         /* Pointer to filter object */
   148995   char *aBuffer;                  /* Buffer to merge doclists in */
   148996   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
   148997 
   148998   int iColFilter;                 /* If >=0, filter for this column */
   148999   int bRestart;
   149000 
   149001   /* Used by fts3.c only. */
   149002   int nCost;                      /* Cost of running iterator */
   149003   int bLookup;                    /* True if a lookup of a single entry. */
   149004 
   149005   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
   149006   char *zTerm;                    /* Pointer to term buffer */
   149007   int nTerm;                      /* Size of zTerm in bytes */
   149008   char *aDoclist;                 /* Pointer to doclist buffer */
   149009   int nDoclist;                   /* Size of aDoclist[] in bytes */
   149010 };
   149011 
   149012 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
   149013 
   149014 #define fts3GetVarint32(p, piVal) (                                           \
   149015   (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
   149016 )
   149017 
   149018 /* fts3.c */
   149019 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
   149020 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
   149021 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
   149022 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
   149023 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
   149024 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
   149025 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
   149026 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
   149027 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
   149028 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
   149029 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
   149030 
   149031 /* fts3_tokenizer.c */
   149032 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
   149033 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
   149034 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
   149035     sqlite3_tokenizer **, char **
   149036 );
   149037 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
   149038 
   149039 /* fts3_snippet.c */
   149040 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
   149041 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
   149042   const char *, const char *, int, int
   149043 );
   149044 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
   149045 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
   149046 
   149047 /* fts3_expr.c */
   149048 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
   149049   char **, int, int, int, const char *, int, Fts3Expr **, char **
   149050 );
   149051 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
   149052 #ifdef SQLITE_TEST
   149053 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
   149054 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
   149055 #endif
   149056 
   149057 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
   149058   sqlite3_tokenizer_cursor **
   149059 );
   149060 
   149061 /* fts3_aux.c */
   149062 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
   149063 
   149064 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
   149065 
   149066 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   149067     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
   149068 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   149069     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
   149070 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
   149071 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
   149072 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
   149073 
   149074 /* fts3_tokenize_vtab.c */
   149075 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
   149076 
   149077 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
   149078 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   149079 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
   149080 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
   149081 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
   149082 #endif
   149083 
   149084 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
   149085 #endif /* _FTSINT_H */
   149086 
   149087 /************** End of fts3Int.h *********************************************/
   149088 /************** Continuing where we left off in fts3.c ***********************/
   149089 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   149090 
   149091 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
   149092 # define SQLITE_CORE 1
   149093 #endif
   149094 
   149095 /* #include <assert.h> */
   149096 /* #include <stdlib.h> */
   149097 /* #include <stddef.h> */
   149098 /* #include <stdio.h> */
   149099 /* #include <string.h> */
   149100 /* #include <stdarg.h> */
   149101 
   149102 /* #include "fts3.h" */
   149103 #ifndef SQLITE_CORE
   149104 /* # include "sqlite3ext.h" */
   149105   SQLITE_EXTENSION_INIT1
   149106 #endif
   149107 
   149108 static int fts3EvalNext(Fts3Cursor *pCsr);
   149109 static int fts3EvalStart(Fts3Cursor *pCsr);
   149110 static int fts3TermSegReaderCursor(
   149111     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
   149112 
   149113 #ifndef SQLITE_AMALGAMATION
   149114 # if defined(SQLITE_DEBUG)
   149115 SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
   149116 SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
   149117 # endif
   149118 #endif
   149119 
   149120 /*
   149121 ** Write a 64-bit variable-length integer to memory starting at p[0].
   149122 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
   149123 ** The number of bytes written is returned.
   149124 */
   149125 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   149126   unsigned char *q = (unsigned char *) p;
   149127   sqlite_uint64 vu = v;
   149128   do{
   149129     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
   149130     vu >>= 7;
   149131   }while( vu!=0 );
   149132   q[-1] &= 0x7f;  /* turn off high bit in final byte */
   149133   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
   149134   return (int) (q - (unsigned char *)p);
   149135 }
   149136 
   149137 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
   149138   v = (v & mask1) | ( (*ptr++) << shift );                    \
   149139   if( (v & mask2)==0 ){ var = v; return ret; }
   149140 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
   149141   v = (*ptr++);                                               \
   149142   if( (v & mask2)==0 ){ var = v; return ret; }
   149143 
   149144 /*
   149145 ** Read a 64-bit variable-length integer from memory starting at p[0].
   149146 ** Return the number of bytes read, or 0 on error.
   149147 ** The value is stored in *v.
   149148 */
   149149 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
   149150   const unsigned char *p = (const unsigned char*)pBuf;
   149151   const unsigned char *pStart = p;
   149152   u32 a;
   149153   u64 b;
   149154   int shift;
   149155 
   149156   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
   149157   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
   149158   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
   149159   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
   149160   b = (a & 0x0FFFFFFF );
   149161 
   149162   for(shift=28; shift<=63; shift+=7){
   149163     u64 c = *p++;
   149164     b += (c&0x7F) << shift;
   149165     if( (c & 0x80)==0 ) break;
   149166   }
   149167   *v = b;
   149168   return (int)(p - pStart);
   149169 }
   149170 
   149171 /*
   149172 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
   149173 ** a non-negative 32-bit integer before it is returned.
   149174 */
   149175 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
   149176   u32 a;
   149177 
   149178 #ifndef fts3GetVarint32
   149179   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
   149180 #else
   149181   a = (*p++);
   149182   assert( a & 0x80 );
   149183 #endif
   149184 
   149185   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
   149186   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
   149187   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
   149188   a = (a & 0x0FFFFFFF );
   149189   *pi = (int)(a | ((u32)(*p & 0x07) << 28));
   149190   assert( 0==(a & 0x80000000) );
   149191   assert( *pi>=0 );
   149192   return 5;
   149193 }
   149194 
   149195 /*
   149196 ** Return the number of bytes required to encode v as a varint
   149197 */
   149198 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
   149199   int i = 0;
   149200   do{
   149201     i++;
   149202     v >>= 7;
   149203   }while( v!=0 );
   149204   return i;
   149205 }
   149206 
   149207 /*
   149208 ** Convert an SQL-style quoted string into a normal string by removing
   149209 ** the quote characters.  The conversion is done in-place.  If the
   149210 ** input does not begin with a quote character, then this routine
   149211 ** is a no-op.
   149212 **
   149213 ** Examples:
   149214 **
   149215 **     "abc"   becomes   abc
   149216 **     'xyz'   becomes   xyz
   149217 **     [pqr]   becomes   pqr
   149218 **     `mno`   becomes   mno
   149219 **
   149220 */
   149221 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
   149222   char quote;                     /* Quote character (if any ) */
   149223 
   149224   quote = z[0];
   149225   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   149226     int iIn = 1;                  /* Index of next byte to read from input */
   149227     int iOut = 0;                 /* Index of next byte to write to output */
   149228 
   149229     /* If the first byte was a '[', then the close-quote character is a ']' */
   149230     if( quote=='[' ) quote = ']';
   149231 
   149232     while( z[iIn] ){
   149233       if( z[iIn]==quote ){
   149234         if( z[iIn+1]!=quote ) break;
   149235         z[iOut++] = quote;
   149236         iIn += 2;
   149237       }else{
   149238         z[iOut++] = z[iIn++];
   149239       }
   149240     }
   149241     z[iOut] = '\0';
   149242   }
   149243 }
   149244 
   149245 /*
   149246 ** Read a single varint from the doclist at *pp and advance *pp to point
   149247 ** to the first byte past the end of the varint.  Add the value of the varint
   149248 ** to *pVal.
   149249 */
   149250 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
   149251   sqlite3_int64 iVal;
   149252   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   149253   *pVal += iVal;
   149254 }
   149255 
   149256 /*
   149257 ** When this function is called, *pp points to the first byte following a
   149258 ** varint that is part of a doclist (or position-list, or any other list
   149259 ** of varints). This function moves *pp to point to the start of that varint,
   149260 ** and sets *pVal by the varint value.
   149261 **
   149262 ** Argument pStart points to the first byte of the doclist that the
   149263 ** varint is part of.
   149264 */
   149265 static void fts3GetReverseVarint(
   149266   char **pp,
   149267   char *pStart,
   149268   sqlite3_int64 *pVal
   149269 ){
   149270   sqlite3_int64 iVal;
   149271   char *p;
   149272 
   149273   /* Pointer p now points at the first byte past the varint we are
   149274   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
   149275   ** clear on character p[-1]. */
   149276   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
   149277   p++;
   149278   *pp = p;
   149279 
   149280   sqlite3Fts3GetVarint(p, &iVal);
   149281   *pVal = iVal;
   149282 }
   149283 
   149284 /*
   149285 ** The xDisconnect() virtual table method.
   149286 */
   149287 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
   149288   Fts3Table *p = (Fts3Table *)pVtab;
   149289   int i;
   149290 
   149291   assert( p->nPendingData==0 );
   149292   assert( p->pSegments==0 );
   149293 
   149294   /* Free any prepared statements held */
   149295   sqlite3_finalize(p->pSeekStmt);
   149296   for(i=0; i<SizeofArray(p->aStmt); i++){
   149297     sqlite3_finalize(p->aStmt[i]);
   149298   }
   149299   sqlite3_free(p->zSegmentsTbl);
   149300   sqlite3_free(p->zReadExprlist);
   149301   sqlite3_free(p->zWriteExprlist);
   149302   sqlite3_free(p->zContentTbl);
   149303   sqlite3_free(p->zLanguageid);
   149304 
   149305   /* Invoke the tokenizer destructor to free the tokenizer. */
   149306   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
   149307 
   149308   sqlite3_free(p);
   149309   return SQLITE_OK;
   149310 }
   149311 
   149312 /*
   149313 ** Write an error message into *pzErr
   149314 */
   149315 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
   149316   va_list ap;
   149317   sqlite3_free(*pzErr);
   149318   va_start(ap, zFormat);
   149319   *pzErr = sqlite3_vmprintf(zFormat, ap);
   149320   va_end(ap);
   149321 }
   149322 
   149323 /*
   149324 ** Construct one or more SQL statements from the format string given
   149325 ** and then evaluate those statements. The success code is written
   149326 ** into *pRc.
   149327 **
   149328 ** If *pRc is initially non-zero then this routine is a no-op.
   149329 */
   149330 static void fts3DbExec(
   149331   int *pRc,              /* Success code */
   149332   sqlite3 *db,           /* Database in which to run SQL */
   149333   const char *zFormat,   /* Format string for SQL */
   149334   ...                    /* Arguments to the format string */
   149335 ){
   149336   va_list ap;
   149337   char *zSql;
   149338   if( *pRc ) return;
   149339   va_start(ap, zFormat);
   149340   zSql = sqlite3_vmprintf(zFormat, ap);
   149341   va_end(ap);
   149342   if( zSql==0 ){
   149343     *pRc = SQLITE_NOMEM;
   149344   }else{
   149345     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
   149346     sqlite3_free(zSql);
   149347   }
   149348 }
   149349 
   149350 /*
   149351 ** The xDestroy() virtual table method.
   149352 */
   149353 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   149354   Fts3Table *p = (Fts3Table *)pVtab;
   149355   int rc = SQLITE_OK;              /* Return code */
   149356   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
   149357   sqlite3 *db = p->db;             /* Database handle */
   149358 
   149359   /* Drop the shadow tables */
   149360   if( p->zContentTbl==0 ){
   149361     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
   149362   }
   149363   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
   149364   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
   149365   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
   149366   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
   149367 
   149368   /* If everything has worked, invoke fts3DisconnectMethod() to free the
   149369   ** memory associated with the Fts3Table structure and return SQLITE_OK.
   149370   ** Otherwise, return an SQLite error code.
   149371   */
   149372   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
   149373 }
   149374 
   149375 
   149376 /*
   149377 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
   149378 ** passed as the first argument. This is done as part of the xConnect()
   149379 ** and xCreate() methods.
   149380 **
   149381 ** If *pRc is non-zero when this function is called, it is a no-op.
   149382 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   149383 ** before returning.
   149384 */
   149385 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
   149386   if( *pRc==SQLITE_OK ){
   149387     int i;                        /* Iterator variable */
   149388     int rc;                       /* Return code */
   149389     char *zSql;                   /* SQL statement passed to declare_vtab() */
   149390     char *zCols;                  /* List of user defined columns */
   149391     const char *zLanguageid;
   149392 
   149393     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
   149394     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   149395 
   149396     /* Create a list of user columns for the virtual table */
   149397     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
   149398     for(i=1; zCols && i<p->nColumn; i++){
   149399       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
   149400     }
   149401 
   149402     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
   149403     zSql = sqlite3_mprintf(
   149404         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
   149405         zCols, p->zName, zLanguageid
   149406     );
   149407     if( !zCols || !zSql ){
   149408       rc = SQLITE_NOMEM;
   149409     }else{
   149410       rc = sqlite3_declare_vtab(p->db, zSql);
   149411     }
   149412 
   149413     sqlite3_free(zSql);
   149414     sqlite3_free(zCols);
   149415     *pRc = rc;
   149416   }
   149417 }
   149418 
   149419 /*
   149420 ** Create the %_stat table if it does not already exist.
   149421 */
   149422 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
   149423   fts3DbExec(pRc, p->db,
   149424       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
   149425           "(id INTEGER PRIMARY KEY, value BLOB);",
   149426       p->zDb, p->zName
   149427   );
   149428   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
   149429 }
   149430 
   149431 /*
   149432 ** Create the backing store tables (%_content, %_segments and %_segdir)
   149433 ** required by the FTS3 table passed as the only argument. This is done
   149434 ** as part of the vtab xCreate() method.
   149435 **
   149436 ** If the p->bHasDocsize boolean is true (indicating that this is an
   149437 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
   149438 ** %_stat tables required by FTS4.
   149439 */
   149440 static int fts3CreateTables(Fts3Table *p){
   149441   int rc = SQLITE_OK;             /* Return code */
   149442   int i;                          /* Iterator variable */
   149443   sqlite3 *db = p->db;            /* The database connection */
   149444 
   149445   if( p->zContentTbl==0 ){
   149446     const char *zLanguageid = p->zLanguageid;
   149447     char *zContentCols;           /* Columns of %_content table */
   149448 
   149449     /* Create a list of user columns for the content table */
   149450     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
   149451     for(i=0; zContentCols && i<p->nColumn; i++){
   149452       char *z = p->azColumn[i];
   149453       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
   149454     }
   149455     if( zLanguageid && zContentCols ){
   149456       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
   149457     }
   149458     if( zContentCols==0 ) rc = SQLITE_NOMEM;
   149459 
   149460     /* Create the content table */
   149461     fts3DbExec(&rc, db,
   149462        "CREATE TABLE %Q.'%q_content'(%s)",
   149463        p->zDb, p->zName, zContentCols
   149464     );
   149465     sqlite3_free(zContentCols);
   149466   }
   149467 
   149468   /* Create other tables */
   149469   fts3DbExec(&rc, db,
   149470       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
   149471       p->zDb, p->zName
   149472   );
   149473   fts3DbExec(&rc, db,
   149474       "CREATE TABLE %Q.'%q_segdir'("
   149475         "level INTEGER,"
   149476         "idx INTEGER,"
   149477         "start_block INTEGER,"
   149478         "leaves_end_block INTEGER,"
   149479         "end_block INTEGER,"
   149480         "root BLOB,"
   149481         "PRIMARY KEY(level, idx)"
   149482       ");",
   149483       p->zDb, p->zName
   149484   );
   149485   if( p->bHasDocsize ){
   149486     fts3DbExec(&rc, db,
   149487         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
   149488         p->zDb, p->zName
   149489     );
   149490   }
   149491   assert( p->bHasStat==p->bFts4 );
   149492   if( p->bHasStat ){
   149493     sqlite3Fts3CreateStatTable(&rc, p);
   149494   }
   149495   return rc;
   149496 }
   149497 
   149498 /*
   149499 ** Store the current database page-size in bytes in p->nPgsz.
   149500 **
   149501 ** If *pRc is non-zero when this function is called, it is a no-op.
   149502 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   149503 ** before returning.
   149504 */
   149505 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
   149506   if( *pRc==SQLITE_OK ){
   149507     int rc;                       /* Return code */
   149508     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
   149509     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
   149510 
   149511     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
   149512     if( !zSql ){
   149513       rc = SQLITE_NOMEM;
   149514     }else{
   149515       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
   149516       if( rc==SQLITE_OK ){
   149517         sqlite3_step(pStmt);
   149518         p->nPgsz = sqlite3_column_int(pStmt, 0);
   149519         rc = sqlite3_finalize(pStmt);
   149520       }else if( rc==SQLITE_AUTH ){
   149521         p->nPgsz = 1024;
   149522         rc = SQLITE_OK;
   149523       }
   149524     }
   149525     assert( p->nPgsz>0 || rc!=SQLITE_OK );
   149526     sqlite3_free(zSql);
   149527     *pRc = rc;
   149528   }
   149529 }
   149530 
   149531 /*
   149532 ** "Special" FTS4 arguments are column specifications of the following form:
   149533 **
   149534 **   <key> = <value>
   149535 **
   149536 ** There may not be whitespace surrounding the "=" character. The <value>
   149537 ** term may be quoted, but the <key> may not.
   149538 */
   149539 static int fts3IsSpecialColumn(
   149540   const char *z,
   149541   int *pnKey,
   149542   char **pzValue
   149543 ){
   149544   char *zValue;
   149545   const char *zCsr = z;
   149546 
   149547   while( *zCsr!='=' ){
   149548     if( *zCsr=='\0' ) return 0;
   149549     zCsr++;
   149550   }
   149551 
   149552   *pnKey = (int)(zCsr-z);
   149553   zValue = sqlite3_mprintf("%s", &zCsr[1]);
   149554   if( zValue ){
   149555     sqlite3Fts3Dequote(zValue);
   149556   }
   149557   *pzValue = zValue;
   149558   return 1;
   149559 }
   149560 
   149561 /*
   149562 ** Append the output of a printf() style formatting to an existing string.
   149563 */
   149564 static void fts3Appendf(
   149565   int *pRc,                       /* IN/OUT: Error code */
   149566   char **pz,                      /* IN/OUT: Pointer to string buffer */
   149567   const char *zFormat,            /* Printf format string to append */
   149568   ...                             /* Arguments for printf format string */
   149569 ){
   149570   if( *pRc==SQLITE_OK ){
   149571     va_list ap;
   149572     char *z;
   149573     va_start(ap, zFormat);
   149574     z = sqlite3_vmprintf(zFormat, ap);
   149575     va_end(ap);
   149576     if( z && *pz ){
   149577       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
   149578       sqlite3_free(z);
   149579       z = z2;
   149580     }
   149581     if( z==0 ) *pRc = SQLITE_NOMEM;
   149582     sqlite3_free(*pz);
   149583     *pz = z;
   149584   }
   149585 }
   149586 
   149587 /*
   149588 ** Return a copy of input string zInput enclosed in double-quotes (") and
   149589 ** with all double quote characters escaped. For example:
   149590 **
   149591 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
   149592 **
   149593 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
   149594 ** is the callers responsibility to call sqlite3_free() to release this
   149595 ** memory.
   149596 */
   149597 static char *fts3QuoteId(char const *zInput){
   149598   int nRet;
   149599   char *zRet;
   149600   nRet = 2 + (int)strlen(zInput)*2 + 1;
   149601   zRet = sqlite3_malloc(nRet);
   149602   if( zRet ){
   149603     int i;
   149604     char *z = zRet;
   149605     *(z++) = '"';
   149606     for(i=0; zInput[i]; i++){
   149607       if( zInput[i]=='"' ) *(z++) = '"';
   149608       *(z++) = zInput[i];
   149609     }
   149610     *(z++) = '"';
   149611     *(z++) = '\0';
   149612   }
   149613   return zRet;
   149614 }
   149615 
   149616 /*
   149617 ** Return a list of comma separated SQL expressions and a FROM clause that
   149618 ** could be used in a SELECT statement such as the following:
   149619 **
   149620 **     SELECT <list of expressions> FROM %_content AS x ...
   149621 **
   149622 ** to return the docid, followed by each column of text data in order
   149623 ** from left to write. If parameter zFunc is not NULL, then instead of
   149624 ** being returned directly each column of text data is passed to an SQL
   149625 ** function named zFunc first. For example, if zFunc is "unzip" and the
   149626 ** table has the three user-defined columns "a", "b", and "c", the following
   149627 ** string is returned:
   149628 **
   149629 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
   149630 **
   149631 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   149632 ** is the responsibility of the caller to eventually free it.
   149633 **
   149634 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   149635 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   149636 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   149637 ** no error occurs, *pRc is left unmodified.
   149638 */
   149639 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
   149640   char *zRet = 0;
   149641   char *zFree = 0;
   149642   char *zFunction;
   149643   int i;
   149644 
   149645   if( p->zContentTbl==0 ){
   149646     if( !zFunc ){
   149647       zFunction = "";
   149648     }else{
   149649       zFree = zFunction = fts3QuoteId(zFunc);
   149650     }
   149651     fts3Appendf(pRc, &zRet, "docid");
   149652     for(i=0; i<p->nColumn; i++){
   149653       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
   149654     }
   149655     if( p->zLanguageid ){
   149656       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
   149657     }
   149658     sqlite3_free(zFree);
   149659   }else{
   149660     fts3Appendf(pRc, &zRet, "rowid");
   149661     for(i=0; i<p->nColumn; i++){
   149662       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
   149663     }
   149664     if( p->zLanguageid ){
   149665       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
   149666     }
   149667   }
   149668   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
   149669       p->zDb,
   149670       (p->zContentTbl ? p->zContentTbl : p->zName),
   149671       (p->zContentTbl ? "" : "_content")
   149672   );
   149673   return zRet;
   149674 }
   149675 
   149676 /*
   149677 ** Return a list of N comma separated question marks, where N is the number
   149678 ** of columns in the %_content table (one for the docid plus one for each
   149679 ** user-defined text column).
   149680 **
   149681 ** If argument zFunc is not NULL, then all but the first question mark
   149682 ** is preceded by zFunc and an open bracket, and followed by a closed
   149683 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
   149684 ** user-defined text columns, the following string is returned:
   149685 **
   149686 **     "?, zip(?), zip(?), zip(?)"
   149687 **
   149688 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   149689 ** is the responsibility of the caller to eventually free it.
   149690 **
   149691 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   149692 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   149693 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   149694 ** no error occurs, *pRc is left unmodified.
   149695 */
   149696 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
   149697   char *zRet = 0;
   149698   char *zFree = 0;
   149699   char *zFunction;
   149700   int i;
   149701 
   149702   if( !zFunc ){
   149703     zFunction = "";
   149704   }else{
   149705     zFree = zFunction = fts3QuoteId(zFunc);
   149706   }
   149707   fts3Appendf(pRc, &zRet, "?");
   149708   for(i=0; i<p->nColumn; i++){
   149709     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
   149710   }
   149711   if( p->zLanguageid ){
   149712     fts3Appendf(pRc, &zRet, ", ?");
   149713   }
   149714   sqlite3_free(zFree);
   149715   return zRet;
   149716 }
   149717 
   149718 /*
   149719 ** This function interprets the string at (*pp) as a non-negative integer
   149720 ** value. It reads the integer and sets *pnOut to the value read, then
   149721 ** sets *pp to point to the byte immediately following the last byte of
   149722 ** the integer value.
   149723 **
   149724 ** Only decimal digits ('0'..'9') may be part of an integer value.
   149725 **
   149726 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
   149727 ** the output value undefined. Otherwise SQLITE_OK is returned.
   149728 **
   149729 ** This function is used when parsing the "prefix=" FTS4 parameter.
   149730 */
   149731 static int fts3GobbleInt(const char **pp, int *pnOut){
   149732   const int MAX_NPREFIX = 10000000;
   149733   const char *p;                  /* Iterator pointer */
   149734   int nInt = 0;                   /* Output value */
   149735 
   149736   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
   149737     nInt = nInt * 10 + (p[0] - '0');
   149738     if( nInt>MAX_NPREFIX ){
   149739       nInt = 0;
   149740       break;
   149741     }
   149742   }
   149743   if( p==*pp ) return SQLITE_ERROR;
   149744   *pnOut = nInt;
   149745   *pp = p;
   149746   return SQLITE_OK;
   149747 }
   149748 
   149749 /*
   149750 ** This function is called to allocate an array of Fts3Index structures
   149751 ** representing the indexes maintained by the current FTS table. FTS tables
   149752 ** always maintain the main "terms" index, but may also maintain one or
   149753 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
   149754 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
   149755 **
   149756 ** Argument zParam is passed the value of the "prefix=" option if one was
   149757 ** specified, or NULL otherwise.
   149758 **
   149759 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
   149760 ** the allocated array. *pnIndex is set to the number of elements in the
   149761 ** array. If an error does occur, an SQLite error code is returned.
   149762 **
   149763 ** Regardless of whether or not an error is returned, it is the responsibility
   149764 ** of the caller to call sqlite3_free() on the output array to free it.
   149765 */
   149766 static int fts3PrefixParameter(
   149767   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
   149768   int *pnIndex,                   /* OUT: size of *apIndex[] array */
   149769   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
   149770 ){
   149771   struct Fts3Index *aIndex;       /* Allocated array */
   149772   int nIndex = 1;                 /* Number of entries in array */
   149773 
   149774   if( zParam && zParam[0] ){
   149775     const char *p;
   149776     nIndex++;
   149777     for(p=zParam; *p; p++){
   149778       if( *p==',' ) nIndex++;
   149779     }
   149780   }
   149781 
   149782   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
   149783   *apIndex = aIndex;
   149784   if( !aIndex ){
   149785     return SQLITE_NOMEM;
   149786   }
   149787 
   149788   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
   149789   if( zParam ){
   149790     const char *p = zParam;
   149791     int i;
   149792     for(i=1; i<nIndex; i++){
   149793       int nPrefix = 0;
   149794       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
   149795       assert( nPrefix>=0 );
   149796       if( nPrefix==0 ){
   149797         nIndex--;
   149798         i--;
   149799       }else{
   149800         aIndex[i].nPrefix = nPrefix;
   149801       }
   149802       p++;
   149803     }
   149804   }
   149805 
   149806   *pnIndex = nIndex;
   149807   return SQLITE_OK;
   149808 }
   149809 
   149810 /*
   149811 ** This function is called when initializing an FTS4 table that uses the
   149812 ** content=xxx option. It determines the number of and names of the columns
   149813 ** of the new FTS4 table.
   149814 **
   149815 ** The third argument passed to this function is the value passed to the
   149816 ** config=xxx option (i.e. "xxx"). This function queries the database for
   149817 ** a table of that name. If found, the output variables are populated
   149818 ** as follows:
   149819 **
   149820 **   *pnCol:   Set to the number of columns table xxx has,
   149821 **
   149822 **   *pnStr:   Set to the total amount of space required to store a copy
   149823 **             of each columns name, including the nul-terminator.
   149824 **
   149825 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
   149826 **             the name of the corresponding column in table xxx. The array
   149827 **             and its contents are allocated using a single allocation. It
   149828 **             is the responsibility of the caller to free this allocation
   149829 **             by eventually passing the *pazCol value to sqlite3_free().
   149830 **
   149831 ** If the table cannot be found, an error code is returned and the output
   149832 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
   149833 ** returned (and the output variables are undefined).
   149834 */
   149835 static int fts3ContentColumns(
   149836   sqlite3 *db,                    /* Database handle */
   149837   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
   149838   const char *zTbl,               /* Name of content table */
   149839   const char ***pazCol,           /* OUT: Malloc'd array of column names */
   149840   int *pnCol,                     /* OUT: Size of array *pazCol */
   149841   int *pnStr,                     /* OUT: Bytes of string content */
   149842   char **pzErr                    /* OUT: error message */
   149843 ){
   149844   int rc = SQLITE_OK;             /* Return code */
   149845   char *zSql;                     /* "SELECT *" statement on zTbl */
   149846   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
   149847 
   149848   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
   149849   if( !zSql ){
   149850     rc = SQLITE_NOMEM;
   149851   }else{
   149852     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   149853     if( rc!=SQLITE_OK ){
   149854       sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
   149855     }
   149856   }
   149857   sqlite3_free(zSql);
   149858 
   149859   if( rc==SQLITE_OK ){
   149860     const char **azCol;           /* Output array */
   149861     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
   149862     int nCol;                     /* Number of table columns */
   149863     int i;                        /* Used to iterate through columns */
   149864 
   149865     /* Loop through the returned columns. Set nStr to the number of bytes of
   149866     ** space required to store a copy of each column name, including the
   149867     ** nul-terminator byte.  */
   149868     nCol = sqlite3_column_count(pStmt);
   149869     for(i=0; i<nCol; i++){
   149870       const char *zCol = sqlite3_column_name(pStmt, i);
   149871       nStr += (int)strlen(zCol) + 1;
   149872     }
   149873 
   149874     /* Allocate and populate the array to return. */
   149875     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
   149876     if( azCol==0 ){
   149877       rc = SQLITE_NOMEM;
   149878     }else{
   149879       char *p = (char *)&azCol[nCol];
   149880       for(i=0; i<nCol; i++){
   149881         const char *zCol = sqlite3_column_name(pStmt, i);
   149882         int n = (int)strlen(zCol)+1;
   149883         memcpy(p, zCol, n);
   149884         azCol[i] = p;
   149885         p += n;
   149886       }
   149887     }
   149888     sqlite3_finalize(pStmt);
   149889 
   149890     /* Set the output variables. */
   149891     *pnCol = nCol;
   149892     *pnStr = nStr;
   149893     *pazCol = azCol;
   149894   }
   149895 
   149896   return rc;
   149897 }
   149898 
   149899 /*
   149900 ** This function is the implementation of both the xConnect and xCreate
   149901 ** methods of the FTS3 virtual table.
   149902 **
   149903 ** The argv[] array contains the following:
   149904 **
   149905 **   argv[0]   -> module name  ("fts3" or "fts4")
   149906 **   argv[1]   -> database name
   149907 **   argv[2]   -> table name
   149908 **   argv[...] -> "column name" and other module argument fields.
   149909 */
   149910 static int fts3InitVtab(
   149911   int isCreate,                   /* True for xCreate, false for xConnect */
   149912   sqlite3 *db,                    /* The SQLite database connection */
   149913   void *pAux,                     /* Hash table containing tokenizers */
   149914   int argc,                       /* Number of elements in argv array */
   149915   const char * const *argv,       /* xCreate/xConnect argument array */
   149916   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   149917   char **pzErr                    /* Write any error message here */
   149918 ){
   149919   Fts3Hash *pHash = (Fts3Hash *)pAux;
   149920   Fts3Table *p = 0;               /* Pointer to allocated vtab */
   149921   int rc = SQLITE_OK;             /* Return code */
   149922   int i;                          /* Iterator variable */
   149923   int nByte;                      /* Size of allocation used for *p */
   149924   int iCol;                       /* Column index */
   149925   int nString = 0;                /* Bytes required to hold all column names */
   149926   int nCol = 0;                   /* Number of columns in the FTS table */
   149927   char *zCsr;                     /* Space for holding column names */
   149928   int nDb;                        /* Bytes required to hold database name */
   149929   int nName;                      /* Bytes required to hold table name */
   149930   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
   149931   const char **aCol;              /* Array of column names */
   149932   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
   149933 
   149934   int nIndex = 0;                 /* Size of aIndex[] array */
   149935   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
   149936 
   149937   /* The results of parsing supported FTS4 key=value options: */
   149938   int bNoDocsize = 0;             /* True to omit %_docsize table */
   149939   int bDescIdx = 0;               /* True to store descending indexes */
   149940   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
   149941   char *zCompress = 0;            /* compress=? parameter (or NULL) */
   149942   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
   149943   char *zContent = 0;             /* content=? parameter (or NULL) */
   149944   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
   149945   char **azNotindexed = 0;        /* The set of notindexed= columns */
   149946   int nNotindexed = 0;            /* Size of azNotindexed[] array */
   149947 
   149948   assert( strlen(argv[0])==4 );
   149949   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
   149950        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
   149951   );
   149952 
   149953   nDb = (int)strlen(argv[1]) + 1;
   149954   nName = (int)strlen(argv[2]) + 1;
   149955 
   149956   nByte = sizeof(const char *) * (argc-2);
   149957   aCol = (const char **)sqlite3_malloc(nByte);
   149958   if( aCol ){
   149959     memset((void*)aCol, 0, nByte);
   149960     azNotindexed = (char **)sqlite3_malloc(nByte);
   149961   }
   149962   if( azNotindexed ){
   149963     memset(azNotindexed, 0, nByte);
   149964   }
   149965   if( !aCol || !azNotindexed ){
   149966     rc = SQLITE_NOMEM;
   149967     goto fts3_init_out;
   149968   }
   149969 
   149970   /* Loop through all of the arguments passed by the user to the FTS3/4
   149971   ** module (i.e. all the column names and special arguments). This loop
   149972   ** does the following:
   149973   **
   149974   **   + Figures out the number of columns the FTSX table will have, and
   149975   **     the number of bytes of space that must be allocated to store copies
   149976   **     of the column names.
   149977   **
   149978   **   + If there is a tokenizer specification included in the arguments,
   149979   **     initializes the tokenizer pTokenizer.
   149980   */
   149981   for(i=3; rc==SQLITE_OK && i<argc; i++){
   149982     char const *z = argv[i];
   149983     int nKey;
   149984     char *zVal;
   149985 
   149986     /* Check if this is a tokenizer specification */
   149987     if( !pTokenizer
   149988      && strlen(z)>8
   149989      && 0==sqlite3_strnicmp(z, "tokenize", 8)
   149990      && 0==sqlite3Fts3IsIdChar(z[8])
   149991     ){
   149992       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
   149993     }
   149994 
   149995     /* Check if it is an FTS4 special argument. */
   149996     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
   149997       struct Fts4Option {
   149998         const char *zOpt;
   149999         int nOpt;
   150000       } aFts4Opt[] = {
   150001         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
   150002         { "prefix",      6 },     /* 1 -> PREFIX */
   150003         { "compress",    8 },     /* 2 -> COMPRESS */
   150004         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
   150005         { "order",       5 },     /* 4 -> ORDER */
   150006         { "content",     7 },     /* 5 -> CONTENT */
   150007         { "languageid", 10 },     /* 6 -> LANGUAGEID */
   150008         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
   150009       };
   150010 
   150011       int iOpt;
   150012       if( !zVal ){
   150013         rc = SQLITE_NOMEM;
   150014       }else{
   150015         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
   150016           struct Fts4Option *pOp = &aFts4Opt[iOpt];
   150017           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
   150018             break;
   150019           }
   150020         }
   150021         switch( iOpt ){
   150022           case 0:               /* MATCHINFO */
   150023             if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
   150024               sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
   150025               rc = SQLITE_ERROR;
   150026             }
   150027             bNoDocsize = 1;
   150028             break;
   150029 
   150030           case 1:               /* PREFIX */
   150031             sqlite3_free(zPrefix);
   150032             zPrefix = zVal;
   150033             zVal = 0;
   150034             break;
   150035 
   150036           case 2:               /* COMPRESS */
   150037             sqlite3_free(zCompress);
   150038             zCompress = zVal;
   150039             zVal = 0;
   150040             break;
   150041 
   150042           case 3:               /* UNCOMPRESS */
   150043             sqlite3_free(zUncompress);
   150044             zUncompress = zVal;
   150045             zVal = 0;
   150046             break;
   150047 
   150048           case 4:               /* ORDER */
   150049             if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
   150050              && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
   150051             ){
   150052               sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
   150053               rc = SQLITE_ERROR;
   150054             }
   150055             bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
   150056             break;
   150057 
   150058           case 5:              /* CONTENT */
   150059             sqlite3_free(zContent);
   150060             zContent = zVal;
   150061             zVal = 0;
   150062             break;
   150063 
   150064           case 6:              /* LANGUAGEID */
   150065             assert( iOpt==6 );
   150066             sqlite3_free(zLanguageid);
   150067             zLanguageid = zVal;
   150068             zVal = 0;
   150069             break;
   150070 
   150071           case 7:              /* NOTINDEXED */
   150072             azNotindexed[nNotindexed++] = zVal;
   150073             zVal = 0;
   150074             break;
   150075 
   150076           default:
   150077             assert( iOpt==SizeofArray(aFts4Opt) );
   150078             sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
   150079             rc = SQLITE_ERROR;
   150080             break;
   150081         }
   150082         sqlite3_free(zVal);
   150083       }
   150084     }
   150085 
   150086     /* Otherwise, the argument is a column name. */
   150087     else {
   150088       nString += (int)(strlen(z) + 1);
   150089       aCol[nCol++] = z;
   150090     }
   150091   }
   150092 
   150093   /* If a content=xxx option was specified, the following:
   150094   **
   150095   **   1. Ignore any compress= and uncompress= options.
   150096   **
   150097   **   2. If no column names were specified as part of the CREATE VIRTUAL
   150098   **      TABLE statement, use all columns from the content table.
   150099   */
   150100   if( rc==SQLITE_OK && zContent ){
   150101     sqlite3_free(zCompress);
   150102     sqlite3_free(zUncompress);
   150103     zCompress = 0;
   150104     zUncompress = 0;
   150105     if( nCol==0 ){
   150106       sqlite3_free((void*)aCol);
   150107       aCol = 0;
   150108       rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
   150109 
   150110       /* If a languageid= option was specified, remove the language id
   150111       ** column from the aCol[] array. */
   150112       if( rc==SQLITE_OK && zLanguageid ){
   150113         int j;
   150114         for(j=0; j<nCol; j++){
   150115           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
   150116             int k;
   150117             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
   150118             nCol--;
   150119             break;
   150120           }
   150121         }
   150122       }
   150123     }
   150124   }
   150125   if( rc!=SQLITE_OK ) goto fts3_init_out;
   150126 
   150127   if( nCol==0 ){
   150128     assert( nString==0 );
   150129     aCol[0] = "content";
   150130     nString = 8;
   150131     nCol = 1;
   150132   }
   150133 
   150134   if( pTokenizer==0 ){
   150135     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
   150136     if( rc!=SQLITE_OK ) goto fts3_init_out;
   150137   }
   150138   assert( pTokenizer );
   150139 
   150140   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
   150141   if( rc==SQLITE_ERROR ){
   150142     assert( zPrefix );
   150143     sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
   150144   }
   150145   if( rc!=SQLITE_OK ) goto fts3_init_out;
   150146 
   150147   /* Allocate and populate the Fts3Table structure. */
   150148   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
   150149           nCol * sizeof(char *) +              /* azColumn */
   150150           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
   150151           nCol * sizeof(u8) +                  /* abNotindexed */
   150152           nName +                              /* zName */
   150153           nDb +                                /* zDb */
   150154           nString;                             /* Space for azColumn strings */
   150155   p = (Fts3Table*)sqlite3_malloc(nByte);
   150156   if( p==0 ){
   150157     rc = SQLITE_NOMEM;
   150158     goto fts3_init_out;
   150159   }
   150160   memset(p, 0, nByte);
   150161   p->db = db;
   150162   p->nColumn = nCol;
   150163   p->nPendingData = 0;
   150164   p->azColumn = (char **)&p[1];
   150165   p->pTokenizer = pTokenizer;
   150166   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
   150167   p->bHasDocsize = (isFts4 && bNoDocsize==0);
   150168   p->bHasStat = (u8)isFts4;
   150169   p->bFts4 = (u8)isFts4;
   150170   p->bDescIdx = (u8)bDescIdx;
   150171   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
   150172   p->zContentTbl = zContent;
   150173   p->zLanguageid = zLanguageid;
   150174   zContent = 0;
   150175   zLanguageid = 0;
   150176   TESTONLY( p->inTransaction = -1 );
   150177   TESTONLY( p->mxSavepoint = -1 );
   150178 
   150179   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
   150180   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
   150181   p->nIndex = nIndex;
   150182   for(i=0; i<nIndex; i++){
   150183     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
   150184   }
   150185   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
   150186 
   150187   /* Fill in the zName and zDb fields of the vtab structure. */
   150188   zCsr = (char *)&p->abNotindexed[nCol];
   150189   p->zName = zCsr;
   150190   memcpy(zCsr, argv[2], nName);
   150191   zCsr += nName;
   150192   p->zDb = zCsr;
   150193   memcpy(zCsr, argv[1], nDb);
   150194   zCsr += nDb;
   150195 
   150196   /* Fill in the azColumn array */
   150197   for(iCol=0; iCol<nCol; iCol++){
   150198     char *z;
   150199     int n = 0;
   150200     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
   150201     if( n>0 ){
   150202       memcpy(zCsr, z, n);
   150203     }
   150204     zCsr[n] = '\0';
   150205     sqlite3Fts3Dequote(zCsr);
   150206     p->azColumn[iCol] = zCsr;
   150207     zCsr += n+1;
   150208     assert( zCsr <= &((char *)p)[nByte] );
   150209   }
   150210 
   150211   /* Fill in the abNotindexed array */
   150212   for(iCol=0; iCol<nCol; iCol++){
   150213     int n = (int)strlen(p->azColumn[iCol]);
   150214     for(i=0; i<nNotindexed; i++){
   150215       char *zNot = azNotindexed[i];
   150216       if( zNot && n==(int)strlen(zNot)
   150217        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
   150218       ){
   150219         p->abNotindexed[iCol] = 1;
   150220         sqlite3_free(zNot);
   150221         azNotindexed[i] = 0;
   150222       }
   150223     }
   150224   }
   150225   for(i=0; i<nNotindexed; i++){
   150226     if( azNotindexed[i] ){
   150227       sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
   150228       rc = SQLITE_ERROR;
   150229     }
   150230   }
   150231 
   150232   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
   150233     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
   150234     rc = SQLITE_ERROR;
   150235     sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
   150236   }
   150237   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
   150238   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
   150239   if( rc!=SQLITE_OK ) goto fts3_init_out;
   150240 
   150241   /* If this is an xCreate call, create the underlying tables in the
   150242   ** database. TODO: For xConnect(), it could verify that said tables exist.
   150243   */
   150244   if( isCreate ){
   150245     rc = fts3CreateTables(p);
   150246   }
   150247 
   150248   /* Check to see if a legacy fts3 table has been "upgraded" by the
   150249   ** addition of a %_stat table so that it can use incremental merge.
   150250   */
   150251   if( !isFts4 && !isCreate ){
   150252     p->bHasStat = 2;
   150253   }
   150254 
   150255   /* Figure out the page-size for the database. This is required in order to
   150256   ** estimate the cost of loading large doclists from the database.  */
   150257   fts3DatabasePageSize(&rc, p);
   150258   p->nNodeSize = p->nPgsz-35;
   150259 
   150260   /* Declare the table schema to SQLite. */
   150261   fts3DeclareVtab(&rc, p);
   150262 
   150263 fts3_init_out:
   150264   sqlite3_free(zPrefix);
   150265   sqlite3_free(aIndex);
   150266   sqlite3_free(zCompress);
   150267   sqlite3_free(zUncompress);
   150268   sqlite3_free(zContent);
   150269   sqlite3_free(zLanguageid);
   150270   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
   150271   sqlite3_free((void *)aCol);
   150272   sqlite3_free((void *)azNotindexed);
   150273   if( rc!=SQLITE_OK ){
   150274     if( p ){
   150275       fts3DisconnectMethod((sqlite3_vtab *)p);
   150276     }else if( pTokenizer ){
   150277       pTokenizer->pModule->xDestroy(pTokenizer);
   150278     }
   150279   }else{
   150280     assert( p->pSegments==0 );
   150281     *ppVTab = &p->base;
   150282   }
   150283   return rc;
   150284 }
   150285 
   150286 /*
   150287 ** The xConnect() and xCreate() methods for the virtual table. All the
   150288 ** work is done in function fts3InitVtab().
   150289 */
   150290 static int fts3ConnectMethod(
   150291   sqlite3 *db,                    /* Database connection */
   150292   void *pAux,                     /* Pointer to tokenizer hash table */
   150293   int argc,                       /* Number of elements in argv array */
   150294   const char * const *argv,       /* xCreate/xConnect argument array */
   150295   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   150296   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   150297 ){
   150298   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   150299 }
   150300 static int fts3CreateMethod(
   150301   sqlite3 *db,                    /* Database connection */
   150302   void *pAux,                     /* Pointer to tokenizer hash table */
   150303   int argc,                       /* Number of elements in argv array */
   150304   const char * const *argv,       /* xCreate/xConnect argument array */
   150305   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   150306   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   150307 ){
   150308   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
   150309 }
   150310 
   150311 /*
   150312 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
   150313 ** extension is currently being used by a version of SQLite too old to
   150314 ** support estimatedRows. In that case this function is a no-op.
   150315 */
   150316 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
   150317 #if SQLITE_VERSION_NUMBER>=3008002
   150318   if( sqlite3_libversion_number()>=3008002 ){
   150319     pIdxInfo->estimatedRows = nRow;
   150320   }
   150321 #endif
   150322 }
   150323 
   150324 /*
   150325 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
   150326 ** extension is currently being used by a version of SQLite too old to
   150327 ** support index-info flags. In that case this function is a no-op.
   150328 */
   150329 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
   150330 #if SQLITE_VERSION_NUMBER>=3008012
   150331   if( sqlite3_libversion_number()>=3008012 ){
   150332     pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
   150333   }
   150334 #endif
   150335 }
   150336 
   150337 /*
   150338 ** Implementation of the xBestIndex method for FTS3 tables. There
   150339 ** are three possible strategies, in order of preference:
   150340 **
   150341 **   1. Direct lookup by rowid or docid.
   150342 **   2. Full-text search using a MATCH operator on a non-docid column.
   150343 **   3. Linear scan of %_content table.
   150344 */
   150345 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   150346   Fts3Table *p = (Fts3Table *)pVTab;
   150347   int i;                          /* Iterator variable */
   150348   int iCons = -1;                 /* Index of constraint to use */
   150349 
   150350   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
   150351   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
   150352   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
   150353   int iIdx;
   150354 
   150355   /* By default use a full table scan. This is an expensive option,
   150356   ** so search through the constraints to see if a more efficient
   150357   ** strategy is possible.
   150358   */
   150359   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   150360   pInfo->estimatedCost = 5000000;
   150361   for(i=0; i<pInfo->nConstraint; i++){
   150362     int bDocid;                 /* True if this constraint is on docid */
   150363     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
   150364     if( pCons->usable==0 ){
   150365       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
   150366         /* There exists an unusable MATCH constraint. This means that if
   150367         ** the planner does elect to use the results of this call as part
   150368         ** of the overall query plan the user will see an "unable to use
   150369         ** function MATCH in the requested context" error. To discourage
   150370         ** this, return a very high cost here.  */
   150371         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   150372         pInfo->estimatedCost = 1e50;
   150373         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
   150374         return SQLITE_OK;
   150375       }
   150376       continue;
   150377     }
   150378 
   150379     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
   150380 
   150381     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
   150382     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
   150383       pInfo->idxNum = FTS3_DOCID_SEARCH;
   150384       pInfo->estimatedCost = 1.0;
   150385       iCons = i;
   150386     }
   150387 
   150388     /* A MATCH constraint. Use a full-text search.
   150389     **
   150390     ** If there is more than one MATCH constraint available, use the first
   150391     ** one encountered. If there is both a MATCH constraint and a direct
   150392     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
   150393     ** though the rowid/docid lookup is faster than a MATCH query, selecting
   150394     ** it would lead to an "unable to use function MATCH in the requested
   150395     ** context" error.
   150396     */
   150397     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
   150398      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
   150399     ){
   150400       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
   150401       pInfo->estimatedCost = 2.0;
   150402       iCons = i;
   150403     }
   150404 
   150405     /* Equality constraint on the langid column */
   150406     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   150407      && pCons->iColumn==p->nColumn + 2
   150408     ){
   150409       iLangidCons = i;
   150410     }
   150411 
   150412     if( bDocid ){
   150413       switch( pCons->op ){
   150414         case SQLITE_INDEX_CONSTRAINT_GE:
   150415         case SQLITE_INDEX_CONSTRAINT_GT:
   150416           iDocidGe = i;
   150417           break;
   150418 
   150419         case SQLITE_INDEX_CONSTRAINT_LE:
   150420         case SQLITE_INDEX_CONSTRAINT_LT:
   150421           iDocidLe = i;
   150422           break;
   150423       }
   150424     }
   150425   }
   150426 
   150427   /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
   150428   if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
   150429 
   150430   iIdx = 1;
   150431   if( iCons>=0 ){
   150432     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
   150433     pInfo->aConstraintUsage[iCons].omit = 1;
   150434   }
   150435   if( iLangidCons>=0 ){
   150436     pInfo->idxNum |= FTS3_HAVE_LANGID;
   150437     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
   150438   }
   150439   if( iDocidGe>=0 ){
   150440     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
   150441     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
   150442   }
   150443   if( iDocidLe>=0 ){
   150444     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
   150445     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
   150446   }
   150447 
   150448   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
   150449   ** docid) order. Both ascending and descending are possible.
   150450   */
   150451   if( pInfo->nOrderBy==1 ){
   150452     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
   150453     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
   150454       if( pOrder->desc ){
   150455         pInfo->idxStr = "DESC";
   150456       }else{
   150457         pInfo->idxStr = "ASC";
   150458       }
   150459       pInfo->orderByConsumed = 1;
   150460     }
   150461   }
   150462 
   150463   assert( p->pSegments==0 );
   150464   return SQLITE_OK;
   150465 }
   150466 
   150467 /*
   150468 ** Implementation of xOpen method.
   150469 */
   150470 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   150471   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
   150472 
   150473   UNUSED_PARAMETER(pVTab);
   150474 
   150475   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
   150476   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   150477   ** if the allocation fails, return SQLITE_NOMEM.
   150478   */
   150479   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
   150480   if( !pCsr ){
   150481     return SQLITE_NOMEM;
   150482   }
   150483   memset(pCsr, 0, sizeof(Fts3Cursor));
   150484   return SQLITE_OK;
   150485 }
   150486 
   150487 /*
   150488 ** Finalize the statement handle at pCsr->pStmt.
   150489 **
   150490 ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
   150491 ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
   150492 ** pointer there instead of finalizing it.
   150493 */
   150494 static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
   150495   if( pCsr->bSeekStmt ){
   150496     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   150497     if( p->pSeekStmt==0 ){
   150498       p->pSeekStmt = pCsr->pStmt;
   150499       sqlite3_reset(pCsr->pStmt);
   150500       pCsr->pStmt = 0;
   150501     }
   150502     pCsr->bSeekStmt = 0;
   150503   }
   150504   sqlite3_finalize(pCsr->pStmt);
   150505 }
   150506 
   150507 /*
   150508 ** Free all resources currently held by the cursor passed as the only
   150509 ** argument.
   150510 */
   150511 static void fts3ClearCursor(Fts3Cursor *pCsr){
   150512   fts3CursorFinalizeStmt(pCsr);
   150513   sqlite3Fts3FreeDeferredTokens(pCsr);
   150514   sqlite3_free(pCsr->aDoclist);
   150515   sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
   150516   sqlite3Fts3ExprFree(pCsr->pExpr);
   150517   memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
   150518 }
   150519 
   150520 /*
   150521 ** Close the cursor.  For additional information see the documentation
   150522 ** on the xClose method of the virtual table interface.
   150523 */
   150524 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
   150525   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   150526   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   150527   fts3ClearCursor(pCsr);
   150528   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   150529   sqlite3_free(pCsr);
   150530   return SQLITE_OK;
   150531 }
   150532 
   150533 /*
   150534 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
   150535 ** compose and prepare an SQL statement of the form:
   150536 **
   150537 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
   150538 **
   150539 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
   150540 ** it. If an error occurs, return an SQLite error code.
   150541 */
   150542 static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
   150543   int rc = SQLITE_OK;
   150544   if( pCsr->pStmt==0 ){
   150545     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   150546     char *zSql;
   150547     if( p->pSeekStmt ){
   150548       pCsr->pStmt = p->pSeekStmt;
   150549       p->pSeekStmt = 0;
   150550     }else{
   150551       zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
   150552       if( !zSql ) return SQLITE_NOMEM;
   150553       rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
   150554       sqlite3_free(zSql);
   150555     }
   150556     if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
   150557   }
   150558   return rc;
   150559 }
   150560 
   150561 /*
   150562 ** Position the pCsr->pStmt statement so that it is on the row
   150563 ** of the %_content table that contains the last match.  Return
   150564 ** SQLITE_OK on success.
   150565 */
   150566 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   150567   int rc = SQLITE_OK;
   150568   if( pCsr->isRequireSeek ){
   150569     rc = fts3CursorSeekStmt(pCsr);
   150570     if( rc==SQLITE_OK ){
   150571       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
   150572       pCsr->isRequireSeek = 0;
   150573       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
   150574         return SQLITE_OK;
   150575       }else{
   150576         rc = sqlite3_reset(pCsr->pStmt);
   150577         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
   150578           /* If no row was found and no error has occurred, then the %_content
   150579           ** table is missing a row that is present in the full-text index.
   150580           ** The data structures are corrupt.  */
   150581           rc = FTS_CORRUPT_VTAB;
   150582           pCsr->isEof = 1;
   150583         }
   150584       }
   150585     }
   150586   }
   150587 
   150588   if( rc!=SQLITE_OK && pContext ){
   150589     sqlite3_result_error_code(pContext, rc);
   150590   }
   150591   return rc;
   150592 }
   150593 
   150594 /*
   150595 ** This function is used to process a single interior node when searching
   150596 ** a b-tree for a term or term prefix. The node data is passed to this
   150597 ** function via the zNode/nNode parameters. The term to search for is
   150598 ** passed in zTerm/nTerm.
   150599 **
   150600 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
   150601 ** of the child node that heads the sub-tree that may contain the term.
   150602 **
   150603 ** If piLast is not NULL, then *piLast is set to the right-most child node
   150604 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
   150605 ** a prefix.
   150606 **
   150607 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   150608 */
   150609 static int fts3ScanInteriorNode(
   150610   const char *zTerm,              /* Term to select leaves for */
   150611   int nTerm,                      /* Size of term zTerm in bytes */
   150612   const char *zNode,              /* Buffer containing segment interior node */
   150613   int nNode,                      /* Size of buffer at zNode */
   150614   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
   150615   sqlite3_int64 *piLast           /* OUT: Selected child node */
   150616 ){
   150617   int rc = SQLITE_OK;             /* Return code */
   150618   const char *zCsr = zNode;       /* Cursor to iterate through node */
   150619   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
   150620   char *zBuffer = 0;              /* Buffer to load terms into */
   150621   int nAlloc = 0;                 /* Size of allocated buffer */
   150622   int isFirstTerm = 1;            /* True when processing first term on page */
   150623   sqlite3_int64 iChild;           /* Block id of child node to descend to */
   150624 
   150625   /* Skip over the 'height' varint that occurs at the start of every
   150626   ** interior node. Then load the blockid of the left-child of the b-tree
   150627   ** node into variable iChild.
   150628   **
   150629   ** Even if the data structure on disk is corrupted, this (reading two
   150630   ** varints from the buffer) does not risk an overread. If zNode is a
   150631   ** root node, then the buffer comes from a SELECT statement. SQLite does
   150632   ** not make this guarantee explicitly, but in practice there are always
   150633   ** either more than 20 bytes of allocated space following the nNode bytes of
   150634   ** contents, or two zero bytes. Or, if the node is read from the %_segments
   150635   ** table, then there are always 20 bytes of zeroed padding following the
   150636   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
   150637   */
   150638   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   150639   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   150640   if( zCsr>zEnd ){
   150641     return FTS_CORRUPT_VTAB;
   150642   }
   150643 
   150644   while( zCsr<zEnd && (piFirst || piLast) ){
   150645     int cmp;                      /* memcmp() result */
   150646     int nSuffix;                  /* Size of term suffix */
   150647     int nPrefix = 0;              /* Size of term prefix */
   150648     int nBuffer;                  /* Total term size */
   150649 
   150650     /* Load the next term on the node into zBuffer. Use realloc() to expand
   150651     ** the size of zBuffer if required.  */
   150652     if( !isFirstTerm ){
   150653       zCsr += fts3GetVarint32(zCsr, &nPrefix);
   150654     }
   150655     isFirstTerm = 0;
   150656     zCsr += fts3GetVarint32(zCsr, &nSuffix);
   150657 
   150658     assert( nPrefix>=0 && nSuffix>=0 );
   150659     if( &zCsr[nSuffix]>zEnd ){
   150660       rc = FTS_CORRUPT_VTAB;
   150661       goto finish_scan;
   150662     }
   150663     if( nPrefix+nSuffix>nAlloc ){
   150664       char *zNew;
   150665       nAlloc = (nPrefix+nSuffix) * 2;
   150666       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
   150667       if( !zNew ){
   150668         rc = SQLITE_NOMEM;
   150669         goto finish_scan;
   150670       }
   150671       zBuffer = zNew;
   150672     }
   150673     assert( zBuffer );
   150674     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
   150675     nBuffer = nPrefix + nSuffix;
   150676     zCsr += nSuffix;
   150677 
   150678     /* Compare the term we are searching for with the term just loaded from
   150679     ** the interior node. If the specified term is greater than or equal
   150680     ** to the term from the interior node, then all terms on the sub-tree
   150681     ** headed by node iChild are smaller than zTerm. No need to search
   150682     ** iChild.
   150683     **
   150684     ** If the interior node term is larger than the specified term, then
   150685     ** the tree headed by iChild may contain the specified term.
   150686     */
   150687     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
   150688     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
   150689       *piFirst = iChild;
   150690       piFirst = 0;
   150691     }
   150692 
   150693     if( piLast && cmp<0 ){
   150694       *piLast = iChild;
   150695       piLast = 0;
   150696     }
   150697 
   150698     iChild++;
   150699   };
   150700 
   150701   if( piFirst ) *piFirst = iChild;
   150702   if( piLast ) *piLast = iChild;
   150703 
   150704  finish_scan:
   150705   sqlite3_free(zBuffer);
   150706   return rc;
   150707 }
   150708 
   150709 
   150710 /*
   150711 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
   150712 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
   150713 ** contains a term. This function searches the sub-tree headed by the zNode
   150714 ** node for the range of leaf nodes that may contain the specified term
   150715 ** or terms for which the specified term is a prefix.
   150716 **
   150717 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
   150718 ** left-most leaf node in the tree that may contain the specified term.
   150719 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
   150720 ** right-most leaf node that may contain a term for which the specified
   150721 ** term is a prefix.
   150722 **
   150723 ** It is possible that the range of returned leaf nodes does not contain
   150724 ** the specified term or any terms for which it is a prefix. However, if the
   150725 ** segment does contain any such terms, they are stored within the identified
   150726 ** range. Because this function only inspects interior segment nodes (and
   150727 ** never loads leaf nodes into memory), it is not possible to be sure.
   150728 **
   150729 ** If an error occurs, an error code other than SQLITE_OK is returned.
   150730 */
   150731 static int fts3SelectLeaf(
   150732   Fts3Table *p,                   /* Virtual table handle */
   150733   const char *zTerm,              /* Term to select leaves for */
   150734   int nTerm,                      /* Size of term zTerm in bytes */
   150735   const char *zNode,              /* Buffer containing segment interior node */
   150736   int nNode,                      /* Size of buffer at zNode */
   150737   sqlite3_int64 *piLeaf,          /* Selected leaf node */
   150738   sqlite3_int64 *piLeaf2          /* Selected leaf node */
   150739 ){
   150740   int rc = SQLITE_OK;             /* Return code */
   150741   int iHeight;                    /* Height of this node in tree */
   150742 
   150743   assert( piLeaf || piLeaf2 );
   150744 
   150745   fts3GetVarint32(zNode, &iHeight);
   150746   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
   150747   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
   150748 
   150749   if( rc==SQLITE_OK && iHeight>1 ){
   150750     char *zBlob = 0;              /* Blob read from %_segments table */
   150751     int nBlob = 0;                /* Size of zBlob in bytes */
   150752 
   150753     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
   150754       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
   150755       if( rc==SQLITE_OK ){
   150756         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
   150757       }
   150758       sqlite3_free(zBlob);
   150759       piLeaf = 0;
   150760       zBlob = 0;
   150761     }
   150762 
   150763     if( rc==SQLITE_OK ){
   150764       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
   150765     }
   150766     if( rc==SQLITE_OK ){
   150767       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
   150768     }
   150769     sqlite3_free(zBlob);
   150770   }
   150771 
   150772   return rc;
   150773 }
   150774 
   150775 /*
   150776 ** This function is used to create delta-encoded serialized lists of FTS3
   150777 ** varints. Each call to this function appends a single varint to a list.
   150778 */
   150779 static void fts3PutDeltaVarint(
   150780   char **pp,                      /* IN/OUT: Output pointer */
   150781   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   150782   sqlite3_int64 iVal              /* Write this value to the list */
   150783 ){
   150784   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   150785   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   150786   *piPrev = iVal;
   150787 }
   150788 
   150789 /*
   150790 ** When this function is called, *ppPoslist is assumed to point to the
   150791 ** start of a position-list. After it returns, *ppPoslist points to the
   150792 ** first byte after the position-list.
   150793 **
   150794 ** A position list is list of positions (delta encoded) and columns for
   150795 ** a single document record of a doclist.  So, in other words, this
   150796 ** routine advances *ppPoslist so that it points to the next docid in
   150797 ** the doclist, or to the first byte past the end of the doclist.
   150798 **
   150799 ** If pp is not NULL, then the contents of the position list are copied
   150800 ** to *pp. *pp is set to point to the first byte past the last byte copied
   150801 ** before this function returns.
   150802 */
   150803 static void fts3PoslistCopy(char **pp, char **ppPoslist){
   150804   char *pEnd = *ppPoslist;
   150805   char c = 0;
   150806 
   150807   /* The end of a position list is marked by a zero encoded as an FTS3
   150808   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
   150809   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   150810   ** of some other, multi-byte, value.
   150811   **
   150812   ** The following while-loop moves pEnd to point to the first byte that is not
   150813   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   150814   ** pEnd once more so that it points to the byte immediately following the
   150815   ** last byte in the position-list.
   150816   */
   150817   while( *pEnd | c ){
   150818     c = *pEnd++ & 0x80;
   150819     testcase( c!=0 && (*pEnd)==0 );
   150820   }
   150821   pEnd++;  /* Advance past the POS_END terminator byte */
   150822 
   150823   if( pp ){
   150824     int n = (int)(pEnd - *ppPoslist);
   150825     char *p = *pp;
   150826     memcpy(p, *ppPoslist, n);
   150827     p += n;
   150828     *pp = p;
   150829   }
   150830   *ppPoslist = pEnd;
   150831 }
   150832 
   150833 /*
   150834 ** When this function is called, *ppPoslist is assumed to point to the
   150835 ** start of a column-list. After it returns, *ppPoslist points to the
   150836 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
   150837 **
   150838 ** A column-list is list of delta-encoded positions for a single column
   150839 ** within a single document within a doclist.
   150840 **
   150841 ** The column-list is terminated either by a POS_COLUMN varint (1) or
   150842 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
   150843 ** the POS_COLUMN or POS_END that terminates the column-list.
   150844 **
   150845 ** If pp is not NULL, then the contents of the column-list are copied
   150846 ** to *pp. *pp is set to point to the first byte past the last byte copied
   150847 ** before this function returns.  The POS_COLUMN or POS_END terminator
   150848 ** is not copied into *pp.
   150849 */
   150850 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
   150851   char *pEnd = *ppPoslist;
   150852   char c = 0;
   150853 
   150854   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
   150855   ** not part of a multi-byte varint.
   150856   */
   150857   while( 0xFE & (*pEnd | c) ){
   150858     c = *pEnd++ & 0x80;
   150859     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
   150860   }
   150861   if( pp ){
   150862     int n = (int)(pEnd - *ppPoslist);
   150863     char *p = *pp;
   150864     memcpy(p, *ppPoslist, n);
   150865     p += n;
   150866     *pp = p;
   150867   }
   150868   *ppPoslist = pEnd;
   150869 }
   150870 
   150871 /*
   150872 ** Value used to signify the end of an position-list. This is safe because
   150873 ** it is not possible to have a document with 2^31 terms.
   150874 */
   150875 #define POSITION_LIST_END 0x7fffffff
   150876 
   150877 /*
   150878 ** This function is used to help parse position-lists. When this function is
   150879 ** called, *pp may point to the start of the next varint in the position-list
   150880 ** being parsed, or it may point to 1 byte past the end of the position-list
   150881 ** (in which case **pp will be a terminator bytes POS_END (0) or
   150882 ** (1)).
   150883 **
   150884 ** If *pp points past the end of the current position-list, set *pi to
   150885 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
   150886 ** increment the current value of *pi by the value read, and set *pp to
   150887 ** point to the next value before returning.
   150888 **
   150889 ** Before calling this routine *pi must be initialized to the value of
   150890 ** the previous position, or zero if we are reading the first position
   150891 ** in the position-list.  Because positions are delta-encoded, the value
   150892 ** of the previous position is needed in order to compute the value of
   150893 ** the next position.
   150894 */
   150895 static void fts3ReadNextPos(
   150896   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
   150897   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
   150898 ){
   150899   if( (**pp)&0xFE ){
   150900     fts3GetDeltaVarint(pp, pi);
   150901     *pi -= 2;
   150902   }else{
   150903     *pi = POSITION_LIST_END;
   150904   }
   150905 }
   150906 
   150907 /*
   150908 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
   150909 ** the value of iCol encoded as a varint to *pp.   This will start a new
   150910 ** column list.
   150911 **
   150912 ** Set *pp to point to the byte just after the last byte written before
   150913 ** returning (do not modify it if iCol==0). Return the total number of bytes
   150914 ** written (0 if iCol==0).
   150915 */
   150916 static int fts3PutColNumber(char **pp, int iCol){
   150917   int n = 0;                      /* Number of bytes written */
   150918   if( iCol ){
   150919     char *p = *pp;                /* Output pointer */
   150920     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
   150921     *p = 0x01;
   150922     *pp = &p[n];
   150923   }
   150924   return n;
   150925 }
   150926 
   150927 /*
   150928 ** Compute the union of two position lists.  The output written
   150929 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
   150930 ** order and with any duplicates removed.  All pointers are
   150931 ** updated appropriately.   The caller is responsible for insuring
   150932 ** that there is enough space in *pp to hold the complete output.
   150933 */
   150934 static void fts3PoslistMerge(
   150935   char **pp,                      /* Output buffer */
   150936   char **pp1,                     /* Left input list */
   150937   char **pp2                      /* Right input list */
   150938 ){
   150939   char *p = *pp;
   150940   char *p1 = *pp1;
   150941   char *p2 = *pp2;
   150942 
   150943   while( *p1 || *p2 ){
   150944     int iCol1;         /* The current column index in pp1 */
   150945     int iCol2;         /* The current column index in pp2 */
   150946 
   150947     if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
   150948     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
   150949     else iCol1 = 0;
   150950 
   150951     if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
   150952     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
   150953     else iCol2 = 0;
   150954 
   150955     if( iCol1==iCol2 ){
   150956       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
   150957       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
   150958       sqlite3_int64 iPrev = 0;
   150959       int n = fts3PutColNumber(&p, iCol1);
   150960       p1 += n;
   150961       p2 += n;
   150962 
   150963       /* At this point, both p1 and p2 point to the start of column-lists
   150964       ** for the same column (the column with index iCol1 and iCol2).
   150965       ** A column-list is a list of non-negative delta-encoded varints, each
   150966       ** incremented by 2 before being stored. Each list is terminated by a
   150967       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
   150968       ** and writes the results to buffer p. p is left pointing to the byte
   150969       ** after the list written. No terminator (POS_END or POS_COLUMN) is
   150970       ** written to the output.
   150971       */
   150972       fts3GetDeltaVarint(&p1, &i1);
   150973       fts3GetDeltaVarint(&p2, &i2);
   150974       do {
   150975         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
   150976         iPrev -= 2;
   150977         if( i1==i2 ){
   150978           fts3ReadNextPos(&p1, &i1);
   150979           fts3ReadNextPos(&p2, &i2);
   150980         }else if( i1<i2 ){
   150981           fts3ReadNextPos(&p1, &i1);
   150982         }else{
   150983           fts3ReadNextPos(&p2, &i2);
   150984         }
   150985       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
   150986     }else if( iCol1<iCol2 ){
   150987       p1 += fts3PutColNumber(&p, iCol1);
   150988       fts3ColumnlistCopy(&p, &p1);
   150989     }else{
   150990       p2 += fts3PutColNumber(&p, iCol2);
   150991       fts3ColumnlistCopy(&p, &p2);
   150992     }
   150993   }
   150994 
   150995   *p++ = POS_END;
   150996   *pp = p;
   150997   *pp1 = p1 + 1;
   150998   *pp2 = p2 + 1;
   150999 }
   151000 
   151001 /*
   151002 ** This function is used to merge two position lists into one. When it is
   151003 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
   151004 ** the part of a doclist that follows each document id. For example, if a row
   151005 ** contains:
   151006 **
   151007 **     'a b c'|'x y z'|'a b b a'
   151008 **
   151009 ** Then the position list for this row for token 'b' would consist of:
   151010 **
   151011 **     0x02 0x01 0x02 0x03 0x03 0x00
   151012 **
   151013 ** When this function returns, both *pp1 and *pp2 are left pointing to the
   151014 ** byte following the 0x00 terminator of their respective position lists.
   151015 **
   151016 ** If isSaveLeft is 0, an entry is added to the output position list for
   151017 ** each position in *pp2 for which there exists one or more positions in
   151018 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
   151019 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
   151020 ** slots before it.
   151021 **
   151022 ** e.g. nToken==1 searches for adjacent positions.
   151023 */
   151024 static int fts3PoslistPhraseMerge(
   151025   char **pp,                      /* IN/OUT: Preallocated output buffer */
   151026   int nToken,                     /* Maximum difference in token positions */
   151027   int isSaveLeft,                 /* Save the left position */
   151028   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
   151029   char **pp1,                     /* IN/OUT: Left input list */
   151030   char **pp2                      /* IN/OUT: Right input list */
   151031 ){
   151032   char *p = *pp;
   151033   char *p1 = *pp1;
   151034   char *p2 = *pp2;
   151035   int iCol1 = 0;
   151036   int iCol2 = 0;
   151037 
   151038   /* Never set both isSaveLeft and isExact for the same invocation. */
   151039   assert( isSaveLeft==0 || isExact==0 );
   151040 
   151041   assert( p!=0 && *p1!=0 && *p2!=0 );
   151042   if( *p1==POS_COLUMN ){
   151043     p1++;
   151044     p1 += fts3GetVarint32(p1, &iCol1);
   151045   }
   151046   if( *p2==POS_COLUMN ){
   151047     p2++;
   151048     p2 += fts3GetVarint32(p2, &iCol2);
   151049   }
   151050 
   151051   while( 1 ){
   151052     if( iCol1==iCol2 ){
   151053       char *pSave = p;
   151054       sqlite3_int64 iPrev = 0;
   151055       sqlite3_int64 iPos1 = 0;
   151056       sqlite3_int64 iPos2 = 0;
   151057 
   151058       if( iCol1 ){
   151059         *p++ = POS_COLUMN;
   151060         p += sqlite3Fts3PutVarint(p, iCol1);
   151061       }
   151062 
   151063       assert( *p1!=POS_END && *p1!=POS_COLUMN );
   151064       assert( *p2!=POS_END && *p2!=POS_COLUMN );
   151065       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   151066       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   151067 
   151068       while( 1 ){
   151069         if( iPos2==iPos1+nToken
   151070          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
   151071         ){
   151072           sqlite3_int64 iSave;
   151073           iSave = isSaveLeft ? iPos1 : iPos2;
   151074           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
   151075           pSave = 0;
   151076           assert( p );
   151077         }
   151078         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
   151079           if( (*p2&0xFE)==0 ) break;
   151080           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   151081         }else{
   151082           if( (*p1&0xFE)==0 ) break;
   151083           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   151084         }
   151085       }
   151086 
   151087       if( pSave ){
   151088         assert( pp && p );
   151089         p = pSave;
   151090       }
   151091 
   151092       fts3ColumnlistCopy(0, &p1);
   151093       fts3ColumnlistCopy(0, &p2);
   151094       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
   151095       if( 0==*p1 || 0==*p2 ) break;
   151096 
   151097       p1++;
   151098       p1 += fts3GetVarint32(p1, &iCol1);
   151099       p2++;
   151100       p2 += fts3GetVarint32(p2, &iCol2);
   151101     }
   151102 
   151103     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
   151104     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
   151105     ** end of the position list, or the 0x01 that precedes the next
   151106     ** column-number in the position list.
   151107     */
   151108     else if( iCol1<iCol2 ){
   151109       fts3ColumnlistCopy(0, &p1);
   151110       if( 0==*p1 ) break;
   151111       p1++;
   151112       p1 += fts3GetVarint32(p1, &iCol1);
   151113     }else{
   151114       fts3ColumnlistCopy(0, &p2);
   151115       if( 0==*p2 ) break;
   151116       p2++;
   151117       p2 += fts3GetVarint32(p2, &iCol2);
   151118     }
   151119   }
   151120 
   151121   fts3PoslistCopy(0, &p2);
   151122   fts3PoslistCopy(0, &p1);
   151123   *pp1 = p1;
   151124   *pp2 = p2;
   151125   if( *pp==p ){
   151126     return 0;
   151127   }
   151128   *p++ = 0x00;
   151129   *pp = p;
   151130   return 1;
   151131 }
   151132 
   151133 /*
   151134 ** Merge two position-lists as required by the NEAR operator. The argument
   151135 ** position lists correspond to the left and right phrases of an expression
   151136 ** like:
   151137 **
   151138 **     "phrase 1" NEAR "phrase number 2"
   151139 **
   151140 ** Position list *pp1 corresponds to the left-hand side of the NEAR
   151141 ** expression and *pp2 to the right. As usual, the indexes in the position
   151142 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
   151143 ** in the example above).
   151144 **
   151145 ** The output position list - written to *pp - is a copy of *pp2 with those
   151146 ** entries that are not sufficiently NEAR entries in *pp1 removed.
   151147 */
   151148 static int fts3PoslistNearMerge(
   151149   char **pp,                      /* Output buffer */
   151150   char *aTmp,                     /* Temporary buffer space */
   151151   int nRight,                     /* Maximum difference in token positions */
   151152   int nLeft,                      /* Maximum difference in token positions */
   151153   char **pp1,                     /* IN/OUT: Left input list */
   151154   char **pp2                      /* IN/OUT: Right input list */
   151155 ){
   151156   char *p1 = *pp1;
   151157   char *p2 = *pp2;
   151158 
   151159   char *pTmp1 = aTmp;
   151160   char *pTmp2;
   151161   char *aTmp2;
   151162   int res = 1;
   151163 
   151164   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
   151165   aTmp2 = pTmp2 = pTmp1;
   151166   *pp1 = p1;
   151167   *pp2 = p2;
   151168   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
   151169   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
   151170     fts3PoslistMerge(pp, &aTmp, &aTmp2);
   151171   }else if( pTmp1!=aTmp ){
   151172     fts3PoslistCopy(pp, &aTmp);
   151173   }else if( pTmp2!=aTmp2 ){
   151174     fts3PoslistCopy(pp, &aTmp2);
   151175   }else{
   151176     res = 0;
   151177   }
   151178 
   151179   return res;
   151180 }
   151181 
   151182 /*
   151183 ** An instance of this function is used to merge together the (potentially
   151184 ** large number of) doclists for each term that matches a prefix query.
   151185 ** See function fts3TermSelectMerge() for details.
   151186 */
   151187 typedef struct TermSelect TermSelect;
   151188 struct TermSelect {
   151189   char *aaOutput[16];             /* Malloc'd output buffers */
   151190   int anOutput[16];               /* Size each output buffer in bytes */
   151191 };
   151192 
   151193 /*
   151194 ** This function is used to read a single varint from a buffer. Parameter
   151195 ** pEnd points 1 byte past the end of the buffer. When this function is
   151196 ** called, if *pp points to pEnd or greater, then the end of the buffer
   151197 ** has been reached. In this case *pp is set to 0 and the function returns.
   151198 **
   151199 ** If *pp does not point to or past pEnd, then a single varint is read
   151200 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
   151201 **
   151202 ** If bDescIdx is false, the value read is added to *pVal before returning.
   151203 ** If it is true, the value read is subtracted from *pVal before this
   151204 ** function returns.
   151205 */
   151206 static void fts3GetDeltaVarint3(
   151207   char **pp,                      /* IN/OUT: Point to read varint from */
   151208   char *pEnd,                     /* End of buffer */
   151209   int bDescIdx,                   /* True if docids are descending */
   151210   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
   151211 ){
   151212   if( *pp>=pEnd ){
   151213     *pp = 0;
   151214   }else{
   151215     sqlite3_int64 iVal;
   151216     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   151217     if( bDescIdx ){
   151218       *pVal -= iVal;
   151219     }else{
   151220       *pVal += iVal;
   151221     }
   151222   }
   151223 }
   151224 
   151225 /*
   151226 ** This function is used to write a single varint to a buffer. The varint
   151227 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
   151228 ** end of the value written.
   151229 **
   151230 ** If *pbFirst is zero when this function is called, the value written to
   151231 ** the buffer is that of parameter iVal.
   151232 **
   151233 ** If *pbFirst is non-zero when this function is called, then the value
   151234 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
   151235 ** (if bDescIdx is non-zero).
   151236 **
   151237 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
   151238 ** to the value of parameter iVal.
   151239 */
   151240 static void fts3PutDeltaVarint3(
   151241   char **pp,                      /* IN/OUT: Output pointer */
   151242   int bDescIdx,                   /* True for descending docids */
   151243   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   151244   int *pbFirst,                   /* IN/OUT: True after first int written */
   151245   sqlite3_int64 iVal              /* Write this value to the list */
   151246 ){
   151247   sqlite3_int64 iWrite;
   151248   if( bDescIdx==0 || *pbFirst==0 ){
   151249     iWrite = iVal - *piPrev;
   151250   }else{
   151251     iWrite = *piPrev - iVal;
   151252   }
   151253   assert( *pbFirst || *piPrev==0 );
   151254   assert( *pbFirst==0 || iWrite>0 );
   151255   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
   151256   *piPrev = iVal;
   151257   *pbFirst = 1;
   151258 }
   151259 
   151260 
   151261 /*
   151262 ** This macro is used by various functions that merge doclists. The two
   151263 ** arguments are 64-bit docid values. If the value of the stack variable
   151264 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
   151265 ** Otherwise, (i2-i1).
   151266 **
   151267 ** Using this makes it easier to write code that can merge doclists that are
   151268 ** sorted in either ascending or descending order.
   151269 */
   151270 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
   151271 
   151272 /*
   151273 ** This function does an "OR" merge of two doclists (output contains all
   151274 ** positions contained in either argument doclist). If the docids in the
   151275 ** input doclists are sorted in ascending order, parameter bDescDoclist
   151276 ** should be false. If they are sorted in ascending order, it should be
   151277 ** passed a non-zero value.
   151278 **
   151279 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
   151280 ** containing the output doclist and SQLITE_OK is returned. In this case
   151281 ** *pnOut is set to the number of bytes in the output doclist.
   151282 **
   151283 ** If an error occurs, an SQLite error code is returned. The output values
   151284 ** are undefined in this case.
   151285 */
   151286 static int fts3DoclistOrMerge(
   151287   int bDescDoclist,               /* True if arguments are desc */
   151288   char *a1, int n1,               /* First doclist */
   151289   char *a2, int n2,               /* Second doclist */
   151290   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
   151291 ){
   151292   sqlite3_int64 i1 = 0;
   151293   sqlite3_int64 i2 = 0;
   151294   sqlite3_int64 iPrev = 0;
   151295   char *pEnd1 = &a1[n1];
   151296   char *pEnd2 = &a2[n2];
   151297   char *p1 = a1;
   151298   char *p2 = a2;
   151299   char *p;
   151300   char *aOut;
   151301   int bFirstOut = 0;
   151302 
   151303   *paOut = 0;
   151304   *pnOut = 0;
   151305 
   151306   /* Allocate space for the output. Both the input and output doclists
   151307   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
   151308   ** then the first docid in each list is simply encoded as a varint. For
   151309   ** each subsequent docid, the varint stored is the difference between the
   151310   ** current and previous docid (a positive number - since the list is in
   151311   ** ascending order).
   151312   **
   151313   ** The first docid written to the output is therefore encoded using the
   151314   ** same number of bytes as it is in whichever of the input lists it is
   151315   ** read from. And each subsequent docid read from the same input list
   151316   ** consumes either the same or less bytes as it did in the input (since
   151317   ** the difference between it and the previous value in the output must
   151318   ** be a positive value less than or equal to the delta value read from
   151319   ** the input list). The same argument applies to all but the first docid
   151320   ** read from the 'other' list. And to the contents of all position lists
   151321   ** that will be copied and merged from the input to the output.
   151322   **
   151323   ** However, if the first docid copied to the output is a negative number,
   151324   ** then the encoding of the first docid from the 'other' input list may
   151325   ** be larger in the output than it was in the input (since the delta value
   151326   ** may be a larger positive integer than the actual docid).
   151327   **
   151328   ** The space required to store the output is therefore the sum of the
   151329   ** sizes of the two inputs, plus enough space for exactly one of the input
   151330   ** docids to grow.
   151331   **
   151332   ** A symetric argument may be made if the doclists are in descending
   151333   ** order.
   151334   */
   151335   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
   151336   if( !aOut ) return SQLITE_NOMEM;
   151337 
   151338   p = aOut;
   151339   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   151340   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   151341   while( p1 || p2 ){
   151342     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   151343 
   151344     if( p2 && p1 && iDiff==0 ){
   151345       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   151346       fts3PoslistMerge(&p, &p1, &p2);
   151347       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   151348       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   151349     }else if( !p2 || (p1 && iDiff<0) ){
   151350       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   151351       fts3PoslistCopy(&p, &p1);
   151352       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   151353     }else{
   151354       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
   151355       fts3PoslistCopy(&p, &p2);
   151356       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   151357     }
   151358   }
   151359 
   151360   *paOut = aOut;
   151361   *pnOut = (int)(p-aOut);
   151362   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
   151363   return SQLITE_OK;
   151364 }
   151365 
   151366 /*
   151367 ** This function does a "phrase" merge of two doclists. In a phrase merge,
   151368 ** the output contains a copy of each position from the right-hand input
   151369 ** doclist for which there is a position in the left-hand input doclist
   151370 ** exactly nDist tokens before it.
   151371 **
   151372 ** If the docids in the input doclists are sorted in ascending order,
   151373 ** parameter bDescDoclist should be false. If they are sorted in ascending
   151374 ** order, it should be passed a non-zero value.
   151375 **
   151376 ** The right-hand input doclist is overwritten by this function.
   151377 */
   151378 static int fts3DoclistPhraseMerge(
   151379   int bDescDoclist,               /* True if arguments are desc */
   151380   int nDist,                      /* Distance from left to right (1=adjacent) */
   151381   char *aLeft, int nLeft,         /* Left doclist */
   151382   char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
   151383 ){
   151384   sqlite3_int64 i1 = 0;
   151385   sqlite3_int64 i2 = 0;
   151386   sqlite3_int64 iPrev = 0;
   151387   char *aRight = *paRight;
   151388   char *pEnd1 = &aLeft[nLeft];
   151389   char *pEnd2 = &aRight[*pnRight];
   151390   char *p1 = aLeft;
   151391   char *p2 = aRight;
   151392   char *p;
   151393   int bFirstOut = 0;
   151394   char *aOut;
   151395 
   151396   assert( nDist>0 );
   151397   if( bDescDoclist ){
   151398     aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
   151399     if( aOut==0 ) return SQLITE_NOMEM;
   151400   }else{
   151401     aOut = aRight;
   151402   }
   151403   p = aOut;
   151404 
   151405   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   151406   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   151407 
   151408   while( p1 && p2 ){
   151409     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   151410     if( iDiff==0 ){
   151411       char *pSave = p;
   151412       sqlite3_int64 iPrevSave = iPrev;
   151413       int bFirstOutSave = bFirstOut;
   151414 
   151415       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   151416       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
   151417         p = pSave;
   151418         iPrev = iPrevSave;
   151419         bFirstOut = bFirstOutSave;
   151420       }
   151421       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   151422       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   151423     }else if( iDiff<0 ){
   151424       fts3PoslistCopy(0, &p1);
   151425       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   151426     }else{
   151427       fts3PoslistCopy(0, &p2);
   151428       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   151429     }
   151430   }
   151431 
   151432   *pnRight = (int)(p - aOut);
   151433   if( bDescDoclist ){
   151434     sqlite3_free(aRight);
   151435     *paRight = aOut;
   151436   }
   151437 
   151438   return SQLITE_OK;
   151439 }
   151440 
   151441 /*
   151442 ** Argument pList points to a position list nList bytes in size. This
   151443 ** function checks to see if the position list contains any entries for
   151444 ** a token in position 0 (of any column). If so, it writes argument iDelta
   151445 ** to the output buffer pOut, followed by a position list consisting only
   151446 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
   151447 ** The value returned is the number of bytes written to pOut (if any).
   151448 */
   151449 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
   151450   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
   151451   char *pList,                    /* Position list (no 0x00 term) */
   151452   int nList,                      /* Size of pList in bytes */
   151453   char *pOut                      /* Write output here */
   151454 ){
   151455   int nOut = 0;
   151456   int bWritten = 0;               /* True once iDelta has been written */
   151457   char *p = pList;
   151458   char *pEnd = &pList[nList];
   151459 
   151460   if( *p!=0x01 ){
   151461     if( *p==0x02 ){
   151462       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   151463       pOut[nOut++] = 0x02;
   151464       bWritten = 1;
   151465     }
   151466     fts3ColumnlistCopy(0, &p);
   151467   }
   151468 
   151469   while( p<pEnd ){
   151470     sqlite3_int64 iCol;
   151471     p++;
   151472     p += sqlite3Fts3GetVarint(p, &iCol);
   151473     if( *p==0x02 ){
   151474       if( bWritten==0 ){
   151475         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   151476         bWritten = 1;
   151477       }
   151478       pOut[nOut++] = 0x01;
   151479       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
   151480       pOut[nOut++] = 0x02;
   151481     }
   151482     fts3ColumnlistCopy(0, &p);
   151483   }
   151484   if( bWritten ){
   151485     pOut[nOut++] = 0x00;
   151486   }
   151487 
   151488   return nOut;
   151489 }
   151490 
   151491 
   151492 /*
   151493 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
   151494 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
   151495 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
   151496 **
   151497 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
   151498 ** the responsibility of the caller to free any doclists left in the
   151499 ** TermSelect.aaOutput[] array.
   151500 */
   151501 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
   151502   char *aOut = 0;
   151503   int nOut = 0;
   151504   int i;
   151505 
   151506   /* Loop through the doclists in the aaOutput[] array. Merge them all
   151507   ** into a single doclist.
   151508   */
   151509   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
   151510     if( pTS->aaOutput[i] ){
   151511       if( !aOut ){
   151512         aOut = pTS->aaOutput[i];
   151513         nOut = pTS->anOutput[i];
   151514         pTS->aaOutput[i] = 0;
   151515       }else{
   151516         int nNew;
   151517         char *aNew;
   151518 
   151519         int rc = fts3DoclistOrMerge(p->bDescIdx,
   151520             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
   151521         );
   151522         if( rc!=SQLITE_OK ){
   151523           sqlite3_free(aOut);
   151524           return rc;
   151525         }
   151526 
   151527         sqlite3_free(pTS->aaOutput[i]);
   151528         sqlite3_free(aOut);
   151529         pTS->aaOutput[i] = 0;
   151530         aOut = aNew;
   151531         nOut = nNew;
   151532       }
   151533     }
   151534   }
   151535 
   151536   pTS->aaOutput[0] = aOut;
   151537   pTS->anOutput[0] = nOut;
   151538   return SQLITE_OK;
   151539 }
   151540 
   151541 /*
   151542 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
   151543 ** as the first argument. The merge is an "OR" merge (see function
   151544 ** fts3DoclistOrMerge() for details).
   151545 **
   151546 ** This function is called with the doclist for each term that matches
   151547 ** a queried prefix. It merges all these doclists into one, the doclist
   151548 ** for the specified prefix. Since there can be a very large number of
   151549 ** doclists to merge, the merging is done pair-wise using the TermSelect
   151550 ** object.
   151551 **
   151552 ** This function returns SQLITE_OK if the merge is successful, or an
   151553 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
   151554 */
   151555 static int fts3TermSelectMerge(
   151556   Fts3Table *p,                   /* FTS table handle */
   151557   TermSelect *pTS,                /* TermSelect object to merge into */
   151558   char *aDoclist,                 /* Pointer to doclist */
   151559   int nDoclist                    /* Size of aDoclist in bytes */
   151560 ){
   151561   if( pTS->aaOutput[0]==0 ){
   151562     /* If this is the first term selected, copy the doclist to the output
   151563     ** buffer using memcpy().
   151564     **
   151565     ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
   151566     ** allocation. This is so as to ensure that the buffer is big enough
   151567     ** to hold the current doclist AND'd with any other doclist. If the
   151568     ** doclists are stored in order=ASC order, this padding would not be
   151569     ** required (since the size of [doclistA AND doclistB] is always less
   151570     ** than or equal to the size of [doclistA] in that case). But this is
   151571     ** not true for order=DESC. For example, a doclist containing (1, -1)
   151572     ** may be smaller than (-1), as in the first example the -1 may be stored
   151573     ** as a single-byte delta, whereas in the second it must be stored as a
   151574     ** FTS3_VARINT_MAX byte varint.
   151575     **
   151576     ** Similar padding is added in the fts3DoclistOrMerge() function.
   151577     */
   151578     pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
   151579     pTS->anOutput[0] = nDoclist;
   151580     if( pTS->aaOutput[0] ){
   151581       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
   151582     }else{
   151583       return SQLITE_NOMEM;
   151584     }
   151585   }else{
   151586     char *aMerge = aDoclist;
   151587     int nMerge = nDoclist;
   151588     int iOut;
   151589 
   151590     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
   151591       if( pTS->aaOutput[iOut]==0 ){
   151592         assert( iOut>0 );
   151593         pTS->aaOutput[iOut] = aMerge;
   151594         pTS->anOutput[iOut] = nMerge;
   151595         break;
   151596       }else{
   151597         char *aNew;
   151598         int nNew;
   151599 
   151600         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
   151601             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
   151602         );
   151603         if( rc!=SQLITE_OK ){
   151604           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   151605           return rc;
   151606         }
   151607 
   151608         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   151609         sqlite3_free(pTS->aaOutput[iOut]);
   151610         pTS->aaOutput[iOut] = 0;
   151611 
   151612         aMerge = aNew;
   151613         nMerge = nNew;
   151614         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
   151615           pTS->aaOutput[iOut] = aMerge;
   151616           pTS->anOutput[iOut] = nMerge;
   151617         }
   151618       }
   151619     }
   151620   }
   151621   return SQLITE_OK;
   151622 }
   151623 
   151624 /*
   151625 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
   151626 */
   151627 static int fts3SegReaderCursorAppend(
   151628   Fts3MultiSegReader *pCsr,
   151629   Fts3SegReader *pNew
   151630 ){
   151631   if( (pCsr->nSegment%16)==0 ){
   151632     Fts3SegReader **apNew;
   151633     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
   151634     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
   151635     if( !apNew ){
   151636       sqlite3Fts3SegReaderFree(pNew);
   151637       return SQLITE_NOMEM;
   151638     }
   151639     pCsr->apSegment = apNew;
   151640   }
   151641   pCsr->apSegment[pCsr->nSegment++] = pNew;
   151642   return SQLITE_OK;
   151643 }
   151644 
   151645 /*
   151646 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
   151647 ** 8th argument.
   151648 **
   151649 ** This function returns SQLITE_OK if successful, or an SQLite error code
   151650 ** otherwise.
   151651 */
   151652 static int fts3SegReaderCursor(
   151653   Fts3Table *p,                   /* FTS3 table handle */
   151654   int iLangid,                    /* Language id */
   151655   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   151656   int iLevel,                     /* Level of segments to scan */
   151657   const char *zTerm,              /* Term to query for */
   151658   int nTerm,                      /* Size of zTerm in bytes */
   151659   int isPrefix,                   /* True for a prefix search */
   151660   int isScan,                     /* True to scan from zTerm to EOF */
   151661   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   151662 ){
   151663   int rc = SQLITE_OK;             /* Error code */
   151664   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
   151665   int rc2;                        /* Result of sqlite3_reset() */
   151666 
   151667   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
   151668   ** for the pending-terms. If this is a scan, then this call must be being
   151669   ** made by an fts4aux module, not an FTS table. In this case calling
   151670   ** Fts3SegReaderPending might segfault, as the data structures used by
   151671   ** fts4aux are not completely populated. So it's easiest to filter these
   151672   ** calls out here.  */
   151673   if( iLevel<0 && p->aIndex ){
   151674     Fts3SegReader *pSeg = 0;
   151675     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
   151676     if( rc==SQLITE_OK && pSeg ){
   151677       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   151678     }
   151679   }
   151680 
   151681   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   151682     if( rc==SQLITE_OK ){
   151683       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
   151684     }
   151685 
   151686     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   151687       Fts3SegReader *pSeg = 0;
   151688 
   151689       /* Read the values returned by the SELECT into local variables. */
   151690       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
   151691       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
   151692       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
   151693       int nRoot = sqlite3_column_bytes(pStmt, 4);
   151694       char const *zRoot = sqlite3_column_blob(pStmt, 4);
   151695 
   151696       /* If zTerm is not NULL, and this segment is not stored entirely on its
   151697       ** root node, the range of leaves scanned can be reduced. Do this. */
   151698       if( iStartBlock && zTerm ){
   151699         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
   151700         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
   151701         if( rc!=SQLITE_OK ) goto finished;
   151702         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
   151703       }
   151704 
   151705       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
   151706           (isPrefix==0 && isScan==0),
   151707           iStartBlock, iLeavesEndBlock,
   151708           iEndBlock, zRoot, nRoot, &pSeg
   151709       );
   151710       if( rc!=SQLITE_OK ) goto finished;
   151711       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   151712     }
   151713   }
   151714 
   151715  finished:
   151716   rc2 = sqlite3_reset(pStmt);
   151717   if( rc==SQLITE_DONE ) rc = rc2;
   151718 
   151719   return rc;
   151720 }
   151721 
   151722 /*
   151723 ** Set up a cursor object for iterating through a full-text index or a
   151724 ** single level therein.
   151725 */
   151726 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
   151727   Fts3Table *p,                   /* FTS3 table handle */
   151728   int iLangid,                    /* Language-id to search */
   151729   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   151730   int iLevel,                     /* Level of segments to scan */
   151731   const char *zTerm,              /* Term to query for */
   151732   int nTerm,                      /* Size of zTerm in bytes */
   151733   int isPrefix,                   /* True for a prefix search */
   151734   int isScan,                     /* True to scan from zTerm to EOF */
   151735   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
   151736 ){
   151737   assert( iIndex>=0 && iIndex<p->nIndex );
   151738   assert( iLevel==FTS3_SEGCURSOR_ALL
   151739       ||  iLevel==FTS3_SEGCURSOR_PENDING
   151740       ||  iLevel>=0
   151741   );
   151742   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   151743   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
   151744   assert( isPrefix==0 || isScan==0 );
   151745 
   151746   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
   151747   return fts3SegReaderCursor(
   151748       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
   151749   );
   151750 }
   151751 
   151752 /*
   151753 ** In addition to its current configuration, have the Fts3MultiSegReader
   151754 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
   151755 **
   151756 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   151757 */
   151758 static int fts3SegReaderCursorAddZero(
   151759   Fts3Table *p,                   /* FTS virtual table handle */
   151760   int iLangid,
   151761   const char *zTerm,              /* Term to scan doclist of */
   151762   int nTerm,                      /* Number of bytes in zTerm */
   151763   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
   151764 ){
   151765   return fts3SegReaderCursor(p,
   151766       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
   151767   );
   151768 }
   151769 
   151770 /*
   151771 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
   151772 ** if isPrefix is true, to scan the doclist for all terms for which
   151773 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
   151774 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
   151775 ** an SQLite error code.
   151776 **
   151777 ** It is the responsibility of the caller to free this object by eventually
   151778 ** passing it to fts3SegReaderCursorFree()
   151779 **
   151780 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   151781 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
   151782 */
   151783 static int fts3TermSegReaderCursor(
   151784   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
   151785   const char *zTerm,              /* Term to query for */
   151786   int nTerm,                      /* Size of zTerm in bytes */
   151787   int isPrefix,                   /* True for a prefix search */
   151788   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
   151789 ){
   151790   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
   151791   int rc = SQLITE_NOMEM;          /* Return code */
   151792 
   151793   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
   151794   if( pSegcsr ){
   151795     int i;
   151796     int bFound = 0;               /* True once an index has been found */
   151797     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   151798 
   151799     if( isPrefix ){
   151800       for(i=1; bFound==0 && i<p->nIndex; i++){
   151801         if( p->aIndex[i].nPrefix==nTerm ){
   151802           bFound = 1;
   151803           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   151804               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
   151805           );
   151806           pSegcsr->bLookup = 1;
   151807         }
   151808       }
   151809 
   151810       for(i=1; bFound==0 && i<p->nIndex; i++){
   151811         if( p->aIndex[i].nPrefix==nTerm+1 ){
   151812           bFound = 1;
   151813           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   151814               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
   151815           );
   151816           if( rc==SQLITE_OK ){
   151817             rc = fts3SegReaderCursorAddZero(
   151818                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
   151819             );
   151820           }
   151821         }
   151822       }
   151823     }
   151824 
   151825     if( bFound==0 ){
   151826       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   151827           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
   151828       );
   151829       pSegcsr->bLookup = !isPrefix;
   151830     }
   151831   }
   151832 
   151833   *ppSegcsr = pSegcsr;
   151834   return rc;
   151835 }
   151836 
   151837 /*
   151838 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
   151839 */
   151840 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
   151841   sqlite3Fts3SegReaderFinish(pSegcsr);
   151842   sqlite3_free(pSegcsr);
   151843 }
   151844 
   151845 /*
   151846 ** This function retrieves the doclist for the specified term (or term
   151847 ** prefix) from the database.
   151848 */
   151849 static int fts3TermSelect(
   151850   Fts3Table *p,                   /* Virtual table handle */
   151851   Fts3PhraseToken *pTok,          /* Token to query for */
   151852   int iColumn,                    /* Column to query (or -ve for all columns) */
   151853   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
   151854   char **ppOut                    /* OUT: Malloced result buffer */
   151855 ){
   151856   int rc;                         /* Return code */
   151857   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
   151858   TermSelect tsc;                 /* Object for pair-wise doclist merging */
   151859   Fts3SegFilter filter;           /* Segment term filter configuration */
   151860 
   151861   pSegcsr = pTok->pSegcsr;
   151862   memset(&tsc, 0, sizeof(TermSelect));
   151863 
   151864   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
   151865         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
   151866         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
   151867         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
   151868   filter.iCol = iColumn;
   151869   filter.zTerm = pTok->z;
   151870   filter.nTerm = pTok->n;
   151871 
   151872   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
   151873   while( SQLITE_OK==rc
   151874       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
   151875   ){
   151876     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
   151877   }
   151878 
   151879   if( rc==SQLITE_OK ){
   151880     rc = fts3TermSelectFinishMerge(p, &tsc);
   151881   }
   151882   if( rc==SQLITE_OK ){
   151883     *ppOut = tsc.aaOutput[0];
   151884     *pnOut = tsc.anOutput[0];
   151885   }else{
   151886     int i;
   151887     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
   151888       sqlite3_free(tsc.aaOutput[i]);
   151889     }
   151890   }
   151891 
   151892   fts3SegReaderCursorFree(pSegcsr);
   151893   pTok->pSegcsr = 0;
   151894   return rc;
   151895 }
   151896 
   151897 /*
   151898 ** This function counts the total number of docids in the doclist stored
   151899 ** in buffer aList[], size nList bytes.
   151900 **
   151901 ** If the isPoslist argument is true, then it is assumed that the doclist
   151902 ** contains a position-list following each docid. Otherwise, it is assumed
   151903 ** that the doclist is simply a list of docids stored as delta encoded
   151904 ** varints.
   151905 */
   151906 static int fts3DoclistCountDocids(char *aList, int nList){
   151907   int nDoc = 0;                   /* Return value */
   151908   if( aList ){
   151909     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
   151910     char *p = aList;              /* Cursor */
   151911     while( p<aEnd ){
   151912       nDoc++;
   151913       while( (*p++)&0x80 );     /* Skip docid varint */
   151914       fts3PoslistCopy(0, &p);   /* Skip over position list */
   151915     }
   151916   }
   151917 
   151918   return nDoc;
   151919 }
   151920 
   151921 /*
   151922 ** Advance the cursor to the next row in the %_content table that
   151923 ** matches the search criteria.  For a MATCH search, this will be
   151924 ** the next row that matches. For a full-table scan, this will be
   151925 ** simply the next row in the %_content table.  For a docid lookup,
   151926 ** this routine simply sets the EOF flag.
   151927 **
   151928 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
   151929 ** even if we reach end-of-file.  The fts3EofMethod() will be called
   151930 ** subsequently to determine whether or not an EOF was hit.
   151931 */
   151932 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   151933   int rc;
   151934   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   151935   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
   151936     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
   151937       pCsr->isEof = 1;
   151938       rc = sqlite3_reset(pCsr->pStmt);
   151939     }else{
   151940       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
   151941       rc = SQLITE_OK;
   151942     }
   151943   }else{
   151944     rc = fts3EvalNext((Fts3Cursor *)pCursor);
   151945   }
   151946   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   151947   return rc;
   151948 }
   151949 
   151950 /*
   151951 ** The following are copied from sqliteInt.h.
   151952 **
   151953 ** Constants for the largest and smallest possible 64-bit signed integers.
   151954 ** These macros are designed to work correctly on both 32-bit and 64-bit
   151955 ** compilers.
   151956 */
   151957 #ifndef SQLITE_AMALGAMATION
   151958 # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
   151959 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
   151960 #endif
   151961 
   151962 /*
   151963 ** If the numeric type of argument pVal is "integer", then return it
   151964 ** converted to a 64-bit signed integer. Otherwise, return a copy of
   151965 ** the second parameter, iDefault.
   151966 */
   151967 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
   151968   if( pVal ){
   151969     int eType = sqlite3_value_numeric_type(pVal);
   151970     if( eType==SQLITE_INTEGER ){
   151971       return sqlite3_value_int64(pVal);
   151972     }
   151973   }
   151974   return iDefault;
   151975 }
   151976 
   151977 /*
   151978 ** This is the xFilter interface for the virtual table.  See
   151979 ** the virtual table xFilter method documentation for additional
   151980 ** information.
   151981 **
   151982 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
   151983 ** the %_content table.
   151984 **
   151985 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
   151986 ** in the %_content table.
   151987 **
   151988 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
   151989 ** column on the left-hand side of the MATCH operator is column
   151990 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
   151991 ** side of the MATCH operator.
   151992 */
   151993 static int fts3FilterMethod(
   151994   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   151995   int idxNum,                     /* Strategy index */
   151996   const char *idxStr,             /* Unused */
   151997   int nVal,                       /* Number of elements in apVal */
   151998   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   151999 ){
   152000   int rc = SQLITE_OK;
   152001   char *zSql;                     /* SQL statement used to access %_content */
   152002   int eSearch;
   152003   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   152004   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   152005 
   152006   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
   152007   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
   152008   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
   152009   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
   152010   int iIdx;
   152011 
   152012   UNUSED_PARAMETER(idxStr);
   152013   UNUSED_PARAMETER(nVal);
   152014 
   152015   eSearch = (idxNum & 0x0000FFFF);
   152016   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   152017   assert( p->pSegments==0 );
   152018 
   152019   /* Collect arguments into local variables */
   152020   iIdx = 0;
   152021   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
   152022   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
   152023   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
   152024   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
   152025   assert( iIdx==nVal );
   152026 
   152027   /* In case the cursor has been used before, clear it now. */
   152028   fts3ClearCursor(pCsr);
   152029 
   152030   /* Set the lower and upper bounds on docids to return */
   152031   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
   152032   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
   152033 
   152034   if( idxStr ){
   152035     pCsr->bDesc = (idxStr[0]=='D');
   152036   }else{
   152037     pCsr->bDesc = p->bDescIdx;
   152038   }
   152039   pCsr->eSearch = (i16)eSearch;
   152040 
   152041   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
   152042     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
   152043     const char *zQuery = (const char *)sqlite3_value_text(pCons);
   152044 
   152045     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
   152046       return SQLITE_NOMEM;
   152047     }
   152048 
   152049     pCsr->iLangid = 0;
   152050     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
   152051 
   152052     assert( p->base.zErrMsg==0 );
   152053     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
   152054         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
   152055         &p->base.zErrMsg
   152056     );
   152057     if( rc!=SQLITE_OK ){
   152058       return rc;
   152059     }
   152060 
   152061     rc = fts3EvalStart(pCsr);
   152062     sqlite3Fts3SegmentsClose(p);
   152063     if( rc!=SQLITE_OK ) return rc;
   152064     pCsr->pNextId = pCsr->aDoclist;
   152065     pCsr->iPrevId = 0;
   152066   }
   152067 
   152068   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
   152069   ** statement loops through all rows of the %_content table. For a
   152070   ** full-text query or docid lookup, the statement retrieves a single
   152071   ** row by docid.
   152072   */
   152073   if( eSearch==FTS3_FULLSCAN_SEARCH ){
   152074     if( pDocidGe || pDocidLe ){
   152075       zSql = sqlite3_mprintf(
   152076           "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
   152077           p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
   152078           (pCsr->bDesc ? "DESC" : "ASC")
   152079       );
   152080     }else{
   152081       zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
   152082           p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
   152083       );
   152084     }
   152085     if( zSql ){
   152086       rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
   152087       sqlite3_free(zSql);
   152088     }else{
   152089       rc = SQLITE_NOMEM;
   152090     }
   152091   }else if( eSearch==FTS3_DOCID_SEARCH ){
   152092     rc = fts3CursorSeekStmt(pCsr);
   152093     if( rc==SQLITE_OK ){
   152094       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
   152095     }
   152096   }
   152097   if( rc!=SQLITE_OK ) return rc;
   152098 
   152099   return fts3NextMethod(pCursor);
   152100 }
   152101 
   152102 /*
   152103 ** This is the xEof method of the virtual table. SQLite calls this
   152104 ** routine to find out if it has reached the end of a result set.
   152105 */
   152106 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   152107   Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
   152108   if( pCsr->isEof ){
   152109     fts3ClearCursor(pCsr);
   152110     pCsr->isEof = 1;
   152111   }
   152112   return pCsr->isEof;
   152113 }
   152114 
   152115 /*
   152116 ** This is the xRowid method. The SQLite core calls this routine to
   152117 ** retrieve the rowid for the current row of the result set. fts3
   152118 ** exposes %_content.docid as the rowid for the virtual table. The
   152119 ** rowid should be written to *pRowid.
   152120 */
   152121 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   152122   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   152123   *pRowid = pCsr->iPrevId;
   152124   return SQLITE_OK;
   152125 }
   152126 
   152127 /*
   152128 ** This is the xColumn method, called by SQLite to request a value from
   152129 ** the row that the supplied cursor currently points to.
   152130 **
   152131 ** If:
   152132 **
   152133 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
   152134 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
   152135 **   (iCol == p->nColumn+1) -> Docid column
   152136 **   (iCol == p->nColumn+2) -> Langid column
   152137 */
   152138 static int fts3ColumnMethod(
   152139   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   152140   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   152141   int iCol                        /* Index of column to read value from */
   152142 ){
   152143   int rc = SQLITE_OK;             /* Return Code */
   152144   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   152145   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   152146 
   152147   /* The column value supplied by SQLite must be in range. */
   152148   assert( iCol>=0 && iCol<=p->nColumn+2 );
   152149 
   152150   switch( iCol-p->nColumn ){
   152151     case 0:
   152152       /* The special 'table-name' column */
   152153       sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
   152154       break;
   152155 
   152156     case 1:
   152157       /* The docid column */
   152158       sqlite3_result_int64(pCtx, pCsr->iPrevId);
   152159       break;
   152160 
   152161     case 2:
   152162       if( pCsr->pExpr ){
   152163         sqlite3_result_int64(pCtx, pCsr->iLangid);
   152164         break;
   152165       }else if( p->zLanguageid==0 ){
   152166         sqlite3_result_int(pCtx, 0);
   152167         break;
   152168       }else{
   152169         iCol = p->nColumn;
   152170         /* fall-through */
   152171       }
   152172 
   152173     default:
   152174       /* A user column. Or, if this is a full-table scan, possibly the
   152175       ** language-id column. Seek the cursor. */
   152176       rc = fts3CursorSeek(0, pCsr);
   152177       if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
   152178         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
   152179       }
   152180       break;
   152181   }
   152182 
   152183   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   152184   return rc;
   152185 }
   152186 
   152187 /*
   152188 ** This function is the implementation of the xUpdate callback used by
   152189 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   152190 ** inserted, updated or deleted.
   152191 */
   152192 static int fts3UpdateMethod(
   152193   sqlite3_vtab *pVtab,            /* Virtual table handle */
   152194   int nArg,                       /* Size of argument array */
   152195   sqlite3_value **apVal,          /* Array of arguments */
   152196   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   152197 ){
   152198   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
   152199 }
   152200 
   152201 /*
   152202 ** Implementation of xSync() method. Flush the contents of the pending-terms
   152203 ** hash-table to the database.
   152204 */
   152205 static int fts3SyncMethod(sqlite3_vtab *pVtab){
   152206 
   152207   /* Following an incremental-merge operation, assuming that the input
   152208   ** segments are not completely consumed (the usual case), they are updated
   152209   ** in place to remove the entries that have already been merged. This
   152210   ** involves updating the leaf block that contains the smallest unmerged
   152211   ** entry and each block (if any) between the leaf and the root node. So
   152212   ** if the height of the input segment b-trees is N, and input segments
   152213   ** are merged eight at a time, updating the input segments at the end
   152214   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
   152215   ** small - often between 0 and 2. So the overhead of the incremental
   152216   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
   152217   ** dwarfing the actual productive work accomplished, the incremental merge
   152218   ** is only attempted if it will write at least 64 leaf blocks. Hence
   152219   ** nMinMerge.
   152220   **
   152221   ** Of course, updating the input segments also involves deleting a bunch
   152222   ** of blocks from the segments table. But this is not considered overhead
   152223   ** as it would also be required by a crisis-merge that used the same input
   152224   ** segments.
   152225   */
   152226   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
   152227 
   152228   Fts3Table *p = (Fts3Table*)pVtab;
   152229   int rc;
   152230   i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
   152231 
   152232   rc = sqlite3Fts3PendingTermsFlush(p);
   152233   if( rc==SQLITE_OK
   152234    && p->nLeafAdd>(nMinMerge/16)
   152235    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
   152236   ){
   152237     int mxLevel = 0;              /* Maximum relative level value in db */
   152238     int A;                        /* Incr-merge parameter A */
   152239 
   152240     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
   152241     assert( rc==SQLITE_OK || mxLevel==0 );
   152242     A = p->nLeafAdd * mxLevel;
   152243     A += (A/2);
   152244     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
   152245   }
   152246   sqlite3Fts3SegmentsClose(p);
   152247   sqlite3_set_last_insert_rowid(p->db, iLastRowid);
   152248   return rc;
   152249 }
   152250 
   152251 /*
   152252 ** If it is currently unknown whether or not the FTS table has an %_stat
   152253 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
   152254 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
   152255 ** if an error occurs.
   152256 */
   152257 static int fts3SetHasStat(Fts3Table *p){
   152258   int rc = SQLITE_OK;
   152259   if( p->bHasStat==2 ){
   152260     char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
   152261     if( zTbl ){
   152262       int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
   152263       sqlite3_free(zTbl);
   152264       p->bHasStat = (res==SQLITE_OK);
   152265     }else{
   152266       rc = SQLITE_NOMEM;
   152267     }
   152268   }
   152269   return rc;
   152270 }
   152271 
   152272 /*
   152273 ** Implementation of xBegin() method.
   152274 */
   152275 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   152276   Fts3Table *p = (Fts3Table*)pVtab;
   152277   UNUSED_PARAMETER(pVtab);
   152278   assert( p->pSegments==0 );
   152279   assert( p->nPendingData==0 );
   152280   assert( p->inTransaction!=1 );
   152281   TESTONLY( p->inTransaction = 1 );
   152282   TESTONLY( p->mxSavepoint = -1; );
   152283   p->nLeafAdd = 0;
   152284   return fts3SetHasStat(p);
   152285 }
   152286 
   152287 /*
   152288 ** Implementation of xCommit() method. This is a no-op. The contents of
   152289 ** the pending-terms hash-table have already been flushed into the database
   152290 ** by fts3SyncMethod().
   152291 */
   152292 static int fts3CommitMethod(sqlite3_vtab *pVtab){
   152293   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   152294   UNUSED_PARAMETER(pVtab);
   152295   assert( p->nPendingData==0 );
   152296   assert( p->inTransaction!=0 );
   152297   assert( p->pSegments==0 );
   152298   TESTONLY( p->inTransaction = 0 );
   152299   TESTONLY( p->mxSavepoint = -1; );
   152300   return SQLITE_OK;
   152301 }
   152302 
   152303 /*
   152304 ** Implementation of xRollback(). Discard the contents of the pending-terms
   152305 ** hash-table. Any changes made to the database are reverted by SQLite.
   152306 */
   152307 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
   152308   Fts3Table *p = (Fts3Table*)pVtab;
   152309   sqlite3Fts3PendingTermsClear(p);
   152310   assert( p->inTransaction!=0 );
   152311   TESTONLY( p->inTransaction = 0 );
   152312   TESTONLY( p->mxSavepoint = -1; );
   152313   return SQLITE_OK;
   152314 }
   152315 
   152316 /*
   152317 ** When called, *ppPoslist must point to the byte immediately following the
   152318 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
   152319 ** moves *ppPoslist so that it instead points to the first byte of the
   152320 ** same position list.
   152321 */
   152322 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
   152323   char *p = &(*ppPoslist)[-2];
   152324   char c = 0;
   152325 
   152326   /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
   152327   while( p>pStart && (c=*p--)==0 );
   152328 
   152329   /* Search backwards for a varint with value zero (the end of the previous
   152330   ** poslist). This is an 0x00 byte preceded by some byte that does not
   152331   ** have the 0x80 bit set.  */
   152332   while( p>pStart && (*p & 0x80) | c ){
   152333     c = *p--;
   152334   }
   152335   assert( p==pStart || c==0 );
   152336 
   152337   /* At this point p points to that preceding byte without the 0x80 bit
   152338   ** set. So to find the start of the poslist, skip forward 2 bytes then
   152339   ** over a varint.
   152340   **
   152341   ** Normally. The other case is that p==pStart and the poslist to return
   152342   ** is the first in the doclist. In this case do not skip forward 2 bytes.
   152343   ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
   152344   ** is required for cases where the first byte of a doclist and the
   152345   ** doclist is empty. For example, if the first docid is 10, a doclist
   152346   ** that begins with:
   152347   **
   152348   **   0x0A 0x00 <next docid delta varint>
   152349   */
   152350   if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
   152351   while( *p++&0x80 );
   152352   *ppPoslist = p;
   152353 }
   152354 
   152355 /*
   152356 ** Helper function used by the implementation of the overloaded snippet(),
   152357 ** offsets() and optimize() SQL functions.
   152358 **
   152359 ** If the value passed as the third argument is a blob of size
   152360 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
   152361 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
   152362 ** message is written to context pContext and SQLITE_ERROR returned. The
   152363 ** string passed via zFunc is used as part of the error message.
   152364 */
   152365 static int fts3FunctionArg(
   152366   sqlite3_context *pContext,      /* SQL function call context */
   152367   const char *zFunc,              /* Function name */
   152368   sqlite3_value *pVal,            /* argv[0] passed to function */
   152369   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
   152370 ){
   152371   int rc;
   152372   *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
   152373   if( (*ppCsr)!=0 ){
   152374     rc = SQLITE_OK;
   152375   }else{
   152376     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
   152377     sqlite3_result_error(pContext, zErr, -1);
   152378     sqlite3_free(zErr);
   152379     rc = SQLITE_ERROR;
   152380   }
   152381   return rc;
   152382 }
   152383 
   152384 /*
   152385 ** Implementation of the snippet() function for FTS3
   152386 */
   152387 static void fts3SnippetFunc(
   152388   sqlite3_context *pContext,      /* SQLite function call context */
   152389   int nVal,                       /* Size of apVal[] array */
   152390   sqlite3_value **apVal           /* Array of arguments */
   152391 ){
   152392   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   152393   const char *zStart = "<b>";
   152394   const char *zEnd = "</b>";
   152395   const char *zEllipsis = "<b>...</b>";
   152396   int iCol = -1;
   152397   int nToken = 15;                /* Default number of tokens in snippet */
   152398 
   152399   /* There must be at least one argument passed to this function (otherwise
   152400   ** the non-overloaded version would have been called instead of this one).
   152401   */
   152402   assert( nVal>=1 );
   152403 
   152404   if( nVal>6 ){
   152405     sqlite3_result_error(pContext,
   152406         "wrong number of arguments to function snippet()", -1);
   152407     return;
   152408   }
   152409   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   152410 
   152411   switch( nVal ){
   152412     case 6: nToken = sqlite3_value_int(apVal[5]);
   152413     case 5: iCol = sqlite3_value_int(apVal[4]);
   152414     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   152415     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   152416     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   152417   }
   152418   if( !zEllipsis || !zEnd || !zStart ){
   152419     sqlite3_result_error_nomem(pContext);
   152420   }else if( nToken==0 ){
   152421     sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
   152422   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   152423     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
   152424   }
   152425 }
   152426 
   152427 /*
   152428 ** Implementation of the offsets() function for FTS3
   152429 */
   152430 static void fts3OffsetsFunc(
   152431   sqlite3_context *pContext,      /* SQLite function call context */
   152432   int nVal,                       /* Size of argument array */
   152433   sqlite3_value **apVal           /* Array of arguments */
   152434 ){
   152435   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   152436 
   152437   UNUSED_PARAMETER(nVal);
   152438 
   152439   assert( nVal==1 );
   152440   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
   152441   assert( pCsr );
   152442   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   152443     sqlite3Fts3Offsets(pContext, pCsr);
   152444   }
   152445 }
   152446 
   152447 /*
   152448 ** Implementation of the special optimize() function for FTS3. This
   152449 ** function merges all segments in the database to a single segment.
   152450 ** Example usage is:
   152451 **
   152452 **   SELECT optimize(t) FROM t LIMIT 1;
   152453 **
   152454 ** where 't' is the name of an FTS3 table.
   152455 */
   152456 static void fts3OptimizeFunc(
   152457   sqlite3_context *pContext,      /* SQLite function call context */
   152458   int nVal,                       /* Size of argument array */
   152459   sqlite3_value **apVal           /* Array of arguments */
   152460 ){
   152461   int rc;                         /* Return code */
   152462   Fts3Table *p;                   /* Virtual table handle */
   152463   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
   152464 
   152465   UNUSED_PARAMETER(nVal);
   152466 
   152467   assert( nVal==1 );
   152468   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
   152469   p = (Fts3Table *)pCursor->base.pVtab;
   152470   assert( p );
   152471 
   152472   rc = sqlite3Fts3Optimize(p);
   152473 
   152474   switch( rc ){
   152475     case SQLITE_OK:
   152476       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
   152477       break;
   152478     case SQLITE_DONE:
   152479       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
   152480       break;
   152481     default:
   152482       sqlite3_result_error_code(pContext, rc);
   152483       break;
   152484   }
   152485 }
   152486 
   152487 /*
   152488 ** Implementation of the matchinfo() function for FTS3
   152489 */
   152490 static void fts3MatchinfoFunc(
   152491   sqlite3_context *pContext,      /* SQLite function call context */
   152492   int nVal,                       /* Size of argument array */
   152493   sqlite3_value **apVal           /* Array of arguments */
   152494 ){
   152495   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   152496   assert( nVal==1 || nVal==2 );
   152497   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
   152498     const char *zArg = 0;
   152499     if( nVal>1 ){
   152500       zArg = (const char *)sqlite3_value_text(apVal[1]);
   152501     }
   152502     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
   152503   }
   152504 }
   152505 
   152506 /*
   152507 ** This routine implements the xFindFunction method for the FTS3
   152508 ** virtual table.
   152509 */
   152510 static int fts3FindFunctionMethod(
   152511   sqlite3_vtab *pVtab,            /* Virtual table handle */
   152512   int nArg,                       /* Number of SQL function arguments */
   152513   const char *zName,              /* Name of SQL function */
   152514   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   152515   void **ppArg                    /* Unused */
   152516 ){
   152517   struct Overloaded {
   152518     const char *zName;
   152519     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   152520   } aOverload[] = {
   152521     { "snippet", fts3SnippetFunc },
   152522     { "offsets", fts3OffsetsFunc },
   152523     { "optimize", fts3OptimizeFunc },
   152524     { "matchinfo", fts3MatchinfoFunc },
   152525   };
   152526   int i;                          /* Iterator variable */
   152527 
   152528   UNUSED_PARAMETER(pVtab);
   152529   UNUSED_PARAMETER(nArg);
   152530   UNUSED_PARAMETER(ppArg);
   152531 
   152532   for(i=0; i<SizeofArray(aOverload); i++){
   152533     if( strcmp(zName, aOverload[i].zName)==0 ){
   152534       *pxFunc = aOverload[i].xFunc;
   152535       return 1;
   152536     }
   152537   }
   152538 
   152539   /* No function of the specified name was found. Return 0. */
   152540   return 0;
   152541 }
   152542 
   152543 /*
   152544 ** Implementation of FTS3 xRename method. Rename an fts3 table.
   152545 */
   152546 static int fts3RenameMethod(
   152547   sqlite3_vtab *pVtab,            /* Virtual table handle */
   152548   const char *zName               /* New name of table */
   152549 ){
   152550   Fts3Table *p = (Fts3Table *)pVtab;
   152551   sqlite3 *db = p->db;            /* Database connection */
   152552   int rc;                         /* Return Code */
   152553 
   152554   /* At this point it must be known if the %_stat table exists or not.
   152555   ** So bHasStat may not be 2.  */
   152556   rc = fts3SetHasStat(p);
   152557 
   152558   /* As it happens, the pending terms table is always empty here. This is
   152559   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
   152560   ** always opens a savepoint transaction. And the xSavepoint() method
   152561   ** flushes the pending terms table. But leave the (no-op) call to
   152562   ** PendingTermsFlush() in in case that changes.
   152563   */
   152564   assert( p->nPendingData==0 );
   152565   if( rc==SQLITE_OK ){
   152566     rc = sqlite3Fts3PendingTermsFlush(p);
   152567   }
   152568 
   152569   if( p->zContentTbl==0 ){
   152570     fts3DbExec(&rc, db,
   152571       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
   152572       p->zDb, p->zName, zName
   152573     );
   152574   }
   152575 
   152576   if( p->bHasDocsize ){
   152577     fts3DbExec(&rc, db,
   152578       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
   152579       p->zDb, p->zName, zName
   152580     );
   152581   }
   152582   if( p->bHasStat ){
   152583     fts3DbExec(&rc, db,
   152584       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
   152585       p->zDb, p->zName, zName
   152586     );
   152587   }
   152588   fts3DbExec(&rc, db,
   152589     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
   152590     p->zDb, p->zName, zName
   152591   );
   152592   fts3DbExec(&rc, db,
   152593     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
   152594     p->zDb, p->zName, zName
   152595   );
   152596   return rc;
   152597 }
   152598 
   152599 /*
   152600 ** The xSavepoint() method.
   152601 **
   152602 ** Flush the contents of the pending-terms table to disk.
   152603 */
   152604 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
   152605   int rc = SQLITE_OK;
   152606   UNUSED_PARAMETER(iSavepoint);
   152607   assert( ((Fts3Table *)pVtab)->inTransaction );
   152608   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
   152609   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
   152610   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
   152611     rc = fts3SyncMethod(pVtab);
   152612   }
   152613   return rc;
   152614 }
   152615 
   152616 /*
   152617 ** The xRelease() method.
   152618 **
   152619 ** This is a no-op.
   152620 */
   152621 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
   152622   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   152623   UNUSED_PARAMETER(iSavepoint);
   152624   UNUSED_PARAMETER(pVtab);
   152625   assert( p->inTransaction );
   152626   assert( p->mxSavepoint >= iSavepoint );
   152627   TESTONLY( p->mxSavepoint = iSavepoint-1 );
   152628   return SQLITE_OK;
   152629 }
   152630 
   152631 /*
   152632 ** The xRollbackTo() method.
   152633 **
   152634 ** Discard the contents of the pending terms table.
   152635 */
   152636 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
   152637   Fts3Table *p = (Fts3Table*)pVtab;
   152638   UNUSED_PARAMETER(iSavepoint);
   152639   assert( p->inTransaction );
   152640   assert( p->mxSavepoint >= iSavepoint );
   152641   TESTONLY( p->mxSavepoint = iSavepoint );
   152642   sqlite3Fts3PendingTermsClear(p);
   152643   return SQLITE_OK;
   152644 }
   152645 
   152646 static const sqlite3_module fts3Module = {
   152647   /* iVersion      */ 2,
   152648   /* xCreate       */ fts3CreateMethod,
   152649   /* xConnect      */ fts3ConnectMethod,
   152650   /* xBestIndex    */ fts3BestIndexMethod,
   152651   /* xDisconnect   */ fts3DisconnectMethod,
   152652   /* xDestroy      */ fts3DestroyMethod,
   152653   /* xOpen         */ fts3OpenMethod,
   152654   /* xClose        */ fts3CloseMethod,
   152655   /* xFilter       */ fts3FilterMethod,
   152656   /* xNext         */ fts3NextMethod,
   152657   /* xEof          */ fts3EofMethod,
   152658   /* xColumn       */ fts3ColumnMethod,
   152659   /* xRowid        */ fts3RowidMethod,
   152660   /* xUpdate       */ fts3UpdateMethod,
   152661   /* xBegin        */ fts3BeginMethod,
   152662   /* xSync         */ fts3SyncMethod,
   152663   /* xCommit       */ fts3CommitMethod,
   152664   /* xRollback     */ fts3RollbackMethod,
   152665   /* xFindFunction */ fts3FindFunctionMethod,
   152666   /* xRename */       fts3RenameMethod,
   152667   /* xSavepoint    */ fts3SavepointMethod,
   152668   /* xRelease      */ fts3ReleaseMethod,
   152669   /* xRollbackTo   */ fts3RollbackToMethod,
   152670 };
   152671 
   152672 /*
   152673 ** This function is registered as the module destructor (called when an
   152674 ** FTS3 enabled database connection is closed). It frees the memory
   152675 ** allocated for the tokenizer hash table.
   152676 */
   152677 static void hashDestroy(void *p){
   152678   Fts3Hash *pHash = (Fts3Hash *)p;
   152679   sqlite3Fts3HashClear(pHash);
   152680   sqlite3_free(pHash);
   152681 }
   152682 
   152683 /*
   152684 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
   152685 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
   152686 ** respectively. The following three forward declarations are for functions
   152687 ** declared in these files used to retrieve the respective implementations.
   152688 **
   152689 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
   152690 ** to by the argument to point to the "simple" tokenizer implementation.
   152691 ** And so on.
   152692 */
   152693 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   152694 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   152695 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   152696 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
   152697 #endif
   152698 #ifdef SQLITE_ENABLE_ICU
   152699 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   152700 #endif
   152701 
   152702 /*
   152703 ** Initialize the fts3 extension. If this extension is built as part
   152704 ** of the sqlite library, then this function is called directly by
   152705 ** SQLite. If fts3 is built as a dynamically loadable extension, this
   152706 ** function is called by the sqlite3_extension_init() entry point.
   152707 */
   152708 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   152709   int rc = SQLITE_OK;
   152710   Fts3Hash *pHash = 0;
   152711   const sqlite3_tokenizer_module *pSimple = 0;
   152712   const sqlite3_tokenizer_module *pPorter = 0;
   152713 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   152714   const sqlite3_tokenizer_module *pUnicode = 0;
   152715 #endif
   152716 
   152717 #ifdef SQLITE_ENABLE_ICU
   152718   const sqlite3_tokenizer_module *pIcu = 0;
   152719   sqlite3Fts3IcuTokenizerModule(&pIcu);
   152720 #endif
   152721 
   152722 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   152723   sqlite3Fts3UnicodeTokenizer(&pUnicode);
   152724 #endif
   152725 
   152726 #ifdef SQLITE_TEST
   152727   rc = sqlite3Fts3InitTerm(db);
   152728   if( rc!=SQLITE_OK ) return rc;
   152729 #endif
   152730 
   152731   rc = sqlite3Fts3InitAux(db);
   152732   if( rc!=SQLITE_OK ) return rc;
   152733 
   152734   sqlite3Fts3SimpleTokenizerModule(&pSimple);
   152735   sqlite3Fts3PorterTokenizerModule(&pPorter);
   152736 
   152737   /* Allocate and initialize the hash-table used to store tokenizers. */
   152738   pHash = sqlite3_malloc(sizeof(Fts3Hash));
   152739   if( !pHash ){
   152740     rc = SQLITE_NOMEM;
   152741   }else{
   152742     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   152743   }
   152744 
   152745   /* Load the built-in tokenizers into the hash table */
   152746   if( rc==SQLITE_OK ){
   152747     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
   152748      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
   152749 
   152750 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   152751      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
   152752 #endif
   152753 #ifdef SQLITE_ENABLE_ICU
   152754      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
   152755 #endif
   152756     ){
   152757       rc = SQLITE_NOMEM;
   152758     }
   152759   }
   152760 
   152761 #ifdef SQLITE_TEST
   152762   if( rc==SQLITE_OK ){
   152763     rc = sqlite3Fts3ExprInitTestInterface(db);
   152764   }
   152765 #endif
   152766 
   152767   /* Create the virtual table wrapper around the hash-table and overload
   152768   ** the four scalar functions. If this is successful, register the
   152769   ** module with sqlite.
   152770   */
   152771   if( SQLITE_OK==rc
   152772    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   152773    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   152774    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
   152775    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
   152776    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
   152777    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   152778   ){
   152779     rc = sqlite3_create_module_v2(
   152780         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
   152781     );
   152782     if( rc==SQLITE_OK ){
   152783       rc = sqlite3_create_module_v2(
   152784           db, "fts4", &fts3Module, (void *)pHash, 0
   152785       );
   152786     }
   152787     if( rc==SQLITE_OK ){
   152788       rc = sqlite3Fts3InitTok(db, (void *)pHash);
   152789     }
   152790     return rc;
   152791   }
   152792 
   152793 
   152794   /* An error has occurred. Delete the hash table and return the error code. */
   152795   assert( rc!=SQLITE_OK );
   152796   if( pHash ){
   152797     sqlite3Fts3HashClear(pHash);
   152798     sqlite3_free(pHash);
   152799   }
   152800   return rc;
   152801 }
   152802 
   152803 /*
   152804 ** Allocate an Fts3MultiSegReader for each token in the expression headed
   152805 ** by pExpr.
   152806 **
   152807 ** An Fts3SegReader object is a cursor that can seek or scan a range of
   152808 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
   152809 ** Fts3SegReader objects internally to provide an interface to seek or scan
   152810 ** within the union of all segments of a b-tree. Hence the name.
   152811 **
   152812 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
   152813 ** segment b-tree (if the term is not a prefix or it is a prefix for which
   152814 ** there exists prefix b-tree of the right length) then it may be traversed
   152815 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
   152816 ** doclist and then traversed.
   152817 */
   152818 static void fts3EvalAllocateReaders(
   152819   Fts3Cursor *pCsr,               /* FTS cursor handle */
   152820   Fts3Expr *pExpr,                /* Allocate readers for this expression */
   152821   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
   152822   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
   152823   int *pRc                        /* IN/OUT: Error code */
   152824 ){
   152825   if( pExpr && SQLITE_OK==*pRc ){
   152826     if( pExpr->eType==FTSQUERY_PHRASE ){
   152827       int i;
   152828       int nToken = pExpr->pPhrase->nToken;
   152829       *pnToken += nToken;
   152830       for(i=0; i<nToken; i++){
   152831         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
   152832         int rc = fts3TermSegReaderCursor(pCsr,
   152833             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
   152834         );
   152835         if( rc!=SQLITE_OK ){
   152836           *pRc = rc;
   152837           return;
   152838         }
   152839       }
   152840       assert( pExpr->pPhrase->iDoclistToken==0 );
   152841       pExpr->pPhrase->iDoclistToken = -1;
   152842     }else{
   152843       *pnOr += (pExpr->eType==FTSQUERY_OR);
   152844       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
   152845       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
   152846     }
   152847   }
   152848 }
   152849 
   152850 /*
   152851 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
   152852 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
   152853 **
   152854 ** This function assumes that pList points to a buffer allocated using
   152855 ** sqlite3_malloc(). This function takes responsibility for eventually
   152856 ** freeing the buffer.
   152857 **
   152858 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
   152859 */
   152860 static int fts3EvalPhraseMergeToken(
   152861   Fts3Table *pTab,                /* FTS Table pointer */
   152862   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
   152863   int iToken,                     /* Token pList/nList corresponds to */
   152864   char *pList,                    /* Pointer to doclist */
   152865   int nList                       /* Number of bytes in pList */
   152866 ){
   152867   int rc = SQLITE_OK;
   152868   assert( iToken!=p->iDoclistToken );
   152869 
   152870   if( pList==0 ){
   152871     sqlite3_free(p->doclist.aAll);
   152872     p->doclist.aAll = 0;
   152873     p->doclist.nAll = 0;
   152874   }
   152875 
   152876   else if( p->iDoclistToken<0 ){
   152877     p->doclist.aAll = pList;
   152878     p->doclist.nAll = nList;
   152879   }
   152880 
   152881   else if( p->doclist.aAll==0 ){
   152882     sqlite3_free(pList);
   152883   }
   152884 
   152885   else {
   152886     char *pLeft;
   152887     char *pRight;
   152888     int nLeft;
   152889     int nRight;
   152890     int nDiff;
   152891 
   152892     if( p->iDoclistToken<iToken ){
   152893       pLeft = p->doclist.aAll;
   152894       nLeft = p->doclist.nAll;
   152895       pRight = pList;
   152896       nRight = nList;
   152897       nDiff = iToken - p->iDoclistToken;
   152898     }else{
   152899       pRight = p->doclist.aAll;
   152900       nRight = p->doclist.nAll;
   152901       pLeft = pList;
   152902       nLeft = nList;
   152903       nDiff = p->iDoclistToken - iToken;
   152904     }
   152905 
   152906     rc = fts3DoclistPhraseMerge(
   152907         pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
   152908     );
   152909     sqlite3_free(pLeft);
   152910     p->doclist.aAll = pRight;
   152911     p->doclist.nAll = nRight;
   152912   }
   152913 
   152914   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
   152915   return rc;
   152916 }
   152917 
   152918 /*
   152919 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
   152920 ** does not take deferred tokens into account.
   152921 **
   152922 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   152923 */
   152924 static int fts3EvalPhraseLoad(
   152925   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   152926   Fts3Phrase *p                   /* Phrase object */
   152927 ){
   152928   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   152929   int iToken;
   152930   int rc = SQLITE_OK;
   152931 
   152932   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
   152933     Fts3PhraseToken *pToken = &p->aToken[iToken];
   152934     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
   152935 
   152936     if( pToken->pSegcsr ){
   152937       int nThis = 0;
   152938       char *pThis = 0;
   152939       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
   152940       if( rc==SQLITE_OK ){
   152941         rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
   152942       }
   152943     }
   152944     assert( pToken->pSegcsr==0 );
   152945   }
   152946 
   152947   return rc;
   152948 }
   152949 
   152950 /*
   152951 ** This function is called on each phrase after the position lists for
   152952 ** any deferred tokens have been loaded into memory. It updates the phrases
   152953 ** current position list to include only those positions that are really
   152954 ** instances of the phrase (after considering deferred tokens). If this
   152955 ** means that the phrase does not appear in the current row, doclist.pList
   152956 ** and doclist.nList are both zeroed.
   152957 **
   152958 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   152959 */
   152960 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
   152961   int iToken;                     /* Used to iterate through phrase tokens */
   152962   char *aPoslist = 0;             /* Position list for deferred tokens */
   152963   int nPoslist = 0;               /* Number of bytes in aPoslist */
   152964   int iPrev = -1;                 /* Token number of previous deferred token */
   152965 
   152966   assert( pPhrase->doclist.bFreeList==0 );
   152967 
   152968   for(iToken=0; iToken<pPhrase->nToken; iToken++){
   152969     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   152970     Fts3DeferredToken *pDeferred = pToken->pDeferred;
   152971 
   152972     if( pDeferred ){
   152973       char *pList;
   152974       int nList;
   152975       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
   152976       if( rc!=SQLITE_OK ) return rc;
   152977 
   152978       if( pList==0 ){
   152979         sqlite3_free(aPoslist);
   152980         pPhrase->doclist.pList = 0;
   152981         pPhrase->doclist.nList = 0;
   152982         return SQLITE_OK;
   152983 
   152984       }else if( aPoslist==0 ){
   152985         aPoslist = pList;
   152986         nPoslist = nList;
   152987 
   152988       }else{
   152989         char *aOut = pList;
   152990         char *p1 = aPoslist;
   152991         char *p2 = aOut;
   152992 
   152993         assert( iPrev>=0 );
   152994         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
   152995         sqlite3_free(aPoslist);
   152996         aPoslist = pList;
   152997         nPoslist = (int)(aOut - aPoslist);
   152998         if( nPoslist==0 ){
   152999           sqlite3_free(aPoslist);
   153000           pPhrase->doclist.pList = 0;
   153001           pPhrase->doclist.nList = 0;
   153002           return SQLITE_OK;
   153003         }
   153004       }
   153005       iPrev = iToken;
   153006     }
   153007   }
   153008 
   153009   if( iPrev>=0 ){
   153010     int nMaxUndeferred = pPhrase->iDoclistToken;
   153011     if( nMaxUndeferred<0 ){
   153012       pPhrase->doclist.pList = aPoslist;
   153013       pPhrase->doclist.nList = nPoslist;
   153014       pPhrase->doclist.iDocid = pCsr->iPrevId;
   153015       pPhrase->doclist.bFreeList = 1;
   153016     }else{
   153017       int nDistance;
   153018       char *p1;
   153019       char *p2;
   153020       char *aOut;
   153021 
   153022       if( nMaxUndeferred>iPrev ){
   153023         p1 = aPoslist;
   153024         p2 = pPhrase->doclist.pList;
   153025         nDistance = nMaxUndeferred - iPrev;
   153026       }else{
   153027         p1 = pPhrase->doclist.pList;
   153028         p2 = aPoslist;
   153029         nDistance = iPrev - nMaxUndeferred;
   153030       }
   153031 
   153032       aOut = (char *)sqlite3_malloc(nPoslist+8);
   153033       if( !aOut ){
   153034         sqlite3_free(aPoslist);
   153035         return SQLITE_NOMEM;
   153036       }
   153037 
   153038       pPhrase->doclist.pList = aOut;
   153039       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
   153040         pPhrase->doclist.bFreeList = 1;
   153041         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
   153042       }else{
   153043         sqlite3_free(aOut);
   153044         pPhrase->doclist.pList = 0;
   153045         pPhrase->doclist.nList = 0;
   153046       }
   153047       sqlite3_free(aPoslist);
   153048     }
   153049   }
   153050 
   153051   return SQLITE_OK;
   153052 }
   153053 
   153054 /*
   153055 ** Maximum number of tokens a phrase may have to be considered for the
   153056 ** incremental doclists strategy.
   153057 */
   153058 #define MAX_INCR_PHRASE_TOKENS 4
   153059 
   153060 /*
   153061 ** This function is called for each Fts3Phrase in a full-text query
   153062 ** expression to initialize the mechanism for returning rows. Once this
   153063 ** function has been called successfully on an Fts3Phrase, it may be
   153064 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
   153065 **
   153066 ** If parameter bOptOk is true, then the phrase may (or may not) use the
   153067 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
   153068 ** memory within this call.
   153069 **
   153070 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   153071 */
   153072 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
   153073   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   153074   int rc = SQLITE_OK;             /* Error code */
   153075   int i;
   153076 
   153077   /* Determine if doclists may be loaded from disk incrementally. This is
   153078   ** possible if the bOptOk argument is true, the FTS doclists will be
   153079   ** scanned in forward order, and the phrase consists of
   153080   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
   153081   ** tokens or prefix tokens that cannot use a prefix-index.  */
   153082   int bHaveIncr = 0;
   153083   int bIncrOk = (bOptOk
   153084    && pCsr->bDesc==pTab->bDescIdx
   153085    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
   153086 #ifdef SQLITE_TEST
   153087    && pTab->bNoIncrDoclist==0
   153088 #endif
   153089   );
   153090   for(i=0; bIncrOk==1 && i<p->nToken; i++){
   153091     Fts3PhraseToken *pToken = &p->aToken[i];
   153092     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
   153093       bIncrOk = 0;
   153094     }
   153095     if( pToken->pSegcsr ) bHaveIncr = 1;
   153096   }
   153097 
   153098   if( bIncrOk && bHaveIncr ){
   153099     /* Use the incremental approach. */
   153100     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
   153101     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
   153102       Fts3PhraseToken *pToken = &p->aToken[i];
   153103       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
   153104       if( pSegcsr ){
   153105         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
   153106       }
   153107     }
   153108     p->bIncr = 1;
   153109   }else{
   153110     /* Load the full doclist for the phrase into memory. */
   153111     rc = fts3EvalPhraseLoad(pCsr, p);
   153112     p->bIncr = 0;
   153113   }
   153114 
   153115   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
   153116   return rc;
   153117 }
   153118 
   153119 /*
   153120 ** This function is used to iterate backwards (from the end to start)
   153121 ** through doclists. It is used by this module to iterate through phrase
   153122 ** doclists in reverse and by the fts3_write.c module to iterate through
   153123 ** pending-terms lists when writing to databases with "order=desc".
   153124 **
   153125 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
   153126 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
   153127 ** function iterates from the end of the doclist to the beginning.
   153128 */
   153129 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
   153130   int bDescIdx,                   /* True if the doclist is desc */
   153131   char *aDoclist,                 /* Pointer to entire doclist */
   153132   int nDoclist,                   /* Length of aDoclist in bytes */
   153133   char **ppIter,                  /* IN/OUT: Iterator pointer */
   153134   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   153135   int *pnList,                    /* OUT: List length pointer */
   153136   u8 *pbEof                       /* OUT: End-of-file flag */
   153137 ){
   153138   char *p = *ppIter;
   153139 
   153140   assert( nDoclist>0 );
   153141   assert( *pbEof==0 );
   153142   assert( p || *piDocid==0 );
   153143   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
   153144 
   153145   if( p==0 ){
   153146     sqlite3_int64 iDocid = 0;
   153147     char *pNext = 0;
   153148     char *pDocid = aDoclist;
   153149     char *pEnd = &aDoclist[nDoclist];
   153150     int iMul = 1;
   153151 
   153152     while( pDocid<pEnd ){
   153153       sqlite3_int64 iDelta;
   153154       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
   153155       iDocid += (iMul * iDelta);
   153156       pNext = pDocid;
   153157       fts3PoslistCopy(0, &pDocid);
   153158       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
   153159       iMul = (bDescIdx ? -1 : 1);
   153160     }
   153161 
   153162     *pnList = (int)(pEnd - pNext);
   153163     *ppIter = pNext;
   153164     *piDocid = iDocid;
   153165   }else{
   153166     int iMul = (bDescIdx ? -1 : 1);
   153167     sqlite3_int64 iDelta;
   153168     fts3GetReverseVarint(&p, aDoclist, &iDelta);
   153169     *piDocid -= (iMul * iDelta);
   153170 
   153171     if( p==aDoclist ){
   153172       *pbEof = 1;
   153173     }else{
   153174       char *pSave = p;
   153175       fts3ReversePoslist(aDoclist, &p);
   153176       *pnList = (int)(pSave - p);
   153177     }
   153178     *ppIter = p;
   153179   }
   153180 }
   153181 
   153182 /*
   153183 ** Iterate forwards through a doclist.
   153184 */
   153185 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
   153186   int bDescIdx,                   /* True if the doclist is desc */
   153187   char *aDoclist,                 /* Pointer to entire doclist */
   153188   int nDoclist,                   /* Length of aDoclist in bytes */
   153189   char **ppIter,                  /* IN/OUT: Iterator pointer */
   153190   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   153191   u8 *pbEof                       /* OUT: End-of-file flag */
   153192 ){
   153193   char *p = *ppIter;
   153194 
   153195   assert( nDoclist>0 );
   153196   assert( *pbEof==0 );
   153197   assert( p || *piDocid==0 );
   153198   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
   153199 
   153200   if( p==0 ){
   153201     p = aDoclist;
   153202     p += sqlite3Fts3GetVarint(p, piDocid);
   153203   }else{
   153204     fts3PoslistCopy(0, &p);
   153205     while( p<&aDoclist[nDoclist] && *p==0 ) p++;
   153206     if( p>=&aDoclist[nDoclist] ){
   153207       *pbEof = 1;
   153208     }else{
   153209       sqlite3_int64 iVar;
   153210       p += sqlite3Fts3GetVarint(p, &iVar);
   153211       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
   153212     }
   153213   }
   153214 
   153215   *ppIter = p;
   153216 }
   153217 
   153218 /*
   153219 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
   153220 ** to true if EOF is reached.
   153221 */
   153222 static void fts3EvalDlPhraseNext(
   153223   Fts3Table *pTab,
   153224   Fts3Doclist *pDL,
   153225   u8 *pbEof
   153226 ){
   153227   char *pIter;                            /* Used to iterate through aAll */
   153228   char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
   153229 
   153230   if( pDL->pNextDocid ){
   153231     pIter = pDL->pNextDocid;
   153232   }else{
   153233     pIter = pDL->aAll;
   153234   }
   153235 
   153236   if( pIter>=pEnd ){
   153237     /* We have already reached the end of this doclist. EOF. */
   153238     *pbEof = 1;
   153239   }else{
   153240     sqlite3_int64 iDelta;
   153241     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
   153242     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
   153243       pDL->iDocid += iDelta;
   153244     }else{
   153245       pDL->iDocid -= iDelta;
   153246     }
   153247     pDL->pList = pIter;
   153248     fts3PoslistCopy(0, &pIter);
   153249     pDL->nList = (int)(pIter - pDL->pList);
   153250 
   153251     /* pIter now points just past the 0x00 that terminates the position-
   153252     ** list for document pDL->iDocid. However, if this position-list was
   153253     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
   153254     ** point to the start of the next docid value. The following line deals
   153255     ** with this case by advancing pIter past the zero-padding added by
   153256     ** fts3EvalNearTrim().  */
   153257     while( pIter<pEnd && *pIter==0 ) pIter++;
   153258 
   153259     pDL->pNextDocid = pIter;
   153260     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
   153261     *pbEof = 0;
   153262   }
   153263 }
   153264 
   153265 /*
   153266 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
   153267 */
   153268 typedef struct TokenDoclist TokenDoclist;
   153269 struct TokenDoclist {
   153270   int bIgnore;
   153271   sqlite3_int64 iDocid;
   153272   char *pList;
   153273   int nList;
   153274 };
   153275 
   153276 /*
   153277 ** Token pToken is an incrementally loaded token that is part of a
   153278 ** multi-token phrase. Advance it to the next matching document in the
   153279 ** database and populate output variable *p with the details of the new
   153280 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
   153281 **
   153282 ** If an error occurs, return an SQLite error code. Otherwise, return
   153283 ** SQLITE_OK.
   153284 */
   153285 static int incrPhraseTokenNext(
   153286   Fts3Table *pTab,                /* Virtual table handle */
   153287   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
   153288   int iToken,                     /* Specific token to advance */
   153289   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
   153290   u8 *pbEof                       /* OUT: True if iterator is at EOF */
   153291 ){
   153292   int rc = SQLITE_OK;
   153293 
   153294   if( pPhrase->iDoclistToken==iToken ){
   153295     assert( p->bIgnore==0 );
   153296     assert( pPhrase->aToken[iToken].pSegcsr==0 );
   153297     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
   153298     p->pList = pPhrase->doclist.pList;
   153299     p->nList = pPhrase->doclist.nList;
   153300     p->iDocid = pPhrase->doclist.iDocid;
   153301   }else{
   153302     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   153303     assert( pToken->pDeferred==0 );
   153304     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
   153305     if( pToken->pSegcsr ){
   153306       assert( p->bIgnore==0 );
   153307       rc = sqlite3Fts3MsrIncrNext(
   153308           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
   153309       );
   153310       if( p->pList==0 ) *pbEof = 1;
   153311     }else{
   153312       p->bIgnore = 1;
   153313     }
   153314   }
   153315 
   153316   return rc;
   153317 }
   153318 
   153319 
   153320 /*
   153321 ** The phrase iterator passed as the second argument:
   153322 **
   153323 **   * features at least one token that uses an incremental doclist, and
   153324 **
   153325 **   * does not contain any deferred tokens.
   153326 **
   153327 ** Advance it to the next matching documnent in the database and populate
   153328 ** the Fts3Doclist.pList and nList fields.
   153329 **
   153330 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   153331 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   153332 ** successfully advanced, *pbEof is set to 0.
   153333 **
   153334 ** If an error occurs, return an SQLite error code. Otherwise, return
   153335 ** SQLITE_OK.
   153336 */
   153337 static int fts3EvalIncrPhraseNext(
   153338   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   153339   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   153340   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   153341 ){
   153342   int rc = SQLITE_OK;
   153343   Fts3Doclist *pDL = &p->doclist;
   153344   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   153345   u8 bEof = 0;
   153346 
   153347   /* This is only called if it is guaranteed that the phrase has at least
   153348   ** one incremental token. In which case the bIncr flag is set. */
   153349   assert( p->bIncr==1 );
   153350 
   153351   if( p->nToken==1 ){
   153352     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
   153353         &pDL->iDocid, &pDL->pList, &pDL->nList
   153354     );
   153355     if( pDL->pList==0 ) bEof = 1;
   153356   }else{
   153357     int bDescDoclist = pCsr->bDesc;
   153358     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
   153359 
   153360     memset(a, 0, sizeof(a));
   153361     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
   153362     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
   153363 
   153364     while( bEof==0 ){
   153365       int bMaxSet = 0;
   153366       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
   153367       int i;                      /* Used to iterate through tokens */
   153368 
   153369       /* Advance the iterator for each token in the phrase once. */
   153370       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
   153371         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
   153372         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
   153373           iMax = a[i].iDocid;
   153374           bMaxSet = 1;
   153375         }
   153376       }
   153377       assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
   153378       assert( rc!=SQLITE_OK || bMaxSet );
   153379 
   153380       /* Keep advancing iterators until they all point to the same document */
   153381       for(i=0; i<p->nToken; i++){
   153382         while( rc==SQLITE_OK && bEof==0
   153383             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
   153384         ){
   153385           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
   153386           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
   153387             iMax = a[i].iDocid;
   153388             i = 0;
   153389           }
   153390         }
   153391       }
   153392 
   153393       /* Check if the current entries really are a phrase match */
   153394       if( bEof==0 ){
   153395         int nList = 0;
   153396         int nByte = a[p->nToken-1].nList;
   153397         char *aDoclist = sqlite3_malloc(nByte+1);
   153398         if( !aDoclist ) return SQLITE_NOMEM;
   153399         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
   153400 
   153401         for(i=0; i<(p->nToken-1); i++){
   153402           if( a[i].bIgnore==0 ){
   153403             char *pL = a[i].pList;
   153404             char *pR = aDoclist;
   153405             char *pOut = aDoclist;
   153406             int nDist = p->nToken-1-i;
   153407             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
   153408             if( res==0 ) break;
   153409             nList = (int)(pOut - aDoclist);
   153410           }
   153411         }
   153412         if( i==(p->nToken-1) ){
   153413           pDL->iDocid = iMax;
   153414           pDL->pList = aDoclist;
   153415           pDL->nList = nList;
   153416           pDL->bFreeList = 1;
   153417           break;
   153418         }
   153419         sqlite3_free(aDoclist);
   153420       }
   153421     }
   153422   }
   153423 
   153424   *pbEof = bEof;
   153425   return rc;
   153426 }
   153427 
   153428 /*
   153429 ** Attempt to move the phrase iterator to point to the next matching docid.
   153430 ** If an error occurs, return an SQLite error code. Otherwise, return
   153431 ** SQLITE_OK.
   153432 **
   153433 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   153434 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   153435 ** successfully advanced, *pbEof is set to 0.
   153436 */
   153437 static int fts3EvalPhraseNext(
   153438   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   153439   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   153440   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   153441 ){
   153442   int rc = SQLITE_OK;
   153443   Fts3Doclist *pDL = &p->doclist;
   153444   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   153445 
   153446   if( p->bIncr ){
   153447     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
   153448   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
   153449     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
   153450         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
   153451     );
   153452     pDL->pList = pDL->pNextDocid;
   153453   }else{
   153454     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
   153455   }
   153456 
   153457   return rc;
   153458 }
   153459 
   153460 /*
   153461 **
   153462 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   153463 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
   153464 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
   153465 ** expressions for which all descendent tokens are deferred.
   153466 **
   153467 ** If parameter bOptOk is zero, then it is guaranteed that the
   153468 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
   153469 ** each phrase in the expression (subject to deferred token processing).
   153470 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
   153471 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
   153472 **
   153473 ** If an error occurs within this function, *pRc is set to an SQLite error
   153474 ** code before returning.
   153475 */
   153476 static void fts3EvalStartReaders(
   153477   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   153478   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
   153479   int *pRc                        /* IN/OUT: Error code */
   153480 ){
   153481   if( pExpr && SQLITE_OK==*pRc ){
   153482     if( pExpr->eType==FTSQUERY_PHRASE ){
   153483       int nToken = pExpr->pPhrase->nToken;
   153484       if( nToken ){
   153485         int i;
   153486         for(i=0; i<nToken; i++){
   153487           if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
   153488         }
   153489         pExpr->bDeferred = (i==nToken);
   153490       }
   153491       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
   153492     }else{
   153493       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
   153494       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
   153495       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
   153496     }
   153497   }
   153498 }
   153499 
   153500 /*
   153501 ** An array of the following structures is assembled as part of the process
   153502 ** of selecting tokens to defer before the query starts executing (as part
   153503 ** of the xFilter() method). There is one element in the array for each
   153504 ** token in the FTS expression.
   153505 **
   153506 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
   153507 ** to phrases that are connected only by AND and NEAR operators (not OR or
   153508 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
   153509 ** separately. The root of a tokens AND/NEAR cluster is stored in
   153510 ** Fts3TokenAndCost.pRoot.
   153511 */
   153512 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
   153513 struct Fts3TokenAndCost {
   153514   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
   153515   int iToken;                     /* Position of token in phrase */
   153516   Fts3PhraseToken *pToken;        /* The token itself */
   153517   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
   153518   int nOvfl;                      /* Number of overflow pages to load doclist */
   153519   int iCol;                       /* The column the token must match */
   153520 };
   153521 
   153522 /*
   153523 ** This function is used to populate an allocated Fts3TokenAndCost array.
   153524 **
   153525 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   153526 ** Otherwise, if an error occurs during execution, *pRc is set to an
   153527 ** SQLite error code.
   153528 */
   153529 static void fts3EvalTokenCosts(
   153530   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   153531   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
   153532   Fts3Expr *pExpr,                /* Expression to consider */
   153533   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
   153534   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
   153535   int *pRc                        /* IN/OUT: Error code */
   153536 ){
   153537   if( *pRc==SQLITE_OK ){
   153538     if( pExpr->eType==FTSQUERY_PHRASE ){
   153539       Fts3Phrase *pPhrase = pExpr->pPhrase;
   153540       int i;
   153541       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
   153542         Fts3TokenAndCost *pTC = (*ppTC)++;
   153543         pTC->pPhrase = pPhrase;
   153544         pTC->iToken = i;
   153545         pTC->pRoot = pRoot;
   153546         pTC->pToken = &pPhrase->aToken[i];
   153547         pTC->iCol = pPhrase->iColumn;
   153548         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
   153549       }
   153550     }else if( pExpr->eType!=FTSQUERY_NOT ){
   153551       assert( pExpr->eType==FTSQUERY_OR
   153552            || pExpr->eType==FTSQUERY_AND
   153553            || pExpr->eType==FTSQUERY_NEAR
   153554       );
   153555       assert( pExpr->pLeft && pExpr->pRight );
   153556       if( pExpr->eType==FTSQUERY_OR ){
   153557         pRoot = pExpr->pLeft;
   153558         **ppOr = pRoot;
   153559         (*ppOr)++;
   153560       }
   153561       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
   153562       if( pExpr->eType==FTSQUERY_OR ){
   153563         pRoot = pExpr->pRight;
   153564         **ppOr = pRoot;
   153565         (*ppOr)++;
   153566       }
   153567       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
   153568     }
   153569   }
   153570 }
   153571 
   153572 /*
   153573 ** Determine the average document (row) size in pages. If successful,
   153574 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
   153575 ** an SQLite error code.
   153576 **
   153577 ** The average document size in pages is calculated by first calculating
   153578 ** determining the average size in bytes, B. If B is less than the amount
   153579 ** of data that will fit on a single leaf page of an intkey table in
   153580 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
   153581 ** the number of overflow pages consumed by a record B bytes in size.
   153582 */
   153583 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
   153584   int rc = SQLITE_OK;
   153585   if( pCsr->nRowAvg==0 ){
   153586     /* The average document size, which is required to calculate the cost
   153587     ** of each doclist, has not yet been determined. Read the required
   153588     ** data from the %_stat table to calculate it.
   153589     **
   153590     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
   153591     ** varints, where nCol is the number of columns in the FTS3 table.
   153592     ** The first varint is the number of documents currently stored in
   153593     ** the table. The following nCol varints contain the total amount of
   153594     ** data stored in all rows of each column of the table, from left
   153595     ** to right.
   153596     */
   153597     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   153598     sqlite3_stmt *pStmt;
   153599     sqlite3_int64 nDoc = 0;
   153600     sqlite3_int64 nByte = 0;
   153601     const char *pEnd;
   153602     const char *a;
   153603 
   153604     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
   153605     if( rc!=SQLITE_OK ) return rc;
   153606     a = sqlite3_column_blob(pStmt, 0);
   153607     assert( a );
   153608 
   153609     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
   153610     a += sqlite3Fts3GetVarint(a, &nDoc);
   153611     while( a<pEnd ){
   153612       a += sqlite3Fts3GetVarint(a, &nByte);
   153613     }
   153614     if( nDoc==0 || nByte==0 ){
   153615       sqlite3_reset(pStmt);
   153616       return FTS_CORRUPT_VTAB;
   153617     }
   153618 
   153619     pCsr->nDoc = nDoc;
   153620     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
   153621     assert( pCsr->nRowAvg>0 );
   153622     rc = sqlite3_reset(pStmt);
   153623   }
   153624 
   153625   *pnPage = pCsr->nRowAvg;
   153626   return rc;
   153627 }
   153628 
   153629 /*
   153630 ** This function is called to select the tokens (if any) that will be
   153631 ** deferred. The array aTC[] has already been populated when this is
   153632 ** called.
   153633 **
   153634 ** This function is called once for each AND/NEAR cluster in the
   153635 ** expression. Each invocation determines which tokens to defer within
   153636 ** the cluster with root node pRoot. See comments above the definition
   153637 ** of struct Fts3TokenAndCost for more details.
   153638 **
   153639 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
   153640 ** called on each token to defer. Otherwise, an SQLite error code is
   153641 ** returned.
   153642 */
   153643 static int fts3EvalSelectDeferred(
   153644   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   153645   Fts3Expr *pRoot,                /* Consider tokens with this root node */
   153646   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
   153647   int nTC                         /* Number of entries in aTC[] */
   153648 ){
   153649   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   153650   int nDocSize = 0;               /* Number of pages per doc loaded */
   153651   int rc = SQLITE_OK;             /* Return code */
   153652   int ii;                         /* Iterator variable for various purposes */
   153653   int nOvfl = 0;                  /* Total overflow pages used by doclists */
   153654   int nToken = 0;                 /* Total number of tokens in cluster */
   153655 
   153656   int nMinEst = 0;                /* The minimum count for any phrase so far. */
   153657   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
   153658 
   153659   /* Tokens are never deferred for FTS tables created using the content=xxx
   153660   ** option. The reason being that it is not guaranteed that the content
   153661   ** table actually contains the same data as the index. To prevent this from
   153662   ** causing any problems, the deferred token optimization is completely
   153663   ** disabled for content=xxx tables. */
   153664   if( pTab->zContentTbl ){
   153665     return SQLITE_OK;
   153666   }
   153667 
   153668   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
   153669   ** associated with the tokens spill onto overflow pages, or if there is
   153670   ** only 1 token, exit early. No tokens to defer in this case. */
   153671   for(ii=0; ii<nTC; ii++){
   153672     if( aTC[ii].pRoot==pRoot ){
   153673       nOvfl += aTC[ii].nOvfl;
   153674       nToken++;
   153675     }
   153676   }
   153677   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
   153678 
   153679   /* Obtain the average docsize (in pages). */
   153680   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
   153681   assert( rc!=SQLITE_OK || nDocSize>0 );
   153682 
   153683 
   153684   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
   153685   ** of the number of overflow pages that will be loaded by the pager layer
   153686   ** to retrieve the entire doclist for the token from the full-text index.
   153687   ** Load the doclists for tokens that are either:
   153688   **
   153689   **   a. The cheapest token in the entire query (i.e. the one visited by the
   153690   **      first iteration of this loop), or
   153691   **
   153692   **   b. Part of a multi-token phrase.
   153693   **
   153694   ** After each token doclist is loaded, merge it with the others from the
   153695   ** same phrase and count the number of documents that the merged doclist
   153696   ** contains. Set variable "nMinEst" to the smallest number of documents in
   153697   ** any phrase doclist for which 1 or more token doclists have been loaded.
   153698   ** Let nOther be the number of other phrases for which it is certain that
   153699   ** one or more tokens will not be deferred.
   153700   **
   153701   ** Then, for each token, defer it if loading the doclist would result in
   153702   ** loading N or more overflow pages into memory, where N is computed as:
   153703   **
   153704   **    (nMinEst + 4^nOther - 1) / (4^nOther)
   153705   */
   153706   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
   153707     int iTC;                      /* Used to iterate through aTC[] array. */
   153708     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
   153709 
   153710     /* Set pTC to point to the cheapest remaining token. */
   153711     for(iTC=0; iTC<nTC; iTC++){
   153712       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
   153713        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
   153714       ){
   153715         pTC = &aTC[iTC];
   153716       }
   153717     }
   153718     assert( pTC );
   153719 
   153720     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
   153721       /* The number of overflow pages to load for this (and therefore all
   153722       ** subsequent) tokens is greater than the estimated number of pages
   153723       ** that will be loaded if all subsequent tokens are deferred.
   153724       */
   153725       Fts3PhraseToken *pToken = pTC->pToken;
   153726       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
   153727       fts3SegReaderCursorFree(pToken->pSegcsr);
   153728       pToken->pSegcsr = 0;
   153729     }else{
   153730       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
   153731       ** for-loop. Except, limit the value to 2^24 to prevent it from
   153732       ** overflowing the 32-bit integer it is stored in. */
   153733       if( ii<12 ) nLoad4 = nLoad4*4;
   153734 
   153735       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
   153736         /* Either this is the cheapest token in the entire query, or it is
   153737         ** part of a multi-token phrase. Either way, the entire doclist will
   153738         ** (eventually) be loaded into memory. It may as well be now. */
   153739         Fts3PhraseToken *pToken = pTC->pToken;
   153740         int nList = 0;
   153741         char *pList = 0;
   153742         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
   153743         assert( rc==SQLITE_OK || pList==0 );
   153744         if( rc==SQLITE_OK ){
   153745           rc = fts3EvalPhraseMergeToken(
   153746               pTab, pTC->pPhrase, pTC->iToken,pList,nList
   153747           );
   153748         }
   153749         if( rc==SQLITE_OK ){
   153750           int nCount;
   153751           nCount = fts3DoclistCountDocids(
   153752               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
   153753           );
   153754           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
   153755         }
   153756       }
   153757     }
   153758     pTC->pToken = 0;
   153759   }
   153760 
   153761   return rc;
   153762 }
   153763 
   153764 /*
   153765 ** This function is called from within the xFilter method. It initializes
   153766 ** the full-text query currently stored in pCsr->pExpr. To iterate through
   153767 ** the results of a query, the caller does:
   153768 **
   153769 **    fts3EvalStart(pCsr);
   153770 **    while( 1 ){
   153771 **      fts3EvalNext(pCsr);
   153772 **      if( pCsr->bEof ) break;
   153773 **      ... return row pCsr->iPrevId to the caller ...
   153774 **    }
   153775 */
   153776 static int fts3EvalStart(Fts3Cursor *pCsr){
   153777   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   153778   int rc = SQLITE_OK;
   153779   int nToken = 0;
   153780   int nOr = 0;
   153781 
   153782   /* Allocate a MultiSegReader for each token in the expression. */
   153783   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
   153784 
   153785   /* Determine which, if any, tokens in the expression should be deferred. */
   153786 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   153787   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
   153788     Fts3TokenAndCost *aTC;
   153789     Fts3Expr **apOr;
   153790     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
   153791         sizeof(Fts3TokenAndCost) * nToken
   153792       + sizeof(Fts3Expr *) * nOr * 2
   153793     );
   153794     apOr = (Fts3Expr **)&aTC[nToken];
   153795 
   153796     if( !aTC ){
   153797       rc = SQLITE_NOMEM;
   153798     }else{
   153799       int ii;
   153800       Fts3TokenAndCost *pTC = aTC;
   153801       Fts3Expr **ppOr = apOr;
   153802 
   153803       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
   153804       nToken = (int)(pTC-aTC);
   153805       nOr = (int)(ppOr-apOr);
   153806 
   153807       if( rc==SQLITE_OK ){
   153808         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
   153809         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
   153810           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
   153811         }
   153812       }
   153813 
   153814       sqlite3_free(aTC);
   153815     }
   153816   }
   153817 #endif
   153818 
   153819   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
   153820   return rc;
   153821 }
   153822 
   153823 /*
   153824 ** Invalidate the current position list for phrase pPhrase.
   153825 */
   153826 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
   153827   if( pPhrase->doclist.bFreeList ){
   153828     sqlite3_free(pPhrase->doclist.pList);
   153829   }
   153830   pPhrase->doclist.pList = 0;
   153831   pPhrase->doclist.nList = 0;
   153832   pPhrase->doclist.bFreeList = 0;
   153833 }
   153834 
   153835 /*
   153836 ** This function is called to edit the position list associated with
   153837 ** the phrase object passed as the fifth argument according to a NEAR
   153838 ** condition. For example:
   153839 **
   153840 **     abc NEAR/5 "def ghi"
   153841 **
   153842 ** Parameter nNear is passed the NEAR distance of the expression (5 in
   153843 ** the example above). When this function is called, *paPoslist points to
   153844 ** the position list, and *pnToken is the number of phrase tokens in, the
   153845 ** phrase on the other side of the NEAR operator to pPhrase. For example,
   153846 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
   153847 ** the position list associated with phrase "abc".
   153848 **
   153849 ** All positions in the pPhrase position list that are not sufficiently
   153850 ** close to a position in the *paPoslist position list are removed. If this
   153851 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
   153852 **
   153853 ** Before returning, *paPoslist is set to point to the position lsit
   153854 ** associated with pPhrase. And *pnToken is set to the number of tokens in
   153855 ** pPhrase.
   153856 */
   153857 static int fts3EvalNearTrim(
   153858   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
   153859   char *aTmp,                     /* Temporary space to use */
   153860   char **paPoslist,               /* IN/OUT: Position list */
   153861   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
   153862   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
   153863 ){
   153864   int nParam1 = nNear + pPhrase->nToken;
   153865   int nParam2 = nNear + *pnToken;
   153866   int nNew;
   153867   char *p2;
   153868   char *pOut;
   153869   int res;
   153870 
   153871   assert( pPhrase->doclist.pList );
   153872 
   153873   p2 = pOut = pPhrase->doclist.pList;
   153874   res = fts3PoslistNearMerge(
   153875     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
   153876   );
   153877   if( res ){
   153878     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
   153879     assert( pPhrase->doclist.pList[nNew]=='\0' );
   153880     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
   153881     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
   153882     pPhrase->doclist.nList = nNew;
   153883     *paPoslist = pPhrase->doclist.pList;
   153884     *pnToken = pPhrase->nToken;
   153885   }
   153886 
   153887   return res;
   153888 }
   153889 
   153890 /*
   153891 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
   153892 ** Otherwise, it advances the expression passed as the second argument to
   153893 ** point to the next matching row in the database. Expressions iterate through
   153894 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
   153895 ** or descending if it is non-zero.
   153896 **
   153897 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
   153898 ** successful, the following variables in pExpr are set:
   153899 **
   153900 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
   153901 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
   153902 **
   153903 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
   153904 ** at EOF, then the following variables are populated with the position list
   153905 ** for the phrase for the visited row:
   153906 **
   153907 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
   153908 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
   153909 **
   153910 ** It says above that this function advances the expression to the next
   153911 ** matching row. This is usually true, but there are the following exceptions:
   153912 **
   153913 **   1. Deferred tokens are not taken into account. If a phrase consists
   153914 **      entirely of deferred tokens, it is assumed to match every row in
   153915 **      the db. In this case the position-list is not populated at all.
   153916 **
   153917 **      Or, if a phrase contains one or more deferred tokens and one or
   153918 **      more non-deferred tokens, then the expression is advanced to the
   153919 **      next possible match, considering only non-deferred tokens. In other
   153920 **      words, if the phrase is "A B C", and "B" is deferred, the expression
   153921 **      is advanced to the next row that contains an instance of "A * C",
   153922 **      where "*" may match any single token. The position list in this case
   153923 **      is populated as for "A * C" before returning.
   153924 **
   153925 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
   153926 **      advanced to point to the next row that matches "x AND y".
   153927 **
   153928 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
   153929 ** really a match, taking into account deferred tokens and NEAR operators.
   153930 */
   153931 static void fts3EvalNextRow(
   153932   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   153933   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
   153934   int *pRc                        /* IN/OUT: Error code */
   153935 ){
   153936   if( *pRc==SQLITE_OK ){
   153937     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
   153938     assert( pExpr->bEof==0 );
   153939     pExpr->bStart = 1;
   153940 
   153941     switch( pExpr->eType ){
   153942       case FTSQUERY_NEAR:
   153943       case FTSQUERY_AND: {
   153944         Fts3Expr *pLeft = pExpr->pLeft;
   153945         Fts3Expr *pRight = pExpr->pRight;
   153946         assert( !pLeft->bDeferred || !pRight->bDeferred );
   153947 
   153948         if( pLeft->bDeferred ){
   153949           /* LHS is entirely deferred. So we assume it matches every row.
   153950           ** Advance the RHS iterator to find the next row visited. */
   153951           fts3EvalNextRow(pCsr, pRight, pRc);
   153952           pExpr->iDocid = pRight->iDocid;
   153953           pExpr->bEof = pRight->bEof;
   153954         }else if( pRight->bDeferred ){
   153955           /* RHS is entirely deferred. So we assume it matches every row.
   153956           ** Advance the LHS iterator to find the next row visited. */
   153957           fts3EvalNextRow(pCsr, pLeft, pRc);
   153958           pExpr->iDocid = pLeft->iDocid;
   153959           pExpr->bEof = pLeft->bEof;
   153960         }else{
   153961           /* Neither the RHS or LHS are deferred. */
   153962           fts3EvalNextRow(pCsr, pLeft, pRc);
   153963           fts3EvalNextRow(pCsr, pRight, pRc);
   153964           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
   153965             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   153966             if( iDiff==0 ) break;
   153967             if( iDiff<0 ){
   153968               fts3EvalNextRow(pCsr, pLeft, pRc);
   153969             }else{
   153970               fts3EvalNextRow(pCsr, pRight, pRc);
   153971             }
   153972           }
   153973           pExpr->iDocid = pLeft->iDocid;
   153974           pExpr->bEof = (pLeft->bEof || pRight->bEof);
   153975           if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
   153976             assert( pRight->eType==FTSQUERY_PHRASE );
   153977             if( pRight->pPhrase->doclist.aAll ){
   153978               Fts3Doclist *pDl = &pRight->pPhrase->doclist;
   153979               while( *pRc==SQLITE_OK && pRight->bEof==0 ){
   153980                 memset(pDl->pList, 0, pDl->nList);
   153981                 fts3EvalNextRow(pCsr, pRight, pRc);
   153982               }
   153983             }
   153984             if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
   153985               Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
   153986               while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
   153987                 memset(pDl->pList, 0, pDl->nList);
   153988                 fts3EvalNextRow(pCsr, pLeft, pRc);
   153989               }
   153990             }
   153991           }
   153992         }
   153993         break;
   153994       }
   153995 
   153996       case FTSQUERY_OR: {
   153997         Fts3Expr *pLeft = pExpr->pLeft;
   153998         Fts3Expr *pRight = pExpr->pRight;
   153999         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   154000 
   154001         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
   154002         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
   154003 
   154004         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
   154005           fts3EvalNextRow(pCsr, pLeft, pRc);
   154006         }else if( pLeft->bEof || iCmp>0 ){
   154007           fts3EvalNextRow(pCsr, pRight, pRc);
   154008         }else{
   154009           fts3EvalNextRow(pCsr, pLeft, pRc);
   154010           fts3EvalNextRow(pCsr, pRight, pRc);
   154011         }
   154012 
   154013         pExpr->bEof = (pLeft->bEof && pRight->bEof);
   154014         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   154015         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
   154016           pExpr->iDocid = pLeft->iDocid;
   154017         }else{
   154018           pExpr->iDocid = pRight->iDocid;
   154019         }
   154020 
   154021         break;
   154022       }
   154023 
   154024       case FTSQUERY_NOT: {
   154025         Fts3Expr *pLeft = pExpr->pLeft;
   154026         Fts3Expr *pRight = pExpr->pRight;
   154027 
   154028         if( pRight->bStart==0 ){
   154029           fts3EvalNextRow(pCsr, pRight, pRc);
   154030           assert( *pRc!=SQLITE_OK || pRight->bStart );
   154031         }
   154032 
   154033         fts3EvalNextRow(pCsr, pLeft, pRc);
   154034         if( pLeft->bEof==0 ){
   154035           while( !*pRc
   154036               && !pRight->bEof
   154037               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
   154038           ){
   154039             fts3EvalNextRow(pCsr, pRight, pRc);
   154040           }
   154041         }
   154042         pExpr->iDocid = pLeft->iDocid;
   154043         pExpr->bEof = pLeft->bEof;
   154044         break;
   154045       }
   154046 
   154047       default: {
   154048         Fts3Phrase *pPhrase = pExpr->pPhrase;
   154049         fts3EvalInvalidatePoslist(pPhrase);
   154050         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
   154051         pExpr->iDocid = pPhrase->doclist.iDocid;
   154052         break;
   154053       }
   154054     }
   154055   }
   154056 }
   154057 
   154058 /*
   154059 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
   154060 ** cluster, then this function returns 1 immediately.
   154061 **
   154062 ** Otherwise, it checks if the current row really does match the NEAR
   154063 ** expression, using the data currently stored in the position lists
   154064 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
   154065 **
   154066 ** If the current row is a match, the position list associated with each
   154067 ** phrase in the NEAR expression is edited in place to contain only those
   154068 ** phrase instances sufficiently close to their peers to satisfy all NEAR
   154069 ** constraints. In this case it returns 1. If the NEAR expression does not
   154070 ** match the current row, 0 is returned. The position lists may or may not
   154071 ** be edited if 0 is returned.
   154072 */
   154073 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
   154074   int res = 1;
   154075 
   154076   /* The following block runs if pExpr is the root of a NEAR query.
   154077   ** For example, the query:
   154078   **
   154079   **         "w" NEAR "x" NEAR "y" NEAR "z"
   154080   **
   154081   ** which is represented in tree form as:
   154082   **
   154083   **                               |
   154084   **                          +--NEAR--+      <-- root of NEAR query
   154085   **                          |        |
   154086   **                     +--NEAR--+   "z"
   154087   **                     |        |
   154088   **                +--NEAR--+   "y"
   154089   **                |        |
   154090   **               "w"      "x"
   154091   **
   154092   ** The right-hand child of a NEAR node is always a phrase. The
   154093   ** left-hand child may be either a phrase or a NEAR node. There are
   154094   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
   154095   */
   154096   if( *pRc==SQLITE_OK
   154097    && pExpr->eType==FTSQUERY_NEAR
   154098    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   154099   ){
   154100     Fts3Expr *p;
   154101     int nTmp = 0;                 /* Bytes of temp space */
   154102     char *aTmp;                   /* Temp space for PoslistNearMerge() */
   154103 
   154104     /* Allocate temporary working space. */
   154105     for(p=pExpr; p->pLeft; p=p->pLeft){
   154106       assert( p->pRight->pPhrase->doclist.nList>0 );
   154107       nTmp += p->pRight->pPhrase->doclist.nList;
   154108     }
   154109     nTmp += p->pPhrase->doclist.nList;
   154110     aTmp = sqlite3_malloc(nTmp*2);
   154111     if( !aTmp ){
   154112       *pRc = SQLITE_NOMEM;
   154113       res = 0;
   154114     }else{
   154115       char *aPoslist = p->pPhrase->doclist.pList;
   154116       int nToken = p->pPhrase->nToken;
   154117 
   154118       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
   154119         Fts3Phrase *pPhrase = p->pRight->pPhrase;
   154120         int nNear = p->nNear;
   154121         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   154122       }
   154123 
   154124       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
   154125       nToken = pExpr->pRight->pPhrase->nToken;
   154126       for(p=pExpr->pLeft; p && res; p=p->pLeft){
   154127         int nNear;
   154128         Fts3Phrase *pPhrase;
   154129         assert( p->pParent && p->pParent->pLeft==p );
   154130         nNear = p->pParent->nNear;
   154131         pPhrase = (
   154132             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
   154133         );
   154134         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   154135       }
   154136     }
   154137 
   154138     sqlite3_free(aTmp);
   154139   }
   154140 
   154141   return res;
   154142 }
   154143 
   154144 /*
   154145 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
   154146 ** Assuming no error occurs or has occurred, It returns non-zero if the
   154147 ** expression passed as the second argument matches the row that pCsr
   154148 ** currently points to, or zero if it does not.
   154149 **
   154150 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   154151 ** If an error occurs during execution of this function, *pRc is set to
   154152 ** the appropriate SQLite error code. In this case the returned value is
   154153 ** undefined.
   154154 */
   154155 static int fts3EvalTestExpr(
   154156   Fts3Cursor *pCsr,               /* FTS cursor handle */
   154157   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
   154158   int *pRc                        /* IN/OUT: Error code */
   154159 ){
   154160   int bHit = 1;                   /* Return value */
   154161   if( *pRc==SQLITE_OK ){
   154162     switch( pExpr->eType ){
   154163       case FTSQUERY_NEAR:
   154164       case FTSQUERY_AND:
   154165         bHit = (
   154166             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   154167          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   154168          && fts3EvalNearTest(pExpr, pRc)
   154169         );
   154170 
   154171         /* If the NEAR expression does not match any rows, zero the doclist for
   154172         ** all phrases involved in the NEAR. This is because the snippet(),
   154173         ** offsets() and matchinfo() functions are not supposed to recognize
   154174         ** any instances of phrases that are part of unmatched NEAR queries.
   154175         ** For example if this expression:
   154176         **
   154177         **    ... MATCH 'a OR (b NEAR c)'
   154178         **
   154179         ** is matched against a row containing:
   154180         **
   154181         **        'a b d e'
   154182         **
   154183         ** then any snippet() should ony highlight the "a" term, not the "b"
   154184         ** (as "b" is part of a non-matching NEAR clause).
   154185         */
   154186         if( bHit==0
   154187          && pExpr->eType==FTSQUERY_NEAR
   154188          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   154189         ){
   154190           Fts3Expr *p;
   154191           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
   154192             if( p->pRight->iDocid==pCsr->iPrevId ){
   154193               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
   154194             }
   154195           }
   154196           if( p->iDocid==pCsr->iPrevId ){
   154197             fts3EvalInvalidatePoslist(p->pPhrase);
   154198           }
   154199         }
   154200 
   154201         break;
   154202 
   154203       case FTSQUERY_OR: {
   154204         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
   154205         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
   154206         bHit = bHit1 || bHit2;
   154207         break;
   154208       }
   154209 
   154210       case FTSQUERY_NOT:
   154211         bHit = (
   154212             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   154213          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   154214         );
   154215         break;
   154216 
   154217       default: {
   154218 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   154219         if( pCsr->pDeferred
   154220          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
   154221         ){
   154222           Fts3Phrase *pPhrase = pExpr->pPhrase;
   154223           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
   154224           if( pExpr->bDeferred ){
   154225             fts3EvalInvalidatePoslist(pPhrase);
   154226           }
   154227           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
   154228           bHit = (pPhrase->doclist.pList!=0);
   154229           pExpr->iDocid = pCsr->iPrevId;
   154230         }else
   154231 #endif
   154232         {
   154233           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
   154234         }
   154235         break;
   154236       }
   154237     }
   154238   }
   154239   return bHit;
   154240 }
   154241 
   154242 /*
   154243 ** This function is called as the second part of each xNext operation when
   154244 ** iterating through the results of a full-text query. At this point the
   154245 ** cursor points to a row that matches the query expression, with the
   154246 ** following caveats:
   154247 **
   154248 **   * Up until this point, "NEAR" operators in the expression have been
   154249 **     treated as "AND".
   154250 **
   154251 **   * Deferred tokens have not yet been considered.
   154252 **
   154253 ** If *pRc is not SQLITE_OK when this function is called, it immediately
   154254 ** returns 0. Otherwise, it tests whether or not after considering NEAR
   154255 ** operators and deferred tokens the current row is still a match for the
   154256 ** expression. It returns 1 if both of the following are true:
   154257 **
   154258 **   1. *pRc is SQLITE_OK when this function returns, and
   154259 **
   154260 **   2. After scanning the current FTS table row for the deferred tokens,
   154261 **      it is determined that the row does *not* match the query.
   154262 **
   154263 ** Or, if no error occurs and it seems the current row does match the FTS
   154264 ** query, return 0.
   154265 */
   154266 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
   154267   int rc = *pRc;
   154268   int bMiss = 0;
   154269   if( rc==SQLITE_OK ){
   154270 
   154271     /* If there are one or more deferred tokens, load the current row into
   154272     ** memory and scan it to determine the position list for each deferred
   154273     ** token. Then, see if this row is really a match, considering deferred
   154274     ** tokens and NEAR operators (neither of which were taken into account
   154275     ** earlier, by fts3EvalNextRow()).
   154276     */
   154277     if( pCsr->pDeferred ){
   154278       rc = fts3CursorSeek(0, pCsr);
   154279       if( rc==SQLITE_OK ){
   154280         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
   154281       }
   154282     }
   154283     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
   154284 
   154285     /* Free the position-lists accumulated for each deferred token above. */
   154286     sqlite3Fts3FreeDeferredDoclists(pCsr);
   154287     *pRc = rc;
   154288   }
   154289   return (rc==SQLITE_OK && bMiss);
   154290 }
   154291 
   154292 /*
   154293 ** Advance to the next document that matches the FTS expression in
   154294 ** Fts3Cursor.pExpr.
   154295 */
   154296 static int fts3EvalNext(Fts3Cursor *pCsr){
   154297   int rc = SQLITE_OK;             /* Return Code */
   154298   Fts3Expr *pExpr = pCsr->pExpr;
   154299   assert( pCsr->isEof==0 );
   154300   if( pExpr==0 ){
   154301     pCsr->isEof = 1;
   154302   }else{
   154303     do {
   154304       if( pCsr->isRequireSeek==0 ){
   154305         sqlite3_reset(pCsr->pStmt);
   154306       }
   154307       assert( sqlite3_data_count(pCsr->pStmt)==0 );
   154308       fts3EvalNextRow(pCsr, pExpr, &rc);
   154309       pCsr->isEof = pExpr->bEof;
   154310       pCsr->isRequireSeek = 1;
   154311       pCsr->isMatchinfoNeeded = 1;
   154312       pCsr->iPrevId = pExpr->iDocid;
   154313     }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
   154314   }
   154315 
   154316   /* Check if the cursor is past the end of the docid range specified
   154317   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
   154318   if( rc==SQLITE_OK && (
   154319         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
   154320      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
   154321   )){
   154322     pCsr->isEof = 1;
   154323   }
   154324 
   154325   return rc;
   154326 }
   154327 
   154328 /*
   154329 ** Restart interation for expression pExpr so that the next call to
   154330 ** fts3EvalNext() visits the first row. Do not allow incremental
   154331 ** loading or merging of phrase doclists for this iteration.
   154332 **
   154333 ** If *pRc is other than SQLITE_OK when this function is called, it is
   154334 ** a no-op. If an error occurs within this function, *pRc is set to an
   154335 ** SQLite error code before returning.
   154336 */
   154337 static void fts3EvalRestart(
   154338   Fts3Cursor *pCsr,
   154339   Fts3Expr *pExpr,
   154340   int *pRc
   154341 ){
   154342   if( pExpr && *pRc==SQLITE_OK ){
   154343     Fts3Phrase *pPhrase = pExpr->pPhrase;
   154344 
   154345     if( pPhrase ){
   154346       fts3EvalInvalidatePoslist(pPhrase);
   154347       if( pPhrase->bIncr ){
   154348         int i;
   154349         for(i=0; i<pPhrase->nToken; i++){
   154350           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
   154351           assert( pToken->pDeferred==0 );
   154352           if( pToken->pSegcsr ){
   154353             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
   154354           }
   154355         }
   154356         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
   154357       }
   154358       pPhrase->doclist.pNextDocid = 0;
   154359       pPhrase->doclist.iDocid = 0;
   154360       pPhrase->pOrPoslist = 0;
   154361     }
   154362 
   154363     pExpr->iDocid = 0;
   154364     pExpr->bEof = 0;
   154365     pExpr->bStart = 0;
   154366 
   154367     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
   154368     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
   154369   }
   154370 }
   154371 
   154372 /*
   154373 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
   154374 ** expression rooted at pExpr, the cursor iterates through all rows matched
   154375 ** by pExpr, calling this function for each row. This function increments
   154376 ** the values in Fts3Expr.aMI[] according to the position-list currently
   154377 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
   154378 ** expression nodes.
   154379 */
   154380 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
   154381   if( pExpr ){
   154382     Fts3Phrase *pPhrase = pExpr->pPhrase;
   154383     if( pPhrase && pPhrase->doclist.pList ){
   154384       int iCol = 0;
   154385       char *p = pPhrase->doclist.pList;
   154386 
   154387       assert( *p );
   154388       while( 1 ){
   154389         u8 c = 0;
   154390         int iCnt = 0;
   154391         while( 0xFE & (*p | c) ){
   154392           if( (c&0x80)==0 ) iCnt++;
   154393           c = *p++ & 0x80;
   154394         }
   154395 
   154396         /* aMI[iCol*3 + 1] = Number of occurrences
   154397         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
   154398         */
   154399         pExpr->aMI[iCol*3 + 1] += iCnt;
   154400         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
   154401         if( *p==0x00 ) break;
   154402         p++;
   154403         p += fts3GetVarint32(p, &iCol);
   154404       }
   154405     }
   154406 
   154407     fts3EvalUpdateCounts(pExpr->pLeft);
   154408     fts3EvalUpdateCounts(pExpr->pRight);
   154409   }
   154410 }
   154411 
   154412 /*
   154413 ** Expression pExpr must be of type FTSQUERY_PHRASE.
   154414 **
   154415 ** If it is not already allocated and populated, this function allocates and
   154416 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
   154417 ** of a NEAR expression, then it also allocates and populates the same array
   154418 ** for all other phrases that are part of the NEAR expression.
   154419 **
   154420 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
   154421 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
   154422 */
   154423 static int fts3EvalGatherStats(
   154424   Fts3Cursor *pCsr,               /* Cursor object */
   154425   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
   154426 ){
   154427   int rc = SQLITE_OK;             /* Return code */
   154428 
   154429   assert( pExpr->eType==FTSQUERY_PHRASE );
   154430   if( pExpr->aMI==0 ){
   154431     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   154432     Fts3Expr *pRoot;                /* Root of NEAR expression */
   154433     Fts3Expr *p;                    /* Iterator used for several purposes */
   154434 
   154435     sqlite3_int64 iPrevId = pCsr->iPrevId;
   154436     sqlite3_int64 iDocid;
   154437     u8 bEof;
   154438 
   154439     /* Find the root of the NEAR expression */
   154440     pRoot = pExpr;
   154441     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
   154442       pRoot = pRoot->pParent;
   154443     }
   154444     iDocid = pRoot->iDocid;
   154445     bEof = pRoot->bEof;
   154446     assert( pRoot->bStart );
   154447 
   154448     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
   154449     for(p=pRoot; p; p=p->pLeft){
   154450       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
   154451       assert( pE->aMI==0 );
   154452       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
   154453       if( !pE->aMI ) return SQLITE_NOMEM;
   154454       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
   154455     }
   154456 
   154457     fts3EvalRestart(pCsr, pRoot, &rc);
   154458 
   154459     while( pCsr->isEof==0 && rc==SQLITE_OK ){
   154460 
   154461       do {
   154462         /* Ensure the %_content statement is reset. */
   154463         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
   154464         assert( sqlite3_data_count(pCsr->pStmt)==0 );
   154465 
   154466         /* Advance to the next document */
   154467         fts3EvalNextRow(pCsr, pRoot, &rc);
   154468         pCsr->isEof = pRoot->bEof;
   154469         pCsr->isRequireSeek = 1;
   154470         pCsr->isMatchinfoNeeded = 1;
   154471         pCsr->iPrevId = pRoot->iDocid;
   154472       }while( pCsr->isEof==0
   154473            && pRoot->eType==FTSQUERY_NEAR
   154474            && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
   154475       );
   154476 
   154477       if( rc==SQLITE_OK && pCsr->isEof==0 ){
   154478         fts3EvalUpdateCounts(pRoot);
   154479       }
   154480     }
   154481 
   154482     pCsr->isEof = 0;
   154483     pCsr->iPrevId = iPrevId;
   154484 
   154485     if( bEof ){
   154486       pRoot->bEof = bEof;
   154487     }else{
   154488       /* Caution: pRoot may iterate through docids in ascending or descending
   154489       ** order. For this reason, even though it seems more defensive, the
   154490       ** do loop can not be written:
   154491       **
   154492       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
   154493       */
   154494       fts3EvalRestart(pCsr, pRoot, &rc);
   154495       do {
   154496         fts3EvalNextRow(pCsr, pRoot, &rc);
   154497         assert( pRoot->bEof==0 );
   154498       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
   154499     }
   154500   }
   154501   return rc;
   154502 }
   154503 
   154504 /*
   154505 ** This function is used by the matchinfo() module to query a phrase
   154506 ** expression node for the following information:
   154507 **
   154508 **   1. The total number of occurrences of the phrase in each column of
   154509 **      the FTS table (considering all rows), and
   154510 **
   154511 **   2. For each column, the number of rows in the table for which the
   154512 **      column contains at least one instance of the phrase.
   154513 **
   154514 ** If no error occurs, SQLITE_OK is returned and the values for each column
   154515 ** written into the array aiOut as follows:
   154516 **
   154517 **   aiOut[iCol*3 + 1] = Number of occurrences
   154518 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
   154519 **
   154520 ** Caveats:
   154521 **
   154522 **   * If a phrase consists entirely of deferred tokens, then all output
   154523 **     values are set to the number of documents in the table. In other
   154524 **     words we assume that very common tokens occur exactly once in each
   154525 **     column of each row of the table.
   154526 **
   154527 **   * If a phrase contains some deferred tokens (and some non-deferred
   154528 **     tokens), count the potential occurrence identified by considering
   154529 **     the non-deferred tokens instead of actual phrase occurrences.
   154530 **
   154531 **   * If the phrase is part of a NEAR expression, then only phrase instances
   154532 **     that meet the NEAR constraint are included in the counts.
   154533 */
   154534 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
   154535   Fts3Cursor *pCsr,               /* FTS cursor handle */
   154536   Fts3Expr *pExpr,                /* Phrase expression */
   154537   u32 *aiOut                      /* Array to write results into (see above) */
   154538 ){
   154539   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   154540   int rc = SQLITE_OK;
   154541   int iCol;
   154542 
   154543   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
   154544     assert( pCsr->nDoc>0 );
   154545     for(iCol=0; iCol<pTab->nColumn; iCol++){
   154546       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
   154547       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
   154548     }
   154549   }else{
   154550     rc = fts3EvalGatherStats(pCsr, pExpr);
   154551     if( rc==SQLITE_OK ){
   154552       assert( pExpr->aMI );
   154553       for(iCol=0; iCol<pTab->nColumn; iCol++){
   154554         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
   154555         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
   154556       }
   154557     }
   154558   }
   154559 
   154560   return rc;
   154561 }
   154562 
   154563 /*
   154564 ** The expression pExpr passed as the second argument to this function
   154565 ** must be of type FTSQUERY_PHRASE.
   154566 **
   154567 ** The returned value is either NULL or a pointer to a buffer containing
   154568 ** a position-list indicating the occurrences of the phrase in column iCol
   154569 ** of the current row.
   154570 **
   154571 ** More specifically, the returned buffer contains 1 varint for each
   154572 ** occurrence of the phrase in the column, stored using the normal (delta+2)
   154573 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
   154574 ** if the requested column contains "a b X c d X X" and the position-list
   154575 ** for 'X' is requested, the buffer returned may contain:
   154576 **
   154577 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
   154578 **
   154579 ** This function works regardless of whether or not the phrase is deferred,
   154580 ** incremental, or neither.
   154581 */
   154582 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
   154583   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   154584   Fts3Expr *pExpr,                /* Phrase to return doclist for */
   154585   int iCol,                       /* Column to return position list for */
   154586   char **ppOut                    /* OUT: Pointer to position list */
   154587 ){
   154588   Fts3Phrase *pPhrase = pExpr->pPhrase;
   154589   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   154590   char *pIter;
   154591   int iThis;
   154592   sqlite3_int64 iDocid;
   154593 
   154594   /* If this phrase is applies specifically to some column other than
   154595   ** column iCol, return a NULL pointer.  */
   154596   *ppOut = 0;
   154597   assert( iCol>=0 && iCol<pTab->nColumn );
   154598   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
   154599     return SQLITE_OK;
   154600   }
   154601 
   154602   iDocid = pExpr->iDocid;
   154603   pIter = pPhrase->doclist.pList;
   154604   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
   154605     int rc = SQLITE_OK;
   154606     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
   154607     int bOr = 0;
   154608     u8 bTreeEof = 0;
   154609     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
   154610     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
   154611     int bMatch;
   154612 
   154613     /* Check if this phrase descends from an OR expression node. If not,
   154614     ** return NULL. Otherwise, the entry that corresponds to docid
   154615     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
   154616     ** tree that the node is part of has been marked as EOF, but the node
   154617     ** itself is not EOF, then it may point to an earlier entry. */
   154618     pNear = pExpr;
   154619     for(p=pExpr->pParent; p; p=p->pParent){
   154620       if( p->eType==FTSQUERY_OR ) bOr = 1;
   154621       if( p->eType==FTSQUERY_NEAR ) pNear = p;
   154622       if( p->bEof ) bTreeEof = 1;
   154623     }
   154624     if( bOr==0 ) return SQLITE_OK;
   154625 
   154626     /* This is the descendent of an OR node. In this case we cannot use
   154627     ** an incremental phrase. Load the entire doclist for the phrase
   154628     ** into memory in this case.  */
   154629     if( pPhrase->bIncr ){
   154630       int bEofSave = pNear->bEof;
   154631       fts3EvalRestart(pCsr, pNear, &rc);
   154632       while( rc==SQLITE_OK && !pNear->bEof ){
   154633         fts3EvalNextRow(pCsr, pNear, &rc);
   154634         if( bEofSave==0 && pNear->iDocid==iDocid ) break;
   154635       }
   154636       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
   154637     }
   154638     if( bTreeEof ){
   154639       while( rc==SQLITE_OK && !pNear->bEof ){
   154640         fts3EvalNextRow(pCsr, pNear, &rc);
   154641       }
   154642     }
   154643     if( rc!=SQLITE_OK ) return rc;
   154644 
   154645     bMatch = 1;
   154646     for(p=pNear; p; p=p->pLeft){
   154647       u8 bEof = 0;
   154648       Fts3Expr *pTest = p;
   154649       Fts3Phrase *pPh;
   154650       assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
   154651       if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
   154652       assert( pTest->eType==FTSQUERY_PHRASE );
   154653       pPh = pTest->pPhrase;
   154654 
   154655       pIter = pPh->pOrPoslist;
   154656       iDocid = pPh->iOrDocid;
   154657       if( pCsr->bDesc==bDescDoclist ){
   154658         bEof = !pPh->doclist.nAll ||
   154659           (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
   154660         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
   154661           sqlite3Fts3DoclistNext(
   154662               bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
   154663               &pIter, &iDocid, &bEof
   154664           );
   154665         }
   154666       }else{
   154667         bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
   154668         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
   154669           int dummy;
   154670           sqlite3Fts3DoclistPrev(
   154671               bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
   154672               &pIter, &iDocid, &dummy, &bEof
   154673               );
   154674         }
   154675       }
   154676       pPh->pOrPoslist = pIter;
   154677       pPh->iOrDocid = iDocid;
   154678       if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
   154679     }
   154680 
   154681     if( bMatch ){
   154682       pIter = pPhrase->pOrPoslist;
   154683     }else{
   154684       pIter = 0;
   154685     }
   154686   }
   154687   if( pIter==0 ) return SQLITE_OK;
   154688 
   154689   if( *pIter==0x01 ){
   154690     pIter++;
   154691     pIter += fts3GetVarint32(pIter, &iThis);
   154692   }else{
   154693     iThis = 0;
   154694   }
   154695   while( iThis<iCol ){
   154696     fts3ColumnlistCopy(0, &pIter);
   154697     if( *pIter==0x00 ) return SQLITE_OK;
   154698     pIter++;
   154699     pIter += fts3GetVarint32(pIter, &iThis);
   154700   }
   154701   if( *pIter==0x00 ){
   154702     pIter = 0;
   154703   }
   154704 
   154705   *ppOut = ((iCol==iThis)?pIter:0);
   154706   return SQLITE_OK;
   154707 }
   154708 
   154709 /*
   154710 ** Free all components of the Fts3Phrase structure that were allocated by
   154711 ** the eval module. Specifically, this means to free:
   154712 **
   154713 **   * the contents of pPhrase->doclist, and
   154714 **   * any Fts3MultiSegReader objects held by phrase tokens.
   154715 */
   154716 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
   154717   if( pPhrase ){
   154718     int i;
   154719     sqlite3_free(pPhrase->doclist.aAll);
   154720     fts3EvalInvalidatePoslist(pPhrase);
   154721     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
   154722     for(i=0; i<pPhrase->nToken; i++){
   154723       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
   154724       pPhrase->aToken[i].pSegcsr = 0;
   154725     }
   154726   }
   154727 }
   154728 
   154729 
   154730 /*
   154731 ** Return SQLITE_CORRUPT_VTAB.
   154732 */
   154733 #ifdef SQLITE_DEBUG
   154734 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
   154735   return SQLITE_CORRUPT_VTAB;
   154736 }
   154737 #endif
   154738 
   154739 #if !SQLITE_CORE
   154740 /*
   154741 ** Initialize API pointer table, if required.
   154742 */
   154743 #ifdef _WIN32
   154744 __declspec(dllexport)
   154745 #endif
   154746 SQLITE_API int sqlite3_fts3_init(
   154747   sqlite3 *db,
   154748   char **pzErrMsg,
   154749   const sqlite3_api_routines *pApi
   154750 ){
   154751   SQLITE_EXTENSION_INIT2(pApi)
   154752   return sqlite3Fts3Init(db);
   154753 }
   154754 #endif
   154755 
   154756 #endif
   154757 
   154758 /************** End of fts3.c ************************************************/
   154759 /************** Begin file fts3_aux.c ****************************************/
   154760 /*
   154761 ** 2011 Jan 27
   154762 **
   154763 ** The author disclaims copyright to this source code.  In place of
   154764 ** a legal notice, here is a blessing:
   154765 **
   154766 **    May you do good and not evil.
   154767 **    May you find forgiveness for yourself and forgive others.
   154768 **    May you share freely, never taking more than you give.
   154769 **
   154770 ******************************************************************************
   154771 **
   154772 */
   154773 /* #include "fts3Int.h" */
   154774 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   154775 
   154776 /* #include <string.h> */
   154777 /* #include <assert.h> */
   154778 
   154779 typedef struct Fts3auxTable Fts3auxTable;
   154780 typedef struct Fts3auxCursor Fts3auxCursor;
   154781 
   154782 struct Fts3auxTable {
   154783   sqlite3_vtab base;              /* Base class used by SQLite core */
   154784   Fts3Table *pFts3Tab;
   154785 };
   154786 
   154787 struct Fts3auxCursor {
   154788   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   154789   Fts3MultiSegReader csr;        /* Must be right after "base" */
   154790   Fts3SegFilter filter;
   154791   char *zStop;
   154792   int nStop;                      /* Byte-length of string zStop */
   154793   int iLangid;                    /* Language id to query */
   154794   int isEof;                      /* True if cursor is at EOF */
   154795   sqlite3_int64 iRowid;           /* Current rowid */
   154796 
   154797   int iCol;                       /* Current value of 'col' column */
   154798   int nStat;                      /* Size of aStat[] array */
   154799   struct Fts3auxColstats {
   154800     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
   154801     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
   154802   } *aStat;
   154803 };
   154804 
   154805 /*
   154806 ** Schema of the terms table.
   154807 */
   154808 #define FTS3_AUX_SCHEMA \
   154809   "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
   154810 
   154811 /*
   154812 ** This function does all the work for both the xConnect and xCreate methods.
   154813 ** These tables have no persistent representation of their own, so xConnect
   154814 ** and xCreate are identical operations.
   154815 */
   154816 static int fts3auxConnectMethod(
   154817   sqlite3 *db,                    /* Database connection */
   154818   void *pUnused,                  /* Unused */
   154819   int argc,                       /* Number of elements in argv array */
   154820   const char * const *argv,       /* xCreate/xConnect argument array */
   154821   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   154822   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   154823 ){
   154824   char const *zDb;                /* Name of database (e.g. "main") */
   154825   char const *zFts3;              /* Name of fts3 table */
   154826   int nDb;                        /* Result of strlen(zDb) */
   154827   int nFts3;                      /* Result of strlen(zFts3) */
   154828   int nByte;                      /* Bytes of space to allocate here */
   154829   int rc;                         /* value returned by declare_vtab() */
   154830   Fts3auxTable *p;                /* Virtual table object to return */
   154831 
   154832   UNUSED_PARAMETER(pUnused);
   154833 
   154834   /* The user should invoke this in one of two forms:
   154835   **
   154836   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
   154837   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
   154838   */
   154839   if( argc!=4 && argc!=5 ) goto bad_args;
   154840 
   154841   zDb = argv[1];
   154842   nDb = (int)strlen(zDb);
   154843   if( argc==5 ){
   154844     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
   154845       zDb = argv[3];
   154846       nDb = (int)strlen(zDb);
   154847       zFts3 = argv[4];
   154848     }else{
   154849       goto bad_args;
   154850     }
   154851   }else{
   154852     zFts3 = argv[3];
   154853   }
   154854   nFts3 = (int)strlen(zFts3);
   154855 
   154856   rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
   154857   if( rc!=SQLITE_OK ) return rc;
   154858 
   154859   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
   154860   p = (Fts3auxTable *)sqlite3_malloc(nByte);
   154861   if( !p ) return SQLITE_NOMEM;
   154862   memset(p, 0, nByte);
   154863 
   154864   p->pFts3Tab = (Fts3Table *)&p[1];
   154865   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
   154866   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
   154867   p->pFts3Tab->db = db;
   154868   p->pFts3Tab->nIndex = 1;
   154869 
   154870   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
   154871   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
   154872   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
   154873 
   154874   *ppVtab = (sqlite3_vtab *)p;
   154875   return SQLITE_OK;
   154876 
   154877  bad_args:
   154878   sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
   154879   return SQLITE_ERROR;
   154880 }
   154881 
   154882 /*
   154883 ** This function does the work for both the xDisconnect and xDestroy methods.
   154884 ** These tables have no persistent representation of their own, so xDisconnect
   154885 ** and xDestroy are identical operations.
   154886 */
   154887 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
   154888   Fts3auxTable *p = (Fts3auxTable *)pVtab;
   154889   Fts3Table *pFts3 = p->pFts3Tab;
   154890   int i;
   154891 
   154892   /* Free any prepared statements held */
   154893   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
   154894     sqlite3_finalize(pFts3->aStmt[i]);
   154895   }
   154896   sqlite3_free(pFts3->zSegmentsTbl);
   154897   sqlite3_free(p);
   154898   return SQLITE_OK;
   154899 }
   154900 
   154901 #define FTS4AUX_EQ_CONSTRAINT 1
   154902 #define FTS4AUX_GE_CONSTRAINT 2
   154903 #define FTS4AUX_LE_CONSTRAINT 4
   154904 
   154905 /*
   154906 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   154907 */
   154908 static int fts3auxBestIndexMethod(
   154909   sqlite3_vtab *pVTab,
   154910   sqlite3_index_info *pInfo
   154911 ){
   154912   int i;
   154913   int iEq = -1;
   154914   int iGe = -1;
   154915   int iLe = -1;
   154916   int iLangid = -1;
   154917   int iNext = 1;                  /* Next free argvIndex value */
   154918 
   154919   UNUSED_PARAMETER(pVTab);
   154920 
   154921   /* This vtab delivers always results in "ORDER BY term ASC" order. */
   154922   if( pInfo->nOrderBy==1
   154923    && pInfo->aOrderBy[0].iColumn==0
   154924    && pInfo->aOrderBy[0].desc==0
   154925   ){
   154926     pInfo->orderByConsumed = 1;
   154927   }
   154928 
   154929   /* Search for equality and range constraints on the "term" column.
   154930   ** And equality constraints on the hidden "languageid" column. */
   154931   for(i=0; i<pInfo->nConstraint; i++){
   154932     if( pInfo->aConstraint[i].usable ){
   154933       int op = pInfo->aConstraint[i].op;
   154934       int iCol = pInfo->aConstraint[i].iColumn;
   154935 
   154936       if( iCol==0 ){
   154937         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
   154938         if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
   154939         if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
   154940         if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
   154941         if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
   154942       }
   154943       if( iCol==4 ){
   154944         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
   154945       }
   154946     }
   154947   }
   154948 
   154949   if( iEq>=0 ){
   154950     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
   154951     pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
   154952     pInfo->estimatedCost = 5;
   154953   }else{
   154954     pInfo->idxNum = 0;
   154955     pInfo->estimatedCost = 20000;
   154956     if( iGe>=0 ){
   154957       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
   154958       pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
   154959       pInfo->estimatedCost /= 2;
   154960     }
   154961     if( iLe>=0 ){
   154962       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
   154963       pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
   154964       pInfo->estimatedCost /= 2;
   154965     }
   154966   }
   154967   if( iLangid>=0 ){
   154968     pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
   154969     pInfo->estimatedCost--;
   154970   }
   154971 
   154972   return SQLITE_OK;
   154973 }
   154974 
   154975 /*
   154976 ** xOpen - Open a cursor.
   154977 */
   154978 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   154979   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
   154980 
   154981   UNUSED_PARAMETER(pVTab);
   154982 
   154983   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
   154984   if( !pCsr ) return SQLITE_NOMEM;
   154985   memset(pCsr, 0, sizeof(Fts3auxCursor));
   154986 
   154987   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   154988   return SQLITE_OK;
   154989 }
   154990 
   154991 /*
   154992 ** xClose - Close a cursor.
   154993 */
   154994 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
   154995   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   154996   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   154997 
   154998   sqlite3Fts3SegmentsClose(pFts3);
   154999   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   155000   sqlite3_free((void *)pCsr->filter.zTerm);
   155001   sqlite3_free(pCsr->zStop);
   155002   sqlite3_free(pCsr->aStat);
   155003   sqlite3_free(pCsr);
   155004   return SQLITE_OK;
   155005 }
   155006 
   155007 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
   155008   if( nSize>pCsr->nStat ){
   155009     struct Fts3auxColstats *aNew;
   155010     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
   155011         sizeof(struct Fts3auxColstats) * nSize
   155012     );
   155013     if( aNew==0 ) return SQLITE_NOMEM;
   155014     memset(&aNew[pCsr->nStat], 0,
   155015         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
   155016     );
   155017     pCsr->aStat = aNew;
   155018     pCsr->nStat = nSize;
   155019   }
   155020   return SQLITE_OK;
   155021 }
   155022 
   155023 /*
   155024 ** xNext - Advance the cursor to the next row, if any.
   155025 */
   155026 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
   155027   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   155028   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   155029   int rc;
   155030 
   155031   /* Increment our pretend rowid value. */
   155032   pCsr->iRowid++;
   155033 
   155034   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
   155035     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
   155036   }
   155037 
   155038   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
   155039   if( rc==SQLITE_ROW ){
   155040     int i = 0;
   155041     int nDoclist = pCsr->csr.nDoclist;
   155042     char *aDoclist = pCsr->csr.aDoclist;
   155043     int iCol;
   155044 
   155045     int eState = 0;
   155046 
   155047     if( pCsr->zStop ){
   155048       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
   155049       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
   155050       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
   155051         pCsr->isEof = 1;
   155052         return SQLITE_OK;
   155053       }
   155054     }
   155055 
   155056     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
   155057     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
   155058     iCol = 0;
   155059 
   155060     while( i<nDoclist ){
   155061       sqlite3_int64 v = 0;
   155062 
   155063       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
   155064       switch( eState ){
   155065         /* State 0. In this state the integer just read was a docid. */
   155066         case 0:
   155067           pCsr->aStat[0].nDoc++;
   155068           eState = 1;
   155069           iCol = 0;
   155070           break;
   155071 
   155072         /* State 1. In this state we are expecting either a 1, indicating
   155073         ** that the following integer will be a column number, or the
   155074         ** start of a position list for column 0.
   155075         **
   155076         ** The only difference between state 1 and state 2 is that if the
   155077         ** integer encountered in state 1 is not 0 or 1, then we need to
   155078         ** increment the column 0 "nDoc" count for this term.
   155079         */
   155080         case 1:
   155081           assert( iCol==0 );
   155082           if( v>1 ){
   155083             pCsr->aStat[1].nDoc++;
   155084           }
   155085           eState = 2;
   155086           /* fall through */
   155087 
   155088         case 2:
   155089           if( v==0 ){       /* 0x00. Next integer will be a docid. */
   155090             eState = 0;
   155091           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
   155092             eState = 3;
   155093           }else{            /* 2 or greater. A position. */
   155094             pCsr->aStat[iCol+1].nOcc++;
   155095             pCsr->aStat[0].nOcc++;
   155096           }
   155097           break;
   155098 
   155099         /* State 3. The integer just read is a column number. */
   155100         default: assert( eState==3 );
   155101           iCol = (int)v;
   155102           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
   155103           pCsr->aStat[iCol+1].nDoc++;
   155104           eState = 2;
   155105           break;
   155106       }
   155107     }
   155108 
   155109     pCsr->iCol = 0;
   155110     rc = SQLITE_OK;
   155111   }else{
   155112     pCsr->isEof = 1;
   155113   }
   155114   return rc;
   155115 }
   155116 
   155117 /*
   155118 ** xFilter - Initialize a cursor to point at the start of its data.
   155119 */
   155120 static int fts3auxFilterMethod(
   155121   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   155122   int idxNum,                     /* Strategy index */
   155123   const char *idxStr,             /* Unused */
   155124   int nVal,                       /* Number of elements in apVal */
   155125   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   155126 ){
   155127   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   155128   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   155129   int rc;
   155130   int isScan = 0;
   155131   int iLangVal = 0;               /* Language id to query */
   155132 
   155133   int iEq = -1;                   /* Index of term=? value in apVal */
   155134   int iGe = -1;                   /* Index of term>=? value in apVal */
   155135   int iLe = -1;                   /* Index of term<=? value in apVal */
   155136   int iLangid = -1;               /* Index of languageid=? value in apVal */
   155137   int iNext = 0;
   155138 
   155139   UNUSED_PARAMETER(nVal);
   155140   UNUSED_PARAMETER(idxStr);
   155141 
   155142   assert( idxStr==0 );
   155143   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
   155144        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
   155145        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
   155146   );
   155147 
   155148   if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
   155149     iEq = iNext++;
   155150   }else{
   155151     isScan = 1;
   155152     if( idxNum & FTS4AUX_GE_CONSTRAINT ){
   155153       iGe = iNext++;
   155154     }
   155155     if( idxNum & FTS4AUX_LE_CONSTRAINT ){
   155156       iLe = iNext++;
   155157     }
   155158   }
   155159   if( iNext<nVal ){
   155160     iLangid = iNext++;
   155161   }
   155162 
   155163   /* In case this cursor is being reused, close and zero it. */
   155164   testcase(pCsr->filter.zTerm);
   155165   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   155166   sqlite3_free((void *)pCsr->filter.zTerm);
   155167   sqlite3_free(pCsr->aStat);
   155168   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
   155169 
   155170   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   155171   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
   155172 
   155173   if( iEq>=0 || iGe>=0 ){
   155174     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
   155175     assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
   155176     if( zStr ){
   155177       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
   155178       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
   155179       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
   155180     }
   155181   }
   155182 
   155183   if( iLe>=0 ){
   155184     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
   155185     pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
   155186     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
   155187   }
   155188 
   155189   if( iLangid>=0 ){
   155190     iLangVal = sqlite3_value_int(apVal[iLangid]);
   155191 
   155192     /* If the user specified a negative value for the languageid, use zero
   155193     ** instead. This works, as the "languageid=?" constraint will also
   155194     ** be tested by the VDBE layer. The test will always be false (since
   155195     ** this module will not return a row with a negative languageid), and
   155196     ** so the overall query will return zero rows.  */
   155197     if( iLangVal<0 ) iLangVal = 0;
   155198   }
   155199   pCsr->iLangid = iLangVal;
   155200 
   155201   rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
   155202       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
   155203   );
   155204   if( rc==SQLITE_OK ){
   155205     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
   155206   }
   155207 
   155208   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
   155209   return rc;
   155210 }
   155211 
   155212 /*
   155213 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   155214 */
   155215 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
   155216   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   155217   return pCsr->isEof;
   155218 }
   155219 
   155220 /*
   155221 ** xColumn - Return a column value.
   155222 */
   155223 static int fts3auxColumnMethod(
   155224   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   155225   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   155226   int iCol                        /* Index of column to read value from */
   155227 ){
   155228   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
   155229 
   155230   assert( p->isEof==0 );
   155231   switch( iCol ){
   155232     case 0: /* term */
   155233       sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
   155234       break;
   155235 
   155236     case 1: /* col */
   155237       if( p->iCol ){
   155238         sqlite3_result_int(pCtx, p->iCol-1);
   155239       }else{
   155240         sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
   155241       }
   155242       break;
   155243 
   155244     case 2: /* documents */
   155245       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
   155246       break;
   155247 
   155248     case 3: /* occurrences */
   155249       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
   155250       break;
   155251 
   155252     default: /* languageid */
   155253       assert( iCol==4 );
   155254       sqlite3_result_int(pCtx, p->iLangid);
   155255       break;
   155256   }
   155257 
   155258   return SQLITE_OK;
   155259 }
   155260 
   155261 /*
   155262 ** xRowid - Return the current rowid for the cursor.
   155263 */
   155264 static int fts3auxRowidMethod(
   155265   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   155266   sqlite_int64 *pRowid            /* OUT: Rowid value */
   155267 ){
   155268   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   155269   *pRowid = pCsr->iRowid;
   155270   return SQLITE_OK;
   155271 }
   155272 
   155273 /*
   155274 ** Register the fts3aux module with database connection db. Return SQLITE_OK
   155275 ** if successful or an error code if sqlite3_create_module() fails.
   155276 */
   155277 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
   155278   static const sqlite3_module fts3aux_module = {
   155279      0,                           /* iVersion      */
   155280      fts3auxConnectMethod,        /* xCreate       */
   155281      fts3auxConnectMethod,        /* xConnect      */
   155282      fts3auxBestIndexMethod,      /* xBestIndex    */
   155283      fts3auxDisconnectMethod,     /* xDisconnect   */
   155284      fts3auxDisconnectMethod,     /* xDestroy      */
   155285      fts3auxOpenMethod,           /* xOpen         */
   155286      fts3auxCloseMethod,          /* xClose        */
   155287      fts3auxFilterMethod,         /* xFilter       */
   155288      fts3auxNextMethod,           /* xNext         */
   155289      fts3auxEofMethod,            /* xEof          */
   155290      fts3auxColumnMethod,         /* xColumn       */
   155291      fts3auxRowidMethod,          /* xRowid        */
   155292      0,                           /* xUpdate       */
   155293      0,                           /* xBegin        */
   155294      0,                           /* xSync         */
   155295      0,                           /* xCommit       */
   155296      0,                           /* xRollback     */
   155297      0,                           /* xFindFunction */
   155298      0,                           /* xRename       */
   155299      0,                           /* xSavepoint    */
   155300      0,                           /* xRelease      */
   155301      0                            /* xRollbackTo   */
   155302   };
   155303   int rc;                         /* Return code */
   155304 
   155305   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
   155306   return rc;
   155307 }
   155308 
   155309 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   155310 
   155311 /************** End of fts3_aux.c ********************************************/
   155312 /************** Begin file fts3_expr.c ***************************************/
   155313 /*
   155314 ** 2008 Nov 28
   155315 **
   155316 ** The author disclaims copyright to this source code.  In place of
   155317 ** a legal notice, here is a blessing:
   155318 **
   155319 **    May you do good and not evil.
   155320 **    May you find forgiveness for yourself and forgive others.
   155321 **    May you share freely, never taking more than you give.
   155322 **
   155323 ******************************************************************************
   155324 **
   155325 ** This module contains code that implements a parser for fts3 query strings
   155326 ** (the right-hand argument to the MATCH operator). Because the supported
   155327 ** syntax is relatively simple, the whole tokenizer/parser system is
   155328 ** hand-coded.
   155329 */
   155330 /* #include "fts3Int.h" */
   155331 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   155332 
   155333 /*
   155334 ** By default, this module parses the legacy syntax that has been
   155335 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
   155336 ** is defined, then it uses the new syntax. The differences between
   155337 ** the new and the old syntaxes are:
   155338 **
   155339 **  a) The new syntax supports parenthesis. The old does not.
   155340 **
   155341 **  b) The new syntax supports the AND and NOT operators. The old does not.
   155342 **
   155343 **  c) The old syntax supports the "-" token qualifier. This is not
   155344 **     supported by the new syntax (it is replaced by the NOT operator).
   155345 **
   155346 **  d) When using the old syntax, the OR operator has a greater precedence
   155347 **     than an implicit AND. When using the new, both implicity and explicit
   155348 **     AND operators have a higher precedence than OR.
   155349 **
   155350 ** If compiled with SQLITE_TEST defined, then this module exports the
   155351 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
   155352 ** to zero causes the module to use the old syntax. If it is set to
   155353 ** non-zero the new syntax is activated. This is so both syntaxes can
   155354 ** be tested using a single build of testfixture.
   155355 **
   155356 ** The following describes the syntax supported by the fts3 MATCH
   155357 ** operator in a similar format to that used by the lemon parser
   155358 ** generator. This module does not use actually lemon, it uses a
   155359 ** custom parser.
   155360 **
   155361 **   query ::= andexpr (OR andexpr)*.
   155362 **
   155363 **   andexpr ::= notexpr (AND? notexpr)*.
   155364 **
   155365 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
   155366 **   notexpr ::= LP query RP.
   155367 **
   155368 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
   155369 **
   155370 **   distance_opt ::= .
   155371 **   distance_opt ::= / INTEGER.
   155372 **
   155373 **   phrase ::= TOKEN.
   155374 **   phrase ::= COLUMN:TOKEN.
   155375 **   phrase ::= "TOKEN TOKEN TOKEN...".
   155376 */
   155377 
   155378 #ifdef SQLITE_TEST
   155379 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
   155380 #else
   155381 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   155382 #  define sqlite3_fts3_enable_parentheses 1
   155383 # else
   155384 #  define sqlite3_fts3_enable_parentheses 0
   155385 # endif
   155386 #endif
   155387 
   155388 /*
   155389 ** Default span for NEAR operators.
   155390 */
   155391 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
   155392 
   155393 /* #include <string.h> */
   155394 /* #include <assert.h> */
   155395 
   155396 /*
   155397 ** isNot:
   155398 **   This variable is used by function getNextNode(). When getNextNode() is
   155399 **   called, it sets ParseContext.isNot to true if the 'next node' is a
   155400 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
   155401 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
   155402 **   zero.
   155403 */
   155404 typedef struct ParseContext ParseContext;
   155405 struct ParseContext {
   155406   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
   155407   int iLangid;                        /* Language id used with tokenizer */
   155408   const char **azCol;                 /* Array of column names for fts3 table */
   155409   int bFts4;                          /* True to allow FTS4-only syntax */
   155410   int nCol;                           /* Number of entries in azCol[] */
   155411   int iDefaultCol;                    /* Default column to query */
   155412   int isNot;                          /* True if getNextNode() sees a unary - */
   155413   sqlite3_context *pCtx;              /* Write error message here */
   155414   int nNest;                          /* Number of nested brackets */
   155415 };
   155416 
   155417 /*
   155418 ** This function is equivalent to the standard isspace() function.
   155419 **
   155420 ** The standard isspace() can be awkward to use safely, because although it
   155421 ** is defined to accept an argument of type int, its behavior when passed
   155422 ** an integer that falls outside of the range of the unsigned char type
   155423 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
   155424 ** is defined to accept an argument of type char, and always returns 0 for
   155425 ** any values that fall outside of the range of the unsigned char type (i.e.
   155426 ** negative values).
   155427 */
   155428 static int fts3isspace(char c){
   155429   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
   155430 }
   155431 
   155432 /*
   155433 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
   155434 ** zero the memory before returning a pointer to it. If unsuccessful,
   155435 ** return NULL.
   155436 */
   155437 static void *fts3MallocZero(int nByte){
   155438   void *pRet = sqlite3_malloc(nByte);
   155439   if( pRet ) memset(pRet, 0, nByte);
   155440   return pRet;
   155441 }
   155442 
   155443 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
   155444   sqlite3_tokenizer *pTokenizer,
   155445   int iLangid,
   155446   const char *z,
   155447   int n,
   155448   sqlite3_tokenizer_cursor **ppCsr
   155449 ){
   155450   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   155451   sqlite3_tokenizer_cursor *pCsr = 0;
   155452   int rc;
   155453 
   155454   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
   155455   assert( rc==SQLITE_OK || pCsr==0 );
   155456   if( rc==SQLITE_OK ){
   155457     pCsr->pTokenizer = pTokenizer;
   155458     if( pModule->iVersion>=1 ){
   155459       rc = pModule->xLanguageid(pCsr, iLangid);
   155460       if( rc!=SQLITE_OK ){
   155461         pModule->xClose(pCsr);
   155462         pCsr = 0;
   155463       }
   155464     }
   155465   }
   155466   *ppCsr = pCsr;
   155467   return rc;
   155468 }
   155469 
   155470 /*
   155471 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
   155472 ** call fts3ExprParse(). So this forward declaration is required.
   155473 */
   155474 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
   155475 
   155476 /*
   155477 ** Extract the next token from buffer z (length n) using the tokenizer
   155478 ** and other information (column names etc.) in pParse. Create an Fts3Expr
   155479 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
   155480 ** single token and set *ppExpr to point to it. If the end of the buffer is
   155481 ** reached before a token is found, set *ppExpr to zero. It is the
   155482 ** responsibility of the caller to eventually deallocate the allocated
   155483 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
   155484 **
   155485 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
   155486 ** fails.
   155487 */
   155488 static int getNextToken(
   155489   ParseContext *pParse,                   /* fts3 query parse context */
   155490   int iCol,                               /* Value for Fts3Phrase.iColumn */
   155491   const char *z, int n,                   /* Input string */
   155492   Fts3Expr **ppExpr,                      /* OUT: expression */
   155493   int *pnConsumed                         /* OUT: Number of bytes consumed */
   155494 ){
   155495   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   155496   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   155497   int rc;
   155498   sqlite3_tokenizer_cursor *pCursor;
   155499   Fts3Expr *pRet = 0;
   155500   int i = 0;
   155501 
   155502   /* Set variable i to the maximum number of bytes of input to tokenize. */
   155503   for(i=0; i<n; i++){
   155504     if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
   155505     if( z[i]=='"' ) break;
   155506   }
   155507 
   155508   *pnConsumed = i;
   155509   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
   155510   if( rc==SQLITE_OK ){
   155511     const char *zToken;
   155512     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
   155513     int nByte;                               /* total space to allocate */
   155514 
   155515     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
   155516     if( rc==SQLITE_OK ){
   155517       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
   155518       pRet = (Fts3Expr *)fts3MallocZero(nByte);
   155519       if( !pRet ){
   155520         rc = SQLITE_NOMEM;
   155521       }else{
   155522         pRet->eType = FTSQUERY_PHRASE;
   155523         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
   155524         pRet->pPhrase->nToken = 1;
   155525         pRet->pPhrase->iColumn = iCol;
   155526         pRet->pPhrase->aToken[0].n = nToken;
   155527         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
   155528         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
   155529 
   155530         if( iEnd<n && z[iEnd]=='*' ){
   155531           pRet->pPhrase->aToken[0].isPrefix = 1;
   155532           iEnd++;
   155533         }
   155534 
   155535         while( 1 ){
   155536           if( !sqlite3_fts3_enable_parentheses
   155537            && iStart>0 && z[iStart-1]=='-'
   155538           ){
   155539             pParse->isNot = 1;
   155540             iStart--;
   155541           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
   155542             pRet->pPhrase->aToken[0].bFirst = 1;
   155543             iStart--;
   155544           }else{
   155545             break;
   155546           }
   155547         }
   155548 
   155549       }
   155550       *pnConsumed = iEnd;
   155551     }else if( i && rc==SQLITE_DONE ){
   155552       rc = SQLITE_OK;
   155553     }
   155554 
   155555     pModule->xClose(pCursor);
   155556   }
   155557 
   155558   *ppExpr = pRet;
   155559   return rc;
   155560 }
   155561 
   155562 
   155563 /*
   155564 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
   155565 ** then free the old allocation.
   155566 */
   155567 static void *fts3ReallocOrFree(void *pOrig, int nNew){
   155568   void *pRet = sqlite3_realloc(pOrig, nNew);
   155569   if( !pRet ){
   155570     sqlite3_free(pOrig);
   155571   }
   155572   return pRet;
   155573 }
   155574 
   155575 /*
   155576 ** Buffer zInput, length nInput, contains the contents of a quoted string
   155577 ** that appeared as part of an fts3 query expression. Neither quote character
   155578 ** is included in the buffer. This function attempts to tokenize the entire
   155579 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
   155580 ** containing the results.
   155581 **
   155582 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
   155583 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
   155584 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
   155585 ** to 0.
   155586 */
   155587 static int getNextString(
   155588   ParseContext *pParse,                   /* fts3 query parse context */
   155589   const char *zInput, int nInput,         /* Input string */
   155590   Fts3Expr **ppExpr                       /* OUT: expression */
   155591 ){
   155592   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   155593   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   155594   int rc;
   155595   Fts3Expr *p = 0;
   155596   sqlite3_tokenizer_cursor *pCursor = 0;
   155597   char *zTemp = 0;
   155598   int nTemp = 0;
   155599 
   155600   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   155601   int nToken = 0;
   155602 
   155603   /* The final Fts3Expr data structure, including the Fts3Phrase,
   155604   ** Fts3PhraseToken structures token buffers are all stored as a single
   155605   ** allocation so that the expression can be freed with a single call to
   155606   ** sqlite3_free(). Setting this up requires a two pass approach.
   155607   **
   155608   ** The first pass, in the block below, uses a tokenizer cursor to iterate
   155609   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
   155610   ** to assemble data in two dynamic buffers:
   155611   **
   155612   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
   155613   **             structure, followed by the array of Fts3PhraseToken
   155614   **             structures. This pass only populates the Fts3PhraseToken array.
   155615   **
   155616   **   Buffer zTemp: Contains copies of all tokens.
   155617   **
   155618   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
   155619   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
   155620   ** structures.
   155621   */
   155622   rc = sqlite3Fts3OpenTokenizer(
   155623       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
   155624   if( rc==SQLITE_OK ){
   155625     int ii;
   155626     for(ii=0; rc==SQLITE_OK; ii++){
   155627       const char *zByte;
   155628       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
   155629       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
   155630       if( rc==SQLITE_OK ){
   155631         Fts3PhraseToken *pToken;
   155632 
   155633         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
   155634         if( !p ) goto no_mem;
   155635 
   155636         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
   155637         if( !zTemp ) goto no_mem;
   155638 
   155639         assert( nToken==ii );
   155640         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
   155641         memset(pToken, 0, sizeof(Fts3PhraseToken));
   155642 
   155643         memcpy(&zTemp[nTemp], zByte, nByte);
   155644         nTemp += nByte;
   155645 
   155646         pToken->n = nByte;
   155647         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
   155648         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
   155649         nToken = ii+1;
   155650       }
   155651     }
   155652 
   155653     pModule->xClose(pCursor);
   155654     pCursor = 0;
   155655   }
   155656 
   155657   if( rc==SQLITE_DONE ){
   155658     int jj;
   155659     char *zBuf = 0;
   155660 
   155661     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
   155662     if( !p ) goto no_mem;
   155663     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
   155664     p->eType = FTSQUERY_PHRASE;
   155665     p->pPhrase = (Fts3Phrase *)&p[1];
   155666     p->pPhrase->iColumn = pParse->iDefaultCol;
   155667     p->pPhrase->nToken = nToken;
   155668 
   155669     zBuf = (char *)&p->pPhrase->aToken[nToken];
   155670     if( zTemp ){
   155671       memcpy(zBuf, zTemp, nTemp);
   155672       sqlite3_free(zTemp);
   155673     }else{
   155674       assert( nTemp==0 );
   155675     }
   155676 
   155677     for(jj=0; jj<p->pPhrase->nToken; jj++){
   155678       p->pPhrase->aToken[jj].z = zBuf;
   155679       zBuf += p->pPhrase->aToken[jj].n;
   155680     }
   155681     rc = SQLITE_OK;
   155682   }
   155683 
   155684   *ppExpr = p;
   155685   return rc;
   155686 no_mem:
   155687 
   155688   if( pCursor ){
   155689     pModule->xClose(pCursor);
   155690   }
   155691   sqlite3_free(zTemp);
   155692   sqlite3_free(p);
   155693   *ppExpr = 0;
   155694   return SQLITE_NOMEM;
   155695 }
   155696 
   155697 /*
   155698 ** The output variable *ppExpr is populated with an allocated Fts3Expr
   155699 ** structure, or set to 0 if the end of the input buffer is reached.
   155700 **
   155701 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
   155702 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
   155703 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
   155704 */
   155705 static int getNextNode(
   155706   ParseContext *pParse,                   /* fts3 query parse context */
   155707   const char *z, int n,                   /* Input string */
   155708   Fts3Expr **ppExpr,                      /* OUT: expression */
   155709   int *pnConsumed                         /* OUT: Number of bytes consumed */
   155710 ){
   155711   static const struct Fts3Keyword {
   155712     char *z;                              /* Keyword text */
   155713     unsigned char n;                      /* Length of the keyword */
   155714     unsigned char parenOnly;              /* Only valid in paren mode */
   155715     unsigned char eType;                  /* Keyword code */
   155716   } aKeyword[] = {
   155717     { "OR" ,  2, 0, FTSQUERY_OR   },
   155718     { "AND",  3, 1, FTSQUERY_AND  },
   155719     { "NOT",  3, 1, FTSQUERY_NOT  },
   155720     { "NEAR", 4, 0, FTSQUERY_NEAR }
   155721   };
   155722   int ii;
   155723   int iCol;
   155724   int iColLen;
   155725   int rc;
   155726   Fts3Expr *pRet = 0;
   155727 
   155728   const char *zInput = z;
   155729   int nInput = n;
   155730 
   155731   pParse->isNot = 0;
   155732 
   155733   /* Skip over any whitespace before checking for a keyword, an open or
   155734   ** close bracket, or a quoted string.
   155735   */
   155736   while( nInput>0 && fts3isspace(*zInput) ){
   155737     nInput--;
   155738     zInput++;
   155739   }
   155740   if( nInput==0 ){
   155741     return SQLITE_DONE;
   155742   }
   155743 
   155744   /* See if we are dealing with a keyword. */
   155745   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
   155746     const struct Fts3Keyword *pKey = &aKeyword[ii];
   155747 
   155748     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
   155749       continue;
   155750     }
   155751 
   155752     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
   155753       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
   155754       int nKey = pKey->n;
   155755       char cNext;
   155756 
   155757       /* If this is a "NEAR" keyword, check for an explicit nearness. */
   155758       if( pKey->eType==FTSQUERY_NEAR ){
   155759         assert( nKey==4 );
   155760         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
   155761           nNear = 0;
   155762           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
   155763             nNear = nNear * 10 + (zInput[nKey] - '0');
   155764           }
   155765         }
   155766       }
   155767 
   155768       /* At this point this is probably a keyword. But for that to be true,
   155769       ** the next byte must contain either whitespace, an open or close
   155770       ** parenthesis, a quote character, or EOF.
   155771       */
   155772       cNext = zInput[nKey];
   155773       if( fts3isspace(cNext)
   155774        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
   155775       ){
   155776         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
   155777         if( !pRet ){
   155778           return SQLITE_NOMEM;
   155779         }
   155780         pRet->eType = pKey->eType;
   155781         pRet->nNear = nNear;
   155782         *ppExpr = pRet;
   155783         *pnConsumed = (int)((zInput - z) + nKey);
   155784         return SQLITE_OK;
   155785       }
   155786 
   155787       /* Turns out that wasn't a keyword after all. This happens if the
   155788       ** user has supplied a token such as "ORacle". Continue.
   155789       */
   155790     }
   155791   }
   155792 
   155793   /* See if we are dealing with a quoted phrase. If this is the case, then
   155794   ** search for the closing quote and pass the whole string to getNextString()
   155795   ** for processing. This is easy to do, as fts3 has no syntax for escaping
   155796   ** a quote character embedded in a string.
   155797   */
   155798   if( *zInput=='"' ){
   155799     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
   155800     *pnConsumed = (int)((zInput - z) + ii + 1);
   155801     if( ii==nInput ){
   155802       return SQLITE_ERROR;
   155803     }
   155804     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
   155805   }
   155806 
   155807   if( sqlite3_fts3_enable_parentheses ){
   155808     if( *zInput=='(' ){
   155809       int nConsumed = 0;
   155810       pParse->nNest++;
   155811       rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
   155812       if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
   155813       *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
   155814       return rc;
   155815     }else if( *zInput==')' ){
   155816       pParse->nNest--;
   155817       *pnConsumed = (int)((zInput - z) + 1);
   155818       *ppExpr = 0;
   155819       return SQLITE_DONE;
   155820     }
   155821   }
   155822 
   155823   /* If control flows to this point, this must be a regular token, or
   155824   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   155825   ** interface. Before doing so, figure out if there is an explicit
   155826   ** column specifier for the token.
   155827   **
   155828   ** TODO: Strangely, it is not possible to associate a column specifier
   155829   ** with a quoted phrase, only with a single token. Not sure if this was
   155830   ** an implementation artifact or an intentional decision when fts3 was
   155831   ** first implemented. Whichever it was, this module duplicates the
   155832   ** limitation.
   155833   */
   155834   iCol = pParse->iDefaultCol;
   155835   iColLen = 0;
   155836   for(ii=0; ii<pParse->nCol; ii++){
   155837     const char *zStr = pParse->azCol[ii];
   155838     int nStr = (int)strlen(zStr);
   155839     if( nInput>nStr && zInput[nStr]==':'
   155840      && sqlite3_strnicmp(zStr, zInput, nStr)==0
   155841     ){
   155842       iCol = ii;
   155843       iColLen = (int)((zInput - z) + nStr + 1);
   155844       break;
   155845     }
   155846   }
   155847   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
   155848   *pnConsumed += iColLen;
   155849   return rc;
   155850 }
   155851 
   155852 /*
   155853 ** The argument is an Fts3Expr structure for a binary operator (any type
   155854 ** except an FTSQUERY_PHRASE). Return an integer value representing the
   155855 ** precedence of the operator. Lower values have a higher precedence (i.e.
   155856 ** group more tightly). For example, in the C language, the == operator
   155857 ** groups more tightly than ||, and would therefore have a higher precedence.
   155858 **
   155859 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
   155860 ** is defined), the order of the operators in precedence from highest to
   155861 ** lowest is:
   155862 **
   155863 **   NEAR
   155864 **   NOT
   155865 **   AND (including implicit ANDs)
   155866 **   OR
   155867 **
   155868 ** Note that when using the old query syntax, the OR operator has a higher
   155869 ** precedence than the AND operator.
   155870 */
   155871 static int opPrecedence(Fts3Expr *p){
   155872   assert( p->eType!=FTSQUERY_PHRASE );
   155873   if( sqlite3_fts3_enable_parentheses ){
   155874     return p->eType;
   155875   }else if( p->eType==FTSQUERY_NEAR ){
   155876     return 1;
   155877   }else if( p->eType==FTSQUERY_OR ){
   155878     return 2;
   155879   }
   155880   assert( p->eType==FTSQUERY_AND );
   155881   return 3;
   155882 }
   155883 
   155884 /*
   155885 ** Argument ppHead contains a pointer to the current head of a query
   155886 ** expression tree being parsed. pPrev is the expression node most recently
   155887 ** inserted into the tree. This function adds pNew, which is always a binary
   155888 ** operator node, into the expression tree based on the relative precedence
   155889 ** of pNew and the existing nodes of the tree. This may result in the head
   155890 ** of the tree changing, in which case *ppHead is set to the new root node.
   155891 */
   155892 static void insertBinaryOperator(
   155893   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
   155894   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
   155895   Fts3Expr *pNew           /* New binary node to insert into expression tree */
   155896 ){
   155897   Fts3Expr *pSplit = pPrev;
   155898   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
   155899     pSplit = pSplit->pParent;
   155900   }
   155901 
   155902   if( pSplit->pParent ){
   155903     assert( pSplit->pParent->pRight==pSplit );
   155904     pSplit->pParent->pRight = pNew;
   155905     pNew->pParent = pSplit->pParent;
   155906   }else{
   155907     *ppHead = pNew;
   155908   }
   155909   pNew->pLeft = pSplit;
   155910   pSplit->pParent = pNew;
   155911 }
   155912 
   155913 /*
   155914 ** Parse the fts3 query expression found in buffer z, length n. This function
   155915 ** returns either when the end of the buffer is reached or an unmatched
   155916 ** closing bracket - ')' - is encountered.
   155917 **
   155918 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
   155919 ** parsed form of the expression and *pnConsumed is set to the number of
   155920 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
   155921 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
   155922 */
   155923 static int fts3ExprParse(
   155924   ParseContext *pParse,                   /* fts3 query parse context */
   155925   const char *z, int n,                   /* Text of MATCH query */
   155926   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
   155927   int *pnConsumed                         /* OUT: Number of bytes consumed */
   155928 ){
   155929   Fts3Expr *pRet = 0;
   155930   Fts3Expr *pPrev = 0;
   155931   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
   155932   int nIn = n;
   155933   const char *zIn = z;
   155934   int rc = SQLITE_OK;
   155935   int isRequirePhrase = 1;
   155936 
   155937   while( rc==SQLITE_OK ){
   155938     Fts3Expr *p = 0;
   155939     int nByte = 0;
   155940 
   155941     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
   155942     assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
   155943     if( rc==SQLITE_OK ){
   155944       if( p ){
   155945         int isPhrase;
   155946 
   155947         if( !sqlite3_fts3_enable_parentheses
   155948             && p->eType==FTSQUERY_PHRASE && pParse->isNot
   155949         ){
   155950           /* Create an implicit NOT operator. */
   155951           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
   155952           if( !pNot ){
   155953             sqlite3Fts3ExprFree(p);
   155954             rc = SQLITE_NOMEM;
   155955             goto exprparse_out;
   155956           }
   155957           pNot->eType = FTSQUERY_NOT;
   155958           pNot->pRight = p;
   155959           p->pParent = pNot;
   155960           if( pNotBranch ){
   155961             pNot->pLeft = pNotBranch;
   155962             pNotBranch->pParent = pNot;
   155963           }
   155964           pNotBranch = pNot;
   155965           p = pPrev;
   155966         }else{
   155967           int eType = p->eType;
   155968           isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
   155969 
   155970           /* The isRequirePhrase variable is set to true if a phrase or
   155971           ** an expression contained in parenthesis is required. If a
   155972           ** binary operator (AND, OR, NOT or NEAR) is encounted when
   155973           ** isRequirePhrase is set, this is a syntax error.
   155974           */
   155975           if( !isPhrase && isRequirePhrase ){
   155976             sqlite3Fts3ExprFree(p);
   155977             rc = SQLITE_ERROR;
   155978             goto exprparse_out;
   155979           }
   155980 
   155981           if( isPhrase && !isRequirePhrase ){
   155982             /* Insert an implicit AND operator. */
   155983             Fts3Expr *pAnd;
   155984             assert( pRet && pPrev );
   155985             pAnd = fts3MallocZero(sizeof(Fts3Expr));
   155986             if( !pAnd ){
   155987               sqlite3Fts3ExprFree(p);
   155988               rc = SQLITE_NOMEM;
   155989               goto exprparse_out;
   155990             }
   155991             pAnd->eType = FTSQUERY_AND;
   155992             insertBinaryOperator(&pRet, pPrev, pAnd);
   155993             pPrev = pAnd;
   155994           }
   155995 
   155996           /* This test catches attempts to make either operand of a NEAR
   155997            ** operator something other than a phrase. For example, either of
   155998            ** the following:
   155999            **
   156000            **    (bracketed expression) NEAR phrase
   156001            **    phrase NEAR (bracketed expression)
   156002            **
   156003            ** Return an error in either case.
   156004            */
   156005           if( pPrev && (
   156006             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
   156007          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
   156008           )){
   156009             sqlite3Fts3ExprFree(p);
   156010             rc = SQLITE_ERROR;
   156011             goto exprparse_out;
   156012           }
   156013 
   156014           if( isPhrase ){
   156015             if( pRet ){
   156016               assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
   156017               pPrev->pRight = p;
   156018               p->pParent = pPrev;
   156019             }else{
   156020               pRet = p;
   156021             }
   156022           }else{
   156023             insertBinaryOperator(&pRet, pPrev, p);
   156024           }
   156025           isRequirePhrase = !isPhrase;
   156026         }
   156027         pPrev = p;
   156028       }
   156029       assert( nByte>0 );
   156030     }
   156031     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
   156032     nIn -= nByte;
   156033     zIn += nByte;
   156034   }
   156035 
   156036   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
   156037     rc = SQLITE_ERROR;
   156038   }
   156039 
   156040   if( rc==SQLITE_DONE ){
   156041     rc = SQLITE_OK;
   156042     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
   156043       if( !pRet ){
   156044         rc = SQLITE_ERROR;
   156045       }else{
   156046         Fts3Expr *pIter = pNotBranch;
   156047         while( pIter->pLeft ){
   156048           pIter = pIter->pLeft;
   156049         }
   156050         pIter->pLeft = pRet;
   156051         pRet->pParent = pIter;
   156052         pRet = pNotBranch;
   156053       }
   156054     }
   156055   }
   156056   *pnConsumed = n - nIn;
   156057 
   156058 exprparse_out:
   156059   if( rc!=SQLITE_OK ){
   156060     sqlite3Fts3ExprFree(pRet);
   156061     sqlite3Fts3ExprFree(pNotBranch);
   156062     pRet = 0;
   156063   }
   156064   *ppExpr = pRet;
   156065   return rc;
   156066 }
   156067 
   156068 /*
   156069 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
   156070 ** as the only argument is more than nMaxDepth.
   156071 */
   156072 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
   156073   int rc = SQLITE_OK;
   156074   if( p ){
   156075     if( nMaxDepth<0 ){
   156076       rc = SQLITE_TOOBIG;
   156077     }else{
   156078       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
   156079       if( rc==SQLITE_OK ){
   156080         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
   156081       }
   156082     }
   156083   }
   156084   return rc;
   156085 }
   156086 
   156087 /*
   156088 ** This function attempts to transform the expression tree at (*pp) to
   156089 ** an equivalent but more balanced form. The tree is modified in place.
   156090 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
   156091 ** new root expression node.
   156092 **
   156093 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
   156094 **
   156095 ** Otherwise, if an error occurs, an SQLite error code is returned and
   156096 ** expression (*pp) freed.
   156097 */
   156098 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
   156099   int rc = SQLITE_OK;             /* Return code */
   156100   Fts3Expr *pRoot = *pp;          /* Initial root node */
   156101   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
   156102   int eType = pRoot->eType;       /* Type of node in this tree */
   156103 
   156104   if( nMaxDepth==0 ){
   156105     rc = SQLITE_ERROR;
   156106   }
   156107 
   156108   if( rc==SQLITE_OK ){
   156109     if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
   156110       Fts3Expr **apLeaf;
   156111       apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
   156112       if( 0==apLeaf ){
   156113         rc = SQLITE_NOMEM;
   156114       }else{
   156115         memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
   156116       }
   156117 
   156118       if( rc==SQLITE_OK ){
   156119         int i;
   156120         Fts3Expr *p;
   156121 
   156122         /* Set $p to point to the left-most leaf in the tree of eType nodes. */
   156123         for(p=pRoot; p->eType==eType; p=p->pLeft){
   156124           assert( p->pParent==0 || p->pParent->pLeft==p );
   156125           assert( p->pLeft && p->pRight );
   156126         }
   156127 
   156128         /* This loop runs once for each leaf in the tree of eType nodes. */
   156129         while( 1 ){
   156130           int iLvl;
   156131           Fts3Expr *pParent = p->pParent;     /* Current parent of p */
   156132 
   156133           assert( pParent==0 || pParent->pLeft==p );
   156134           p->pParent = 0;
   156135           if( pParent ){
   156136             pParent->pLeft = 0;
   156137           }else{
   156138             pRoot = 0;
   156139           }
   156140           rc = fts3ExprBalance(&p, nMaxDepth-1);
   156141           if( rc!=SQLITE_OK ) break;
   156142 
   156143           for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
   156144             if( apLeaf[iLvl]==0 ){
   156145               apLeaf[iLvl] = p;
   156146               p = 0;
   156147             }else{
   156148               assert( pFree );
   156149               pFree->pLeft = apLeaf[iLvl];
   156150               pFree->pRight = p;
   156151               pFree->pLeft->pParent = pFree;
   156152               pFree->pRight->pParent = pFree;
   156153 
   156154               p = pFree;
   156155               pFree = pFree->pParent;
   156156               p->pParent = 0;
   156157               apLeaf[iLvl] = 0;
   156158             }
   156159           }
   156160           if( p ){
   156161             sqlite3Fts3ExprFree(p);
   156162             rc = SQLITE_TOOBIG;
   156163             break;
   156164           }
   156165 
   156166           /* If that was the last leaf node, break out of the loop */
   156167           if( pParent==0 ) break;
   156168 
   156169           /* Set $p to point to the next leaf in the tree of eType nodes */
   156170           for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
   156171 
   156172           /* Remove pParent from the original tree. */
   156173           assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
   156174           pParent->pRight->pParent = pParent->pParent;
   156175           if( pParent->pParent ){
   156176             pParent->pParent->pLeft = pParent->pRight;
   156177           }else{
   156178             assert( pParent==pRoot );
   156179             pRoot = pParent->pRight;
   156180           }
   156181 
   156182           /* Link pParent into the free node list. It will be used as an
   156183           ** internal node of the new tree.  */
   156184           pParent->pParent = pFree;
   156185           pFree = pParent;
   156186         }
   156187 
   156188         if( rc==SQLITE_OK ){
   156189           p = 0;
   156190           for(i=0; i<nMaxDepth; i++){
   156191             if( apLeaf[i] ){
   156192               if( p==0 ){
   156193                 p = apLeaf[i];
   156194                 p->pParent = 0;
   156195               }else{
   156196                 assert( pFree!=0 );
   156197                 pFree->pRight = p;
   156198                 pFree->pLeft = apLeaf[i];
   156199                 pFree->pLeft->pParent = pFree;
   156200                 pFree->pRight->pParent = pFree;
   156201 
   156202                 p = pFree;
   156203                 pFree = pFree->pParent;
   156204                 p->pParent = 0;
   156205               }
   156206             }
   156207           }
   156208           pRoot = p;
   156209         }else{
   156210           /* An error occurred. Delete the contents of the apLeaf[] array
   156211           ** and pFree list. Everything else is cleaned up by the call to
   156212           ** sqlite3Fts3ExprFree(pRoot) below.  */
   156213           Fts3Expr *pDel;
   156214           for(i=0; i<nMaxDepth; i++){
   156215             sqlite3Fts3ExprFree(apLeaf[i]);
   156216           }
   156217           while( (pDel=pFree)!=0 ){
   156218             pFree = pDel->pParent;
   156219             sqlite3_free(pDel);
   156220           }
   156221         }
   156222 
   156223         assert( pFree==0 );
   156224         sqlite3_free( apLeaf );
   156225       }
   156226     }else if( eType==FTSQUERY_NOT ){
   156227       Fts3Expr *pLeft = pRoot->pLeft;
   156228       Fts3Expr *pRight = pRoot->pRight;
   156229 
   156230       pRoot->pLeft = 0;
   156231       pRoot->pRight = 0;
   156232       pLeft->pParent = 0;
   156233       pRight->pParent = 0;
   156234 
   156235       rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
   156236       if( rc==SQLITE_OK ){
   156237         rc = fts3ExprBalance(&pRight, nMaxDepth-1);
   156238       }
   156239 
   156240       if( rc!=SQLITE_OK ){
   156241         sqlite3Fts3ExprFree(pRight);
   156242         sqlite3Fts3ExprFree(pLeft);
   156243       }else{
   156244         assert( pLeft && pRight );
   156245         pRoot->pLeft = pLeft;
   156246         pLeft->pParent = pRoot;
   156247         pRoot->pRight = pRight;
   156248         pRight->pParent = pRoot;
   156249       }
   156250     }
   156251   }
   156252 
   156253   if( rc!=SQLITE_OK ){
   156254     sqlite3Fts3ExprFree(pRoot);
   156255     pRoot = 0;
   156256   }
   156257   *pp = pRoot;
   156258   return rc;
   156259 }
   156260 
   156261 /*
   156262 ** This function is similar to sqlite3Fts3ExprParse(), with the following
   156263 ** differences:
   156264 **
   156265 **   1. It does not do expression rebalancing.
   156266 **   2. It does not check that the expression does not exceed the
   156267 **      maximum allowable depth.
   156268 **   3. Even if it fails, *ppExpr may still be set to point to an
   156269 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
   156270 **      in this case.
   156271 */
   156272 static int fts3ExprParseUnbalanced(
   156273   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   156274   int iLangid,                        /* Language id for tokenizer */
   156275   char **azCol,                       /* Array of column names for fts3 table */
   156276   int bFts4,                          /* True to allow FTS4-only syntax */
   156277   int nCol,                           /* Number of entries in azCol[] */
   156278   int iDefaultCol,                    /* Default column to query */
   156279   const char *z, int n,               /* Text of MATCH query */
   156280   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
   156281 ){
   156282   int nParsed;
   156283   int rc;
   156284   ParseContext sParse;
   156285 
   156286   memset(&sParse, 0, sizeof(ParseContext));
   156287   sParse.pTokenizer = pTokenizer;
   156288   sParse.iLangid = iLangid;
   156289   sParse.azCol = (const char **)azCol;
   156290   sParse.nCol = nCol;
   156291   sParse.iDefaultCol = iDefaultCol;
   156292   sParse.bFts4 = bFts4;
   156293   if( z==0 ){
   156294     *ppExpr = 0;
   156295     return SQLITE_OK;
   156296   }
   156297   if( n<0 ){
   156298     n = (int)strlen(z);
   156299   }
   156300   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
   156301   assert( rc==SQLITE_OK || *ppExpr==0 );
   156302 
   156303   /* Check for mismatched parenthesis */
   156304   if( rc==SQLITE_OK && sParse.nNest ){
   156305     rc = SQLITE_ERROR;
   156306   }
   156307 
   156308   return rc;
   156309 }
   156310 
   156311 /*
   156312 ** Parameters z and n contain a pointer to and length of a buffer containing
   156313 ** an fts3 query expression, respectively. This function attempts to parse the
   156314 ** query expression and create a tree of Fts3Expr structures representing the
   156315 ** parsed expression. If successful, *ppExpr is set to point to the head
   156316 ** of the parsed expression tree and SQLITE_OK is returned. If an error
   156317 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
   156318 ** error) is returned and *ppExpr is set to 0.
   156319 **
   156320 ** If parameter n is a negative number, then z is assumed to point to a
   156321 ** nul-terminated string and the length is determined using strlen().
   156322 **
   156323 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
   156324 ** use to normalize query tokens while parsing the expression. The azCol[]
   156325 ** array, which is assumed to contain nCol entries, should contain the names
   156326 ** of each column in the target fts3 table, in order from left to right.
   156327 ** Column names must be nul-terminated strings.
   156328 **
   156329 ** The iDefaultCol parameter should be passed the index of the table column
   156330 ** that appears on the left-hand-side of the MATCH operator (the default
   156331 ** column to match against for tokens for which a column name is not explicitly
   156332 ** specified as part of the query string), or -1 if tokens may by default
   156333 ** match any table column.
   156334 */
   156335 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   156336   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   156337   int iLangid,                        /* Language id for tokenizer */
   156338   char **azCol,                       /* Array of column names for fts3 table */
   156339   int bFts4,                          /* True to allow FTS4-only syntax */
   156340   int nCol,                           /* Number of entries in azCol[] */
   156341   int iDefaultCol,                    /* Default column to query */
   156342   const char *z, int n,               /* Text of MATCH query */
   156343   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
   156344   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
   156345 ){
   156346   int rc = fts3ExprParseUnbalanced(
   156347       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
   156348   );
   156349 
   156350   /* Rebalance the expression. And check that its depth does not exceed
   156351   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
   156352   if( rc==SQLITE_OK && *ppExpr ){
   156353     rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
   156354     if( rc==SQLITE_OK ){
   156355       rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
   156356     }
   156357   }
   156358 
   156359   if( rc!=SQLITE_OK ){
   156360     sqlite3Fts3ExprFree(*ppExpr);
   156361     *ppExpr = 0;
   156362     if( rc==SQLITE_TOOBIG ){
   156363       sqlite3Fts3ErrMsg(pzErr,
   156364           "FTS expression tree is too large (maximum depth %d)",
   156365           SQLITE_FTS3_MAX_EXPR_DEPTH
   156366       );
   156367       rc = SQLITE_ERROR;
   156368     }else if( rc==SQLITE_ERROR ){
   156369       sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
   156370     }
   156371   }
   156372 
   156373   return rc;
   156374 }
   156375 
   156376 /*
   156377 ** Free a single node of an expression tree.
   156378 */
   156379 static void fts3FreeExprNode(Fts3Expr *p){
   156380   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
   156381   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
   156382   sqlite3_free(p->aMI);
   156383   sqlite3_free(p);
   156384 }
   156385 
   156386 /*
   156387 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
   156388 **
   156389 ** This function would be simpler if it recursively called itself. But
   156390 ** that would mean passing a sufficiently large expression to ExprParse()
   156391 ** could cause a stack overflow.
   156392 */
   156393 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
   156394   Fts3Expr *p;
   156395   assert( pDel==0 || pDel->pParent==0 );
   156396   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
   156397     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
   156398   }
   156399   while( p ){
   156400     Fts3Expr *pParent = p->pParent;
   156401     fts3FreeExprNode(p);
   156402     if( pParent && p==pParent->pLeft && pParent->pRight ){
   156403       p = pParent->pRight;
   156404       while( p && (p->pLeft || p->pRight) ){
   156405         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
   156406         p = (p->pLeft ? p->pLeft : p->pRight);
   156407       }
   156408     }else{
   156409       p = pParent;
   156410     }
   156411   }
   156412 }
   156413 
   156414 /****************************************************************************
   156415 *****************************************************************************
   156416 ** Everything after this point is just test code.
   156417 */
   156418 
   156419 #ifdef SQLITE_TEST
   156420 
   156421 /* #include <stdio.h> */
   156422 
   156423 /*
   156424 ** Function to query the hash-table of tokenizers (see README.tokenizers).
   156425 */
   156426 static int queryTestTokenizer(
   156427   sqlite3 *db,
   156428   const char *zName,
   156429   const sqlite3_tokenizer_module **pp
   156430 ){
   156431   int rc;
   156432   sqlite3_stmt *pStmt;
   156433   const char zSql[] = "SELECT fts3_tokenizer(?)";
   156434 
   156435   *pp = 0;
   156436   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   156437   if( rc!=SQLITE_OK ){
   156438     return rc;
   156439   }
   156440 
   156441   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   156442   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   156443     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   156444       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   156445     }
   156446   }
   156447 
   156448   return sqlite3_finalize(pStmt);
   156449 }
   156450 
   156451 /*
   156452 ** Return a pointer to a buffer containing a text representation of the
   156453 ** expression passed as the first argument. The buffer is obtained from
   156454 ** sqlite3_malloc(). It is the responsibility of the caller to use
   156455 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
   156456 ** NULL is returned.
   156457 **
   156458 ** If the second argument is not NULL, then its contents are prepended to
   156459 ** the returned expression text and then freed using sqlite3_free().
   156460 */
   156461 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
   156462   if( pExpr==0 ){
   156463     return sqlite3_mprintf("");
   156464   }
   156465   switch( pExpr->eType ){
   156466     case FTSQUERY_PHRASE: {
   156467       Fts3Phrase *pPhrase = pExpr->pPhrase;
   156468       int i;
   156469       zBuf = sqlite3_mprintf(
   156470           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
   156471       for(i=0; zBuf && i<pPhrase->nToken; i++){
   156472         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
   156473             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
   156474             (pPhrase->aToken[i].isPrefix?"+":"")
   156475         );
   156476       }
   156477       return zBuf;
   156478     }
   156479 
   156480     case FTSQUERY_NEAR:
   156481       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
   156482       break;
   156483     case FTSQUERY_NOT:
   156484       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
   156485       break;
   156486     case FTSQUERY_AND:
   156487       zBuf = sqlite3_mprintf("%zAND ", zBuf);
   156488       break;
   156489     case FTSQUERY_OR:
   156490       zBuf = sqlite3_mprintf("%zOR ", zBuf);
   156491       break;
   156492   }
   156493 
   156494   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
   156495   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
   156496   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
   156497 
   156498   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
   156499   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
   156500 
   156501   return zBuf;
   156502 }
   156503 
   156504 /*
   156505 ** This is the implementation of a scalar SQL function used to test the
   156506 ** expression parser. It should be called as follows:
   156507 **
   156508 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
   156509 **
   156510 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
   156511 ** to parse the query expression (see README.tokenizers). The second argument
   156512 ** is the query expression to parse. Each subsequent argument is the name
   156513 ** of a column of the fts3 table that the query expression may refer to.
   156514 ** For example:
   156515 **
   156516 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
   156517 */
   156518 static void fts3ExprTest(
   156519   sqlite3_context *context,
   156520   int argc,
   156521   sqlite3_value **argv
   156522 ){
   156523   sqlite3_tokenizer_module const *pModule = 0;
   156524   sqlite3_tokenizer *pTokenizer = 0;
   156525   int rc;
   156526   char **azCol = 0;
   156527   const char *zExpr;
   156528   int nExpr;
   156529   int nCol;
   156530   int ii;
   156531   Fts3Expr *pExpr;
   156532   char *zBuf = 0;
   156533   sqlite3 *db = sqlite3_context_db_handle(context);
   156534 
   156535   if( argc<3 ){
   156536     sqlite3_result_error(context,
   156537         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
   156538     );
   156539     return;
   156540   }
   156541 
   156542   rc = queryTestTokenizer(db,
   156543                           (const char *)sqlite3_value_text(argv[0]), &pModule);
   156544   if( rc==SQLITE_NOMEM ){
   156545     sqlite3_result_error_nomem(context);
   156546     goto exprtest_out;
   156547   }else if( !pModule ){
   156548     sqlite3_result_error(context, "No such tokenizer module", -1);
   156549     goto exprtest_out;
   156550   }
   156551 
   156552   rc = pModule->xCreate(0, 0, &pTokenizer);
   156553   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   156554   if( rc==SQLITE_NOMEM ){
   156555     sqlite3_result_error_nomem(context);
   156556     goto exprtest_out;
   156557   }
   156558   pTokenizer->pModule = pModule;
   156559 
   156560   zExpr = (const char *)sqlite3_value_text(argv[1]);
   156561   nExpr = sqlite3_value_bytes(argv[1]);
   156562   nCol = argc-2;
   156563   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
   156564   if( !azCol ){
   156565     sqlite3_result_error_nomem(context);
   156566     goto exprtest_out;
   156567   }
   156568   for(ii=0; ii<nCol; ii++){
   156569     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
   156570   }
   156571 
   156572   if( sqlite3_user_data(context) ){
   156573     char *zDummy = 0;
   156574     rc = sqlite3Fts3ExprParse(
   156575         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
   156576     );
   156577     assert( rc==SQLITE_OK || pExpr==0 );
   156578     sqlite3_free(zDummy);
   156579   }else{
   156580     rc = fts3ExprParseUnbalanced(
   156581         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
   156582     );
   156583   }
   156584 
   156585   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
   156586     sqlite3Fts3ExprFree(pExpr);
   156587     sqlite3_result_error(context, "Error parsing expression", -1);
   156588   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
   156589     sqlite3_result_error_nomem(context);
   156590   }else{
   156591     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   156592     sqlite3_free(zBuf);
   156593   }
   156594 
   156595   sqlite3Fts3ExprFree(pExpr);
   156596 
   156597 exprtest_out:
   156598   if( pModule && pTokenizer ){
   156599     rc = pModule->xDestroy(pTokenizer);
   156600   }
   156601   sqlite3_free(azCol);
   156602 }
   156603 
   156604 /*
   156605 ** Register the query expression parser test function fts3_exprtest()
   156606 ** with database connection db.
   156607 */
   156608 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
   156609   int rc = sqlite3_create_function(
   156610       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
   156611   );
   156612   if( rc==SQLITE_OK ){
   156613     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
   156614         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
   156615     );
   156616   }
   156617   return rc;
   156618 }
   156619 
   156620 #endif
   156621 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   156622 
   156623 /************** End of fts3_expr.c *******************************************/
   156624 /************** Begin file fts3_hash.c ***************************************/
   156625 /*
   156626 ** 2001 September 22
   156627 **
   156628 ** The author disclaims copyright to this source code.  In place of
   156629 ** a legal notice, here is a blessing:
   156630 **
   156631 **    May you do good and not evil.
   156632 **    May you find forgiveness for yourself and forgive others.
   156633 **    May you share freely, never taking more than you give.
   156634 **
   156635 *************************************************************************
   156636 ** This is the implementation of generic hash-tables used in SQLite.
   156637 ** We've modified it slightly to serve as a standalone hash table
   156638 ** implementation for the full-text indexing module.
   156639 */
   156640 
   156641 /*
   156642 ** The code in this file is only compiled if:
   156643 **
   156644 **     * The FTS3 module is being built as an extension
   156645 **       (in which case SQLITE_CORE is not defined), or
   156646 **
   156647 **     * The FTS3 module is being built into the core of
   156648 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   156649 */
   156650 /* #include "fts3Int.h" */
   156651 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   156652 
   156653 /* #include <assert.h> */
   156654 /* #include <stdlib.h> */
   156655 /* #include <string.h> */
   156656 
   156657 /* #include "fts3_hash.h" */
   156658 
   156659 /*
   156660 ** Malloc and Free functions
   156661 */
   156662 static void *fts3HashMalloc(int n){
   156663   void *p = sqlite3_malloc(n);
   156664   if( p ){
   156665     memset(p, 0, n);
   156666   }
   156667   return p;
   156668 }
   156669 static void fts3HashFree(void *p){
   156670   sqlite3_free(p);
   156671 }
   156672 
   156673 /* Turn bulk memory into a hash table object by initializing the
   156674 ** fields of the Hash structure.
   156675 **
   156676 ** "pNew" is a pointer to the hash table that is to be initialized.
   156677 ** keyClass is one of the constants
   156678 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
   156679 ** determines what kind of key the hash table will use.  "copyKey" is
   156680 ** true if the hash table should make its own private copy of keys and
   156681 ** false if it should just use the supplied pointer.
   156682 */
   156683 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
   156684   assert( pNew!=0 );
   156685   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
   156686   pNew->keyClass = keyClass;
   156687   pNew->copyKey = copyKey;
   156688   pNew->first = 0;
   156689   pNew->count = 0;
   156690   pNew->htsize = 0;
   156691   pNew->ht = 0;
   156692 }
   156693 
   156694 /* Remove all entries from a hash table.  Reclaim all memory.
   156695 ** Call this routine to delete a hash table or to reset a hash table
   156696 ** to the empty state.
   156697 */
   156698 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
   156699   Fts3HashElem *elem;         /* For looping over all elements of the table */
   156700 
   156701   assert( pH!=0 );
   156702   elem = pH->first;
   156703   pH->first = 0;
   156704   fts3HashFree(pH->ht);
   156705   pH->ht = 0;
   156706   pH->htsize = 0;
   156707   while( elem ){
   156708     Fts3HashElem *next_elem = elem->next;
   156709     if( pH->copyKey && elem->pKey ){
   156710       fts3HashFree(elem->pKey);
   156711     }
   156712     fts3HashFree(elem);
   156713     elem = next_elem;
   156714   }
   156715   pH->count = 0;
   156716 }
   156717 
   156718 /*
   156719 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
   156720 */
   156721 static int fts3StrHash(const void *pKey, int nKey){
   156722   const char *z = (const char *)pKey;
   156723   unsigned h = 0;
   156724   if( nKey<=0 ) nKey = (int) strlen(z);
   156725   while( nKey > 0  ){
   156726     h = (h<<3) ^ h ^ *z++;
   156727     nKey--;
   156728   }
   156729   return (int)(h & 0x7fffffff);
   156730 }
   156731 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   156732   if( n1!=n2 ) return 1;
   156733   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
   156734 }
   156735 
   156736 /*
   156737 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
   156738 */
   156739 static int fts3BinHash(const void *pKey, int nKey){
   156740   int h = 0;
   156741   const char *z = (const char *)pKey;
   156742   while( nKey-- > 0 ){
   156743     h = (h<<3) ^ h ^ *(z++);
   156744   }
   156745   return h & 0x7fffffff;
   156746 }
   156747 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   156748   if( n1!=n2 ) return 1;
   156749   return memcmp(pKey1,pKey2,n1);
   156750 }
   156751 
   156752 /*
   156753 ** Return a pointer to the appropriate hash function given the key class.
   156754 **
   156755 ** The C syntax in this function definition may be unfamilar to some
   156756 ** programmers, so we provide the following additional explanation:
   156757 **
   156758 ** The name of the function is "ftsHashFunction".  The function takes a
   156759 ** single parameter "keyClass".  The return value of ftsHashFunction()
   156760 ** is a pointer to another function.  Specifically, the return value
   156761 ** of ftsHashFunction() is a pointer to a function that takes two parameters
   156762 ** with types "const void*" and "int" and returns an "int".
   156763 */
   156764 static int (*ftsHashFunction(int keyClass))(const void*,int){
   156765   if( keyClass==FTS3_HASH_STRING ){
   156766     return &fts3StrHash;
   156767   }else{
   156768     assert( keyClass==FTS3_HASH_BINARY );
   156769     return &fts3BinHash;
   156770   }
   156771 }
   156772 
   156773 /*
   156774 ** Return a pointer to the appropriate hash function given the key class.
   156775 **
   156776 ** For help in interpreted the obscure C code in the function definition,
   156777 ** see the header comment on the previous function.
   156778 */
   156779 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
   156780   if( keyClass==FTS3_HASH_STRING ){
   156781     return &fts3StrCompare;
   156782   }else{
   156783     assert( keyClass==FTS3_HASH_BINARY );
   156784     return &fts3BinCompare;
   156785   }
   156786 }
   156787 
   156788 /* Link an element into the hash table
   156789 */
   156790 static void fts3HashInsertElement(
   156791   Fts3Hash *pH,            /* The complete hash table */
   156792   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
   156793   Fts3HashElem *pNew       /* The element to be inserted */
   156794 ){
   156795   Fts3HashElem *pHead;     /* First element already in pEntry */
   156796   pHead = pEntry->chain;
   156797   if( pHead ){
   156798     pNew->next = pHead;
   156799     pNew->prev = pHead->prev;
   156800     if( pHead->prev ){ pHead->prev->next = pNew; }
   156801     else             { pH->first = pNew; }
   156802     pHead->prev = pNew;
   156803   }else{
   156804     pNew->next = pH->first;
   156805     if( pH->first ){ pH->first->prev = pNew; }
   156806     pNew->prev = 0;
   156807     pH->first = pNew;
   156808   }
   156809   pEntry->count++;
   156810   pEntry->chain = pNew;
   156811 }
   156812 
   156813 
   156814 /* Resize the hash table so that it cantains "new_size" buckets.
   156815 ** "new_size" must be a power of 2.  The hash table might fail
   156816 ** to resize if sqliteMalloc() fails.
   156817 **
   156818 ** Return non-zero if a memory allocation error occurs.
   156819 */
   156820 static int fts3Rehash(Fts3Hash *pH, int new_size){
   156821   struct _fts3ht *new_ht;          /* The new hash table */
   156822   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
   156823   int (*xHash)(const void*,int);   /* The hash function */
   156824 
   156825   assert( (new_size & (new_size-1))==0 );
   156826   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
   156827   if( new_ht==0 ) return 1;
   156828   fts3HashFree(pH->ht);
   156829   pH->ht = new_ht;
   156830   pH->htsize = new_size;
   156831   xHash = ftsHashFunction(pH->keyClass);
   156832   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   156833     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
   156834     next_elem = elem->next;
   156835     fts3HashInsertElement(pH, &new_ht[h], elem);
   156836   }
   156837   return 0;
   156838 }
   156839 
   156840 /* This function (for internal use only) locates an element in an
   156841 ** hash table that matches the given key.  The hash for this key has
   156842 ** already been computed and is passed as the 4th parameter.
   156843 */
   156844 static Fts3HashElem *fts3FindElementByHash(
   156845   const Fts3Hash *pH, /* The pH to be searched */
   156846   const void *pKey,   /* The key we are searching for */
   156847   int nKey,
   156848   int h               /* The hash for this key. */
   156849 ){
   156850   Fts3HashElem *elem;            /* Used to loop thru the element list */
   156851   int count;                     /* Number of elements left to test */
   156852   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
   156853 
   156854   if( pH->ht ){
   156855     struct _fts3ht *pEntry = &pH->ht[h];
   156856     elem = pEntry->chain;
   156857     count = pEntry->count;
   156858     xCompare = ftsCompareFunction(pH->keyClass);
   156859     while( count-- && elem ){
   156860       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
   156861         return elem;
   156862       }
   156863       elem = elem->next;
   156864     }
   156865   }
   156866   return 0;
   156867 }
   156868 
   156869 /* Remove a single entry from the hash table given a pointer to that
   156870 ** element and a hash on the element's key.
   156871 */
   156872 static void fts3RemoveElementByHash(
   156873   Fts3Hash *pH,         /* The pH containing "elem" */
   156874   Fts3HashElem* elem,   /* The element to be removed from the pH */
   156875   int h                 /* Hash value for the element */
   156876 ){
   156877   struct _fts3ht *pEntry;
   156878   if( elem->prev ){
   156879     elem->prev->next = elem->next;
   156880   }else{
   156881     pH->first = elem->next;
   156882   }
   156883   if( elem->next ){
   156884     elem->next->prev = elem->prev;
   156885   }
   156886   pEntry = &pH->ht[h];
   156887   if( pEntry->chain==elem ){
   156888     pEntry->chain = elem->next;
   156889   }
   156890   pEntry->count--;
   156891   if( pEntry->count<=0 ){
   156892     pEntry->chain = 0;
   156893   }
   156894   if( pH->copyKey && elem->pKey ){
   156895     fts3HashFree(elem->pKey);
   156896   }
   156897   fts3HashFree( elem );
   156898   pH->count--;
   156899   if( pH->count<=0 ){
   156900     assert( pH->first==0 );
   156901     assert( pH->count==0 );
   156902     fts3HashClear(pH);
   156903   }
   156904 }
   156905 
   156906 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   156907   const Fts3Hash *pH,
   156908   const void *pKey,
   156909   int nKey
   156910 ){
   156911   int h;                          /* A hash on key */
   156912   int (*xHash)(const void*,int);  /* The hash function */
   156913 
   156914   if( pH==0 || pH->ht==0 ) return 0;
   156915   xHash = ftsHashFunction(pH->keyClass);
   156916   assert( xHash!=0 );
   156917   h = (*xHash)(pKey,nKey);
   156918   assert( (pH->htsize & (pH->htsize-1))==0 );
   156919   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
   156920 }
   156921 
   156922 /*
   156923 ** Attempt to locate an element of the hash table pH with a key
   156924 ** that matches pKey,nKey.  Return the data for this element if it is
   156925 ** found, or NULL if there is no match.
   156926 */
   156927 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
   156928   Fts3HashElem *pElem;            /* The element that matches key (if any) */
   156929 
   156930   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
   156931   return pElem ? pElem->data : 0;
   156932 }
   156933 
   156934 /* Insert an element into the hash table pH.  The key is pKey,nKey
   156935 ** and the data is "data".
   156936 **
   156937 ** If no element exists with a matching key, then a new
   156938 ** element is created.  A copy of the key is made if the copyKey
   156939 ** flag is set.  NULL is returned.
   156940 **
   156941 ** If another element already exists with the same key, then the
   156942 ** new data replaces the old data and the old data is returned.
   156943 ** The key is not copied in this instance.  If a malloc fails, then
   156944 ** the new data is returned and the hash table is unchanged.
   156945 **
   156946 ** If the "data" parameter to this function is NULL, then the
   156947 ** element corresponding to "key" is removed from the hash table.
   156948 */
   156949 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
   156950   Fts3Hash *pH,        /* The hash table to insert into */
   156951   const void *pKey,    /* The key */
   156952   int nKey,            /* Number of bytes in the key */
   156953   void *data           /* The data */
   156954 ){
   156955   int hraw;                 /* Raw hash value of the key */
   156956   int h;                    /* the hash of the key modulo hash table size */
   156957   Fts3HashElem *elem;       /* Used to loop thru the element list */
   156958   Fts3HashElem *new_elem;   /* New element added to the pH */
   156959   int (*xHash)(const void*,int);  /* The hash function */
   156960 
   156961   assert( pH!=0 );
   156962   xHash = ftsHashFunction(pH->keyClass);
   156963   assert( xHash!=0 );
   156964   hraw = (*xHash)(pKey, nKey);
   156965   assert( (pH->htsize & (pH->htsize-1))==0 );
   156966   h = hraw & (pH->htsize-1);
   156967   elem = fts3FindElementByHash(pH,pKey,nKey,h);
   156968   if( elem ){
   156969     void *old_data = elem->data;
   156970     if( data==0 ){
   156971       fts3RemoveElementByHash(pH,elem,h);
   156972     }else{
   156973       elem->data = data;
   156974     }
   156975     return old_data;
   156976   }
   156977   if( data==0 ) return 0;
   156978   if( (pH->htsize==0 && fts3Rehash(pH,8))
   156979    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
   156980   ){
   156981     pH->count = 0;
   156982     return data;
   156983   }
   156984   assert( pH->htsize>0 );
   156985   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
   156986   if( new_elem==0 ) return data;
   156987   if( pH->copyKey && pKey!=0 ){
   156988     new_elem->pKey = fts3HashMalloc( nKey );
   156989     if( new_elem->pKey==0 ){
   156990       fts3HashFree(new_elem);
   156991       return data;
   156992     }
   156993     memcpy((void*)new_elem->pKey, pKey, nKey);
   156994   }else{
   156995     new_elem->pKey = (void*)pKey;
   156996   }
   156997   new_elem->nKey = nKey;
   156998   pH->count++;
   156999   assert( pH->htsize>0 );
   157000   assert( (pH->htsize & (pH->htsize-1))==0 );
   157001   h = hraw & (pH->htsize-1);
   157002   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
   157003   new_elem->data = data;
   157004   return 0;
   157005 }
   157006 
   157007 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   157008 
   157009 /************** End of fts3_hash.c *******************************************/
   157010 /************** Begin file fts3_porter.c *************************************/
   157011 /*
   157012 ** 2006 September 30
   157013 **
   157014 ** The author disclaims copyright to this source code.  In place of
   157015 ** a legal notice, here is a blessing:
   157016 **
   157017 **    May you do good and not evil.
   157018 **    May you find forgiveness for yourself and forgive others.
   157019 **    May you share freely, never taking more than you give.
   157020 **
   157021 *************************************************************************
   157022 ** Implementation of the full-text-search tokenizer that implements
   157023 ** a Porter stemmer.
   157024 */
   157025 
   157026 /*
   157027 ** The code in this file is only compiled if:
   157028 **
   157029 **     * The FTS3 module is being built as an extension
   157030 **       (in which case SQLITE_CORE is not defined), or
   157031 **
   157032 **     * The FTS3 module is being built into the core of
   157033 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   157034 */
   157035 /* #include "fts3Int.h" */
   157036 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   157037 
   157038 /* #include <assert.h> */
   157039 /* #include <stdlib.h> */
   157040 /* #include <stdio.h> */
   157041 /* #include <string.h> */
   157042 
   157043 /* #include "fts3_tokenizer.h" */
   157044 
   157045 /*
   157046 ** Class derived from sqlite3_tokenizer
   157047 */
   157048 typedef struct porter_tokenizer {
   157049   sqlite3_tokenizer base;      /* Base class */
   157050 } porter_tokenizer;
   157051 
   157052 /*
   157053 ** Class derived from sqlite3_tokenizer_cursor
   157054 */
   157055 typedef struct porter_tokenizer_cursor {
   157056   sqlite3_tokenizer_cursor base;
   157057   const char *zInput;          /* input we are tokenizing */
   157058   int nInput;                  /* size of the input */
   157059   int iOffset;                 /* current position in zInput */
   157060   int iToken;                  /* index of next token to be returned */
   157061   char *zToken;                /* storage for current token */
   157062   int nAllocated;              /* space allocated to zToken buffer */
   157063 } porter_tokenizer_cursor;
   157064 
   157065 
   157066 /*
   157067 ** Create a new tokenizer instance.
   157068 */
   157069 static int porterCreate(
   157070   int argc, const char * const *argv,
   157071   sqlite3_tokenizer **ppTokenizer
   157072 ){
   157073   porter_tokenizer *t;
   157074 
   157075   UNUSED_PARAMETER(argc);
   157076   UNUSED_PARAMETER(argv);
   157077 
   157078   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
   157079   if( t==NULL ) return SQLITE_NOMEM;
   157080   memset(t, 0, sizeof(*t));
   157081   *ppTokenizer = &t->base;
   157082   return SQLITE_OK;
   157083 }
   157084 
   157085 /*
   157086 ** Destroy a tokenizer
   157087 */
   157088 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
   157089   sqlite3_free(pTokenizer);
   157090   return SQLITE_OK;
   157091 }
   157092 
   157093 /*
   157094 ** Prepare to begin tokenizing a particular string.  The input
   157095 ** string to be tokenized is zInput[0..nInput-1].  A cursor
   157096 ** used to incrementally tokenize this string is returned in
   157097 ** *ppCursor.
   157098 */
   157099 static int porterOpen(
   157100   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   157101   const char *zInput, int nInput,        /* String to be tokenized */
   157102   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   157103 ){
   157104   porter_tokenizer_cursor *c;
   157105 
   157106   UNUSED_PARAMETER(pTokenizer);
   157107 
   157108   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   157109   if( c==NULL ) return SQLITE_NOMEM;
   157110 
   157111   c->zInput = zInput;
   157112   if( zInput==0 ){
   157113     c->nInput = 0;
   157114   }else if( nInput<0 ){
   157115     c->nInput = (int)strlen(zInput);
   157116   }else{
   157117     c->nInput = nInput;
   157118   }
   157119   c->iOffset = 0;                 /* start tokenizing at the beginning */
   157120   c->iToken = 0;
   157121   c->zToken = NULL;               /* no space allocated, yet. */
   157122   c->nAllocated = 0;
   157123 
   157124   *ppCursor = &c->base;
   157125   return SQLITE_OK;
   157126 }
   157127 
   157128 /*
   157129 ** Close a tokenization cursor previously opened by a call to
   157130 ** porterOpen() above.
   157131 */
   157132 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
   157133   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   157134   sqlite3_free(c->zToken);
   157135   sqlite3_free(c);
   157136   return SQLITE_OK;
   157137 }
   157138 /*
   157139 ** Vowel or consonant
   157140 */
   157141 static const char cType[] = {
   157142    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   157143    1, 1, 1, 2, 1
   157144 };
   157145 
   157146 /*
   157147 ** isConsonant() and isVowel() determine if their first character in
   157148 ** the string they point to is a consonant or a vowel, according
   157149 ** to Porter ruls.
   157150 **
   157151 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
   157152 ** 'Y' is a consonant unless it follows another consonant,
   157153 ** in which case it is a vowel.
   157154 **
   157155 ** In these routine, the letters are in reverse order.  So the 'y' rule
   157156 ** is that 'y' is a consonant unless it is followed by another
   157157 ** consonent.
   157158 */
   157159 static int isVowel(const char*);
   157160 static int isConsonant(const char *z){
   157161   int j;
   157162   char x = *z;
   157163   if( x==0 ) return 0;
   157164   assert( x>='a' && x<='z' );
   157165   j = cType[x-'a'];
   157166   if( j<2 ) return j;
   157167   return z[1]==0 || isVowel(z + 1);
   157168 }
   157169 static int isVowel(const char *z){
   157170   int j;
   157171   char x = *z;
   157172   if( x==0 ) return 0;
   157173   assert( x>='a' && x<='z' );
   157174   j = cType[x-'a'];
   157175   if( j<2 ) return 1-j;
   157176   return isConsonant(z + 1);
   157177 }
   157178 
   157179 /*
   157180 ** Let any sequence of one or more vowels be represented by V and let
   157181 ** C be sequence of one or more consonants.  Then every word can be
   157182 ** represented as:
   157183 **
   157184 **           [C] (VC){m} [V]
   157185 **
   157186 ** In prose:  A word is an optional consonant followed by zero or
   157187 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
   157188 ** number of vowel consonant pairs.  This routine computes the value
   157189 ** of m for the first i bytes of a word.
   157190 **
   157191 ** Return true if the m-value for z is 1 or more.  In other words,
   157192 ** return true if z contains at least one vowel that is followed
   157193 ** by a consonant.
   157194 **
   157195 ** In this routine z[] is in reverse order.  So we are really looking
   157196 ** for an instance of a consonant followed by a vowel.
   157197 */
   157198 static int m_gt_0(const char *z){
   157199   while( isVowel(z) ){ z++; }
   157200   if( *z==0 ) return 0;
   157201   while( isConsonant(z) ){ z++; }
   157202   return *z!=0;
   157203 }
   157204 
   157205 /* Like mgt0 above except we are looking for a value of m which is
   157206 ** exactly 1
   157207 */
   157208 static int m_eq_1(const char *z){
   157209   while( isVowel(z) ){ z++; }
   157210   if( *z==0 ) return 0;
   157211   while( isConsonant(z) ){ z++; }
   157212   if( *z==0 ) return 0;
   157213   while( isVowel(z) ){ z++; }
   157214   if( *z==0 ) return 1;
   157215   while( isConsonant(z) ){ z++; }
   157216   return *z==0;
   157217 }
   157218 
   157219 /* Like mgt0 above except we are looking for a value of m>1 instead
   157220 ** or m>0
   157221 */
   157222 static int m_gt_1(const char *z){
   157223   while( isVowel(z) ){ z++; }
   157224   if( *z==0 ) return 0;
   157225   while( isConsonant(z) ){ z++; }
   157226   if( *z==0 ) return 0;
   157227   while( isVowel(z) ){ z++; }
   157228   if( *z==0 ) return 0;
   157229   while( isConsonant(z) ){ z++; }
   157230   return *z!=0;
   157231 }
   157232 
   157233 /*
   157234 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
   157235 */
   157236 static int hasVowel(const char *z){
   157237   while( isConsonant(z) ){ z++; }
   157238   return *z!=0;
   157239 }
   157240 
   157241 /*
   157242 ** Return TRUE if the word ends in a double consonant.
   157243 **
   157244 ** The text is reversed here. So we are really looking at
   157245 ** the first two characters of z[].
   157246 */
   157247 static int doubleConsonant(const char *z){
   157248   return isConsonant(z) && z[0]==z[1];
   157249 }
   157250 
   157251 /*
   157252 ** Return TRUE if the word ends with three letters which
   157253 ** are consonant-vowel-consonent and where the final consonant
   157254 ** is not 'w', 'x', or 'y'.
   157255 **
   157256 ** The word is reversed here.  So we are really checking the
   157257 ** first three letters and the first one cannot be in [wxy].
   157258 */
   157259 static int star_oh(const char *z){
   157260   return
   157261     isConsonant(z) &&
   157262     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
   157263     isVowel(z+1) &&
   157264     isConsonant(z+2);
   157265 }
   157266 
   157267 /*
   157268 ** If the word ends with zFrom and xCond() is true for the stem
   157269 ** of the word that preceeds the zFrom ending, then change the
   157270 ** ending to zTo.
   157271 **
   157272 ** The input word *pz and zFrom are both in reverse order.  zTo
   157273 ** is in normal order.
   157274 **
   157275 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
   157276 ** match.  Not that TRUE is returned even if xCond() fails and
   157277 ** no substitution occurs.
   157278 */
   157279 static int stem(
   157280   char **pz,             /* The word being stemmed (Reversed) */
   157281   const char *zFrom,     /* If the ending matches this... (Reversed) */
   157282   const char *zTo,       /* ... change the ending to this (not reversed) */
   157283   int (*xCond)(const char*)   /* Condition that must be true */
   157284 ){
   157285   char *z = *pz;
   157286   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
   157287   if( *zFrom!=0 ) return 0;
   157288   if( xCond && !xCond(z) ) return 1;
   157289   while( *zTo ){
   157290     *(--z) = *(zTo++);
   157291   }
   157292   *pz = z;
   157293   return 1;
   157294 }
   157295 
   157296 /*
   157297 ** This is the fallback stemmer used when the porter stemmer is
   157298 ** inappropriate.  The input word is copied into the output with
   157299 ** US-ASCII case folding.  If the input word is too long (more
   157300 ** than 20 bytes if it contains no digits or more than 6 bytes if
   157301 ** it contains digits) then word is truncated to 20 or 6 bytes
   157302 ** by taking 10 or 3 bytes from the beginning and end.
   157303 */
   157304 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   157305   int i, mx, j;
   157306   int hasDigit = 0;
   157307   for(i=0; i<nIn; i++){
   157308     char c = zIn[i];
   157309     if( c>='A' && c<='Z' ){
   157310       zOut[i] = c - 'A' + 'a';
   157311     }else{
   157312       if( c>='0' && c<='9' ) hasDigit = 1;
   157313       zOut[i] = c;
   157314     }
   157315   }
   157316   mx = hasDigit ? 3 : 10;
   157317   if( nIn>mx*2 ){
   157318     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
   157319       zOut[j] = zOut[i];
   157320     }
   157321     i = j;
   157322   }
   157323   zOut[i] = 0;
   157324   *pnOut = i;
   157325 }
   157326 
   157327 
   157328 /*
   157329 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
   157330 ** zOut is at least big enough to hold nIn bytes.  Write the actual
   157331 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
   157332 **
   157333 ** Any upper-case characters in the US-ASCII character set ([A-Z])
   157334 ** are converted to lower case.  Upper-case UTF characters are
   157335 ** unchanged.
   157336 **
   157337 ** Words that are longer than about 20 bytes are stemmed by retaining
   157338 ** a few bytes from the beginning and the end of the word.  If the
   157339 ** word contains digits, 3 bytes are taken from the beginning and
   157340 ** 3 bytes from the end.  For long words without digits, 10 bytes
   157341 ** are taken from each end.  US-ASCII case folding still applies.
   157342 **
   157343 ** If the input word contains not digits but does characters not
   157344 ** in [a-zA-Z] then no stemming is attempted and this routine just
   157345 ** copies the input into the input into the output with US-ASCII
   157346 ** case folding.
   157347 **
   157348 ** Stemming never increases the length of the word.  So there is
   157349 ** no chance of overflowing the zOut buffer.
   157350 */
   157351 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   157352   int i, j;
   157353   char zReverse[28];
   157354   char *z, *z2;
   157355   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
   157356     /* The word is too big or too small for the porter stemmer.
   157357     ** Fallback to the copy stemmer */
   157358     copy_stemmer(zIn, nIn, zOut, pnOut);
   157359     return;
   157360   }
   157361   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
   157362     char c = zIn[i];
   157363     if( c>='A' && c<='Z' ){
   157364       zReverse[j] = c + 'a' - 'A';
   157365     }else if( c>='a' && c<='z' ){
   157366       zReverse[j] = c;
   157367     }else{
   157368       /* The use of a character not in [a-zA-Z] means that we fallback
   157369       ** to the copy stemmer */
   157370       copy_stemmer(zIn, nIn, zOut, pnOut);
   157371       return;
   157372     }
   157373   }
   157374   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
   157375   z = &zReverse[j+1];
   157376 
   157377 
   157378   /* Step 1a */
   157379   if( z[0]=='s' ){
   157380     if(
   157381      !stem(&z, "sess", "ss", 0) &&
   157382      !stem(&z, "sei", "i", 0)  &&
   157383      !stem(&z, "ss", "ss", 0)
   157384     ){
   157385       z++;
   157386     }
   157387   }
   157388 
   157389   /* Step 1b */
   157390   z2 = z;
   157391   if( stem(&z, "dee", "ee", m_gt_0) ){
   157392     /* Do nothing.  The work was all in the test */
   157393   }else if(
   157394      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
   157395       && z!=z2
   157396   ){
   157397      if( stem(&z, "ta", "ate", 0) ||
   157398          stem(&z, "lb", "ble", 0) ||
   157399          stem(&z, "zi", "ize", 0) ){
   157400        /* Do nothing.  The work was all in the test */
   157401      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
   157402        z++;
   157403      }else if( m_eq_1(z) && star_oh(z) ){
   157404        *(--z) = 'e';
   157405      }
   157406   }
   157407 
   157408   /* Step 1c */
   157409   if( z[0]=='y' && hasVowel(z+1) ){
   157410     z[0] = 'i';
   157411   }
   157412 
   157413   /* Step 2 */
   157414   switch( z[1] ){
   157415    case 'a':
   157416      if( !stem(&z, "lanoita", "ate", m_gt_0) ){
   157417        stem(&z, "lanoit", "tion", m_gt_0);
   157418      }
   157419      break;
   157420    case 'c':
   157421      if( !stem(&z, "icne", "ence", m_gt_0) ){
   157422        stem(&z, "icna", "ance", m_gt_0);
   157423      }
   157424      break;
   157425    case 'e':
   157426      stem(&z, "rezi", "ize", m_gt_0);
   157427      break;
   157428    case 'g':
   157429      stem(&z, "igol", "log", m_gt_0);
   157430      break;
   157431    case 'l':
   157432      if( !stem(&z, "ilb", "ble", m_gt_0)
   157433       && !stem(&z, "illa", "al", m_gt_0)
   157434       && !stem(&z, "iltne", "ent", m_gt_0)
   157435       && !stem(&z, "ile", "e", m_gt_0)
   157436      ){
   157437        stem(&z, "ilsuo", "ous", m_gt_0);
   157438      }
   157439      break;
   157440    case 'o':
   157441      if( !stem(&z, "noitazi", "ize", m_gt_0)
   157442       && !stem(&z, "noita", "ate", m_gt_0)
   157443      ){
   157444        stem(&z, "rota", "ate", m_gt_0);
   157445      }
   157446      break;
   157447    case 's':
   157448      if( !stem(&z, "msila", "al", m_gt_0)
   157449       && !stem(&z, "ssenevi", "ive", m_gt_0)
   157450       && !stem(&z, "ssenluf", "ful", m_gt_0)
   157451      ){
   157452        stem(&z, "ssensuo", "ous", m_gt_0);
   157453      }
   157454      break;
   157455    case 't':
   157456      if( !stem(&z, "itila", "al", m_gt_0)
   157457       && !stem(&z, "itivi", "ive", m_gt_0)
   157458      ){
   157459        stem(&z, "itilib", "ble", m_gt_0);
   157460      }
   157461      break;
   157462   }
   157463 
   157464   /* Step 3 */
   157465   switch( z[0] ){
   157466    case 'e':
   157467      if( !stem(&z, "etaci", "ic", m_gt_0)
   157468       && !stem(&z, "evita", "", m_gt_0)
   157469      ){
   157470        stem(&z, "ezila", "al", m_gt_0);
   157471      }
   157472      break;
   157473    case 'i':
   157474      stem(&z, "itici", "ic", m_gt_0);
   157475      break;
   157476    case 'l':
   157477      if( !stem(&z, "laci", "ic", m_gt_0) ){
   157478        stem(&z, "luf", "", m_gt_0);
   157479      }
   157480      break;
   157481    case 's':
   157482      stem(&z, "ssen", "", m_gt_0);
   157483      break;
   157484   }
   157485 
   157486   /* Step 4 */
   157487   switch( z[1] ){
   157488    case 'a':
   157489      if( z[0]=='l' && m_gt_1(z+2) ){
   157490        z += 2;
   157491      }
   157492      break;
   157493    case 'c':
   157494      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
   157495        z += 4;
   157496      }
   157497      break;
   157498    case 'e':
   157499      if( z[0]=='r' && m_gt_1(z+2) ){
   157500        z += 2;
   157501      }
   157502      break;
   157503    case 'i':
   157504      if( z[0]=='c' && m_gt_1(z+2) ){
   157505        z += 2;
   157506      }
   157507      break;
   157508    case 'l':
   157509      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
   157510        z += 4;
   157511      }
   157512      break;
   157513    case 'n':
   157514      if( z[0]=='t' ){
   157515        if( z[2]=='a' ){
   157516          if( m_gt_1(z+3) ){
   157517            z += 3;
   157518          }
   157519        }else if( z[2]=='e' ){
   157520          if( !stem(&z, "tneme", "", m_gt_1)
   157521           && !stem(&z, "tnem", "", m_gt_1)
   157522          ){
   157523            stem(&z, "tne", "", m_gt_1);
   157524          }
   157525        }
   157526      }
   157527      break;
   157528    case 'o':
   157529      if( z[0]=='u' ){
   157530        if( m_gt_1(z+2) ){
   157531          z += 2;
   157532        }
   157533      }else if( z[3]=='s' || z[3]=='t' ){
   157534        stem(&z, "noi", "", m_gt_1);
   157535      }
   157536      break;
   157537    case 's':
   157538      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
   157539        z += 3;
   157540      }
   157541      break;
   157542    case 't':
   157543      if( !stem(&z, "eta", "", m_gt_1) ){
   157544        stem(&z, "iti", "", m_gt_1);
   157545      }
   157546      break;
   157547    case 'u':
   157548      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
   157549        z += 3;
   157550      }
   157551      break;
   157552    case 'v':
   157553    case 'z':
   157554      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
   157555        z += 3;
   157556      }
   157557      break;
   157558   }
   157559 
   157560   /* Step 5a */
   157561   if( z[0]=='e' ){
   157562     if( m_gt_1(z+1) ){
   157563       z++;
   157564     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
   157565       z++;
   157566     }
   157567   }
   157568 
   157569   /* Step 5b */
   157570   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
   157571     z++;
   157572   }
   157573 
   157574   /* z[] is now the stemmed word in reverse order.  Flip it back
   157575   ** around into forward order and return.
   157576   */
   157577   *pnOut = i = (int)strlen(z);
   157578   zOut[i] = 0;
   157579   while( *z ){
   157580     zOut[--i] = *(z++);
   157581   }
   157582 }
   157583 
   157584 /*
   157585 ** Characters that can be part of a token.  We assume any character
   157586 ** whose value is greater than 0x80 (any UTF character) can be
   157587 ** part of a token.  In other words, delimiters all must have
   157588 ** values of 0x7f or lower.
   157589 */
   157590 static const char porterIdChar[] = {
   157591 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   157592     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   157593     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   157594     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   157595     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   157596     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   157597 };
   157598 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
   157599 
   157600 /*
   157601 ** Extract the next token from a tokenization cursor.  The cursor must
   157602 ** have been opened by a prior call to porterOpen().
   157603 */
   157604 static int porterNext(
   157605   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
   157606   const char **pzToken,               /* OUT: *pzToken is the token text */
   157607   int *pnBytes,                       /* OUT: Number of bytes in token */
   157608   int *piStartOffset,                 /* OUT: Starting offset of token */
   157609   int *piEndOffset,                   /* OUT: Ending offset of token */
   157610   int *piPosition                     /* OUT: Position integer of token */
   157611 ){
   157612   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   157613   const char *z = c->zInput;
   157614 
   157615   while( c->iOffset<c->nInput ){
   157616     int iStartOffset, ch;
   157617 
   157618     /* Scan past delimiter characters */
   157619     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
   157620       c->iOffset++;
   157621     }
   157622 
   157623     /* Count non-delimiter characters. */
   157624     iStartOffset = c->iOffset;
   157625     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
   157626       c->iOffset++;
   157627     }
   157628 
   157629     if( c->iOffset>iStartOffset ){
   157630       int n = c->iOffset-iStartOffset;
   157631       if( n>c->nAllocated ){
   157632         char *pNew;
   157633         c->nAllocated = n+20;
   157634         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
   157635         if( !pNew ) return SQLITE_NOMEM;
   157636         c->zToken = pNew;
   157637       }
   157638       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
   157639       *pzToken = c->zToken;
   157640       *piStartOffset = iStartOffset;
   157641       *piEndOffset = c->iOffset;
   157642       *piPosition = c->iToken++;
   157643       return SQLITE_OK;
   157644     }
   157645   }
   157646   return SQLITE_DONE;
   157647 }
   157648 
   157649 /*
   157650 ** The set of routines that implement the porter-stemmer tokenizer
   157651 */
   157652 static const sqlite3_tokenizer_module porterTokenizerModule = {
   157653   0,
   157654   porterCreate,
   157655   porterDestroy,
   157656   porterOpen,
   157657   porterClose,
   157658   porterNext,
   157659   0
   157660 };
   157661 
   157662 /*
   157663 ** Allocate a new porter tokenizer.  Return a pointer to the new
   157664 ** tokenizer in *ppModule
   157665 */
   157666 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
   157667   sqlite3_tokenizer_module const**ppModule
   157668 ){
   157669   *ppModule = &porterTokenizerModule;
   157670 }
   157671 
   157672 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   157673 
   157674 /************** End of fts3_porter.c *****************************************/
   157675 /************** Begin file fts3_tokenizer.c **********************************/
   157676 /*
   157677 ** 2007 June 22
   157678 **
   157679 ** The author disclaims copyright to this source code.  In place of
   157680 ** a legal notice, here is a blessing:
   157681 **
   157682 **    May you do good and not evil.
   157683 **    May you find forgiveness for yourself and forgive others.
   157684 **    May you share freely, never taking more than you give.
   157685 **
   157686 ******************************************************************************
   157687 **
   157688 ** This is part of an SQLite module implementing full-text search.
   157689 ** This particular file implements the generic tokenizer interface.
   157690 */
   157691 
   157692 /*
   157693 ** The code in this file is only compiled if:
   157694 **
   157695 **     * The FTS3 module is being built as an extension
   157696 **       (in which case SQLITE_CORE is not defined), or
   157697 **
   157698 **     * The FTS3 module is being built into the core of
   157699 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   157700 */
   157701 /* #include "fts3Int.h" */
   157702 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   157703 
   157704 /* #include <assert.h> */
   157705 /* #include <string.h> */
   157706 
   157707 /*
   157708 ** Return true if the two-argument version of fts3_tokenizer()
   157709 ** has been activated via a prior call to sqlite3_db_config(db,
   157710 ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
   157711 */
   157712 static int fts3TokenizerEnabled(sqlite3_context *context){
   157713   sqlite3 *db = sqlite3_context_db_handle(context);
   157714   int isEnabled = 0;
   157715   sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
   157716   return isEnabled;
   157717 }
   157718 
   157719 /*
   157720 ** Implementation of the SQL scalar function for accessing the underlying
   157721 ** hash table. This function may be called as follows:
   157722 **
   157723 **   SELECT <function-name>(<key-name>);
   157724 **   SELECT <function-name>(<key-name>, <pointer>);
   157725 **
   157726 ** where <function-name> is the name passed as the second argument
   157727 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
   157728 **
   157729 ** If the <pointer> argument is specified, it must be a blob value
   157730 ** containing a pointer to be stored as the hash data corresponding
   157731 ** to the string <key-name>. If <pointer> is not specified, then
   157732 ** the string <key-name> must already exist in the has table. Otherwise,
   157733 ** an error is returned.
   157734 **
   157735 ** Whether or not the <pointer> argument is specified, the value returned
   157736 ** is a blob containing the pointer stored as the hash data corresponding
   157737 ** to string <key-name> (after the hash-table is updated, if applicable).
   157738 */
   157739 static void fts3TokenizerFunc(
   157740   sqlite3_context *context,
   157741   int argc,
   157742   sqlite3_value **argv
   157743 ){
   157744   Fts3Hash *pHash;
   157745   void *pPtr = 0;
   157746   const unsigned char *zName;
   157747   int nName;
   157748 
   157749   assert( argc==1 || argc==2 );
   157750 
   157751   pHash = (Fts3Hash *)sqlite3_user_data(context);
   157752 
   157753   zName = sqlite3_value_text(argv[0]);
   157754   nName = sqlite3_value_bytes(argv[0])+1;
   157755 
   157756   if( argc==2 ){
   157757     if( fts3TokenizerEnabled(context) ){
   157758       void *pOld;
   157759       int n = sqlite3_value_bytes(argv[1]);
   157760       if( zName==0 || n!=sizeof(pPtr) ){
   157761         sqlite3_result_error(context, "argument type mismatch", -1);
   157762         return;
   157763       }
   157764       pPtr = *(void **)sqlite3_value_blob(argv[1]);
   157765       pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
   157766       if( pOld==pPtr ){
   157767         sqlite3_result_error(context, "out of memory", -1);
   157768       }
   157769     }else{
   157770       sqlite3_result_error(context, "fts3tokenize disabled", -1);
   157771       return;
   157772     }
   157773   }else{
   157774     if( zName ){
   157775       pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
   157776     }
   157777     if( !pPtr ){
   157778       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   157779       sqlite3_result_error(context, zErr, -1);
   157780       sqlite3_free(zErr);
   157781       return;
   157782     }
   157783   }
   157784   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
   157785 }
   157786 
   157787 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
   157788   static const char isFtsIdChar[] = {
   157789       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
   157790       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
   157791       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
   157792       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   157793       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   157794       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   157795       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   157796       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   157797   };
   157798   return (c&0x80 || isFtsIdChar[(int)(c)]);
   157799 }
   157800 
   157801 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
   157802   const char *z1;
   157803   const char *z2 = 0;
   157804 
   157805   /* Find the start of the next token. */
   157806   z1 = zStr;
   157807   while( z2==0 ){
   157808     char c = *z1;
   157809     switch( c ){
   157810       case '\0': return 0;        /* No more tokens here */
   157811       case '\'':
   157812       case '"':
   157813       case '`': {
   157814         z2 = z1;
   157815         while( *++z2 && (*z2!=c || *++z2==c) );
   157816         break;
   157817       }
   157818       case '[':
   157819         z2 = &z1[1];
   157820         while( *z2 && z2[0]!=']' ) z2++;
   157821         if( *z2 ) z2++;
   157822         break;
   157823 
   157824       default:
   157825         if( sqlite3Fts3IsIdChar(*z1) ){
   157826           z2 = &z1[1];
   157827           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
   157828         }else{
   157829           z1++;
   157830         }
   157831     }
   157832   }
   157833 
   157834   *pn = (int)(z2-z1);
   157835   return z1;
   157836 }
   157837 
   157838 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
   157839   Fts3Hash *pHash,                /* Tokenizer hash table */
   157840   const char *zArg,               /* Tokenizer name */
   157841   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
   157842   char **pzErr                    /* OUT: Set to malloced error message */
   157843 ){
   157844   int rc;
   157845   char *z = (char *)zArg;
   157846   int n = 0;
   157847   char *zCopy;
   157848   char *zEnd;                     /* Pointer to nul-term of zCopy */
   157849   sqlite3_tokenizer_module *m;
   157850 
   157851   zCopy = sqlite3_mprintf("%s", zArg);
   157852   if( !zCopy ) return SQLITE_NOMEM;
   157853   zEnd = &zCopy[strlen(zCopy)];
   157854 
   157855   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
   157856   if( z==0 ){
   157857     assert( n==0 );
   157858     z = zCopy;
   157859   }
   157860   z[n] = '\0';
   157861   sqlite3Fts3Dequote(z);
   157862 
   157863   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
   157864   if( !m ){
   157865     sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
   157866     rc = SQLITE_ERROR;
   157867   }else{
   157868     char const **aArg = 0;
   157869     int iArg = 0;
   157870     z = &z[n+1];
   157871     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
   157872       int nNew = sizeof(char *)*(iArg+1);
   157873       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
   157874       if( !aNew ){
   157875         sqlite3_free(zCopy);
   157876         sqlite3_free((void *)aArg);
   157877         return SQLITE_NOMEM;
   157878       }
   157879       aArg = aNew;
   157880       aArg[iArg++] = z;
   157881       z[n] = '\0';
   157882       sqlite3Fts3Dequote(z);
   157883       z = &z[n+1];
   157884     }
   157885     rc = m->xCreate(iArg, aArg, ppTok);
   157886     assert( rc!=SQLITE_OK || *ppTok );
   157887     if( rc!=SQLITE_OK ){
   157888       sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
   157889     }else{
   157890       (*ppTok)->pModule = m;
   157891     }
   157892     sqlite3_free((void *)aArg);
   157893   }
   157894 
   157895   sqlite3_free(zCopy);
   157896   return rc;
   157897 }
   157898 
   157899 
   157900 #ifdef SQLITE_TEST
   157901 
   157902 #if defined(INCLUDE_SQLITE_TCL_H)
   157903 #  include "sqlite_tcl.h"
   157904 #else
   157905 #  include "tcl.h"
   157906 #endif
   157907 /* #include <string.h> */
   157908 
   157909 /*
   157910 ** Implementation of a special SQL scalar function for testing tokenizers
   157911 ** designed to be used in concert with the Tcl testing framework. This
   157912 ** function must be called with two or more arguments:
   157913 **
   157914 **   SELECT <function-name>(<key-name>, ..., <input-string>);
   157915 **
   157916 ** where <function-name> is the name passed as the second argument
   157917 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
   157918 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
   157919 **
   157920 ** The return value is a string that may be interpreted as a Tcl
   157921 ** list. For each token in the <input-string>, three elements are
   157922 ** added to the returned list. The first is the token position, the
   157923 ** second is the token text (folded, stemmed, etc.) and the third is the
   157924 ** substring of <input-string> associated with the token. For example,
   157925 ** using the built-in "simple" tokenizer:
   157926 **
   157927 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
   157928 **
   157929 ** will return the string:
   157930 **
   157931 **   "{0 i I 1 dont don't 2 see see 3 how how}"
   157932 **
   157933 */
   157934 static void testFunc(
   157935   sqlite3_context *context,
   157936   int argc,
   157937   sqlite3_value **argv
   157938 ){
   157939   Fts3Hash *pHash;
   157940   sqlite3_tokenizer_module *p;
   157941   sqlite3_tokenizer *pTokenizer = 0;
   157942   sqlite3_tokenizer_cursor *pCsr = 0;
   157943 
   157944   const char *zErr = 0;
   157945 
   157946   const char *zName;
   157947   int nName;
   157948   const char *zInput;
   157949   int nInput;
   157950 
   157951   const char *azArg[64];
   157952 
   157953   const char *zToken;
   157954   int nToken = 0;
   157955   int iStart = 0;
   157956   int iEnd = 0;
   157957   int iPos = 0;
   157958   int i;
   157959 
   157960   Tcl_Obj *pRet;
   157961 
   157962   if( argc<2 ){
   157963     sqlite3_result_error(context, "insufficient arguments", -1);
   157964     return;
   157965   }
   157966 
   157967   nName = sqlite3_value_bytes(argv[0]);
   157968   zName = (const char *)sqlite3_value_text(argv[0]);
   157969   nInput = sqlite3_value_bytes(argv[argc-1]);
   157970   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
   157971 
   157972   pHash = (Fts3Hash *)sqlite3_user_data(context);
   157973   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   157974 
   157975   if( !p ){
   157976     char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
   157977     sqlite3_result_error(context, zErr2, -1);
   157978     sqlite3_free(zErr2);
   157979     return;
   157980   }
   157981 
   157982   pRet = Tcl_NewObj();
   157983   Tcl_IncrRefCount(pRet);
   157984 
   157985   for(i=1; i<argc-1; i++){
   157986     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
   157987   }
   157988 
   157989   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
   157990     zErr = "error in xCreate()";
   157991     goto finish;
   157992   }
   157993   pTokenizer->pModule = p;
   157994   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
   157995     zErr = "error in xOpen()";
   157996     goto finish;
   157997   }
   157998 
   157999   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
   158000     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
   158001     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   158002     zToken = &zInput[iStart];
   158003     nToken = iEnd-iStart;
   158004     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   158005   }
   158006 
   158007   if( SQLITE_OK!=p->xClose(pCsr) ){
   158008     zErr = "error in xClose()";
   158009     goto finish;
   158010   }
   158011   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
   158012     zErr = "error in xDestroy()";
   158013     goto finish;
   158014   }
   158015 
   158016 finish:
   158017   if( zErr ){
   158018     sqlite3_result_error(context, zErr, -1);
   158019   }else{
   158020     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
   158021   }
   158022   Tcl_DecrRefCount(pRet);
   158023 }
   158024 
   158025 static
   158026 int registerTokenizer(
   158027   sqlite3 *db,
   158028   char *zName,
   158029   const sqlite3_tokenizer_module *p
   158030 ){
   158031   int rc;
   158032   sqlite3_stmt *pStmt;
   158033   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
   158034 
   158035   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   158036   if( rc!=SQLITE_OK ){
   158037     return rc;
   158038   }
   158039 
   158040   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   158041   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
   158042   sqlite3_step(pStmt);
   158043 
   158044   return sqlite3_finalize(pStmt);
   158045 }
   158046 
   158047 
   158048 static
   158049 int queryTokenizer(
   158050   sqlite3 *db,
   158051   char *zName,
   158052   const sqlite3_tokenizer_module **pp
   158053 ){
   158054   int rc;
   158055   sqlite3_stmt *pStmt;
   158056   const char zSql[] = "SELECT fts3_tokenizer(?)";
   158057 
   158058   *pp = 0;
   158059   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   158060   if( rc!=SQLITE_OK ){
   158061     return rc;
   158062   }
   158063 
   158064   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   158065   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   158066     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   158067       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   158068     }
   158069   }
   158070 
   158071   return sqlite3_finalize(pStmt);
   158072 }
   158073 
   158074 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   158075 
   158076 /*
   158077 ** Implementation of the scalar function fts3_tokenizer_internal_test().
   158078 ** This function is used for testing only, it is not included in the
   158079 ** build unless SQLITE_TEST is defined.
   158080 **
   158081 ** The purpose of this is to test that the fts3_tokenizer() function
   158082 ** can be used as designed by the C-code in the queryTokenizer and
   158083 ** registerTokenizer() functions above. These two functions are repeated
   158084 ** in the README.tokenizer file as an example, so it is important to
   158085 ** test them.
   158086 **
   158087 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
   158088 ** function with no arguments. An assert() will fail if a problem is
   158089 ** detected. i.e.:
   158090 **
   158091 **     SELECT fts3_tokenizer_internal_test();
   158092 **
   158093 */
   158094 static void intTestFunc(
   158095   sqlite3_context *context,
   158096   int argc,
   158097   sqlite3_value **argv
   158098 ){
   158099   int rc;
   158100   const sqlite3_tokenizer_module *p1;
   158101   const sqlite3_tokenizer_module *p2;
   158102   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
   158103 
   158104   UNUSED_PARAMETER(argc);
   158105   UNUSED_PARAMETER(argv);
   158106 
   158107   /* Test the query function */
   158108   sqlite3Fts3SimpleTokenizerModule(&p1);
   158109   rc = queryTokenizer(db, "simple", &p2);
   158110   assert( rc==SQLITE_OK );
   158111   assert( p1==p2 );
   158112   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   158113   assert( rc==SQLITE_ERROR );
   158114   assert( p2==0 );
   158115   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
   158116 
   158117   /* Test the storage function */
   158118   if( fts3TokenizerEnabled(context) ){
   158119     rc = registerTokenizer(db, "nosuchtokenizer", p1);
   158120     assert( rc==SQLITE_OK );
   158121     rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   158122     assert( rc==SQLITE_OK );
   158123     assert( p2==p1 );
   158124   }
   158125 
   158126   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
   158127 }
   158128 
   158129 #endif
   158130 
   158131 /*
   158132 ** Set up SQL objects in database db used to access the contents of
   158133 ** the hash table pointed to by argument pHash. The hash table must
   158134 ** been initialized to use string keys, and to take a private copy
   158135 ** of the key when a value is inserted. i.e. by a call similar to:
   158136 **
   158137 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   158138 **
   158139 ** This function adds a scalar function (see header comment above
   158140 ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
   158141 ** defined at compilation time, a temporary virtual table (see header
   158142 ** comment above struct HashTableVtab) to the database schema. Both
   158143 ** provide read/write access to the contents of *pHash.
   158144 **
   158145 ** The third argument to this function, zName, is used as the name
   158146 ** of both the scalar and, if created, the virtual table.
   158147 */
   158148 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
   158149   sqlite3 *db,
   158150   Fts3Hash *pHash,
   158151   const char *zName
   158152 ){
   158153   int rc = SQLITE_OK;
   158154   void *p = (void *)pHash;
   158155   const int any = SQLITE_ANY;
   158156 
   158157 #ifdef SQLITE_TEST
   158158   char *zTest = 0;
   158159   char *zTest2 = 0;
   158160   void *pdb = (void *)db;
   158161   zTest = sqlite3_mprintf("%s_test", zName);
   158162   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
   158163   if( !zTest || !zTest2 ){
   158164     rc = SQLITE_NOMEM;
   158165   }
   158166 #endif
   158167 
   158168   if( SQLITE_OK==rc ){
   158169     rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
   158170   }
   158171   if( SQLITE_OK==rc ){
   158172     rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
   158173   }
   158174 #ifdef SQLITE_TEST
   158175   if( SQLITE_OK==rc ){
   158176     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
   158177   }
   158178   if( SQLITE_OK==rc ){
   158179     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
   158180   }
   158181 #endif
   158182 
   158183 #ifdef SQLITE_TEST
   158184   sqlite3_free(zTest);
   158185   sqlite3_free(zTest2);
   158186 #endif
   158187 
   158188   return rc;
   158189 }
   158190 
   158191 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   158192 
   158193 /************** End of fts3_tokenizer.c **************************************/
   158194 /************** Begin file fts3_tokenizer1.c *********************************/
   158195 /*
   158196 ** 2006 Oct 10
   158197 **
   158198 ** The author disclaims copyright to this source code.  In place of
   158199 ** a legal notice, here is a blessing:
   158200 **
   158201 **    May you do good and not evil.
   158202 **    May you find forgiveness for yourself and forgive others.
   158203 **    May you share freely, never taking more than you give.
   158204 **
   158205 ******************************************************************************
   158206 **
   158207 ** Implementation of the "simple" full-text-search tokenizer.
   158208 */
   158209 
   158210 /*
   158211 ** The code in this file is only compiled if:
   158212 **
   158213 **     * The FTS3 module is being built as an extension
   158214 **       (in which case SQLITE_CORE is not defined), or
   158215 **
   158216 **     * The FTS3 module is being built into the core of
   158217 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   158218 */
   158219 /* #include "fts3Int.h" */
   158220 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   158221 
   158222 /* #include <assert.h> */
   158223 /* #include <stdlib.h> */
   158224 /* #include <stdio.h> */
   158225 /* #include <string.h> */
   158226 
   158227 /* #include "fts3_tokenizer.h" */
   158228 
   158229 typedef struct simple_tokenizer {
   158230   sqlite3_tokenizer base;
   158231   char delim[128];             /* flag ASCII delimiters */
   158232 } simple_tokenizer;
   158233 
   158234 typedef struct simple_tokenizer_cursor {
   158235   sqlite3_tokenizer_cursor base;
   158236   const char *pInput;          /* input we are tokenizing */
   158237   int nBytes;                  /* size of the input */
   158238   int iOffset;                 /* current position in pInput */
   158239   int iToken;                  /* index of next token to be returned */
   158240   char *pToken;                /* storage for current token */
   158241   int nTokenAllocated;         /* space allocated to zToken buffer */
   158242 } simple_tokenizer_cursor;
   158243 
   158244 
   158245 static int simpleDelim(simple_tokenizer *t, unsigned char c){
   158246   return c<0x80 && t->delim[c];
   158247 }
   158248 static int fts3_isalnum(int x){
   158249   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
   158250 }
   158251 
   158252 /*
   158253 ** Create a new tokenizer instance.
   158254 */
   158255 static int simpleCreate(
   158256   int argc, const char * const *argv,
   158257   sqlite3_tokenizer **ppTokenizer
   158258 ){
   158259   simple_tokenizer *t;
   158260 
   158261   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
   158262   if( t==NULL ) return SQLITE_NOMEM;
   158263   memset(t, 0, sizeof(*t));
   158264 
   158265   /* TODO(shess) Delimiters need to remain the same from run to run,
   158266   ** else we need to reindex.  One solution would be a meta-table to
   158267   ** track such information in the database, then we'd only want this
   158268   ** information on the initial create.
   158269   */
   158270   if( argc>1 ){
   158271     int i, n = (int)strlen(argv[1]);
   158272     for(i=0; i<n; i++){
   158273       unsigned char ch = argv[1][i];
   158274       /* We explicitly don't support UTF-8 delimiters for now. */
   158275       if( ch>=0x80 ){
   158276         sqlite3_free(t);
   158277         return SQLITE_ERROR;
   158278       }
   158279       t->delim[ch] = 1;
   158280     }
   158281   } else {
   158282     /* Mark non-alphanumeric ASCII characters as delimiters */
   158283     int i;
   158284     for(i=1; i<0x80; i++){
   158285       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
   158286     }
   158287   }
   158288 
   158289   *ppTokenizer = &t->base;
   158290   return SQLITE_OK;
   158291 }
   158292 
   158293 /*
   158294 ** Destroy a tokenizer
   158295 */
   158296 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
   158297   sqlite3_free(pTokenizer);
   158298   return SQLITE_OK;
   158299 }
   158300 
   158301 /*
   158302 ** Prepare to begin tokenizing a particular string.  The input
   158303 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   158304 ** used to incrementally tokenize this string is returned in
   158305 ** *ppCursor.
   158306 */
   158307 static int simpleOpen(
   158308   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   158309   const char *pInput, int nBytes,        /* String to be tokenized */
   158310   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   158311 ){
   158312   simple_tokenizer_cursor *c;
   158313 
   158314   UNUSED_PARAMETER(pTokenizer);
   158315 
   158316   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   158317   if( c==NULL ) return SQLITE_NOMEM;
   158318 
   158319   c->pInput = pInput;
   158320   if( pInput==0 ){
   158321     c->nBytes = 0;
   158322   }else if( nBytes<0 ){
   158323     c->nBytes = (int)strlen(pInput);
   158324   }else{
   158325     c->nBytes = nBytes;
   158326   }
   158327   c->iOffset = 0;                 /* start tokenizing at the beginning */
   158328   c->iToken = 0;
   158329   c->pToken = NULL;               /* no space allocated, yet. */
   158330   c->nTokenAllocated = 0;
   158331 
   158332   *ppCursor = &c->base;
   158333   return SQLITE_OK;
   158334 }
   158335 
   158336 /*
   158337 ** Close a tokenization cursor previously opened by a call to
   158338 ** simpleOpen() above.
   158339 */
   158340 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
   158341   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   158342   sqlite3_free(c->pToken);
   158343   sqlite3_free(c);
   158344   return SQLITE_OK;
   158345 }
   158346 
   158347 /*
   158348 ** Extract the next token from a tokenization cursor.  The cursor must
   158349 ** have been opened by a prior call to simpleOpen().
   158350 */
   158351 static int simpleNext(
   158352   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   158353   const char **ppToken,               /* OUT: *ppToken is the token text */
   158354   int *pnBytes,                       /* OUT: Number of bytes in token */
   158355   int *piStartOffset,                 /* OUT: Starting offset of token */
   158356   int *piEndOffset,                   /* OUT: Ending offset of token */
   158357   int *piPosition                     /* OUT: Position integer of token */
   158358 ){
   158359   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   158360   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
   158361   unsigned char *p = (unsigned char *)c->pInput;
   158362 
   158363   while( c->iOffset<c->nBytes ){
   158364     int iStartOffset;
   158365 
   158366     /* Scan past delimiter characters */
   158367     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
   158368       c->iOffset++;
   158369     }
   158370 
   158371     /* Count non-delimiter characters. */
   158372     iStartOffset = c->iOffset;
   158373     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
   158374       c->iOffset++;
   158375     }
   158376 
   158377     if( c->iOffset>iStartOffset ){
   158378       int i, n = c->iOffset-iStartOffset;
   158379       if( n>c->nTokenAllocated ){
   158380         char *pNew;
   158381         c->nTokenAllocated = n+20;
   158382         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
   158383         if( !pNew ) return SQLITE_NOMEM;
   158384         c->pToken = pNew;
   158385       }
   158386       for(i=0; i<n; i++){
   158387         /* TODO(shess) This needs expansion to handle UTF-8
   158388         ** case-insensitivity.
   158389         */
   158390         unsigned char ch = p[iStartOffset+i];
   158391         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
   158392       }
   158393       *ppToken = c->pToken;
   158394       *pnBytes = n;
   158395       *piStartOffset = iStartOffset;
   158396       *piEndOffset = c->iOffset;
   158397       *piPosition = c->iToken++;
   158398 
   158399       return SQLITE_OK;
   158400     }
   158401   }
   158402   return SQLITE_DONE;
   158403 }
   158404 
   158405 /*
   158406 ** The set of routines that implement the simple tokenizer
   158407 */
   158408 static const sqlite3_tokenizer_module simpleTokenizerModule = {
   158409   0,
   158410   simpleCreate,
   158411   simpleDestroy,
   158412   simpleOpen,
   158413   simpleClose,
   158414   simpleNext,
   158415   0,
   158416 };
   158417 
   158418 /*
   158419 ** Allocate a new simple tokenizer.  Return a pointer to the new
   158420 ** tokenizer in *ppModule
   158421 */
   158422 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
   158423   sqlite3_tokenizer_module const**ppModule
   158424 ){
   158425   *ppModule = &simpleTokenizerModule;
   158426 }
   158427 
   158428 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   158429 
   158430 /************** End of fts3_tokenizer1.c *************************************/
   158431 /************** Begin file fts3_tokenize_vtab.c ******************************/
   158432 /*
   158433 ** 2013 Apr 22
   158434 **
   158435 ** The author disclaims copyright to this source code.  In place of
   158436 ** a legal notice, here is a blessing:
   158437 **
   158438 **    May you do good and not evil.
   158439 **    May you find forgiveness for yourself and forgive others.
   158440 **    May you share freely, never taking more than you give.
   158441 **
   158442 ******************************************************************************
   158443 **
   158444 ** This file contains code for the "fts3tokenize" virtual table module.
   158445 ** An fts3tokenize virtual table is created as follows:
   158446 **
   158447 **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
   158448 **       <tokenizer-name>, <arg-1>, ...
   158449 **   );
   158450 **
   158451 ** The table created has the following schema:
   158452 **
   158453 **   CREATE TABLE <tbl>(input, token, start, end, position)
   158454 **
   158455 ** When queried, the query must include a WHERE clause of type:
   158456 **
   158457 **   input = <string>
   158458 **
   158459 ** The virtual table module tokenizes this <string>, using the FTS3
   158460 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
   158461 ** statement and returns one row for each token in the result. With
   158462 ** fields set as follows:
   158463 **
   158464 **   input:   Always set to a copy of <string>
   158465 **   token:   A token from the input.
   158466 **   start:   Byte offset of the token within the input <string>.
   158467 **   end:     Byte offset of the byte immediately following the end of the
   158468 **            token within the input string.
   158469 **   pos:     Token offset of token within input.
   158470 **
   158471 */
   158472 /* #include "fts3Int.h" */
   158473 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   158474 
   158475 /* #include <string.h> */
   158476 /* #include <assert.h> */
   158477 
   158478 typedef struct Fts3tokTable Fts3tokTable;
   158479 typedef struct Fts3tokCursor Fts3tokCursor;
   158480 
   158481 /*
   158482 ** Virtual table structure.
   158483 */
   158484 struct Fts3tokTable {
   158485   sqlite3_vtab base;              /* Base class used by SQLite core */
   158486   const sqlite3_tokenizer_module *pMod;
   158487   sqlite3_tokenizer *pTok;
   158488 };
   158489 
   158490 /*
   158491 ** Virtual table cursor structure.
   158492 */
   158493 struct Fts3tokCursor {
   158494   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   158495   char *zInput;                   /* Input string */
   158496   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
   158497   int iRowid;                     /* Current 'rowid' value */
   158498   const char *zToken;             /* Current 'token' value */
   158499   int nToken;                     /* Size of zToken in bytes */
   158500   int iStart;                     /* Current 'start' value */
   158501   int iEnd;                       /* Current 'end' value */
   158502   int iPos;                       /* Current 'pos' value */
   158503 };
   158504 
   158505 /*
   158506 ** Query FTS for the tokenizer implementation named zName.
   158507 */
   158508 static int fts3tokQueryTokenizer(
   158509   Fts3Hash *pHash,
   158510   const char *zName,
   158511   const sqlite3_tokenizer_module **pp,
   158512   char **pzErr
   158513 ){
   158514   sqlite3_tokenizer_module *p;
   158515   int nName = (int)strlen(zName);
   158516 
   158517   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   158518   if( !p ){
   158519     sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
   158520     return SQLITE_ERROR;
   158521   }
   158522 
   158523   *pp = p;
   158524   return SQLITE_OK;
   158525 }
   158526 
   158527 /*
   158528 ** The second argument, argv[], is an array of pointers to nul-terminated
   158529 ** strings. This function makes a copy of the array and strings into a
   158530 ** single block of memory. It then dequotes any of the strings that appear
   158531 ** to be quoted.
   158532 **
   158533 ** If successful, output parameter *pazDequote is set to point at the
   158534 ** array of dequoted strings and SQLITE_OK is returned. The caller is
   158535 ** responsible for eventually calling sqlite3_free() to free the array
   158536 ** in this case. Or, if an error occurs, an SQLite error code is returned.
   158537 ** The final value of *pazDequote is undefined in this case.
   158538 */
   158539 static int fts3tokDequoteArray(
   158540   int argc,                       /* Number of elements in argv[] */
   158541   const char * const *argv,       /* Input array */
   158542   char ***pazDequote              /* Output array */
   158543 ){
   158544   int rc = SQLITE_OK;             /* Return code */
   158545   if( argc==0 ){
   158546     *pazDequote = 0;
   158547   }else{
   158548     int i;
   158549     int nByte = 0;
   158550     char **azDequote;
   158551 
   158552     for(i=0; i<argc; i++){
   158553       nByte += (int)(strlen(argv[i]) + 1);
   158554     }
   158555 
   158556     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
   158557     if( azDequote==0 ){
   158558       rc = SQLITE_NOMEM;
   158559     }else{
   158560       char *pSpace = (char *)&azDequote[argc];
   158561       for(i=0; i<argc; i++){
   158562         int n = (int)strlen(argv[i]);
   158563         azDequote[i] = pSpace;
   158564         memcpy(pSpace, argv[i], n+1);
   158565         sqlite3Fts3Dequote(pSpace);
   158566         pSpace += (n+1);
   158567       }
   158568     }
   158569   }
   158570 
   158571   return rc;
   158572 }
   158573 
   158574 /*
   158575 ** Schema of the tokenizer table.
   158576 */
   158577 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
   158578 
   158579 /*
   158580 ** This function does all the work for both the xConnect and xCreate methods.
   158581 ** These tables have no persistent representation of their own, so xConnect
   158582 ** and xCreate are identical operations.
   158583 **
   158584 **   argv[0]: module name
   158585 **   argv[1]: database name
   158586 **   argv[2]: table name
   158587 **   argv[3]: first argument (tokenizer name)
   158588 */
   158589 static int fts3tokConnectMethod(
   158590   sqlite3 *db,                    /* Database connection */
   158591   void *pHash,                    /* Hash table of tokenizers */
   158592   int argc,                       /* Number of elements in argv array */
   158593   const char * const *argv,       /* xCreate/xConnect argument array */
   158594   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   158595   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   158596 ){
   158597   Fts3tokTable *pTab = 0;
   158598   const sqlite3_tokenizer_module *pMod = 0;
   158599   sqlite3_tokenizer *pTok = 0;
   158600   int rc;
   158601   char **azDequote = 0;
   158602   int nDequote;
   158603 
   158604   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
   158605   if( rc!=SQLITE_OK ) return rc;
   158606 
   158607   nDequote = argc-3;
   158608   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
   158609 
   158610   if( rc==SQLITE_OK ){
   158611     const char *zModule;
   158612     if( nDequote<1 ){
   158613       zModule = "simple";
   158614     }else{
   158615       zModule = azDequote[0];
   158616     }
   158617     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
   158618   }
   158619 
   158620   assert( (rc==SQLITE_OK)==(pMod!=0) );
   158621   if( rc==SQLITE_OK ){
   158622     const char * const *azArg = (const char * const *)&azDequote[1];
   158623     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
   158624   }
   158625 
   158626   if( rc==SQLITE_OK ){
   158627     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
   158628     if( pTab==0 ){
   158629       rc = SQLITE_NOMEM;
   158630     }
   158631   }
   158632 
   158633   if( rc==SQLITE_OK ){
   158634     memset(pTab, 0, sizeof(Fts3tokTable));
   158635     pTab->pMod = pMod;
   158636     pTab->pTok = pTok;
   158637     *ppVtab = &pTab->base;
   158638   }else{
   158639     if( pTok ){
   158640       pMod->xDestroy(pTok);
   158641     }
   158642   }
   158643 
   158644   sqlite3_free(azDequote);
   158645   return rc;
   158646 }
   158647 
   158648 /*
   158649 ** This function does the work for both the xDisconnect and xDestroy methods.
   158650 ** These tables have no persistent representation of their own, so xDisconnect
   158651 ** and xDestroy are identical operations.
   158652 */
   158653 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
   158654   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
   158655 
   158656   pTab->pMod->xDestroy(pTab->pTok);
   158657   sqlite3_free(pTab);
   158658   return SQLITE_OK;
   158659 }
   158660 
   158661 /*
   158662 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   158663 */
   158664 static int fts3tokBestIndexMethod(
   158665   sqlite3_vtab *pVTab,
   158666   sqlite3_index_info *pInfo
   158667 ){
   158668   int i;
   158669   UNUSED_PARAMETER(pVTab);
   158670 
   158671   for(i=0; i<pInfo->nConstraint; i++){
   158672     if( pInfo->aConstraint[i].usable
   158673      && pInfo->aConstraint[i].iColumn==0
   158674      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
   158675     ){
   158676       pInfo->idxNum = 1;
   158677       pInfo->aConstraintUsage[i].argvIndex = 1;
   158678       pInfo->aConstraintUsage[i].omit = 1;
   158679       pInfo->estimatedCost = 1;
   158680       return SQLITE_OK;
   158681     }
   158682   }
   158683 
   158684   pInfo->idxNum = 0;
   158685   assert( pInfo->estimatedCost>1000000.0 );
   158686 
   158687   return SQLITE_OK;
   158688 }
   158689 
   158690 /*
   158691 ** xOpen - Open a cursor.
   158692 */
   158693 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   158694   Fts3tokCursor *pCsr;
   158695   UNUSED_PARAMETER(pVTab);
   158696 
   158697   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
   158698   if( pCsr==0 ){
   158699     return SQLITE_NOMEM;
   158700   }
   158701   memset(pCsr, 0, sizeof(Fts3tokCursor));
   158702 
   158703   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   158704   return SQLITE_OK;
   158705 }
   158706 
   158707 /*
   158708 ** Reset the tokenizer cursor passed as the only argument. As if it had
   158709 ** just been returned by fts3tokOpenMethod().
   158710 */
   158711 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
   158712   if( pCsr->pCsr ){
   158713     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
   158714     pTab->pMod->xClose(pCsr->pCsr);
   158715     pCsr->pCsr = 0;
   158716   }
   158717   sqlite3_free(pCsr->zInput);
   158718   pCsr->zInput = 0;
   158719   pCsr->zToken = 0;
   158720   pCsr->nToken = 0;
   158721   pCsr->iStart = 0;
   158722   pCsr->iEnd = 0;
   158723   pCsr->iPos = 0;
   158724   pCsr->iRowid = 0;
   158725 }
   158726 
   158727 /*
   158728 ** xClose - Close a cursor.
   158729 */
   158730 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
   158731   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   158732 
   158733   fts3tokResetCursor(pCsr);
   158734   sqlite3_free(pCsr);
   158735   return SQLITE_OK;
   158736 }
   158737 
   158738 /*
   158739 ** xNext - Advance the cursor to the next row, if any.
   158740 */
   158741 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
   158742   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   158743   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
   158744   int rc;                         /* Return code */
   158745 
   158746   pCsr->iRowid++;
   158747   rc = pTab->pMod->xNext(pCsr->pCsr,
   158748       &pCsr->zToken, &pCsr->nToken,
   158749       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
   158750   );
   158751 
   158752   if( rc!=SQLITE_OK ){
   158753     fts3tokResetCursor(pCsr);
   158754     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   158755   }
   158756 
   158757   return rc;
   158758 }
   158759 
   158760 /*
   158761 ** xFilter - Initialize a cursor to point at the start of its data.
   158762 */
   158763 static int fts3tokFilterMethod(
   158764   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   158765   int idxNum,                     /* Strategy index */
   158766   const char *idxStr,             /* Unused */
   158767   int nVal,                       /* Number of elements in apVal */
   158768   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   158769 ){
   158770   int rc = SQLITE_ERROR;
   158771   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   158772   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
   158773   UNUSED_PARAMETER(idxStr);
   158774   UNUSED_PARAMETER(nVal);
   158775 
   158776   fts3tokResetCursor(pCsr);
   158777   if( idxNum==1 ){
   158778     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
   158779     int nByte = sqlite3_value_bytes(apVal[0]);
   158780     pCsr->zInput = sqlite3_malloc(nByte+1);
   158781     if( pCsr->zInput==0 ){
   158782       rc = SQLITE_NOMEM;
   158783     }else{
   158784       memcpy(pCsr->zInput, zByte, nByte);
   158785       pCsr->zInput[nByte] = 0;
   158786       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
   158787       if( rc==SQLITE_OK ){
   158788         pCsr->pCsr->pTokenizer = pTab->pTok;
   158789       }
   158790     }
   158791   }
   158792 
   158793   if( rc!=SQLITE_OK ) return rc;
   158794   return fts3tokNextMethod(pCursor);
   158795 }
   158796 
   158797 /*
   158798 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   158799 */
   158800 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
   158801   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   158802   return (pCsr->zToken==0);
   158803 }
   158804 
   158805 /*
   158806 ** xColumn - Return a column value.
   158807 */
   158808 static int fts3tokColumnMethod(
   158809   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   158810   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   158811   int iCol                        /* Index of column to read value from */
   158812 ){
   158813   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   158814 
   158815   /* CREATE TABLE x(input, token, start, end, position) */
   158816   switch( iCol ){
   158817     case 0:
   158818       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
   158819       break;
   158820     case 1:
   158821       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
   158822       break;
   158823     case 2:
   158824       sqlite3_result_int(pCtx, pCsr->iStart);
   158825       break;
   158826     case 3:
   158827       sqlite3_result_int(pCtx, pCsr->iEnd);
   158828       break;
   158829     default:
   158830       assert( iCol==4 );
   158831       sqlite3_result_int(pCtx, pCsr->iPos);
   158832       break;
   158833   }
   158834   return SQLITE_OK;
   158835 }
   158836 
   158837 /*
   158838 ** xRowid - Return the current rowid for the cursor.
   158839 */
   158840 static int fts3tokRowidMethod(
   158841   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   158842   sqlite_int64 *pRowid            /* OUT: Rowid value */
   158843 ){
   158844   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
   158845   *pRowid = (sqlite3_int64)pCsr->iRowid;
   158846   return SQLITE_OK;
   158847 }
   158848 
   158849 /*
   158850 ** Register the fts3tok module with database connection db. Return SQLITE_OK
   158851 ** if successful or an error code if sqlite3_create_module() fails.
   158852 */
   158853 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
   158854   static const sqlite3_module fts3tok_module = {
   158855      0,                           /* iVersion      */
   158856      fts3tokConnectMethod,        /* xCreate       */
   158857      fts3tokConnectMethod,        /* xConnect      */
   158858      fts3tokBestIndexMethod,      /* xBestIndex    */
   158859      fts3tokDisconnectMethod,     /* xDisconnect   */
   158860      fts3tokDisconnectMethod,     /* xDestroy      */
   158861      fts3tokOpenMethod,           /* xOpen         */
   158862      fts3tokCloseMethod,          /* xClose        */
   158863      fts3tokFilterMethod,         /* xFilter       */
   158864      fts3tokNextMethod,           /* xNext         */
   158865      fts3tokEofMethod,            /* xEof          */
   158866      fts3tokColumnMethod,         /* xColumn       */
   158867      fts3tokRowidMethod,          /* xRowid        */
   158868      0,                           /* xUpdate       */
   158869      0,                           /* xBegin        */
   158870      0,                           /* xSync         */
   158871      0,                           /* xCommit       */
   158872      0,                           /* xRollback     */
   158873      0,                           /* xFindFunction */
   158874      0,                           /* xRename       */
   158875      0,                           /* xSavepoint    */
   158876      0,                           /* xRelease      */
   158877      0                            /* xRollbackTo   */
   158878   };
   158879   int rc;                         /* Return code */
   158880 
   158881   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
   158882   return rc;
   158883 }
   158884 
   158885 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   158886 
   158887 /************** End of fts3_tokenize_vtab.c **********************************/
   158888 /************** Begin file fts3_write.c **************************************/
   158889 /*
   158890 ** 2009 Oct 23
   158891 **
   158892 ** The author disclaims copyright to this source code.  In place of
   158893 ** a legal notice, here is a blessing:
   158894 **
   158895 **    May you do good and not evil.
   158896 **    May you find forgiveness for yourself and forgive others.
   158897 **    May you share freely, never taking more than you give.
   158898 **
   158899 ******************************************************************************
   158900 **
   158901 ** This file is part of the SQLite FTS3 extension module. Specifically,
   158902 ** this file contains code to insert, update and delete rows from FTS3
   158903 ** tables. It also contains code to merge FTS3 b-tree segments. Some
   158904 ** of the sub-routines used to merge segments are also used by the query
   158905 ** code in fts3.c.
   158906 */
   158907 
   158908 /* #include "fts3Int.h" */
   158909 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   158910 
   158911 /* #include <string.h> */
   158912 /* #include <assert.h> */
   158913 /* #include <stdlib.h> */
   158914 
   158915 
   158916 #define FTS_MAX_APPENDABLE_HEIGHT 16
   158917 
   158918 /*
   158919 ** When full-text index nodes are loaded from disk, the buffer that they
   158920 ** are loaded into has the following number of bytes of padding at the end
   158921 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
   158922 ** of 920 bytes is allocated for it.
   158923 **
   158924 ** This means that if we have a pointer into a buffer containing node data,
   158925 ** it is always safe to read up to two varints from it without risking an
   158926 ** overread, even if the node data is corrupted.
   158927 */
   158928 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
   158929 
   158930 /*
   158931 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
   158932 ** memory incrementally instead of all at once. This can be a big performance
   158933 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
   158934 ** method before retrieving all query results (as may happen, for example,
   158935 ** if a query has a LIMIT clause).
   158936 **
   158937 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
   158938 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
   158939 ** The code is written so that the hard lower-limit for each of these values
   158940 ** is 1. Clearly such small values would be inefficient, but can be useful
   158941 ** for testing purposes.
   158942 **
   158943 ** If this module is built with SQLITE_TEST defined, these constants may
   158944 ** be overridden at runtime for testing purposes. File fts3_test.c contains
   158945 ** a Tcl interface to read and write the values.
   158946 */
   158947 #ifdef SQLITE_TEST
   158948 int test_fts3_node_chunksize = (4*1024);
   158949 int test_fts3_node_chunk_threshold = (4*1024)*4;
   158950 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
   158951 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
   158952 #else
   158953 # define FTS3_NODE_CHUNKSIZE (4*1024)
   158954 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
   158955 #endif
   158956 
   158957 /*
   158958 ** The two values that may be meaningfully bound to the :1 parameter in
   158959 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
   158960 */
   158961 #define FTS_STAT_DOCTOTAL      0
   158962 #define FTS_STAT_INCRMERGEHINT 1
   158963 #define FTS_STAT_AUTOINCRMERGE 2
   158964 
   158965 /*
   158966 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
   158967 ** and incremental merge operation that takes place. This is used for
   158968 ** debugging FTS only, it should not usually be turned on in production
   158969 ** systems.
   158970 */
   158971 #ifdef FTS3_LOG_MERGES
   158972 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
   158973   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
   158974 }
   158975 #else
   158976 #define fts3LogMerge(x, y)
   158977 #endif
   158978 
   158979 
   158980 typedef struct PendingList PendingList;
   158981 typedef struct SegmentNode SegmentNode;
   158982 typedef struct SegmentWriter SegmentWriter;
   158983 
   158984 /*
   158985 ** An instance of the following data structure is used to build doclists
   158986 ** incrementally. See function fts3PendingListAppend() for details.
   158987 */
   158988 struct PendingList {
   158989   int nData;
   158990   char *aData;
   158991   int nSpace;
   158992   sqlite3_int64 iLastDocid;
   158993   sqlite3_int64 iLastCol;
   158994   sqlite3_int64 iLastPos;
   158995 };
   158996 
   158997 
   158998 /*
   158999 ** Each cursor has a (possibly empty) linked list of the following objects.
   159000 */
   159001 struct Fts3DeferredToken {
   159002   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
   159003   int iCol;                       /* Column token must occur in */
   159004   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
   159005   PendingList *pList;             /* Doclist is assembled here */
   159006 };
   159007 
   159008 /*
   159009 ** An instance of this structure is used to iterate through the terms on
   159010 ** a contiguous set of segment b-tree leaf nodes. Although the details of
   159011 ** this structure are only manipulated by code in this file, opaque handles
   159012 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
   159013 ** terms when querying the full-text index. See functions:
   159014 **
   159015 **   sqlite3Fts3SegReaderNew()
   159016 **   sqlite3Fts3SegReaderFree()
   159017 **   sqlite3Fts3SegReaderIterate()
   159018 **
   159019 ** Methods used to manipulate Fts3SegReader structures:
   159020 **
   159021 **   fts3SegReaderNext()
   159022 **   fts3SegReaderFirstDocid()
   159023 **   fts3SegReaderNextDocid()
   159024 */
   159025 struct Fts3SegReader {
   159026   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
   159027   u8 bLookup;                     /* True for a lookup only */
   159028   u8 rootOnly;                    /* True for a root-only reader */
   159029 
   159030   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
   159031   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
   159032   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
   159033   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
   159034 
   159035   char *aNode;                    /* Pointer to node data (or NULL) */
   159036   int nNode;                      /* Size of buffer at aNode (or 0) */
   159037   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
   159038   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
   159039 
   159040   Fts3HashElem **ppNextElem;
   159041 
   159042   /* Variables set by fts3SegReaderNext(). These may be read directly
   159043   ** by the caller. They are valid from the time SegmentReaderNew() returns
   159044   ** until SegmentReaderNext() returns something other than SQLITE_OK
   159045   ** (i.e. SQLITE_DONE).
   159046   */
   159047   int nTerm;                      /* Number of bytes in current term */
   159048   char *zTerm;                    /* Pointer to current term */
   159049   int nTermAlloc;                 /* Allocated size of zTerm buffer */
   159050   char *aDoclist;                 /* Pointer to doclist of current entry */
   159051   int nDoclist;                   /* Size of doclist in current entry */
   159052 
   159053   /* The following variables are used by fts3SegReaderNextDocid() to iterate
   159054   ** through the current doclist (aDoclist/nDoclist).
   159055   */
   159056   char *pOffsetList;
   159057   int nOffsetList;                /* For descending pending seg-readers only */
   159058   sqlite3_int64 iDocid;
   159059 };
   159060 
   159061 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
   159062 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
   159063 
   159064 /*
   159065 ** An instance of this structure is used to create a segment b-tree in the
   159066 ** database. The internal details of this type are only accessed by the
   159067 ** following functions:
   159068 **
   159069 **   fts3SegWriterAdd()
   159070 **   fts3SegWriterFlush()
   159071 **   fts3SegWriterFree()
   159072 */
   159073 struct SegmentWriter {
   159074   SegmentNode *pTree;             /* Pointer to interior tree structure */
   159075   sqlite3_int64 iFirst;           /* First slot in %_segments written */
   159076   sqlite3_int64 iFree;            /* Next free slot in %_segments */
   159077   char *zTerm;                    /* Pointer to previous term buffer */
   159078   int nTerm;                      /* Number of bytes in zTerm */
   159079   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   159080   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   159081   int nSize;                      /* Size of allocation at aData */
   159082   int nData;                      /* Bytes of data in aData */
   159083   char *aData;                    /* Pointer to block from malloc() */
   159084   i64 nLeafData;                  /* Number of bytes of leaf data written */
   159085 };
   159086 
   159087 /*
   159088 ** Type SegmentNode is used by the following three functions to create
   159089 ** the interior part of the segment b+-tree structures (everything except
   159090 ** the leaf nodes). These functions and type are only ever used by code
   159091 ** within the fts3SegWriterXXX() family of functions described above.
   159092 **
   159093 **   fts3NodeAddTerm()
   159094 **   fts3NodeWrite()
   159095 **   fts3NodeFree()
   159096 **
   159097 ** When a b+tree is written to the database (either as a result of a merge
   159098 ** or the pending-terms table being flushed), leaves are written into the
   159099 ** database file as soon as they are completely populated. The interior of
   159100 ** the tree is assembled in memory and written out only once all leaves have
   159101 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
   159102 ** very large, meaning that the interior of the tree consumes relatively
   159103 ** little memory.
   159104 */
   159105 struct SegmentNode {
   159106   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
   159107   SegmentNode *pRight;            /* Pointer to right-sibling */
   159108   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
   159109   int nEntry;                     /* Number of terms written to node so far */
   159110   char *zTerm;                    /* Pointer to previous term buffer */
   159111   int nTerm;                      /* Number of bytes in zTerm */
   159112   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   159113   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   159114   int nData;                      /* Bytes of valid data so far */
   159115   char *aData;                    /* Node data */
   159116 };
   159117 
   159118 /*
   159119 ** Valid values for the second argument to fts3SqlStmt().
   159120 */
   159121 #define SQL_DELETE_CONTENT             0
   159122 #define SQL_IS_EMPTY                   1
   159123 #define SQL_DELETE_ALL_CONTENT         2
   159124 #define SQL_DELETE_ALL_SEGMENTS        3
   159125 #define SQL_DELETE_ALL_SEGDIR          4
   159126 #define SQL_DELETE_ALL_DOCSIZE         5
   159127 #define SQL_DELETE_ALL_STAT            6
   159128 #define SQL_SELECT_CONTENT_BY_ROWID    7
   159129 #define SQL_NEXT_SEGMENT_INDEX         8
   159130 #define SQL_INSERT_SEGMENTS            9
   159131 #define SQL_NEXT_SEGMENTS_ID          10
   159132 #define SQL_INSERT_SEGDIR             11
   159133 #define SQL_SELECT_LEVEL              12
   159134 #define SQL_SELECT_LEVEL_RANGE        13
   159135 #define SQL_SELECT_LEVEL_COUNT        14
   159136 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
   159137 #define SQL_DELETE_SEGDIR_LEVEL       16
   159138 #define SQL_DELETE_SEGMENTS_RANGE     17
   159139 #define SQL_CONTENT_INSERT            18
   159140 #define SQL_DELETE_DOCSIZE            19
   159141 #define SQL_REPLACE_DOCSIZE           20
   159142 #define SQL_SELECT_DOCSIZE            21
   159143 #define SQL_SELECT_STAT               22
   159144 #define SQL_REPLACE_STAT              23
   159145 
   159146 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
   159147 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
   159148 #define SQL_DELETE_SEGDIR_RANGE       26
   159149 #define SQL_SELECT_ALL_LANGID         27
   159150 #define SQL_FIND_MERGE_LEVEL          28
   159151 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
   159152 #define SQL_DELETE_SEGDIR_ENTRY       30
   159153 #define SQL_SHIFT_SEGDIR_ENTRY        31
   159154 #define SQL_SELECT_SEGDIR             32
   159155 #define SQL_CHOMP_SEGDIR              33
   159156 #define SQL_SEGMENT_IS_APPENDABLE     34
   159157 #define SQL_SELECT_INDEXES            35
   159158 #define SQL_SELECT_MXLEVEL            36
   159159 
   159160 #define SQL_SELECT_LEVEL_RANGE2       37
   159161 #define SQL_UPDATE_LEVEL_IDX          38
   159162 #define SQL_UPDATE_LEVEL              39
   159163 
   159164 /*
   159165 ** This function is used to obtain an SQLite prepared statement handle
   159166 ** for the statement identified by the second argument. If successful,
   159167 ** *pp is set to the requested statement handle and SQLITE_OK returned.
   159168 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
   159169 **
   159170 ** If argument apVal is not NULL, then it must point to an array with
   159171 ** at least as many entries as the requested statement has bound
   159172 ** parameters. The values are bound to the statements parameters before
   159173 ** returning.
   159174 */
   159175 static int fts3SqlStmt(
   159176   Fts3Table *p,                   /* Virtual table handle */
   159177   int eStmt,                      /* One of the SQL_XXX constants above */
   159178   sqlite3_stmt **pp,              /* OUT: Statement handle */
   159179   sqlite3_value **apVal           /* Values to bind to statement */
   159180 ){
   159181   const char *azSql[] = {
   159182 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
   159183 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
   159184 /* 2  */  "DELETE FROM %Q.'%q_content'",
   159185 /* 3  */  "DELETE FROM %Q.'%q_segments'",
   159186 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
   159187 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
   159188 /* 6  */  "DELETE FROM %Q.'%q_stat'",
   159189 /* 7  */  "SELECT %s WHERE rowid=?",
   159190 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
   159191 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
   159192 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
   159193 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
   159194 
   159195           /* Return segments in order from oldest to newest.*/
   159196 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   159197             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
   159198 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   159199             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
   159200             "ORDER BY level DESC, idx ASC",
   159201 
   159202 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
   159203 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   159204 
   159205 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
   159206 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
   159207 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
   159208 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
   159209 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
   159210 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
   159211 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
   159212 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
   159213 /* 24 */  "",
   159214 /* 25 */  "",
   159215 
   159216 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   159217 /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
   159218 
   159219 /* This statement is used to determine which level to read the input from
   159220 ** when performing an incremental merge. It returns the absolute level number
   159221 ** of the oldest level in the db that contains at least ? segments. Or,
   159222 ** if no level in the FTS index contains more than ? segments, the statement
   159223 ** returns zero rows.  */
   159224 /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
   159225          "  GROUP BY level HAVING cnt>=?"
   159226          "  ORDER BY (level %% 1024) ASC LIMIT 1",
   159227 
   159228 /* Estimate the upper limit on the number of leaf nodes in a new segment
   159229 ** created by merging the oldest :2 segments from absolute level :1. See
   159230 ** function sqlite3Fts3Incrmerge() for details.  */
   159231 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
   159232          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
   159233 
   159234 /* SQL_DELETE_SEGDIR_ENTRY
   159235 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
   159236 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
   159237 
   159238 /* SQL_SHIFT_SEGDIR_ENTRY
   159239 **   Modify the idx value for the segment with idx=:3 on absolute level :2
   159240 **   to :1.  */
   159241 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
   159242 
   159243 /* SQL_SELECT_SEGDIR
   159244 **   Read a single entry from the %_segdir table. The entry from absolute
   159245 **   level :1 with index value :2.  */
   159246 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   159247             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
   159248 
   159249 /* SQL_CHOMP_SEGDIR
   159250 **   Update the start_block (:1) and root (:2) fields of the %_segdir
   159251 **   entry located on absolute level :3 with index :4.  */
   159252 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
   159253             "WHERE level = ? AND idx = ?",
   159254 
   159255 /* SQL_SEGMENT_IS_APPENDABLE
   159256 **   Return a single row if the segment with end_block=? is appendable. Or
   159257 **   no rows otherwise.  */
   159258 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
   159259 
   159260 /* SQL_SELECT_INDEXES
   159261 **   Return the list of valid segment indexes for absolute level ?  */
   159262 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
   159263 
   159264 /* SQL_SELECT_MXLEVEL
   159265 **   Return the largest relative level in the FTS index or indexes.  */
   159266 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
   159267 
   159268           /* Return segments in order from oldest to newest.*/
   159269 /* 37 */  "SELECT level, idx, end_block "
   159270             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
   159271             "ORDER BY level DESC, idx ASC",
   159272 
   159273           /* Update statements used while promoting segments */
   159274 /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
   159275             "WHERE level=? AND idx=?",
   159276 /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
   159277 
   159278   };
   159279   int rc = SQLITE_OK;
   159280   sqlite3_stmt *pStmt;
   159281 
   159282   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   159283   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
   159284 
   159285   pStmt = p->aStmt[eStmt];
   159286   if( !pStmt ){
   159287     char *zSql;
   159288     if( eStmt==SQL_CONTENT_INSERT ){
   159289       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
   159290     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
   159291       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
   159292     }else{
   159293       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
   159294     }
   159295     if( !zSql ){
   159296       rc = SQLITE_NOMEM;
   159297     }else{
   159298       rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
   159299                               &pStmt, NULL);
   159300       sqlite3_free(zSql);
   159301       assert( rc==SQLITE_OK || pStmt==0 );
   159302       p->aStmt[eStmt] = pStmt;
   159303     }
   159304   }
   159305   if( apVal ){
   159306     int i;
   159307     int nParam = sqlite3_bind_parameter_count(pStmt);
   159308     for(i=0; rc==SQLITE_OK && i<nParam; i++){
   159309       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
   159310     }
   159311   }
   159312   *pp = pStmt;
   159313   return rc;
   159314 }
   159315 
   159316 
   159317 static int fts3SelectDocsize(
   159318   Fts3Table *pTab,                /* FTS3 table handle */
   159319   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
   159320   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   159321 ){
   159322   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
   159323   int rc;                         /* Return code */
   159324 
   159325   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
   159326   if( rc==SQLITE_OK ){
   159327     sqlite3_bind_int64(pStmt, 1, iDocid);
   159328     rc = sqlite3_step(pStmt);
   159329     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
   159330       rc = sqlite3_reset(pStmt);
   159331       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   159332       pStmt = 0;
   159333     }else{
   159334       rc = SQLITE_OK;
   159335     }
   159336   }
   159337 
   159338   *ppStmt = pStmt;
   159339   return rc;
   159340 }
   159341 
   159342 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
   159343   Fts3Table *pTab,                /* Fts3 table handle */
   159344   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   159345 ){
   159346   sqlite3_stmt *pStmt = 0;
   159347   int rc;
   159348   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
   159349   if( rc==SQLITE_OK ){
   159350     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   159351     if( sqlite3_step(pStmt)!=SQLITE_ROW
   159352      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
   159353     ){
   159354       rc = sqlite3_reset(pStmt);
   159355       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   159356       pStmt = 0;
   159357     }
   159358   }
   159359   *ppStmt = pStmt;
   159360   return rc;
   159361 }
   159362 
   159363 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
   159364   Fts3Table *pTab,                /* Fts3 table handle */
   159365   sqlite3_int64 iDocid,           /* Docid to read size data for */
   159366   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   159367 ){
   159368   return fts3SelectDocsize(pTab, iDocid, ppStmt);
   159369 }
   159370 
   159371 /*
   159372 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
   159373 ** array apVal[] to the SQL statement identified by eStmt, the statement
   159374 ** is executed.
   159375 **
   159376 ** Returns SQLITE_OK if the statement is successfully executed, or an
   159377 ** SQLite error code otherwise.
   159378 */
   159379 static void fts3SqlExec(
   159380   int *pRC,                /* Result code */
   159381   Fts3Table *p,            /* The FTS3 table */
   159382   int eStmt,               /* Index of statement to evaluate */
   159383   sqlite3_value **apVal    /* Parameters to bind */
   159384 ){
   159385   sqlite3_stmt *pStmt;
   159386   int rc;
   159387   if( *pRC ) return;
   159388   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   159389   if( rc==SQLITE_OK ){
   159390     sqlite3_step(pStmt);
   159391     rc = sqlite3_reset(pStmt);
   159392   }
   159393   *pRC = rc;
   159394 }
   159395 
   159396 
   159397 /*
   159398 ** This function ensures that the caller has obtained an exclusive
   159399 ** shared-cache table-lock on the %_segdir table. This is required before
   159400 ** writing data to the fts3 table. If this lock is not acquired first, then
   159401 ** the caller may end up attempting to take this lock as part of committing
   159402 ** a transaction, causing SQLite to return SQLITE_LOCKED or
   159403 ** LOCKED_SHAREDCACHEto a COMMIT command.
   159404 **
   159405 ** It is best to avoid this because if FTS3 returns any error when
   159406 ** committing a transaction, the whole transaction will be rolled back.
   159407 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
   159408 ** It can still happen if the user locks the underlying tables directly
   159409 ** instead of accessing them via FTS.
   159410 */
   159411 static int fts3Writelock(Fts3Table *p){
   159412   int rc = SQLITE_OK;
   159413 
   159414   if( p->nPendingData==0 ){
   159415     sqlite3_stmt *pStmt;
   159416     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
   159417     if( rc==SQLITE_OK ){
   159418       sqlite3_bind_null(pStmt, 1);
   159419       sqlite3_step(pStmt);
   159420       rc = sqlite3_reset(pStmt);
   159421     }
   159422   }
   159423 
   159424   return rc;
   159425 }
   159426 
   159427 /*
   159428 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
   159429 ** Within each language id, a separate index is maintained to store the
   159430 ** document terms, and each configured prefix size (configured the FTS
   159431 ** "prefix=" option). And each index consists of multiple levels ("relative
   159432 ** levels").
   159433 **
   159434 ** All three of these values (the language id, the specific index and the
   159435 ** level within the index) are encoded in 64-bit integer values stored
   159436 ** in the %_segdir table on disk. This function is used to convert three
   159437 ** separate component values into the single 64-bit integer value that
   159438 ** can be used to query the %_segdir table.
   159439 **
   159440 ** Specifically, each language-id/index combination is allocated 1024
   159441 ** 64-bit integer level values ("absolute levels"). The main terms index
   159442 ** for language-id 0 is allocate values 0-1023. The first prefix index
   159443 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
   159444 ** Language 1 indexes are allocated immediately following language 0.
   159445 **
   159446 ** So, for a system with nPrefix prefix indexes configured, the block of
   159447 ** absolute levels that corresponds to language-id iLangid and index
   159448 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
   159449 */
   159450 static sqlite3_int64 getAbsoluteLevel(
   159451   Fts3Table *p,                   /* FTS3 table handle */
   159452   int iLangid,                    /* Language id */
   159453   int iIndex,                     /* Index in p->aIndex[] */
   159454   int iLevel                      /* Level of segments */
   159455 ){
   159456   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
   159457   assert( iLangid>=0 );
   159458   assert( p->nIndex>0 );
   159459   assert( iIndex>=0 && iIndex<p->nIndex );
   159460 
   159461   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
   159462   return iBase + iLevel;
   159463 }
   159464 
   159465 /*
   159466 ** Set *ppStmt to a statement handle that may be used to iterate through
   159467 ** all rows in the %_segdir table, from oldest to newest. If successful,
   159468 ** return SQLITE_OK. If an error occurs while preparing the statement,
   159469 ** return an SQLite error code.
   159470 **
   159471 ** There is only ever one instance of this SQL statement compiled for
   159472 ** each FTS3 table.
   159473 **
   159474 ** The statement returns the following columns from the %_segdir table:
   159475 **
   159476 **   0: idx
   159477 **   1: start_block
   159478 **   2: leaves_end_block
   159479 **   3: end_block
   159480 **   4: root
   159481 */
   159482 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
   159483   Fts3Table *p,                   /* FTS3 table */
   159484   int iLangid,                    /* Language being queried */
   159485   int iIndex,                     /* Index for p->aIndex[] */
   159486   int iLevel,                     /* Level to select (relative level) */
   159487   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
   159488 ){
   159489   int rc;
   159490   sqlite3_stmt *pStmt = 0;
   159491 
   159492   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
   159493   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   159494   assert( iIndex>=0 && iIndex<p->nIndex );
   159495 
   159496   if( iLevel<0 ){
   159497     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
   159498     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
   159499     if( rc==SQLITE_OK ){
   159500       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   159501       sqlite3_bind_int64(pStmt, 2,
   159502           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   159503       );
   159504     }
   159505   }else{
   159506     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
   159507     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   159508     if( rc==SQLITE_OK ){
   159509       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
   159510     }
   159511   }
   159512   *ppStmt = pStmt;
   159513   return rc;
   159514 }
   159515 
   159516 
   159517 /*
   159518 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
   159519 ** if successful, or an SQLite error code otherwise.
   159520 **
   159521 ** This function also serves to allocate the PendingList structure itself.
   159522 ** For example, to create a new PendingList structure containing two
   159523 ** varints:
   159524 **
   159525 **   PendingList *p = 0;
   159526 **   fts3PendingListAppendVarint(&p, 1);
   159527 **   fts3PendingListAppendVarint(&p, 2);
   159528 */
   159529 static int fts3PendingListAppendVarint(
   159530   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
   159531   sqlite3_int64 i                 /* Value to append to data */
   159532 ){
   159533   PendingList *p = *pp;
   159534 
   159535   /* Allocate or grow the PendingList as required. */
   159536   if( !p ){
   159537     p = sqlite3_malloc(sizeof(*p) + 100);
   159538     if( !p ){
   159539       return SQLITE_NOMEM;
   159540     }
   159541     p->nSpace = 100;
   159542     p->aData = (char *)&p[1];
   159543     p->nData = 0;
   159544   }
   159545   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
   159546     int nNew = p->nSpace * 2;
   159547     p = sqlite3_realloc(p, sizeof(*p) + nNew);
   159548     if( !p ){
   159549       sqlite3_free(*pp);
   159550       *pp = 0;
   159551       return SQLITE_NOMEM;
   159552     }
   159553     p->nSpace = nNew;
   159554     p->aData = (char *)&p[1];
   159555   }
   159556 
   159557   /* Append the new serialized varint to the end of the list. */
   159558   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
   159559   p->aData[p->nData] = '\0';
   159560   *pp = p;
   159561   return SQLITE_OK;
   159562 }
   159563 
   159564 /*
   159565 ** Add a docid/column/position entry to a PendingList structure. Non-zero
   159566 ** is returned if the structure is sqlite3_realloced as part of adding
   159567 ** the entry. Otherwise, zero.
   159568 **
   159569 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
   159570 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
   159571 ** it is set to SQLITE_OK.
   159572 */
   159573 static int fts3PendingListAppend(
   159574   PendingList **pp,               /* IN/OUT: PendingList structure */
   159575   sqlite3_int64 iDocid,           /* Docid for entry to add */
   159576   sqlite3_int64 iCol,             /* Column for entry to add */
   159577   sqlite3_int64 iPos,             /* Position of term for entry to add */
   159578   int *pRc                        /* OUT: Return code */
   159579 ){
   159580   PendingList *p = *pp;
   159581   int rc = SQLITE_OK;
   159582 
   159583   assert( !p || p->iLastDocid<=iDocid );
   159584 
   159585   if( !p || p->iLastDocid!=iDocid ){
   159586     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
   159587     if( p ){
   159588       assert( p->nData<p->nSpace );
   159589       assert( p->aData[p->nData]==0 );
   159590       p->nData++;
   159591     }
   159592     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
   159593       goto pendinglistappend_out;
   159594     }
   159595     p->iLastCol = -1;
   159596     p->iLastPos = 0;
   159597     p->iLastDocid = iDocid;
   159598   }
   159599   if( iCol>0 && p->iLastCol!=iCol ){
   159600     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
   159601      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
   159602     ){
   159603       goto pendinglistappend_out;
   159604     }
   159605     p->iLastCol = iCol;
   159606     p->iLastPos = 0;
   159607   }
   159608   if( iCol>=0 ){
   159609     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
   159610     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
   159611     if( rc==SQLITE_OK ){
   159612       p->iLastPos = iPos;
   159613     }
   159614   }
   159615 
   159616  pendinglistappend_out:
   159617   *pRc = rc;
   159618   if( p!=*pp ){
   159619     *pp = p;
   159620     return 1;
   159621   }
   159622   return 0;
   159623 }
   159624 
   159625 /*
   159626 ** Free a PendingList object allocated by fts3PendingListAppend().
   159627 */
   159628 static void fts3PendingListDelete(PendingList *pList){
   159629   sqlite3_free(pList);
   159630 }
   159631 
   159632 /*
   159633 ** Add an entry to one of the pending-terms hash tables.
   159634 */
   159635 static int fts3PendingTermsAddOne(
   159636   Fts3Table *p,
   159637   int iCol,
   159638   int iPos,
   159639   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
   159640   const char *zToken,
   159641   int nToken
   159642 ){
   159643   PendingList *pList;
   159644   int rc = SQLITE_OK;
   159645 
   159646   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
   159647   if( pList ){
   159648     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
   159649   }
   159650   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
   159651     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
   159652       /* Malloc failed while inserting the new entry. This can only
   159653       ** happen if there was no previous entry for this token.
   159654       */
   159655       assert( 0==fts3HashFind(pHash, zToken, nToken) );
   159656       sqlite3_free(pList);
   159657       rc = SQLITE_NOMEM;
   159658     }
   159659   }
   159660   if( rc==SQLITE_OK ){
   159661     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
   159662   }
   159663   return rc;
   159664 }
   159665 
   159666 /*
   159667 ** Tokenize the nul-terminated string zText and add all tokens to the
   159668 ** pending-terms hash-table. The docid used is that currently stored in
   159669 ** p->iPrevDocid, and the column is specified by argument iCol.
   159670 **
   159671 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   159672 */
   159673 static int fts3PendingTermsAdd(
   159674   Fts3Table *p,                   /* Table into which text will be inserted */
   159675   int iLangid,                    /* Language id to use */
   159676   const char *zText,              /* Text of document to be inserted */
   159677   int iCol,                       /* Column into which text is being inserted */
   159678   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
   159679 ){
   159680   int rc;
   159681   int iStart = 0;
   159682   int iEnd = 0;
   159683   int iPos = 0;
   159684   int nWord = 0;
   159685 
   159686   char const *zToken;
   159687   int nToken = 0;
   159688 
   159689   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
   159690   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   159691   sqlite3_tokenizer_cursor *pCsr;
   159692   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
   159693       const char**,int*,int*,int*,int*);
   159694 
   159695   assert( pTokenizer && pModule );
   159696 
   159697   /* If the user has inserted a NULL value, this function may be called with
   159698   ** zText==0. In this case, add zero token entries to the hash table and
   159699   ** return early. */
   159700   if( zText==0 ){
   159701     *pnWord = 0;
   159702     return SQLITE_OK;
   159703   }
   159704 
   159705   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
   159706   if( rc!=SQLITE_OK ){
   159707     return rc;
   159708   }
   159709 
   159710   xNext = pModule->xNext;
   159711   while( SQLITE_OK==rc
   159712       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
   159713   ){
   159714     int i;
   159715     if( iPos>=nWord ) nWord = iPos+1;
   159716 
   159717     /* Positions cannot be negative; we use -1 as a terminator internally.
   159718     ** Tokens must have a non-zero length.
   159719     */
   159720     if( iPos<0 || !zToken || nToken<=0 ){
   159721       rc = SQLITE_ERROR;
   159722       break;
   159723     }
   159724 
   159725     /* Add the term to the terms index */
   159726     rc = fts3PendingTermsAddOne(
   159727         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
   159728     );
   159729 
   159730     /* Add the term to each of the prefix indexes that it is not too
   159731     ** short for. */
   159732     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
   159733       struct Fts3Index *pIndex = &p->aIndex[i];
   159734       if( nToken<pIndex->nPrefix ) continue;
   159735       rc = fts3PendingTermsAddOne(
   159736           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
   159737       );
   159738     }
   159739   }
   159740 
   159741   pModule->xClose(pCsr);
   159742   *pnWord += nWord;
   159743   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   159744 }
   159745 
   159746 /*
   159747 ** Calling this function indicates that subsequent calls to
   159748 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
   159749 ** contents of the document with docid iDocid.
   159750 */
   159751 static int fts3PendingTermsDocid(
   159752   Fts3Table *p,                   /* Full-text table handle */
   159753   int bDelete,                    /* True if this op is a delete */
   159754   int iLangid,                    /* Language id of row being written */
   159755   sqlite_int64 iDocid             /* Docid of row being written */
   159756 ){
   159757   assert( iLangid>=0 );
   159758   assert( bDelete==1 || bDelete==0 );
   159759 
   159760   /* TODO(shess) Explore whether partially flushing the buffer on
   159761   ** forced-flush would provide better performance.  I suspect that if
   159762   ** we ordered the doclists by size and flushed the largest until the
   159763   ** buffer was half empty, that would let the less frequent terms
   159764   ** generate longer doclists.
   159765   */
   159766   if( iDocid<p->iPrevDocid
   159767    || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
   159768    || p->iPrevLangid!=iLangid
   159769    || p->nPendingData>p->nMaxPendingData
   159770   ){
   159771     int rc = sqlite3Fts3PendingTermsFlush(p);
   159772     if( rc!=SQLITE_OK ) return rc;
   159773   }
   159774   p->iPrevDocid = iDocid;
   159775   p->iPrevLangid = iLangid;
   159776   p->bPrevDelete = bDelete;
   159777   return SQLITE_OK;
   159778 }
   159779 
   159780 /*
   159781 ** Discard the contents of the pending-terms hash tables.
   159782 */
   159783 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   159784   int i;
   159785   for(i=0; i<p->nIndex; i++){
   159786     Fts3HashElem *pElem;
   159787     Fts3Hash *pHash = &p->aIndex[i].hPending;
   159788     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
   159789       PendingList *pList = (PendingList *)fts3HashData(pElem);
   159790       fts3PendingListDelete(pList);
   159791     }
   159792     fts3HashClear(pHash);
   159793   }
   159794   p->nPendingData = 0;
   159795 }
   159796 
   159797 /*
   159798 ** This function is called by the xUpdate() method as part of an INSERT
   159799 ** operation. It adds entries for each term in the new record to the
   159800 ** pendingTerms hash table.
   159801 **
   159802 ** Argument apVal is the same as the similarly named argument passed to
   159803 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
   159804 */
   159805 static int fts3InsertTerms(
   159806   Fts3Table *p,
   159807   int iLangid,
   159808   sqlite3_value **apVal,
   159809   u32 *aSz
   159810 ){
   159811   int i;                          /* Iterator variable */
   159812   for(i=2; i<p->nColumn+2; i++){
   159813     int iCol = i-2;
   159814     if( p->abNotindexed[iCol]==0 ){
   159815       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
   159816       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
   159817       if( rc!=SQLITE_OK ){
   159818         return rc;
   159819       }
   159820       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
   159821     }
   159822   }
   159823   return SQLITE_OK;
   159824 }
   159825 
   159826 /*
   159827 ** This function is called by the xUpdate() method for an INSERT operation.
   159828 ** The apVal parameter is passed a copy of the apVal argument passed by
   159829 ** SQLite to the xUpdate() method. i.e:
   159830 **
   159831 **   apVal[0]                Not used for INSERT.
   159832 **   apVal[1]                rowid
   159833 **   apVal[2]                Left-most user-defined column
   159834 **   ...
   159835 **   apVal[p->nColumn+1]     Right-most user-defined column
   159836 **   apVal[p->nColumn+2]     Hidden column with same name as table
   159837 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
   159838 **   apVal[p->nColumn+4]     Hidden languageid column
   159839 */
   159840 static int fts3InsertData(
   159841   Fts3Table *p,                   /* Full-text table */
   159842   sqlite3_value **apVal,          /* Array of values to insert */
   159843   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
   159844 ){
   159845   int rc;                         /* Return code */
   159846   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
   159847 
   159848   if( p->zContentTbl ){
   159849     sqlite3_value *pRowid = apVal[p->nColumn+3];
   159850     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
   159851       pRowid = apVal[1];
   159852     }
   159853     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
   159854       return SQLITE_CONSTRAINT;
   159855     }
   159856     *piDocid = sqlite3_value_int64(pRowid);
   159857     return SQLITE_OK;
   159858   }
   159859 
   159860   /* Locate the statement handle used to insert data into the %_content
   159861   ** table. The SQL for this statement is:
   159862   **
   159863   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
   159864   **
   159865   ** The statement features N '?' variables, where N is the number of user
   159866   ** defined columns in the FTS3 table, plus one for the docid field.
   159867   */
   159868   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   159869   if( rc==SQLITE_OK && p->zLanguageid ){
   159870     rc = sqlite3_bind_int(
   159871         pContentInsert, p->nColumn+2,
   159872         sqlite3_value_int(apVal[p->nColumn+4])
   159873     );
   159874   }
   159875   if( rc!=SQLITE_OK ) return rc;
   159876 
   159877   /* There is a quirk here. The users INSERT statement may have specified
   159878   ** a value for the "rowid" field, for the "docid" field, or for both.
   159879   ** Which is a problem, since "rowid" and "docid" are aliases for the
   159880   ** same value. For example:
   159881   **
   159882   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
   159883   **
   159884   ** In FTS3, this is an error. It is an error to specify non-NULL values
   159885   ** for both docid and some other rowid alias.
   159886   */
   159887   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
   159888     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
   159889      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
   159890     ){
   159891       /* A rowid/docid conflict. */
   159892       return SQLITE_ERROR;
   159893     }
   159894     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
   159895     if( rc!=SQLITE_OK ) return rc;
   159896   }
   159897 
   159898   /* Execute the statement to insert the record. Set *piDocid to the
   159899   ** new docid value.
   159900   */
   159901   sqlite3_step(pContentInsert);
   159902   rc = sqlite3_reset(pContentInsert);
   159903 
   159904   *piDocid = sqlite3_last_insert_rowid(p->db);
   159905   return rc;
   159906 }
   159907 
   159908 
   159909 
   159910 /*
   159911 ** Remove all data from the FTS3 table. Clear the hash table containing
   159912 ** pending terms.
   159913 */
   159914 static int fts3DeleteAll(Fts3Table *p, int bContent){
   159915   int rc = SQLITE_OK;             /* Return code */
   159916 
   159917   /* Discard the contents of the pending-terms hash table. */
   159918   sqlite3Fts3PendingTermsClear(p);
   159919 
   159920   /* Delete everything from the shadow tables. Except, leave %_content as
   159921   ** is if bContent is false.  */
   159922   assert( p->zContentTbl==0 || bContent==0 );
   159923   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
   159924   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
   159925   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
   159926   if( p->bHasDocsize ){
   159927     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
   159928   }
   159929   if( p->bHasStat ){
   159930     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
   159931   }
   159932   return rc;
   159933 }
   159934 
   159935 /*
   159936 **
   159937 */
   159938 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
   159939   int iLangid = 0;
   159940   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
   159941   return iLangid;
   159942 }
   159943 
   159944 /*
   159945 ** The first element in the apVal[] array is assumed to contain the docid
   159946 ** (an integer) of a row about to be deleted. Remove all terms from the
   159947 ** full-text index.
   159948 */
   159949 static void fts3DeleteTerms(
   159950   int *pRC,               /* Result code */
   159951   Fts3Table *p,           /* The FTS table to delete from */
   159952   sqlite3_value *pRowid,  /* The docid to be deleted */
   159953   u32 *aSz,               /* Sizes of deleted document written here */
   159954   int *pbFound            /* OUT: Set to true if row really does exist */
   159955 ){
   159956   int rc;
   159957   sqlite3_stmt *pSelect;
   159958 
   159959   assert( *pbFound==0 );
   159960   if( *pRC ) return;
   159961   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
   159962   if( rc==SQLITE_OK ){
   159963     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   159964       int i;
   159965       int iLangid = langidFromSelect(p, pSelect);
   159966       i64 iDocid = sqlite3_column_int64(pSelect, 0);
   159967       rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
   159968       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
   159969         int iCol = i-1;
   159970         if( p->abNotindexed[iCol]==0 ){
   159971           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
   159972           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
   159973           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
   159974         }
   159975       }
   159976       if( rc!=SQLITE_OK ){
   159977         sqlite3_reset(pSelect);
   159978         *pRC = rc;
   159979         return;
   159980       }
   159981       *pbFound = 1;
   159982     }
   159983     rc = sqlite3_reset(pSelect);
   159984   }else{
   159985     sqlite3_reset(pSelect);
   159986   }
   159987   *pRC = rc;
   159988 }
   159989 
   159990 /*
   159991 ** Forward declaration to account for the circular dependency between
   159992 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
   159993 */
   159994 static int fts3SegmentMerge(Fts3Table *, int, int, int);
   159995 
   159996 /*
   159997 ** This function allocates a new level iLevel index in the segdir table.
   159998 ** Usually, indexes are allocated within a level sequentially starting
   159999 ** with 0, so the allocated index is one greater than the value returned
   160000 ** by:
   160001 **
   160002 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
   160003 **
   160004 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
   160005 ** level, they are merged into a single level (iLevel+1) segment and the
   160006 ** allocated index is 0.
   160007 **
   160008 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
   160009 ** returned. Otherwise, an SQLite error code is returned.
   160010 */
   160011 static int fts3AllocateSegdirIdx(
   160012   Fts3Table *p,
   160013   int iLangid,                    /* Language id */
   160014   int iIndex,                     /* Index for p->aIndex */
   160015   int iLevel,
   160016   int *piIdx
   160017 ){
   160018   int rc;                         /* Return Code */
   160019   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
   160020   int iNext = 0;                  /* Result of query pNextIdx */
   160021 
   160022   assert( iLangid>=0 );
   160023   assert( p->nIndex>=1 );
   160024 
   160025   /* Set variable iNext to the next available segdir index at level iLevel. */
   160026   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
   160027   if( rc==SQLITE_OK ){
   160028     sqlite3_bind_int64(
   160029         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   160030     );
   160031     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
   160032       iNext = sqlite3_column_int(pNextIdx, 0);
   160033     }
   160034     rc = sqlite3_reset(pNextIdx);
   160035   }
   160036 
   160037   if( rc==SQLITE_OK ){
   160038     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
   160039     ** full, merge all segments in level iLevel into a single iLevel+1
   160040     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
   160041     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
   160042     */
   160043     if( iNext>=FTS3_MERGE_COUNT ){
   160044       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
   160045       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
   160046       *piIdx = 0;
   160047     }else{
   160048       *piIdx = iNext;
   160049     }
   160050   }
   160051 
   160052   return rc;
   160053 }
   160054 
   160055 /*
   160056 ** The %_segments table is declared as follows:
   160057 **
   160058 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
   160059 **
   160060 ** This function reads data from a single row of the %_segments table. The
   160061 ** specific row is identified by the iBlockid parameter. If paBlob is not
   160062 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
   160063 ** with the contents of the blob stored in the "block" column of the
   160064 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
   160065 ** to the size of the blob in bytes before returning.
   160066 **
   160067 ** If an error occurs, or the table does not contain the specified row,
   160068 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
   160069 ** paBlob is non-NULL, then it is the responsibility of the caller to
   160070 ** eventually free the returned buffer.
   160071 **
   160072 ** This function may leave an open sqlite3_blob* handle in the
   160073 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
   160074 ** to this function. The handle may be closed by calling the
   160075 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
   160076 ** performance improvement, but the blob handle should always be closed
   160077 ** before control is returned to the user (to prevent a lock being held
   160078 ** on the database file for longer than necessary). Thus, any virtual table
   160079 ** method (xFilter etc.) that may directly or indirectly call this function
   160080 ** must call sqlite3Fts3SegmentsClose() before returning.
   160081 */
   160082 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
   160083   Fts3Table *p,                   /* FTS3 table handle */
   160084   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
   160085   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
   160086   int *pnBlob,                    /* OUT: Size of blob data */
   160087   int *pnLoad                     /* OUT: Bytes actually loaded */
   160088 ){
   160089   int rc;                         /* Return code */
   160090 
   160091   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
   160092   assert( pnBlob );
   160093 
   160094   if( p->pSegments ){
   160095     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
   160096   }else{
   160097     if( 0==p->zSegmentsTbl ){
   160098       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
   160099       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
   160100     }
   160101     rc = sqlite3_blob_open(
   160102        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
   160103     );
   160104   }
   160105 
   160106   if( rc==SQLITE_OK ){
   160107     int nByte = sqlite3_blob_bytes(p->pSegments);
   160108     *pnBlob = nByte;
   160109     if( paBlob ){
   160110       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
   160111       if( !aByte ){
   160112         rc = SQLITE_NOMEM;
   160113       }else{
   160114         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
   160115           nByte = FTS3_NODE_CHUNKSIZE;
   160116           *pnLoad = nByte;
   160117         }
   160118         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
   160119         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
   160120         if( rc!=SQLITE_OK ){
   160121           sqlite3_free(aByte);
   160122           aByte = 0;
   160123         }
   160124       }
   160125       *paBlob = aByte;
   160126     }
   160127   }
   160128 
   160129   return rc;
   160130 }
   160131 
   160132 /*
   160133 ** Close the blob handle at p->pSegments, if it is open. See comments above
   160134 ** the sqlite3Fts3ReadBlock() function for details.
   160135 */
   160136 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
   160137   sqlite3_blob_close(p->pSegments);
   160138   p->pSegments = 0;
   160139 }
   160140 
   160141 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
   160142   int nRead;                      /* Number of bytes to read */
   160143   int rc;                         /* Return code */
   160144 
   160145   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
   160146   rc = sqlite3_blob_read(
   160147       pReader->pBlob,
   160148       &pReader->aNode[pReader->nPopulate],
   160149       nRead,
   160150       pReader->nPopulate
   160151   );
   160152 
   160153   if( rc==SQLITE_OK ){
   160154     pReader->nPopulate += nRead;
   160155     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
   160156     if( pReader->nPopulate==pReader->nNode ){
   160157       sqlite3_blob_close(pReader->pBlob);
   160158       pReader->pBlob = 0;
   160159       pReader->nPopulate = 0;
   160160     }
   160161   }
   160162   return rc;
   160163 }
   160164 
   160165 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
   160166   int rc = SQLITE_OK;
   160167   assert( !pReader->pBlob
   160168        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
   160169   );
   160170   while( pReader->pBlob && rc==SQLITE_OK
   160171      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
   160172   ){
   160173     rc = fts3SegReaderIncrRead(pReader);
   160174   }
   160175   return rc;
   160176 }
   160177 
   160178 /*
   160179 ** Set an Fts3SegReader cursor to point at EOF.
   160180 */
   160181 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
   160182   if( !fts3SegReaderIsRootOnly(pSeg) ){
   160183     sqlite3_free(pSeg->aNode);
   160184     sqlite3_blob_close(pSeg->pBlob);
   160185     pSeg->pBlob = 0;
   160186   }
   160187   pSeg->aNode = 0;
   160188 }
   160189 
   160190 /*
   160191 ** Move the iterator passed as the first argument to the next term in the
   160192 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
   160193 ** SQLITE_DONE. Otherwise, an SQLite error code.
   160194 */
   160195 static int fts3SegReaderNext(
   160196   Fts3Table *p,
   160197   Fts3SegReader *pReader,
   160198   int bIncr
   160199 ){
   160200   int rc;                         /* Return code of various sub-routines */
   160201   char *pNext;                    /* Cursor variable */
   160202   int nPrefix;                    /* Number of bytes in term prefix */
   160203   int nSuffix;                    /* Number of bytes in term suffix */
   160204 
   160205   if( !pReader->aDoclist ){
   160206     pNext = pReader->aNode;
   160207   }else{
   160208     pNext = &pReader->aDoclist[pReader->nDoclist];
   160209   }
   160210 
   160211   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
   160212 
   160213     if( fts3SegReaderIsPending(pReader) ){
   160214       Fts3HashElem *pElem = *(pReader->ppNextElem);
   160215       sqlite3_free(pReader->aNode);
   160216       pReader->aNode = 0;
   160217       if( pElem ){
   160218         char *aCopy;
   160219         PendingList *pList = (PendingList *)fts3HashData(pElem);
   160220         int nCopy = pList->nData+1;
   160221         pReader->zTerm = (char *)fts3HashKey(pElem);
   160222         pReader->nTerm = fts3HashKeysize(pElem);
   160223         aCopy = (char*)sqlite3_malloc(nCopy);
   160224         if( !aCopy ) return SQLITE_NOMEM;
   160225         memcpy(aCopy, pList->aData, nCopy);
   160226         pReader->nNode = pReader->nDoclist = nCopy;
   160227         pReader->aNode = pReader->aDoclist = aCopy;
   160228         pReader->ppNextElem++;
   160229         assert( pReader->aNode );
   160230       }
   160231       return SQLITE_OK;
   160232     }
   160233 
   160234     fts3SegReaderSetEof(pReader);
   160235 
   160236     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
   160237     ** blocks have already been traversed.  */
   160238     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
   160239     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
   160240       return SQLITE_OK;
   160241     }
   160242 
   160243     rc = sqlite3Fts3ReadBlock(
   160244         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
   160245         (bIncr ? &pReader->nPopulate : 0)
   160246     );
   160247     if( rc!=SQLITE_OK ) return rc;
   160248     assert( pReader->pBlob==0 );
   160249     if( bIncr && pReader->nPopulate<pReader->nNode ){
   160250       pReader->pBlob = p->pSegments;
   160251       p->pSegments = 0;
   160252     }
   160253     pNext = pReader->aNode;
   160254   }
   160255 
   160256   assert( !fts3SegReaderIsPending(pReader) );
   160257 
   160258   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
   160259   if( rc!=SQLITE_OK ) return rc;
   160260 
   160261   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
   160262   ** safe (no risk of overread) even if the node data is corrupted. */
   160263   pNext += fts3GetVarint32(pNext, &nPrefix);
   160264   pNext += fts3GetVarint32(pNext, &nSuffix);
   160265   if( nPrefix<0 || nSuffix<=0
   160266    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
   160267   ){
   160268     return FTS_CORRUPT_VTAB;
   160269   }
   160270 
   160271   if( nPrefix+nSuffix>pReader->nTermAlloc ){
   160272     int nNew = (nPrefix+nSuffix)*2;
   160273     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
   160274     if( !zNew ){
   160275       return SQLITE_NOMEM;
   160276     }
   160277     pReader->zTerm = zNew;
   160278     pReader->nTermAlloc = nNew;
   160279   }
   160280 
   160281   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
   160282   if( rc!=SQLITE_OK ) return rc;
   160283 
   160284   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
   160285   pReader->nTerm = nPrefix+nSuffix;
   160286   pNext += nSuffix;
   160287   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
   160288   pReader->aDoclist = pNext;
   160289   pReader->pOffsetList = 0;
   160290 
   160291   /* Check that the doclist does not appear to extend past the end of the
   160292   ** b-tree node. And that the final byte of the doclist is 0x00. If either
   160293   ** of these statements is untrue, then the data structure is corrupt.
   160294   */
   160295   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
   160296    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
   160297   ){
   160298     return FTS_CORRUPT_VTAB;
   160299   }
   160300   return SQLITE_OK;
   160301 }
   160302 
   160303 /*
   160304 ** Set the SegReader to point to the first docid in the doclist associated
   160305 ** with the current term.
   160306 */
   160307 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
   160308   int rc = SQLITE_OK;
   160309   assert( pReader->aDoclist );
   160310   assert( !pReader->pOffsetList );
   160311   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   160312     u8 bEof = 0;
   160313     pReader->iDocid = 0;
   160314     pReader->nOffsetList = 0;
   160315     sqlite3Fts3DoclistPrev(0,
   160316         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
   160317         &pReader->iDocid, &pReader->nOffsetList, &bEof
   160318     );
   160319   }else{
   160320     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
   160321     if( rc==SQLITE_OK ){
   160322       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
   160323       pReader->pOffsetList = &pReader->aDoclist[n];
   160324     }
   160325   }
   160326   return rc;
   160327 }
   160328 
   160329 /*
   160330 ** Advance the SegReader to point to the next docid in the doclist
   160331 ** associated with the current term.
   160332 **
   160333 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
   160334 ** *ppOffsetList is set to point to the first column-offset list
   160335 ** in the doclist entry (i.e. immediately past the docid varint).
   160336 ** *pnOffsetList is set to the length of the set of column-offset
   160337 ** lists, not including the nul-terminator byte. For example:
   160338 */
   160339 static int fts3SegReaderNextDocid(
   160340   Fts3Table *pTab,
   160341   Fts3SegReader *pReader,         /* Reader to advance to next docid */
   160342   char **ppOffsetList,            /* OUT: Pointer to current position-list */
   160343   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
   160344 ){
   160345   int rc = SQLITE_OK;
   160346   char *p = pReader->pOffsetList;
   160347   char c = 0;
   160348 
   160349   assert( p );
   160350 
   160351   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   160352     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
   160353     ** Pending-terms doclists are always built up in ascending order, so
   160354     ** we have to iterate through them backwards here. */
   160355     u8 bEof = 0;
   160356     if( ppOffsetList ){
   160357       *ppOffsetList = pReader->pOffsetList;
   160358       *pnOffsetList = pReader->nOffsetList - 1;
   160359     }
   160360     sqlite3Fts3DoclistPrev(0,
   160361         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
   160362         &pReader->nOffsetList, &bEof
   160363     );
   160364     if( bEof ){
   160365       pReader->pOffsetList = 0;
   160366     }else{
   160367       pReader->pOffsetList = p;
   160368     }
   160369   }else{
   160370     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
   160371 
   160372     /* Pointer p currently points at the first byte of an offset list. The
   160373     ** following block advances it to point one byte past the end of
   160374     ** the same offset list. */
   160375     while( 1 ){
   160376 
   160377       /* The following line of code (and the "p++" below the while() loop) is
   160378       ** normally all that is required to move pointer p to the desired
   160379       ** position. The exception is if this node is being loaded from disk
   160380       ** incrementally and pointer "p" now points to the first byte past
   160381       ** the populated part of pReader->aNode[].
   160382       */
   160383       while( *p | c ) c = *p++ & 0x80;
   160384       assert( *p==0 );
   160385 
   160386       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
   160387       rc = fts3SegReaderIncrRead(pReader);
   160388       if( rc!=SQLITE_OK ) return rc;
   160389     }
   160390     p++;
   160391 
   160392     /* If required, populate the output variables with a pointer to and the
   160393     ** size of the previous offset-list.
   160394     */
   160395     if( ppOffsetList ){
   160396       *ppOffsetList = pReader->pOffsetList;
   160397       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
   160398     }
   160399 
   160400     /* List may have been edited in place by fts3EvalNearTrim() */
   160401     while( p<pEnd && *p==0 ) p++;
   160402 
   160403     /* If there are no more entries in the doclist, set pOffsetList to
   160404     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
   160405     ** Fts3SegReader.pOffsetList to point to the next offset list before
   160406     ** returning.
   160407     */
   160408     if( p>=pEnd ){
   160409       pReader->pOffsetList = 0;
   160410     }else{
   160411       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
   160412       if( rc==SQLITE_OK ){
   160413         sqlite3_int64 iDelta;
   160414         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
   160415         if( pTab->bDescIdx ){
   160416           pReader->iDocid -= iDelta;
   160417         }else{
   160418           pReader->iDocid += iDelta;
   160419         }
   160420       }
   160421     }
   160422   }
   160423 
   160424   return SQLITE_OK;
   160425 }
   160426 
   160427 
   160428 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
   160429   Fts3Cursor *pCsr,
   160430   Fts3MultiSegReader *pMsr,
   160431   int *pnOvfl
   160432 ){
   160433   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   160434   int nOvfl = 0;
   160435   int ii;
   160436   int rc = SQLITE_OK;
   160437   int pgsz = p->nPgsz;
   160438 
   160439   assert( p->bFts4 );
   160440   assert( pgsz>0 );
   160441 
   160442   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
   160443     Fts3SegReader *pReader = pMsr->apSegment[ii];
   160444     if( !fts3SegReaderIsPending(pReader)
   160445      && !fts3SegReaderIsRootOnly(pReader)
   160446     ){
   160447       sqlite3_int64 jj;
   160448       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
   160449         int nBlob;
   160450         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
   160451         if( rc!=SQLITE_OK ) break;
   160452         if( (nBlob+35)>pgsz ){
   160453           nOvfl += (nBlob + 34)/pgsz;
   160454         }
   160455       }
   160456     }
   160457   }
   160458   *pnOvfl = nOvfl;
   160459   return rc;
   160460 }
   160461 
   160462 /*
   160463 ** Free all allocations associated with the iterator passed as the
   160464 ** second argument.
   160465 */
   160466 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
   160467   if( pReader ){
   160468     if( !fts3SegReaderIsPending(pReader) ){
   160469       sqlite3_free(pReader->zTerm);
   160470     }
   160471     if( !fts3SegReaderIsRootOnly(pReader) ){
   160472       sqlite3_free(pReader->aNode);
   160473     }
   160474     sqlite3_blob_close(pReader->pBlob);
   160475   }
   160476   sqlite3_free(pReader);
   160477 }
   160478 
   160479 /*
   160480 ** Allocate a new SegReader object.
   160481 */
   160482 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
   160483   int iAge,                       /* Segment "age". */
   160484   int bLookup,                    /* True for a lookup only */
   160485   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
   160486   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
   160487   sqlite3_int64 iEndBlock,        /* Final block of segment */
   160488   const char *zRoot,              /* Buffer containing root node */
   160489   int nRoot,                      /* Size of buffer containing root node */
   160490   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   160491 ){
   160492   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
   160493   int nExtra = 0;                 /* Bytes to allocate segment root node */
   160494 
   160495   assert( iStartLeaf<=iEndLeaf );
   160496   if( iStartLeaf==0 ){
   160497     nExtra = nRoot + FTS3_NODE_PADDING;
   160498   }
   160499 
   160500   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
   160501   if( !pReader ){
   160502     return SQLITE_NOMEM;
   160503   }
   160504   memset(pReader, 0, sizeof(Fts3SegReader));
   160505   pReader->iIdx = iAge;
   160506   pReader->bLookup = bLookup!=0;
   160507   pReader->iStartBlock = iStartLeaf;
   160508   pReader->iLeafEndBlock = iEndLeaf;
   160509   pReader->iEndBlock = iEndBlock;
   160510 
   160511   if( nExtra ){
   160512     /* The entire segment is stored in the root node. */
   160513     pReader->aNode = (char *)&pReader[1];
   160514     pReader->rootOnly = 1;
   160515     pReader->nNode = nRoot;
   160516     memcpy(pReader->aNode, zRoot, nRoot);
   160517     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
   160518   }else{
   160519     pReader->iCurrentBlock = iStartLeaf-1;
   160520   }
   160521   *ppReader = pReader;
   160522   return SQLITE_OK;
   160523 }
   160524 
   160525 /*
   160526 ** This is a comparison function used as a qsort() callback when sorting
   160527 ** an array of pending terms by term. This occurs as part of flushing
   160528 ** the contents of the pending-terms hash table to the database.
   160529 */
   160530 static int SQLITE_CDECL fts3CompareElemByTerm(
   160531   const void *lhs,
   160532   const void *rhs
   160533 ){
   160534   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
   160535   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
   160536   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
   160537   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
   160538 
   160539   int n = (n1<n2 ? n1 : n2);
   160540   int c = memcmp(z1, z2, n);
   160541   if( c==0 ){
   160542     c = n1 - n2;
   160543   }
   160544   return c;
   160545 }
   160546 
   160547 /*
   160548 ** This function is used to allocate an Fts3SegReader that iterates through
   160549 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
   160550 **
   160551 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
   160552 ** through each term in the pending-terms table. Or, if isPrefixIter is
   160553 ** non-zero, it iterates through each term and its prefixes. For example, if
   160554 ** the pending terms hash table contains the terms "sqlite", "mysql" and
   160555 ** "firebird", then the iterator visits the following 'terms' (in the order
   160556 ** shown):
   160557 **
   160558 **   f fi fir fire fireb firebi firebir firebird
   160559 **   m my mys mysq mysql
   160560 **   s sq sql sqli sqlit sqlite
   160561 **
   160562 ** Whereas if isPrefixIter is zero, the terms visited are:
   160563 **
   160564 **   firebird mysql sqlite
   160565 */
   160566 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   160567   Fts3Table *p,                   /* Virtual table handle */
   160568   int iIndex,                     /* Index for p->aIndex */
   160569   const char *zTerm,              /* Term to search for */
   160570   int nTerm,                      /* Size of buffer zTerm */
   160571   int bPrefix,                    /* True for a prefix iterator */
   160572   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
   160573 ){
   160574   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
   160575   Fts3HashElem *pE;               /* Iterator variable */
   160576   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
   160577   int nElem = 0;                  /* Size of array at aElem */
   160578   int rc = SQLITE_OK;             /* Return Code */
   160579   Fts3Hash *pHash;
   160580 
   160581   pHash = &p->aIndex[iIndex].hPending;
   160582   if( bPrefix ){
   160583     int nAlloc = 0;               /* Size of allocated array at aElem */
   160584 
   160585     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
   160586       char *zKey = (char *)fts3HashKey(pE);
   160587       int nKey = fts3HashKeysize(pE);
   160588       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
   160589         if( nElem==nAlloc ){
   160590           Fts3HashElem **aElem2;
   160591           nAlloc += 16;
   160592           aElem2 = (Fts3HashElem **)sqlite3_realloc(
   160593               aElem, nAlloc*sizeof(Fts3HashElem *)
   160594           );
   160595           if( !aElem2 ){
   160596             rc = SQLITE_NOMEM;
   160597             nElem = 0;
   160598             break;
   160599           }
   160600           aElem = aElem2;
   160601         }
   160602 
   160603         aElem[nElem++] = pE;
   160604       }
   160605     }
   160606 
   160607     /* If more than one term matches the prefix, sort the Fts3HashElem
   160608     ** objects in term order using qsort(). This uses the same comparison
   160609     ** callback as is used when flushing terms to disk.
   160610     */
   160611     if( nElem>1 ){
   160612       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
   160613     }
   160614 
   160615   }else{
   160616     /* The query is a simple term lookup that matches at most one term in
   160617     ** the index. All that is required is a straight hash-lookup.
   160618     **
   160619     ** Because the stack address of pE may be accessed via the aElem pointer
   160620     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
   160621     ** within this entire function, not just this "else{...}" block.
   160622     */
   160623     pE = fts3HashFindElem(pHash, zTerm, nTerm);
   160624     if( pE ){
   160625       aElem = &pE;
   160626       nElem = 1;
   160627     }
   160628   }
   160629 
   160630   if( nElem>0 ){
   160631     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
   160632     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
   160633     if( !pReader ){
   160634       rc = SQLITE_NOMEM;
   160635     }else{
   160636       memset(pReader, 0, nByte);
   160637       pReader->iIdx = 0x7FFFFFFF;
   160638       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
   160639       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
   160640     }
   160641   }
   160642 
   160643   if( bPrefix ){
   160644     sqlite3_free(aElem);
   160645   }
   160646   *ppReader = pReader;
   160647   return rc;
   160648 }
   160649 
   160650 /*
   160651 ** Compare the entries pointed to by two Fts3SegReader structures.
   160652 ** Comparison is as follows:
   160653 **
   160654 **   1) EOF is greater than not EOF.
   160655 **
   160656 **   2) The current terms (if any) are compared using memcmp(). If one
   160657 **      term is a prefix of another, the longer term is considered the
   160658 **      larger.
   160659 **
   160660 **   3) By segment age. An older segment is considered larger.
   160661 */
   160662 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   160663   int rc;
   160664   if( pLhs->aNode && pRhs->aNode ){
   160665     int rc2 = pLhs->nTerm - pRhs->nTerm;
   160666     if( rc2<0 ){
   160667       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
   160668     }else{
   160669       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
   160670     }
   160671     if( rc==0 ){
   160672       rc = rc2;
   160673     }
   160674   }else{
   160675     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
   160676   }
   160677   if( rc==0 ){
   160678     rc = pRhs->iIdx - pLhs->iIdx;
   160679   }
   160680   assert( rc!=0 );
   160681   return rc;
   160682 }
   160683 
   160684 /*
   160685 ** A different comparison function for SegReader structures. In this
   160686 ** version, it is assumed that each SegReader points to an entry in
   160687 ** a doclist for identical terms. Comparison is made as follows:
   160688 **
   160689 **   1) EOF (end of doclist in this case) is greater than not EOF.
   160690 **
   160691 **   2) By current docid.
   160692 **
   160693 **   3) By segment age. An older segment is considered larger.
   160694 */
   160695 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   160696   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   160697   if( rc==0 ){
   160698     if( pLhs->iDocid==pRhs->iDocid ){
   160699       rc = pRhs->iIdx - pLhs->iIdx;
   160700     }else{
   160701       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
   160702     }
   160703   }
   160704   assert( pLhs->aNode && pRhs->aNode );
   160705   return rc;
   160706 }
   160707 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   160708   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   160709   if( rc==0 ){
   160710     if( pLhs->iDocid==pRhs->iDocid ){
   160711       rc = pRhs->iIdx - pLhs->iIdx;
   160712     }else{
   160713       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
   160714     }
   160715   }
   160716   assert( pLhs->aNode && pRhs->aNode );
   160717   return rc;
   160718 }
   160719 
   160720 /*
   160721 ** Compare the term that the Fts3SegReader object passed as the first argument
   160722 ** points to with the term specified by arguments zTerm and nTerm.
   160723 **
   160724 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
   160725 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
   160726 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
   160727 */
   160728 static int fts3SegReaderTermCmp(
   160729   Fts3SegReader *pSeg,            /* Segment reader object */
   160730   const char *zTerm,              /* Term to compare to */
   160731   int nTerm                       /* Size of term zTerm in bytes */
   160732 ){
   160733   int res = 0;
   160734   if( pSeg->aNode ){
   160735     if( pSeg->nTerm>nTerm ){
   160736       res = memcmp(pSeg->zTerm, zTerm, nTerm);
   160737     }else{
   160738       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
   160739     }
   160740     if( res==0 ){
   160741       res = pSeg->nTerm-nTerm;
   160742     }
   160743   }
   160744   return res;
   160745 }
   160746 
   160747 /*
   160748 ** Argument apSegment is an array of nSegment elements. It is known that
   160749 ** the final (nSegment-nSuspect) members are already in sorted order
   160750 ** (according to the comparison function provided). This function shuffles
   160751 ** the array around until all entries are in sorted order.
   160752 */
   160753 static void fts3SegReaderSort(
   160754   Fts3SegReader **apSegment,                     /* Array to sort entries of */
   160755   int nSegment,                                  /* Size of apSegment array */
   160756   int nSuspect,                                  /* Unsorted entry count */
   160757   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
   160758 ){
   160759   int i;                          /* Iterator variable */
   160760 
   160761   assert( nSuspect<=nSegment );
   160762 
   160763   if( nSuspect==nSegment ) nSuspect--;
   160764   for(i=nSuspect-1; i>=0; i--){
   160765     int j;
   160766     for(j=i; j<(nSegment-1); j++){
   160767       Fts3SegReader *pTmp;
   160768       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
   160769       pTmp = apSegment[j+1];
   160770       apSegment[j+1] = apSegment[j];
   160771       apSegment[j] = pTmp;
   160772     }
   160773   }
   160774 
   160775 #ifndef NDEBUG
   160776   /* Check that the list really is sorted now. */
   160777   for(i=0; i<(nSuspect-1); i++){
   160778     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
   160779   }
   160780 #endif
   160781 }
   160782 
   160783 /*
   160784 ** Insert a record into the %_segments table.
   160785 */
   160786 static int fts3WriteSegment(
   160787   Fts3Table *p,                   /* Virtual table handle */
   160788   sqlite3_int64 iBlock,           /* Block id for new block */
   160789   char *z,                        /* Pointer to buffer containing block data */
   160790   int n                           /* Size of buffer z in bytes */
   160791 ){
   160792   sqlite3_stmt *pStmt;
   160793   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
   160794   if( rc==SQLITE_OK ){
   160795     sqlite3_bind_int64(pStmt, 1, iBlock);
   160796     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
   160797     sqlite3_step(pStmt);
   160798     rc = sqlite3_reset(pStmt);
   160799   }
   160800   return rc;
   160801 }
   160802 
   160803 /*
   160804 ** Find the largest relative level number in the table. If successful, set
   160805 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
   160806 ** set *pnMax to zero and return an SQLite error code.
   160807 */
   160808 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
   160809   int rc;
   160810   int mxLevel = 0;
   160811   sqlite3_stmt *pStmt = 0;
   160812 
   160813   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
   160814   if( rc==SQLITE_OK ){
   160815     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   160816       mxLevel = sqlite3_column_int(pStmt, 0);
   160817     }
   160818     rc = sqlite3_reset(pStmt);
   160819   }
   160820   *pnMax = mxLevel;
   160821   return rc;
   160822 }
   160823 
   160824 /*
   160825 ** Insert a record into the %_segdir table.
   160826 */
   160827 static int fts3WriteSegdir(
   160828   Fts3Table *p,                   /* Virtual table handle */
   160829   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
   160830   int iIdx,                       /* Value for "idx" field */
   160831   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
   160832   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
   160833   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
   160834   sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
   160835   char *zRoot,                    /* Blob value for "root" field */
   160836   int nRoot                       /* Number of bytes in buffer zRoot */
   160837 ){
   160838   sqlite3_stmt *pStmt;
   160839   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
   160840   if( rc==SQLITE_OK ){
   160841     sqlite3_bind_int64(pStmt, 1, iLevel);
   160842     sqlite3_bind_int(pStmt, 2, iIdx);
   160843     sqlite3_bind_int64(pStmt, 3, iStartBlock);
   160844     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
   160845     if( nLeafData==0 ){
   160846       sqlite3_bind_int64(pStmt, 5, iEndBlock);
   160847     }else{
   160848       char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
   160849       if( !zEnd ) return SQLITE_NOMEM;
   160850       sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
   160851     }
   160852     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
   160853     sqlite3_step(pStmt);
   160854     rc = sqlite3_reset(pStmt);
   160855   }
   160856   return rc;
   160857 }
   160858 
   160859 /*
   160860 ** Return the size of the common prefix (if any) shared by zPrev and
   160861 ** zNext, in bytes. For example,
   160862 **
   160863 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
   160864 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
   160865 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
   160866 */
   160867 static int fts3PrefixCompress(
   160868   const char *zPrev,              /* Buffer containing previous term */
   160869   int nPrev,                      /* Size of buffer zPrev in bytes */
   160870   const char *zNext,              /* Buffer containing next term */
   160871   int nNext                       /* Size of buffer zNext in bytes */
   160872 ){
   160873   int n;
   160874   UNUSED_PARAMETER(nNext);
   160875   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
   160876   return n;
   160877 }
   160878 
   160879 /*
   160880 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
   160881 ** (according to memcmp) than the previous term.
   160882 */
   160883 static int fts3NodeAddTerm(
   160884   Fts3Table *p,                   /* Virtual table handle */
   160885   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   160886   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   160887   const char *zTerm,              /* Pointer to buffer containing term */
   160888   int nTerm                       /* Size of term in bytes */
   160889 ){
   160890   SegmentNode *pTree = *ppTree;
   160891   int rc;
   160892   SegmentNode *pNew;
   160893 
   160894   /* First try to append the term to the current node. Return early if
   160895   ** this is possible.
   160896   */
   160897   if( pTree ){
   160898     int nData = pTree->nData;     /* Current size of node in bytes */
   160899     int nReq = nData;             /* Required space after adding zTerm */
   160900     int nPrefix;                  /* Number of bytes of prefix compression */
   160901     int nSuffix;                  /* Suffix length */
   160902 
   160903     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
   160904     nSuffix = nTerm-nPrefix;
   160905 
   160906     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
   160907     if( nReq<=p->nNodeSize || !pTree->zTerm ){
   160908 
   160909       if( nReq>p->nNodeSize ){
   160910         /* An unusual case: this is the first term to be added to the node
   160911         ** and the static node buffer (p->nNodeSize bytes) is not large
   160912         ** enough. Use a separately malloced buffer instead This wastes
   160913         ** p->nNodeSize bytes, but since this scenario only comes about when
   160914         ** the database contain two terms that share a prefix of almost 2KB,
   160915         ** this is not expected to be a serious problem.
   160916         */
   160917         assert( pTree->aData==(char *)&pTree[1] );
   160918         pTree->aData = (char *)sqlite3_malloc(nReq);
   160919         if( !pTree->aData ){
   160920           return SQLITE_NOMEM;
   160921         }
   160922       }
   160923 
   160924       if( pTree->zTerm ){
   160925         /* There is no prefix-length field for first term in a node */
   160926         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
   160927       }
   160928 
   160929       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
   160930       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
   160931       pTree->nData = nData + nSuffix;
   160932       pTree->nEntry++;
   160933 
   160934       if( isCopyTerm ){
   160935         if( pTree->nMalloc<nTerm ){
   160936           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
   160937           if( !zNew ){
   160938             return SQLITE_NOMEM;
   160939           }
   160940           pTree->nMalloc = nTerm*2;
   160941           pTree->zMalloc = zNew;
   160942         }
   160943         pTree->zTerm = pTree->zMalloc;
   160944         memcpy(pTree->zTerm, zTerm, nTerm);
   160945         pTree->nTerm = nTerm;
   160946       }else{
   160947         pTree->zTerm = (char *)zTerm;
   160948         pTree->nTerm = nTerm;
   160949       }
   160950       return SQLITE_OK;
   160951     }
   160952   }
   160953 
   160954   /* If control flows to here, it was not possible to append zTerm to the
   160955   ** current node. Create a new node (a right-sibling of the current node).
   160956   ** If this is the first node in the tree, the term is added to it.
   160957   **
   160958   ** Otherwise, the term is not added to the new node, it is left empty for
   160959   ** now. Instead, the term is inserted into the parent of pTree. If pTree
   160960   ** has no parent, one is created here.
   160961   */
   160962   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
   160963   if( !pNew ){
   160964     return SQLITE_NOMEM;
   160965   }
   160966   memset(pNew, 0, sizeof(SegmentNode));
   160967   pNew->nData = 1 + FTS3_VARINT_MAX;
   160968   pNew->aData = (char *)&pNew[1];
   160969 
   160970   if( pTree ){
   160971     SegmentNode *pParent = pTree->pParent;
   160972     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
   160973     if( pTree->pParent==0 ){
   160974       pTree->pParent = pParent;
   160975     }
   160976     pTree->pRight = pNew;
   160977     pNew->pLeftmost = pTree->pLeftmost;
   160978     pNew->pParent = pParent;
   160979     pNew->zMalloc = pTree->zMalloc;
   160980     pNew->nMalloc = pTree->nMalloc;
   160981     pTree->zMalloc = 0;
   160982   }else{
   160983     pNew->pLeftmost = pNew;
   160984     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   160985   }
   160986 
   160987   *ppTree = pNew;
   160988   return rc;
   160989 }
   160990 
   160991 /*
   160992 ** Helper function for fts3NodeWrite().
   160993 */
   160994 static int fts3TreeFinishNode(
   160995   SegmentNode *pTree,
   160996   int iHeight,
   160997   sqlite3_int64 iLeftChild
   160998 ){
   160999   int nStart;
   161000   assert( iHeight>=1 && iHeight<128 );
   161001   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
   161002   pTree->aData[nStart] = (char)iHeight;
   161003   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
   161004   return nStart;
   161005 }
   161006 
   161007 /*
   161008 ** Write the buffer for the segment node pTree and all of its peers to the
   161009 ** database. Then call this function recursively to write the parent of
   161010 ** pTree and its peers to the database.
   161011 **
   161012 ** Except, if pTree is a root node, do not write it to the database. Instead,
   161013 ** set output variables *paRoot and *pnRoot to contain the root node.
   161014 **
   161015 ** If successful, SQLITE_OK is returned and output variable *piLast is
   161016 ** set to the largest blockid written to the database (or zero if no
   161017 ** blocks were written to the db). Otherwise, an SQLite error code is
   161018 ** returned.
   161019 */
   161020 static int fts3NodeWrite(
   161021   Fts3Table *p,                   /* Virtual table handle */
   161022   SegmentNode *pTree,             /* SegmentNode handle */
   161023   int iHeight,                    /* Height of this node in tree */
   161024   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
   161025   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
   161026   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
   161027   char **paRoot,                  /* OUT: Data for root node */
   161028   int *pnRoot                     /* OUT: Size of root node in bytes */
   161029 ){
   161030   int rc = SQLITE_OK;
   161031 
   161032   if( !pTree->pParent ){
   161033     /* Root node of the tree. */
   161034     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
   161035     *piLast = iFree-1;
   161036     *pnRoot = pTree->nData - nStart;
   161037     *paRoot = &pTree->aData[nStart];
   161038   }else{
   161039     SegmentNode *pIter;
   161040     sqlite3_int64 iNextFree = iFree;
   161041     sqlite3_int64 iNextLeaf = iLeaf;
   161042     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
   161043       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
   161044       int nWrite = pIter->nData - nStart;
   161045 
   161046       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
   161047       iNextFree++;
   161048       iNextLeaf += (pIter->nEntry+1);
   161049     }
   161050     if( rc==SQLITE_OK ){
   161051       assert( iNextLeaf==iFree );
   161052       rc = fts3NodeWrite(
   161053           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
   161054       );
   161055     }
   161056   }
   161057 
   161058   return rc;
   161059 }
   161060 
   161061 /*
   161062 ** Free all memory allocations associated with the tree pTree.
   161063 */
   161064 static void fts3NodeFree(SegmentNode *pTree){
   161065   if( pTree ){
   161066     SegmentNode *p = pTree->pLeftmost;
   161067     fts3NodeFree(p->pParent);
   161068     while( p ){
   161069       SegmentNode *pRight = p->pRight;
   161070       if( p->aData!=(char *)&p[1] ){
   161071         sqlite3_free(p->aData);
   161072       }
   161073       assert( pRight==0 || p->zMalloc==0 );
   161074       sqlite3_free(p->zMalloc);
   161075       sqlite3_free(p);
   161076       p = pRight;
   161077     }
   161078   }
   161079 }
   161080 
   161081 /*
   161082 ** Add a term to the segment being constructed by the SegmentWriter object
   161083 ** *ppWriter. When adding the first term to a segment, *ppWriter should
   161084 ** be passed NULL. This function will allocate a new SegmentWriter object
   161085 ** and return it via the input/output variable *ppWriter in this case.
   161086 **
   161087 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   161088 */
   161089 static int fts3SegWriterAdd(
   161090   Fts3Table *p,                   /* Virtual table handle */
   161091   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   161092   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   161093   const char *zTerm,              /* Pointer to buffer containing term */
   161094   int nTerm,                      /* Size of term in bytes */
   161095   const char *aDoclist,           /* Pointer to buffer containing doclist */
   161096   int nDoclist                    /* Size of doclist in bytes */
   161097 ){
   161098   int nPrefix;                    /* Size of term prefix in bytes */
   161099   int nSuffix;                    /* Size of term suffix in bytes */
   161100   int nReq;                       /* Number of bytes required on leaf page */
   161101   int nData;
   161102   SegmentWriter *pWriter = *ppWriter;
   161103 
   161104   if( !pWriter ){
   161105     int rc;
   161106     sqlite3_stmt *pStmt;
   161107 
   161108     /* Allocate the SegmentWriter structure */
   161109     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
   161110     if( !pWriter ) return SQLITE_NOMEM;
   161111     memset(pWriter, 0, sizeof(SegmentWriter));
   161112     *ppWriter = pWriter;
   161113 
   161114     /* Allocate a buffer in which to accumulate data */
   161115     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
   161116     if( !pWriter->aData ) return SQLITE_NOMEM;
   161117     pWriter->nSize = p->nNodeSize;
   161118 
   161119     /* Find the next free blockid in the %_segments table */
   161120     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
   161121     if( rc!=SQLITE_OK ) return rc;
   161122     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   161123       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
   161124       pWriter->iFirst = pWriter->iFree;
   161125     }
   161126     rc = sqlite3_reset(pStmt);
   161127     if( rc!=SQLITE_OK ) return rc;
   161128   }
   161129   nData = pWriter->nData;
   161130 
   161131   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   161132   nSuffix = nTerm-nPrefix;
   161133 
   161134   /* Figure out how many bytes are required by this new entry */
   161135   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
   161136     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
   161137     nSuffix +                               /* Term suffix */
   161138     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
   161139     nDoclist;                               /* Doclist data */
   161140 
   161141   if( nData>0 && nData+nReq>p->nNodeSize ){
   161142     int rc;
   161143 
   161144     /* The current leaf node is full. Write it out to the database. */
   161145     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
   161146     if( rc!=SQLITE_OK ) return rc;
   161147     p->nLeafAdd++;
   161148 
   161149     /* Add the current term to the interior node tree. The term added to
   161150     ** the interior tree must:
   161151     **
   161152     **   a) be greater than the largest term on the leaf node just written
   161153     **      to the database (still available in pWriter->zTerm), and
   161154     **
   161155     **   b) be less than or equal to the term about to be added to the new
   161156     **      leaf node (zTerm/nTerm).
   161157     **
   161158     ** In other words, it must be the prefix of zTerm 1 byte longer than
   161159     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   161160     */
   161161     assert( nPrefix<nTerm );
   161162     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
   161163     if( rc!=SQLITE_OK ) return rc;
   161164 
   161165     nData = 0;
   161166     pWriter->nTerm = 0;
   161167 
   161168     nPrefix = 0;
   161169     nSuffix = nTerm;
   161170     nReq = 1 +                              /* varint containing prefix size */
   161171       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
   161172       nTerm +                               /* Term suffix */
   161173       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
   161174       nDoclist;                             /* Doclist data */
   161175   }
   161176 
   161177   /* Increase the total number of bytes written to account for the new entry. */
   161178   pWriter->nLeafData += nReq;
   161179 
   161180   /* If the buffer currently allocated is too small for this entry, realloc
   161181   ** the buffer to make it large enough.
   161182   */
   161183   if( nReq>pWriter->nSize ){
   161184     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
   161185     if( !aNew ) return SQLITE_NOMEM;
   161186     pWriter->aData = aNew;
   161187     pWriter->nSize = nReq;
   161188   }
   161189   assert( nData+nReq<=pWriter->nSize );
   161190 
   161191   /* Append the prefix-compressed term and doclist to the buffer. */
   161192   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   161193   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
   161194   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   161195   nData += nSuffix;
   161196   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
   161197   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   161198   pWriter->nData = nData + nDoclist;
   161199 
   161200   /* Save the current term so that it can be used to prefix-compress the next.
   161201   ** If the isCopyTerm parameter is true, then the buffer pointed to by
   161202   ** zTerm is transient, so take a copy of the term data. Otherwise, just
   161203   ** store a copy of the pointer.
   161204   */
   161205   if( isCopyTerm ){
   161206     if( nTerm>pWriter->nMalloc ){
   161207       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
   161208       if( !zNew ){
   161209         return SQLITE_NOMEM;
   161210       }
   161211       pWriter->nMalloc = nTerm*2;
   161212       pWriter->zMalloc = zNew;
   161213       pWriter->zTerm = zNew;
   161214     }
   161215     assert( pWriter->zTerm==pWriter->zMalloc );
   161216     memcpy(pWriter->zTerm, zTerm, nTerm);
   161217   }else{
   161218     pWriter->zTerm = (char *)zTerm;
   161219   }
   161220   pWriter->nTerm = nTerm;
   161221 
   161222   return SQLITE_OK;
   161223 }
   161224 
   161225 /*
   161226 ** Flush all data associated with the SegmentWriter object pWriter to the
   161227 ** database. This function must be called after all terms have been added
   161228 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
   161229 ** returned. Otherwise, an SQLite error code.
   161230 */
   161231 static int fts3SegWriterFlush(
   161232   Fts3Table *p,                   /* Virtual table handle */
   161233   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
   161234   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
   161235   int iIdx                        /* Value for 'idx' column of %_segdir */
   161236 ){
   161237   int rc;                         /* Return code */
   161238   if( pWriter->pTree ){
   161239     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
   161240     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
   161241     char *zRoot = NULL;           /* Pointer to buffer containing root node */
   161242     int nRoot = 0;                /* Size of buffer zRoot */
   161243 
   161244     iLastLeaf = pWriter->iFree;
   161245     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
   161246     if( rc==SQLITE_OK ){
   161247       rc = fts3NodeWrite(p, pWriter->pTree, 1,
   161248           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
   161249     }
   161250     if( rc==SQLITE_OK ){
   161251       rc = fts3WriteSegdir(p, iLevel, iIdx,
   161252           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
   161253     }
   161254   }else{
   161255     /* The entire tree fits on the root node. Write it to the segdir table. */
   161256     rc = fts3WriteSegdir(p, iLevel, iIdx,
   161257         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
   161258   }
   161259   p->nLeafAdd++;
   161260   return rc;
   161261 }
   161262 
   161263 /*
   161264 ** Release all memory held by the SegmentWriter object passed as the
   161265 ** first argument.
   161266 */
   161267 static void fts3SegWriterFree(SegmentWriter *pWriter){
   161268   if( pWriter ){
   161269     sqlite3_free(pWriter->aData);
   161270     sqlite3_free(pWriter->zMalloc);
   161271     fts3NodeFree(pWriter->pTree);
   161272     sqlite3_free(pWriter);
   161273   }
   161274 }
   161275 
   161276 /*
   161277 ** The first value in the apVal[] array is assumed to contain an integer.
   161278 ** This function tests if there exist any documents with docid values that
   161279 ** are different from that integer. i.e. if deleting the document with docid
   161280 ** pRowid would mean the FTS3 table were empty.
   161281 **
   161282 ** If successful, *pisEmpty is set to true if the table is empty except for
   161283 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
   161284 ** error occurs, an SQLite error code is returned.
   161285 */
   161286 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
   161287   sqlite3_stmt *pStmt;
   161288   int rc;
   161289   if( p->zContentTbl ){
   161290     /* If using the content=xxx option, assume the table is never empty */
   161291     *pisEmpty = 0;
   161292     rc = SQLITE_OK;
   161293   }else{
   161294     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
   161295     if( rc==SQLITE_OK ){
   161296       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   161297         *pisEmpty = sqlite3_column_int(pStmt, 0);
   161298       }
   161299       rc = sqlite3_reset(pStmt);
   161300     }
   161301   }
   161302   return rc;
   161303 }
   161304 
   161305 /*
   161306 ** Set *pnMax to the largest segment level in the database for the index
   161307 ** iIndex.
   161308 **
   161309 ** Segment levels are stored in the 'level' column of the %_segdir table.
   161310 **
   161311 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   161312 */
   161313 static int fts3SegmentMaxLevel(
   161314   Fts3Table *p,
   161315   int iLangid,
   161316   int iIndex,
   161317   sqlite3_int64 *pnMax
   161318 ){
   161319   sqlite3_stmt *pStmt;
   161320   int rc;
   161321   assert( iIndex>=0 && iIndex<p->nIndex );
   161322 
   161323   /* Set pStmt to the compiled version of:
   161324   **
   161325   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   161326   **
   161327   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   161328   */
   161329   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   161330   if( rc!=SQLITE_OK ) return rc;
   161331   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   161332   sqlite3_bind_int64(pStmt, 2,
   161333       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   161334   );
   161335   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   161336     *pnMax = sqlite3_column_int64(pStmt, 0);
   161337   }
   161338   return sqlite3_reset(pStmt);
   161339 }
   161340 
   161341 /*
   161342 ** iAbsLevel is an absolute level that may be assumed to exist within
   161343 ** the database. This function checks if it is the largest level number
   161344 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
   161345 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
   161346 ** is returned. If an error occurs, an error code is returned and the
   161347 ** final value of *pbMax is undefined.
   161348 */
   161349 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
   161350 
   161351   /* Set pStmt to the compiled version of:
   161352   **
   161353   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   161354   **
   161355   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   161356   */
   161357   sqlite3_stmt *pStmt;
   161358   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   161359   if( rc!=SQLITE_OK ) return rc;
   161360   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
   161361   sqlite3_bind_int64(pStmt, 2,
   161362       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
   161363   );
   161364 
   161365   *pbMax = 0;
   161366   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   161367     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
   161368   }
   161369   return sqlite3_reset(pStmt);
   161370 }
   161371 
   161372 /*
   161373 ** Delete all entries in the %_segments table associated with the segment
   161374 ** opened with seg-reader pSeg. This function does not affect the contents
   161375 ** of the %_segdir table.
   161376 */
   161377 static int fts3DeleteSegment(
   161378   Fts3Table *p,                   /* FTS table handle */
   161379   Fts3SegReader *pSeg             /* Segment to delete */
   161380 ){
   161381   int rc = SQLITE_OK;             /* Return code */
   161382   if( pSeg->iStartBlock ){
   161383     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
   161384     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
   161385     if( rc==SQLITE_OK ){
   161386       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
   161387       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
   161388       sqlite3_step(pDelete);
   161389       rc = sqlite3_reset(pDelete);
   161390     }
   161391   }
   161392   return rc;
   161393 }
   161394 
   161395 /*
   161396 ** This function is used after merging multiple segments into a single large
   161397 ** segment to delete the old, now redundant, segment b-trees. Specifically,
   161398 ** it:
   161399 **
   161400 **   1) Deletes all %_segments entries for the segments associated with
   161401 **      each of the SegReader objects in the array passed as the third
   161402 **      argument, and
   161403 **
   161404 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
   161405 **      entries regardless of level if (iLevel<0).
   161406 **
   161407 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
   161408 */
   161409 static int fts3DeleteSegdir(
   161410   Fts3Table *p,                   /* Virtual table handle */
   161411   int iLangid,                    /* Language id */
   161412   int iIndex,                     /* Index for p->aIndex */
   161413   int iLevel,                     /* Level of %_segdir entries to delete */
   161414   Fts3SegReader **apSegment,      /* Array of SegReader objects */
   161415   int nReader                     /* Size of array apSegment */
   161416 ){
   161417   int rc = SQLITE_OK;             /* Return Code */
   161418   int i;                          /* Iterator variable */
   161419   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
   161420 
   161421   for(i=0; rc==SQLITE_OK && i<nReader; i++){
   161422     rc = fts3DeleteSegment(p, apSegment[i]);
   161423   }
   161424   if( rc!=SQLITE_OK ){
   161425     return rc;
   161426   }
   161427 
   161428   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
   161429   if( iLevel==FTS3_SEGCURSOR_ALL ){
   161430     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
   161431     if( rc==SQLITE_OK ){
   161432       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   161433       sqlite3_bind_int64(pDelete, 2,
   161434           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   161435       );
   161436     }
   161437   }else{
   161438     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
   161439     if( rc==SQLITE_OK ){
   161440       sqlite3_bind_int64(
   161441           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   161442       );
   161443     }
   161444   }
   161445 
   161446   if( rc==SQLITE_OK ){
   161447     sqlite3_step(pDelete);
   161448     rc = sqlite3_reset(pDelete);
   161449   }
   161450 
   161451   return rc;
   161452 }
   161453 
   161454 /*
   161455 ** When this function is called, buffer *ppList (size *pnList bytes) contains
   161456 ** a position list that may (or may not) feature multiple columns. This
   161457 ** function adjusts the pointer *ppList and the length *pnList so that they
   161458 ** identify the subset of the position list that corresponds to column iCol.
   161459 **
   161460 ** If there are no entries in the input position list for column iCol, then
   161461 ** *pnList is set to zero before returning.
   161462 **
   161463 ** If parameter bZero is non-zero, then any part of the input list following
   161464 ** the end of the output list is zeroed before returning.
   161465 */
   161466 static void fts3ColumnFilter(
   161467   int iCol,                       /* Column to filter on */
   161468   int bZero,                      /* Zero out anything following *ppList */
   161469   char **ppList,                  /* IN/OUT: Pointer to position list */
   161470   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
   161471 ){
   161472   char *pList = *ppList;
   161473   int nList = *pnList;
   161474   char *pEnd = &pList[nList];
   161475   int iCurrent = 0;
   161476   char *p = pList;
   161477 
   161478   assert( iCol>=0 );
   161479   while( 1 ){
   161480     char c = 0;
   161481     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
   161482 
   161483     if( iCol==iCurrent ){
   161484       nList = (int)(p - pList);
   161485       break;
   161486     }
   161487 
   161488     nList -= (int)(p - pList);
   161489     pList = p;
   161490     if( nList==0 ){
   161491       break;
   161492     }
   161493     p = &pList[1];
   161494     p += fts3GetVarint32(p, &iCurrent);
   161495   }
   161496 
   161497   if( bZero && &pList[nList]!=pEnd ){
   161498     memset(&pList[nList], 0, pEnd - &pList[nList]);
   161499   }
   161500   *ppList = pList;
   161501   *pnList = nList;
   161502 }
   161503 
   161504 /*
   161505 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
   161506 ** existing data). Grow the buffer if required.
   161507 **
   161508 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
   161509 ** trying to resize the buffer, return SQLITE_NOMEM.
   161510 */
   161511 static int fts3MsrBufferData(
   161512   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   161513   char *pList,
   161514   int nList
   161515 ){
   161516   if( nList>pMsr->nBuffer ){
   161517     char *pNew;
   161518     pMsr->nBuffer = nList*2;
   161519     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
   161520     if( !pNew ) return SQLITE_NOMEM;
   161521     pMsr->aBuffer = pNew;
   161522   }
   161523 
   161524   memcpy(pMsr->aBuffer, pList, nList);
   161525   return SQLITE_OK;
   161526 }
   161527 
   161528 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   161529   Fts3Table *p,                   /* Virtual table handle */
   161530   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   161531   sqlite3_int64 *piDocid,         /* OUT: Docid value */
   161532   char **paPoslist,               /* OUT: Pointer to position list */
   161533   int *pnPoslist                  /* OUT: Size of position list in bytes */
   161534 ){
   161535   int nMerge = pMsr->nAdvance;
   161536   Fts3SegReader **apSegment = pMsr->apSegment;
   161537   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   161538     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   161539   );
   161540 
   161541   if( nMerge==0 ){
   161542     *paPoslist = 0;
   161543     return SQLITE_OK;
   161544   }
   161545 
   161546   while( 1 ){
   161547     Fts3SegReader *pSeg;
   161548     pSeg = pMsr->apSegment[0];
   161549 
   161550     if( pSeg->pOffsetList==0 ){
   161551       *paPoslist = 0;
   161552       break;
   161553     }else{
   161554       int rc;
   161555       char *pList;
   161556       int nList;
   161557       int j;
   161558       sqlite3_int64 iDocid = apSegment[0]->iDocid;
   161559 
   161560       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   161561       j = 1;
   161562       while( rc==SQLITE_OK
   161563         && j<nMerge
   161564         && apSegment[j]->pOffsetList
   161565         && apSegment[j]->iDocid==iDocid
   161566       ){
   161567         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   161568         j++;
   161569       }
   161570       if( rc!=SQLITE_OK ) return rc;
   161571       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
   161572 
   161573       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
   161574         rc = fts3MsrBufferData(pMsr, pList, nList+1);
   161575         if( rc!=SQLITE_OK ) return rc;
   161576         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
   161577         pList = pMsr->aBuffer;
   161578       }
   161579 
   161580       if( pMsr->iColFilter>=0 ){
   161581         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
   161582       }
   161583 
   161584       if( nList>0 ){
   161585         *paPoslist = pList;
   161586         *piDocid = iDocid;
   161587         *pnPoslist = nList;
   161588         break;
   161589       }
   161590     }
   161591   }
   161592 
   161593   return SQLITE_OK;
   161594 }
   161595 
   161596 static int fts3SegReaderStart(
   161597   Fts3Table *p,                   /* Virtual table handle */
   161598   Fts3MultiSegReader *pCsr,       /* Cursor object */
   161599   const char *zTerm,              /* Term searched for (or NULL) */
   161600   int nTerm                       /* Length of zTerm in bytes */
   161601 ){
   161602   int i;
   161603   int nSeg = pCsr->nSegment;
   161604 
   161605   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   161606   ** for, then advance each segment iterator until it points to a term of
   161607   ** equal or greater value than the specified term. This prevents many
   161608   ** unnecessary merge/sort operations for the case where single segment
   161609   ** b-tree leaf nodes contain more than one term.
   161610   */
   161611   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
   161612     int res = 0;
   161613     Fts3SegReader *pSeg = pCsr->apSegment[i];
   161614     do {
   161615       int rc = fts3SegReaderNext(p, pSeg, 0);
   161616       if( rc!=SQLITE_OK ) return rc;
   161617     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
   161618 
   161619     if( pSeg->bLookup && res!=0 ){
   161620       fts3SegReaderSetEof(pSeg);
   161621     }
   161622   }
   161623   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
   161624 
   161625   return SQLITE_OK;
   161626 }
   161627 
   161628 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
   161629   Fts3Table *p,                   /* Virtual table handle */
   161630   Fts3MultiSegReader *pCsr,       /* Cursor object */
   161631   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
   161632 ){
   161633   pCsr->pFilter = pFilter;
   161634   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
   161635 }
   161636 
   161637 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   161638   Fts3Table *p,                   /* Virtual table handle */
   161639   Fts3MultiSegReader *pCsr,       /* Cursor object */
   161640   int iCol,                       /* Column to match on. */
   161641   const char *zTerm,              /* Term to iterate through a doclist for */
   161642   int nTerm                       /* Number of bytes in zTerm */
   161643 ){
   161644   int i;
   161645   int rc;
   161646   int nSegment = pCsr->nSegment;
   161647   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   161648     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   161649   );
   161650 
   161651   assert( pCsr->pFilter==0 );
   161652   assert( zTerm && nTerm>0 );
   161653 
   161654   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
   161655   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
   161656   if( rc!=SQLITE_OK ) return rc;
   161657 
   161658   /* Determine how many of the segments actually point to zTerm/nTerm. */
   161659   for(i=0; i<nSegment; i++){
   161660     Fts3SegReader *pSeg = pCsr->apSegment[i];
   161661     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
   161662       break;
   161663     }
   161664   }
   161665   pCsr->nAdvance = i;
   161666 
   161667   /* Advance each of the segments to point to the first docid. */
   161668   for(i=0; i<pCsr->nAdvance; i++){
   161669     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
   161670     if( rc!=SQLITE_OK ) return rc;
   161671   }
   161672   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
   161673 
   161674   assert( iCol<0 || iCol<p->nColumn );
   161675   pCsr->iColFilter = iCol;
   161676 
   161677   return SQLITE_OK;
   161678 }
   161679 
   161680 /*
   161681 ** This function is called on a MultiSegReader that has been started using
   161682 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
   161683 ** have been made. Calling this function puts the MultiSegReader in such
   161684 ** a state that if the next two calls are:
   161685 **
   161686 **   sqlite3Fts3SegReaderStart()
   161687 **   sqlite3Fts3SegReaderStep()
   161688 **
   161689 ** then the entire doclist for the term is available in
   161690 ** MultiSegReader.aDoclist/nDoclist.
   161691 */
   161692 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
   161693   int i;                          /* Used to iterate through segment-readers */
   161694 
   161695   assert( pCsr->zTerm==0 );
   161696   assert( pCsr->nTerm==0 );
   161697   assert( pCsr->aDoclist==0 );
   161698   assert( pCsr->nDoclist==0 );
   161699 
   161700   pCsr->nAdvance = 0;
   161701   pCsr->bRestart = 1;
   161702   for(i=0; i<pCsr->nSegment; i++){
   161703     pCsr->apSegment[i]->pOffsetList = 0;
   161704     pCsr->apSegment[i]->nOffsetList = 0;
   161705     pCsr->apSegment[i]->iDocid = 0;
   161706   }
   161707 
   161708   return SQLITE_OK;
   161709 }
   161710 
   161711 
   161712 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
   161713   Fts3Table *p,                   /* Virtual table handle */
   161714   Fts3MultiSegReader *pCsr        /* Cursor object */
   161715 ){
   161716   int rc = SQLITE_OK;
   161717 
   161718   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
   161719   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
   161720   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
   161721   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
   161722   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
   161723   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
   161724 
   161725   Fts3SegReader **apSegment = pCsr->apSegment;
   161726   int nSegment = pCsr->nSegment;
   161727   Fts3SegFilter *pFilter = pCsr->pFilter;
   161728   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   161729     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   161730   );
   161731 
   161732   if( pCsr->nSegment==0 ) return SQLITE_OK;
   161733 
   161734   do {
   161735     int nMerge;
   161736     int i;
   161737 
   161738     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
   161739     ** forward. Then sort the list in order of current term again.
   161740     */
   161741     for(i=0; i<pCsr->nAdvance; i++){
   161742       Fts3SegReader *pSeg = apSegment[i];
   161743       if( pSeg->bLookup ){
   161744         fts3SegReaderSetEof(pSeg);
   161745       }else{
   161746         rc = fts3SegReaderNext(p, pSeg, 0);
   161747       }
   161748       if( rc!=SQLITE_OK ) return rc;
   161749     }
   161750     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
   161751     pCsr->nAdvance = 0;
   161752 
   161753     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
   161754     assert( rc==SQLITE_OK );
   161755     if( apSegment[0]->aNode==0 ) break;
   161756 
   161757     pCsr->nTerm = apSegment[0]->nTerm;
   161758     pCsr->zTerm = apSegment[0]->zTerm;
   161759 
   161760     /* If this is a prefix-search, and if the term that apSegment[0] points
   161761     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
   161762     ** required callbacks have been made. In this case exit early.
   161763     **
   161764     ** Similarly, if this is a search for an exact match, and the first term
   161765     ** of segment apSegment[0] is not a match, exit early.
   161766     */
   161767     if( pFilter->zTerm && !isScan ){
   161768       if( pCsr->nTerm<pFilter->nTerm
   161769        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
   161770        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
   161771       ){
   161772         break;
   161773       }
   161774     }
   161775 
   161776     nMerge = 1;
   161777     while( nMerge<nSegment
   161778         && apSegment[nMerge]->aNode
   161779         && apSegment[nMerge]->nTerm==pCsr->nTerm
   161780         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
   161781     ){
   161782       nMerge++;
   161783     }
   161784 
   161785     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
   161786     if( nMerge==1
   161787      && !isIgnoreEmpty
   161788      && !isFirst
   161789      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
   161790     ){
   161791       pCsr->nDoclist = apSegment[0]->nDoclist;
   161792       if( fts3SegReaderIsPending(apSegment[0]) ){
   161793         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
   161794         pCsr->aDoclist = pCsr->aBuffer;
   161795       }else{
   161796         pCsr->aDoclist = apSegment[0]->aDoclist;
   161797       }
   161798       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
   161799     }else{
   161800       int nDoclist = 0;           /* Size of doclist */
   161801       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
   161802 
   161803       /* The current term of the first nMerge entries in the array
   161804       ** of Fts3SegReader objects is the same. The doclists must be merged
   161805       ** and a single term returned with the merged doclist.
   161806       */
   161807       for(i=0; i<nMerge; i++){
   161808         fts3SegReaderFirstDocid(p, apSegment[i]);
   161809       }
   161810       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
   161811       while( apSegment[0]->pOffsetList ){
   161812         int j;                    /* Number of segments that share a docid */
   161813         char *pList = 0;
   161814         int nList = 0;
   161815         int nByte;
   161816         sqlite3_int64 iDocid = apSegment[0]->iDocid;
   161817         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   161818         j = 1;
   161819         while( j<nMerge
   161820             && apSegment[j]->pOffsetList
   161821             && apSegment[j]->iDocid==iDocid
   161822         ){
   161823           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   161824           j++;
   161825         }
   161826 
   161827         if( isColFilter ){
   161828           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
   161829         }
   161830 
   161831         if( !isIgnoreEmpty || nList>0 ){
   161832 
   161833           /* Calculate the 'docid' delta value to write into the merged
   161834           ** doclist. */
   161835           sqlite3_int64 iDelta;
   161836           if( p->bDescIdx && nDoclist>0 ){
   161837             iDelta = iPrev - iDocid;
   161838           }else{
   161839             iDelta = iDocid - iPrev;
   161840           }
   161841           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
   161842           assert( nDoclist>0 || iDelta==iDocid );
   161843 
   161844           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
   161845           if( nDoclist+nByte>pCsr->nBuffer ){
   161846             char *aNew;
   161847             pCsr->nBuffer = (nDoclist+nByte)*2;
   161848             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
   161849             if( !aNew ){
   161850               return SQLITE_NOMEM;
   161851             }
   161852             pCsr->aBuffer = aNew;
   161853           }
   161854 
   161855           if( isFirst ){
   161856             char *a = &pCsr->aBuffer[nDoclist];
   161857             int nWrite;
   161858 
   161859             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
   161860             if( nWrite ){
   161861               iPrev = iDocid;
   161862               nDoclist += nWrite;
   161863             }
   161864           }else{
   161865             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
   161866             iPrev = iDocid;
   161867             if( isRequirePos ){
   161868               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
   161869               nDoclist += nList;
   161870               pCsr->aBuffer[nDoclist++] = '\0';
   161871             }
   161872           }
   161873         }
   161874 
   161875         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
   161876       }
   161877       if( nDoclist>0 ){
   161878         pCsr->aDoclist = pCsr->aBuffer;
   161879         pCsr->nDoclist = nDoclist;
   161880         rc = SQLITE_ROW;
   161881       }
   161882     }
   161883     pCsr->nAdvance = nMerge;
   161884   }while( rc==SQLITE_OK );
   161885 
   161886   return rc;
   161887 }
   161888 
   161889 
   161890 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
   161891   Fts3MultiSegReader *pCsr       /* Cursor object */
   161892 ){
   161893   if( pCsr ){
   161894     int i;
   161895     for(i=0; i<pCsr->nSegment; i++){
   161896       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
   161897     }
   161898     sqlite3_free(pCsr->apSegment);
   161899     sqlite3_free(pCsr->aBuffer);
   161900 
   161901     pCsr->nSegment = 0;
   161902     pCsr->apSegment = 0;
   161903     pCsr->aBuffer = 0;
   161904   }
   161905 }
   161906 
   161907 /*
   161908 ** Decode the "end_block" field, selected by column iCol of the SELECT
   161909 ** statement passed as the first argument.
   161910 **
   161911 ** The "end_block" field may contain either an integer, or a text field
   161912 ** containing the text representation of two non-negative integers separated
   161913 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
   161914 ** to the integer value and *pnByte to zero before returning. In the second,
   161915 ** set *piEndBlock to the first value and *pnByte to the second.
   161916 */
   161917 static void fts3ReadEndBlockField(
   161918   sqlite3_stmt *pStmt,
   161919   int iCol,
   161920   i64 *piEndBlock,
   161921   i64 *pnByte
   161922 ){
   161923   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
   161924   if( zText ){
   161925     int i;
   161926     int iMul = 1;
   161927     i64 iVal = 0;
   161928     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
   161929       iVal = iVal*10 + (zText[i] - '0');
   161930     }
   161931     *piEndBlock = iVal;
   161932     while( zText[i]==' ' ) i++;
   161933     iVal = 0;
   161934     if( zText[i]=='-' ){
   161935       i++;
   161936       iMul = -1;
   161937     }
   161938     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
   161939       iVal = iVal*10 + (zText[i] - '0');
   161940     }
   161941     *pnByte = (iVal * (i64)iMul);
   161942   }
   161943 }
   161944 
   161945 
   161946 /*
   161947 ** A segment of size nByte bytes has just been written to absolute level
   161948 ** iAbsLevel. Promote any segments that should be promoted as a result.
   161949 */
   161950 static int fts3PromoteSegments(
   161951   Fts3Table *p,                   /* FTS table handle */
   161952   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
   161953   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
   161954 ){
   161955   int rc = SQLITE_OK;
   161956   sqlite3_stmt *pRange;
   161957 
   161958   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
   161959 
   161960   if( rc==SQLITE_OK ){
   161961     int bOk = 0;
   161962     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
   161963     i64 nLimit = (nByte*3)/2;
   161964 
   161965     /* Loop through all entries in the %_segdir table corresponding to
   161966     ** segments in this index on levels greater than iAbsLevel. If there is
   161967     ** at least one such segment, and it is possible to determine that all
   161968     ** such segments are smaller than nLimit bytes in size, they will be
   161969     ** promoted to level iAbsLevel.  */
   161970     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
   161971     sqlite3_bind_int64(pRange, 2, iLast);
   161972     while( SQLITE_ROW==sqlite3_step(pRange) ){
   161973       i64 nSize = 0, dummy;
   161974       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
   161975       if( nSize<=0 || nSize>nLimit ){
   161976         /* If nSize==0, then the %_segdir.end_block field does not not
   161977         ** contain a size value. This happens if it was written by an
   161978         ** old version of FTS. In this case it is not possible to determine
   161979         ** the size of the segment, and so segment promotion does not
   161980         ** take place.  */
   161981         bOk = 0;
   161982         break;
   161983       }
   161984       bOk = 1;
   161985     }
   161986     rc = sqlite3_reset(pRange);
   161987 
   161988     if( bOk ){
   161989       int iIdx = 0;
   161990       sqlite3_stmt *pUpdate1 = 0;
   161991       sqlite3_stmt *pUpdate2 = 0;
   161992 
   161993       if( rc==SQLITE_OK ){
   161994         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
   161995       }
   161996       if( rc==SQLITE_OK ){
   161997         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
   161998       }
   161999 
   162000       if( rc==SQLITE_OK ){
   162001 
   162002         /* Loop through all %_segdir entries for segments in this index with
   162003         ** levels equal to or greater than iAbsLevel. As each entry is visited,
   162004         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
   162005         ** oldest segment in the range, 1 for the next oldest, and so on.
   162006         **
   162007         ** In other words, move all segments being promoted to level -1,
   162008         ** setting the "idx" fields as appropriate to keep them in the same
   162009         ** order. The contents of level -1 (which is never used, except
   162010         ** transiently here), will be moved back to level iAbsLevel below.  */
   162011         sqlite3_bind_int64(pRange, 1, iAbsLevel);
   162012         while( SQLITE_ROW==sqlite3_step(pRange) ){
   162013           sqlite3_bind_int(pUpdate1, 1, iIdx++);
   162014           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
   162015           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
   162016           sqlite3_step(pUpdate1);
   162017           rc = sqlite3_reset(pUpdate1);
   162018           if( rc!=SQLITE_OK ){
   162019             sqlite3_reset(pRange);
   162020             break;
   162021           }
   162022         }
   162023       }
   162024       if( rc==SQLITE_OK ){
   162025         rc = sqlite3_reset(pRange);
   162026       }
   162027 
   162028       /* Move level -1 to level iAbsLevel */
   162029       if( rc==SQLITE_OK ){
   162030         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
   162031         sqlite3_step(pUpdate2);
   162032         rc = sqlite3_reset(pUpdate2);
   162033       }
   162034     }
   162035   }
   162036 
   162037 
   162038   return rc;
   162039 }
   162040 
   162041 /*
   162042 ** Merge all level iLevel segments in the database into a single
   162043 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
   162044 ** single segment with a level equal to the numerically largest level
   162045 ** currently present in the database.
   162046 **
   162047 ** If this function is called with iLevel<0, but there is only one
   162048 ** segment in the database, SQLITE_DONE is returned immediately.
   162049 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
   162050 ** an SQLite error code is returned.
   162051 */
   162052 static int fts3SegmentMerge(
   162053   Fts3Table *p,
   162054   int iLangid,                    /* Language id to merge */
   162055   int iIndex,                     /* Index in p->aIndex[] to merge */
   162056   int iLevel                      /* Level to merge */
   162057 ){
   162058   int rc;                         /* Return code */
   162059   int iIdx = 0;                   /* Index of new segment */
   162060   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
   162061   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
   162062   Fts3SegFilter filter;           /* Segment term filter condition */
   162063   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
   162064   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
   162065   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
   162066 
   162067   assert( iLevel==FTS3_SEGCURSOR_ALL
   162068        || iLevel==FTS3_SEGCURSOR_PENDING
   162069        || iLevel>=0
   162070   );
   162071   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   162072   assert( iIndex>=0 && iIndex<p->nIndex );
   162073 
   162074   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
   162075   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
   162076 
   162077   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   162078     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
   162079     if( rc!=SQLITE_OK ) goto finished;
   162080   }
   162081 
   162082   if( iLevel==FTS3_SEGCURSOR_ALL ){
   162083     /* This call is to merge all segments in the database to a single
   162084     ** segment. The level of the new segment is equal to the numerically
   162085     ** greatest segment level currently present in the database for this
   162086     ** index. The idx of the new segment is always 0.  */
   162087     if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
   162088       rc = SQLITE_DONE;
   162089       goto finished;
   162090     }
   162091     iNewLevel = iMaxLevel;
   162092     bIgnoreEmpty = 1;
   162093 
   162094   }else{
   162095     /* This call is to merge all segments at level iLevel. find the next
   162096     ** available segment index at level iLevel+1. The call to
   162097     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
   162098     ** a single iLevel+2 segment if necessary.  */
   162099     assert( FTS3_SEGCURSOR_PENDING==-1 );
   162100     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
   162101     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
   162102     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
   162103   }
   162104   if( rc!=SQLITE_OK ) goto finished;
   162105 
   162106   assert( csr.nSegment>0 );
   162107   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
   162108   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
   162109 
   162110   memset(&filter, 0, sizeof(Fts3SegFilter));
   162111   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
   162112   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
   162113 
   162114   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   162115   while( SQLITE_OK==rc ){
   162116     rc = sqlite3Fts3SegReaderStep(p, &csr);
   162117     if( rc!=SQLITE_ROW ) break;
   162118     rc = fts3SegWriterAdd(p, &pWriter, 1,
   162119         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
   162120   }
   162121   if( rc!=SQLITE_OK ) goto finished;
   162122   assert( pWriter || bIgnoreEmpty );
   162123 
   162124   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   162125     rc = fts3DeleteSegdir(
   162126         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
   162127     );
   162128     if( rc!=SQLITE_OK ) goto finished;
   162129   }
   162130   if( pWriter ){
   162131     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
   162132     if( rc==SQLITE_OK ){
   162133       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
   162134         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
   162135       }
   162136     }
   162137   }
   162138 
   162139  finished:
   162140   fts3SegWriterFree(pWriter);
   162141   sqlite3Fts3SegReaderFinish(&csr);
   162142   return rc;
   162143 }
   162144 
   162145 
   162146 /*
   162147 ** Flush the contents of pendingTerms to level 0 segments.
   162148 */
   162149 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   162150   int rc = SQLITE_OK;
   162151   int i;
   162152 
   162153   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   162154     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
   162155     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   162156   }
   162157   sqlite3Fts3PendingTermsClear(p);
   162158 
   162159   /* Determine the auto-incr-merge setting if unknown.  If enabled,
   162160   ** estimate the number of leaf blocks of content to be written
   162161   */
   162162   if( rc==SQLITE_OK && p->bHasStat
   162163    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
   162164   ){
   162165     sqlite3_stmt *pStmt = 0;
   162166     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
   162167     if( rc==SQLITE_OK ){
   162168       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
   162169       rc = sqlite3_step(pStmt);
   162170       if( rc==SQLITE_ROW ){
   162171         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
   162172         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
   162173       }else if( rc==SQLITE_DONE ){
   162174         p->nAutoincrmerge = 0;
   162175       }
   162176       rc = sqlite3_reset(pStmt);
   162177     }
   162178   }
   162179   return rc;
   162180 }
   162181 
   162182 /*
   162183 ** Encode N integers as varints into a blob.
   162184 */
   162185 static void fts3EncodeIntArray(
   162186   int N,             /* The number of integers to encode */
   162187   u32 *a,            /* The integer values */
   162188   char *zBuf,        /* Write the BLOB here */
   162189   int *pNBuf         /* Write number of bytes if zBuf[] used here */
   162190 ){
   162191   int i, j;
   162192   for(i=j=0; i<N; i++){
   162193     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
   162194   }
   162195   *pNBuf = j;
   162196 }
   162197 
   162198 /*
   162199 ** Decode a blob of varints into N integers
   162200 */
   162201 static void fts3DecodeIntArray(
   162202   int N,             /* The number of integers to decode */
   162203   u32 *a,            /* Write the integer values */
   162204   const char *zBuf,  /* The BLOB containing the varints */
   162205   int nBuf           /* size of the BLOB */
   162206 ){
   162207   int i, j;
   162208   UNUSED_PARAMETER(nBuf);
   162209   for(i=j=0; i<N; i++){
   162210     sqlite3_int64 x;
   162211     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
   162212     assert(j<=nBuf);
   162213     a[i] = (u32)(x & 0xffffffff);
   162214   }
   162215 }
   162216 
   162217 /*
   162218 ** Insert the sizes (in tokens) for each column of the document
   162219 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
   162220 ** a blob of varints.
   162221 */
   162222 static void fts3InsertDocsize(
   162223   int *pRC,                       /* Result code */
   162224   Fts3Table *p,                   /* Table into which to insert */
   162225   u32 *aSz                        /* Sizes of each column, in tokens */
   162226 ){
   162227   char *pBlob;             /* The BLOB encoding of the document size */
   162228   int nBlob;               /* Number of bytes in the BLOB */
   162229   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
   162230   int rc;                  /* Result code from subfunctions */
   162231 
   162232   if( *pRC ) return;
   162233   pBlob = sqlite3_malloc( 10*p->nColumn );
   162234   if( pBlob==0 ){
   162235     *pRC = SQLITE_NOMEM;
   162236     return;
   162237   }
   162238   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
   162239   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
   162240   if( rc ){
   162241     sqlite3_free(pBlob);
   162242     *pRC = rc;
   162243     return;
   162244   }
   162245   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
   162246   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
   162247   sqlite3_step(pStmt);
   162248   *pRC = sqlite3_reset(pStmt);
   162249 }
   162250 
   162251 /*
   162252 ** Record 0 of the %_stat table contains a blob consisting of N varints,
   162253 ** where N is the number of user defined columns in the fts3 table plus
   162254 ** two. If nCol is the number of user defined columns, then values of the
   162255 ** varints are set as follows:
   162256 **
   162257 **   Varint 0:       Total number of rows in the table.
   162258 **
   162259 **   Varint 1..nCol: For each column, the total number of tokens stored in
   162260 **                   the column for all rows of the table.
   162261 **
   162262 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
   162263 **                   columns of all rows of the table.
   162264 **
   162265 */
   162266 static void fts3UpdateDocTotals(
   162267   int *pRC,                       /* The result code */
   162268   Fts3Table *p,                   /* Table being updated */
   162269   u32 *aSzIns,                    /* Size increases */
   162270   u32 *aSzDel,                    /* Size decreases */
   162271   int nChng                       /* Change in the number of documents */
   162272 ){
   162273   char *pBlob;             /* Storage for BLOB written into %_stat */
   162274   int nBlob;               /* Size of BLOB written into %_stat */
   162275   u32 *a;                  /* Array of integers that becomes the BLOB */
   162276   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
   162277   int i;                   /* Loop counter */
   162278   int rc;                  /* Result code from subfunctions */
   162279 
   162280   const int nStat = p->nColumn+2;
   162281 
   162282   if( *pRC ) return;
   162283   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
   162284   if( a==0 ){
   162285     *pRC = SQLITE_NOMEM;
   162286     return;
   162287   }
   162288   pBlob = (char*)&a[nStat];
   162289   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
   162290   if( rc ){
   162291     sqlite3_free(a);
   162292     *pRC = rc;
   162293     return;
   162294   }
   162295   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   162296   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   162297     fts3DecodeIntArray(nStat, a,
   162298          sqlite3_column_blob(pStmt, 0),
   162299          sqlite3_column_bytes(pStmt, 0));
   162300   }else{
   162301     memset(a, 0, sizeof(u32)*(nStat) );
   162302   }
   162303   rc = sqlite3_reset(pStmt);
   162304   if( rc!=SQLITE_OK ){
   162305     sqlite3_free(a);
   162306     *pRC = rc;
   162307     return;
   162308   }
   162309   if( nChng<0 && a[0]<(u32)(-nChng) ){
   162310     a[0] = 0;
   162311   }else{
   162312     a[0] += nChng;
   162313   }
   162314   for(i=0; i<p->nColumn+1; i++){
   162315     u32 x = a[i+1];
   162316     if( x+aSzIns[i] < aSzDel[i] ){
   162317       x = 0;
   162318     }else{
   162319       x = x + aSzIns[i] - aSzDel[i];
   162320     }
   162321     a[i+1] = x;
   162322   }
   162323   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
   162324   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
   162325   if( rc ){
   162326     sqlite3_free(a);
   162327     *pRC = rc;
   162328     return;
   162329   }
   162330   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
   162331   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
   162332   sqlite3_step(pStmt);
   162333   *pRC = sqlite3_reset(pStmt);
   162334   sqlite3_free(a);
   162335 }
   162336 
   162337 /*
   162338 ** Merge the entire database so that there is one segment for each
   162339 ** iIndex/iLangid combination.
   162340 */
   162341 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
   162342   int bSeenDone = 0;
   162343   int rc;
   162344   sqlite3_stmt *pAllLangid = 0;
   162345 
   162346   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   162347   if( rc==SQLITE_OK ){
   162348     int rc2;
   162349     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
   162350     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
   162351     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
   162352       int i;
   162353       int iLangid = sqlite3_column_int(pAllLangid, 0);
   162354       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   162355         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
   162356         if( rc==SQLITE_DONE ){
   162357           bSeenDone = 1;
   162358           rc = SQLITE_OK;
   162359         }
   162360       }
   162361     }
   162362     rc2 = sqlite3_reset(pAllLangid);
   162363     if( rc==SQLITE_OK ) rc = rc2;
   162364   }
   162365 
   162366   sqlite3Fts3SegmentsClose(p);
   162367   sqlite3Fts3PendingTermsClear(p);
   162368 
   162369   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
   162370 }
   162371 
   162372 /*
   162373 ** This function is called when the user executes the following statement:
   162374 **
   162375 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
   162376 **
   162377 ** The entire FTS index is discarded and rebuilt. If the table is one
   162378 ** created using the content=xxx option, then the new index is based on
   162379 ** the current contents of the xxx table. Otherwise, it is rebuilt based
   162380 ** on the contents of the %_content table.
   162381 */
   162382 static int fts3DoRebuild(Fts3Table *p){
   162383   int rc;                         /* Return Code */
   162384 
   162385   rc = fts3DeleteAll(p, 0);
   162386   if( rc==SQLITE_OK ){
   162387     u32 *aSz = 0;
   162388     u32 *aSzIns = 0;
   162389     u32 *aSzDel = 0;
   162390     sqlite3_stmt *pStmt = 0;
   162391     int nEntry = 0;
   162392 
   162393     /* Compose and prepare an SQL statement to loop through the content table */
   162394     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   162395     if( !zSql ){
   162396       rc = SQLITE_NOMEM;
   162397     }else{
   162398       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   162399       sqlite3_free(zSql);
   162400     }
   162401 
   162402     if( rc==SQLITE_OK ){
   162403       int nByte = sizeof(u32) * (p->nColumn+1)*3;
   162404       aSz = (u32 *)sqlite3_malloc(nByte);
   162405       if( aSz==0 ){
   162406         rc = SQLITE_NOMEM;
   162407       }else{
   162408         memset(aSz, 0, nByte);
   162409         aSzIns = &aSz[p->nColumn+1];
   162410         aSzDel = &aSzIns[p->nColumn+1];
   162411       }
   162412     }
   162413 
   162414     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   162415       int iCol;
   162416       int iLangid = langidFromSelect(p, pStmt);
   162417       rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
   162418       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
   162419       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   162420         if( p->abNotindexed[iCol]==0 ){
   162421           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
   162422           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
   162423           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
   162424         }
   162425       }
   162426       if( p->bHasDocsize ){
   162427         fts3InsertDocsize(&rc, p, aSz);
   162428       }
   162429       if( rc!=SQLITE_OK ){
   162430         sqlite3_finalize(pStmt);
   162431         pStmt = 0;
   162432       }else{
   162433         nEntry++;
   162434         for(iCol=0; iCol<=p->nColumn; iCol++){
   162435           aSzIns[iCol] += aSz[iCol];
   162436         }
   162437       }
   162438     }
   162439     if( p->bFts4 ){
   162440       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
   162441     }
   162442     sqlite3_free(aSz);
   162443 
   162444     if( pStmt ){
   162445       int rc2 = sqlite3_finalize(pStmt);
   162446       if( rc==SQLITE_OK ){
   162447         rc = rc2;
   162448       }
   162449     }
   162450   }
   162451 
   162452   return rc;
   162453 }
   162454 
   162455 
   162456 /*
   162457 ** This function opens a cursor used to read the input data for an
   162458 ** incremental merge operation. Specifically, it opens a cursor to scan
   162459 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
   162460 ** level iAbsLevel.
   162461 */
   162462 static int fts3IncrmergeCsr(
   162463   Fts3Table *p,                   /* FTS3 table handle */
   162464   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
   162465   int nSeg,                       /* Number of segments to merge */
   162466   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   162467 ){
   162468   int rc;                         /* Return Code */
   162469   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
   162470   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
   162471 
   162472   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
   162473   memset(pCsr, 0, sizeof(*pCsr));
   162474   nByte = sizeof(Fts3SegReader *) * nSeg;
   162475   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
   162476 
   162477   if( pCsr->apSegment==0 ){
   162478     rc = SQLITE_NOMEM;
   162479   }else{
   162480     memset(pCsr->apSegment, 0, nByte);
   162481     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   162482   }
   162483   if( rc==SQLITE_OK ){
   162484     int i;
   162485     int rc2;
   162486     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
   162487     assert( pCsr->nSegment==0 );
   162488     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
   162489       rc = sqlite3Fts3SegReaderNew(i, 0,
   162490           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
   162491           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
   162492           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
   162493           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
   162494           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
   162495           &pCsr->apSegment[i]
   162496       );
   162497       pCsr->nSegment++;
   162498     }
   162499     rc2 = sqlite3_reset(pStmt);
   162500     if( rc==SQLITE_OK ) rc = rc2;
   162501   }
   162502 
   162503   return rc;
   162504 }
   162505 
   162506 typedef struct IncrmergeWriter IncrmergeWriter;
   162507 typedef struct NodeWriter NodeWriter;
   162508 typedef struct Blob Blob;
   162509 typedef struct NodeReader NodeReader;
   162510 
   162511 /*
   162512 ** An instance of the following structure is used as a dynamic buffer
   162513 ** to build up nodes or other blobs of data in.
   162514 **
   162515 ** The function blobGrowBuffer() is used to extend the allocation.
   162516 */
   162517 struct Blob {
   162518   char *a;                        /* Pointer to allocation */
   162519   int n;                          /* Number of valid bytes of data in a[] */
   162520   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
   162521 };
   162522 
   162523 /*
   162524 ** This structure is used to build up buffers containing segment b-tree
   162525 ** nodes (blocks).
   162526 */
   162527 struct NodeWriter {
   162528   sqlite3_int64 iBlock;           /* Current block id */
   162529   Blob key;                       /* Last key written to the current block */
   162530   Blob block;                     /* Current block image */
   162531 };
   162532 
   162533 /*
   162534 ** An object of this type contains the state required to create or append
   162535 ** to an appendable b-tree segment.
   162536 */
   162537 struct IncrmergeWriter {
   162538   int nLeafEst;                   /* Space allocated for leaf blocks */
   162539   int nWork;                      /* Number of leaf pages flushed */
   162540   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
   162541   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
   162542   sqlite3_int64 iStart;           /* Block number of first allocated block */
   162543   sqlite3_int64 iEnd;             /* Block number of last allocated block */
   162544   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
   162545   u8 bNoLeafData;                 /* If true, store 0 for segment size */
   162546   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
   162547 };
   162548 
   162549 /*
   162550 ** An object of the following type is used to read data from a single
   162551 ** FTS segment node. See the following functions:
   162552 **
   162553 **     nodeReaderInit()
   162554 **     nodeReaderNext()
   162555 **     nodeReaderRelease()
   162556 */
   162557 struct NodeReader {
   162558   const char *aNode;
   162559   int nNode;
   162560   int iOff;                       /* Current offset within aNode[] */
   162561 
   162562   /* Output variables. Containing the current node entry. */
   162563   sqlite3_int64 iChild;           /* Pointer to child node */
   162564   Blob term;                      /* Current term */
   162565   const char *aDoclist;           /* Pointer to doclist */
   162566   int nDoclist;                   /* Size of doclist in bytes */
   162567 };
   162568 
   162569 /*
   162570 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   162571 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
   162572 ** bytes in size, extend (realloc) it to be so.
   162573 **
   162574 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
   162575 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
   162576 ** to reflect the new size of the pBlob->a[] buffer.
   162577 */
   162578 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
   162579   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
   162580     int nAlloc = nMin;
   162581     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
   162582     if( a ){
   162583       pBlob->nAlloc = nAlloc;
   162584       pBlob->a = a;
   162585     }else{
   162586       *pRc = SQLITE_NOMEM;
   162587     }
   162588   }
   162589 }
   162590 
   162591 /*
   162592 ** Attempt to advance the node-reader object passed as the first argument to
   162593 ** the next entry on the node.
   162594 **
   162595 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
   162596 ** Otherwise return SQLITE_OK. If there is no next entry on the node
   162597 ** (e.g. because the current entry is the last) set NodeReader->aNode to
   162598 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
   162599 ** variables for the new entry.
   162600 */
   162601 static int nodeReaderNext(NodeReader *p){
   162602   int bFirst = (p->term.n==0);    /* True for first term on the node */
   162603   int nPrefix = 0;                /* Bytes to copy from previous term */
   162604   int nSuffix = 0;                /* Bytes to append to the prefix */
   162605   int rc = SQLITE_OK;             /* Return code */
   162606 
   162607   assert( p->aNode );
   162608   if( p->iChild && bFirst==0 ) p->iChild++;
   162609   if( p->iOff>=p->nNode ){
   162610     /* EOF */
   162611     p->aNode = 0;
   162612   }else{
   162613     if( bFirst==0 ){
   162614       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
   162615     }
   162616     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
   162617 
   162618     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
   162619     if( rc==SQLITE_OK ){
   162620       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
   162621       p->term.n = nPrefix+nSuffix;
   162622       p->iOff += nSuffix;
   162623       if( p->iChild==0 ){
   162624         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
   162625         p->aDoclist = &p->aNode[p->iOff];
   162626         p->iOff += p->nDoclist;
   162627       }
   162628     }
   162629   }
   162630 
   162631   assert( p->iOff<=p->nNode );
   162632 
   162633   return rc;
   162634 }
   162635 
   162636 /*
   162637 ** Release all dynamic resources held by node-reader object *p.
   162638 */
   162639 static void nodeReaderRelease(NodeReader *p){
   162640   sqlite3_free(p->term.a);
   162641 }
   162642 
   162643 /*
   162644 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
   162645 **
   162646 ** If successful, SQLITE_OK is returned and the NodeReader object set to
   162647 ** point to the first entry on the node (if any). Otherwise, an SQLite
   162648 ** error code is returned.
   162649 */
   162650 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
   162651   memset(p, 0, sizeof(NodeReader));
   162652   p->aNode = aNode;
   162653   p->nNode = nNode;
   162654 
   162655   /* Figure out if this is a leaf or an internal node. */
   162656   if( p->aNode[0] ){
   162657     /* An internal node. */
   162658     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
   162659   }else{
   162660     p->iOff = 1;
   162661   }
   162662 
   162663   return nodeReaderNext(p);
   162664 }
   162665 
   162666 /*
   162667 ** This function is called while writing an FTS segment each time a leaf o
   162668 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
   162669 ** to be greater than the largest key on the node just written, but smaller
   162670 ** than or equal to the first key that will be written to the next leaf
   162671 ** node.
   162672 **
   162673 ** The block id of the leaf node just written to disk may be found in
   162674 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
   162675 */
   162676 static int fts3IncrmergePush(
   162677   Fts3Table *p,                   /* Fts3 table handle */
   162678   IncrmergeWriter *pWriter,       /* Writer object */
   162679   const char *zTerm,              /* Term to write to internal node */
   162680   int nTerm                       /* Bytes at zTerm */
   162681 ){
   162682   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
   162683   int iLayer;
   162684 
   162685   assert( nTerm>0 );
   162686   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
   162687     sqlite3_int64 iNextPtr = 0;
   162688     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
   162689     int rc = SQLITE_OK;
   162690     int nPrefix;
   162691     int nSuffix;
   162692     int nSpace;
   162693 
   162694     /* Figure out how much space the key will consume if it is written to
   162695     ** the current node of layer iLayer. Due to the prefix compression,
   162696     ** the space required changes depending on which node the key is to
   162697     ** be added to.  */
   162698     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
   162699     nSuffix = nTerm - nPrefix;
   162700     nSpace  = sqlite3Fts3VarintLen(nPrefix);
   162701     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   162702 
   162703     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
   162704       /* If the current node of layer iLayer contains zero keys, or if adding
   162705       ** the key to it will not cause it to grow to larger than nNodeSize
   162706       ** bytes in size, write the key here.  */
   162707 
   162708       Blob *pBlk = &pNode->block;
   162709       if( pBlk->n==0 ){
   162710         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
   162711         if( rc==SQLITE_OK ){
   162712           pBlk->a[0] = (char)iLayer;
   162713           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
   162714         }
   162715       }
   162716       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
   162717       blobGrowBuffer(&pNode->key, nTerm, &rc);
   162718 
   162719       if( rc==SQLITE_OK ){
   162720         if( pNode->key.n ){
   162721           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
   162722         }
   162723         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
   162724         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
   162725         pBlk->n += nSuffix;
   162726 
   162727         memcpy(pNode->key.a, zTerm, nTerm);
   162728         pNode->key.n = nTerm;
   162729       }
   162730     }else{
   162731       /* Otherwise, flush the current node of layer iLayer to disk.
   162732       ** Then allocate a new, empty sibling node. The key will be written
   162733       ** into the parent of this node. */
   162734       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
   162735 
   162736       assert( pNode->block.nAlloc>=p->nNodeSize );
   162737       pNode->block.a[0] = (char)iLayer;
   162738       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
   162739 
   162740       iNextPtr = pNode->iBlock;
   162741       pNode->iBlock++;
   162742       pNode->key.n = 0;
   162743     }
   162744 
   162745     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
   162746     iPtr = iNextPtr;
   162747   }
   162748 
   162749   assert( 0 );
   162750   return 0;
   162751 }
   162752 
   162753 /*
   162754 ** Append a term and (optionally) doclist to the FTS segment node currently
   162755 ** stored in blob *pNode. The node need not contain any terms, but the
   162756 ** header must be written before this function is called.
   162757 **
   162758 ** A node header is a single 0x00 byte for a leaf node, or a height varint
   162759 ** followed by the left-hand-child varint for an internal node.
   162760 **
   162761 ** The term to be appended is passed via arguments zTerm/nTerm. For a
   162762 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
   162763 ** node, both aDoclist and nDoclist must be passed 0.
   162764 **
   162765 ** If the size of the value in blob pPrev is zero, then this is the first
   162766 ** term written to the node. Otherwise, pPrev contains a copy of the
   162767 ** previous term. Before this function returns, it is updated to contain a
   162768 ** copy of zTerm/nTerm.
   162769 **
   162770 ** It is assumed that the buffer associated with pNode is already large
   162771 ** enough to accommodate the new entry. The buffer associated with pPrev
   162772 ** is extended by this function if requrired.
   162773 **
   162774 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
   162775 ** returned. Otherwise, SQLITE_OK.
   162776 */
   162777 static int fts3AppendToNode(
   162778   Blob *pNode,                    /* Current node image to append to */
   162779   Blob *pPrev,                    /* Buffer containing previous term written */
   162780   const char *zTerm,              /* New term to write */
   162781   int nTerm,                      /* Size of zTerm in bytes */
   162782   const char *aDoclist,           /* Doclist (or NULL) to write */
   162783   int nDoclist                    /* Size of aDoclist in bytes */
   162784 ){
   162785   int rc = SQLITE_OK;             /* Return code */
   162786   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
   162787   int nPrefix;                    /* Size of term prefix in bytes */
   162788   int nSuffix;                    /* Size of term suffix in bytes */
   162789 
   162790   /* Node must have already been started. There must be a doclist for a
   162791   ** leaf node, and there must not be a doclist for an internal node.  */
   162792   assert( pNode->n>0 );
   162793   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
   162794 
   162795   blobGrowBuffer(pPrev, nTerm, &rc);
   162796   if( rc!=SQLITE_OK ) return rc;
   162797 
   162798   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
   162799   nSuffix = nTerm - nPrefix;
   162800   memcpy(pPrev->a, zTerm, nTerm);
   162801   pPrev->n = nTerm;
   162802 
   162803   if( bFirst==0 ){
   162804     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
   162805   }
   162806   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
   162807   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
   162808   pNode->n += nSuffix;
   162809 
   162810   if( aDoclist ){
   162811     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
   162812     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
   162813     pNode->n += nDoclist;
   162814   }
   162815 
   162816   assert( pNode->n<=pNode->nAlloc );
   162817 
   162818   return SQLITE_OK;
   162819 }
   162820 
   162821 /*
   162822 ** Append the current term and doclist pointed to by cursor pCsr to the
   162823 ** appendable b-tree segment opened for writing by pWriter.
   162824 **
   162825 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
   162826 */
   162827 static int fts3IncrmergeAppend(
   162828   Fts3Table *p,                   /* Fts3 table handle */
   162829   IncrmergeWriter *pWriter,       /* Writer object */
   162830   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
   162831 ){
   162832   const char *zTerm = pCsr->zTerm;
   162833   int nTerm = pCsr->nTerm;
   162834   const char *aDoclist = pCsr->aDoclist;
   162835   int nDoclist = pCsr->nDoclist;
   162836   int rc = SQLITE_OK;           /* Return code */
   162837   int nSpace;                   /* Total space in bytes required on leaf */
   162838   int nPrefix;                  /* Size of prefix shared with previous term */
   162839   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
   162840   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
   162841 
   162842   pLeaf = &pWriter->aNodeWriter[0];
   162843   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
   162844   nSuffix = nTerm - nPrefix;
   162845 
   162846   nSpace  = sqlite3Fts3VarintLen(nPrefix);
   162847   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   162848   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
   162849 
   162850   /* If the current block is not empty, and if adding this term/doclist
   162851   ** to the current block would make it larger than Fts3Table.nNodeSize
   162852   ** bytes, write this block out to the database. */
   162853   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
   162854     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
   162855     pWriter->nWork++;
   162856 
   162857     /* Add the current term to the parent node. The term added to the
   162858     ** parent must:
   162859     **
   162860     **   a) be greater than the largest term on the leaf node just written
   162861     **      to the database (still available in pLeaf->key), and
   162862     **
   162863     **   b) be less than or equal to the term about to be added to the new
   162864     **      leaf node (zTerm/nTerm).
   162865     **
   162866     ** In other words, it must be the prefix of zTerm 1 byte longer than
   162867     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   162868     */
   162869     if( rc==SQLITE_OK ){
   162870       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
   162871     }
   162872 
   162873     /* Advance to the next output block */
   162874     pLeaf->iBlock++;
   162875     pLeaf->key.n = 0;
   162876     pLeaf->block.n = 0;
   162877 
   162878     nSuffix = nTerm;
   162879     nSpace  = 1;
   162880     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
   162881     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
   162882   }
   162883 
   162884   pWriter->nLeafData += nSpace;
   162885   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
   162886   if( rc==SQLITE_OK ){
   162887     if( pLeaf->block.n==0 ){
   162888       pLeaf->block.n = 1;
   162889       pLeaf->block.a[0] = '\0';
   162890     }
   162891     rc = fts3AppendToNode(
   162892         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
   162893     );
   162894   }
   162895 
   162896   return rc;
   162897 }
   162898 
   162899 /*
   162900 ** This function is called to release all dynamic resources held by the
   162901 ** merge-writer object pWriter, and if no error has occurred, to flush
   162902 ** all outstanding node buffers held by pWriter to disk.
   162903 **
   162904 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
   162905 ** is made to write any data to disk. Instead, this function serves only
   162906 ** to release outstanding resources.
   162907 **
   162908 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
   162909 ** flushing buffers to disk, *pRc is set to an SQLite error code before
   162910 ** returning.
   162911 */
   162912 static void fts3IncrmergeRelease(
   162913   Fts3Table *p,                   /* FTS3 table handle */
   162914   IncrmergeWriter *pWriter,       /* Merge-writer object */
   162915   int *pRc                        /* IN/OUT: Error code */
   162916 ){
   162917   int i;                          /* Used to iterate through non-root layers */
   162918   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
   162919   NodeWriter *pRoot;              /* NodeWriter for root node */
   162920   int rc = *pRc;                  /* Error code */
   162921 
   162922   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
   162923   ** root node. If the segment fits entirely on a single leaf node, iRoot
   162924   ** will be set to 0. If the root node is the parent of the leaves, iRoot
   162925   ** will be 1. And so on.  */
   162926   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
   162927     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
   162928     if( pNode->block.n>0 ) break;
   162929     assert( *pRc || pNode->block.nAlloc==0 );
   162930     assert( *pRc || pNode->key.nAlloc==0 );
   162931     sqlite3_free(pNode->block.a);
   162932     sqlite3_free(pNode->key.a);
   162933   }
   162934 
   162935   /* Empty output segment. This is a no-op. */
   162936   if( iRoot<0 ) return;
   162937 
   162938   /* The entire output segment fits on a single node. Normally, this means
   162939   ** the node would be stored as a blob in the "root" column of the %_segdir
   162940   ** table. However, this is not permitted in this case. The problem is that
   162941   ** space has already been reserved in the %_segments table, and so the
   162942   ** start_block and end_block fields of the %_segdir table must be populated.
   162943   ** And, by design or by accident, released versions of FTS cannot handle
   162944   ** segments that fit entirely on the root node with start_block!=0.
   162945   **
   162946   ** Instead, create a synthetic root node that contains nothing but a
   162947   ** pointer to the single content node. So that the segment consists of a
   162948   ** single leaf and a single interior (root) node.
   162949   **
   162950   ** Todo: Better might be to defer allocating space in the %_segments
   162951   ** table until we are sure it is needed.
   162952   */
   162953   if( iRoot==0 ){
   162954     Blob *pBlock = &pWriter->aNodeWriter[1].block;
   162955     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
   162956     if( rc==SQLITE_OK ){
   162957       pBlock->a[0] = 0x01;
   162958       pBlock->n = 1 + sqlite3Fts3PutVarint(
   162959           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
   162960       );
   162961     }
   162962     iRoot = 1;
   162963   }
   162964   pRoot = &pWriter->aNodeWriter[iRoot];
   162965 
   162966   /* Flush all currently outstanding nodes to disk. */
   162967   for(i=0; i<iRoot; i++){
   162968     NodeWriter *pNode = &pWriter->aNodeWriter[i];
   162969     if( pNode->block.n>0 && rc==SQLITE_OK ){
   162970       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
   162971     }
   162972     sqlite3_free(pNode->block.a);
   162973     sqlite3_free(pNode->key.a);
   162974   }
   162975 
   162976   /* Write the %_segdir record. */
   162977   if( rc==SQLITE_OK ){
   162978     rc = fts3WriteSegdir(p,
   162979         pWriter->iAbsLevel+1,               /* level */
   162980         pWriter->iIdx,                      /* idx */
   162981         pWriter->iStart,                    /* start_block */
   162982         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
   162983         pWriter->iEnd,                      /* end_block */
   162984         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
   162985         pRoot->block.a, pRoot->block.n      /* root */
   162986     );
   162987   }
   162988   sqlite3_free(pRoot->block.a);
   162989   sqlite3_free(pRoot->key.a);
   162990 
   162991   *pRc = rc;
   162992 }
   162993 
   162994 /*
   162995 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
   162996 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
   162997 ** the other, it is considered to be smaller than the other.
   162998 **
   162999 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
   163000 ** if it is greater.
   163001 */
   163002 static int fts3TermCmp(
   163003   const char *zLhs, int nLhs,     /* LHS of comparison */
   163004   const char *zRhs, int nRhs      /* RHS of comparison */
   163005 ){
   163006   int nCmp = MIN(nLhs, nRhs);
   163007   int res;
   163008 
   163009   res = memcmp(zLhs, zRhs, nCmp);
   163010   if( res==0 ) res = nLhs - nRhs;
   163011 
   163012   return res;
   163013 }
   163014 
   163015 
   163016 /*
   163017 ** Query to see if the entry in the %_segments table with blockid iEnd is
   163018 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
   163019 ** returning. Otherwise, set *pbRes to 0.
   163020 **
   163021 ** Or, if an error occurs while querying the database, return an SQLite
   163022 ** error code. The final value of *pbRes is undefined in this case.
   163023 **
   163024 ** This is used to test if a segment is an "appendable" segment. If it
   163025 ** is, then a NULL entry has been inserted into the %_segments table
   163026 ** with blockid %_segdir.end_block.
   163027 */
   163028 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
   163029   int bRes = 0;                   /* Result to set *pbRes to */
   163030   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
   163031   int rc;                         /* Return code */
   163032 
   163033   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
   163034   if( rc==SQLITE_OK ){
   163035     sqlite3_bind_int64(pCheck, 1, iEnd);
   163036     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
   163037     rc = sqlite3_reset(pCheck);
   163038   }
   163039 
   163040   *pbRes = bRes;
   163041   return rc;
   163042 }
   163043 
   163044 /*
   163045 ** This function is called when initializing an incremental-merge operation.
   163046 ** It checks if the existing segment with index value iIdx at absolute level
   163047 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
   163048 ** merge-writer object *pWriter is initialized to write to it.
   163049 **
   163050 ** An existing segment can be appended to by an incremental merge if:
   163051 **
   163052 **   * It was initially created as an appendable segment (with all required
   163053 **     space pre-allocated), and
   163054 **
   163055 **   * The first key read from the input (arguments zKey and nKey) is
   163056 **     greater than the largest key currently stored in the potential
   163057 **     output segment.
   163058 */
   163059 static int fts3IncrmergeLoad(
   163060   Fts3Table *p,                   /* Fts3 table handle */
   163061   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
   163062   int iIdx,                       /* Index of candidate output segment */
   163063   const char *zKey,               /* First key to write */
   163064   int nKey,                       /* Number of bytes in nKey */
   163065   IncrmergeWriter *pWriter        /* Populate this object */
   163066 ){
   163067   int rc;                         /* Return code */
   163068   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
   163069 
   163070   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
   163071   if( rc==SQLITE_OK ){
   163072     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
   163073     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
   163074     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
   163075     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
   163076     int nRoot = 0;                /* Size of aRoot[] in bytes */
   163077     int rc2;                      /* Return code from sqlite3_reset() */
   163078     int bAppendable = 0;          /* Set to true if segment is appendable */
   163079 
   163080     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
   163081     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
   163082     sqlite3_bind_int(pSelect, 2, iIdx);
   163083     if( sqlite3_step(pSelect)==SQLITE_ROW ){
   163084       iStart = sqlite3_column_int64(pSelect, 1);
   163085       iLeafEnd = sqlite3_column_int64(pSelect, 2);
   163086       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
   163087       if( pWriter->nLeafData<0 ){
   163088         pWriter->nLeafData = pWriter->nLeafData * -1;
   163089       }
   163090       pWriter->bNoLeafData = (pWriter->nLeafData==0);
   163091       nRoot = sqlite3_column_bytes(pSelect, 4);
   163092       aRoot = sqlite3_column_blob(pSelect, 4);
   163093     }else{
   163094       return sqlite3_reset(pSelect);
   163095     }
   163096 
   163097     /* Check for the zero-length marker in the %_segments table */
   163098     rc = fts3IsAppendable(p, iEnd, &bAppendable);
   163099 
   163100     /* Check that zKey/nKey is larger than the largest key the candidate */
   163101     if( rc==SQLITE_OK && bAppendable ){
   163102       char *aLeaf = 0;
   163103       int nLeaf = 0;
   163104 
   163105       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
   163106       if( rc==SQLITE_OK ){
   163107         NodeReader reader;
   163108         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
   163109             rc==SQLITE_OK && reader.aNode;
   163110             rc = nodeReaderNext(&reader)
   163111         ){
   163112           assert( reader.aNode );
   163113         }
   163114         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
   163115           bAppendable = 0;
   163116         }
   163117         nodeReaderRelease(&reader);
   163118       }
   163119       sqlite3_free(aLeaf);
   163120     }
   163121 
   163122     if( rc==SQLITE_OK && bAppendable ){
   163123       /* It is possible to append to this segment. Set up the IncrmergeWriter
   163124       ** object to do so.  */
   163125       int i;
   163126       int nHeight = (int)aRoot[0];
   163127       NodeWriter *pNode;
   163128 
   163129       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
   163130       pWriter->iStart = iStart;
   163131       pWriter->iEnd = iEnd;
   163132       pWriter->iAbsLevel = iAbsLevel;
   163133       pWriter->iIdx = iIdx;
   163134 
   163135       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
   163136         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
   163137       }
   163138 
   163139       pNode = &pWriter->aNodeWriter[nHeight];
   163140       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
   163141       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
   163142       if( rc==SQLITE_OK ){
   163143         memcpy(pNode->block.a, aRoot, nRoot);
   163144         pNode->block.n = nRoot;
   163145       }
   163146 
   163147       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
   163148         NodeReader reader;
   163149         pNode = &pWriter->aNodeWriter[i];
   163150 
   163151         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
   163152         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
   163153         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
   163154         if( rc==SQLITE_OK ){
   163155           memcpy(pNode->key.a, reader.term.a, reader.term.n);
   163156           pNode->key.n = reader.term.n;
   163157           if( i>0 ){
   163158             char *aBlock = 0;
   163159             int nBlock = 0;
   163160             pNode = &pWriter->aNodeWriter[i-1];
   163161             pNode->iBlock = reader.iChild;
   163162             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
   163163             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
   163164             if( rc==SQLITE_OK ){
   163165               memcpy(pNode->block.a, aBlock, nBlock);
   163166               pNode->block.n = nBlock;
   163167             }
   163168             sqlite3_free(aBlock);
   163169           }
   163170         }
   163171         nodeReaderRelease(&reader);
   163172       }
   163173     }
   163174 
   163175     rc2 = sqlite3_reset(pSelect);
   163176     if( rc==SQLITE_OK ) rc = rc2;
   163177   }
   163178 
   163179   return rc;
   163180 }
   163181 
   163182 /*
   163183 ** Determine the largest segment index value that exists within absolute
   163184 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
   163185 ** one before returning SQLITE_OK. Or, if there are no segments at all
   163186 ** within level iAbsLevel, set *piIdx to zero.
   163187 **
   163188 ** If an error occurs, return an SQLite error code. The final value of
   163189 ** *piIdx is undefined in this case.
   163190 */
   163191 static int fts3IncrmergeOutputIdx(
   163192   Fts3Table *p,                   /* FTS Table handle */
   163193   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
   163194   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
   163195 ){
   163196   int rc;
   163197   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
   163198 
   163199   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
   163200   if( rc==SQLITE_OK ){
   163201     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
   163202     sqlite3_step(pOutputIdx);
   163203     *piIdx = sqlite3_column_int(pOutputIdx, 0);
   163204     rc = sqlite3_reset(pOutputIdx);
   163205   }
   163206 
   163207   return rc;
   163208 }
   163209 
   163210 /*
   163211 ** Allocate an appendable output segment on absolute level iAbsLevel+1
   163212 ** with idx value iIdx.
   163213 **
   163214 ** In the %_segdir table, a segment is defined by the values in three
   163215 ** columns:
   163216 **
   163217 **     start_block
   163218 **     leaves_end_block
   163219 **     end_block
   163220 **
   163221 ** When an appendable segment is allocated, it is estimated that the
   163222 ** maximum number of leaf blocks that may be required is the sum of the
   163223 ** number of leaf blocks consumed by the input segments, plus the number
   163224 ** of input segments, multiplied by two. This value is stored in stack
   163225 ** variable nLeafEst.
   163226 **
   163227 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
   163228 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
   163229 ** array of leaf nodes starts at the first block allocated. The array
   163230 ** of interior nodes that are parents of the leaf nodes start at block
   163231 ** (start_block + (1 + end_block - start_block) / 16). And so on.
   163232 **
   163233 ** In the actual code below, the value "16" is replaced with the
   163234 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
   163235 */
   163236 static int fts3IncrmergeWriter(
   163237   Fts3Table *p,                   /* Fts3 table handle */
   163238   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
   163239   int iIdx,                       /* Index of new output segment */
   163240   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
   163241   IncrmergeWriter *pWriter        /* Populate this object */
   163242 ){
   163243   int rc;                         /* Return Code */
   163244   int i;                          /* Iterator variable */
   163245   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
   163246   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
   163247   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
   163248 
   163249   /* Calculate nLeafEst. */
   163250   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
   163251   if( rc==SQLITE_OK ){
   163252     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
   163253     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
   163254     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
   163255       nLeafEst = sqlite3_column_int(pLeafEst, 0);
   163256     }
   163257     rc = sqlite3_reset(pLeafEst);
   163258   }
   163259   if( rc!=SQLITE_OK ) return rc;
   163260 
   163261   /* Calculate the first block to use in the output segment */
   163262   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
   163263   if( rc==SQLITE_OK ){
   163264     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
   163265       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
   163266       pWriter->iEnd = pWriter->iStart - 1;
   163267       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
   163268     }
   163269     rc = sqlite3_reset(pFirstBlock);
   163270   }
   163271   if( rc!=SQLITE_OK ) return rc;
   163272 
   163273   /* Insert the marker in the %_segments table to make sure nobody tries
   163274   ** to steal the space just allocated. This is also used to identify
   163275   ** appendable segments.  */
   163276   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
   163277   if( rc!=SQLITE_OK ) return rc;
   163278 
   163279   pWriter->iAbsLevel = iAbsLevel;
   163280   pWriter->nLeafEst = nLeafEst;
   163281   pWriter->iIdx = iIdx;
   163282 
   163283   /* Set up the array of NodeWriter objects */
   163284   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
   163285     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
   163286   }
   163287   return SQLITE_OK;
   163288 }
   163289 
   163290 /*
   163291 ** Remove an entry from the %_segdir table. This involves running the
   163292 ** following two statements:
   163293 **
   163294 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
   163295 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
   163296 **
   163297 ** The DELETE statement removes the specific %_segdir level. The UPDATE
   163298 ** statement ensures that the remaining segments have contiguously allocated
   163299 ** idx values.
   163300 */
   163301 static int fts3RemoveSegdirEntry(
   163302   Fts3Table *p,                   /* FTS3 table handle */
   163303   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
   163304   int iIdx                        /* Index of %_segdir entry to delete */
   163305 ){
   163306   int rc;                         /* Return code */
   163307   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
   163308 
   163309   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
   163310   if( rc==SQLITE_OK ){
   163311     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
   163312     sqlite3_bind_int(pDelete, 2, iIdx);
   163313     sqlite3_step(pDelete);
   163314     rc = sqlite3_reset(pDelete);
   163315   }
   163316 
   163317   return rc;
   163318 }
   163319 
   163320 /*
   163321 ** One or more segments have just been removed from absolute level iAbsLevel.
   163322 ** Update the 'idx' values of the remaining segments in the level so that
   163323 ** the idx values are a contiguous sequence starting from 0.
   163324 */
   163325 static int fts3RepackSegdirLevel(
   163326   Fts3Table *p,                   /* FTS3 table handle */
   163327   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
   163328 ){
   163329   int rc;                         /* Return code */
   163330   int *aIdx = 0;                  /* Array of remaining idx values */
   163331   int nIdx = 0;                   /* Valid entries in aIdx[] */
   163332   int nAlloc = 0;                 /* Allocated size of aIdx[] */
   163333   int i;                          /* Iterator variable */
   163334   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
   163335   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
   163336 
   163337   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
   163338   if( rc==SQLITE_OK ){
   163339     int rc2;
   163340     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
   163341     while( SQLITE_ROW==sqlite3_step(pSelect) ){
   163342       if( nIdx>=nAlloc ){
   163343         int *aNew;
   163344         nAlloc += 16;
   163345         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
   163346         if( !aNew ){
   163347           rc = SQLITE_NOMEM;
   163348           break;
   163349         }
   163350         aIdx = aNew;
   163351       }
   163352       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
   163353     }
   163354     rc2 = sqlite3_reset(pSelect);
   163355     if( rc==SQLITE_OK ) rc = rc2;
   163356   }
   163357 
   163358   if( rc==SQLITE_OK ){
   163359     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
   163360   }
   163361   if( rc==SQLITE_OK ){
   163362     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
   163363   }
   163364 
   163365   assert( p->bIgnoreSavepoint==0 );
   163366   p->bIgnoreSavepoint = 1;
   163367   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
   163368     if( aIdx[i]!=i ){
   163369       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
   163370       sqlite3_bind_int(pUpdate, 1, i);
   163371       sqlite3_step(pUpdate);
   163372       rc = sqlite3_reset(pUpdate);
   163373     }
   163374   }
   163375   p->bIgnoreSavepoint = 0;
   163376 
   163377   sqlite3_free(aIdx);
   163378   return rc;
   163379 }
   163380 
   163381 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
   163382   pNode->a[0] = (char)iHeight;
   163383   if( iChild ){
   163384     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
   163385     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
   163386   }else{
   163387     assert( pNode->nAlloc>=1 );
   163388     pNode->n = 1;
   163389   }
   163390 }
   163391 
   163392 /*
   163393 ** The first two arguments are a pointer to and the size of a segment b-tree
   163394 ** node. The node may be a leaf or an internal node.
   163395 **
   163396 ** This function creates a new node image in blob object *pNew by copying
   163397 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
   163398 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
   163399 */
   163400 static int fts3TruncateNode(
   163401   const char *aNode,              /* Current node image */
   163402   int nNode,                      /* Size of aNode in bytes */
   163403   Blob *pNew,                     /* OUT: Write new node image here */
   163404   const char *zTerm,              /* Omit all terms smaller than this */
   163405   int nTerm,                      /* Size of zTerm in bytes */
   163406   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
   163407 ){
   163408   NodeReader reader;              /* Reader object */
   163409   Blob prev = {0, 0, 0};          /* Previous term written to new node */
   163410   int rc = SQLITE_OK;             /* Return code */
   163411   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
   163412 
   163413   /* Allocate required output space */
   163414   blobGrowBuffer(pNew, nNode, &rc);
   163415   if( rc!=SQLITE_OK ) return rc;
   163416   pNew->n = 0;
   163417 
   163418   /* Populate new node buffer */
   163419   for(rc = nodeReaderInit(&reader, aNode, nNode);
   163420       rc==SQLITE_OK && reader.aNode;
   163421       rc = nodeReaderNext(&reader)
   163422   ){
   163423     if( pNew->n==0 ){
   163424       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
   163425       if( res<0 || (bLeaf==0 && res==0) ) continue;
   163426       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
   163427       *piBlock = reader.iChild;
   163428     }
   163429     rc = fts3AppendToNode(
   163430         pNew, &prev, reader.term.a, reader.term.n,
   163431         reader.aDoclist, reader.nDoclist
   163432     );
   163433     if( rc!=SQLITE_OK ) break;
   163434   }
   163435   if( pNew->n==0 ){
   163436     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
   163437     *piBlock = reader.iChild;
   163438   }
   163439   assert( pNew->n<=pNew->nAlloc );
   163440 
   163441   nodeReaderRelease(&reader);
   163442   sqlite3_free(prev.a);
   163443   return rc;
   163444 }
   163445 
   163446 /*
   163447 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
   163448 ** level iAbsLevel. This may involve deleting entries from the %_segments
   163449 ** table, and modifying existing entries in both the %_segments and %_segdir
   163450 ** tables.
   163451 **
   163452 ** SQLITE_OK is returned if the segment is updated successfully. Or an
   163453 ** SQLite error code otherwise.
   163454 */
   163455 static int fts3TruncateSegment(
   163456   Fts3Table *p,                   /* FTS3 table handle */
   163457   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
   163458   int iIdx,                       /* Index within level of segment to modify */
   163459   const char *zTerm,              /* Remove terms smaller than this */
   163460   int nTerm                      /* Number of bytes in buffer zTerm */
   163461 ){
   163462   int rc = SQLITE_OK;             /* Return code */
   163463   Blob root = {0,0,0};            /* New root page image */
   163464   Blob block = {0,0,0};           /* Buffer used for any other block */
   163465   sqlite3_int64 iBlock = 0;       /* Block id */
   163466   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
   163467   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
   163468   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
   163469 
   163470   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
   163471   if( rc==SQLITE_OK ){
   163472     int rc2;                      /* sqlite3_reset() return code */
   163473     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
   163474     sqlite3_bind_int(pFetch, 2, iIdx);
   163475     if( SQLITE_ROW==sqlite3_step(pFetch) ){
   163476       const char *aRoot = sqlite3_column_blob(pFetch, 4);
   163477       int nRoot = sqlite3_column_bytes(pFetch, 4);
   163478       iOldStart = sqlite3_column_int64(pFetch, 1);
   163479       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
   163480     }
   163481     rc2 = sqlite3_reset(pFetch);
   163482     if( rc==SQLITE_OK ) rc = rc2;
   163483   }
   163484 
   163485   while( rc==SQLITE_OK && iBlock ){
   163486     char *aBlock = 0;
   163487     int nBlock = 0;
   163488     iNewStart = iBlock;
   163489 
   163490     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
   163491     if( rc==SQLITE_OK ){
   163492       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
   163493     }
   163494     if( rc==SQLITE_OK ){
   163495       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
   163496     }
   163497     sqlite3_free(aBlock);
   163498   }
   163499 
   163500   /* Variable iNewStart now contains the first valid leaf node. */
   163501   if( rc==SQLITE_OK && iNewStart ){
   163502     sqlite3_stmt *pDel = 0;
   163503     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
   163504     if( rc==SQLITE_OK ){
   163505       sqlite3_bind_int64(pDel, 1, iOldStart);
   163506       sqlite3_bind_int64(pDel, 2, iNewStart-1);
   163507       sqlite3_step(pDel);
   163508       rc = sqlite3_reset(pDel);
   163509     }
   163510   }
   163511 
   163512   if( rc==SQLITE_OK ){
   163513     sqlite3_stmt *pChomp = 0;
   163514     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
   163515     if( rc==SQLITE_OK ){
   163516       sqlite3_bind_int64(pChomp, 1, iNewStart);
   163517       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
   163518       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
   163519       sqlite3_bind_int(pChomp, 4, iIdx);
   163520       sqlite3_step(pChomp);
   163521       rc = sqlite3_reset(pChomp);
   163522     }
   163523   }
   163524 
   163525   sqlite3_free(root.a);
   163526   sqlite3_free(block.a);
   163527   return rc;
   163528 }
   163529 
   163530 /*
   163531 ** This function is called after an incrmental-merge operation has run to
   163532 ** merge (or partially merge) two or more segments from absolute level
   163533 ** iAbsLevel.
   163534 **
   163535 ** Each input segment is either removed from the db completely (if all of
   163536 ** its data was copied to the output segment by the incrmerge operation)
   163537 ** or modified in place so that it no longer contains those entries that
   163538 ** have been duplicated in the output segment.
   163539 */
   163540 static int fts3IncrmergeChomp(
   163541   Fts3Table *p,                   /* FTS table handle */
   163542   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
   163543   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
   163544   int *pnRem                      /* Number of segments not deleted */
   163545 ){
   163546   int i;
   163547   int nRem = 0;
   163548   int rc = SQLITE_OK;
   163549 
   163550   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
   163551     Fts3SegReader *pSeg = 0;
   163552     int j;
   163553 
   163554     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
   163555     ** somewhere in the pCsr->apSegment[] array.  */
   163556     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
   163557       pSeg = pCsr->apSegment[j];
   163558       if( pSeg->iIdx==i ) break;
   163559     }
   163560     assert( j<pCsr->nSegment && pSeg->iIdx==i );
   163561 
   163562     if( pSeg->aNode==0 ){
   163563       /* Seg-reader is at EOF. Remove the entire input segment. */
   163564       rc = fts3DeleteSegment(p, pSeg);
   163565       if( rc==SQLITE_OK ){
   163566         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
   163567       }
   163568       *pnRem = 0;
   163569     }else{
   163570       /* The incremental merge did not copy all the data from this
   163571       ** segment to the upper level. The segment is modified in place
   163572       ** so that it contains no keys smaller than zTerm/nTerm. */
   163573       const char *zTerm = pSeg->zTerm;
   163574       int nTerm = pSeg->nTerm;
   163575       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
   163576       nRem++;
   163577     }
   163578   }
   163579 
   163580   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
   163581     rc = fts3RepackSegdirLevel(p, iAbsLevel);
   163582   }
   163583 
   163584   *pnRem = nRem;
   163585   return rc;
   163586 }
   163587 
   163588 /*
   163589 ** Store an incr-merge hint in the database.
   163590 */
   163591 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
   163592   sqlite3_stmt *pReplace = 0;
   163593   int rc;                         /* Return code */
   163594 
   163595   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
   163596   if( rc==SQLITE_OK ){
   163597     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
   163598     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
   163599     sqlite3_step(pReplace);
   163600     rc = sqlite3_reset(pReplace);
   163601   }
   163602 
   163603   return rc;
   163604 }
   163605 
   163606 /*
   163607 ** Load an incr-merge hint from the database. The incr-merge hint, if one
   163608 ** exists, is stored in the rowid==1 row of the %_stat table.
   163609 **
   163610 ** If successful, populate blob *pHint with the value read from the %_stat
   163611 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
   163612 ** SQLite error code.
   163613 */
   163614 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
   163615   sqlite3_stmt *pSelect = 0;
   163616   int rc;
   163617 
   163618   pHint->n = 0;
   163619   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
   163620   if( rc==SQLITE_OK ){
   163621     int rc2;
   163622     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
   163623     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   163624       const char *aHint = sqlite3_column_blob(pSelect, 0);
   163625       int nHint = sqlite3_column_bytes(pSelect, 0);
   163626       if( aHint ){
   163627         blobGrowBuffer(pHint, nHint, &rc);
   163628         if( rc==SQLITE_OK ){
   163629           memcpy(pHint->a, aHint, nHint);
   163630           pHint->n = nHint;
   163631         }
   163632       }
   163633     }
   163634     rc2 = sqlite3_reset(pSelect);
   163635     if( rc==SQLITE_OK ) rc = rc2;
   163636   }
   163637 
   163638   return rc;
   163639 }
   163640 
   163641 /*
   163642 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   163643 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
   163644 ** consists of two varints, the absolute level number of the input segments
   163645 ** and the number of input segments.
   163646 **
   163647 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
   163648 ** set *pRc to an SQLite error code before returning.
   163649 */
   163650 static void fts3IncrmergeHintPush(
   163651   Blob *pHint,                    /* Hint blob to append to */
   163652   i64 iAbsLevel,                  /* First varint to store in hint */
   163653   int nInput,                     /* Second varint to store in hint */
   163654   int *pRc                        /* IN/OUT: Error code */
   163655 ){
   163656   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
   163657   if( *pRc==SQLITE_OK ){
   163658     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
   163659     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
   163660   }
   163661 }
   163662 
   163663 /*
   163664 ** Read the last entry (most recently pushed) from the hint blob *pHint
   163665 ** and then remove the entry. Write the two values read to *piAbsLevel and
   163666 ** *pnInput before returning.
   163667 **
   163668 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
   163669 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
   163670 */
   163671 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
   163672   const int nHint = pHint->n;
   163673   int i;
   163674 
   163675   i = pHint->n-2;
   163676   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
   163677   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
   163678 
   163679   pHint->n = i;
   163680   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
   163681   i += fts3GetVarint32(&pHint->a[i], pnInput);
   163682   if( i!=nHint ) return FTS_CORRUPT_VTAB;
   163683 
   163684   return SQLITE_OK;
   163685 }
   163686 
   163687 
   163688 /*
   163689 ** Attempt an incremental merge that writes nMerge leaf blocks.
   163690 **
   163691 ** Incremental merges happen nMin segments at a time. The segments
   163692 ** to be merged are the nMin oldest segments (the ones with the smallest
   163693 ** values for the _segdir.idx field) in the highest level that contains
   163694 ** at least nMin segments. Multiple merges might occur in an attempt to
   163695 ** write the quota of nMerge leaf blocks.
   163696 */
   163697 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
   163698   int rc;                         /* Return code */
   163699   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
   163700   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
   163701   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
   163702   IncrmergeWriter *pWriter;       /* Writer object */
   163703   int nSeg = 0;                   /* Number of input segments */
   163704   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
   163705   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
   163706   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
   163707 
   163708   /* Allocate space for the cursor, filter and writer objects */
   163709   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
   163710   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
   163711   if( !pWriter ) return SQLITE_NOMEM;
   163712   pFilter = (Fts3SegFilter *)&pWriter[1];
   163713   pCsr = (Fts3MultiSegReader *)&pFilter[1];
   163714 
   163715   rc = fts3IncrmergeHintLoad(p, &hint);
   163716   while( rc==SQLITE_OK && nRem>0 ){
   163717     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
   163718     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
   163719     int bUseHint = 0;             /* True if attempting to append */
   163720     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
   163721 
   163722     /* Search the %_segdir table for the absolute level with the smallest
   163723     ** relative level number that contains at least nMin segments, if any.
   163724     ** If one is found, set iAbsLevel to the absolute level number and
   163725     ** nSeg to nMin. If no level with at least nMin segments can be found,
   163726     ** set nSeg to -1.
   163727     */
   163728     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
   163729     sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
   163730     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
   163731       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
   163732       nSeg = sqlite3_column_int(pFindLevel, 1);
   163733       assert( nSeg>=2 );
   163734     }else{
   163735       nSeg = -1;
   163736     }
   163737     rc = sqlite3_reset(pFindLevel);
   163738 
   163739     /* If the hint read from the %_stat table is not empty, check if the
   163740     ** last entry in it specifies a relative level smaller than or equal
   163741     ** to the level identified by the block above (if any). If so, this
   163742     ** iteration of the loop will work on merging at the hinted level.
   163743     */
   163744     if( rc==SQLITE_OK && hint.n ){
   163745       int nHint = hint.n;
   163746       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
   163747       int nHintSeg = 0;                     /* Hint number of segments */
   163748 
   163749       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
   163750       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
   163751         iAbsLevel = iHintAbsLevel;
   163752         nSeg = nHintSeg;
   163753         bUseHint = 1;
   163754         bDirtyHint = 1;
   163755       }else{
   163756         /* This undoes the effect of the HintPop() above - so that no entry
   163757         ** is removed from the hint blob.  */
   163758         hint.n = nHint;
   163759       }
   163760     }
   163761 
   163762     /* If nSeg is less that zero, then there is no level with at least
   163763     ** nMin segments and no hint in the %_stat table. No work to do.
   163764     ** Exit early in this case.  */
   163765     if( nSeg<0 ) break;
   163766 
   163767     /* Open a cursor to iterate through the contents of the oldest nSeg
   163768     ** indexes of absolute level iAbsLevel. If this cursor is opened using
   163769     ** the 'hint' parameters, it is possible that there are less than nSeg
   163770     ** segments available in level iAbsLevel. In this case, no work is
   163771     ** done on iAbsLevel - fall through to the next iteration of the loop
   163772     ** to start work on some other level.  */
   163773     memset(pWriter, 0, nAlloc);
   163774     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
   163775 
   163776     if( rc==SQLITE_OK ){
   163777       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
   163778       assert( bUseHint==1 || bUseHint==0 );
   163779       if( iIdx==0 || (bUseHint && iIdx==1) ){
   163780         int bIgnore = 0;
   163781         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
   163782         if( bIgnore ){
   163783           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
   163784         }
   163785       }
   163786     }
   163787 
   163788     if( rc==SQLITE_OK ){
   163789       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
   163790     }
   163791     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
   163792      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
   163793      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
   163794     ){
   163795       if( bUseHint && iIdx>0 ){
   163796         const char *zKey = pCsr->zTerm;
   163797         int nKey = pCsr->nTerm;
   163798         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
   163799       }else{
   163800         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
   163801       }
   163802 
   163803       if( rc==SQLITE_OK && pWriter->nLeafEst ){
   163804         fts3LogMerge(nSeg, iAbsLevel);
   163805         do {
   163806           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
   163807           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
   163808           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
   163809         }while( rc==SQLITE_ROW );
   163810 
   163811         /* Update or delete the input segments */
   163812         if( rc==SQLITE_OK ){
   163813           nRem -= (1 + pWriter->nWork);
   163814           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
   163815           if( nSeg!=0 ){
   163816             bDirtyHint = 1;
   163817             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
   163818           }
   163819         }
   163820       }
   163821 
   163822       if( nSeg!=0 ){
   163823         pWriter->nLeafData = pWriter->nLeafData * -1;
   163824       }
   163825       fts3IncrmergeRelease(p, pWriter, &rc);
   163826       if( nSeg==0 && pWriter->bNoLeafData==0 ){
   163827         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
   163828       }
   163829     }
   163830 
   163831     sqlite3Fts3SegReaderFinish(pCsr);
   163832   }
   163833 
   163834   /* Write the hint values into the %_stat table for the next incr-merger */
   163835   if( bDirtyHint && rc==SQLITE_OK ){
   163836     rc = fts3IncrmergeHintStore(p, &hint);
   163837   }
   163838 
   163839   sqlite3_free(pWriter);
   163840   sqlite3_free(hint.a);
   163841   return rc;
   163842 }
   163843 
   163844 /*
   163845 ** Convert the text beginning at *pz into an integer and return
   163846 ** its value.  Advance *pz to point to the first character past
   163847 ** the integer.
   163848 **
   163849 ** This function used for parameters to merge= and incrmerge=
   163850 ** commands.
   163851 */
   163852 static int fts3Getint(const char **pz){
   163853   const char *z = *pz;
   163854   int i = 0;
   163855   while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
   163856   *pz = z;
   163857   return i;
   163858 }
   163859 
   163860 /*
   163861 ** Process statements of the form:
   163862 **
   163863 **    INSERT INTO table(table) VALUES('merge=A,B');
   163864 **
   163865 ** A and B are integers that decode to be the number of leaf pages
   163866 ** written for the merge, and the minimum number of segments on a level
   163867 ** before it will be selected for a merge, respectively.
   163868 */
   163869 static int fts3DoIncrmerge(
   163870   Fts3Table *p,                   /* FTS3 table handle */
   163871   const char *zParam              /* Nul-terminated string containing "A,B" */
   163872 ){
   163873   int rc;
   163874   int nMin = (FTS3_MERGE_COUNT / 2);
   163875   int nMerge = 0;
   163876   const char *z = zParam;
   163877 
   163878   /* Read the first integer value */
   163879   nMerge = fts3Getint(&z);
   163880 
   163881   /* If the first integer value is followed by a ',',  read the second
   163882   ** integer value. */
   163883   if( z[0]==',' && z[1]!='\0' ){
   163884     z++;
   163885     nMin = fts3Getint(&z);
   163886   }
   163887 
   163888   if( z[0]!='\0' || nMin<2 ){
   163889     rc = SQLITE_ERROR;
   163890   }else{
   163891     rc = SQLITE_OK;
   163892     if( !p->bHasStat ){
   163893       assert( p->bFts4==0 );
   163894       sqlite3Fts3CreateStatTable(&rc, p);
   163895     }
   163896     if( rc==SQLITE_OK ){
   163897       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
   163898     }
   163899     sqlite3Fts3SegmentsClose(p);
   163900   }
   163901   return rc;
   163902 }
   163903 
   163904 /*
   163905 ** Process statements of the form:
   163906 **
   163907 **    INSERT INTO table(table) VALUES('automerge=X');
   163908 **
   163909 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
   163910 ** turn it on.  The setting is persistent.
   163911 */
   163912 static int fts3DoAutoincrmerge(
   163913   Fts3Table *p,                   /* FTS3 table handle */
   163914   const char *zParam              /* Nul-terminated string containing boolean */
   163915 ){
   163916   int rc = SQLITE_OK;
   163917   sqlite3_stmt *pStmt = 0;
   163918   p->nAutoincrmerge = fts3Getint(&zParam);
   163919   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
   163920     p->nAutoincrmerge = 8;
   163921   }
   163922   if( !p->bHasStat ){
   163923     assert( p->bFts4==0 );
   163924     sqlite3Fts3CreateStatTable(&rc, p);
   163925     if( rc ) return rc;
   163926   }
   163927   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
   163928   if( rc ) return rc;
   163929   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
   163930   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
   163931   sqlite3_step(pStmt);
   163932   rc = sqlite3_reset(pStmt);
   163933   return rc;
   163934 }
   163935 
   163936 /*
   163937 ** Return a 64-bit checksum for the FTS index entry specified by the
   163938 ** arguments to this function.
   163939 */
   163940 static u64 fts3ChecksumEntry(
   163941   const char *zTerm,              /* Pointer to buffer containing term */
   163942   int nTerm,                      /* Size of zTerm in bytes */
   163943   int iLangid,                    /* Language id for current row */
   163944   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
   163945   i64 iDocid,                     /* Docid for current row. */
   163946   int iCol,                       /* Column number */
   163947   int iPos                        /* Position */
   163948 ){
   163949   int i;
   163950   u64 ret = (u64)iDocid;
   163951 
   163952   ret += (ret<<3) + iLangid;
   163953   ret += (ret<<3) + iIndex;
   163954   ret += (ret<<3) + iCol;
   163955   ret += (ret<<3) + iPos;
   163956   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
   163957 
   163958   return ret;
   163959 }
   163960 
   163961 /*
   163962 ** Return a checksum of all entries in the FTS index that correspond to
   163963 ** language id iLangid. The checksum is calculated by XORing the checksums
   163964 ** of each individual entry (see fts3ChecksumEntry()) together.
   163965 **
   163966 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
   163967 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
   163968 ** return value is undefined in this case.
   163969 */
   163970 static u64 fts3ChecksumIndex(
   163971   Fts3Table *p,                   /* FTS3 table handle */
   163972   int iLangid,                    /* Language id to return cksum for */
   163973   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
   163974   int *pRc                        /* OUT: Return code */
   163975 ){
   163976   Fts3SegFilter filter;
   163977   Fts3MultiSegReader csr;
   163978   int rc;
   163979   u64 cksum = 0;
   163980 
   163981   assert( *pRc==SQLITE_OK );
   163982 
   163983   memset(&filter, 0, sizeof(filter));
   163984   memset(&csr, 0, sizeof(csr));
   163985   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   163986   filter.flags |= FTS3_SEGMENT_SCAN;
   163987 
   163988   rc = sqlite3Fts3SegReaderCursor(
   163989       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
   163990   );
   163991   if( rc==SQLITE_OK ){
   163992     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   163993   }
   163994 
   163995   if( rc==SQLITE_OK ){
   163996     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
   163997       char *pCsr = csr.aDoclist;
   163998       char *pEnd = &pCsr[csr.nDoclist];
   163999 
   164000       i64 iDocid = 0;
   164001       i64 iCol = 0;
   164002       i64 iPos = 0;
   164003 
   164004       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
   164005       while( pCsr<pEnd ){
   164006         i64 iVal = 0;
   164007         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
   164008         if( pCsr<pEnd ){
   164009           if( iVal==0 || iVal==1 ){
   164010             iCol = 0;
   164011             iPos = 0;
   164012             if( iVal ){
   164013               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
   164014             }else{
   164015               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
   164016               iDocid += iVal;
   164017             }
   164018           }else{
   164019             iPos += (iVal - 2);
   164020             cksum = cksum ^ fts3ChecksumEntry(
   164021                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
   164022                 (int)iCol, (int)iPos
   164023             );
   164024           }
   164025         }
   164026       }
   164027     }
   164028   }
   164029   sqlite3Fts3SegReaderFinish(&csr);
   164030 
   164031   *pRc = rc;
   164032   return cksum;
   164033 }
   164034 
   164035 /*
   164036 ** Check if the contents of the FTS index match the current contents of the
   164037 ** content table. If no error occurs and the contents do match, set *pbOk
   164038 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
   164039 ** to false before returning.
   164040 **
   164041 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
   164042 ** code. The final value of *pbOk is undefined in this case.
   164043 */
   164044 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
   164045   int rc = SQLITE_OK;             /* Return code */
   164046   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
   164047   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
   164048   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
   164049 
   164050   /* This block calculates the checksum according to the FTS index. */
   164051   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   164052   if( rc==SQLITE_OK ){
   164053     int rc2;
   164054     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
   164055     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
   164056     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
   164057       int iLangid = sqlite3_column_int(pAllLangid, 0);
   164058       int i;
   164059       for(i=0; i<p->nIndex; i++){
   164060         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
   164061       }
   164062     }
   164063     rc2 = sqlite3_reset(pAllLangid);
   164064     if( rc==SQLITE_OK ) rc = rc2;
   164065   }
   164066 
   164067   /* This block calculates the checksum according to the %_content table */
   164068   if( rc==SQLITE_OK ){
   164069     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
   164070     sqlite3_stmt *pStmt = 0;
   164071     char *zSql;
   164072 
   164073     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   164074     if( !zSql ){
   164075       rc = SQLITE_NOMEM;
   164076     }else{
   164077       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   164078       sqlite3_free(zSql);
   164079     }
   164080 
   164081     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   164082       i64 iDocid = sqlite3_column_int64(pStmt, 0);
   164083       int iLang = langidFromSelect(p, pStmt);
   164084       int iCol;
   164085 
   164086       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   164087         if( p->abNotindexed[iCol]==0 ){
   164088           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
   164089           int nText = sqlite3_column_bytes(pStmt, iCol+1);
   164090           sqlite3_tokenizer_cursor *pT = 0;
   164091 
   164092           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
   164093           while( rc==SQLITE_OK ){
   164094             char const *zToken;       /* Buffer containing token */
   164095             int nToken = 0;           /* Number of bytes in token */
   164096             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
   164097             int iPos = 0;             /* Position of token in zText */
   164098 
   164099             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   164100             if( rc==SQLITE_OK ){
   164101               int i;
   164102               cksum2 = cksum2 ^ fts3ChecksumEntry(
   164103                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
   164104               );
   164105               for(i=1; i<p->nIndex; i++){
   164106                 if( p->aIndex[i].nPrefix<=nToken ){
   164107                   cksum2 = cksum2 ^ fts3ChecksumEntry(
   164108                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
   164109                   );
   164110                 }
   164111               }
   164112             }
   164113           }
   164114           if( pT ) pModule->xClose(pT);
   164115           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   164116         }
   164117       }
   164118     }
   164119 
   164120     sqlite3_finalize(pStmt);
   164121   }
   164122 
   164123   *pbOk = (cksum1==cksum2);
   164124   return rc;
   164125 }
   164126 
   164127 /*
   164128 ** Run the integrity-check. If no error occurs and the current contents of
   164129 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
   164130 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
   164131 **
   164132 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
   164133 ** error code.
   164134 **
   164135 ** The integrity-check works as follows. For each token and indexed token
   164136 ** prefix in the document set, a 64-bit checksum is calculated (by code
   164137 ** in fts3ChecksumEntry()) based on the following:
   164138 **
   164139 **     + The index number (0 for the main index, 1 for the first prefix
   164140 **       index etc.),
   164141 **     + The token (or token prefix) text itself,
   164142 **     + The language-id of the row it appears in,
   164143 **     + The docid of the row it appears in,
   164144 **     + The column it appears in, and
   164145 **     + The tokens position within that column.
   164146 **
   164147 ** The checksums for all entries in the index are XORed together to create
   164148 ** a single checksum for the entire index.
   164149 **
   164150 ** The integrity-check code calculates the same checksum in two ways:
   164151 **
   164152 **     1. By scanning the contents of the FTS index, and
   164153 **     2. By scanning and tokenizing the content table.
   164154 **
   164155 ** If the two checksums are identical, the integrity-check is deemed to have
   164156 ** passed.
   164157 */
   164158 static int fts3DoIntegrityCheck(
   164159   Fts3Table *p                    /* FTS3 table handle */
   164160 ){
   164161   int rc;
   164162   int bOk = 0;
   164163   rc = fts3IntegrityCheck(p, &bOk);
   164164   if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
   164165   return rc;
   164166 }
   164167 
   164168 /*
   164169 ** Handle a 'special' INSERT of the form:
   164170 **
   164171 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
   164172 **
   164173 ** Argument pVal contains the result of <expr>. Currently the only
   164174 ** meaningful value to insert is the text 'optimize'.
   164175 */
   164176 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
   164177   int rc;                         /* Return Code */
   164178   const char *zVal = (const char *)sqlite3_value_text(pVal);
   164179   int nVal = sqlite3_value_bytes(pVal);
   164180 
   164181   if( !zVal ){
   164182     return SQLITE_NOMEM;
   164183   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
   164184     rc = fts3DoOptimize(p, 0);
   164185   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
   164186     rc = fts3DoRebuild(p);
   164187   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
   164188     rc = fts3DoIntegrityCheck(p);
   164189   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
   164190     rc = fts3DoIncrmerge(p, &zVal[6]);
   164191   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
   164192     rc = fts3DoAutoincrmerge(p, &zVal[10]);
   164193 #ifdef SQLITE_TEST
   164194   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
   164195     p->nNodeSize = atoi(&zVal[9]);
   164196     rc = SQLITE_OK;
   164197   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
   164198     p->nMaxPendingData = atoi(&zVal[11]);
   164199     rc = SQLITE_OK;
   164200   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
   164201     p->bNoIncrDoclist = atoi(&zVal[21]);
   164202     rc = SQLITE_OK;
   164203 #endif
   164204   }else{
   164205     rc = SQLITE_ERROR;
   164206   }
   164207 
   164208   return rc;
   164209 }
   164210 
   164211 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   164212 /*
   164213 ** Delete all cached deferred doclists. Deferred doclists are cached
   164214 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
   164215 */
   164216 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
   164217   Fts3DeferredToken *pDef;
   164218   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
   164219     fts3PendingListDelete(pDef->pList);
   164220     pDef->pList = 0;
   164221   }
   164222 }
   164223 
   164224 /*
   164225 ** Free all entries in the pCsr->pDeffered list. Entries are added to
   164226 ** this list using sqlite3Fts3DeferToken().
   164227 */
   164228 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
   164229   Fts3DeferredToken *pDef;
   164230   Fts3DeferredToken *pNext;
   164231   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
   164232     pNext = pDef->pNext;
   164233     fts3PendingListDelete(pDef->pList);
   164234     sqlite3_free(pDef);
   164235   }
   164236   pCsr->pDeferred = 0;
   164237 }
   164238 
   164239 /*
   164240 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
   164241 ** based on the row that pCsr currently points to.
   164242 **
   164243 ** A deferred-doclist is like any other doclist with position information
   164244 ** included, except that it only contains entries for a single row of the
   164245 ** table, not for all rows.
   164246 */
   164247 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
   164248   int rc = SQLITE_OK;             /* Return code */
   164249   if( pCsr->pDeferred ){
   164250     int i;                        /* Used to iterate through table columns */
   164251     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
   164252     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
   164253 
   164254     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   164255     sqlite3_tokenizer *pT = p->pTokenizer;
   164256     sqlite3_tokenizer_module const *pModule = pT->pModule;
   164257 
   164258     assert( pCsr->isRequireSeek==0 );
   164259     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
   164260 
   164261     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
   164262       if( p->abNotindexed[i]==0 ){
   164263         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
   164264         sqlite3_tokenizer_cursor *pTC = 0;
   164265 
   164266         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
   164267         while( rc==SQLITE_OK ){
   164268           char const *zToken;       /* Buffer containing token */
   164269           int nToken = 0;           /* Number of bytes in token */
   164270           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
   164271           int iPos = 0;             /* Position of token in zText */
   164272 
   164273           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   164274           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   164275             Fts3PhraseToken *pPT = pDef->pToken;
   164276             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
   164277                 && (pPT->bFirst==0 || iPos==0)
   164278                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
   164279                 && (0==memcmp(zToken, pPT->z, pPT->n))
   164280               ){
   164281               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
   164282             }
   164283           }
   164284         }
   164285         if( pTC ) pModule->xClose(pTC);
   164286         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   164287       }
   164288     }
   164289 
   164290     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   164291       if( pDef->pList ){
   164292         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
   164293       }
   164294     }
   164295   }
   164296 
   164297   return rc;
   164298 }
   164299 
   164300 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
   164301   Fts3DeferredToken *p,
   164302   char **ppData,
   164303   int *pnData
   164304 ){
   164305   char *pRet;
   164306   int nSkip;
   164307   sqlite3_int64 dummy;
   164308 
   164309   *ppData = 0;
   164310   *pnData = 0;
   164311 
   164312   if( p->pList==0 ){
   164313     return SQLITE_OK;
   164314   }
   164315 
   164316   pRet = (char *)sqlite3_malloc(p->pList->nData);
   164317   if( !pRet ) return SQLITE_NOMEM;
   164318 
   164319   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
   164320   *pnData = p->pList->nData - nSkip;
   164321   *ppData = pRet;
   164322 
   164323   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
   164324   return SQLITE_OK;
   164325 }
   164326 
   164327 /*
   164328 ** Add an entry for token pToken to the pCsr->pDeferred list.
   164329 */
   164330 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
   164331   Fts3Cursor *pCsr,               /* Fts3 table cursor */
   164332   Fts3PhraseToken *pToken,        /* Token to defer */
   164333   int iCol                        /* Column that token must appear in (or -1) */
   164334 ){
   164335   Fts3DeferredToken *pDeferred;
   164336   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
   164337   if( !pDeferred ){
   164338     return SQLITE_NOMEM;
   164339   }
   164340   memset(pDeferred, 0, sizeof(*pDeferred));
   164341   pDeferred->pToken = pToken;
   164342   pDeferred->pNext = pCsr->pDeferred;
   164343   pDeferred->iCol = iCol;
   164344   pCsr->pDeferred = pDeferred;
   164345 
   164346   assert( pToken->pDeferred==0 );
   164347   pToken->pDeferred = pDeferred;
   164348 
   164349   return SQLITE_OK;
   164350 }
   164351 #endif
   164352 
   164353 /*
   164354 ** SQLite value pRowid contains the rowid of a row that may or may not be
   164355 ** present in the FTS3 table. If it is, delete it and adjust the contents
   164356 ** of subsiduary data structures accordingly.
   164357 */
   164358 static int fts3DeleteByRowid(
   164359   Fts3Table *p,
   164360   sqlite3_value *pRowid,
   164361   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
   164362   u32 *aSzDel
   164363 ){
   164364   int rc = SQLITE_OK;             /* Return code */
   164365   int bFound = 0;                 /* True if *pRowid really is in the table */
   164366 
   164367   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
   164368   if( bFound && rc==SQLITE_OK ){
   164369     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
   164370     rc = fts3IsEmpty(p, pRowid, &isEmpty);
   164371     if( rc==SQLITE_OK ){
   164372       if( isEmpty ){
   164373         /* Deleting this row means the whole table is empty. In this case
   164374         ** delete the contents of all three tables and throw away any
   164375         ** data in the pendingTerms hash table.  */
   164376         rc = fts3DeleteAll(p, 1);
   164377         *pnChng = 0;
   164378         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
   164379       }else{
   164380         *pnChng = *pnChng - 1;
   164381         if( p->zContentTbl==0 ){
   164382           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
   164383         }
   164384         if( p->bHasDocsize ){
   164385           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
   164386         }
   164387       }
   164388     }
   164389   }
   164390 
   164391   return rc;
   164392 }
   164393 
   164394 /*
   164395 ** This function does the work for the xUpdate method of FTS3 virtual
   164396 ** tables. The schema of the virtual table being:
   164397 **
   164398 **     CREATE TABLE <table name>(
   164399 **       <user columns>,
   164400 **       <table name> HIDDEN,
   164401 **       docid HIDDEN,
   164402 **       <langid> HIDDEN
   164403 **     );
   164404 **
   164405 **
   164406 */
   164407 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   164408   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
   164409   int nArg,                       /* Size of argument array */
   164410   sqlite3_value **apVal,          /* Array of arguments */
   164411   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   164412 ){
   164413   Fts3Table *p = (Fts3Table *)pVtab;
   164414   int rc = SQLITE_OK;             /* Return Code */
   164415   int isRemove = 0;               /* True for an UPDATE or DELETE */
   164416   u32 *aSzIns = 0;                /* Sizes of inserted documents */
   164417   u32 *aSzDel = 0;                /* Sizes of deleted documents */
   164418   int nChng = 0;                  /* Net change in number of documents */
   164419   int bInsertDone = 0;
   164420 
   164421   /* At this point it must be known if the %_stat table exists or not.
   164422   ** So bHasStat may not be 2.  */
   164423   assert( p->bHasStat==0 || p->bHasStat==1 );
   164424 
   164425   assert( p->pSegments==0 );
   164426   assert(
   164427       nArg==1                     /* DELETE operations */
   164428    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
   164429   );
   164430 
   164431   /* Check for a "special" INSERT operation. One of the form:
   164432   **
   164433   **   INSERT INTO xyz(xyz) VALUES('command');
   164434   */
   164435   if( nArg>1
   164436    && sqlite3_value_type(apVal[0])==SQLITE_NULL
   164437    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
   164438   ){
   164439     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
   164440     goto update_out;
   164441   }
   164442 
   164443   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
   164444     rc = SQLITE_CONSTRAINT;
   164445     goto update_out;
   164446   }
   164447 
   164448   /* Allocate space to hold the change in document sizes */
   164449   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
   164450   if( aSzDel==0 ){
   164451     rc = SQLITE_NOMEM;
   164452     goto update_out;
   164453   }
   164454   aSzIns = &aSzDel[p->nColumn+1];
   164455   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
   164456 
   164457   rc = fts3Writelock(p);
   164458   if( rc!=SQLITE_OK ) goto update_out;
   164459 
   164460   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
   164461   ** value, then this operation requires constraint handling.
   164462   **
   164463   ** If the on-conflict mode is REPLACE, this means that the existing row
   164464   ** should be deleted from the database before inserting the new row. Or,
   164465   ** if the on-conflict mode is other than REPLACE, then this method must
   164466   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
   164467   ** modify the database file.
   164468   */
   164469   if( nArg>1 && p->zContentTbl==0 ){
   164470     /* Find the value object that holds the new rowid value. */
   164471     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
   164472     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
   164473       pNewRowid = apVal[1];
   164474     }
   164475 
   164476     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
   164477         sqlite3_value_type(apVal[0])==SQLITE_NULL
   164478      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
   164479     )){
   164480       /* The new rowid is not NULL (in this case the rowid will be
   164481       ** automatically assigned and there is no chance of a conflict), and
   164482       ** the statement is either an INSERT or an UPDATE that modifies the
   164483       ** rowid column. So if the conflict mode is REPLACE, then delete any
   164484       ** existing row with rowid=pNewRowid.
   164485       **
   164486       ** Or, if the conflict mode is not REPLACE, insert the new record into
   164487       ** the %_content table. If we hit the duplicate rowid constraint (or any
   164488       ** other error) while doing so, return immediately.
   164489       **
   164490       ** This branch may also run if pNewRowid contains a value that cannot
   164491       ** be losslessly converted to an integer. In this case, the eventual
   164492       ** call to fts3InsertData() (either just below or further on in this
   164493       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
   164494       ** invoked, it will delete zero rows (since no row will have
   164495       ** docid=$pNewRowid if $pNewRowid is not an integer value).
   164496       */
   164497       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
   164498         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
   164499       }else{
   164500         rc = fts3InsertData(p, apVal, pRowid);
   164501         bInsertDone = 1;
   164502       }
   164503     }
   164504   }
   164505   if( rc!=SQLITE_OK ){
   164506     goto update_out;
   164507   }
   164508 
   164509   /* If this is a DELETE or UPDATE operation, remove the old record. */
   164510   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   164511     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
   164512     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
   164513     isRemove = 1;
   164514   }
   164515 
   164516   /* If this is an INSERT or UPDATE operation, insert the new record. */
   164517   if( nArg>1 && rc==SQLITE_OK ){
   164518     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
   164519     if( bInsertDone==0 ){
   164520       rc = fts3InsertData(p, apVal, pRowid);
   164521       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
   164522         rc = FTS_CORRUPT_VTAB;
   164523       }
   164524     }
   164525     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
   164526       rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
   164527     }
   164528     if( rc==SQLITE_OK ){
   164529       assert( p->iPrevDocid==*pRowid );
   164530       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
   164531     }
   164532     if( p->bHasDocsize ){
   164533       fts3InsertDocsize(&rc, p, aSzIns);
   164534     }
   164535     nChng++;
   164536   }
   164537 
   164538   if( p->bFts4 ){
   164539     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
   164540   }
   164541 
   164542  update_out:
   164543   sqlite3_free(aSzDel);
   164544   sqlite3Fts3SegmentsClose(p);
   164545   return rc;
   164546 }
   164547 
   164548 /*
   164549 ** Flush any data in the pending-terms hash table to disk. If successful,
   164550 ** merge all segments in the database (including the new segment, if
   164551 ** there was any data to flush) into a single segment.
   164552 */
   164553 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   164554   int rc;
   164555   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
   164556   if( rc==SQLITE_OK ){
   164557     rc = fts3DoOptimize(p, 1);
   164558     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   164559       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   164560       if( rc2!=SQLITE_OK ) rc = rc2;
   164561     }else{
   164562       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
   164563       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   164564     }
   164565   }
   164566   sqlite3Fts3SegmentsClose(p);
   164567   return rc;
   164568 }
   164569 
   164570 #endif
   164571 
   164572 /************** End of fts3_write.c ******************************************/
   164573 /************** Begin file fts3_snippet.c ************************************/
   164574 /*
   164575 ** 2009 Oct 23
   164576 **
   164577 ** The author disclaims copyright to this source code.  In place of
   164578 ** a legal notice, here is a blessing:
   164579 **
   164580 **    May you do good and not evil.
   164581 **    May you find forgiveness for yourself and forgive others.
   164582 **    May you share freely, never taking more than you give.
   164583 **
   164584 ******************************************************************************
   164585 */
   164586 
   164587 /* #include "fts3Int.h" */
   164588 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   164589 
   164590 /* #include <string.h> */
   164591 /* #include <assert.h> */
   164592 
   164593 /*
   164594 ** Characters that may appear in the second argument to matchinfo().
   164595 */
   164596 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
   164597 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
   164598 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
   164599 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
   164600 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
   164601 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
   164602 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
   164603 #define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
   164604 #define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
   164605 
   164606 /*
   164607 ** The default value for the second argument to matchinfo().
   164608 */
   164609 #define FTS3_MATCHINFO_DEFAULT   "pcx"
   164610 
   164611 
   164612 /*
   164613 ** Used as an fts3ExprIterate() context when loading phrase doclists to
   164614 ** Fts3Expr.aDoclist[]/nDoclist.
   164615 */
   164616 typedef struct LoadDoclistCtx LoadDoclistCtx;
   164617 struct LoadDoclistCtx {
   164618   Fts3Cursor *pCsr;               /* FTS3 Cursor */
   164619   int nPhrase;                    /* Number of phrases seen so far */
   164620   int nToken;                     /* Number of tokens seen so far */
   164621 };
   164622 
   164623 /*
   164624 ** The following types are used as part of the implementation of the
   164625 ** fts3BestSnippet() routine.
   164626 */
   164627 typedef struct SnippetIter SnippetIter;
   164628 typedef struct SnippetPhrase SnippetPhrase;
   164629 typedef struct SnippetFragment SnippetFragment;
   164630 
   164631 struct SnippetIter {
   164632   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
   164633   int iCol;                       /* Extract snippet from this column */
   164634   int nSnippet;                   /* Requested snippet length (in tokens) */
   164635   int nPhrase;                    /* Number of phrases in query */
   164636   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
   164637   int iCurrent;                   /* First token of current snippet */
   164638 };
   164639 
   164640 struct SnippetPhrase {
   164641   int nToken;                     /* Number of tokens in phrase */
   164642   char *pList;                    /* Pointer to start of phrase position list */
   164643   int iHead;                      /* Next value in position list */
   164644   char *pHead;                    /* Position list data following iHead */
   164645   int iTail;                      /* Next value in trailing position list */
   164646   char *pTail;                    /* Position list data following iTail */
   164647 };
   164648 
   164649 struct SnippetFragment {
   164650   int iCol;                       /* Column snippet is extracted from */
   164651   int iPos;                       /* Index of first token in snippet */
   164652   u64 covered;                    /* Mask of query phrases covered */
   164653   u64 hlmask;                     /* Mask of snippet terms to highlight */
   164654 };
   164655 
   164656 /*
   164657 ** This type is used as an fts3ExprIterate() context object while
   164658 ** accumulating the data returned by the matchinfo() function.
   164659 */
   164660 typedef struct MatchInfo MatchInfo;
   164661 struct MatchInfo {
   164662   Fts3Cursor *pCursor;            /* FTS3 Cursor */
   164663   int nCol;                       /* Number of columns in table */
   164664   int nPhrase;                    /* Number of matchable phrases in query */
   164665   sqlite3_int64 nDoc;             /* Number of docs in database */
   164666   char flag;
   164667   u32 *aMatchinfo;                /* Pre-allocated buffer */
   164668 };
   164669 
   164670 /*
   164671 ** An instance of this structure is used to manage a pair of buffers, each
   164672 ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
   164673 ** for details.
   164674 */
   164675 struct MatchinfoBuffer {
   164676   u8 aRef[3];
   164677   int nElem;
   164678   int bGlobal;                    /* Set if global data is loaded */
   164679   char *zMatchinfo;
   164680   u32 aMatchinfo[1];
   164681 };
   164682 
   164683 
   164684 /*
   164685 ** The snippet() and offsets() functions both return text values. An instance
   164686 ** of the following structure is used to accumulate those values while the
   164687 ** functions are running. See fts3StringAppend() for details.
   164688 */
   164689 typedef struct StrBuffer StrBuffer;
   164690 struct StrBuffer {
   164691   char *z;                        /* Pointer to buffer containing string */
   164692   int n;                          /* Length of z in bytes (excl. nul-term) */
   164693   int nAlloc;                     /* Allocated size of buffer z in bytes */
   164694 };
   164695 
   164696 
   164697 /*************************************************************************
   164698 ** Start of MatchinfoBuffer code.
   164699 */
   164700 
   164701 /*
   164702 ** Allocate a two-slot MatchinfoBuffer object.
   164703 */
   164704 static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
   164705   MatchinfoBuffer *pRet;
   164706   int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
   164707   int nStr = (int)strlen(zMatchinfo);
   164708 
   164709   pRet = sqlite3_malloc(nByte + nStr+1);
   164710   if( pRet ){
   164711     memset(pRet, 0, nByte);
   164712     pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
   164713     pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
   164714     pRet->nElem = nElem;
   164715     pRet->zMatchinfo = ((char*)pRet) + nByte;
   164716     memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
   164717     pRet->aRef[0] = 1;
   164718   }
   164719 
   164720   return pRet;
   164721 }
   164722 
   164723 static void fts3MIBufferFree(void *p){
   164724   MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
   164725 
   164726   assert( (u32*)p==&pBuf->aMatchinfo[1]
   164727        || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
   164728   );
   164729   if( (u32*)p==&pBuf->aMatchinfo[1] ){
   164730     pBuf->aRef[1] = 0;
   164731   }else{
   164732     pBuf->aRef[2] = 0;
   164733   }
   164734 
   164735   if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
   164736     sqlite3_free(pBuf);
   164737   }
   164738 }
   164739 
   164740 static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
   164741   void (*xRet)(void*) = 0;
   164742   u32 *aOut = 0;
   164743 
   164744   if( p->aRef[1]==0 ){
   164745     p->aRef[1] = 1;
   164746     aOut = &p->aMatchinfo[1];
   164747     xRet = fts3MIBufferFree;
   164748   }
   164749   else if( p->aRef[2]==0 ){
   164750     p->aRef[2] = 1;
   164751     aOut = &p->aMatchinfo[p->nElem+2];
   164752     xRet = fts3MIBufferFree;
   164753   }else{
   164754     aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
   164755     if( aOut ){
   164756       xRet = sqlite3_free;
   164757       if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
   164758     }
   164759   }
   164760 
   164761   *paOut = aOut;
   164762   return xRet;
   164763 }
   164764 
   164765 static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
   164766   p->bGlobal = 1;
   164767   memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
   164768 }
   164769 
   164770 /*
   164771 ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
   164772 */
   164773 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
   164774   if( p ){
   164775     assert( p->aRef[0]==1 );
   164776     p->aRef[0] = 0;
   164777     if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
   164778       sqlite3_free(p);
   164779     }
   164780   }
   164781 }
   164782 
   164783 /*
   164784 ** End of MatchinfoBuffer code.
   164785 *************************************************************************/
   164786 
   164787 
   164788 /*
   164789 ** This function is used to help iterate through a position-list. A position
   164790 ** list is a list of unique integers, sorted from smallest to largest. Each
   164791 ** element of the list is represented by an FTS3 varint that takes the value
   164792 ** of the difference between the current element and the previous one plus
   164793 ** two. For example, to store the position-list:
   164794 **
   164795 **     4 9 113
   164796 **
   164797 ** the three varints:
   164798 **
   164799 **     6 7 106
   164800 **
   164801 ** are encoded.
   164802 **
   164803 ** When this function is called, *pp points to the start of an element of
   164804 ** the list. *piPos contains the value of the previous entry in the list.
   164805 ** After it returns, *piPos contains the value of the next element of the
   164806 ** list and *pp is advanced to the following varint.
   164807 */
   164808 static void fts3GetDeltaPosition(char **pp, int *piPos){
   164809   int iVal;
   164810   *pp += fts3GetVarint32(*pp, &iVal);
   164811   *piPos += (iVal-2);
   164812 }
   164813 
   164814 /*
   164815 ** Helper function for fts3ExprIterate() (see below).
   164816 */
   164817 static int fts3ExprIterate2(
   164818   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   164819   int *piPhrase,                  /* Pointer to phrase counter */
   164820   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   164821   void *pCtx                      /* Second argument to pass to callback */
   164822 ){
   164823   int rc;                         /* Return code */
   164824   int eType = pExpr->eType;     /* Type of expression node pExpr */
   164825 
   164826   if( eType!=FTSQUERY_PHRASE ){
   164827     assert( pExpr->pLeft && pExpr->pRight );
   164828     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
   164829     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
   164830       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
   164831     }
   164832   }else{
   164833     rc = x(pExpr, *piPhrase, pCtx);
   164834     (*piPhrase)++;
   164835   }
   164836   return rc;
   164837 }
   164838 
   164839 /*
   164840 ** Iterate through all phrase nodes in an FTS3 query, except those that
   164841 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
   164842 ** For each phrase node found, the supplied callback function is invoked.
   164843 **
   164844 ** If the callback function returns anything other than SQLITE_OK,
   164845 ** the iteration is abandoned and the error code returned immediately.
   164846 ** Otherwise, SQLITE_OK is returned after a callback has been made for
   164847 ** all eligible phrase nodes.
   164848 */
   164849 static int fts3ExprIterate(
   164850   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   164851   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   164852   void *pCtx                      /* Second argument to pass to callback */
   164853 ){
   164854   int iPhrase = 0;                /* Variable used as the phrase counter */
   164855   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
   164856 }
   164857 
   164858 
   164859 /*
   164860 ** This is an fts3ExprIterate() callback used while loading the doclists
   164861 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
   164862 ** fts3ExprLoadDoclists().
   164863 */
   164864 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   164865   int rc = SQLITE_OK;
   164866   Fts3Phrase *pPhrase = pExpr->pPhrase;
   164867   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
   164868 
   164869   UNUSED_PARAMETER(iPhrase);
   164870 
   164871   p->nPhrase++;
   164872   p->nToken += pPhrase->nToken;
   164873 
   164874   return rc;
   164875 }
   164876 
   164877 /*
   164878 ** Load the doclists for each phrase in the query associated with FTS3 cursor
   164879 ** pCsr.
   164880 **
   164881 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
   164882 ** phrases in the expression (all phrases except those directly or
   164883 ** indirectly descended from the right-hand-side of a NOT operator). If
   164884 ** pnToken is not NULL, then it is set to the number of tokens in all
   164885 ** matchable phrases of the expression.
   164886 */
   164887 static int fts3ExprLoadDoclists(
   164888   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
   164889   int *pnPhrase,                  /* OUT: Number of phrases in query */
   164890   int *pnToken                    /* OUT: Number of tokens in query */
   164891 ){
   164892   int rc;                         /* Return Code */
   164893   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
   164894   sCtx.pCsr = pCsr;
   164895   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
   164896   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
   164897   if( pnToken ) *pnToken = sCtx.nToken;
   164898   return rc;
   164899 }
   164900 
   164901 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   164902   (*(int *)ctx)++;
   164903   pExpr->iPhrase = iPhrase;
   164904   return SQLITE_OK;
   164905 }
   164906 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
   164907   int nPhrase = 0;
   164908   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
   164909   return nPhrase;
   164910 }
   164911 
   164912 /*
   164913 ** Advance the position list iterator specified by the first two
   164914 ** arguments so that it points to the first element with a value greater
   164915 ** than or equal to parameter iNext.
   164916 */
   164917 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
   164918   char *pIter = *ppIter;
   164919   if( pIter ){
   164920     int iIter = *piIter;
   164921 
   164922     while( iIter<iNext ){
   164923       if( 0==(*pIter & 0xFE) ){
   164924         iIter = -1;
   164925         pIter = 0;
   164926         break;
   164927       }
   164928       fts3GetDeltaPosition(&pIter, &iIter);
   164929     }
   164930 
   164931     *piIter = iIter;
   164932     *ppIter = pIter;
   164933   }
   164934 }
   164935 
   164936 /*
   164937 ** Advance the snippet iterator to the next candidate snippet.
   164938 */
   164939 static int fts3SnippetNextCandidate(SnippetIter *pIter){
   164940   int i;                          /* Loop counter */
   164941 
   164942   if( pIter->iCurrent<0 ){
   164943     /* The SnippetIter object has just been initialized. The first snippet
   164944     ** candidate always starts at offset 0 (even if this candidate has a
   164945     ** score of 0.0).
   164946     */
   164947     pIter->iCurrent = 0;
   164948 
   164949     /* Advance the 'head' iterator of each phrase to the first offset that
   164950     ** is greater than or equal to (iNext+nSnippet).
   164951     */
   164952     for(i=0; i<pIter->nPhrase; i++){
   164953       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   164954       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
   164955     }
   164956   }else{
   164957     int iStart;
   164958     int iEnd = 0x7FFFFFFF;
   164959 
   164960     for(i=0; i<pIter->nPhrase; i++){
   164961       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   164962       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
   164963         iEnd = pPhrase->iHead;
   164964       }
   164965     }
   164966     if( iEnd==0x7FFFFFFF ){
   164967       return 1;
   164968     }
   164969 
   164970     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
   164971     for(i=0; i<pIter->nPhrase; i++){
   164972       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   164973       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
   164974       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
   164975     }
   164976   }
   164977 
   164978   return 0;
   164979 }
   164980 
   164981 /*
   164982 ** Retrieve information about the current candidate snippet of snippet
   164983 ** iterator pIter.
   164984 */
   164985 static void fts3SnippetDetails(
   164986   SnippetIter *pIter,             /* Snippet iterator */
   164987   u64 mCovered,                   /* Bitmask of phrases already covered */
   164988   int *piToken,                   /* OUT: First token of proposed snippet */
   164989   int *piScore,                   /* OUT: "Score" for this snippet */
   164990   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
   164991   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
   164992 ){
   164993   int iStart = pIter->iCurrent;   /* First token of snippet */
   164994   int iScore = 0;                 /* Score of this snippet */
   164995   int i;                          /* Loop counter */
   164996   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
   164997   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
   164998 
   164999   for(i=0; i<pIter->nPhrase; i++){
   165000     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   165001     if( pPhrase->pTail ){
   165002       char *pCsr = pPhrase->pTail;
   165003       int iCsr = pPhrase->iTail;
   165004 
   165005       while( iCsr<(iStart+pIter->nSnippet) ){
   165006         int j;
   165007         u64 mPhrase = (u64)1 << i;
   165008         u64 mPos = (u64)1 << (iCsr - iStart);
   165009         assert( iCsr>=iStart );
   165010         if( (mCover|mCovered)&mPhrase ){
   165011           iScore++;
   165012         }else{
   165013           iScore += 1000;
   165014         }
   165015         mCover |= mPhrase;
   165016 
   165017         for(j=0; j<pPhrase->nToken; j++){
   165018           mHighlight |= (mPos>>j);
   165019         }
   165020 
   165021         if( 0==(*pCsr & 0x0FE) ) break;
   165022         fts3GetDeltaPosition(&pCsr, &iCsr);
   165023       }
   165024     }
   165025   }
   165026 
   165027   /* Set the output variables before returning. */
   165028   *piToken = iStart;
   165029   *piScore = iScore;
   165030   *pmCover = mCover;
   165031   *pmHighlight = mHighlight;
   165032 }
   165033 
   165034 /*
   165035 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
   165036 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
   165037 */
   165038 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
   165039   SnippetIter *p = (SnippetIter *)ctx;
   165040   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
   165041   char *pCsr;
   165042   int rc;
   165043 
   165044   pPhrase->nToken = pExpr->pPhrase->nToken;
   165045   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
   165046   assert( rc==SQLITE_OK || pCsr==0 );
   165047   if( pCsr ){
   165048     int iFirst = 0;
   165049     pPhrase->pList = pCsr;
   165050     fts3GetDeltaPosition(&pCsr, &iFirst);
   165051     assert( iFirst>=0 );
   165052     pPhrase->pHead = pCsr;
   165053     pPhrase->pTail = pCsr;
   165054     pPhrase->iHead = iFirst;
   165055     pPhrase->iTail = iFirst;
   165056   }else{
   165057     assert( rc!=SQLITE_OK || (
   165058        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
   165059     ));
   165060   }
   165061 
   165062   return rc;
   165063 }
   165064 
   165065 /*
   165066 ** Select the fragment of text consisting of nFragment contiguous tokens
   165067 ** from column iCol that represent the "best" snippet. The best snippet
   165068 ** is the snippet with the highest score, where scores are calculated
   165069 ** by adding:
   165070 **
   165071 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
   165072 **
   165073 **   (b) +1000 points for the first occurrence of each matchable phrase in
   165074 **       the snippet for which the corresponding mCovered bit is not set.
   165075 **
   165076 ** The selected snippet parameters are stored in structure *pFragment before
   165077 ** returning. The score of the selected snippet is stored in *piScore
   165078 ** before returning.
   165079 */
   165080 static int fts3BestSnippet(
   165081   int nSnippet,                   /* Desired snippet length */
   165082   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
   165083   int iCol,                       /* Index of column to create snippet from */
   165084   u64 mCovered,                   /* Mask of phrases already covered */
   165085   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
   165086   SnippetFragment *pFragment,     /* OUT: Best snippet found */
   165087   int *piScore                    /* OUT: Score of snippet pFragment */
   165088 ){
   165089   int rc;                         /* Return Code */
   165090   int nList;                      /* Number of phrases in expression */
   165091   SnippetIter sIter;              /* Iterates through snippet candidates */
   165092   int nByte;                      /* Number of bytes of space to allocate */
   165093   int iBestScore = -1;            /* Best snippet score found so far */
   165094   int i;                          /* Loop counter */
   165095 
   165096   memset(&sIter, 0, sizeof(sIter));
   165097 
   165098   /* Iterate through the phrases in the expression to count them. The same
   165099   ** callback makes sure the doclists are loaded for each phrase.
   165100   */
   165101   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
   165102   if( rc!=SQLITE_OK ){
   165103     return rc;
   165104   }
   165105 
   165106   /* Now that it is known how many phrases there are, allocate and zero
   165107   ** the required space using malloc().
   165108   */
   165109   nByte = sizeof(SnippetPhrase) * nList;
   165110   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
   165111   if( !sIter.aPhrase ){
   165112     return SQLITE_NOMEM;
   165113   }
   165114   memset(sIter.aPhrase, 0, nByte);
   165115 
   165116   /* Initialize the contents of the SnippetIter object. Then iterate through
   165117   ** the set of phrases in the expression to populate the aPhrase[] array.
   165118   */
   165119   sIter.pCsr = pCsr;
   165120   sIter.iCol = iCol;
   165121   sIter.nSnippet = nSnippet;
   165122   sIter.nPhrase = nList;
   165123   sIter.iCurrent = -1;
   165124   rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
   165125   if( rc==SQLITE_OK ){
   165126 
   165127     /* Set the *pmSeen output variable. */
   165128     for(i=0; i<nList; i++){
   165129       if( sIter.aPhrase[i].pHead ){
   165130         *pmSeen |= (u64)1 << i;
   165131       }
   165132     }
   165133 
   165134     /* Loop through all candidate snippets. Store the best snippet in
   165135      ** *pFragment. Store its associated 'score' in iBestScore.
   165136      */
   165137     pFragment->iCol = iCol;
   165138     while( !fts3SnippetNextCandidate(&sIter) ){
   165139       int iPos;
   165140       int iScore;
   165141       u64 mCover;
   165142       u64 mHighlite;
   165143       fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
   165144       assert( iScore>=0 );
   165145       if( iScore>iBestScore ){
   165146         pFragment->iPos = iPos;
   165147         pFragment->hlmask = mHighlite;
   165148         pFragment->covered = mCover;
   165149         iBestScore = iScore;
   165150       }
   165151     }
   165152 
   165153     *piScore = iBestScore;
   165154   }
   165155   sqlite3_free(sIter.aPhrase);
   165156   return rc;
   165157 }
   165158 
   165159 
   165160 /*
   165161 ** Append a string to the string-buffer passed as the first argument.
   165162 **
   165163 ** If nAppend is negative, then the length of the string zAppend is
   165164 ** determined using strlen().
   165165 */
   165166 static int fts3StringAppend(
   165167   StrBuffer *pStr,                /* Buffer to append to */
   165168   const char *zAppend,            /* Pointer to data to append to buffer */
   165169   int nAppend                     /* Size of zAppend in bytes (or -1) */
   165170 ){
   165171   if( nAppend<0 ){
   165172     nAppend = (int)strlen(zAppend);
   165173   }
   165174 
   165175   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
   165176   ** to grow the buffer until so that it is big enough to accomadate the
   165177   ** appended data.
   165178   */
   165179   if( pStr->n+nAppend+1>=pStr->nAlloc ){
   165180     int nAlloc = pStr->nAlloc+nAppend+100;
   165181     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
   165182     if( !zNew ){
   165183       return SQLITE_NOMEM;
   165184     }
   165185     pStr->z = zNew;
   165186     pStr->nAlloc = nAlloc;
   165187   }
   165188   assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
   165189 
   165190   /* Append the data to the string buffer. */
   165191   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
   165192   pStr->n += nAppend;
   165193   pStr->z[pStr->n] = '\0';
   165194 
   165195   return SQLITE_OK;
   165196 }
   165197 
   165198 /*
   165199 ** The fts3BestSnippet() function often selects snippets that end with a
   165200 ** query term. That is, the final term of the snippet is always a term
   165201 ** that requires highlighting. For example, if 'X' is a highlighted term
   165202 ** and '.' is a non-highlighted term, BestSnippet() may select:
   165203 **
   165204 **     ........X.....X
   165205 **
   165206 ** This function "shifts" the beginning of the snippet forward in the
   165207 ** document so that there are approximately the same number of
   165208 ** non-highlighted terms to the right of the final highlighted term as there
   165209 ** are to the left of the first highlighted term. For example, to this:
   165210 **
   165211 **     ....X.....X....
   165212 **
   165213 ** This is done as part of extracting the snippet text, not when selecting
   165214 ** the snippet. Snippet selection is done based on doclists only, so there
   165215 ** is no way for fts3BestSnippet() to know whether or not the document
   165216 ** actually contains terms that follow the final highlighted term.
   165217 */
   165218 static int fts3SnippetShift(
   165219   Fts3Table *pTab,                /* FTS3 table snippet comes from */
   165220   int iLangid,                    /* Language id to use in tokenizing */
   165221   int nSnippet,                   /* Number of tokens desired for snippet */
   165222   const char *zDoc,               /* Document text to extract snippet from */
   165223   int nDoc,                       /* Size of buffer zDoc in bytes */
   165224   int *piPos,                     /* IN/OUT: First token of snippet */
   165225   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
   165226 ){
   165227   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
   165228 
   165229   if( hlmask ){
   165230     int nLeft;                    /* Tokens to the left of first highlight */
   165231     int nRight;                   /* Tokens to the right of last highlight */
   165232     int nDesired;                 /* Ideal number of tokens to shift forward */
   165233 
   165234     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
   165235     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
   165236     nDesired = (nLeft-nRight)/2;
   165237 
   165238     /* Ideally, the start of the snippet should be pushed forward in the
   165239     ** document nDesired tokens. This block checks if there are actually
   165240     ** nDesired tokens to the right of the snippet. If so, *piPos and
   165241     ** *pHlMask are updated to shift the snippet nDesired tokens to the
   165242     ** right. Otherwise, the snippet is shifted by the number of tokens
   165243     ** available.
   165244     */
   165245     if( nDesired>0 ){
   165246       int nShift;                 /* Number of tokens to shift snippet by */
   165247       int iCurrent = 0;           /* Token counter */
   165248       int rc;                     /* Return Code */
   165249       sqlite3_tokenizer_module *pMod;
   165250       sqlite3_tokenizer_cursor *pC;
   165251       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   165252 
   165253       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
   165254       ** or more tokens in zDoc/nDoc.
   165255       */
   165256       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
   165257       if( rc!=SQLITE_OK ){
   165258         return rc;
   165259       }
   165260       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
   165261         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
   165262         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
   165263       }
   165264       pMod->xClose(pC);
   165265       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
   165266 
   165267       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
   165268       assert( nShift<=nDesired );
   165269       if( nShift>0 ){
   165270         *piPos += nShift;
   165271         *pHlmask = hlmask >> nShift;
   165272       }
   165273     }
   165274   }
   165275   return SQLITE_OK;
   165276 }
   165277 
   165278 /*
   165279 ** Extract the snippet text for fragment pFragment from cursor pCsr and
   165280 ** append it to string buffer pOut.
   165281 */
   165282 static int fts3SnippetText(
   165283   Fts3Cursor *pCsr,               /* FTS3 Cursor */
   165284   SnippetFragment *pFragment,     /* Snippet to extract */
   165285   int iFragment,                  /* Fragment number */
   165286   int isLast,                     /* True for final fragment in snippet */
   165287   int nSnippet,                   /* Number of tokens in extracted snippet */
   165288   const char *zOpen,              /* String inserted before highlighted term */
   165289   const char *zClose,             /* String inserted after highlighted term */
   165290   const char *zEllipsis,          /* String inserted between snippets */
   165291   StrBuffer *pOut                 /* Write output here */
   165292 ){
   165293   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   165294   int rc;                         /* Return code */
   165295   const char *zDoc;               /* Document text to extract snippet from */
   165296   int nDoc;                       /* Size of zDoc in bytes */
   165297   int iCurrent = 0;               /* Current token number of document */
   165298   int iEnd = 0;                   /* Byte offset of end of current token */
   165299   int isShiftDone = 0;            /* True after snippet is shifted */
   165300   int iPos = pFragment->iPos;     /* First token of snippet */
   165301   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
   165302   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
   165303   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   165304   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
   165305 
   165306   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
   165307   if( zDoc==0 ){
   165308     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
   165309       return SQLITE_NOMEM;
   165310     }
   165311     return SQLITE_OK;
   165312   }
   165313   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
   165314 
   165315   /* Open a token cursor on the document. */
   165316   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   165317   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
   165318   if( rc!=SQLITE_OK ){
   165319     return rc;
   165320   }
   165321 
   165322   while( rc==SQLITE_OK ){
   165323     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
   165324     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
   165325     int iBegin = 0;               /* Offset in zDoc of start of token */
   165326     int iFin = 0;                 /* Offset in zDoc of end of token */
   165327     int isHighlight = 0;          /* True for highlighted terms */
   165328 
   165329     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
   165330     ** in the FTS code the variable that the third argument to xNext points to
   165331     ** is initialized to zero before the first (*but not necessarily
   165332     ** subsequent*) call to xNext(). This is done for a particular application
   165333     ** that needs to know whether or not the tokenizer is being used for
   165334     ** snippet generation or for some other purpose.
   165335     **
   165336     ** Extreme care is required when writing code to depend on this
   165337     ** initialization. It is not a documented part of the tokenizer interface.
   165338     ** If a tokenizer is used directly by any code outside of FTS, this
   165339     ** convention might not be respected.  */
   165340     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
   165341     if( rc!=SQLITE_OK ){
   165342       if( rc==SQLITE_DONE ){
   165343         /* Special case - the last token of the snippet is also the last token
   165344         ** of the column. Append any punctuation that occurred between the end
   165345         ** of the previous token and the end of the document to the output.
   165346         ** Then break out of the loop. */
   165347         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
   165348       }
   165349       break;
   165350     }
   165351     if( iCurrent<iPos ){ continue; }
   165352 
   165353     if( !isShiftDone ){
   165354       int n = nDoc - iBegin;
   165355       rc = fts3SnippetShift(
   165356           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
   165357       );
   165358       isShiftDone = 1;
   165359 
   165360       /* Now that the shift has been done, check if the initial "..." are
   165361       ** required. They are required if (a) this is not the first fragment,
   165362       ** or (b) this fragment does not begin at position 0 of its column.
   165363       */
   165364       if( rc==SQLITE_OK ){
   165365         if( iPos>0 || iFragment>0 ){
   165366           rc = fts3StringAppend(pOut, zEllipsis, -1);
   165367         }else if( iBegin ){
   165368           rc = fts3StringAppend(pOut, zDoc, iBegin);
   165369         }
   165370       }
   165371       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
   165372     }
   165373 
   165374     if( iCurrent>=(iPos+nSnippet) ){
   165375       if( isLast ){
   165376         rc = fts3StringAppend(pOut, zEllipsis, -1);
   165377       }
   165378       break;
   165379     }
   165380 
   165381     /* Set isHighlight to true if this term should be highlighted. */
   165382     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
   165383 
   165384     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
   165385     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
   165386     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
   165387     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
   165388 
   165389     iEnd = iFin;
   165390   }
   165391 
   165392   pMod->xClose(pC);
   165393   return rc;
   165394 }
   165395 
   165396 
   165397 /*
   165398 ** This function is used to count the entries in a column-list (a
   165399 ** delta-encoded list of term offsets within a single column of a single
   165400 ** row). When this function is called, *ppCollist should point to the
   165401 ** beginning of the first varint in the column-list (the varint that
   165402 ** contains the position of the first matching term in the column data).
   165403 ** Before returning, *ppCollist is set to point to the first byte after
   165404 ** the last varint in the column-list (either the 0x00 signifying the end
   165405 ** of the position-list, or the 0x01 that precedes the column number of
   165406 ** the next column in the position-list).
   165407 **
   165408 ** The number of elements in the column-list is returned.
   165409 */
   165410 static int fts3ColumnlistCount(char **ppCollist){
   165411   char *pEnd = *ppCollist;
   165412   char c = 0;
   165413   int nEntry = 0;
   165414 
   165415   /* A column-list is terminated by either a 0x01 or 0x00. */
   165416   while( 0xFE & (*pEnd | c) ){
   165417     c = *pEnd++ & 0x80;
   165418     if( !c ) nEntry++;
   165419   }
   165420 
   165421   *ppCollist = pEnd;
   165422   return nEntry;
   165423 }
   165424 
   165425 /*
   165426 ** This function gathers 'y' or 'b' data for a single phrase.
   165427 */
   165428 static void fts3ExprLHits(
   165429   Fts3Expr *pExpr,                /* Phrase expression node */
   165430   MatchInfo *p                    /* Matchinfo context */
   165431 ){
   165432   Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
   165433   int iStart;
   165434   Fts3Phrase *pPhrase = pExpr->pPhrase;
   165435   char *pIter = pPhrase->doclist.pList;
   165436   int iCol = 0;
   165437 
   165438   assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
   165439   if( p->flag==FTS3_MATCHINFO_LHITS ){
   165440     iStart = pExpr->iPhrase * p->nCol;
   165441   }else{
   165442     iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
   165443   }
   165444 
   165445   while( 1 ){
   165446     int nHit = fts3ColumnlistCount(&pIter);
   165447     if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
   165448       if( p->flag==FTS3_MATCHINFO_LHITS ){
   165449         p->aMatchinfo[iStart + iCol] = (u32)nHit;
   165450       }else if( nHit ){
   165451         p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
   165452       }
   165453     }
   165454     assert( *pIter==0x00 || *pIter==0x01 );
   165455     if( *pIter!=0x01 ) break;
   165456     pIter++;
   165457     pIter += fts3GetVarint32(pIter, &iCol);
   165458   }
   165459 }
   165460 
   165461 /*
   165462 ** Gather the results for matchinfo directives 'y' and 'b'.
   165463 */
   165464 static void fts3ExprLHitGather(
   165465   Fts3Expr *pExpr,
   165466   MatchInfo *p
   165467 ){
   165468   assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
   165469   if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
   165470     if( pExpr->pLeft ){
   165471       fts3ExprLHitGather(pExpr->pLeft, p);
   165472       fts3ExprLHitGather(pExpr->pRight, p);
   165473     }else{
   165474       fts3ExprLHits(pExpr, p);
   165475     }
   165476   }
   165477 }
   165478 
   165479 /*
   165480 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
   165481 ** for a single query.
   165482 **
   165483 ** fts3ExprIterate() callback to load the 'global' elements of a
   165484 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
   165485 ** of the matchinfo array that are constant for all rows returned by the
   165486 ** current query.
   165487 **
   165488 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
   165489 ** function populates Matchinfo.aMatchinfo[] as follows:
   165490 **
   165491 **   for(iCol=0; iCol<nCol; iCol++){
   165492 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
   165493 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
   165494 **   }
   165495 **
   165496 ** where X is the number of matches for phrase iPhrase is column iCol of all
   165497 ** rows of the table. Y is the number of rows for which column iCol contains
   165498 ** at least one instance of phrase iPhrase.
   165499 **
   165500 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
   165501 ** Y values are set to nDoc, where nDoc is the number of documents in the
   165502 ** file system. This is done because the full-text index doclist is required
   165503 ** to calculate these values properly, and the full-text index doclist is
   165504 ** not available for deferred tokens.
   165505 */
   165506 static int fts3ExprGlobalHitsCb(
   165507   Fts3Expr *pExpr,                /* Phrase expression node */
   165508   int iPhrase,                    /* Phrase number (numbered from zero) */
   165509   void *pCtx                      /* Pointer to MatchInfo structure */
   165510 ){
   165511   MatchInfo *p = (MatchInfo *)pCtx;
   165512   return sqlite3Fts3EvalPhraseStats(
   165513       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
   165514   );
   165515 }
   165516 
   165517 /*
   165518 ** fts3ExprIterate() callback used to collect the "local" part of the
   165519 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
   165520 ** array that are different for each row returned by the query.
   165521 */
   165522 static int fts3ExprLocalHitsCb(
   165523   Fts3Expr *pExpr,                /* Phrase expression node */
   165524   int iPhrase,                    /* Phrase number */
   165525   void *pCtx                      /* Pointer to MatchInfo structure */
   165526 ){
   165527   int rc = SQLITE_OK;
   165528   MatchInfo *p = (MatchInfo *)pCtx;
   165529   int iStart = iPhrase * p->nCol * 3;
   165530   int i;
   165531 
   165532   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
   165533     char *pCsr;
   165534     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
   165535     if( pCsr ){
   165536       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
   165537     }else{
   165538       p->aMatchinfo[iStart+i*3] = 0;
   165539     }
   165540   }
   165541 
   165542   return rc;
   165543 }
   165544 
   165545 static int fts3MatchinfoCheck(
   165546   Fts3Table *pTab,
   165547   char cArg,
   165548   char **pzErr
   165549 ){
   165550   if( (cArg==FTS3_MATCHINFO_NPHRASE)
   165551    || (cArg==FTS3_MATCHINFO_NCOL)
   165552    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
   165553    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
   165554    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
   165555    || (cArg==FTS3_MATCHINFO_LCS)
   165556    || (cArg==FTS3_MATCHINFO_HITS)
   165557    || (cArg==FTS3_MATCHINFO_LHITS)
   165558    || (cArg==FTS3_MATCHINFO_LHITS_BM)
   165559   ){
   165560     return SQLITE_OK;
   165561   }
   165562   sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
   165563   return SQLITE_ERROR;
   165564 }
   165565 
   165566 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
   165567   int nVal;                       /* Number of integers output by cArg */
   165568 
   165569   switch( cArg ){
   165570     case FTS3_MATCHINFO_NDOC:
   165571     case FTS3_MATCHINFO_NPHRASE:
   165572     case FTS3_MATCHINFO_NCOL:
   165573       nVal = 1;
   165574       break;
   165575 
   165576     case FTS3_MATCHINFO_AVGLENGTH:
   165577     case FTS3_MATCHINFO_LENGTH:
   165578     case FTS3_MATCHINFO_LCS:
   165579       nVal = pInfo->nCol;
   165580       break;
   165581 
   165582     case FTS3_MATCHINFO_LHITS:
   165583       nVal = pInfo->nCol * pInfo->nPhrase;
   165584       break;
   165585 
   165586     case FTS3_MATCHINFO_LHITS_BM:
   165587       nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
   165588       break;
   165589 
   165590     default:
   165591       assert( cArg==FTS3_MATCHINFO_HITS );
   165592       nVal = pInfo->nCol * pInfo->nPhrase * 3;
   165593       break;
   165594   }
   165595 
   165596   return nVal;
   165597 }
   165598 
   165599 static int fts3MatchinfoSelectDoctotal(
   165600   Fts3Table *pTab,
   165601   sqlite3_stmt **ppStmt,
   165602   sqlite3_int64 *pnDoc,
   165603   const char **paLen
   165604 ){
   165605   sqlite3_stmt *pStmt;
   165606   const char *a;
   165607   sqlite3_int64 nDoc;
   165608 
   165609   if( !*ppStmt ){
   165610     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
   165611     if( rc!=SQLITE_OK ) return rc;
   165612   }
   165613   pStmt = *ppStmt;
   165614   assert( sqlite3_data_count(pStmt)==1 );
   165615 
   165616   a = sqlite3_column_blob(pStmt, 0);
   165617   a += sqlite3Fts3GetVarint(a, &nDoc);
   165618   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
   165619   *pnDoc = (u32)nDoc;
   165620 
   165621   if( paLen ) *paLen = a;
   165622   return SQLITE_OK;
   165623 }
   165624 
   165625 /*
   165626 ** An instance of the following structure is used to store state while
   165627 ** iterating through a multi-column position-list corresponding to the
   165628 ** hits for a single phrase on a single row in order to calculate the
   165629 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
   165630 */
   165631 typedef struct LcsIterator LcsIterator;
   165632 struct LcsIterator {
   165633   Fts3Expr *pExpr;                /* Pointer to phrase expression */
   165634   int iPosOffset;                 /* Tokens count up to end of this phrase */
   165635   char *pRead;                    /* Cursor used to iterate through aDoclist */
   165636   int iPos;                       /* Current position */
   165637 };
   165638 
   165639 /*
   165640 ** If LcsIterator.iCol is set to the following value, the iterator has
   165641 ** finished iterating through all offsets for all columns.
   165642 */
   165643 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
   165644 
   165645 static int fts3MatchinfoLcsCb(
   165646   Fts3Expr *pExpr,                /* Phrase expression node */
   165647   int iPhrase,                    /* Phrase number (numbered from zero) */
   165648   void *pCtx                      /* Pointer to MatchInfo structure */
   165649 ){
   165650   LcsIterator *aIter = (LcsIterator *)pCtx;
   165651   aIter[iPhrase].pExpr = pExpr;
   165652   return SQLITE_OK;
   165653 }
   165654 
   165655 /*
   165656 ** Advance the iterator passed as an argument to the next position. Return
   165657 ** 1 if the iterator is at EOF or if it now points to the start of the
   165658 ** position list for the next column.
   165659 */
   165660 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
   165661   char *pRead = pIter->pRead;
   165662   sqlite3_int64 iRead;
   165663   int rc = 0;
   165664 
   165665   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   165666   if( iRead==0 || iRead==1 ){
   165667     pRead = 0;
   165668     rc = 1;
   165669   }else{
   165670     pIter->iPos += (int)(iRead-2);
   165671   }
   165672 
   165673   pIter->pRead = pRead;
   165674   return rc;
   165675 }
   165676 
   165677 /*
   165678 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
   165679 **
   165680 ** If the call is successful, the longest-common-substring lengths for each
   165681 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
   165682 ** array before returning. SQLITE_OK is returned in this case.
   165683 **
   165684 ** Otherwise, if an error occurs, an SQLite error code is returned and the
   165685 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
   165686 ** undefined.
   165687 */
   165688 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
   165689   LcsIterator *aIter;
   165690   int i;
   165691   int iCol;
   165692   int nToken = 0;
   165693 
   165694   /* Allocate and populate the array of LcsIterator objects. The array
   165695   ** contains one element for each matchable phrase in the query.
   165696   **/
   165697   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
   165698   if( !aIter ) return SQLITE_NOMEM;
   165699   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
   165700   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
   165701 
   165702   for(i=0; i<pInfo->nPhrase; i++){
   165703     LcsIterator *pIter = &aIter[i];
   165704     nToken -= pIter->pExpr->pPhrase->nToken;
   165705     pIter->iPosOffset = nToken;
   165706   }
   165707 
   165708   for(iCol=0; iCol<pInfo->nCol; iCol++){
   165709     int nLcs = 0;                 /* LCS value for this column */
   165710     int nLive = 0;                /* Number of iterators in aIter not at EOF */
   165711 
   165712     for(i=0; i<pInfo->nPhrase; i++){
   165713       int rc;
   165714       LcsIterator *pIt = &aIter[i];
   165715       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
   165716       if( rc!=SQLITE_OK ) return rc;
   165717       if( pIt->pRead ){
   165718         pIt->iPos = pIt->iPosOffset;
   165719         fts3LcsIteratorAdvance(&aIter[i]);
   165720         nLive++;
   165721       }
   165722     }
   165723 
   165724     while( nLive>0 ){
   165725       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
   165726       int nThisLcs = 0;           /* LCS for the current iterator positions */
   165727 
   165728       for(i=0; i<pInfo->nPhrase; i++){
   165729         LcsIterator *pIter = &aIter[i];
   165730         if( pIter->pRead==0 ){
   165731           /* This iterator is already at EOF for this column. */
   165732           nThisLcs = 0;
   165733         }else{
   165734           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
   165735             pAdv = pIter;
   165736           }
   165737           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
   165738             nThisLcs++;
   165739           }else{
   165740             nThisLcs = 1;
   165741           }
   165742           if( nThisLcs>nLcs ) nLcs = nThisLcs;
   165743         }
   165744       }
   165745       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
   165746     }
   165747 
   165748     pInfo->aMatchinfo[iCol] = nLcs;
   165749   }
   165750 
   165751   sqlite3_free(aIter);
   165752   return SQLITE_OK;
   165753 }
   165754 
   165755 /*
   165756 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
   165757 ** be returned by the matchinfo() function. Argument zArg contains the
   165758 ** format string passed as the second argument to matchinfo (or the
   165759 ** default value "pcx" if no second argument was specified). The format
   165760 ** string has already been validated and the pInfo->aMatchinfo[] array
   165761 ** is guaranteed to be large enough for the output.
   165762 **
   165763 ** If bGlobal is true, then populate all fields of the matchinfo() output.
   165764 ** If it is false, then assume that those fields that do not change between
   165765 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
   165766 ** have already been populated.
   165767 **
   165768 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   165769 ** occurs. If a value other than SQLITE_OK is returned, the state the
   165770 ** pInfo->aMatchinfo[] buffer is left in is undefined.
   165771 */
   165772 static int fts3MatchinfoValues(
   165773   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   165774   int bGlobal,                    /* True to grab the global stats */
   165775   MatchInfo *pInfo,               /* Matchinfo context object */
   165776   const char *zArg                /* Matchinfo format string */
   165777 ){
   165778   int rc = SQLITE_OK;
   165779   int i;
   165780   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   165781   sqlite3_stmt *pSelect = 0;
   165782 
   165783   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
   165784     pInfo->flag = zArg[i];
   165785     switch( zArg[i] ){
   165786       case FTS3_MATCHINFO_NPHRASE:
   165787         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
   165788         break;
   165789 
   165790       case FTS3_MATCHINFO_NCOL:
   165791         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
   165792         break;
   165793 
   165794       case FTS3_MATCHINFO_NDOC:
   165795         if( bGlobal ){
   165796           sqlite3_int64 nDoc = 0;
   165797           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
   165798           pInfo->aMatchinfo[0] = (u32)nDoc;
   165799         }
   165800         break;
   165801 
   165802       case FTS3_MATCHINFO_AVGLENGTH:
   165803         if( bGlobal ){
   165804           sqlite3_int64 nDoc;     /* Number of rows in table */
   165805           const char *a;          /* Aggregate column length array */
   165806 
   165807           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
   165808           if( rc==SQLITE_OK ){
   165809             int iCol;
   165810             for(iCol=0; iCol<pInfo->nCol; iCol++){
   165811               u32 iVal;
   165812               sqlite3_int64 nToken;
   165813               a += sqlite3Fts3GetVarint(a, &nToken);
   165814               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
   165815               pInfo->aMatchinfo[iCol] = iVal;
   165816             }
   165817           }
   165818         }
   165819         break;
   165820 
   165821       case FTS3_MATCHINFO_LENGTH: {
   165822         sqlite3_stmt *pSelectDocsize = 0;
   165823         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
   165824         if( rc==SQLITE_OK ){
   165825           int iCol;
   165826           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
   165827           for(iCol=0; iCol<pInfo->nCol; iCol++){
   165828             sqlite3_int64 nToken;
   165829             a += sqlite3Fts3GetVarint(a, &nToken);
   165830             pInfo->aMatchinfo[iCol] = (u32)nToken;
   165831           }
   165832         }
   165833         sqlite3_reset(pSelectDocsize);
   165834         break;
   165835       }
   165836 
   165837       case FTS3_MATCHINFO_LCS:
   165838         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   165839         if( rc==SQLITE_OK ){
   165840           rc = fts3MatchinfoLcs(pCsr, pInfo);
   165841         }
   165842         break;
   165843 
   165844       case FTS3_MATCHINFO_LHITS_BM:
   165845       case FTS3_MATCHINFO_LHITS: {
   165846         int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
   165847         memset(pInfo->aMatchinfo, 0, nZero);
   165848         fts3ExprLHitGather(pCsr->pExpr, pInfo);
   165849         break;
   165850       }
   165851 
   165852       default: {
   165853         Fts3Expr *pExpr;
   165854         assert( zArg[i]==FTS3_MATCHINFO_HITS );
   165855         pExpr = pCsr->pExpr;
   165856         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   165857         if( rc!=SQLITE_OK ) break;
   165858         if( bGlobal ){
   165859           if( pCsr->pDeferred ){
   165860             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
   165861             if( rc!=SQLITE_OK ) break;
   165862           }
   165863           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
   165864           sqlite3Fts3EvalTestDeferred(pCsr, &rc);
   165865           if( rc!=SQLITE_OK ) break;
   165866         }
   165867         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
   165868         break;
   165869       }
   165870     }
   165871 
   165872     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
   165873   }
   165874 
   165875   sqlite3_reset(pSelect);
   165876   return rc;
   165877 }
   165878 
   165879 
   165880 /*
   165881 ** Populate pCsr->aMatchinfo[] with data for the current row. The
   165882 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
   165883 */
   165884 static void fts3GetMatchinfo(
   165885   sqlite3_context *pCtx,        /* Return results here */
   165886   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
   165887   const char *zArg                /* Second argument to matchinfo() function */
   165888 ){
   165889   MatchInfo sInfo;
   165890   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   165891   int rc = SQLITE_OK;
   165892   int bGlobal = 0;                /* Collect 'global' stats as well as local */
   165893 
   165894   u32 *aOut = 0;
   165895   void (*xDestroyOut)(void*) = 0;
   165896 
   165897   memset(&sInfo, 0, sizeof(MatchInfo));
   165898   sInfo.pCursor = pCsr;
   165899   sInfo.nCol = pTab->nColumn;
   165900 
   165901   /* If there is cached matchinfo() data, but the format string for the
   165902   ** cache does not match the format string for this request, discard
   165903   ** the cached data. */
   165904   if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
   165905     sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
   165906     pCsr->pMIBuffer = 0;
   165907   }
   165908 
   165909   /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
   165910   ** matchinfo function has been called for this query. In this case
   165911   ** allocate the array used to accumulate the matchinfo data and
   165912   ** initialize those elements that are constant for every row.
   165913   */
   165914   if( pCsr->pMIBuffer==0 ){
   165915     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
   165916     int i;                        /* Used to iterate through zArg */
   165917 
   165918     /* Determine the number of phrases in the query */
   165919     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
   165920     sInfo.nPhrase = pCsr->nPhrase;
   165921 
   165922     /* Determine the number of integers in the buffer returned by this call. */
   165923     for(i=0; zArg[i]; i++){
   165924       char *zErr = 0;
   165925       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
   165926         sqlite3_result_error(pCtx, zErr, -1);
   165927         sqlite3_free(zErr);
   165928         return;
   165929       }
   165930       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
   165931     }
   165932 
   165933     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
   165934     pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
   165935     if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
   165936 
   165937     pCsr->isMatchinfoNeeded = 1;
   165938     bGlobal = 1;
   165939   }
   165940 
   165941   if( rc==SQLITE_OK ){
   165942     xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
   165943     if( xDestroyOut==0 ){
   165944       rc = SQLITE_NOMEM;
   165945     }
   165946   }
   165947 
   165948   if( rc==SQLITE_OK ){
   165949     sInfo.aMatchinfo = aOut;
   165950     sInfo.nPhrase = pCsr->nPhrase;
   165951     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
   165952     if( bGlobal ){
   165953       fts3MIBufferSetGlobal(pCsr->pMIBuffer);
   165954     }
   165955   }
   165956 
   165957   if( rc!=SQLITE_OK ){
   165958     sqlite3_result_error_code(pCtx, rc);
   165959     if( xDestroyOut ) xDestroyOut(aOut);
   165960   }else{
   165961     int n = pCsr->pMIBuffer->nElem * sizeof(u32);
   165962     sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
   165963   }
   165964 }
   165965 
   165966 /*
   165967 ** Implementation of snippet() function.
   165968 */
   165969 SQLITE_PRIVATE void sqlite3Fts3Snippet(
   165970   sqlite3_context *pCtx,          /* SQLite function call context */
   165971   Fts3Cursor *pCsr,               /* Cursor object */
   165972   const char *zStart,             /* Snippet start text - "<b>" */
   165973   const char *zEnd,               /* Snippet end text - "</b>" */
   165974   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
   165975   int iCol,                       /* Extract snippet from this column */
   165976   int nToken                      /* Approximate number of tokens in snippet */
   165977 ){
   165978   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   165979   int rc = SQLITE_OK;
   165980   int i;
   165981   StrBuffer res = {0, 0, 0};
   165982 
   165983   /* The returned text includes up to four fragments of text extracted from
   165984   ** the data in the current row. The first iteration of the for(...) loop
   165985   ** below attempts to locate a single fragment of text nToken tokens in
   165986   ** size that contains at least one instance of all phrases in the query
   165987   ** expression that appear in the current row. If such a fragment of text
   165988   ** cannot be found, the second iteration of the loop attempts to locate
   165989   ** a pair of fragments, and so on.
   165990   */
   165991   int nSnippet = 0;               /* Number of fragments in this snippet */
   165992   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
   165993   int nFToken = -1;               /* Number of tokens in each fragment */
   165994 
   165995   if( !pCsr->pExpr ){
   165996     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   165997     return;
   165998   }
   165999 
   166000   for(nSnippet=1; 1; nSnippet++){
   166001 
   166002     int iSnip;                    /* Loop counter 0..nSnippet-1 */
   166003     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
   166004     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
   166005 
   166006     if( nToken>=0 ){
   166007       nFToken = (nToken+nSnippet-1) / nSnippet;
   166008     }else{
   166009       nFToken = -1 * nToken;
   166010     }
   166011 
   166012     for(iSnip=0; iSnip<nSnippet; iSnip++){
   166013       int iBestScore = -1;        /* Best score of columns checked so far */
   166014       int iRead;                  /* Used to iterate through columns */
   166015       SnippetFragment *pFragment = &aSnippet[iSnip];
   166016 
   166017       memset(pFragment, 0, sizeof(*pFragment));
   166018 
   166019       /* Loop through all columns of the table being considered for snippets.
   166020       ** If the iCol argument to this function was negative, this means all
   166021       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
   166022       */
   166023       for(iRead=0; iRead<pTab->nColumn; iRead++){
   166024         SnippetFragment sF = {0, 0, 0, 0};
   166025         int iS = 0;
   166026         if( iCol>=0 && iRead!=iCol ) continue;
   166027 
   166028         /* Find the best snippet of nFToken tokens in column iRead. */
   166029         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
   166030         if( rc!=SQLITE_OK ){
   166031           goto snippet_out;
   166032         }
   166033         if( iS>iBestScore ){
   166034           *pFragment = sF;
   166035           iBestScore = iS;
   166036         }
   166037       }
   166038 
   166039       mCovered |= pFragment->covered;
   166040     }
   166041 
   166042     /* If all query phrases seen by fts3BestSnippet() are present in at least
   166043     ** one of the nSnippet snippet fragments, break out of the loop.
   166044     */
   166045     assert( (mCovered&mSeen)==mCovered );
   166046     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
   166047   }
   166048 
   166049   assert( nFToken>0 );
   166050 
   166051   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
   166052     rc = fts3SnippetText(pCsr, &aSnippet[i],
   166053         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
   166054     );
   166055   }
   166056 
   166057  snippet_out:
   166058   sqlite3Fts3SegmentsClose(pTab);
   166059   if( rc!=SQLITE_OK ){
   166060     sqlite3_result_error_code(pCtx, rc);
   166061     sqlite3_free(res.z);
   166062   }else{
   166063     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
   166064   }
   166065 }
   166066 
   166067 
   166068 typedef struct TermOffset TermOffset;
   166069 typedef struct TermOffsetCtx TermOffsetCtx;
   166070 
   166071 struct TermOffset {
   166072   char *pList;                    /* Position-list */
   166073   int iPos;                       /* Position just read from pList */
   166074   int iOff;                       /* Offset of this term from read positions */
   166075 };
   166076 
   166077 struct TermOffsetCtx {
   166078   Fts3Cursor *pCsr;
   166079   int iCol;                       /* Column of table to populate aTerm for */
   166080   int iTerm;
   166081   sqlite3_int64 iDocid;
   166082   TermOffset *aTerm;
   166083 };
   166084 
   166085 /*
   166086 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
   166087 */
   166088 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
   166089   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
   166090   int nTerm;                      /* Number of tokens in phrase */
   166091   int iTerm;                      /* For looping through nTerm phrase terms */
   166092   char *pList;                    /* Pointer to position list for phrase */
   166093   int iPos = 0;                   /* First position in position-list */
   166094   int rc;
   166095 
   166096   UNUSED_PARAMETER(iPhrase);
   166097   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
   166098   nTerm = pExpr->pPhrase->nToken;
   166099   if( pList ){
   166100     fts3GetDeltaPosition(&pList, &iPos);
   166101     assert( iPos>=0 );
   166102   }
   166103 
   166104   for(iTerm=0; iTerm<nTerm; iTerm++){
   166105     TermOffset *pT = &p->aTerm[p->iTerm++];
   166106     pT->iOff = nTerm-iTerm-1;
   166107     pT->pList = pList;
   166108     pT->iPos = iPos;
   166109   }
   166110 
   166111   return rc;
   166112 }
   166113 
   166114 /*
   166115 ** Implementation of offsets() function.
   166116 */
   166117 SQLITE_PRIVATE void sqlite3Fts3Offsets(
   166118   sqlite3_context *pCtx,          /* SQLite function call context */
   166119   Fts3Cursor *pCsr                /* Cursor object */
   166120 ){
   166121   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   166122   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
   166123   int rc;                         /* Return Code */
   166124   int nToken;                     /* Number of tokens in query */
   166125   int iCol;                       /* Column currently being processed */
   166126   StrBuffer res = {0, 0, 0};      /* Result string */
   166127   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
   166128 
   166129   if( !pCsr->pExpr ){
   166130     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   166131     return;
   166132   }
   166133 
   166134   memset(&sCtx, 0, sizeof(sCtx));
   166135   assert( pCsr->isRequireSeek==0 );
   166136 
   166137   /* Count the number of terms in the query */
   166138   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
   166139   if( rc!=SQLITE_OK ) goto offsets_out;
   166140 
   166141   /* Allocate the array of TermOffset iterators. */
   166142   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
   166143   if( 0==sCtx.aTerm ){
   166144     rc = SQLITE_NOMEM;
   166145     goto offsets_out;
   166146   }
   166147   sCtx.iDocid = pCsr->iPrevId;
   166148   sCtx.pCsr = pCsr;
   166149 
   166150   /* Loop through the table columns, appending offset information to
   166151   ** string-buffer res for each column.
   166152   */
   166153   for(iCol=0; iCol<pTab->nColumn; iCol++){
   166154     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
   166155     const char *ZDUMMY;           /* Dummy argument used with xNext() */
   166156     int NDUMMY = 0;               /* Dummy argument used with xNext() */
   166157     int iStart = 0;
   166158     int iEnd = 0;
   166159     int iCurrent = 0;
   166160     const char *zDoc;
   166161     int nDoc;
   166162 
   166163     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
   166164     ** no way that this operation can fail, so the return code from
   166165     ** fts3ExprIterate() can be discarded.
   166166     */
   166167     sCtx.iCol = iCol;
   166168     sCtx.iTerm = 0;
   166169     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
   166170 
   166171     /* Retreive the text stored in column iCol. If an SQL NULL is stored
   166172     ** in column iCol, jump immediately to the next iteration of the loop.
   166173     ** If an OOM occurs while retrieving the data (this can happen if SQLite
   166174     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
   166175     ** to the caller.
   166176     */
   166177     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
   166178     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   166179     if( zDoc==0 ){
   166180       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
   166181         continue;
   166182       }
   166183       rc = SQLITE_NOMEM;
   166184       goto offsets_out;
   166185     }
   166186 
   166187     /* Initialize a tokenizer iterator to iterate through column iCol. */
   166188     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
   166189         zDoc, nDoc, &pC
   166190     );
   166191     if( rc!=SQLITE_OK ) goto offsets_out;
   166192 
   166193     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   166194     while( rc==SQLITE_OK ){
   166195       int i;                      /* Used to loop through terms */
   166196       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
   166197       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
   166198 
   166199       for(i=0; i<nToken; i++){
   166200         TermOffset *pT = &sCtx.aTerm[i];
   166201         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
   166202           iMinPos = pT->iPos-pT->iOff;
   166203           pTerm = pT;
   166204         }
   166205       }
   166206 
   166207       if( !pTerm ){
   166208         /* All offsets for this column have been gathered. */
   166209         rc = SQLITE_DONE;
   166210       }else{
   166211         assert( iCurrent<=iMinPos );
   166212         if( 0==(0xFE&*pTerm->pList) ){
   166213           pTerm->pList = 0;
   166214         }else{
   166215           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
   166216         }
   166217         while( rc==SQLITE_OK && iCurrent<iMinPos ){
   166218           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   166219         }
   166220         if( rc==SQLITE_OK ){
   166221           char aBuffer[64];
   166222           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
   166223               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
   166224           );
   166225           rc = fts3StringAppend(&res, aBuffer, -1);
   166226         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
   166227           rc = FTS_CORRUPT_VTAB;
   166228         }
   166229       }
   166230     }
   166231     if( rc==SQLITE_DONE ){
   166232       rc = SQLITE_OK;
   166233     }
   166234 
   166235     pMod->xClose(pC);
   166236     if( rc!=SQLITE_OK ) goto offsets_out;
   166237   }
   166238 
   166239  offsets_out:
   166240   sqlite3_free(sCtx.aTerm);
   166241   assert( rc!=SQLITE_DONE );
   166242   sqlite3Fts3SegmentsClose(pTab);
   166243   if( rc!=SQLITE_OK ){
   166244     sqlite3_result_error_code(pCtx,  rc);
   166245     sqlite3_free(res.z);
   166246   }else{
   166247     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
   166248   }
   166249   return;
   166250 }
   166251 
   166252 /*
   166253 ** Implementation of matchinfo() function.
   166254 */
   166255 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
   166256   sqlite3_context *pContext,      /* Function call context */
   166257   Fts3Cursor *pCsr,               /* FTS3 table cursor */
   166258   const char *zArg                /* Second arg to matchinfo() function */
   166259 ){
   166260   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   166261   const char *zFormat;
   166262 
   166263   if( zArg ){
   166264     zFormat = zArg;
   166265   }else{
   166266     zFormat = FTS3_MATCHINFO_DEFAULT;
   166267   }
   166268 
   166269   if( !pCsr->pExpr ){
   166270     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
   166271     return;
   166272   }else{
   166273     /* Retrieve matchinfo() data. */
   166274     fts3GetMatchinfo(pContext, pCsr, zFormat);
   166275     sqlite3Fts3SegmentsClose(pTab);
   166276   }
   166277 }
   166278 
   166279 #endif
   166280 
   166281 /************** End of fts3_snippet.c ****************************************/
   166282 /************** Begin file fts3_unicode.c ************************************/
   166283 /*
   166284 ** 2012 May 24
   166285 **
   166286 ** The author disclaims copyright to this source code.  In place of
   166287 ** a legal notice, here is a blessing:
   166288 **
   166289 **    May you do good and not evil.
   166290 **    May you find forgiveness for yourself and forgive others.
   166291 **    May you share freely, never taking more than you give.
   166292 **
   166293 ******************************************************************************
   166294 **
   166295 ** Implementation of the "unicode" full-text-search tokenizer.
   166296 */
   166297 
   166298 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   166299 
   166300 /* #include "fts3Int.h" */
   166301 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   166302 
   166303 /* #include <assert.h> */
   166304 /* #include <stdlib.h> */
   166305 /* #include <stdio.h> */
   166306 /* #include <string.h> */
   166307 
   166308 /* #include "fts3_tokenizer.h" */
   166309 
   166310 /*
   166311 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
   166312 ** from the sqlite3 source file utf.c. If this file is compiled as part
   166313 ** of the amalgamation, they are not required.
   166314 */
   166315 #ifndef SQLITE_AMALGAMATION
   166316 
   166317 static const unsigned char sqlite3Utf8Trans1[] = {
   166318   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   166319   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   166320   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   166321   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   166322   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   166323   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   166324   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   166325   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   166326 };
   166327 
   166328 #define READ_UTF8(zIn, zTerm, c)                           \
   166329   c = *(zIn++);                                            \
   166330   if( c>=0xc0 ){                                           \
   166331     c = sqlite3Utf8Trans1[c-0xc0];                         \
   166332     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   166333       c = (c<<6) + (0x3f & *(zIn++));                      \
   166334     }                                                      \
   166335     if( c<0x80                                             \
   166336         || (c&0xFFFFF800)==0xD800                          \
   166337         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   166338   }
   166339 
   166340 #define WRITE_UTF8(zOut, c) {                          \
   166341   if( c<0x00080 ){                                     \
   166342     *zOut++ = (u8)(c&0xFF);                            \
   166343   }                                                    \
   166344   else if( c<0x00800 ){                                \
   166345     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   166346     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   166347   }                                                    \
   166348   else if( c<0x10000 ){                                \
   166349     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   166350     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   166351     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   166352   }else{                                               \
   166353     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   166354     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   166355     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   166356     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   166357   }                                                    \
   166358 }
   166359 
   166360 #endif /* ifndef SQLITE_AMALGAMATION */
   166361 
   166362 typedef struct unicode_tokenizer unicode_tokenizer;
   166363 typedef struct unicode_cursor unicode_cursor;
   166364 
   166365 struct unicode_tokenizer {
   166366   sqlite3_tokenizer base;
   166367   int bRemoveDiacritic;
   166368   int nException;
   166369   int *aiException;
   166370 };
   166371 
   166372 struct unicode_cursor {
   166373   sqlite3_tokenizer_cursor base;
   166374   const unsigned char *aInput;    /* Input text being tokenized */
   166375   int nInput;                     /* Size of aInput[] in bytes */
   166376   int iOff;                       /* Current offset within aInput[] */
   166377   int iToken;                     /* Index of next token to be returned */
   166378   char *zToken;                   /* storage for current token */
   166379   int nAlloc;                     /* space allocated at zToken */
   166380 };
   166381 
   166382 
   166383 /*
   166384 ** Destroy a tokenizer allocated by unicodeCreate().
   166385 */
   166386 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
   166387   if( pTokenizer ){
   166388     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
   166389     sqlite3_free(p->aiException);
   166390     sqlite3_free(p);
   166391   }
   166392   return SQLITE_OK;
   166393 }
   166394 
   166395 /*
   166396 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
   166397 ** statement has specified that the tokenizer for this table shall consider
   166398 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
   166399 ** token characters (if bAlnum==1).
   166400 **
   166401 ** For each codepoint in the zIn/nIn string, this function checks if the
   166402 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
   166403 ** If so, no action is taken. Otherwise, the codepoint is added to the
   166404 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
   166405 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
   166406 ** codepoints in the aiException[] array.
   166407 **
   166408 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
   166409 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
   166410 ** It is not possible to change the behavior of the tokenizer with respect
   166411 ** to these codepoints.
   166412 */
   166413 static int unicodeAddExceptions(
   166414   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
   166415   int bAlnum,                     /* Replace Isalnum() return value with this */
   166416   const char *zIn,                /* Array of characters to make exceptions */
   166417   int nIn                         /* Length of z in bytes */
   166418 ){
   166419   const unsigned char *z = (const unsigned char *)zIn;
   166420   const unsigned char *zTerm = &z[nIn];
   166421   unsigned int iCode;
   166422   int nEntry = 0;
   166423 
   166424   assert( bAlnum==0 || bAlnum==1 );
   166425 
   166426   while( z<zTerm ){
   166427     READ_UTF8(z, zTerm, iCode);
   166428     assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
   166429     if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
   166430      && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
   166431     ){
   166432       nEntry++;
   166433     }
   166434   }
   166435 
   166436   if( nEntry ){
   166437     int *aNew;                    /* New aiException[] array */
   166438     int nNew;                     /* Number of valid entries in array aNew[] */
   166439 
   166440     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
   166441     if( aNew==0 ) return SQLITE_NOMEM;
   166442     nNew = p->nException;
   166443 
   166444     z = (const unsigned char *)zIn;
   166445     while( z<zTerm ){
   166446       READ_UTF8(z, zTerm, iCode);
   166447       if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
   166448        && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
   166449       ){
   166450         int i, j;
   166451         for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
   166452         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
   166453         aNew[i] = (int)iCode;
   166454         nNew++;
   166455       }
   166456     }
   166457     p->aiException = aNew;
   166458     p->nException = nNew;
   166459   }
   166460 
   166461   return SQLITE_OK;
   166462 }
   166463 
   166464 /*
   166465 ** Return true if the p->aiException[] array contains the value iCode.
   166466 */
   166467 static int unicodeIsException(unicode_tokenizer *p, int iCode){
   166468   if( p->nException>0 ){
   166469     int *a = p->aiException;
   166470     int iLo = 0;
   166471     int iHi = p->nException-1;
   166472 
   166473     while( iHi>=iLo ){
   166474       int iTest = (iHi + iLo) / 2;
   166475       if( iCode==a[iTest] ){
   166476         return 1;
   166477       }else if( iCode>a[iTest] ){
   166478         iLo = iTest+1;
   166479       }else{
   166480         iHi = iTest-1;
   166481       }
   166482     }
   166483   }
   166484 
   166485   return 0;
   166486 }
   166487 
   166488 /*
   166489 ** Return true if, for the purposes of tokenization, codepoint iCode is
   166490 ** considered a token character (not a separator).
   166491 */
   166492 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
   166493   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
   166494   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
   166495 }
   166496 
   166497 /*
   166498 ** Create a new tokenizer instance.
   166499 */
   166500 static int unicodeCreate(
   166501   int nArg,                       /* Size of array argv[] */
   166502   const char * const *azArg,      /* Tokenizer creation arguments */
   166503   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
   166504 ){
   166505   unicode_tokenizer *pNew;        /* New tokenizer object */
   166506   int i;
   166507   int rc = SQLITE_OK;
   166508 
   166509   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
   166510   if( pNew==NULL ) return SQLITE_NOMEM;
   166511   memset(pNew, 0, sizeof(unicode_tokenizer));
   166512   pNew->bRemoveDiacritic = 1;
   166513 
   166514   for(i=0; rc==SQLITE_OK && i<nArg; i++){
   166515     const char *z = azArg[i];
   166516     int n = (int)strlen(z);
   166517 
   166518     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
   166519       pNew->bRemoveDiacritic = 1;
   166520     }
   166521     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
   166522       pNew->bRemoveDiacritic = 0;
   166523     }
   166524     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
   166525       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
   166526     }
   166527     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
   166528       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
   166529     }
   166530     else{
   166531       /* Unrecognized argument */
   166532       rc  = SQLITE_ERROR;
   166533     }
   166534   }
   166535 
   166536   if( rc!=SQLITE_OK ){
   166537     unicodeDestroy((sqlite3_tokenizer *)pNew);
   166538     pNew = 0;
   166539   }
   166540   *pp = (sqlite3_tokenizer *)pNew;
   166541   return rc;
   166542 }
   166543 
   166544 /*
   166545 ** Prepare to begin tokenizing a particular string.  The input
   166546 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   166547 ** used to incrementally tokenize this string is returned in
   166548 ** *ppCursor.
   166549 */
   166550 static int unicodeOpen(
   166551   sqlite3_tokenizer *p,           /* The tokenizer */
   166552   const char *aInput,             /* Input string */
   166553   int nInput,                     /* Size of string aInput in bytes */
   166554   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
   166555 ){
   166556   unicode_cursor *pCsr;
   166557 
   166558   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
   166559   if( pCsr==0 ){
   166560     return SQLITE_NOMEM;
   166561   }
   166562   memset(pCsr, 0, sizeof(unicode_cursor));
   166563 
   166564   pCsr->aInput = (const unsigned char *)aInput;
   166565   if( aInput==0 ){
   166566     pCsr->nInput = 0;
   166567   }else if( nInput<0 ){
   166568     pCsr->nInput = (int)strlen(aInput);
   166569   }else{
   166570     pCsr->nInput = nInput;
   166571   }
   166572 
   166573   *pp = &pCsr->base;
   166574   UNUSED_PARAMETER(p);
   166575   return SQLITE_OK;
   166576 }
   166577 
   166578 /*
   166579 ** Close a tokenization cursor previously opened by a call to
   166580 ** simpleOpen() above.
   166581 */
   166582 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
   166583   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
   166584   sqlite3_free(pCsr->zToken);
   166585   sqlite3_free(pCsr);
   166586   return SQLITE_OK;
   166587 }
   166588 
   166589 /*
   166590 ** Extract the next token from a tokenization cursor.  The cursor must
   166591 ** have been opened by a prior call to simpleOpen().
   166592 */
   166593 static int unicodeNext(
   166594   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
   166595   const char **paToken,           /* OUT: Token text */
   166596   int *pnToken,                   /* OUT: Number of bytes at *paToken */
   166597   int *piStart,                   /* OUT: Starting offset of token */
   166598   int *piEnd,                     /* OUT: Ending offset of token */
   166599   int *piPos                      /* OUT: Position integer of token */
   166600 ){
   166601   unicode_cursor *pCsr = (unicode_cursor *)pC;
   166602   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
   166603   unsigned int iCode = 0;
   166604   char *zOut;
   166605   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
   166606   const unsigned char *zStart = z;
   166607   const unsigned char *zEnd;
   166608   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
   166609 
   166610   /* Scan past any delimiter characters before the start of the next token.
   166611   ** Return SQLITE_DONE early if this takes us all the way to the end of
   166612   ** the input.  */
   166613   while( z<zTerm ){
   166614     READ_UTF8(z, zTerm, iCode);
   166615     if( unicodeIsAlnum(p, (int)iCode) ) break;
   166616     zStart = z;
   166617   }
   166618   if( zStart>=zTerm ) return SQLITE_DONE;
   166619 
   166620   zOut = pCsr->zToken;
   166621   do {
   166622     int iOut;
   166623 
   166624     /* Grow the output buffer if required. */
   166625     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
   166626       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
   166627       if( !zNew ) return SQLITE_NOMEM;
   166628       zOut = &zNew[zOut - pCsr->zToken];
   166629       pCsr->zToken = zNew;
   166630       pCsr->nAlloc += 64;
   166631     }
   166632 
   166633     /* Write the folded case of the last character read to the output */
   166634     zEnd = z;
   166635     iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
   166636     if( iOut ){
   166637       WRITE_UTF8(zOut, iOut);
   166638     }
   166639 
   166640     /* If the cursor is not at EOF, read the next character */
   166641     if( z>=zTerm ) break;
   166642     READ_UTF8(z, zTerm, iCode);
   166643   }while( unicodeIsAlnum(p, (int)iCode)
   166644        || sqlite3FtsUnicodeIsdiacritic((int)iCode)
   166645   );
   166646 
   166647   /* Set the output variables and return. */
   166648   pCsr->iOff = (int)(z - pCsr->aInput);
   166649   *paToken = pCsr->zToken;
   166650   *pnToken = (int)(zOut - pCsr->zToken);
   166651   *piStart = (int)(zStart - pCsr->aInput);
   166652   *piEnd = (int)(zEnd - pCsr->aInput);
   166653   *piPos = pCsr->iToken++;
   166654   return SQLITE_OK;
   166655 }
   166656 
   166657 /*
   166658 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
   166659 ** structure for the unicode tokenizer.
   166660 */
   166661 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
   166662   static const sqlite3_tokenizer_module module = {
   166663     0,
   166664     unicodeCreate,
   166665     unicodeDestroy,
   166666     unicodeOpen,
   166667     unicodeClose,
   166668     unicodeNext,
   166669     0,
   166670   };
   166671   *ppModule = &module;
   166672 }
   166673 
   166674 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   166675 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
   166676 
   166677 /************** End of fts3_unicode.c ****************************************/
   166678 /************** Begin file fts3_unicode2.c ***********************************/
   166679 /*
   166680 ** 2012 May 25
   166681 **
   166682 ** The author disclaims copyright to this source code.  In place of
   166683 ** a legal notice, here is a blessing:
   166684 **
   166685 **    May you do good and not evil.
   166686 **    May you find forgiveness for yourself and forgive others.
   166687 **    May you share freely, never taking more than you give.
   166688 **
   166689 ******************************************************************************
   166690 */
   166691 
   166692 /*
   166693 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
   166694 */
   166695 
   166696 #ifndef SQLITE_DISABLE_FTS3_UNICODE
   166697 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
   166698 
   166699 /* #include <assert.h> */
   166700 
   166701 /*
   166702 ** Return true if the argument corresponds to a unicode codepoint
   166703 ** classified as either a letter or a number. Otherwise false.
   166704 **
   166705 ** The results are undefined if the value passed to this function
   166706 ** is less than zero.
   166707 */
   166708 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
   166709   /* Each unsigned integer in the following array corresponds to a contiguous
   166710   ** range of unicode codepoints that are not either letters or numbers (i.e.
   166711   ** codepoints for which this function should return 0).
   166712   **
   166713   ** The most significant 22 bits in each 32-bit value contain the first
   166714   ** codepoint in the range. The least significant 10 bits are used to store
   166715   ** the size of the range (always at least 1). In other words, the value
   166716   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
   166717   ** C. It is not possible to represent a range larger than 1023 codepoints
   166718   ** using this format.
   166719   */
   166720   static const unsigned int aEntry[] = {
   166721     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
   166722     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
   166723     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
   166724     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
   166725     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
   166726     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
   166727     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
   166728     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
   166729     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
   166730     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
   166731     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
   166732     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
   166733     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
   166734     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
   166735     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
   166736     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
   166737     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
   166738     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
   166739     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
   166740     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
   166741     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
   166742     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
   166743     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
   166744     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
   166745     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
   166746     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
   166747     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
   166748     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
   166749     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
   166750     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
   166751     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
   166752     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
   166753     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
   166754     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
   166755     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
   166756     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
   166757     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
   166758     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
   166759     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
   166760     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
   166761     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
   166762     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
   166763     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
   166764     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
   166765     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
   166766     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
   166767     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
   166768     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
   166769     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
   166770     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
   166771     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
   166772     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
   166773     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
   166774     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
   166775     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
   166776     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
   166777     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
   166778     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
   166779     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
   166780     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
   166781     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
   166782     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
   166783     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
   166784     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
   166785     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
   166786     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
   166787     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
   166788     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
   166789     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
   166790     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
   166791     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
   166792     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
   166793     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
   166794     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
   166795     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
   166796     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
   166797     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
   166798     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
   166799     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
   166800     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
   166801     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
   166802     0x380400F0,
   166803   };
   166804   static const unsigned int aAscii[4] = {
   166805     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
   166806   };
   166807 
   166808   if( (unsigned int)c<128 ){
   166809     return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
   166810   }else if( (unsigned int)c<(1<<22) ){
   166811     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
   166812     int iRes = 0;
   166813     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   166814     int iLo = 0;
   166815     while( iHi>=iLo ){
   166816       int iTest = (iHi + iLo) / 2;
   166817       if( key >= aEntry[iTest] ){
   166818         iRes = iTest;
   166819         iLo = iTest+1;
   166820       }else{
   166821         iHi = iTest-1;
   166822       }
   166823     }
   166824     assert( aEntry[0]<key );
   166825     assert( key>=aEntry[iRes] );
   166826     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
   166827   }
   166828   return 1;
   166829 }
   166830 
   166831 
   166832 /*
   166833 ** If the argument is a codepoint corresponding to a lowercase letter
   166834 ** in the ASCII range with a diacritic added, return the codepoint
   166835 ** of the ASCII letter only. For example, if passed 235 - "LATIN
   166836 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
   166837 ** E"). The resuls of passing a codepoint that corresponds to an
   166838 ** uppercase letter are undefined.
   166839 */
   166840 static int remove_diacritic(int c){
   166841   unsigned short aDia[] = {
   166842         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
   166843      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
   166844      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
   166845      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
   166846      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
   166847      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
   166848      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
   166849      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
   166850     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
   166851     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
   166852     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
   166853     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
   166854     62924, 63050, 63082, 63274, 63390,
   166855   };
   166856   char aChar[] = {
   166857     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
   166858     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
   166859     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
   166860     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
   166861     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
   166862     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
   166863     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
   166864     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
   166865     'e',  'i',  'o',  'u',  'y',
   166866   };
   166867 
   166868   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
   166869   int iRes = 0;
   166870   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
   166871   int iLo = 0;
   166872   while( iHi>=iLo ){
   166873     int iTest = (iHi + iLo) / 2;
   166874     if( key >= aDia[iTest] ){
   166875       iRes = iTest;
   166876       iLo = iTest+1;
   166877     }else{
   166878       iHi = iTest-1;
   166879     }
   166880   }
   166881   assert( key>=aDia[iRes] );
   166882   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
   166883 }
   166884 
   166885 
   166886 /*
   166887 ** Return true if the argument interpreted as a unicode codepoint
   166888 ** is a diacritical modifier character.
   166889 */
   166890 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
   166891   unsigned int mask0 = 0x08029FDF;
   166892   unsigned int mask1 = 0x000361F8;
   166893   if( c<768 || c>817 ) return 0;
   166894   return (c < 768+32) ?
   166895       (mask0 & (1 << (c-768))) :
   166896       (mask1 & (1 << (c-768-32)));
   166897 }
   166898 
   166899 
   166900 /*
   166901 ** Interpret the argument as a unicode codepoint. If the codepoint
   166902 ** is an upper case character that has a lower case equivalent,
   166903 ** return the codepoint corresponding to the lower case version.
   166904 ** Otherwise, return a copy of the argument.
   166905 **
   166906 ** The results are undefined if the value passed to this function
   166907 ** is less than zero.
   166908 */
   166909 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
   166910   /* Each entry in the following array defines a rule for folding a range
   166911   ** of codepoints to lower case. The rule applies to a range of nRange
   166912   ** codepoints starting at codepoint iCode.
   166913   **
   166914   ** If the least significant bit in flags is clear, then the rule applies
   166915   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
   166916   ** need to be folded). Or, if it is set, then the rule only applies to
   166917   ** every second codepoint in the range, starting with codepoint C.
   166918   **
   166919   ** The 7 most significant bits in flags are an index into the aiOff[]
   166920   ** array. If a specific codepoint C does require folding, then its lower
   166921   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
   166922   **
   166923   ** The contents of this array are generated by parsing the CaseFolding.txt
   166924   ** file distributed as part of the "Unicode Character Database". See
   166925   ** http://www.unicode.org for details.
   166926   */
   166927   static const struct TableEntry {
   166928     unsigned short iCode;
   166929     unsigned char flags;
   166930     unsigned char nRange;
   166931   } aEntry[] = {
   166932     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
   166933     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
   166934     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
   166935     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
   166936     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
   166937     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
   166938     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
   166939     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
   166940     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
   166941     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
   166942     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
   166943     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
   166944     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
   166945     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
   166946     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
   166947     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
   166948     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
   166949     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
   166950     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
   166951     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
   166952     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
   166953     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
   166954     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
   166955     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
   166956     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
   166957     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
   166958     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
   166959     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
   166960     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
   166961     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
   166962     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
   166963     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
   166964     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
   166965     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
   166966     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
   166967     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
   166968     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
   166969     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
   166970     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
   166971     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
   166972     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
   166973     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
   166974     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
   166975     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
   166976     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
   166977     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
   166978     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
   166979     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
   166980     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
   166981     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
   166982     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
   166983     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
   166984     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
   166985     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
   166986     {65313, 14, 26},
   166987   };
   166988   static const unsigned short aiOff[] = {
   166989    1,     2,     8,     15,    16,    26,    28,    32,
   166990    37,    38,    40,    48,    63,    64,    69,    71,
   166991    79,    80,    116,   202,   203,   205,   206,   207,
   166992    209,   210,   211,   213,   214,   217,   218,   219,
   166993    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
   166994    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
   166995    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
   166996    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
   166997    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
   166998    65514, 65521, 65527, 65528, 65529,
   166999   };
   167000 
   167001   int ret = c;
   167002 
   167003   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
   167004 
   167005   if( c<128 ){
   167006     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
   167007   }else if( c<65536 ){
   167008     const struct TableEntry *p;
   167009     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   167010     int iLo = 0;
   167011     int iRes = -1;
   167012 
   167013     assert( c>aEntry[0].iCode );
   167014     while( iHi>=iLo ){
   167015       int iTest = (iHi + iLo) / 2;
   167016       int cmp = (c - aEntry[iTest].iCode);
   167017       if( cmp>=0 ){
   167018         iRes = iTest;
   167019         iLo = iTest+1;
   167020       }else{
   167021         iHi = iTest-1;
   167022       }
   167023     }
   167024 
   167025     assert( iRes>=0 && c>=aEntry[iRes].iCode );
   167026     p = &aEntry[iRes];
   167027     if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
   167028       ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
   167029       assert( ret>0 );
   167030     }
   167031 
   167032     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
   167033   }
   167034 
   167035   else if( c>=66560 && c<66600 ){
   167036     ret = c + 40;
   167037   }
   167038 
   167039   return ret;
   167040 }
   167041 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
   167042 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
   167043 
   167044 /************** End of fts3_unicode2.c ***************************************/
   167045 /************** Begin file rtree.c *******************************************/
   167046 /*
   167047 ** 2001 September 15
   167048 **
   167049 ** The author disclaims copyright to this source code.  In place of
   167050 ** a legal notice, here is a blessing:
   167051 **
   167052 **    May you do good and not evil.
   167053 **    May you find forgiveness for yourself and forgive others.
   167054 **    May you share freely, never taking more than you give.
   167055 **
   167056 *************************************************************************
   167057 ** This file contains code for implementations of the r-tree and r*-tree
   167058 ** algorithms packaged as an SQLite virtual table module.
   167059 */
   167060 
   167061 /*
   167062 ** Database Format of R-Tree Tables
   167063 ** --------------------------------
   167064 **
   167065 ** The data structure for a single virtual r-tree table is stored in three
   167066 ** native SQLite tables declared as follows. In each case, the '%' character
   167067 ** in the table name is replaced with the user-supplied name of the r-tree
   167068 ** table.
   167069 **
   167070 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
   167071 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
   167072 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
   167073 **
   167074 ** The data for each node of the r-tree structure is stored in the %_node
   167075 ** table. For each node that is not the root node of the r-tree, there is
   167076 ** an entry in the %_parent table associating the node with its parent.
   167077 ** And for each row of data in the table, there is an entry in the %_rowid
   167078 ** table that maps from the entries rowid to the id of the node that it
   167079 ** is stored on.
   167080 **
   167081 ** The root node of an r-tree always exists, even if the r-tree table is
   167082 ** empty. The nodeno of the root node is always 1. All other nodes in the
   167083 ** table must be the same size as the root node. The content of each node
   167084 ** is formatted as follows:
   167085 **
   167086 **   1. If the node is the root node (node 1), then the first 2 bytes
   167087 **      of the node contain the tree depth as a big-endian integer.
   167088 **      For non-root nodes, the first 2 bytes are left unused.
   167089 **
   167090 **   2. The next 2 bytes contain the number of entries currently
   167091 **      stored in the node.
   167092 **
   167093 **   3. The remainder of the node contains the node entries. Each entry
   167094 **      consists of a single 8-byte integer followed by an even number
   167095 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
   167096 **      of a record. For internal nodes it is the node number of a
   167097 **      child page.
   167098 */
   167099 
   167100 #if !defined(SQLITE_CORE) \
   167101   || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
   167102 
   167103 #ifndef SQLITE_CORE
   167104 /*   #include "sqlite3ext.h" */
   167105   SQLITE_EXTENSION_INIT1
   167106 #else
   167107 /*   #include "sqlite3.h" */
   167108 #endif
   167109 
   167110 /* #include <string.h> */
   167111 /* #include <assert.h> */
   167112 /* #include <stdio.h> */
   167113 
   167114 #ifndef SQLITE_AMALGAMATION
   167115 #include "sqlite3rtree.h"
   167116 typedef sqlite3_int64 i64;
   167117 typedef sqlite3_uint64 u64;
   167118 typedef unsigned char u8;
   167119 typedef unsigned short u16;
   167120 typedef unsigned int u32;
   167121 #endif
   167122 
   167123 /*  The following macro is used to suppress compiler warnings.
   167124 */
   167125 #ifndef UNUSED_PARAMETER
   167126 # define UNUSED_PARAMETER(x) (void)(x)
   167127 #endif
   167128 
   167129 typedef struct Rtree Rtree;
   167130 typedef struct RtreeCursor RtreeCursor;
   167131 typedef struct RtreeNode RtreeNode;
   167132 typedef struct RtreeCell RtreeCell;
   167133 typedef struct RtreeConstraint RtreeConstraint;
   167134 typedef struct RtreeMatchArg RtreeMatchArg;
   167135 typedef struct RtreeGeomCallback RtreeGeomCallback;
   167136 typedef union RtreeCoord RtreeCoord;
   167137 typedef struct RtreeSearchPoint RtreeSearchPoint;
   167138 
   167139 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
   167140 #define RTREE_MAX_DIMENSIONS 5
   167141 
   167142 /* Size of hash table Rtree.aHash. This hash table is not expected to
   167143 ** ever contain very many entries, so a fixed number of buckets is
   167144 ** used.
   167145 */
   167146 #define HASHSIZE 97
   167147 
   167148 /* The xBestIndex method of this virtual table requires an estimate of
   167149 ** the number of rows in the virtual table to calculate the costs of
   167150 ** various strategies. If possible, this estimate is loaded from the
   167151 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
   167152 ** Otherwise, if no sqlite_stat1 entry is available, use
   167153 ** RTREE_DEFAULT_ROWEST.
   167154 */
   167155 #define RTREE_DEFAULT_ROWEST 1048576
   167156 #define RTREE_MIN_ROWEST         100
   167157 
   167158 /*
   167159 ** An rtree virtual-table object.
   167160 */
   167161 struct Rtree {
   167162   sqlite3_vtab base;          /* Base class.  Must be first */
   167163   sqlite3 *db;                /* Host database connection */
   167164   int iNodeSize;              /* Size in bytes of each node in the node table */
   167165   u8 nDim;                    /* Number of dimensions */
   167166   u8 nDim2;                   /* Twice the number of dimensions */
   167167   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
   167168   u8 nBytesPerCell;           /* Bytes consumed per cell */
   167169   u8 inWrTrans;               /* True if inside write transaction */
   167170   int iDepth;                 /* Current depth of the r-tree structure */
   167171   char *zDb;                  /* Name of database containing r-tree table */
   167172   char *zName;                /* Name of r-tree table */
   167173   u32 nBusy;                  /* Current number of users of this structure */
   167174   i64 nRowEst;                /* Estimated number of rows in this table */
   167175   u32 nCursor;                /* Number of open cursors */
   167176 
   167177   /* List of nodes removed during a CondenseTree operation. List is
   167178   ** linked together via the pointer normally used for hash chains -
   167179   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   167180   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   167181   */
   167182   RtreeNode *pDeleted;
   167183   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
   167184 
   167185   /* Blob I/O on xxx_node */
   167186   sqlite3_blob *pNodeBlob;
   167187 
   167188   /* Statements to read/write/delete a record from xxx_node */
   167189   sqlite3_stmt *pWriteNode;
   167190   sqlite3_stmt *pDeleteNode;
   167191 
   167192   /* Statements to read/write/delete a record from xxx_rowid */
   167193   sqlite3_stmt *pReadRowid;
   167194   sqlite3_stmt *pWriteRowid;
   167195   sqlite3_stmt *pDeleteRowid;
   167196 
   167197   /* Statements to read/write/delete a record from xxx_parent */
   167198   sqlite3_stmt *pReadParent;
   167199   sqlite3_stmt *pWriteParent;
   167200   sqlite3_stmt *pDeleteParent;
   167201 
   167202   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
   167203 };
   167204 
   167205 /* Possible values for Rtree.eCoordType: */
   167206 #define RTREE_COORD_REAL32 0
   167207 #define RTREE_COORD_INT32  1
   167208 
   167209 /*
   167210 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
   167211 ** only deal with integer coordinates.  No floating point operations
   167212 ** will be done.
   167213 */
   167214 #ifdef SQLITE_RTREE_INT_ONLY
   167215   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
   167216   typedef int RtreeValue;                  /* Low accuracy coordinate */
   167217 # define RTREE_ZERO 0
   167218 #else
   167219   typedef double RtreeDValue;              /* High accuracy coordinate */
   167220   typedef float RtreeValue;                /* Low accuracy coordinate */
   167221 # define RTREE_ZERO 0.0
   167222 #endif
   167223 
   167224 /*
   167225 ** When doing a search of an r-tree, instances of the following structure
   167226 ** record intermediate results from the tree walk.
   167227 **
   167228 ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
   167229 ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
   167230 ** the id is of the parent node and the cell that RtreeSearchPoint
   167231 ** represents is the iCell-th entry in the parent node.
   167232 */
   167233 struct RtreeSearchPoint {
   167234   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
   167235   sqlite3_int64 id;      /* Node ID */
   167236   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
   167237   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
   167238   u8 iCell;              /* Cell index within the node */
   167239 };
   167240 
   167241 /*
   167242 ** The minimum number of cells allowed for a node is a third of the
   167243 ** maximum. In Gutman's notation:
   167244 **
   167245 **     m = M/3
   167246 **
   167247 ** If an R*-tree "Reinsert" operation is required, the same number of
   167248 ** cells are removed from the overfull node and reinserted into the tree.
   167249 */
   167250 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
   167251 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
   167252 #define RTREE_MAXCELLS 51
   167253 
   167254 /*
   167255 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
   167256 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
   167257 ** Therefore all non-root nodes must contain at least 3 entries. Since
   167258 ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
   167259 ** 40 or less.
   167260 */
   167261 #define RTREE_MAX_DEPTH 40
   167262 
   167263 
   167264 /*
   167265 ** Number of entries in the cursor RtreeNode cache.  The first entry is
   167266 ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
   167267 ** entries cache the RtreeNode for the first elements of the priority queue.
   167268 */
   167269 #define RTREE_CACHE_SZ  5
   167270 
   167271 /*
   167272 ** An rtree cursor object.
   167273 */
   167274 struct RtreeCursor {
   167275   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
   167276   u8 atEOF;                         /* True if at end of search */
   167277   u8 bPoint;                        /* True if sPoint is valid */
   167278   int iStrategy;                    /* Copy of idxNum search parameter */
   167279   int nConstraint;                  /* Number of entries in aConstraint */
   167280   RtreeConstraint *aConstraint;     /* Search constraints. */
   167281   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
   167282   int nPoint;                       /* Number of slots used in aPoint[] */
   167283   int mxLevel;                      /* iLevel value for root of the tree */
   167284   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
   167285   RtreeSearchPoint sPoint;          /* Cached next search point */
   167286   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
   167287   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
   167288 };
   167289 
   167290 /* Return the Rtree of a RtreeCursor */
   167291 #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
   167292 
   167293 /*
   167294 ** A coordinate can be either a floating point number or a integer.  All
   167295 ** coordinates within a single R-Tree are always of the same time.
   167296 */
   167297 union RtreeCoord {
   167298   RtreeValue f;      /* Floating point value */
   167299   int i;             /* Integer value */
   167300   u32 u;             /* Unsigned for byte-order conversions */
   167301 };
   167302 
   167303 /*
   167304 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
   167305 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
   167306 ** variable pRtree points to the Rtree structure associated with the
   167307 ** RtreeCoord.
   167308 */
   167309 #ifdef SQLITE_RTREE_INT_ONLY
   167310 # define DCOORD(coord) ((RtreeDValue)coord.i)
   167311 #else
   167312 # define DCOORD(coord) (                           \
   167313     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
   167314       ((double)coord.f) :                           \
   167315       ((double)coord.i)                             \
   167316   )
   167317 #endif
   167318 
   167319 /*
   167320 ** A search constraint.
   167321 */
   167322 struct RtreeConstraint {
   167323   int iCoord;                     /* Index of constrained coordinate */
   167324   int op;                         /* Constraining operation */
   167325   union {
   167326     RtreeDValue rValue;             /* Constraint value. */
   167327     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
   167328     int (*xQueryFunc)(sqlite3_rtree_query_info*);
   167329   } u;
   167330   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
   167331 };
   167332 
   167333 /* Possible values for RtreeConstraint.op */
   167334 #define RTREE_EQ    0x41  /* A */
   167335 #define RTREE_LE    0x42  /* B */
   167336 #define RTREE_LT    0x43  /* C */
   167337 #define RTREE_GE    0x44  /* D */
   167338 #define RTREE_GT    0x45  /* E */
   167339 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
   167340 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
   167341 
   167342 
   167343 /*
   167344 ** An rtree structure node.
   167345 */
   167346 struct RtreeNode {
   167347   RtreeNode *pParent;         /* Parent node */
   167348   i64 iNode;                  /* The node number */
   167349   int nRef;                   /* Number of references to this node */
   167350   int isDirty;                /* True if the node needs to be written to disk */
   167351   u8 *zData;                  /* Content of the node, as should be on disk */
   167352   RtreeNode *pNext;           /* Next node in this hash collision chain */
   167353 };
   167354 
   167355 /* Return the number of cells in a node  */
   167356 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
   167357 
   167358 /*
   167359 ** A single cell from a node, deserialized
   167360 */
   167361 struct RtreeCell {
   167362   i64 iRowid;                                 /* Node or entry ID */
   167363   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
   167364 };
   167365 
   167366 
   167367 /*
   167368 ** This object becomes the sqlite3_user_data() for the SQL functions
   167369 ** that are created by sqlite3_rtree_geometry_callback() and
   167370 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
   167371 ** operators in order to constrain a search.
   167372 **
   167373 ** xGeom and xQueryFunc are the callback functions.  Exactly one of
   167374 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
   167375 ** SQL function was created using sqlite3_rtree_geometry_callback() or
   167376 ** sqlite3_rtree_query_callback().
   167377 **
   167378 ** This object is deleted automatically by the destructor mechanism in
   167379 ** sqlite3_create_function_v2().
   167380 */
   167381 struct RtreeGeomCallback {
   167382   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
   167383   int (*xQueryFunc)(sqlite3_rtree_query_info*);
   167384   void (*xDestructor)(void*);
   167385   void *pContext;
   167386 };
   167387 
   167388 /*
   167389 ** An instance of this structure (in the form of a BLOB) is returned by
   167390 ** the SQL functions that sqlite3_rtree_geometry_callback() and
   167391 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
   167392 ** operand to the MATCH operator of an R-Tree.
   167393 */
   167394 struct RtreeMatchArg {
   167395   u32 iSize;                  /* Size of this object */
   167396   RtreeGeomCallback cb;       /* Info about the callback functions */
   167397   int nParam;                 /* Number of parameters to the SQL function */
   167398   sqlite3_value **apSqlParam; /* Original SQL parameter values */
   167399   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
   167400 };
   167401 
   167402 #ifndef MAX
   167403 # define MAX(x,y) ((x) < (y) ? (y) : (x))
   167404 #endif
   167405 #ifndef MIN
   167406 # define MIN(x,y) ((x) > (y) ? (y) : (x))
   167407 #endif
   167408 
   167409 /* What version of GCC is being used.  0 means GCC is not being used .
   167410 ** Note that the GCC_VERSION macro will also be set correctly when using
   167411 ** clang, since clang works hard to be gcc compatible.  So the gcc
   167412 ** optimizations will also work when compiling with clang.
   167413 */
   167414 #ifndef GCC_VERSION
   167415 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
   167416 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
   167417 #else
   167418 # define GCC_VERSION 0
   167419 #endif
   167420 #endif
   167421 
   167422 /* The testcase() macro should already be defined in the amalgamation.  If
   167423 ** it is not, make it a no-op.
   167424 */
   167425 #ifndef SQLITE_AMALGAMATION
   167426 # define testcase(X)
   167427 #endif
   167428 
   167429 /*
   167430 ** Macros to determine whether the machine is big or little endian,
   167431 ** and whether or not that determination is run-time or compile-time.
   167432 **
   167433 ** For best performance, an attempt is made to guess at the byte-order
   167434 ** using C-preprocessor macros.  If that is unsuccessful, or if
   167435 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
   167436 ** at run-time.
   167437 */
   167438 #ifndef SQLITE_BYTEORDER
   167439 #if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
   167440     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
   167441     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
   167442     defined(__arm__)
   167443 # define SQLITE_BYTEORDER    1234
   167444 #elif defined(sparc)    || defined(__ppc__)
   167445 # define SQLITE_BYTEORDER    4321
   167446 #else
   167447 # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
   167448 #endif
   167449 #endif
   167450 
   167451 
   167452 /* What version of MSVC is being used.  0 means MSVC is not being used */
   167453 #ifndef MSVC_VERSION
   167454 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
   167455 # define MSVC_VERSION _MSC_VER
   167456 #else
   167457 # define MSVC_VERSION 0
   167458 #endif
   167459 #endif
   167460 
   167461 /*
   167462 ** Functions to deserialize a 16 bit integer, 32 bit real number and
   167463 ** 64 bit integer. The deserialized value is returned.
   167464 */
   167465 static int readInt16(u8 *p){
   167466   return (p[0]<<8) + p[1];
   167467 }
   167468 static void readCoord(u8 *p, RtreeCoord *pCoord){
   167469   assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
   167470 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   167471   pCoord->u = _byteswap_ulong(*(u32*)p);
   167472 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
   167473   pCoord->u = __builtin_bswap32(*(u32*)p);
   167474 #elif SQLITE_BYTEORDER==4321
   167475   pCoord->u = *(u32*)p;
   167476 #else
   167477   pCoord->u = (
   167478     (((u32)p[0]) << 24) +
   167479     (((u32)p[1]) << 16) +
   167480     (((u32)p[2]) <<  8) +
   167481     (((u32)p[3]) <<  0)
   167482   );
   167483 #endif
   167484 }
   167485 static i64 readInt64(u8 *p){
   167486 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   167487   u64 x;
   167488   memcpy(&x, p, 8);
   167489   return (i64)_byteswap_uint64(x);
   167490 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
   167491   u64 x;
   167492   memcpy(&x, p, 8);
   167493   return (i64)__builtin_bswap64(x);
   167494 #elif SQLITE_BYTEORDER==4321
   167495   i64 x;
   167496   memcpy(&x, p, 8);
   167497   return x;
   167498 #else
   167499   return (i64)(
   167500     (((u64)p[0]) << 56) +
   167501     (((u64)p[1]) << 48) +
   167502     (((u64)p[2]) << 40) +
   167503     (((u64)p[3]) << 32) +
   167504     (((u64)p[4]) << 24) +
   167505     (((u64)p[5]) << 16) +
   167506     (((u64)p[6]) <<  8) +
   167507     (((u64)p[7]) <<  0)
   167508   );
   167509 #endif
   167510 }
   167511 
   167512 /*
   167513 ** Functions to serialize a 16 bit integer, 32 bit real number and
   167514 ** 64 bit integer. The value returned is the number of bytes written
   167515 ** to the argument buffer (always 2, 4 and 8 respectively).
   167516 */
   167517 static void writeInt16(u8 *p, int i){
   167518   p[0] = (i>> 8)&0xFF;
   167519   p[1] = (i>> 0)&0xFF;
   167520 }
   167521 static int writeCoord(u8 *p, RtreeCoord *pCoord){
   167522   u32 i;
   167523   assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
   167524   assert( sizeof(RtreeCoord)==4 );
   167525   assert( sizeof(u32)==4 );
   167526 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
   167527   i = __builtin_bswap32(pCoord->u);
   167528   memcpy(p, &i, 4);
   167529 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   167530   i = _byteswap_ulong(pCoord->u);
   167531   memcpy(p, &i, 4);
   167532 #elif SQLITE_BYTEORDER==4321
   167533   i = pCoord->u;
   167534   memcpy(p, &i, 4);
   167535 #else
   167536   i = pCoord->u;
   167537   p[0] = (i>>24)&0xFF;
   167538   p[1] = (i>>16)&0xFF;
   167539   p[2] = (i>> 8)&0xFF;
   167540   p[3] = (i>> 0)&0xFF;
   167541 #endif
   167542   return 4;
   167543 }
   167544 static int writeInt64(u8 *p, i64 i){
   167545 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
   167546   i = (i64)__builtin_bswap64((u64)i);
   167547   memcpy(p, &i, 8);
   167548 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   167549   i = (i64)_byteswap_uint64((u64)i);
   167550   memcpy(p, &i, 8);
   167551 #elif SQLITE_BYTEORDER==4321
   167552   memcpy(p, &i, 8);
   167553 #else
   167554   p[0] = (i>>56)&0xFF;
   167555   p[1] = (i>>48)&0xFF;
   167556   p[2] = (i>>40)&0xFF;
   167557   p[3] = (i>>32)&0xFF;
   167558   p[4] = (i>>24)&0xFF;
   167559   p[5] = (i>>16)&0xFF;
   167560   p[6] = (i>> 8)&0xFF;
   167561   p[7] = (i>> 0)&0xFF;
   167562 #endif
   167563   return 8;
   167564 }
   167565 
   167566 /*
   167567 ** Increment the reference count of node p.
   167568 */
   167569 static void nodeReference(RtreeNode *p){
   167570   if( p ){
   167571     p->nRef++;
   167572   }
   167573 }
   167574 
   167575 /*
   167576 ** Clear the content of node p (set all bytes to 0x00).
   167577 */
   167578 static void nodeZero(Rtree *pRtree, RtreeNode *p){
   167579   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
   167580   p->isDirty = 1;
   167581 }
   167582 
   167583 /*
   167584 ** Given a node number iNode, return the corresponding key to use
   167585 ** in the Rtree.aHash table.
   167586 */
   167587 static int nodeHash(i64 iNode){
   167588   return iNode % HASHSIZE;
   167589 }
   167590 
   167591 /*
   167592 ** Search the node hash table for node iNode. If found, return a pointer
   167593 ** to it. Otherwise, return 0.
   167594 */
   167595 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
   167596   RtreeNode *p;
   167597   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
   167598   return p;
   167599 }
   167600 
   167601 /*
   167602 ** Add node pNode to the node hash table.
   167603 */
   167604 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
   167605   int iHash;
   167606   assert( pNode->pNext==0 );
   167607   iHash = nodeHash(pNode->iNode);
   167608   pNode->pNext = pRtree->aHash[iHash];
   167609   pRtree->aHash[iHash] = pNode;
   167610 }
   167611 
   167612 /*
   167613 ** Remove node pNode from the node hash table.
   167614 */
   167615 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
   167616   RtreeNode **pp;
   167617   if( pNode->iNode!=0 ){
   167618     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
   167619     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
   167620     *pp = pNode->pNext;
   167621     pNode->pNext = 0;
   167622   }
   167623 }
   167624 
   167625 /*
   167626 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
   167627 ** indicating that node has not yet been assigned a node number. It is
   167628 ** assigned a node number when nodeWrite() is called to write the
   167629 ** node contents out to the database.
   167630 */
   167631 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
   167632   RtreeNode *pNode;
   167633   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   167634   if( pNode ){
   167635     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
   167636     pNode->zData = (u8 *)&pNode[1];
   167637     pNode->nRef = 1;
   167638     pNode->pParent = pParent;
   167639     pNode->isDirty = 1;
   167640     nodeReference(pParent);
   167641   }
   167642   return pNode;
   167643 }
   167644 
   167645 /*
   167646 ** Clear the Rtree.pNodeBlob object
   167647 */
   167648 static void nodeBlobReset(Rtree *pRtree){
   167649   if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
   167650     sqlite3_blob *pBlob = pRtree->pNodeBlob;
   167651     pRtree->pNodeBlob = 0;
   167652     sqlite3_blob_close(pBlob);
   167653   }
   167654 }
   167655 
   167656 /*
   167657 ** Obtain a reference to an r-tree node.
   167658 */
   167659 static int nodeAcquire(
   167660   Rtree *pRtree,             /* R-tree structure */
   167661   i64 iNode,                 /* Node number to load */
   167662   RtreeNode *pParent,        /* Either the parent node or NULL */
   167663   RtreeNode **ppNode         /* OUT: Acquired node */
   167664 ){
   167665   int rc = SQLITE_OK;
   167666   RtreeNode *pNode = 0;
   167667 
   167668   /* Check if the requested node is already in the hash table. If so,
   167669   ** increase its reference count and return it.
   167670   */
   167671   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
   167672     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
   167673     if( pParent && !pNode->pParent ){
   167674       nodeReference(pParent);
   167675       pNode->pParent = pParent;
   167676     }
   167677     pNode->nRef++;
   167678     *ppNode = pNode;
   167679     return SQLITE_OK;
   167680   }
   167681 
   167682   if( pRtree->pNodeBlob ){
   167683     sqlite3_blob *pBlob = pRtree->pNodeBlob;
   167684     pRtree->pNodeBlob = 0;
   167685     rc = sqlite3_blob_reopen(pBlob, iNode);
   167686     pRtree->pNodeBlob = pBlob;
   167687     if( rc ){
   167688       nodeBlobReset(pRtree);
   167689       if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
   167690     }
   167691   }
   167692   if( pRtree->pNodeBlob==0 ){
   167693     char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
   167694     if( zTab==0 ) return SQLITE_NOMEM;
   167695     rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
   167696                            &pRtree->pNodeBlob);
   167697     sqlite3_free(zTab);
   167698   }
   167699   if( rc ){
   167700     nodeBlobReset(pRtree);
   167701     *ppNode = 0;
   167702     /* If unable to open an sqlite3_blob on the desired row, that can only
   167703     ** be because the shadow tables hold erroneous data. */
   167704     if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
   167705   }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
   167706     pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
   167707     if( !pNode ){
   167708       rc = SQLITE_NOMEM;
   167709     }else{
   167710       pNode->pParent = pParent;
   167711       pNode->zData = (u8 *)&pNode[1];
   167712       pNode->nRef = 1;
   167713       pNode->iNode = iNode;
   167714       pNode->isDirty = 0;
   167715       pNode->pNext = 0;
   167716       rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
   167717                              pRtree->iNodeSize, 0);
   167718       nodeReference(pParent);
   167719     }
   167720   }
   167721 
   167722   /* If the root node was just loaded, set pRtree->iDepth to the height
   167723   ** of the r-tree structure. A height of zero means all data is stored on
   167724   ** the root node. A height of one means the children of the root node
   167725   ** are the leaves, and so on. If the depth as specified on the root node
   167726   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   167727   */
   167728   if( pNode && iNode==1 ){
   167729     pRtree->iDepth = readInt16(pNode->zData);
   167730     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
   167731       rc = SQLITE_CORRUPT_VTAB;
   167732     }
   167733   }
   167734 
   167735   /* If no error has occurred so far, check if the "number of entries"
   167736   ** field on the node is too large. If so, set the return code to
   167737   ** SQLITE_CORRUPT_VTAB.
   167738   */
   167739   if( pNode && rc==SQLITE_OK ){
   167740     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
   167741       rc = SQLITE_CORRUPT_VTAB;
   167742     }
   167743   }
   167744 
   167745   if( rc==SQLITE_OK ){
   167746     if( pNode!=0 ){
   167747       nodeHashInsert(pRtree, pNode);
   167748     }else{
   167749       rc = SQLITE_CORRUPT_VTAB;
   167750     }
   167751     *ppNode = pNode;
   167752   }else{
   167753     sqlite3_free(pNode);
   167754     *ppNode = 0;
   167755   }
   167756 
   167757   return rc;
   167758 }
   167759 
   167760 /*
   167761 ** Overwrite cell iCell of node pNode with the contents of pCell.
   167762 */
   167763 static void nodeOverwriteCell(
   167764   Rtree *pRtree,             /* The overall R-Tree */
   167765   RtreeNode *pNode,          /* The node into which the cell is to be written */
   167766   RtreeCell *pCell,          /* The cell to write */
   167767   int iCell                  /* Index into pNode into which pCell is written */
   167768 ){
   167769   int ii;
   167770   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   167771   p += writeInt64(p, pCell->iRowid);
   167772   for(ii=0; ii<pRtree->nDim2; ii++){
   167773     p += writeCoord(p, &pCell->aCoord[ii]);
   167774   }
   167775   pNode->isDirty = 1;
   167776 }
   167777 
   167778 /*
   167779 ** Remove the cell with index iCell from node pNode.
   167780 */
   167781 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
   167782   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   167783   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
   167784   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
   167785   memmove(pDst, pSrc, nByte);
   167786   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
   167787   pNode->isDirty = 1;
   167788 }
   167789 
   167790 /*
   167791 ** Insert the contents of cell pCell into node pNode. If the insert
   167792 ** is successful, return SQLITE_OK.
   167793 **
   167794 ** If there is not enough free space in pNode, return SQLITE_FULL.
   167795 */
   167796 static int nodeInsertCell(
   167797   Rtree *pRtree,                /* The overall R-Tree */
   167798   RtreeNode *pNode,             /* Write new cell into this node */
   167799   RtreeCell *pCell              /* The cell to be inserted */
   167800 ){
   167801   int nCell;                    /* Current number of cells in pNode */
   167802   int nMaxCell;                 /* Maximum number of cells for pNode */
   167803 
   167804   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
   167805   nCell = NCELL(pNode);
   167806 
   167807   assert( nCell<=nMaxCell );
   167808   if( nCell<nMaxCell ){
   167809     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
   167810     writeInt16(&pNode->zData[2], nCell+1);
   167811     pNode->isDirty = 1;
   167812   }
   167813 
   167814   return (nCell==nMaxCell);
   167815 }
   167816 
   167817 /*
   167818 ** If the node is dirty, write it out to the database.
   167819 */
   167820 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
   167821   int rc = SQLITE_OK;
   167822   if( pNode->isDirty ){
   167823     sqlite3_stmt *p = pRtree->pWriteNode;
   167824     if( pNode->iNode ){
   167825       sqlite3_bind_int64(p, 1, pNode->iNode);
   167826     }else{
   167827       sqlite3_bind_null(p, 1);
   167828     }
   167829     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
   167830     sqlite3_step(p);
   167831     pNode->isDirty = 0;
   167832     rc = sqlite3_reset(p);
   167833     if( pNode->iNode==0 && rc==SQLITE_OK ){
   167834       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
   167835       nodeHashInsert(pRtree, pNode);
   167836     }
   167837   }
   167838   return rc;
   167839 }
   167840 
   167841 /*
   167842 ** Release a reference to a node. If the node is dirty and the reference
   167843 ** count drops to zero, the node data is written to the database.
   167844 */
   167845 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
   167846   int rc = SQLITE_OK;
   167847   if( pNode ){
   167848     assert( pNode->nRef>0 );
   167849     pNode->nRef--;
   167850     if( pNode->nRef==0 ){
   167851       if( pNode->iNode==1 ){
   167852         pRtree->iDepth = -1;
   167853       }
   167854       if( pNode->pParent ){
   167855         rc = nodeRelease(pRtree, pNode->pParent);
   167856       }
   167857       if( rc==SQLITE_OK ){
   167858         rc = nodeWrite(pRtree, pNode);
   167859       }
   167860       nodeHashDelete(pRtree, pNode);
   167861       sqlite3_free(pNode);
   167862     }
   167863   }
   167864   return rc;
   167865 }
   167866 
   167867 /*
   167868 ** Return the 64-bit integer value associated with cell iCell of
   167869 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
   167870 ** an internal node, then the 64-bit integer is a child page number.
   167871 */
   167872 static i64 nodeGetRowid(
   167873   Rtree *pRtree,       /* The overall R-Tree */
   167874   RtreeNode *pNode,    /* The node from which to extract the ID */
   167875   int iCell            /* The cell index from which to extract the ID */
   167876 ){
   167877   assert( iCell<NCELL(pNode) );
   167878   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
   167879 }
   167880 
   167881 /*
   167882 ** Return coordinate iCoord from cell iCell in node pNode.
   167883 */
   167884 static void nodeGetCoord(
   167885   Rtree *pRtree,               /* The overall R-Tree */
   167886   RtreeNode *pNode,            /* The node from which to extract a coordinate */
   167887   int iCell,                   /* The index of the cell within the node */
   167888   int iCoord,                  /* Which coordinate to extract */
   167889   RtreeCoord *pCoord           /* OUT: Space to write result to */
   167890 ){
   167891   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
   167892 }
   167893 
   167894 /*
   167895 ** Deserialize cell iCell of node pNode. Populate the structure pointed
   167896 ** to by pCell with the results.
   167897 */
   167898 static void nodeGetCell(
   167899   Rtree *pRtree,               /* The overall R-Tree */
   167900   RtreeNode *pNode,            /* The node containing the cell to be read */
   167901   int iCell,                   /* Index of the cell within the node */
   167902   RtreeCell *pCell             /* OUT: Write the cell contents here */
   167903 ){
   167904   u8 *pData;
   167905   RtreeCoord *pCoord;
   167906   int ii = 0;
   167907   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
   167908   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
   167909   pCoord = pCell->aCoord;
   167910   do{
   167911     readCoord(pData, &pCoord[ii]);
   167912     readCoord(pData+4, &pCoord[ii+1]);
   167913     pData += 8;
   167914     ii += 2;
   167915   }while( ii<pRtree->nDim2 );
   167916 }
   167917 
   167918 
   167919 /* Forward declaration for the function that does the work of
   167920 ** the virtual table module xCreate() and xConnect() methods.
   167921 */
   167922 static int rtreeInit(
   167923   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
   167924 );
   167925 
   167926 /*
   167927 ** Rtree virtual table module xCreate method.
   167928 */
   167929 static int rtreeCreate(
   167930   sqlite3 *db,
   167931   void *pAux,
   167932   int argc, const char *const*argv,
   167933   sqlite3_vtab **ppVtab,
   167934   char **pzErr
   167935 ){
   167936   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
   167937 }
   167938 
   167939 /*
   167940 ** Rtree virtual table module xConnect method.
   167941 */
   167942 static int rtreeConnect(
   167943   sqlite3 *db,
   167944   void *pAux,
   167945   int argc, const char *const*argv,
   167946   sqlite3_vtab **ppVtab,
   167947   char **pzErr
   167948 ){
   167949   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
   167950 }
   167951 
   167952 /*
   167953 ** Increment the r-tree reference count.
   167954 */
   167955 static void rtreeReference(Rtree *pRtree){
   167956   pRtree->nBusy++;
   167957 }
   167958 
   167959 /*
   167960 ** Decrement the r-tree reference count. When the reference count reaches
   167961 ** zero the structure is deleted.
   167962 */
   167963 static void rtreeRelease(Rtree *pRtree){
   167964   pRtree->nBusy--;
   167965   if( pRtree->nBusy==0 ){
   167966     pRtree->inWrTrans = 0;
   167967     pRtree->nCursor = 0;
   167968     nodeBlobReset(pRtree);
   167969     sqlite3_finalize(pRtree->pWriteNode);
   167970     sqlite3_finalize(pRtree->pDeleteNode);
   167971     sqlite3_finalize(pRtree->pReadRowid);
   167972     sqlite3_finalize(pRtree->pWriteRowid);
   167973     sqlite3_finalize(pRtree->pDeleteRowid);
   167974     sqlite3_finalize(pRtree->pReadParent);
   167975     sqlite3_finalize(pRtree->pWriteParent);
   167976     sqlite3_finalize(pRtree->pDeleteParent);
   167977     sqlite3_free(pRtree);
   167978   }
   167979 }
   167980 
   167981 /*
   167982 ** Rtree virtual table module xDisconnect method.
   167983 */
   167984 static int rtreeDisconnect(sqlite3_vtab *pVtab){
   167985   rtreeRelease((Rtree *)pVtab);
   167986   return SQLITE_OK;
   167987 }
   167988 
   167989 /*
   167990 ** Rtree virtual table module xDestroy method.
   167991 */
   167992 static int rtreeDestroy(sqlite3_vtab *pVtab){
   167993   Rtree *pRtree = (Rtree *)pVtab;
   167994   int rc;
   167995   char *zCreate = sqlite3_mprintf(
   167996     "DROP TABLE '%q'.'%q_node';"
   167997     "DROP TABLE '%q'.'%q_rowid';"
   167998     "DROP TABLE '%q'.'%q_parent';",
   167999     pRtree->zDb, pRtree->zName,
   168000     pRtree->zDb, pRtree->zName,
   168001     pRtree->zDb, pRtree->zName
   168002   );
   168003   if( !zCreate ){
   168004     rc = SQLITE_NOMEM;
   168005   }else{
   168006     nodeBlobReset(pRtree);
   168007     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
   168008     sqlite3_free(zCreate);
   168009   }
   168010   if( rc==SQLITE_OK ){
   168011     rtreeRelease(pRtree);
   168012   }
   168013 
   168014   return rc;
   168015 }
   168016 
   168017 /*
   168018 ** Rtree virtual table module xOpen method.
   168019 */
   168020 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   168021   int rc = SQLITE_NOMEM;
   168022   Rtree *pRtree = (Rtree *)pVTab;
   168023   RtreeCursor *pCsr;
   168024 
   168025   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
   168026   if( pCsr ){
   168027     memset(pCsr, 0, sizeof(RtreeCursor));
   168028     pCsr->base.pVtab = pVTab;
   168029     rc = SQLITE_OK;
   168030     pRtree->nCursor++;
   168031   }
   168032   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   168033 
   168034   return rc;
   168035 }
   168036 
   168037 
   168038 /*
   168039 ** Free the RtreeCursor.aConstraint[] array and its contents.
   168040 */
   168041 static void freeCursorConstraints(RtreeCursor *pCsr){
   168042   if( pCsr->aConstraint ){
   168043     int i;                        /* Used to iterate through constraint array */
   168044     for(i=0; i<pCsr->nConstraint; i++){
   168045       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
   168046       if( pInfo ){
   168047         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
   168048         sqlite3_free(pInfo);
   168049       }
   168050     }
   168051     sqlite3_free(pCsr->aConstraint);
   168052     pCsr->aConstraint = 0;
   168053   }
   168054 }
   168055 
   168056 /*
   168057 ** Rtree virtual table module xClose method.
   168058 */
   168059 static int rtreeClose(sqlite3_vtab_cursor *cur){
   168060   Rtree *pRtree = (Rtree *)(cur->pVtab);
   168061   int ii;
   168062   RtreeCursor *pCsr = (RtreeCursor *)cur;
   168063   assert( pRtree->nCursor>0 );
   168064   freeCursorConstraints(pCsr);
   168065   sqlite3_free(pCsr->aPoint);
   168066   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
   168067   sqlite3_free(pCsr);
   168068   pRtree->nCursor--;
   168069   nodeBlobReset(pRtree);
   168070   return SQLITE_OK;
   168071 }
   168072 
   168073 /*
   168074 ** Rtree virtual table module xEof method.
   168075 **
   168076 ** Return non-zero if the cursor does not currently point to a valid
   168077 ** record (i.e if the scan has finished), or zero otherwise.
   168078 */
   168079 static int rtreeEof(sqlite3_vtab_cursor *cur){
   168080   RtreeCursor *pCsr = (RtreeCursor *)cur;
   168081   return pCsr->atEOF;
   168082 }
   168083 
   168084 /*
   168085 ** Convert raw bits from the on-disk RTree record into a coordinate value.
   168086 ** The on-disk format is big-endian and needs to be converted for little-
   168087 ** endian platforms.  The on-disk record stores integer coordinates if
   168088 ** eInt is true and it stores 32-bit floating point records if eInt is
   168089 ** false.  a[] is the four bytes of the on-disk record to be decoded.
   168090 ** Store the results in "r".
   168091 **
   168092 ** There are five versions of this macro.  The last one is generic.  The
   168093 ** other four are various architectures-specific optimizations.
   168094 */
   168095 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
   168096 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   168097     RtreeCoord c;    /* Coordinate decoded */                   \
   168098     c.u = _byteswap_ulong(*(u32*)a);                            \
   168099     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   168100 }
   168101 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
   168102 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   168103     RtreeCoord c;    /* Coordinate decoded */                   \
   168104     c.u = __builtin_bswap32(*(u32*)a);                          \
   168105     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   168106 }
   168107 #elif SQLITE_BYTEORDER==1234
   168108 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   168109     RtreeCoord c;    /* Coordinate decoded */                   \
   168110     memcpy(&c.u,a,4);                                           \
   168111     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
   168112           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
   168113     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   168114 }
   168115 #elif SQLITE_BYTEORDER==4321
   168116 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   168117     RtreeCoord c;    /* Coordinate decoded */                   \
   168118     memcpy(&c.u,a,4);                                           \
   168119     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   168120 }
   168121 #else
   168122 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
   168123     RtreeCoord c;    /* Coordinate decoded */                   \
   168124     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
   168125            +((u32)a[2]<<8) + a[3];                              \
   168126     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
   168127 }
   168128 #endif
   168129 
   168130 /*
   168131 ** Check the RTree node or entry given by pCellData and p against the MATCH
   168132 ** constraint pConstraint.
   168133 */
   168134 static int rtreeCallbackConstraint(
   168135   RtreeConstraint *pConstraint,  /* The constraint to test */
   168136   int eInt,                      /* True if RTree holding integer coordinates */
   168137   u8 *pCellData,                 /* Raw cell content */
   168138   RtreeSearchPoint *pSearch,     /* Container of this cell */
   168139   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
   168140   int *peWithin                  /* OUT: visibility of the cell */
   168141 ){
   168142   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
   168143   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
   168144   int rc;                                             /* Callback return code */
   168145   RtreeCoord c;                                       /* Translator union */
   168146   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
   168147 
   168148   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
   168149   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
   168150 
   168151   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
   168152     pInfo->iRowid = readInt64(pCellData);
   168153   }
   168154   pCellData += 8;
   168155 #ifndef SQLITE_RTREE_INT_ONLY
   168156   if( eInt==0 ){
   168157     switch( nCoord ){
   168158       case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;
   168159                 readCoord(pCellData+32, &c); aCoord[8] = c.f;
   168160       case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;
   168161                 readCoord(pCellData+24, &c); aCoord[6] = c.f;
   168162       case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;
   168163                 readCoord(pCellData+16, &c); aCoord[4] = c.f;
   168164       case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;
   168165                 readCoord(pCellData+8,  &c); aCoord[2] = c.f;
   168166       default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;
   168167                 readCoord(pCellData,    &c); aCoord[0] = c.f;
   168168     }
   168169   }else
   168170 #endif
   168171   {
   168172     switch( nCoord ){
   168173       case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;
   168174                 readCoord(pCellData+32, &c); aCoord[8] = c.i;
   168175       case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;
   168176                 readCoord(pCellData+24, &c); aCoord[6] = c.i;
   168177       case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;
   168178                 readCoord(pCellData+16, &c); aCoord[4] = c.i;
   168179       case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;
   168180                 readCoord(pCellData+8,  &c); aCoord[2] = c.i;
   168181       default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;
   168182                 readCoord(pCellData,    &c); aCoord[0] = c.i;
   168183     }
   168184   }
   168185   if( pConstraint->op==RTREE_MATCH ){
   168186     int eWithin = 0;
   168187     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
   168188                               nCoord, aCoord, &eWithin);
   168189     if( eWithin==0 ) *peWithin = NOT_WITHIN;
   168190     *prScore = RTREE_ZERO;
   168191   }else{
   168192     pInfo->aCoord = aCoord;
   168193     pInfo->iLevel = pSearch->iLevel - 1;
   168194     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
   168195     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
   168196     rc = pConstraint->u.xQueryFunc(pInfo);
   168197     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
   168198     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
   168199       *prScore = pInfo->rScore;
   168200     }
   168201   }
   168202   return rc;
   168203 }
   168204 
   168205 /*
   168206 ** Check the internal RTree node given by pCellData against constraint p.
   168207 ** If this constraint cannot be satisfied by any child within the node,
   168208 ** set *peWithin to NOT_WITHIN.
   168209 */
   168210 static void rtreeNonleafConstraint(
   168211   RtreeConstraint *p,        /* The constraint to test */
   168212   int eInt,                  /* True if RTree holds integer coordinates */
   168213   u8 *pCellData,             /* Raw cell content as appears on disk */
   168214   int *peWithin              /* Adjust downward, as appropriate */
   168215 ){
   168216   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
   168217 
   168218   /* p->iCoord might point to either a lower or upper bound coordinate
   168219   ** in a coordinate pair.  But make pCellData point to the lower bound.
   168220   */
   168221   pCellData += 8 + 4*(p->iCoord&0xfe);
   168222 
   168223   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   168224       || p->op==RTREE_GT || p->op==RTREE_EQ );
   168225   assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
   168226   switch( p->op ){
   168227     case RTREE_LE:
   168228     case RTREE_LT:
   168229     case RTREE_EQ:
   168230       RTREE_DECODE_COORD(eInt, pCellData, val);
   168231       /* val now holds the lower bound of the coordinate pair */
   168232       if( p->u.rValue>=val ) return;
   168233       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
   168234       /* Fall through for the RTREE_EQ case */
   168235 
   168236     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
   168237       pCellData += 4;
   168238       RTREE_DECODE_COORD(eInt, pCellData, val);
   168239       /* val now holds the upper bound of the coordinate pair */
   168240       if( p->u.rValue<=val ) return;
   168241   }
   168242   *peWithin = NOT_WITHIN;
   168243 }
   168244 
   168245 /*
   168246 ** Check the leaf RTree cell given by pCellData against constraint p.
   168247 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
   168248 ** If the constraint is satisfied, leave *peWithin unchanged.
   168249 **
   168250 ** The constraint is of the form:  xN op $val
   168251 **
   168252 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
   168253 ** pCellData.  $val is given by p->u.rValue.
   168254 */
   168255 static void rtreeLeafConstraint(
   168256   RtreeConstraint *p,        /* The constraint to test */
   168257   int eInt,                  /* True if RTree holds integer coordinates */
   168258   u8 *pCellData,             /* Raw cell content as appears on disk */
   168259   int *peWithin              /* Adjust downward, as appropriate */
   168260 ){
   168261   RtreeDValue xN;      /* Coordinate value converted to a double */
   168262 
   168263   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   168264       || p->op==RTREE_GT || p->op==RTREE_EQ );
   168265   pCellData += 8 + p->iCoord*4;
   168266   assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
   168267   RTREE_DECODE_COORD(eInt, pCellData, xN);
   168268   switch( p->op ){
   168269     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
   168270     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
   168271     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
   168272     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
   168273     default:       if( xN == p->u.rValue ) return;  break;
   168274   }
   168275   *peWithin = NOT_WITHIN;
   168276 }
   168277 
   168278 /*
   168279 ** One of the cells in node pNode is guaranteed to have a 64-bit
   168280 ** integer value equal to iRowid. Return the index of this cell.
   168281 */
   168282 static int nodeRowidIndex(
   168283   Rtree *pRtree,
   168284   RtreeNode *pNode,
   168285   i64 iRowid,
   168286   int *piIndex
   168287 ){
   168288   int ii;
   168289   int nCell = NCELL(pNode);
   168290   assert( nCell<200 );
   168291   for(ii=0; ii<nCell; ii++){
   168292     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
   168293       *piIndex = ii;
   168294       return SQLITE_OK;
   168295     }
   168296   }
   168297   return SQLITE_CORRUPT_VTAB;
   168298 }
   168299 
   168300 /*
   168301 ** Return the index of the cell containing a pointer to node pNode
   168302 ** in its parent. If pNode is the root node, return -1.
   168303 */
   168304 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
   168305   RtreeNode *pParent = pNode->pParent;
   168306   if( pParent ){
   168307     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
   168308   }
   168309   *piIndex = -1;
   168310   return SQLITE_OK;
   168311 }
   168312 
   168313 /*
   168314 ** Compare two search points.  Return negative, zero, or positive if the first
   168315 ** is less than, equal to, or greater than the second.
   168316 **
   168317 ** The rScore is the primary key.  Smaller rScore values come first.
   168318 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
   168319 ** iLevel values coming first.  In this way, if rScore is the same for all
   168320 ** SearchPoints, then iLevel becomes the deciding factor and the result
   168321 ** is a depth-first search, which is the desired default behavior.
   168322 */
   168323 static int rtreeSearchPointCompare(
   168324   const RtreeSearchPoint *pA,
   168325   const RtreeSearchPoint *pB
   168326 ){
   168327   if( pA->rScore<pB->rScore ) return -1;
   168328   if( pA->rScore>pB->rScore ) return +1;
   168329   if( pA->iLevel<pB->iLevel ) return -1;
   168330   if( pA->iLevel>pB->iLevel ) return +1;
   168331   return 0;
   168332 }
   168333 
   168334 /*
   168335 ** Interchange two search points in a cursor.
   168336 */
   168337 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
   168338   RtreeSearchPoint t = p->aPoint[i];
   168339   assert( i<j );
   168340   p->aPoint[i] = p->aPoint[j];
   168341   p->aPoint[j] = t;
   168342   i++; j++;
   168343   if( i<RTREE_CACHE_SZ ){
   168344     if( j>=RTREE_CACHE_SZ ){
   168345       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
   168346       p->aNode[i] = 0;
   168347     }else{
   168348       RtreeNode *pTemp = p->aNode[i];
   168349       p->aNode[i] = p->aNode[j];
   168350       p->aNode[j] = pTemp;
   168351     }
   168352   }
   168353 }
   168354 
   168355 /*
   168356 ** Return the search point with the lowest current score.
   168357 */
   168358 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
   168359   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
   168360 }
   168361 
   168362 /*
   168363 ** Get the RtreeNode for the search point with the lowest score.
   168364 */
   168365 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
   168366   sqlite3_int64 id;
   168367   int ii = 1 - pCur->bPoint;
   168368   assert( ii==0 || ii==1 );
   168369   assert( pCur->bPoint || pCur->nPoint );
   168370   if( pCur->aNode[ii]==0 ){
   168371     assert( pRC!=0 );
   168372     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
   168373     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
   168374   }
   168375   return pCur->aNode[ii];
   168376 }
   168377 
   168378 /*
   168379 ** Push a new element onto the priority queue
   168380 */
   168381 static RtreeSearchPoint *rtreeEnqueue(
   168382   RtreeCursor *pCur,    /* The cursor */
   168383   RtreeDValue rScore,   /* Score for the new search point */
   168384   u8 iLevel             /* Level for the new search point */
   168385 ){
   168386   int i, j;
   168387   RtreeSearchPoint *pNew;
   168388   if( pCur->nPoint>=pCur->nPointAlloc ){
   168389     int nNew = pCur->nPointAlloc*2 + 8;
   168390     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
   168391     if( pNew==0 ) return 0;
   168392     pCur->aPoint = pNew;
   168393     pCur->nPointAlloc = nNew;
   168394   }
   168395   i = pCur->nPoint++;
   168396   pNew = pCur->aPoint + i;
   168397   pNew->rScore = rScore;
   168398   pNew->iLevel = iLevel;
   168399   assert( iLevel<=RTREE_MAX_DEPTH );
   168400   while( i>0 ){
   168401     RtreeSearchPoint *pParent;
   168402     j = (i-1)/2;
   168403     pParent = pCur->aPoint + j;
   168404     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
   168405     rtreeSearchPointSwap(pCur, j, i);
   168406     i = j;
   168407     pNew = pParent;
   168408   }
   168409   return pNew;
   168410 }
   168411 
   168412 /*
   168413 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
   168414 ** NULL if malloc fails.
   168415 */
   168416 static RtreeSearchPoint *rtreeSearchPointNew(
   168417   RtreeCursor *pCur,    /* The cursor */
   168418   RtreeDValue rScore,   /* Score for the new search point */
   168419   u8 iLevel             /* Level for the new search point */
   168420 ){
   168421   RtreeSearchPoint *pNew, *pFirst;
   168422   pFirst = rtreeSearchPointFirst(pCur);
   168423   pCur->anQueue[iLevel]++;
   168424   if( pFirst==0
   168425    || pFirst->rScore>rScore
   168426    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
   168427   ){
   168428     if( pCur->bPoint ){
   168429       int ii;
   168430       pNew = rtreeEnqueue(pCur, rScore, iLevel);
   168431       if( pNew==0 ) return 0;
   168432       ii = (int)(pNew - pCur->aPoint) + 1;
   168433       if( ii<RTREE_CACHE_SZ ){
   168434         assert( pCur->aNode[ii]==0 );
   168435         pCur->aNode[ii] = pCur->aNode[0];
   168436        }else{
   168437         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
   168438       }
   168439       pCur->aNode[0] = 0;
   168440       *pNew = pCur->sPoint;
   168441     }
   168442     pCur->sPoint.rScore = rScore;
   168443     pCur->sPoint.iLevel = iLevel;
   168444     pCur->bPoint = 1;
   168445     return &pCur->sPoint;
   168446   }else{
   168447     return rtreeEnqueue(pCur, rScore, iLevel);
   168448   }
   168449 }
   168450 
   168451 #if 0
   168452 /* Tracing routines for the RtreeSearchPoint queue */
   168453 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
   168454   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
   168455   printf(" %d.%05lld.%02d %g %d",
   168456     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
   168457   );
   168458   idx++;
   168459   if( idx<RTREE_CACHE_SZ ){
   168460     printf(" %p\n", pCur->aNode[idx]);
   168461   }else{
   168462     printf("\n");
   168463   }
   168464 }
   168465 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
   168466   int ii;
   168467   printf("=== %9s ", zPrefix);
   168468   if( pCur->bPoint ){
   168469     tracePoint(&pCur->sPoint, -1, pCur);
   168470   }
   168471   for(ii=0; ii<pCur->nPoint; ii++){
   168472     if( ii>0 || pCur->bPoint ) printf("              ");
   168473     tracePoint(&pCur->aPoint[ii], ii, pCur);
   168474   }
   168475 }
   168476 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
   168477 #else
   168478 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
   168479 #endif
   168480 
   168481 /* Remove the search point with the lowest current score.
   168482 */
   168483 static void rtreeSearchPointPop(RtreeCursor *p){
   168484   int i, j, k, n;
   168485   i = 1 - p->bPoint;
   168486   assert( i==0 || i==1 );
   168487   if( p->aNode[i] ){
   168488     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
   168489     p->aNode[i] = 0;
   168490   }
   168491   if( p->bPoint ){
   168492     p->anQueue[p->sPoint.iLevel]--;
   168493     p->bPoint = 0;
   168494   }else if( p->nPoint ){
   168495     p->anQueue[p->aPoint[0].iLevel]--;
   168496     n = --p->nPoint;
   168497     p->aPoint[0] = p->aPoint[n];
   168498     if( n<RTREE_CACHE_SZ-1 ){
   168499       p->aNode[1] = p->aNode[n+1];
   168500       p->aNode[n+1] = 0;
   168501     }
   168502     i = 0;
   168503     while( (j = i*2+1)<n ){
   168504       k = j+1;
   168505       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
   168506         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
   168507           rtreeSearchPointSwap(p, i, k);
   168508           i = k;
   168509         }else{
   168510           break;
   168511         }
   168512       }else{
   168513         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
   168514           rtreeSearchPointSwap(p, i, j);
   168515           i = j;
   168516         }else{
   168517           break;
   168518         }
   168519       }
   168520     }
   168521   }
   168522 }
   168523 
   168524 
   168525 /*
   168526 ** Continue the search on cursor pCur until the front of the queue
   168527 ** contains an entry suitable for returning as a result-set row,
   168528 ** or until the RtreeSearchPoint queue is empty, indicating that the
   168529 ** query has completed.
   168530 */
   168531 static int rtreeStepToLeaf(RtreeCursor *pCur){
   168532   RtreeSearchPoint *p;
   168533   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
   168534   RtreeNode *pNode;
   168535   int eWithin;
   168536   int rc = SQLITE_OK;
   168537   int nCell;
   168538   int nConstraint = pCur->nConstraint;
   168539   int ii;
   168540   int eInt;
   168541   RtreeSearchPoint x;
   168542 
   168543   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
   168544   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
   168545     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
   168546     if( rc ) return rc;
   168547     nCell = NCELL(pNode);
   168548     assert( nCell<200 );
   168549     while( p->iCell<nCell ){
   168550       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
   168551       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
   168552       eWithin = FULLY_WITHIN;
   168553       for(ii=0; ii<nConstraint; ii++){
   168554         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
   168555         if( pConstraint->op>=RTREE_MATCH ){
   168556           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
   168557                                        &rScore, &eWithin);
   168558           if( rc ) return rc;
   168559         }else if( p->iLevel==1 ){
   168560           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
   168561         }else{
   168562           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
   168563         }
   168564         if( eWithin==NOT_WITHIN ) break;
   168565       }
   168566       p->iCell++;
   168567       if( eWithin==NOT_WITHIN ) continue;
   168568       x.iLevel = p->iLevel - 1;
   168569       if( x.iLevel ){
   168570         x.id = readInt64(pCellData);
   168571         x.iCell = 0;
   168572       }else{
   168573         x.id = p->id;
   168574         x.iCell = p->iCell - 1;
   168575       }
   168576       if( p->iCell>=nCell ){
   168577         RTREE_QUEUE_TRACE(pCur, "POP-S:");
   168578         rtreeSearchPointPop(pCur);
   168579       }
   168580       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
   168581       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
   168582       if( p==0 ) return SQLITE_NOMEM;
   168583       p->eWithin = (u8)eWithin;
   168584       p->id = x.id;
   168585       p->iCell = x.iCell;
   168586       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
   168587       break;
   168588     }
   168589     if( p->iCell>=nCell ){
   168590       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
   168591       rtreeSearchPointPop(pCur);
   168592     }
   168593   }
   168594   pCur->atEOF = p==0;
   168595   return SQLITE_OK;
   168596 }
   168597 
   168598 /*
   168599 ** Rtree virtual table module xNext method.
   168600 */
   168601 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   168602   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   168603   int rc = SQLITE_OK;
   168604 
   168605   /* Move to the next entry that matches the configured constraints. */
   168606   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
   168607   rtreeSearchPointPop(pCsr);
   168608   rc = rtreeStepToLeaf(pCsr);
   168609   return rc;
   168610 }
   168611 
   168612 /*
   168613 ** Rtree virtual table module xRowid method.
   168614 */
   168615 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   168616   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   168617   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
   168618   int rc = SQLITE_OK;
   168619   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
   168620   if( rc==SQLITE_OK && p ){
   168621     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
   168622   }
   168623   return rc;
   168624 }
   168625 
   168626 /*
   168627 ** Rtree virtual table module xColumn method.
   168628 */
   168629 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   168630   Rtree *pRtree = (Rtree *)cur->pVtab;
   168631   RtreeCursor *pCsr = (RtreeCursor *)cur;
   168632   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
   168633   RtreeCoord c;
   168634   int rc = SQLITE_OK;
   168635   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
   168636 
   168637   if( rc ) return rc;
   168638   if( p==0 ) return SQLITE_OK;
   168639   if( i==0 ){
   168640     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
   168641   }else{
   168642     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
   168643 #ifndef SQLITE_RTREE_INT_ONLY
   168644     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   168645       sqlite3_result_double(ctx, c.f);
   168646     }else
   168647 #endif
   168648     {
   168649       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
   168650       sqlite3_result_int(ctx, c.i);
   168651     }
   168652   }
   168653   return SQLITE_OK;
   168654 }
   168655 
   168656 /*
   168657 ** Use nodeAcquire() to obtain the leaf node containing the record with
   168658 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
   168659 ** return SQLITE_OK. If there is no such record in the table, set
   168660 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
   168661 ** to zero and return an SQLite error code.
   168662 */
   168663 static int findLeafNode(
   168664   Rtree *pRtree,              /* RTree to search */
   168665   i64 iRowid,                 /* The rowid searching for */
   168666   RtreeNode **ppLeaf,         /* Write the node here */
   168667   sqlite3_int64 *piNode       /* Write the node-id here */
   168668 ){
   168669   int rc;
   168670   *ppLeaf = 0;
   168671   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
   168672   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
   168673     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
   168674     if( piNode ) *piNode = iNode;
   168675     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
   168676     sqlite3_reset(pRtree->pReadRowid);
   168677   }else{
   168678     rc = sqlite3_reset(pRtree->pReadRowid);
   168679   }
   168680   return rc;
   168681 }
   168682 
   168683 /*
   168684 ** This function is called to configure the RtreeConstraint object passed
   168685 ** as the second argument for a MATCH constraint. The value passed as the
   168686 ** first argument to this function is the right-hand operand to the MATCH
   168687 ** operator.
   168688 */
   168689 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
   168690   RtreeMatchArg *pBlob, *pSrc;       /* BLOB returned by geometry function */
   168691   sqlite3_rtree_query_info *pInfo;   /* Callback information */
   168692 
   168693   pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
   168694   if( pSrc==0 ) return SQLITE_ERROR;
   168695   pInfo = (sqlite3_rtree_query_info*)
   168696                 sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
   168697   if( !pInfo ) return SQLITE_NOMEM;
   168698   memset(pInfo, 0, sizeof(*pInfo));
   168699   pBlob = (RtreeMatchArg*)&pInfo[1];
   168700   memcpy(pBlob, pSrc, pSrc->iSize);
   168701   pInfo->pContext = pBlob->cb.pContext;
   168702   pInfo->nParam = pBlob->nParam;
   168703   pInfo->aParam = pBlob->aParam;
   168704   pInfo->apSqlParam = pBlob->apSqlParam;
   168705 
   168706   if( pBlob->cb.xGeom ){
   168707     pCons->u.xGeom = pBlob->cb.xGeom;
   168708   }else{
   168709     pCons->op = RTREE_QUERY;
   168710     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
   168711   }
   168712   pCons->pInfo = pInfo;
   168713   return SQLITE_OK;
   168714 }
   168715 
   168716 /*
   168717 ** Rtree virtual table module xFilter method.
   168718 */
   168719 static int rtreeFilter(
   168720   sqlite3_vtab_cursor *pVtabCursor,
   168721   int idxNum, const char *idxStr,
   168722   int argc, sqlite3_value **argv
   168723 ){
   168724   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   168725   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   168726   RtreeNode *pRoot = 0;
   168727   int ii;
   168728   int rc = SQLITE_OK;
   168729   int iCell = 0;
   168730 
   168731   rtreeReference(pRtree);
   168732 
   168733   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
   168734   freeCursorConstraints(pCsr);
   168735   sqlite3_free(pCsr->aPoint);
   168736   memset(pCsr, 0, sizeof(RtreeCursor));
   168737   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
   168738 
   168739   pCsr->iStrategy = idxNum;
   168740   if( idxNum==1 ){
   168741     /* Special case - lookup by rowid. */
   168742     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
   168743     RtreeSearchPoint *p;     /* Search point for the leaf */
   168744     i64 iRowid = sqlite3_value_int64(argv[0]);
   168745     i64 iNode = 0;
   168746     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
   168747     if( rc==SQLITE_OK && pLeaf!=0 ){
   168748       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
   168749       assert( p!=0 );  /* Always returns pCsr->sPoint */
   168750       pCsr->aNode[0] = pLeaf;
   168751       p->id = iNode;
   168752       p->eWithin = PARTLY_WITHIN;
   168753       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
   168754       p->iCell = (u8)iCell;
   168755       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
   168756     }else{
   168757       pCsr->atEOF = 1;
   168758     }
   168759   }else{
   168760     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
   168761     ** with the configured constraints.
   168762     */
   168763     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   168764     if( rc==SQLITE_OK && argc>0 ){
   168765       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
   168766       pCsr->nConstraint = argc;
   168767       if( !pCsr->aConstraint ){
   168768         rc = SQLITE_NOMEM;
   168769       }else{
   168770         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
   168771         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
   168772         assert( (idxStr==0 && argc==0)
   168773                 || (idxStr && (int)strlen(idxStr)==argc*2) );
   168774         for(ii=0; ii<argc; ii++){
   168775           RtreeConstraint *p = &pCsr->aConstraint[ii];
   168776           p->op = idxStr[ii*2];
   168777           p->iCoord = idxStr[ii*2+1]-'0';
   168778           if( p->op>=RTREE_MATCH ){
   168779             /* A MATCH operator. The right-hand-side must be a blob that
   168780             ** can be cast into an RtreeMatchArg object. One created using
   168781             ** an sqlite3_rtree_geometry_callback() SQL user function.
   168782             */
   168783             rc = deserializeGeometry(argv[ii], p);
   168784             if( rc!=SQLITE_OK ){
   168785               break;
   168786             }
   168787             p->pInfo->nCoord = pRtree->nDim2;
   168788             p->pInfo->anQueue = pCsr->anQueue;
   168789             p->pInfo->mxLevel = pRtree->iDepth + 1;
   168790           }else{
   168791 #ifdef SQLITE_RTREE_INT_ONLY
   168792             p->u.rValue = sqlite3_value_int64(argv[ii]);
   168793 #else
   168794             p->u.rValue = sqlite3_value_double(argv[ii]);
   168795 #endif
   168796           }
   168797         }
   168798       }
   168799     }
   168800     if( rc==SQLITE_OK ){
   168801       RtreeSearchPoint *pNew;
   168802       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
   168803       if( pNew==0 ) return SQLITE_NOMEM;
   168804       pNew->id = 1;
   168805       pNew->iCell = 0;
   168806       pNew->eWithin = PARTLY_WITHIN;
   168807       assert( pCsr->bPoint==1 );
   168808       pCsr->aNode[0] = pRoot;
   168809       pRoot = 0;
   168810       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
   168811       rc = rtreeStepToLeaf(pCsr);
   168812     }
   168813   }
   168814 
   168815   nodeRelease(pRtree, pRoot);
   168816   rtreeRelease(pRtree);
   168817   return rc;
   168818 }
   168819 
   168820 /*
   168821 ** Rtree virtual table module xBestIndex method. There are three
   168822 ** table scan strategies to choose from (in order from most to
   168823 ** least desirable):
   168824 **
   168825 **   idxNum     idxStr        Strategy
   168826 **   ------------------------------------------------
   168827 **     1        Unused        Direct lookup by rowid.
   168828 **     2        See below     R-tree query or full-table scan.
   168829 **   ------------------------------------------------
   168830 **
   168831 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
   168832 ** 2 is used, idxStr is formatted to contain 2 bytes for each
   168833 ** constraint used. The first two bytes of idxStr correspond to
   168834 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
   168835 ** (argvIndex==1) etc.
   168836 **
   168837 ** The first of each pair of bytes in idxStr identifies the constraint
   168838 ** operator as follows:
   168839 **
   168840 **   Operator    Byte Value
   168841 **   ----------------------
   168842 **      =        0x41 ('A')
   168843 **     <=        0x42 ('B')
   168844 **      <        0x43 ('C')
   168845 **     >=        0x44 ('D')
   168846 **      >        0x45 ('E')
   168847 **   MATCH       0x46 ('F')
   168848 **   ----------------------
   168849 **
   168850 ** The second of each pair of bytes identifies the coordinate column
   168851 ** to which the constraint applies. The leftmost coordinate column
   168852 ** is 'a', the second from the left 'b' etc.
   168853 */
   168854 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   168855   Rtree *pRtree = (Rtree*)tab;
   168856   int rc = SQLITE_OK;
   168857   int ii;
   168858   int bMatch = 0;                 /* True if there exists a MATCH constraint */
   168859   i64 nRow;                       /* Estimated rows returned by this scan */
   168860 
   168861   int iIdx = 0;
   168862   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
   168863   memset(zIdxStr, 0, sizeof(zIdxStr));
   168864 
   168865   /* Check if there exists a MATCH constraint - even an unusable one. If there
   168866   ** is, do not consider the lookup-by-rowid plan as using such a plan would
   168867   ** require the VDBE to evaluate the MATCH constraint, which is not currently
   168868   ** possible. */
   168869   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
   168870     if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
   168871       bMatch = 1;
   168872     }
   168873   }
   168874 
   168875   assert( pIdxInfo->idxStr==0 );
   168876   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
   168877     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
   168878 
   168879     if( bMatch==0 && p->usable
   168880      && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
   168881     ){
   168882       /* We have an equality constraint on the rowid. Use strategy 1. */
   168883       int jj;
   168884       for(jj=0; jj<ii; jj++){
   168885         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
   168886         pIdxInfo->aConstraintUsage[jj].omit = 0;
   168887       }
   168888       pIdxInfo->idxNum = 1;
   168889       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
   168890       pIdxInfo->aConstraintUsage[jj].omit = 1;
   168891 
   168892       /* This strategy involves a two rowid lookups on an B-Tree structures
   168893       ** and then a linear search of an R-Tree node. This should be
   168894       ** considered almost as quick as a direct rowid lookup (for which
   168895       ** sqlite uses an internal cost of 0.0). It is expected to return
   168896       ** a single row.
   168897       */
   168898       pIdxInfo->estimatedCost = 30.0;
   168899       pIdxInfo->estimatedRows = 1;
   168900       return SQLITE_OK;
   168901     }
   168902 
   168903     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
   168904       u8 op;
   168905       switch( p->op ){
   168906         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
   168907         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
   168908         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
   168909         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
   168910         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
   168911         default:
   168912           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
   168913           op = RTREE_MATCH;
   168914           break;
   168915       }
   168916       zIdxStr[iIdx++] = op;
   168917       zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
   168918       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
   168919       pIdxInfo->aConstraintUsage[ii].omit = 1;
   168920     }
   168921   }
   168922 
   168923   pIdxInfo->idxNum = 2;
   168924   pIdxInfo->needToFreeIdxStr = 1;
   168925   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
   168926     return SQLITE_NOMEM;
   168927   }
   168928 
   168929   nRow = pRtree->nRowEst >> (iIdx/2);
   168930   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
   168931   pIdxInfo->estimatedRows = nRow;
   168932 
   168933   return rc;
   168934 }
   168935 
   168936 /*
   168937 ** Return the N-dimensional volumn of the cell stored in *p.
   168938 */
   168939 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
   168940   RtreeDValue area = (RtreeDValue)1;
   168941   assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
   168942 #ifndef SQLITE_RTREE_INT_ONLY
   168943   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   168944     switch( pRtree->nDim ){
   168945       case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;
   168946       case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;
   168947       case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;
   168948       case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;
   168949       default: area *= p->aCoord[1].f - p->aCoord[0].f;
   168950     }
   168951   }else
   168952 #endif
   168953   {
   168954     switch( pRtree->nDim ){
   168955       case 5:  area  = p->aCoord[9].i - p->aCoord[8].i;
   168956       case 4:  area *= p->aCoord[7].i - p->aCoord[6].i;
   168957       case 3:  area *= p->aCoord[5].i - p->aCoord[4].i;
   168958       case 2:  area *= p->aCoord[3].i - p->aCoord[2].i;
   168959       default: area *= p->aCoord[1].i - p->aCoord[0].i;
   168960     }
   168961   }
   168962   return area;
   168963 }
   168964 
   168965 /*
   168966 ** Return the margin length of cell p. The margin length is the sum
   168967 ** of the objects size in each dimension.
   168968 */
   168969 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
   168970   RtreeDValue margin = 0;
   168971   int ii = pRtree->nDim2 - 2;
   168972   do{
   168973     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   168974     ii -= 2;
   168975   }while( ii>=0 );
   168976   return margin;
   168977 }
   168978 
   168979 /*
   168980 ** Store the union of cells p1 and p2 in p1.
   168981 */
   168982 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   168983   int ii = 0;
   168984   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   168985     do{
   168986       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
   168987       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
   168988       ii += 2;
   168989     }while( ii<pRtree->nDim2 );
   168990   }else{
   168991     do{
   168992       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
   168993       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
   168994       ii += 2;
   168995     }while( ii<pRtree->nDim2 );
   168996   }
   168997 }
   168998 
   168999 /*
   169000 ** Return true if the area covered by p2 is a subset of the area covered
   169001 ** by p1. False otherwise.
   169002 */
   169003 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   169004   int ii;
   169005   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
   169006   for(ii=0; ii<pRtree->nDim2; ii+=2){
   169007     RtreeCoord *a1 = &p1->aCoord[ii];
   169008     RtreeCoord *a2 = &p2->aCoord[ii];
   169009     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
   169010      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
   169011     ){
   169012       return 0;
   169013     }
   169014   }
   169015   return 1;
   169016 }
   169017 
   169018 /*
   169019 ** Return the amount cell p would grow by if it were unioned with pCell.
   169020 */
   169021 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
   169022   RtreeDValue area;
   169023   RtreeCell cell;
   169024   memcpy(&cell, p, sizeof(RtreeCell));
   169025   area = cellArea(pRtree, &cell);
   169026   cellUnion(pRtree, &cell, pCell);
   169027   return (cellArea(pRtree, &cell)-area);
   169028 }
   169029 
   169030 static RtreeDValue cellOverlap(
   169031   Rtree *pRtree,
   169032   RtreeCell *p,
   169033   RtreeCell *aCell,
   169034   int nCell
   169035 ){
   169036   int ii;
   169037   RtreeDValue overlap = RTREE_ZERO;
   169038   for(ii=0; ii<nCell; ii++){
   169039     int jj;
   169040     RtreeDValue o = (RtreeDValue)1;
   169041     for(jj=0; jj<pRtree->nDim2; jj+=2){
   169042       RtreeDValue x1, x2;
   169043       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
   169044       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
   169045       if( x2<x1 ){
   169046         o = (RtreeDValue)0;
   169047         break;
   169048       }else{
   169049         o = o * (x2-x1);
   169050       }
   169051     }
   169052     overlap += o;
   169053   }
   169054   return overlap;
   169055 }
   169056 
   169057 
   169058 /*
   169059 ** This function implements the ChooseLeaf algorithm from Gutman[84].
   169060 ** ChooseSubTree in r*tree terminology.
   169061 */
   169062 static int ChooseLeaf(
   169063   Rtree *pRtree,               /* Rtree table */
   169064   RtreeCell *pCell,            /* Cell to insert into rtree */
   169065   int iHeight,                 /* Height of sub-tree rooted at pCell */
   169066   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
   169067 ){
   169068   int rc;
   169069   int ii;
   169070   RtreeNode *pNode = 0;
   169071   rc = nodeAcquire(pRtree, 1, 0, &pNode);
   169072 
   169073   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
   169074     int iCell;
   169075     sqlite3_int64 iBest = 0;
   169076 
   169077     RtreeDValue fMinGrowth = RTREE_ZERO;
   169078     RtreeDValue fMinArea = RTREE_ZERO;
   169079 
   169080     int nCell = NCELL(pNode);
   169081     RtreeCell cell;
   169082     RtreeNode *pChild;
   169083 
   169084     RtreeCell *aCell = 0;
   169085 
   169086     /* Select the child node which will be enlarged the least if pCell
   169087     ** is inserted into it. Resolve ties by choosing the entry with
   169088     ** the smallest area.
   169089     */
   169090     for(iCell=0; iCell<nCell; iCell++){
   169091       int bBest = 0;
   169092       RtreeDValue growth;
   169093       RtreeDValue area;
   169094       nodeGetCell(pRtree, pNode, iCell, &cell);
   169095       growth = cellGrowth(pRtree, &cell, pCell);
   169096       area = cellArea(pRtree, &cell);
   169097       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
   169098         bBest = 1;
   169099       }
   169100       if( bBest ){
   169101         fMinGrowth = growth;
   169102         fMinArea = area;
   169103         iBest = cell.iRowid;
   169104       }
   169105     }
   169106 
   169107     sqlite3_free(aCell);
   169108     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
   169109     nodeRelease(pRtree, pNode);
   169110     pNode = pChild;
   169111   }
   169112 
   169113   *ppLeaf = pNode;
   169114   return rc;
   169115 }
   169116 
   169117 /*
   169118 ** A cell with the same content as pCell has just been inserted into
   169119 ** the node pNode. This function updates the bounding box cells in
   169120 ** all ancestor elements.
   169121 */
   169122 static int AdjustTree(
   169123   Rtree *pRtree,                    /* Rtree table */
   169124   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
   169125   RtreeCell *pCell                  /* This cell was just inserted */
   169126 ){
   169127   RtreeNode *p = pNode;
   169128   while( p->pParent ){
   169129     RtreeNode *pParent = p->pParent;
   169130     RtreeCell cell;
   169131     int iCell;
   169132 
   169133     if( nodeParentIndex(pRtree, p, &iCell) ){
   169134       return SQLITE_CORRUPT_VTAB;
   169135     }
   169136 
   169137     nodeGetCell(pRtree, pParent, iCell, &cell);
   169138     if( !cellContains(pRtree, &cell, pCell) ){
   169139       cellUnion(pRtree, &cell, pCell);
   169140       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
   169141     }
   169142 
   169143     p = pParent;
   169144   }
   169145   return SQLITE_OK;
   169146 }
   169147 
   169148 /*
   169149 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
   169150 */
   169151 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
   169152   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
   169153   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
   169154   sqlite3_step(pRtree->pWriteRowid);
   169155   return sqlite3_reset(pRtree->pWriteRowid);
   169156 }
   169157 
   169158 /*
   169159 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
   169160 */
   169161 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
   169162   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
   169163   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
   169164   sqlite3_step(pRtree->pWriteParent);
   169165   return sqlite3_reset(pRtree->pWriteParent);
   169166 }
   169167 
   169168 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
   169169 
   169170 
   169171 /*
   169172 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
   169173 ** nIdx. The aIdx array contains the set of integers from 0 to
   169174 ** (nIdx-1) in no particular order. This function sorts the values
   169175 ** in aIdx according to the indexed values in aDistance. For
   169176 ** example, assuming the inputs:
   169177 **
   169178 **   aIdx      = { 0,   1,   2,   3 }
   169179 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
   169180 **
   169181 ** this function sets the aIdx array to contain:
   169182 **
   169183 **   aIdx      = { 0,   1,   2,   3 }
   169184 **
   169185 ** The aSpare array is used as temporary working space by the
   169186 ** sorting algorithm.
   169187 */
   169188 static void SortByDistance(
   169189   int *aIdx,
   169190   int nIdx,
   169191   RtreeDValue *aDistance,
   169192   int *aSpare
   169193 ){
   169194   if( nIdx>1 ){
   169195     int iLeft = 0;
   169196     int iRight = 0;
   169197 
   169198     int nLeft = nIdx/2;
   169199     int nRight = nIdx-nLeft;
   169200     int *aLeft = aIdx;
   169201     int *aRight = &aIdx[nLeft];
   169202 
   169203     SortByDistance(aLeft, nLeft, aDistance, aSpare);
   169204     SortByDistance(aRight, nRight, aDistance, aSpare);
   169205 
   169206     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   169207     aLeft = aSpare;
   169208 
   169209     while( iLeft<nLeft || iRight<nRight ){
   169210       if( iLeft==nLeft ){
   169211         aIdx[iLeft+iRight] = aRight[iRight];
   169212         iRight++;
   169213       }else if( iRight==nRight ){
   169214         aIdx[iLeft+iRight] = aLeft[iLeft];
   169215         iLeft++;
   169216       }else{
   169217         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
   169218         RtreeDValue fRight = aDistance[aRight[iRight]];
   169219         if( fLeft<fRight ){
   169220           aIdx[iLeft+iRight] = aLeft[iLeft];
   169221           iLeft++;
   169222         }else{
   169223           aIdx[iLeft+iRight] = aRight[iRight];
   169224           iRight++;
   169225         }
   169226       }
   169227     }
   169228 
   169229 #if 0
   169230     /* Check that the sort worked */
   169231     {
   169232       int jj;
   169233       for(jj=1; jj<nIdx; jj++){
   169234         RtreeDValue left = aDistance[aIdx[jj-1]];
   169235         RtreeDValue right = aDistance[aIdx[jj]];
   169236         assert( left<=right );
   169237       }
   169238     }
   169239 #endif
   169240   }
   169241 }
   169242 
   169243 /*
   169244 ** Arguments aIdx, aCell and aSpare all point to arrays of size
   169245 ** nIdx. The aIdx array contains the set of integers from 0 to
   169246 ** (nIdx-1) in no particular order. This function sorts the values
   169247 ** in aIdx according to dimension iDim of the cells in aCell. The
   169248 ** minimum value of dimension iDim is considered first, the
   169249 ** maximum used to break ties.
   169250 **
   169251 ** The aSpare array is used as temporary working space by the
   169252 ** sorting algorithm.
   169253 */
   169254 static void SortByDimension(
   169255   Rtree *pRtree,
   169256   int *aIdx,
   169257   int nIdx,
   169258   int iDim,
   169259   RtreeCell *aCell,
   169260   int *aSpare
   169261 ){
   169262   if( nIdx>1 ){
   169263 
   169264     int iLeft = 0;
   169265     int iRight = 0;
   169266 
   169267     int nLeft = nIdx/2;
   169268     int nRight = nIdx-nLeft;
   169269     int *aLeft = aIdx;
   169270     int *aRight = &aIdx[nLeft];
   169271 
   169272     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
   169273     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
   169274 
   169275     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   169276     aLeft = aSpare;
   169277     while( iLeft<nLeft || iRight<nRight ){
   169278       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
   169279       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
   169280       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
   169281       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
   169282       if( (iLeft!=nLeft) && ((iRight==nRight)
   169283        || (xleft1<xright1)
   169284        || (xleft1==xright1 && xleft2<xright2)
   169285       )){
   169286         aIdx[iLeft+iRight] = aLeft[iLeft];
   169287         iLeft++;
   169288       }else{
   169289         aIdx[iLeft+iRight] = aRight[iRight];
   169290         iRight++;
   169291       }
   169292     }
   169293 
   169294 #if 0
   169295     /* Check that the sort worked */
   169296     {
   169297       int jj;
   169298       for(jj=1; jj<nIdx; jj++){
   169299         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
   169300         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
   169301         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
   169302         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
   169303         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
   169304       }
   169305     }
   169306 #endif
   169307   }
   169308 }
   169309 
   169310 /*
   169311 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
   169312 */
   169313 static int splitNodeStartree(
   169314   Rtree *pRtree,
   169315   RtreeCell *aCell,
   169316   int nCell,
   169317   RtreeNode *pLeft,
   169318   RtreeNode *pRight,
   169319   RtreeCell *pBboxLeft,
   169320   RtreeCell *pBboxRight
   169321 ){
   169322   int **aaSorted;
   169323   int *aSpare;
   169324   int ii;
   169325 
   169326   int iBestDim = 0;
   169327   int iBestSplit = 0;
   169328   RtreeDValue fBestMargin = RTREE_ZERO;
   169329 
   169330   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
   169331 
   169332   aaSorted = (int **)sqlite3_malloc(nByte);
   169333   if( !aaSorted ){
   169334     return SQLITE_NOMEM;
   169335   }
   169336 
   169337   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
   169338   memset(aaSorted, 0, nByte);
   169339   for(ii=0; ii<pRtree->nDim; ii++){
   169340     int jj;
   169341     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
   169342     for(jj=0; jj<nCell; jj++){
   169343       aaSorted[ii][jj] = jj;
   169344     }
   169345     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
   169346   }
   169347 
   169348   for(ii=0; ii<pRtree->nDim; ii++){
   169349     RtreeDValue margin = RTREE_ZERO;
   169350     RtreeDValue fBestOverlap = RTREE_ZERO;
   169351     RtreeDValue fBestArea = RTREE_ZERO;
   169352     int iBestLeft = 0;
   169353     int nLeft;
   169354 
   169355     for(
   169356       nLeft=RTREE_MINCELLS(pRtree);
   169357       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
   169358       nLeft++
   169359     ){
   169360       RtreeCell left;
   169361       RtreeCell right;
   169362       int kk;
   169363       RtreeDValue overlap;
   169364       RtreeDValue area;
   169365 
   169366       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
   169367       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
   169368       for(kk=1; kk<(nCell-1); kk++){
   169369         if( kk<nLeft ){
   169370           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
   169371         }else{
   169372           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
   169373         }
   169374       }
   169375       margin += cellMargin(pRtree, &left);
   169376       margin += cellMargin(pRtree, &right);
   169377       overlap = cellOverlap(pRtree, &left, &right, 1);
   169378       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
   169379       if( (nLeft==RTREE_MINCELLS(pRtree))
   169380        || (overlap<fBestOverlap)
   169381        || (overlap==fBestOverlap && area<fBestArea)
   169382       ){
   169383         iBestLeft = nLeft;
   169384         fBestOverlap = overlap;
   169385         fBestArea = area;
   169386       }
   169387     }
   169388 
   169389     if( ii==0 || margin<fBestMargin ){
   169390       iBestDim = ii;
   169391       fBestMargin = margin;
   169392       iBestSplit = iBestLeft;
   169393     }
   169394   }
   169395 
   169396   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
   169397   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
   169398   for(ii=0; ii<nCell; ii++){
   169399     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
   169400     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
   169401     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
   169402     nodeInsertCell(pRtree, pTarget, pCell);
   169403     cellUnion(pRtree, pBbox, pCell);
   169404   }
   169405 
   169406   sqlite3_free(aaSorted);
   169407   return SQLITE_OK;
   169408 }
   169409 
   169410 
   169411 static int updateMapping(
   169412   Rtree *pRtree,
   169413   i64 iRowid,
   169414   RtreeNode *pNode,
   169415   int iHeight
   169416 ){
   169417   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
   169418   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   169419   if( iHeight>0 ){
   169420     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
   169421     if( pChild ){
   169422       nodeRelease(pRtree, pChild->pParent);
   169423       nodeReference(pNode);
   169424       pChild->pParent = pNode;
   169425     }
   169426   }
   169427   return xSetMapping(pRtree, iRowid, pNode->iNode);
   169428 }
   169429 
   169430 static int SplitNode(
   169431   Rtree *pRtree,
   169432   RtreeNode *pNode,
   169433   RtreeCell *pCell,
   169434   int iHeight
   169435 ){
   169436   int i;
   169437   int newCellIsRight = 0;
   169438 
   169439   int rc = SQLITE_OK;
   169440   int nCell = NCELL(pNode);
   169441   RtreeCell *aCell;
   169442   int *aiUsed;
   169443 
   169444   RtreeNode *pLeft = 0;
   169445   RtreeNode *pRight = 0;
   169446 
   169447   RtreeCell leftbbox;
   169448   RtreeCell rightbbox;
   169449 
   169450   /* Allocate an array and populate it with a copy of pCell and
   169451   ** all cells from node pLeft. Then zero the original node.
   169452   */
   169453   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
   169454   if( !aCell ){
   169455     rc = SQLITE_NOMEM;
   169456     goto splitnode_out;
   169457   }
   169458   aiUsed = (int *)&aCell[nCell+1];
   169459   memset(aiUsed, 0, sizeof(int)*(nCell+1));
   169460   for(i=0; i<nCell; i++){
   169461     nodeGetCell(pRtree, pNode, i, &aCell[i]);
   169462   }
   169463   nodeZero(pRtree, pNode);
   169464   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
   169465   nCell++;
   169466 
   169467   if( pNode->iNode==1 ){
   169468     pRight = nodeNew(pRtree, pNode);
   169469     pLeft = nodeNew(pRtree, pNode);
   169470     pRtree->iDepth++;
   169471     pNode->isDirty = 1;
   169472     writeInt16(pNode->zData, pRtree->iDepth);
   169473   }else{
   169474     pLeft = pNode;
   169475     pRight = nodeNew(pRtree, pLeft->pParent);
   169476     nodeReference(pLeft);
   169477   }
   169478 
   169479   if( !pLeft || !pRight ){
   169480     rc = SQLITE_NOMEM;
   169481     goto splitnode_out;
   169482   }
   169483 
   169484   memset(pLeft->zData, 0, pRtree->iNodeSize);
   169485   memset(pRight->zData, 0, pRtree->iNodeSize);
   169486 
   169487   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
   169488                          &leftbbox, &rightbbox);
   169489   if( rc!=SQLITE_OK ){
   169490     goto splitnode_out;
   169491   }
   169492 
   169493   /* Ensure both child nodes have node numbers assigned to them by calling
   169494   ** nodeWrite(). Node pRight always needs a node number, as it was created
   169495   ** by nodeNew() above. But node pLeft sometimes already has a node number.
   169496   ** In this case avoid the all to nodeWrite().
   169497   */
   169498   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
   169499    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
   169500   ){
   169501     goto splitnode_out;
   169502   }
   169503 
   169504   rightbbox.iRowid = pRight->iNode;
   169505   leftbbox.iRowid = pLeft->iNode;
   169506 
   169507   if( pNode->iNode==1 ){
   169508     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
   169509     if( rc!=SQLITE_OK ){
   169510       goto splitnode_out;
   169511     }
   169512   }else{
   169513     RtreeNode *pParent = pLeft->pParent;
   169514     int iCell;
   169515     rc = nodeParentIndex(pRtree, pLeft, &iCell);
   169516     if( rc==SQLITE_OK ){
   169517       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
   169518       rc = AdjustTree(pRtree, pParent, &leftbbox);
   169519     }
   169520     if( rc!=SQLITE_OK ){
   169521       goto splitnode_out;
   169522     }
   169523   }
   169524   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
   169525     goto splitnode_out;
   169526   }
   169527 
   169528   for(i=0; i<NCELL(pRight); i++){
   169529     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
   169530     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
   169531     if( iRowid==pCell->iRowid ){
   169532       newCellIsRight = 1;
   169533     }
   169534     if( rc!=SQLITE_OK ){
   169535       goto splitnode_out;
   169536     }
   169537   }
   169538   if( pNode->iNode==1 ){
   169539     for(i=0; i<NCELL(pLeft); i++){
   169540       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
   169541       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
   169542       if( rc!=SQLITE_OK ){
   169543         goto splitnode_out;
   169544       }
   169545     }
   169546   }else if( newCellIsRight==0 ){
   169547     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
   169548   }
   169549 
   169550   if( rc==SQLITE_OK ){
   169551     rc = nodeRelease(pRtree, pRight);
   169552     pRight = 0;
   169553   }
   169554   if( rc==SQLITE_OK ){
   169555     rc = nodeRelease(pRtree, pLeft);
   169556     pLeft = 0;
   169557   }
   169558 
   169559 splitnode_out:
   169560   nodeRelease(pRtree, pRight);
   169561   nodeRelease(pRtree, pLeft);
   169562   sqlite3_free(aCell);
   169563   return rc;
   169564 }
   169565 
   169566 /*
   169567 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
   169568 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
   169569 ** the pLeaf->pParent chain all the way up to the root node.
   169570 **
   169571 ** This operation is required when a row is deleted (or updated - an update
   169572 ** is implemented as a delete followed by an insert). SQLite provides the
   169573 ** rowid of the row to delete, which can be used to find the leaf on which
   169574 ** the entry resides (argument pLeaf). Once the leaf is located, this
   169575 ** function is called to determine its ancestry.
   169576 */
   169577 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
   169578   int rc = SQLITE_OK;
   169579   RtreeNode *pChild = pLeaf;
   169580   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
   169581     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
   169582     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
   169583     rc = sqlite3_step(pRtree->pReadParent);
   169584     if( rc==SQLITE_ROW ){
   169585       RtreeNode *pTest;           /* Used to test for reference loops */
   169586       i64 iNode;                  /* Node number of parent node */
   169587 
   169588       /* Before setting pChild->pParent, test that we are not creating a
   169589       ** loop of references (as we would if, say, pChild==pParent). We don't
   169590       ** want to do this as it leads to a memory leak when trying to delete
   169591       ** the referenced counted node structures.
   169592       */
   169593       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
   169594       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
   169595       if( !pTest ){
   169596         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
   169597       }
   169598     }
   169599     rc = sqlite3_reset(pRtree->pReadParent);
   169600     if( rc==SQLITE_OK ) rc = rc2;
   169601     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
   169602     pChild = pChild->pParent;
   169603   }
   169604   return rc;
   169605 }
   169606 
   169607 static int deleteCell(Rtree *, RtreeNode *, int, int);
   169608 
   169609 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   169610   int rc;
   169611   int rc2;
   169612   RtreeNode *pParent = 0;
   169613   int iCell;
   169614 
   169615   assert( pNode->nRef==1 );
   169616 
   169617   /* Remove the entry in the parent cell. */
   169618   rc = nodeParentIndex(pRtree, pNode, &iCell);
   169619   if( rc==SQLITE_OK ){
   169620     pParent = pNode->pParent;
   169621     pNode->pParent = 0;
   169622     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
   169623   }
   169624   rc2 = nodeRelease(pRtree, pParent);
   169625   if( rc==SQLITE_OK ){
   169626     rc = rc2;
   169627   }
   169628   if( rc!=SQLITE_OK ){
   169629     return rc;
   169630   }
   169631 
   169632   /* Remove the xxx_node entry. */
   169633   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
   169634   sqlite3_step(pRtree->pDeleteNode);
   169635   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
   169636     return rc;
   169637   }
   169638 
   169639   /* Remove the xxx_parent entry. */
   169640   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
   169641   sqlite3_step(pRtree->pDeleteParent);
   169642   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
   169643     return rc;
   169644   }
   169645 
   169646   /* Remove the node from the in-memory hash table and link it into
   169647   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   169648   */
   169649   nodeHashDelete(pRtree, pNode);
   169650   pNode->iNode = iHeight;
   169651   pNode->pNext = pRtree->pDeleted;
   169652   pNode->nRef++;
   169653   pRtree->pDeleted = pNode;
   169654 
   169655   return SQLITE_OK;
   169656 }
   169657 
   169658 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   169659   RtreeNode *pParent = pNode->pParent;
   169660   int rc = SQLITE_OK;
   169661   if( pParent ){
   169662     int ii;
   169663     int nCell = NCELL(pNode);
   169664     RtreeCell box;                            /* Bounding box for pNode */
   169665     nodeGetCell(pRtree, pNode, 0, &box);
   169666     for(ii=1; ii<nCell; ii++){
   169667       RtreeCell cell;
   169668       nodeGetCell(pRtree, pNode, ii, &cell);
   169669       cellUnion(pRtree, &box, &cell);
   169670     }
   169671     box.iRowid = pNode->iNode;
   169672     rc = nodeParentIndex(pRtree, pNode, &ii);
   169673     if( rc==SQLITE_OK ){
   169674       nodeOverwriteCell(pRtree, pParent, &box, ii);
   169675       rc = fixBoundingBox(pRtree, pParent);
   169676     }
   169677   }
   169678   return rc;
   169679 }
   169680 
   169681 /*
   169682 ** Delete the cell at index iCell of node pNode. After removing the
   169683 ** cell, adjust the r-tree data structure if required.
   169684 */
   169685 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
   169686   RtreeNode *pParent;
   169687   int rc;
   169688 
   169689   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
   169690     return rc;
   169691   }
   169692 
   169693   /* Remove the cell from the node. This call just moves bytes around
   169694   ** the in-memory node image, so it cannot fail.
   169695   */
   169696   nodeDeleteCell(pRtree, pNode, iCell);
   169697 
   169698   /* If the node is not the tree root and now has less than the minimum
   169699   ** number of cells, remove it from the tree. Otherwise, update the
   169700   ** cell in the parent node so that it tightly contains the updated
   169701   ** node.
   169702   */
   169703   pParent = pNode->pParent;
   169704   assert( pParent || pNode->iNode==1 );
   169705   if( pParent ){
   169706     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
   169707       rc = removeNode(pRtree, pNode, iHeight);
   169708     }else{
   169709       rc = fixBoundingBox(pRtree, pNode);
   169710     }
   169711   }
   169712 
   169713   return rc;
   169714 }
   169715 
   169716 static int Reinsert(
   169717   Rtree *pRtree,
   169718   RtreeNode *pNode,
   169719   RtreeCell *pCell,
   169720   int iHeight
   169721 ){
   169722   int *aOrder;
   169723   int *aSpare;
   169724   RtreeCell *aCell;
   169725   RtreeDValue *aDistance;
   169726   int nCell;
   169727   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
   169728   int iDim;
   169729   int ii;
   169730   int rc = SQLITE_OK;
   169731   int n;
   169732 
   169733   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
   169734 
   169735   nCell = NCELL(pNode)+1;
   169736   n = (nCell+1)&(~1);
   169737 
   169738   /* Allocate the buffers used by this operation. The allocation is
   169739   ** relinquished before this function returns.
   169740   */
   169741   aCell = (RtreeCell *)sqlite3_malloc(n * (
   169742     sizeof(RtreeCell)     +         /* aCell array */
   169743     sizeof(int)           +         /* aOrder array */
   169744     sizeof(int)           +         /* aSpare array */
   169745     sizeof(RtreeDValue)             /* aDistance array */
   169746   ));
   169747   if( !aCell ){
   169748     return SQLITE_NOMEM;
   169749   }
   169750   aOrder    = (int *)&aCell[n];
   169751   aSpare    = (int *)&aOrder[n];
   169752   aDistance = (RtreeDValue *)&aSpare[n];
   169753 
   169754   for(ii=0; ii<nCell; ii++){
   169755     if( ii==(nCell-1) ){
   169756       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
   169757     }else{
   169758       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
   169759     }
   169760     aOrder[ii] = ii;
   169761     for(iDim=0; iDim<pRtree->nDim; iDim++){
   169762       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
   169763       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
   169764     }
   169765   }
   169766   for(iDim=0; iDim<pRtree->nDim; iDim++){
   169767     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
   169768   }
   169769 
   169770   for(ii=0; ii<nCell; ii++){
   169771     aDistance[ii] = RTREE_ZERO;
   169772     for(iDim=0; iDim<pRtree->nDim; iDim++){
   169773       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
   169774                                DCOORD(aCell[ii].aCoord[iDim*2]));
   169775       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
   169776     }
   169777   }
   169778 
   169779   SortByDistance(aOrder, nCell, aDistance, aSpare);
   169780   nodeZero(pRtree, pNode);
   169781 
   169782   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
   169783     RtreeCell *p = &aCell[aOrder[ii]];
   169784     nodeInsertCell(pRtree, pNode, p);
   169785     if( p->iRowid==pCell->iRowid ){
   169786       if( iHeight==0 ){
   169787         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
   169788       }else{
   169789         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
   169790       }
   169791     }
   169792   }
   169793   if( rc==SQLITE_OK ){
   169794     rc = fixBoundingBox(pRtree, pNode);
   169795   }
   169796   for(; rc==SQLITE_OK && ii<nCell; ii++){
   169797     /* Find a node to store this cell in. pNode->iNode currently contains
   169798     ** the height of the sub-tree headed by the cell.
   169799     */
   169800     RtreeNode *pInsert;
   169801     RtreeCell *p = &aCell[aOrder[ii]];
   169802     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
   169803     if( rc==SQLITE_OK ){
   169804       int rc2;
   169805       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
   169806       rc2 = nodeRelease(pRtree, pInsert);
   169807       if( rc==SQLITE_OK ){
   169808         rc = rc2;
   169809       }
   169810     }
   169811   }
   169812 
   169813   sqlite3_free(aCell);
   169814   return rc;
   169815 }
   169816 
   169817 /*
   169818 ** Insert cell pCell into node pNode. Node pNode is the head of a
   169819 ** subtree iHeight high (leaf nodes have iHeight==0).
   169820 */
   169821 static int rtreeInsertCell(
   169822   Rtree *pRtree,
   169823   RtreeNode *pNode,
   169824   RtreeCell *pCell,
   169825   int iHeight
   169826 ){
   169827   int rc = SQLITE_OK;
   169828   if( iHeight>0 ){
   169829     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
   169830     if( pChild ){
   169831       nodeRelease(pRtree, pChild->pParent);
   169832       nodeReference(pNode);
   169833       pChild->pParent = pNode;
   169834     }
   169835   }
   169836   if( nodeInsertCell(pRtree, pNode, pCell) ){
   169837     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
   169838       rc = SplitNode(pRtree, pNode, pCell, iHeight);
   169839     }else{
   169840       pRtree->iReinsertHeight = iHeight;
   169841       rc = Reinsert(pRtree, pNode, pCell, iHeight);
   169842     }
   169843   }else{
   169844     rc = AdjustTree(pRtree, pNode, pCell);
   169845     if( rc==SQLITE_OK ){
   169846       if( iHeight==0 ){
   169847         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
   169848       }else{
   169849         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
   169850       }
   169851     }
   169852   }
   169853   return rc;
   169854 }
   169855 
   169856 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
   169857   int ii;
   169858   int rc = SQLITE_OK;
   169859   int nCell = NCELL(pNode);
   169860 
   169861   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
   169862     RtreeNode *pInsert;
   169863     RtreeCell cell;
   169864     nodeGetCell(pRtree, pNode, ii, &cell);
   169865 
   169866     /* Find a node to store this cell in. pNode->iNode currently contains
   169867     ** the height of the sub-tree headed by the cell.
   169868     */
   169869     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
   169870     if( rc==SQLITE_OK ){
   169871       int rc2;
   169872       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
   169873       rc2 = nodeRelease(pRtree, pInsert);
   169874       if( rc==SQLITE_OK ){
   169875         rc = rc2;
   169876       }
   169877     }
   169878   }
   169879   return rc;
   169880 }
   169881 
   169882 /*
   169883 ** Select a currently unused rowid for a new r-tree record.
   169884 */
   169885 static int newRowid(Rtree *pRtree, i64 *piRowid){
   169886   int rc;
   169887   sqlite3_bind_null(pRtree->pWriteRowid, 1);
   169888   sqlite3_bind_null(pRtree->pWriteRowid, 2);
   169889   sqlite3_step(pRtree->pWriteRowid);
   169890   rc = sqlite3_reset(pRtree->pWriteRowid);
   169891   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
   169892   return rc;
   169893 }
   169894 
   169895 /*
   169896 ** Remove the entry with rowid=iDelete from the r-tree structure.
   169897 */
   169898 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
   169899   int rc;                         /* Return code */
   169900   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
   169901   int iCell;                      /* Index of iDelete cell in pLeaf */
   169902   RtreeNode *pRoot = 0;           /* Root node of rtree structure */
   169903 
   169904 
   169905   /* Obtain a reference to the root node to initialize Rtree.iDepth */
   169906   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   169907 
   169908   /* Obtain a reference to the leaf node that contains the entry
   169909   ** about to be deleted.
   169910   */
   169911   if( rc==SQLITE_OK ){
   169912     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
   169913   }
   169914 
   169915   /* Delete the cell in question from the leaf node. */
   169916   if( rc==SQLITE_OK ){
   169917     int rc2;
   169918     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
   169919     if( rc==SQLITE_OK ){
   169920       rc = deleteCell(pRtree, pLeaf, iCell, 0);
   169921     }
   169922     rc2 = nodeRelease(pRtree, pLeaf);
   169923     if( rc==SQLITE_OK ){
   169924       rc = rc2;
   169925     }
   169926   }
   169927 
   169928   /* Delete the corresponding entry in the <rtree>_rowid table. */
   169929   if( rc==SQLITE_OK ){
   169930     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
   169931     sqlite3_step(pRtree->pDeleteRowid);
   169932     rc = sqlite3_reset(pRtree->pDeleteRowid);
   169933   }
   169934 
   169935   /* Check if the root node now has exactly one child. If so, remove
   169936   ** it, schedule the contents of the child for reinsertion and
   169937   ** reduce the tree height by one.
   169938   **
   169939   ** This is equivalent to copying the contents of the child into
   169940   ** the root node (the operation that Gutman's paper says to perform
   169941   ** in this scenario).
   169942   */
   169943   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
   169944     int rc2;
   169945     RtreeNode *pChild = 0;
   169946     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
   169947     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
   169948     if( rc==SQLITE_OK ){
   169949       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
   169950     }
   169951     rc2 = nodeRelease(pRtree, pChild);
   169952     if( rc==SQLITE_OK ) rc = rc2;
   169953     if( rc==SQLITE_OK ){
   169954       pRtree->iDepth--;
   169955       writeInt16(pRoot->zData, pRtree->iDepth);
   169956       pRoot->isDirty = 1;
   169957     }
   169958   }
   169959 
   169960   /* Re-insert the contents of any underfull nodes removed from the tree. */
   169961   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
   169962     if( rc==SQLITE_OK ){
   169963       rc = reinsertNodeContent(pRtree, pLeaf);
   169964     }
   169965     pRtree->pDeleted = pLeaf->pNext;
   169966     sqlite3_free(pLeaf);
   169967   }
   169968 
   169969   /* Release the reference to the root node. */
   169970   if( rc==SQLITE_OK ){
   169971     rc = nodeRelease(pRtree, pRoot);
   169972   }else{
   169973     nodeRelease(pRtree, pRoot);
   169974   }
   169975 
   169976   return rc;
   169977 }
   169978 
   169979 /*
   169980 ** Rounding constants for float->double conversion.
   169981 */
   169982 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
   169983 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
   169984 
   169985 #if !defined(SQLITE_RTREE_INT_ONLY)
   169986 /*
   169987 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
   169988 ** while taking care to round toward negative or positive, respectively.
   169989 */
   169990 static RtreeValue rtreeValueDown(sqlite3_value *v){
   169991   double d = sqlite3_value_double(v);
   169992   float f = (float)d;
   169993   if( f>d ){
   169994     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
   169995   }
   169996   return f;
   169997 }
   169998 static RtreeValue rtreeValueUp(sqlite3_value *v){
   169999   double d = sqlite3_value_double(v);
   170000   float f = (float)d;
   170001   if( f<d ){
   170002     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
   170003   }
   170004   return f;
   170005 }
   170006 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
   170007 
   170008 /*
   170009 ** A constraint has failed while inserting a row into an rtree table.
   170010 ** Assuming no OOM error occurs, this function sets the error message
   170011 ** (at pRtree->base.zErrMsg) to an appropriate value and returns
   170012 ** SQLITE_CONSTRAINT.
   170013 **
   170014 ** Parameter iCol is the index of the leftmost column involved in the
   170015 ** constraint failure. If it is 0, then the constraint that failed is
   170016 ** the unique constraint on the id column. Otherwise, it is the rtree
   170017 ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
   170018 **
   170019 ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
   170020 */
   170021 static int rtreeConstraintError(Rtree *pRtree, int iCol){
   170022   sqlite3_stmt *pStmt = 0;
   170023   char *zSql;
   170024   int rc;
   170025 
   170026   assert( iCol==0 || iCol%2 );
   170027   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
   170028   if( zSql ){
   170029     rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
   170030   }else{
   170031     rc = SQLITE_NOMEM;
   170032   }
   170033   sqlite3_free(zSql);
   170034 
   170035   if( rc==SQLITE_OK ){
   170036     if( iCol==0 ){
   170037       const char *zCol = sqlite3_column_name(pStmt, 0);
   170038       pRtree->base.zErrMsg = sqlite3_mprintf(
   170039           "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
   170040       );
   170041     }else{
   170042       const char *zCol1 = sqlite3_column_name(pStmt, iCol);
   170043       const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
   170044       pRtree->base.zErrMsg = sqlite3_mprintf(
   170045           "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
   170046       );
   170047     }
   170048   }
   170049 
   170050   sqlite3_finalize(pStmt);
   170051   return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
   170052 }
   170053 
   170054 
   170055 
   170056 /*
   170057 ** The xUpdate method for rtree module virtual tables.
   170058 */
   170059 static int rtreeUpdate(
   170060   sqlite3_vtab *pVtab,
   170061   int nData,
   170062   sqlite3_value **azData,
   170063   sqlite_int64 *pRowid
   170064 ){
   170065   Rtree *pRtree = (Rtree *)pVtab;
   170066   int rc = SQLITE_OK;
   170067   RtreeCell cell;                 /* New cell to insert if nData>1 */
   170068   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
   170069 
   170070   rtreeReference(pRtree);
   170071   assert(nData>=1);
   170072 
   170073   cell.iRowid = 0;  /* Used only to suppress a compiler warning */
   170074 
   170075   /* Constraint handling. A write operation on an r-tree table may return
   170076   ** SQLITE_CONSTRAINT for two reasons:
   170077   **
   170078   **   1. A duplicate rowid value, or
   170079   **   2. The supplied data violates the "x2>=x1" constraint.
   170080   **
   170081   ** In the first case, if the conflict-handling mode is REPLACE, then
   170082   ** the conflicting row can be removed before proceeding. In the second
   170083   ** case, SQLITE_CONSTRAINT must be returned regardless of the
   170084   ** conflict-handling mode specified by the user.
   170085   */
   170086   if( nData>1 ){
   170087     int ii;
   170088 
   170089     /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
   170090     **
   170091     ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
   170092     ** with "column" that are interpreted as table constraints.
   170093     ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
   170094     ** This problem was discovered after years of use, so we silently ignore
   170095     ** these kinds of misdeclared tables to avoid breaking any legacy.
   170096     */
   170097     assert( nData<=(pRtree->nDim2 + 3) );
   170098 
   170099 #ifndef SQLITE_RTREE_INT_ONLY
   170100     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   170101       for(ii=0; ii<nData-4; ii+=2){
   170102         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
   170103         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
   170104         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
   170105           rc = rtreeConstraintError(pRtree, ii+1);
   170106           goto constraint;
   170107         }
   170108       }
   170109     }else
   170110 #endif
   170111     {
   170112       for(ii=0; ii<nData-4; ii+=2){
   170113         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
   170114         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
   170115         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
   170116           rc = rtreeConstraintError(pRtree, ii+1);
   170117           goto constraint;
   170118         }
   170119       }
   170120     }
   170121 
   170122     /* If a rowid value was supplied, check if it is already present in
   170123     ** the table. If so, the constraint has failed. */
   170124     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
   170125       cell.iRowid = sqlite3_value_int64(azData[2]);
   170126       if( sqlite3_value_type(azData[0])==SQLITE_NULL
   170127        || sqlite3_value_int64(azData[0])!=cell.iRowid
   170128       ){
   170129         int steprc;
   170130         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
   170131         steprc = sqlite3_step(pRtree->pReadRowid);
   170132         rc = sqlite3_reset(pRtree->pReadRowid);
   170133         if( SQLITE_ROW==steprc ){
   170134           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
   170135             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
   170136           }else{
   170137             rc = rtreeConstraintError(pRtree, 0);
   170138             goto constraint;
   170139           }
   170140         }
   170141       }
   170142       bHaveRowid = 1;
   170143     }
   170144   }
   170145 
   170146   /* If azData[0] is not an SQL NULL value, it is the rowid of a
   170147   ** record to delete from the r-tree table. The following block does
   170148   ** just that.
   170149   */
   170150   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
   170151     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
   170152   }
   170153 
   170154   /* If the azData[] array contains more than one element, elements
   170155   ** (azData[2]..azData[argc-1]) contain a new record to insert into
   170156   ** the r-tree structure.
   170157   */
   170158   if( rc==SQLITE_OK && nData>1 ){
   170159     /* Insert the new record into the r-tree */
   170160     RtreeNode *pLeaf = 0;
   170161 
   170162     /* Figure out the rowid of the new row. */
   170163     if( bHaveRowid==0 ){
   170164       rc = newRowid(pRtree, &cell.iRowid);
   170165     }
   170166     *pRowid = cell.iRowid;
   170167 
   170168     if( rc==SQLITE_OK ){
   170169       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
   170170     }
   170171     if( rc==SQLITE_OK ){
   170172       int rc2;
   170173       pRtree->iReinsertHeight = -1;
   170174       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
   170175       rc2 = nodeRelease(pRtree, pLeaf);
   170176       if( rc==SQLITE_OK ){
   170177         rc = rc2;
   170178       }
   170179     }
   170180   }
   170181 
   170182 constraint:
   170183   rtreeRelease(pRtree);
   170184   return rc;
   170185 }
   170186 
   170187 /*
   170188 ** Called when a transaction starts.
   170189 */
   170190 static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
   170191   Rtree *pRtree = (Rtree *)pVtab;
   170192   assert( pRtree->inWrTrans==0 );
   170193   pRtree->inWrTrans++;
   170194   return SQLITE_OK;
   170195 }
   170196 
   170197 /*
   170198 ** Called when a transaction completes (either by COMMIT or ROLLBACK).
   170199 ** The sqlite3_blob object should be released at this point.
   170200 */
   170201 static int rtreeEndTransaction(sqlite3_vtab *pVtab){
   170202   Rtree *pRtree = (Rtree *)pVtab;
   170203   pRtree->inWrTrans = 0;
   170204   nodeBlobReset(pRtree);
   170205   return SQLITE_OK;
   170206 }
   170207 
   170208 /*
   170209 ** The xRename method for rtree module virtual tables.
   170210 */
   170211 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
   170212   Rtree *pRtree = (Rtree *)pVtab;
   170213   int rc = SQLITE_NOMEM;
   170214   char *zSql = sqlite3_mprintf(
   170215     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
   170216     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
   170217     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
   170218     , pRtree->zDb, pRtree->zName, zNewName
   170219     , pRtree->zDb, pRtree->zName, zNewName
   170220     , pRtree->zDb, pRtree->zName, zNewName
   170221   );
   170222   if( zSql ){
   170223     nodeBlobReset(pRtree);
   170224     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
   170225     sqlite3_free(zSql);
   170226   }
   170227   return rc;
   170228 }
   170229 
   170230 /*
   170231 ** The xSavepoint method.
   170232 **
   170233 ** This module does not need to do anything to support savepoints. However,
   170234 ** it uses this hook to close any open blob handle. This is done because a
   170235 ** DROP TABLE command - which fortunately always opens a savepoint - cannot
   170236 ** succeed if there are any open blob handles. i.e. if the blob handle were
   170237 ** not closed here, the following would fail:
   170238 **
   170239 **   BEGIN;
   170240 **     INSERT INTO rtree...
   170241 **     DROP TABLE <tablename>;    -- Would fail with SQLITE_LOCKED
   170242 **   COMMIT;
   170243 */
   170244 static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
   170245   Rtree *pRtree = (Rtree *)pVtab;
   170246   int iwt = pRtree->inWrTrans;
   170247   UNUSED_PARAMETER(iSavepoint);
   170248   pRtree->inWrTrans = 0;
   170249   nodeBlobReset(pRtree);
   170250   pRtree->inWrTrans = iwt;
   170251   return SQLITE_OK;
   170252 }
   170253 
   170254 /*
   170255 ** This function populates the pRtree->nRowEst variable with an estimate
   170256 ** of the number of rows in the virtual table. If possible, this is based
   170257 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
   170258 */
   170259 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
   170260   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
   170261   char *zSql;
   170262   sqlite3_stmt *p;
   170263   int rc;
   170264   i64 nRow = 0;
   170265 
   170266   rc = sqlite3_table_column_metadata(
   170267       db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
   170268   );
   170269   if( rc!=SQLITE_OK ){
   170270     pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
   170271     return rc==SQLITE_ERROR ? SQLITE_OK : rc;
   170272   }
   170273   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
   170274   if( zSql==0 ){
   170275     rc = SQLITE_NOMEM;
   170276   }else{
   170277     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
   170278     if( rc==SQLITE_OK ){
   170279       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
   170280       rc = sqlite3_finalize(p);
   170281     }else if( rc!=SQLITE_NOMEM ){
   170282       rc = SQLITE_OK;
   170283     }
   170284 
   170285     if( rc==SQLITE_OK ){
   170286       if( nRow==0 ){
   170287         pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
   170288       }else{
   170289         pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
   170290       }
   170291     }
   170292     sqlite3_free(zSql);
   170293   }
   170294 
   170295   return rc;
   170296 }
   170297 
   170298 static sqlite3_module rtreeModule = {
   170299   2,                          /* iVersion */
   170300   rtreeCreate,                /* xCreate - create a table */
   170301   rtreeConnect,               /* xConnect - connect to an existing table */
   170302   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
   170303   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
   170304   rtreeDestroy,               /* xDestroy - Drop a table */
   170305   rtreeOpen,                  /* xOpen - open a cursor */
   170306   rtreeClose,                 /* xClose - close a cursor */
   170307   rtreeFilter,                /* xFilter - configure scan constraints */
   170308   rtreeNext,                  /* xNext - advance a cursor */
   170309   rtreeEof,                   /* xEof */
   170310   rtreeColumn,                /* xColumn - read data */
   170311   rtreeRowid,                 /* xRowid - read data */
   170312   rtreeUpdate,                /* xUpdate - write data */
   170313   rtreeBeginTransaction,      /* xBegin - begin transaction */
   170314   rtreeEndTransaction,        /* xSync - sync transaction */
   170315   rtreeEndTransaction,        /* xCommit - commit transaction */
   170316   rtreeEndTransaction,        /* xRollback - rollback transaction */
   170317   0,                          /* xFindFunction - function overloading */
   170318   rtreeRename,                /* xRename - rename the table */
   170319   rtreeSavepoint,             /* xSavepoint */
   170320   0,                          /* xRelease */
   170321   0,                          /* xRollbackTo */
   170322 };
   170323 
   170324 static int rtreeSqlInit(
   170325   Rtree *pRtree,
   170326   sqlite3 *db,
   170327   const char *zDb,
   170328   const char *zPrefix,
   170329   int isCreate
   170330 ){
   170331   int rc = SQLITE_OK;
   170332 
   170333   #define N_STATEMENT 8
   170334   static const char *azSql[N_STATEMENT] = {
   170335     /* Write the xxx_node table */
   170336     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
   170337     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
   170338 
   170339     /* Read and write the xxx_rowid table */
   170340     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
   170341     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
   170342     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
   170343 
   170344     /* Read and write the xxx_parent table */
   170345     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
   170346     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
   170347     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
   170348   };
   170349   sqlite3_stmt **appStmt[N_STATEMENT];
   170350   int i;
   170351 
   170352   pRtree->db = db;
   170353 
   170354   if( isCreate ){
   170355     char *zCreate = sqlite3_mprintf(
   170356 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
   170357 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
   170358 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
   170359                                   " parentnode INTEGER);"
   170360 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
   170361       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
   170362     );
   170363     if( !zCreate ){
   170364       return SQLITE_NOMEM;
   170365     }
   170366     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
   170367     sqlite3_free(zCreate);
   170368     if( rc!=SQLITE_OK ){
   170369       return rc;
   170370     }
   170371   }
   170372 
   170373   appStmt[0] = &pRtree->pWriteNode;
   170374   appStmt[1] = &pRtree->pDeleteNode;
   170375   appStmt[2] = &pRtree->pReadRowid;
   170376   appStmt[3] = &pRtree->pWriteRowid;
   170377   appStmt[4] = &pRtree->pDeleteRowid;
   170378   appStmt[5] = &pRtree->pReadParent;
   170379   appStmt[6] = &pRtree->pWriteParent;
   170380   appStmt[7] = &pRtree->pDeleteParent;
   170381 
   170382   rc = rtreeQueryStat1(db, pRtree);
   170383   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
   170384     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
   170385     if( zSql ){
   170386       rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
   170387                               appStmt[i], 0);
   170388     }else{
   170389       rc = SQLITE_NOMEM;
   170390     }
   170391     sqlite3_free(zSql);
   170392   }
   170393 
   170394   return rc;
   170395 }
   170396 
   170397 /*
   170398 ** The second argument to this function contains the text of an SQL statement
   170399 ** that returns a single integer value. The statement is compiled and executed
   170400 ** using database connection db. If successful, the integer value returned
   170401 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
   170402 ** code is returned and the value of *piVal after returning is not defined.
   170403 */
   170404 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
   170405   int rc = SQLITE_NOMEM;
   170406   if( zSql ){
   170407     sqlite3_stmt *pStmt = 0;
   170408     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   170409     if( rc==SQLITE_OK ){
   170410       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   170411         *piVal = sqlite3_column_int(pStmt, 0);
   170412       }
   170413       rc = sqlite3_finalize(pStmt);
   170414     }
   170415   }
   170416   return rc;
   170417 }
   170418 
   170419 /*
   170420 ** This function is called from within the xConnect() or xCreate() method to
   170421 ** determine the node-size used by the rtree table being created or connected
   170422 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
   170423 ** Otherwise, an SQLite error code is returned.
   170424 **
   170425 ** If this function is being called as part of an xConnect(), then the rtree
   170426 ** table already exists. In this case the node-size is determined by inspecting
   170427 ** the root node of the tree.
   170428 **
   170429 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
   170430 ** This ensures that each node is stored on a single database page. If the
   170431 ** database page-size is so large that more than RTREE_MAXCELLS entries
   170432 ** would fit in a single node, use a smaller node-size.
   170433 */
   170434 static int getNodeSize(
   170435   sqlite3 *db,                    /* Database handle */
   170436   Rtree *pRtree,                  /* Rtree handle */
   170437   int isCreate,                   /* True for xCreate, false for xConnect */
   170438   char **pzErr                    /* OUT: Error message, if any */
   170439 ){
   170440   int rc;
   170441   char *zSql;
   170442   if( isCreate ){
   170443     int iPageSize = 0;
   170444     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
   170445     rc = getIntFromStmt(db, zSql, &iPageSize);
   170446     if( rc==SQLITE_OK ){
   170447       pRtree->iNodeSize = iPageSize-64;
   170448       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
   170449         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
   170450       }
   170451     }else{
   170452       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   170453     }
   170454   }else{
   170455     zSql = sqlite3_mprintf(
   170456         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
   170457         pRtree->zDb, pRtree->zName
   170458     );
   170459     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
   170460     if( rc!=SQLITE_OK ){
   170461       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   170462     }else if( pRtree->iNodeSize<(512-64) ){
   170463       rc = SQLITE_CORRUPT_VTAB;
   170464       *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
   170465                                pRtree->zName);
   170466     }
   170467   }
   170468 
   170469   sqlite3_free(zSql);
   170470   return rc;
   170471 }
   170472 
   170473 /*
   170474 ** This function is the implementation of both the xConnect and xCreate
   170475 ** methods of the r-tree virtual table.
   170476 **
   170477 **   argv[0]   -> module name
   170478 **   argv[1]   -> database name
   170479 **   argv[2]   -> table name
   170480 **   argv[...] -> column names...
   170481 */
   170482 static int rtreeInit(
   170483   sqlite3 *db,                        /* Database connection */
   170484   void *pAux,                         /* One of the RTREE_COORD_* constants */
   170485   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
   170486   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
   170487   char **pzErr,                       /* OUT: Error message, if any */
   170488   int isCreate                        /* True for xCreate, false for xConnect */
   170489 ){
   170490   int rc = SQLITE_OK;
   170491   Rtree *pRtree;
   170492   int nDb;              /* Length of string argv[1] */
   170493   int nName;            /* Length of string argv[2] */
   170494   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
   170495 
   170496   const char *aErrMsg[] = {
   170497     0,                                                    /* 0 */
   170498     "Wrong number of columns for an rtree table",         /* 1 */
   170499     "Too few columns for an rtree table",                 /* 2 */
   170500     "Too many columns for an rtree table"                 /* 3 */
   170501   };
   170502 
   170503   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
   170504   if( aErrMsg[iErr] ){
   170505     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
   170506     return SQLITE_ERROR;
   170507   }
   170508 
   170509   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   170510 
   170511   /* Allocate the sqlite3_vtab structure */
   170512   nDb = (int)strlen(argv[1]);
   170513   nName = (int)strlen(argv[2]);
   170514   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
   170515   if( !pRtree ){
   170516     return SQLITE_NOMEM;
   170517   }
   170518   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
   170519   pRtree->nBusy = 1;
   170520   pRtree->base.pModule = &rtreeModule;
   170521   pRtree->zDb = (char *)&pRtree[1];
   170522   pRtree->zName = &pRtree->zDb[nDb+1];
   170523   pRtree->nDim = (u8)((argc-4)/2);
   170524   pRtree->nDim2 = pRtree->nDim*2;
   170525   pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
   170526   pRtree->eCoordType = (u8)eCoordType;
   170527   memcpy(pRtree->zDb, argv[1], nDb);
   170528   memcpy(pRtree->zName, argv[2], nName);
   170529 
   170530   /* Figure out the node size to use. */
   170531   rc = getNodeSize(db, pRtree, isCreate, pzErr);
   170532 
   170533   /* Create/Connect to the underlying relational database schema. If
   170534   ** that is successful, call sqlite3_declare_vtab() to configure
   170535   ** the r-tree table schema.
   170536   */
   170537   if( rc==SQLITE_OK ){
   170538     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
   170539       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   170540     }else{
   170541       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
   170542       char *zTmp;
   170543       int ii;
   170544       for(ii=4; zSql && ii<argc; ii++){
   170545         zTmp = zSql;
   170546         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
   170547         sqlite3_free(zTmp);
   170548       }
   170549       if( zSql ){
   170550         zTmp = zSql;
   170551         zSql = sqlite3_mprintf("%s);", zTmp);
   170552         sqlite3_free(zTmp);
   170553       }
   170554       if( !zSql ){
   170555         rc = SQLITE_NOMEM;
   170556       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
   170557         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   170558       }
   170559       sqlite3_free(zSql);
   170560     }
   170561   }
   170562 
   170563   if( rc==SQLITE_OK ){
   170564     *ppVtab = (sqlite3_vtab *)pRtree;
   170565   }else{
   170566     assert( *ppVtab==0 );
   170567     assert( pRtree->nBusy==1 );
   170568     rtreeRelease(pRtree);
   170569   }
   170570   return rc;
   170571 }
   170572 
   170573 
   170574 /*
   170575 ** Implementation of a scalar function that decodes r-tree nodes to
   170576 ** human readable strings. This can be used for debugging and analysis.
   170577 **
   170578 ** The scalar function takes two arguments: (1) the number of dimensions
   170579 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
   170580 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
   170581 ** deserialize all nodes, a statement like:
   170582 **
   170583 **   SELECT rtreenode(2, data) FROM rt_node;
   170584 **
   170585 ** The human readable string takes the form of a Tcl list with one
   170586 ** entry for each cell in the r-tree node. Each entry is itself a
   170587 ** list, containing the 8-byte rowid/pageno followed by the
   170588 ** <num-dimension>*2 coordinates.
   170589 */
   170590 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   170591   char *zText = 0;
   170592   RtreeNode node;
   170593   Rtree tree;
   170594   int ii;
   170595 
   170596   UNUSED_PARAMETER(nArg);
   170597   memset(&node, 0, sizeof(RtreeNode));
   170598   memset(&tree, 0, sizeof(Rtree));
   170599   tree.nDim = (u8)sqlite3_value_int(apArg[0]);
   170600   tree.nDim2 = tree.nDim*2;
   170601   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   170602   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
   170603 
   170604   for(ii=0; ii<NCELL(&node); ii++){
   170605     char zCell[512];
   170606     int nCell = 0;
   170607     RtreeCell cell;
   170608     int jj;
   170609 
   170610     nodeGetCell(&tree, &node, ii, &cell);
   170611     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
   170612     nCell = (int)strlen(zCell);
   170613     for(jj=0; jj<tree.nDim2; jj++){
   170614 #ifndef SQLITE_RTREE_INT_ONLY
   170615       sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
   170616                        (double)cell.aCoord[jj].f);
   170617 #else
   170618       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
   170619                        cell.aCoord[jj].i);
   170620 #endif
   170621       nCell = (int)strlen(zCell);
   170622     }
   170623 
   170624     if( zText ){
   170625       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
   170626       sqlite3_free(zText);
   170627       zText = zTextNew;
   170628     }else{
   170629       zText = sqlite3_mprintf("{%s}", zCell);
   170630     }
   170631   }
   170632 
   170633   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
   170634 }
   170635 
   170636 /* This routine implements an SQL function that returns the "depth" parameter
   170637 ** from the front of a blob that is an r-tree node.  For example:
   170638 **
   170639 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
   170640 **
   170641 ** The depth value is 0 for all nodes other than the root node, and the root
   170642 ** node always has nodeno=1, so the example above is the primary use for this
   170643 ** routine.  This routine is intended for testing and analysis only.
   170644 */
   170645 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   170646   UNUSED_PARAMETER(nArg);
   170647   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
   170648    || sqlite3_value_bytes(apArg[0])<2
   170649   ){
   170650     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   170651   }else{
   170652     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
   170653     sqlite3_result_int(ctx, readInt16(zBlob));
   170654   }
   170655 }
   170656 
   170657 /*
   170658 ** Context object passed between the various routines that make up the
   170659 ** implementation of integrity-check function rtreecheck().
   170660 */
   170661 typedef struct RtreeCheck RtreeCheck;
   170662 struct RtreeCheck {
   170663   sqlite3 *db;                    /* Database handle */
   170664   const char *zDb;                /* Database containing rtree table */
   170665   const char *zTab;               /* Name of rtree table */
   170666   int bInt;                       /* True for rtree_i32 table */
   170667   int nDim;                       /* Number of dimensions for this rtree tbl */
   170668   sqlite3_stmt *pGetNode;         /* Statement used to retrieve nodes */
   170669   sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
   170670   int nLeaf;                      /* Number of leaf cells in table */
   170671   int nNonLeaf;                   /* Number of non-leaf cells in table */
   170672   int rc;                         /* Return code */
   170673   char *zReport;                  /* Message to report */
   170674   int nErr;                       /* Number of lines in zReport */
   170675 };
   170676 
   170677 #define RTREE_CHECK_MAX_ERROR 100
   170678 
   170679 /*
   170680 ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
   170681 ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
   170682 */
   170683 static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
   170684   int rc = sqlite3_reset(pStmt);
   170685   if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
   170686 }
   170687 
   170688 /*
   170689 ** The second and subsequent arguments to this function are a format string
   170690 ** and printf style arguments. This function formats the string and attempts
   170691 ** to compile it as an SQL statement.
   170692 **
   170693 ** If successful, a pointer to the new SQL statement is returned. Otherwise,
   170694 ** NULL is returned and an error code left in RtreeCheck.rc.
   170695 */
   170696 static sqlite3_stmt *rtreeCheckPrepare(
   170697   RtreeCheck *pCheck,             /* RtreeCheck object */
   170698   const char *zFmt, ...           /* Format string and trailing args */
   170699 ){
   170700   va_list ap;
   170701   char *z;
   170702   sqlite3_stmt *pRet = 0;
   170703 
   170704   va_start(ap, zFmt);
   170705   z = sqlite3_vmprintf(zFmt, ap);
   170706 
   170707   if( pCheck->rc==SQLITE_OK ){
   170708     if( z==0 ){
   170709       pCheck->rc = SQLITE_NOMEM;
   170710     }else{
   170711       pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
   170712     }
   170713   }
   170714 
   170715   sqlite3_free(z);
   170716   va_end(ap);
   170717   return pRet;
   170718 }
   170719 
   170720 /*
   170721 ** The second and subsequent arguments to this function are a printf()
   170722 ** style format string and arguments. This function formats the string and
   170723 ** appends it to the report being accumuated in pCheck.
   170724 */
   170725 static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
   170726   va_list ap;
   170727   va_start(ap, zFmt);
   170728   if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
   170729     char *z = sqlite3_vmprintf(zFmt, ap);
   170730     if( z==0 ){
   170731       pCheck->rc = SQLITE_NOMEM;
   170732     }else{
   170733       pCheck->zReport = sqlite3_mprintf("%z%s%z",
   170734           pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
   170735       );
   170736       if( pCheck->zReport==0 ){
   170737         pCheck->rc = SQLITE_NOMEM;
   170738       }
   170739     }
   170740     pCheck->nErr++;
   170741   }
   170742   va_end(ap);
   170743 }
   170744 
   170745 /*
   170746 ** This function is a no-op if there is already an error code stored
   170747 ** in the RtreeCheck object indicated by the first argument. NULL is
   170748 ** returned in this case.
   170749 **
   170750 ** Otherwise, the contents of rtree table node iNode are loaded from
   170751 ** the database and copied into a buffer obtained from sqlite3_malloc().
   170752 ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
   170753 ** is set to the size of the buffer in bytes.
   170754 **
   170755 ** Or, if an error does occur, NULL is returned and an error code left
   170756 ** in the RtreeCheck object. The final value of *pnNode is undefined in
   170757 ** this case.
   170758 */
   170759 static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
   170760   u8 *pRet = 0;                   /* Return value */
   170761 
   170762   assert( pCheck->rc==SQLITE_OK );
   170763   if( pCheck->pGetNode==0 ){
   170764     pCheck->pGetNode = rtreeCheckPrepare(pCheck,
   170765         "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
   170766         pCheck->zDb, pCheck->zTab
   170767     );
   170768   }
   170769 
   170770   if( pCheck->rc==SQLITE_OK ){
   170771     sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
   170772     if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
   170773       int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
   170774       const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
   170775       pRet = sqlite3_malloc(nNode);
   170776       if( pRet==0 ){
   170777         pCheck->rc = SQLITE_NOMEM;
   170778       }else{
   170779         memcpy(pRet, pNode, nNode);
   170780         *pnNode = nNode;
   170781       }
   170782     }
   170783     rtreeCheckReset(pCheck, pCheck->pGetNode);
   170784     if( pCheck->rc==SQLITE_OK && pRet==0 ){
   170785       rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
   170786     }
   170787   }
   170788 
   170789   return pRet;
   170790 }
   170791 
   170792 /*
   170793 ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
   170794 ** (if bLeaf==1) table contains a specified entry. The schemas of the
   170795 ** two tables are:
   170796 **
   170797 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
   170798 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
   170799 **
   170800 ** In both cases, this function checks that there exists an entry with
   170801 ** IPK value iKey and the second column set to iVal.
   170802 **
   170803 */
   170804 static void rtreeCheckMapping(
   170805   RtreeCheck *pCheck,             /* RtreeCheck object */
   170806   int bLeaf,                      /* True for a leaf cell, false for interior */
   170807   i64 iKey,                       /* Key for mapping */
   170808   i64 iVal                        /* Expected value for mapping */
   170809 ){
   170810   int rc;
   170811   sqlite3_stmt *pStmt;
   170812   const char *azSql[2] = {
   170813     "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?",
   170814     "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?"
   170815   };
   170816 
   170817   assert( bLeaf==0 || bLeaf==1 );
   170818   if( pCheck->aCheckMapping[bLeaf]==0 ){
   170819     pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
   170820         azSql[bLeaf], pCheck->zDb, pCheck->zTab
   170821     );
   170822   }
   170823   if( pCheck->rc!=SQLITE_OK ) return;
   170824 
   170825   pStmt = pCheck->aCheckMapping[bLeaf];
   170826   sqlite3_bind_int64(pStmt, 1, iKey);
   170827   rc = sqlite3_step(pStmt);
   170828   if( rc==SQLITE_DONE ){
   170829     rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
   170830         iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
   170831     );
   170832   }else if( rc==SQLITE_ROW ){
   170833     i64 ii = sqlite3_column_int64(pStmt, 0);
   170834     if( ii!=iVal ){
   170835       rtreeCheckAppendMsg(pCheck,
   170836           "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
   170837           iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
   170838       );
   170839     }
   170840   }
   170841   rtreeCheckReset(pCheck, pStmt);
   170842 }
   170843 
   170844 /*
   170845 ** Argument pCell points to an array of coordinates stored on an rtree page.
   170846 ** This function checks that the coordinates are internally consistent (no
   170847 ** x1>x2 conditions) and adds an error message to the RtreeCheck object
   170848 ** if they are not.
   170849 **
   170850 ** Additionally, if pParent is not NULL, then it is assumed to point to
   170851 ** the array of coordinates on the parent page that bound the page
   170852 ** containing pCell. In this case it is also verified that the two
   170853 ** sets of coordinates are mutually consistent and an error message added
   170854 ** to the RtreeCheck object if they are not.
   170855 */
   170856 static void rtreeCheckCellCoord(
   170857   RtreeCheck *pCheck,
   170858   i64 iNode,                      /* Node id to use in error messages */
   170859   int iCell,                      /* Cell number to use in error messages */
   170860   u8 *pCell,                      /* Pointer to cell coordinates */
   170861   u8 *pParent                     /* Pointer to parent coordinates */
   170862 ){
   170863   RtreeCoord c1, c2;
   170864   RtreeCoord p1, p2;
   170865   int i;
   170866 
   170867   for(i=0; i<pCheck->nDim; i++){
   170868     readCoord(&pCell[4*2*i], &c1);
   170869     readCoord(&pCell[4*(2*i + 1)], &c2);
   170870 
   170871     /* printf("%e, %e\n", c1.u.f, c2.u.f); */
   170872     if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
   170873       rtreeCheckAppendMsg(pCheck,
   170874           "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
   170875       );
   170876     }
   170877 
   170878     if( pParent ){
   170879       readCoord(&pParent[4*2*i], &p1);
   170880       readCoord(&pParent[4*(2*i + 1)], &p2);
   170881 
   170882       if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
   170883        || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
   170884       ){
   170885         rtreeCheckAppendMsg(pCheck,
   170886             "Dimension %d of cell %d on node %lld is corrupt relative to parent"
   170887             , i, iCell, iNode
   170888         );
   170889       }
   170890     }
   170891   }
   170892 }
   170893 
   170894 /*
   170895 ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
   170896 ** the r-tree structure. Argument aParent points to the array of coordinates
   170897 ** that bound node iNode on the parent node.
   170898 **
   170899 ** If any problems are discovered, an error message is appended to the
   170900 ** report accumulated in the RtreeCheck object.
   170901 */
   170902 static void rtreeCheckNode(
   170903   RtreeCheck *pCheck,
   170904   int iDepth,                     /* Depth of iNode (0==leaf) */
   170905   u8 *aParent,                    /* Buffer containing parent coords */
   170906   i64 iNode                       /* Node to check */
   170907 ){
   170908   u8 *aNode = 0;
   170909   int nNode = 0;
   170910 
   170911   assert( iNode==1 || aParent!=0 );
   170912   assert( pCheck->nDim>0 );
   170913 
   170914   aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
   170915   if( aNode ){
   170916     if( nNode<4 ){
   170917       rtreeCheckAppendMsg(pCheck,
   170918           "Node %lld is too small (%d bytes)", iNode, nNode
   170919       );
   170920     }else{
   170921       int nCell;                  /* Number of cells on page */
   170922       int i;                      /* Used to iterate through cells */
   170923       if( aParent==0 ){
   170924         iDepth = readInt16(aNode);
   170925         if( iDepth>RTREE_MAX_DEPTH ){
   170926           rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
   170927           sqlite3_free(aNode);
   170928           return;
   170929         }
   170930       }
   170931       nCell = readInt16(&aNode[2]);
   170932       if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
   170933         rtreeCheckAppendMsg(pCheck,
   170934             "Node %lld is too small for cell count of %d (%d bytes)",
   170935             iNode, nCell, nNode
   170936         );
   170937       }else{
   170938         for(i=0; i<nCell; i++){
   170939           u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
   170940           i64 iVal = readInt64(pCell);
   170941           rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
   170942 
   170943           if( iDepth>0 ){
   170944             rtreeCheckMapping(pCheck, 0, iVal, iNode);
   170945             rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
   170946             pCheck->nNonLeaf++;
   170947           }else{
   170948             rtreeCheckMapping(pCheck, 1, iVal, iNode);
   170949             pCheck->nLeaf++;
   170950           }
   170951         }
   170952       }
   170953     }
   170954     sqlite3_free(aNode);
   170955   }
   170956 }
   170957 
   170958 /*
   170959 ** The second argument to this function must be either "_rowid" or
   170960 ** "_parent". This function checks that the number of entries in the
   170961 ** %_rowid or %_parent table is exactly nExpect. If not, it adds
   170962 ** an error message to the report in the RtreeCheck object indicated
   170963 ** by the first argument.
   170964 */
   170965 static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
   170966   if( pCheck->rc==SQLITE_OK ){
   170967     sqlite3_stmt *pCount;
   170968     pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
   170969         pCheck->zDb, pCheck->zTab, zTbl
   170970     );
   170971     if( pCount ){
   170972       if( sqlite3_step(pCount)==SQLITE_ROW ){
   170973         i64 nActual = sqlite3_column_int64(pCount, 0);
   170974         if( nActual!=nExpect ){
   170975           rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
   170976               " - expected %lld, actual %lld" , zTbl, nExpect, nActual
   170977           );
   170978         }
   170979       }
   170980       pCheck->rc = sqlite3_finalize(pCount);
   170981     }
   170982   }
   170983 }
   170984 
   170985 /*
   170986 ** This function does the bulk of the work for the rtree integrity-check.
   170987 ** It is called by rtreecheck(), which is the SQL function implementation.
   170988 */
   170989 static int rtreeCheckTable(
   170990   sqlite3 *db,                    /* Database handle to access db through */
   170991   const char *zDb,                /* Name of db ("main", "temp" etc.) */
   170992   const char *zTab,               /* Name of rtree table to check */
   170993   char **pzReport                 /* OUT: sqlite3_malloc'd report text */
   170994 ){
   170995   RtreeCheck check;               /* Common context for various routines */
   170996   sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */
   170997   int bEnd = 0;                   /* True if transaction should be closed */
   170998 
   170999   /* Initialize the context object */
   171000   memset(&check, 0, sizeof(check));
   171001   check.db = db;
   171002   check.zDb = zDb;
   171003   check.zTab = zTab;
   171004 
   171005   /* If there is not already an open transaction, open one now. This is
   171006   ** to ensure that the queries run as part of this integrity-check operate
   171007   ** on a consistent snapshot.  */
   171008   if( sqlite3_get_autocommit(db) ){
   171009     check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
   171010     bEnd = 1;
   171011   }
   171012 
   171013   /* Find number of dimensions in the rtree table. */
   171014   pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
   171015   if( pStmt ){
   171016     int rc;
   171017     check.nDim = (sqlite3_column_count(pStmt) - 1) / 2;
   171018     if( check.nDim<1 ){
   171019       rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
   171020     }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
   171021       check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
   171022     }
   171023     rc = sqlite3_finalize(pStmt);
   171024     if( rc!=SQLITE_CORRUPT ) check.rc = rc;
   171025   }
   171026 
   171027   /* Do the actual integrity-check */
   171028   if( check.nDim>=1 ){
   171029     if( check.rc==SQLITE_OK ){
   171030       rtreeCheckNode(&check, 0, 0, 1);
   171031     }
   171032     rtreeCheckCount(&check, "_rowid", check.nLeaf);
   171033     rtreeCheckCount(&check, "_parent", check.nNonLeaf);
   171034   }
   171035 
   171036   /* Finalize SQL statements used by the integrity-check */
   171037   sqlite3_finalize(check.pGetNode);
   171038   sqlite3_finalize(check.aCheckMapping[0]);
   171039   sqlite3_finalize(check.aCheckMapping[1]);
   171040 
   171041   /* If one was opened, close the transaction */
   171042   if( bEnd ){
   171043     int rc = sqlite3_exec(db, "END", 0, 0, 0);
   171044     if( check.rc==SQLITE_OK ) check.rc = rc;
   171045   }
   171046   *pzReport = check.zReport;
   171047   return check.rc;
   171048 }
   171049 
   171050 /*
   171051 ** Usage:
   171052 **
   171053 **   rtreecheck(<rtree-table>);
   171054 **   rtreecheck(<database>, <rtree-table>);
   171055 **
   171056 ** Invoking this SQL function runs an integrity-check on the named rtree
   171057 ** table. The integrity-check verifies the following:
   171058 **
   171059 **   1. For each cell in the r-tree structure (%_node table), that:
   171060 **
   171061 **       a) for each dimension, (coord1 <= coord2).
   171062 **
   171063 **       b) unless the cell is on the root node, that the cell is bounded
   171064 **          by the parent cell on the parent node.
   171065 **
   171066 **       c) for leaf nodes, that there is an entry in the %_rowid
   171067 **          table corresponding to the cell's rowid value that
   171068 **          points to the correct node.
   171069 **
   171070 **       d) for cells on non-leaf nodes, that there is an entry in the
   171071 **          %_parent table mapping from the cell's child node to the
   171072 **          node that it resides on.
   171073 **
   171074 **   2. That there are the same number of entries in the %_rowid table
   171075 **      as there are leaf cells in the r-tree structure, and that there
   171076 **      is a leaf cell that corresponds to each entry in the %_rowid table.
   171077 **
   171078 **   3. That there are the same number of entries in the %_parent table
   171079 **      as there are non-leaf cells in the r-tree structure, and that
   171080 **      there is a non-leaf cell that corresponds to each entry in the
   171081 **      %_parent table.
   171082 */
   171083 static void rtreecheck(
   171084   sqlite3_context *ctx,
   171085   int nArg,
   171086   sqlite3_value **apArg
   171087 ){
   171088   if( nArg!=1 && nArg!=2 ){
   171089     sqlite3_result_error(ctx,
   171090         "wrong number of arguments to function rtreecheck()", -1
   171091     );
   171092   }else{
   171093     int rc;
   171094     char *zReport = 0;
   171095     const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
   171096     const char *zTab;
   171097     if( nArg==1 ){
   171098       zTab = zDb;
   171099       zDb = "main";
   171100     }else{
   171101       zTab = (const char*)sqlite3_value_text(apArg[1]);
   171102     }
   171103     rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
   171104     if( rc==SQLITE_OK ){
   171105       sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
   171106     }else{
   171107       sqlite3_result_error_code(ctx, rc);
   171108     }
   171109     sqlite3_free(zReport);
   171110   }
   171111 }
   171112 
   171113 
   171114 /*
   171115 ** Register the r-tree module with database handle db. This creates the
   171116 ** virtual table module "rtree" and the debugging/analysis scalar
   171117 ** function "rtreenode".
   171118 */
   171119 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
   171120   const int utf8 = SQLITE_UTF8;
   171121   int rc;
   171122 
   171123   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
   171124   if( rc==SQLITE_OK ){
   171125     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
   171126   }
   171127   if( rc==SQLITE_OK ){
   171128     rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
   171129   }
   171130   if( rc==SQLITE_OK ){
   171131 #ifdef SQLITE_RTREE_INT_ONLY
   171132     void *c = (void *)RTREE_COORD_INT32;
   171133 #else
   171134     void *c = (void *)RTREE_COORD_REAL32;
   171135 #endif
   171136     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
   171137   }
   171138   if( rc==SQLITE_OK ){
   171139     void *c = (void *)RTREE_COORD_INT32;
   171140     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
   171141   }
   171142 
   171143   return rc;
   171144 }
   171145 
   171146 /*
   171147 ** This routine deletes the RtreeGeomCallback object that was attached
   171148 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
   171149 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
   171150 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
   171151 ** the corresponding SQL function is deleted.
   171152 */
   171153 static void rtreeFreeCallback(void *p){
   171154   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
   171155   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
   171156   sqlite3_free(p);
   171157 }
   171158 
   171159 /*
   171160 ** This routine frees the BLOB that is returned by geomCallback().
   171161 */
   171162 static void rtreeMatchArgFree(void *pArg){
   171163   int i;
   171164   RtreeMatchArg *p = (RtreeMatchArg*)pArg;
   171165   for(i=0; i<p->nParam; i++){
   171166     sqlite3_value_free(p->apSqlParam[i]);
   171167   }
   171168   sqlite3_free(p);
   171169 }
   171170 
   171171 /*
   171172 ** Each call to sqlite3_rtree_geometry_callback() or
   171173 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
   171174 ** scalar function that is implemented by this routine.
   171175 **
   171176 ** All this function does is construct an RtreeMatchArg object that
   171177 ** contains the geometry-checking callback routines and a list of
   171178 ** parameters to this function, then return that RtreeMatchArg object
   171179 ** as a BLOB.
   171180 **
   171181 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
   171182 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
   171183 ** out which elements of the R-Tree should be returned by the query.
   171184 */
   171185 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
   171186   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
   171187   RtreeMatchArg *pBlob;
   171188   int nBlob;
   171189   int memErr = 0;
   171190 
   171191   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
   171192            + nArg*sizeof(sqlite3_value*);
   171193   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
   171194   if( !pBlob ){
   171195     sqlite3_result_error_nomem(ctx);
   171196   }else{
   171197     int i;
   171198     pBlob->iSize = nBlob;
   171199     pBlob->cb = pGeomCtx[0];
   171200     pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
   171201     pBlob->nParam = nArg;
   171202     for(i=0; i<nArg; i++){
   171203       pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
   171204       if( pBlob->apSqlParam[i]==0 ) memErr = 1;
   171205 #ifdef SQLITE_RTREE_INT_ONLY
   171206       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
   171207 #else
   171208       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
   171209 #endif
   171210     }
   171211     if( memErr ){
   171212       sqlite3_result_error_nomem(ctx);
   171213       rtreeMatchArgFree(pBlob);
   171214     }else{
   171215       sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
   171216     }
   171217   }
   171218 }
   171219 
   171220 /*
   171221 ** Register a new geometry function for use with the r-tree MATCH operator.
   171222 */
   171223 SQLITE_API int sqlite3_rtree_geometry_callback(
   171224   sqlite3 *db,                  /* Register SQL function on this connection */
   171225   const char *zGeom,            /* Name of the new SQL function */
   171226   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
   171227   void *pContext                /* Extra data associated with the callback */
   171228 ){
   171229   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   171230 
   171231   /* Allocate and populate the context object. */
   171232   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   171233   if( !pGeomCtx ) return SQLITE_NOMEM;
   171234   pGeomCtx->xGeom = xGeom;
   171235   pGeomCtx->xQueryFunc = 0;
   171236   pGeomCtx->xDestructor = 0;
   171237   pGeomCtx->pContext = pContext;
   171238   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
   171239       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   171240   );
   171241 }
   171242 
   171243 /*
   171244 ** Register a new 2nd-generation geometry function for use with the
   171245 ** r-tree MATCH operator.
   171246 */
   171247 SQLITE_API int sqlite3_rtree_query_callback(
   171248   sqlite3 *db,                 /* Register SQL function on this connection */
   171249   const char *zQueryFunc,      /* Name of new SQL function */
   171250   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
   171251   void *pContext,              /* Extra data passed into the callback */
   171252   void (*xDestructor)(void*)   /* Destructor for the extra data */
   171253 ){
   171254   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   171255 
   171256   /* Allocate and populate the context object. */
   171257   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   171258   if( !pGeomCtx ) return SQLITE_NOMEM;
   171259   pGeomCtx->xGeom = 0;
   171260   pGeomCtx->xQueryFunc = xQueryFunc;
   171261   pGeomCtx->xDestructor = xDestructor;
   171262   pGeomCtx->pContext = pContext;
   171263   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
   171264       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   171265   );
   171266 }
   171267 
   171268 #if !SQLITE_CORE
   171269 #ifdef _WIN32
   171270 __declspec(dllexport)
   171271 #endif
   171272 SQLITE_API int sqlite3_rtree_init(
   171273   sqlite3 *db,
   171274   char **pzErrMsg,
   171275   const sqlite3_api_routines *pApi
   171276 ){
   171277   SQLITE_EXTENSION_INIT2(pApi)
   171278   return sqlite3RtreeInit(db);
   171279 }
   171280 #endif
   171281 
   171282 #endif
   171283 
   171284 /************** End of rtree.c ***********************************************/
   171285 /************** Begin file icu.c *********************************************/
   171286 /*
   171287 ** 2007 May 6
   171288 **
   171289 ** The author disclaims copyright to this source code.  In place of
   171290 ** a legal notice, here is a blessing:
   171291 **
   171292 **    May you do good and not evil.
   171293 **    May you find forgiveness for yourself and forgive others.
   171294 **    May you share freely, never taking more than you give.
   171295 **
   171296 *************************************************************************
   171297 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
   171298 **
   171299 ** This file implements an integration between the ICU library
   171300 ** ("International Components for Unicode", an open-source library
   171301 ** for handling unicode data) and SQLite. The integration uses
   171302 ** ICU to provide the following to SQLite:
   171303 **
   171304 **   * An implementation of the SQL regexp() function (and hence REGEXP
   171305 **     operator) using the ICU uregex_XX() APIs.
   171306 **
   171307 **   * Implementations of the SQL scalar upper() and lower() functions
   171308 **     for case mapping.
   171309 **
   171310 **   * Integration of ICU and SQLite collation sequences.
   171311 **
   171312 **   * An implementation of the LIKE operator that uses ICU to
   171313 **     provide case-independent matching.
   171314 */
   171315 
   171316 #if !defined(SQLITE_CORE)                  \
   171317  || defined(SQLITE_ENABLE_ICU)             \
   171318  || defined(SQLITE_ENABLE_ICU_COLLATIONS)
   171319 
   171320 /* Include ICU headers */
   171321 #include <unicode/utypes.h>
   171322 #include <unicode/uregex.h>
   171323 #include <unicode/ustring.h>
   171324 #include <unicode/ucol.h>
   171325 
   171326 /* #include <assert.h> */
   171327 
   171328 #ifndef SQLITE_CORE
   171329 /*   #include "sqlite3ext.h" */
   171330   SQLITE_EXTENSION_INIT1
   171331 #else
   171332 /*   #include "sqlite3.h" */
   171333 #endif
   171334 
   171335 /*
   171336 ** This function is called when an ICU function called from within
   171337 ** the implementation of an SQL scalar function returns an error.
   171338 **
   171339 ** The scalar function context passed as the first argument is
   171340 ** loaded with an error message based on the following two args.
   171341 */
   171342 static void icuFunctionError(
   171343   sqlite3_context *pCtx,       /* SQLite scalar function context */
   171344   const char *zName,           /* Name of ICU function that failed */
   171345   UErrorCode e                 /* Error code returned by ICU function */
   171346 ){
   171347   char zBuf[128];
   171348   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
   171349   zBuf[127] = '\0';
   171350   sqlite3_result_error(pCtx, zBuf, -1);
   171351 }
   171352 
   171353 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   171354 
   171355 /*
   171356 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   171357 ** operator.
   171358 */
   171359 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   171360 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   171361 #endif
   171362 
   171363 /*
   171364 ** Version of sqlite3_free() that is always a function, never a macro.
   171365 */
   171366 static void xFree(void *p){
   171367   sqlite3_free(p);
   171368 }
   171369 
   171370 /*
   171371 ** This lookup table is used to help decode the first byte of
   171372 ** a multi-byte UTF8 character. It is copied here from SQLite source
   171373 ** code file utf8.c.
   171374 */
   171375 static const unsigned char icuUtf8Trans1[] = {
   171376   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   171377   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   171378   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   171379   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   171380   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   171381   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   171382   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   171383   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   171384 };
   171385 
   171386 #define SQLITE_ICU_READ_UTF8(zIn, c)                       \
   171387   c = *(zIn++);                                            \
   171388   if( c>=0xc0 ){                                           \
   171389     c = icuUtf8Trans1[c-0xc0];                             \
   171390     while( (*zIn & 0xc0)==0x80 ){                          \
   171391       c = (c<<6) + (0x3f & *(zIn++));                      \
   171392     }                                                      \
   171393   }
   171394 
   171395 #define SQLITE_ICU_SKIP_UTF8(zIn)                          \
   171396   assert( *zIn );                                          \
   171397   if( *(zIn++)>=0xc0 ){                                    \
   171398     while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
   171399   }
   171400 
   171401 
   171402 /*
   171403 ** Compare two UTF-8 strings for equality where the first string is
   171404 ** a "LIKE" expression. Return true (1) if they are the same and
   171405 ** false (0) if they are different.
   171406 */
   171407 static int icuLikeCompare(
   171408   const uint8_t *zPattern,   /* LIKE pattern */
   171409   const uint8_t *zString,    /* The UTF-8 string to compare against */
   171410   const UChar32 uEsc         /* The escape character */
   171411 ){
   171412   static const uint32_t MATCH_ONE = (uint32_t)'_';
   171413   static const uint32_t MATCH_ALL = (uint32_t)'%';
   171414 
   171415   int prevEscape = 0;     /* True if the previous character was uEsc */
   171416 
   171417   while( 1 ){
   171418 
   171419     /* Read (and consume) the next character from the input pattern. */
   171420     uint32_t uPattern;
   171421     SQLITE_ICU_READ_UTF8(zPattern, uPattern);
   171422     if( uPattern==0 ) break;
   171423 
   171424     /* There are now 4 possibilities:
   171425     **
   171426     **     1. uPattern is an unescaped match-all character "%",
   171427     **     2. uPattern is an unescaped match-one character "_",
   171428     **     3. uPattern is an unescaped escape character, or
   171429     **     4. uPattern is to be handled as an ordinary character
   171430     */
   171431     if( !prevEscape && uPattern==MATCH_ALL ){
   171432       /* Case 1. */
   171433       uint8_t c;
   171434 
   171435       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
   171436       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
   171437       ** test string.
   171438       */
   171439       while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
   171440         if( c==MATCH_ONE ){
   171441           if( *zString==0 ) return 0;
   171442           SQLITE_ICU_SKIP_UTF8(zString);
   171443         }
   171444         zPattern++;
   171445       }
   171446 
   171447       if( *zPattern==0 ) return 1;
   171448 
   171449       while( *zString ){
   171450         if( icuLikeCompare(zPattern, zString, uEsc) ){
   171451           return 1;
   171452         }
   171453         SQLITE_ICU_SKIP_UTF8(zString);
   171454       }
   171455       return 0;
   171456 
   171457     }else if( !prevEscape && uPattern==MATCH_ONE ){
   171458       /* Case 2. */
   171459       if( *zString==0 ) return 0;
   171460       SQLITE_ICU_SKIP_UTF8(zString);
   171461 
   171462     }else if( !prevEscape && uPattern==(uint32_t)uEsc){
   171463       /* Case 3. */
   171464       prevEscape = 1;
   171465 
   171466     }else{
   171467       /* Case 4. */
   171468       uint32_t uString;
   171469       SQLITE_ICU_READ_UTF8(zString, uString);
   171470       uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
   171471       uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
   171472       if( uString!=uPattern ){
   171473         return 0;
   171474       }
   171475       prevEscape = 0;
   171476     }
   171477   }
   171478 
   171479   return *zString==0;
   171480 }
   171481 
   171482 /*
   171483 ** Implementation of the like() SQL function.  This function implements
   171484 ** the build-in LIKE operator.  The first argument to the function is the
   171485 ** pattern and the second argument is the string.  So, the SQL statements:
   171486 **
   171487 **       A LIKE B
   171488 **
   171489 ** is implemented as like(B, A). If there is an escape character E,
   171490 **
   171491 **       A LIKE B ESCAPE E
   171492 **
   171493 ** is mapped to like(B, A, E).
   171494 */
   171495 static void icuLikeFunc(
   171496   sqlite3_context *context,
   171497   int argc,
   171498   sqlite3_value **argv
   171499 ){
   171500   const unsigned char *zA = sqlite3_value_text(argv[0]);
   171501   const unsigned char *zB = sqlite3_value_text(argv[1]);
   171502   UChar32 uEsc = 0;
   171503 
   171504   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   171505   ** of deep recursion and N*N behavior in patternCompare().
   171506   */
   171507   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
   171508     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   171509     return;
   171510   }
   171511 
   171512 
   171513   if( argc==3 ){
   171514     /* The escape character string must consist of a single UTF-8 character.
   171515     ** Otherwise, return an error.
   171516     */
   171517     int nE= sqlite3_value_bytes(argv[2]);
   171518     const unsigned char *zE = sqlite3_value_text(argv[2]);
   171519     int i = 0;
   171520     if( zE==0 ) return;
   171521     U8_NEXT(zE, i, nE, uEsc);
   171522     if( i!=nE){
   171523       sqlite3_result_error(context,
   171524           "ESCAPE expression must be a single character", -1);
   171525       return;
   171526     }
   171527   }
   171528 
   171529   if( zA && zB ){
   171530     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
   171531   }
   171532 }
   171533 
   171534 /*
   171535 ** Function to delete compiled regexp objects. Registered as
   171536 ** a destructor function with sqlite3_set_auxdata().
   171537 */
   171538 static void icuRegexpDelete(void *p){
   171539   URegularExpression *pExpr = (URegularExpression *)p;
   171540   uregex_close(pExpr);
   171541 }
   171542 
   171543 /*
   171544 ** Implementation of SQLite REGEXP operator. This scalar function takes
   171545 ** two arguments. The first is a regular expression pattern to compile
   171546 ** the second is a string to match against that pattern. If either
   171547 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
   171548 ** is 1 if the string matches the pattern, or 0 otherwise.
   171549 **
   171550 ** SQLite maps the regexp() function to the regexp() operator such
   171551 ** that the following two are equivalent:
   171552 **
   171553 **     zString REGEXP zPattern
   171554 **     regexp(zPattern, zString)
   171555 **
   171556 ** Uses the following ICU regexp APIs:
   171557 **
   171558 **     uregex_open()
   171559 **     uregex_matches()
   171560 **     uregex_close()
   171561 */
   171562 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   171563   UErrorCode status = U_ZERO_ERROR;
   171564   URegularExpression *pExpr;
   171565   UBool res;
   171566   const UChar *zString = sqlite3_value_text16(apArg[1]);
   171567 
   171568   (void)nArg;  /* Unused parameter */
   171569 
   171570   /* If the left hand side of the regexp operator is NULL,
   171571   ** then the result is also NULL.
   171572   */
   171573   if( !zString ){
   171574     return;
   171575   }
   171576 
   171577   pExpr = sqlite3_get_auxdata(p, 0);
   171578   if( !pExpr ){
   171579     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
   171580     if( !zPattern ){
   171581       return;
   171582     }
   171583     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
   171584 
   171585     if( U_SUCCESS(status) ){
   171586       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
   171587     }else{
   171588       assert(!pExpr);
   171589       icuFunctionError(p, "uregex_open", status);
   171590       return;
   171591     }
   171592   }
   171593 
   171594   /* Configure the text that the regular expression operates on. */
   171595   uregex_setText(pExpr, zString, -1, &status);
   171596   if( !U_SUCCESS(status) ){
   171597     icuFunctionError(p, "uregex_setText", status);
   171598     return;
   171599   }
   171600 
   171601   /* Attempt the match */
   171602   res = uregex_matches(pExpr, 0, &status);
   171603   if( !U_SUCCESS(status) ){
   171604     icuFunctionError(p, "uregex_matches", status);
   171605     return;
   171606   }
   171607 
   171608   /* Set the text that the regular expression operates on to a NULL
   171609   ** pointer. This is not really necessary, but it is tidier than
   171610   ** leaving the regular expression object configured with an invalid
   171611   ** pointer after this function returns.
   171612   */
   171613   uregex_setText(pExpr, 0, 0, &status);
   171614 
   171615   /* Return 1 or 0. */
   171616   sqlite3_result_int(p, res ? 1 : 0);
   171617 }
   171618 
   171619 /*
   171620 ** Implementations of scalar functions for case mapping - upper() and
   171621 ** lower(). Function upper() converts its input to upper-case (ABC).
   171622 ** Function lower() converts to lower-case (abc).
   171623 **
   171624 ** ICU provides two types of case mapping, "general" case mapping and
   171625 ** "language specific". Refer to ICU documentation for the differences
   171626 ** between the two.
   171627 **
   171628 ** To utilise "general" case mapping, the upper() or lower() scalar
   171629 ** functions are invoked with one argument:
   171630 **
   171631 **     upper('ABC') -> 'abc'
   171632 **     lower('abc') -> 'ABC'
   171633 **
   171634 ** To access ICU "language specific" case mapping, upper() or lower()
   171635 ** should be invoked with two arguments. The second argument is the name
   171636 ** of the locale to use. Passing an empty string ("") or SQL NULL value
   171637 ** as the second argument is the same as invoking the 1 argument version
   171638 ** of upper() or lower().
   171639 **
   171640 **     lower('I', 'en_us') -> 'i'
   171641 **     lower('I', 'tr_tr') -> '\u131' (small dotless i)
   171642 **
   171643 ** http://www.icu-project.org/userguide/posix.html#case_mappings
   171644 */
   171645 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   171646   const UChar *zInput;            /* Pointer to input string */
   171647   UChar *zOutput = 0;             /* Pointer to output buffer */
   171648   int nInput;                     /* Size of utf-16 input string in bytes */
   171649   int nOut;                       /* Size of output buffer in bytes */
   171650   int cnt;
   171651   int bToUpper;                   /* True for toupper(), false for tolower() */
   171652   UErrorCode status;
   171653   const char *zLocale = 0;
   171654 
   171655   assert(nArg==1 || nArg==2);
   171656   bToUpper = (sqlite3_user_data(p)!=0);
   171657   if( nArg==2 ){
   171658     zLocale = (const char *)sqlite3_value_text(apArg[1]);
   171659   }
   171660 
   171661   zInput = sqlite3_value_text16(apArg[0]);
   171662   if( !zInput ){
   171663     return;
   171664   }
   171665   nOut = nInput = sqlite3_value_bytes16(apArg[0]);
   171666   if( nOut==0 ){
   171667     sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
   171668     return;
   171669   }
   171670 
   171671   for(cnt=0; cnt<2; cnt++){
   171672     UChar *zNew = sqlite3_realloc(zOutput, nOut);
   171673     if( zNew==0 ){
   171674       sqlite3_free(zOutput);
   171675       sqlite3_result_error_nomem(p);
   171676       return;
   171677     }
   171678     zOutput = zNew;
   171679     status = U_ZERO_ERROR;
   171680     if( bToUpper ){
   171681       nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
   171682     }else{
   171683       nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
   171684     }
   171685 
   171686     if( U_SUCCESS(status) ){
   171687       sqlite3_result_text16(p, zOutput, nOut, xFree);
   171688     }else if( status==U_BUFFER_OVERFLOW_ERROR ){
   171689       assert( cnt==0 );
   171690       continue;
   171691     }else{
   171692       icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
   171693     }
   171694     return;
   171695   }
   171696   assert( 0 );     /* Unreachable */
   171697 }
   171698 
   171699 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
   171700 
   171701 /*
   171702 ** Collation sequence destructor function. The pCtx argument points to
   171703 ** a UCollator structure previously allocated using ucol_open().
   171704 */
   171705 static void icuCollationDel(void *pCtx){
   171706   UCollator *p = (UCollator *)pCtx;
   171707   ucol_close(p);
   171708 }
   171709 
   171710 /*
   171711 ** Collation sequence comparison function. The pCtx argument points to
   171712 ** a UCollator structure previously allocated using ucol_open().
   171713 */
   171714 static int icuCollationColl(
   171715   void *pCtx,
   171716   int nLeft,
   171717   const void *zLeft,
   171718   int nRight,
   171719   const void *zRight
   171720 ){
   171721   UCollationResult res;
   171722   UCollator *p = (UCollator *)pCtx;
   171723   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
   171724   switch( res ){
   171725     case UCOL_LESS:    return -1;
   171726     case UCOL_GREATER: return +1;
   171727     case UCOL_EQUAL:   return 0;
   171728   }
   171729   assert(!"Unexpected return value from ucol_strcoll()");
   171730   return 0;
   171731 }
   171732 
   171733 /*
   171734 ** Implementation of the scalar function icu_load_collation().
   171735 **
   171736 ** This scalar function is used to add ICU collation based collation
   171737 ** types to an SQLite database connection. It is intended to be called
   171738 ** as follows:
   171739 **
   171740 **     SELECT icu_load_collation(<locale>, <collation-name>);
   171741 **
   171742 ** Where <locale> is a string containing an ICU locale identifier (i.e.
   171743 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
   171744 ** collation sequence to create.
   171745 */
   171746 static void icuLoadCollation(
   171747   sqlite3_context *p,
   171748   int nArg,
   171749   sqlite3_value **apArg
   171750 ){
   171751   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
   171752   UErrorCode status = U_ZERO_ERROR;
   171753   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
   171754   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
   171755   UCollator *pUCollator;    /* ICU library collation object */
   171756   int rc;                   /* Return code from sqlite3_create_collation_x() */
   171757 
   171758   assert(nArg==2);
   171759   (void)nArg; /* Unused parameter */
   171760   zLocale = (const char *)sqlite3_value_text(apArg[0]);
   171761   zName = (const char *)sqlite3_value_text(apArg[1]);
   171762 
   171763   if( !zLocale || !zName ){
   171764     return;
   171765   }
   171766 
   171767   pUCollator = ucol_open(zLocale, &status);
   171768   if( !U_SUCCESS(status) ){
   171769     icuFunctionError(p, "ucol_open", status);
   171770     return;
   171771   }
   171772   assert(p);
   171773 
   171774   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
   171775       icuCollationColl, icuCollationDel
   171776   );
   171777   if( rc!=SQLITE_OK ){
   171778     ucol_close(pUCollator);
   171779     sqlite3_result_error(p, "Error registering collation function", -1);
   171780   }
   171781 }
   171782 
   171783 /*
   171784 ** Register the ICU extension functions with database db.
   171785 */
   171786 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
   171787   static const struct IcuScalar {
   171788     const char *zName;                        /* Function name */
   171789     unsigned char nArg;                       /* Number of arguments */
   171790     unsigned short enc;                       /* Optimal text encoding */
   171791     unsigned char iContext;                   /* sqlite3_user_data() context */
   171792     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   171793   } scalars[] = {
   171794     {"icu_load_collation",  2, SQLITE_UTF8,                1, icuLoadCollation},
   171795 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   171796     {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC,         0, icuRegexpFunc},
   171797     {"lower",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
   171798     {"lower",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
   171799     {"upper",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
   171800     {"upper",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
   171801     {"lower",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
   171802     {"lower",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
   171803     {"upper",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
   171804     {"upper",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
   171805     {"like",   2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
   171806     {"like",   3, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
   171807 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
   171808   };
   171809   int rc = SQLITE_OK;
   171810   int i;
   171811 
   171812   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
   171813     const struct IcuScalar *p = &scalars[i];
   171814     rc = sqlite3_create_function(
   171815         db, p->zName, p->nArg, p->enc,
   171816         p->iContext ? (void*)db : (void*)0,
   171817         p->xFunc, 0, 0
   171818     );
   171819   }
   171820 
   171821   return rc;
   171822 }
   171823 
   171824 #if !SQLITE_CORE
   171825 #ifdef _WIN32
   171826 __declspec(dllexport)
   171827 #endif
   171828 SQLITE_API int sqlite3_icu_init(
   171829   sqlite3 *db,
   171830   char **pzErrMsg,
   171831   const sqlite3_api_routines *pApi
   171832 ){
   171833   SQLITE_EXTENSION_INIT2(pApi)
   171834   return sqlite3IcuInit(db);
   171835 }
   171836 #endif
   171837 
   171838 #endif
   171839 
   171840 /************** End of icu.c *************************************************/
   171841 /************** Begin file fts3_icu.c ****************************************/
   171842 /*
   171843 ** 2007 June 22
   171844 **
   171845 ** The author disclaims copyright to this source code.  In place of
   171846 ** a legal notice, here is a blessing:
   171847 **
   171848 **    May you do good and not evil.
   171849 **    May you find forgiveness for yourself and forgive others.
   171850 **    May you share freely, never taking more than you give.
   171851 **
   171852 *************************************************************************
   171853 ** This file implements a tokenizer for fts3 based on the ICU library.
   171854 */
   171855 /* #include "fts3Int.h" */
   171856 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   171857 #ifdef SQLITE_ENABLE_ICU
   171858 
   171859 /* #include <assert.h> */
   171860 /* #include <string.h> */
   171861 /* #include "fts3_tokenizer.h" */
   171862 
   171863 #include <unicode/ubrk.h>
   171864 /* #include <unicode/ucol.h> */
   171865 /* #include <unicode/ustring.h> */
   171866 #include <unicode/utf16.h>
   171867 
   171868 typedef struct IcuTokenizer IcuTokenizer;
   171869 typedef struct IcuCursor IcuCursor;
   171870 
   171871 struct IcuTokenizer {
   171872   sqlite3_tokenizer base;
   171873   char *zLocale;
   171874 };
   171875 
   171876 struct IcuCursor {
   171877   sqlite3_tokenizer_cursor base;
   171878 
   171879   UBreakIterator *pIter;      /* ICU break-iterator object */
   171880   int nChar;                  /* Number of UChar elements in pInput */
   171881   UChar *aChar;               /* Copy of input using utf-16 encoding */
   171882   int *aOffset;               /* Offsets of each character in utf-8 input */
   171883 
   171884   int nBuffer;
   171885   char *zBuffer;
   171886 
   171887   int iToken;
   171888 };
   171889 
   171890 /*
   171891 ** Create a new tokenizer instance.
   171892 */
   171893 static int icuCreate(
   171894   int argc,                            /* Number of entries in argv[] */
   171895   const char * const *argv,            /* Tokenizer creation arguments */
   171896   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
   171897 ){
   171898   IcuTokenizer *p;
   171899   int n = 0;
   171900 
   171901   if( argc>0 ){
   171902     n = strlen(argv[0])+1;
   171903   }
   171904   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
   171905   if( !p ){
   171906     return SQLITE_NOMEM;
   171907   }
   171908   memset(p, 0, sizeof(IcuTokenizer));
   171909 
   171910   if( n ){
   171911     p->zLocale = (char *)&p[1];
   171912     memcpy(p->zLocale, argv[0], n);
   171913   }
   171914 
   171915   *ppTokenizer = (sqlite3_tokenizer *)p;
   171916 
   171917   return SQLITE_OK;
   171918 }
   171919 
   171920 /*
   171921 ** Destroy a tokenizer
   171922 */
   171923 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
   171924   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   171925   sqlite3_free(p);
   171926   return SQLITE_OK;
   171927 }
   171928 
   171929 /*
   171930 ** Prepare to begin tokenizing a particular string.  The input
   171931 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   171932 ** used to incrementally tokenize this string is returned in
   171933 ** *ppCursor.
   171934 */
   171935 static int icuOpen(
   171936   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   171937   const char *zInput,                    /* Input string */
   171938   int nInput,                            /* Length of zInput in bytes */
   171939   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   171940 ){
   171941   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   171942   IcuCursor *pCsr;
   171943 
   171944   const int32_t opt = U_FOLD_CASE_DEFAULT;
   171945   UErrorCode status = U_ZERO_ERROR;
   171946   int nChar;
   171947 
   171948   UChar32 c;
   171949   int iInput = 0;
   171950   int iOut = 0;
   171951 
   171952   *ppCursor = 0;
   171953 
   171954   if( zInput==0 ){
   171955     nInput = 0;
   171956     zInput = "";
   171957   }else if( nInput<0 ){
   171958     nInput = strlen(zInput);
   171959   }
   171960   nChar = nInput+1;
   171961   pCsr = (IcuCursor *)sqlite3_malloc(
   171962       sizeof(IcuCursor) +                /* IcuCursor */
   171963       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
   171964       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
   171965   );
   171966   if( !pCsr ){
   171967     return SQLITE_NOMEM;
   171968   }
   171969   memset(pCsr, 0, sizeof(IcuCursor));
   171970   pCsr->aChar = (UChar *)&pCsr[1];
   171971   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
   171972 
   171973   pCsr->aOffset[iOut] = iInput;
   171974   U8_NEXT(zInput, iInput, nInput, c);
   171975   while( c>0 ){
   171976     int isError = 0;
   171977     c = u_foldCase(c, opt);
   171978     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
   171979     if( isError ){
   171980       sqlite3_free(pCsr);
   171981       return SQLITE_ERROR;
   171982     }
   171983     pCsr->aOffset[iOut] = iInput;
   171984 
   171985     if( iInput<nInput ){
   171986       U8_NEXT(zInput, iInput, nInput, c);
   171987     }else{
   171988       c = 0;
   171989     }
   171990   }
   171991 
   171992   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
   171993   if( !U_SUCCESS(status) ){
   171994     sqlite3_free(pCsr);
   171995     return SQLITE_ERROR;
   171996   }
   171997   pCsr->nChar = iOut;
   171998 
   171999   ubrk_first(pCsr->pIter);
   172000   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
   172001   return SQLITE_OK;
   172002 }
   172003 
   172004 /*
   172005 ** Close a tokenization cursor previously opened by a call to icuOpen().
   172006 */
   172007 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
   172008   IcuCursor *pCsr = (IcuCursor *)pCursor;
   172009   ubrk_close(pCsr->pIter);
   172010   sqlite3_free(pCsr->zBuffer);
   172011   sqlite3_free(pCsr);
   172012   return SQLITE_OK;
   172013 }
   172014 
   172015 /*
   172016 ** Extract the next token from a tokenization cursor.
   172017 */
   172018 static int icuNext(
   172019   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   172020   const char **ppToken,               /* OUT: *ppToken is the token text */
   172021   int *pnBytes,                       /* OUT: Number of bytes in token */
   172022   int *piStartOffset,                 /* OUT: Starting offset of token */
   172023   int *piEndOffset,                   /* OUT: Ending offset of token */
   172024   int *piPosition                     /* OUT: Position integer of token */
   172025 ){
   172026   IcuCursor *pCsr = (IcuCursor *)pCursor;
   172027 
   172028   int iStart = 0;
   172029   int iEnd = 0;
   172030   int nByte = 0;
   172031 
   172032   while( iStart==iEnd ){
   172033     UChar32 c;
   172034 
   172035     iStart = ubrk_current(pCsr->pIter);
   172036     iEnd = ubrk_next(pCsr->pIter);
   172037     if( iEnd==UBRK_DONE ){
   172038       return SQLITE_DONE;
   172039     }
   172040 
   172041     while( iStart<iEnd ){
   172042       int iWhite = iStart;
   172043       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
   172044       if( u_isspace(c) ){
   172045         iStart = iWhite;
   172046       }else{
   172047         break;
   172048       }
   172049     }
   172050     assert(iStart<=iEnd);
   172051   }
   172052 
   172053   do {
   172054     UErrorCode status = U_ZERO_ERROR;
   172055     if( nByte ){
   172056       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
   172057       if( !zNew ){
   172058         return SQLITE_NOMEM;
   172059       }
   172060       pCsr->zBuffer = zNew;
   172061       pCsr->nBuffer = nByte;
   172062     }
   172063 
   172064     u_strToUTF8(
   172065         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
   172066         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
   172067         &status                                  /* Output success/failure */
   172068     );
   172069   } while( nByte>pCsr->nBuffer );
   172070 
   172071   *ppToken = pCsr->zBuffer;
   172072   *pnBytes = nByte;
   172073   *piStartOffset = pCsr->aOffset[iStart];
   172074   *piEndOffset = pCsr->aOffset[iEnd];
   172075   *piPosition = pCsr->iToken++;
   172076 
   172077   return SQLITE_OK;
   172078 }
   172079 
   172080 /*
   172081 ** The set of routines that implement the simple tokenizer
   172082 */
   172083 static const sqlite3_tokenizer_module icuTokenizerModule = {
   172084   0,                           /* iVersion    */
   172085   icuCreate,                   /* xCreate     */
   172086   icuDestroy,                  /* xCreate     */
   172087   icuOpen,                     /* xOpen       */
   172088   icuClose,                    /* xClose      */
   172089   icuNext,                     /* xNext       */
   172090   0,                           /* xLanguageid */
   172091 };
   172092 
   172093 /*
   172094 ** Set *ppModule to point at the implementation of the ICU tokenizer.
   172095 */
   172096 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
   172097   sqlite3_tokenizer_module const**ppModule
   172098 ){
   172099   *ppModule = &icuTokenizerModule;
   172100 }
   172101 
   172102 #endif /* defined(SQLITE_ENABLE_ICU) */
   172103 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   172104 
   172105 /************** End of fts3_icu.c ********************************************/
   172106 /************** Begin file sqlite3rbu.c **************************************/
   172107 /*
   172108 ** 2014 August 30
   172109 **
   172110 ** The author disclaims copyright to this source code.  In place of
   172111 ** a legal notice, here is a blessing:
   172112 **
   172113 **    May you do good and not evil.
   172114 **    May you find forgiveness for yourself and forgive others.
   172115 **    May you share freely, never taking more than you give.
   172116 **
   172117 *************************************************************************
   172118 **
   172119 **
   172120 ** OVERVIEW
   172121 **
   172122 **  The RBU extension requires that the RBU update be packaged as an
   172123 **  SQLite database. The tables it expects to find are described in
   172124 **  sqlite3rbu.h.  Essentially, for each table xyz in the target database
   172125 **  that the user wishes to write to, a corresponding data_xyz table is
   172126 **  created in the RBU database and populated with one row for each row to
   172127 **  update, insert or delete from the target table.
   172128 **
   172129 **  The update proceeds in three stages:
   172130 **
   172131 **  1) The database is updated. The modified database pages are written
   172132 **     to a *-oal file. A *-oal file is just like a *-wal file, except
   172133 **     that it is named "<database>-oal" instead of "<database>-wal".
   172134 **     Because regular SQLite clients do not look for file named
   172135 **     "<database>-oal", they go on using the original database in
   172136 **     rollback mode while the *-oal file is being generated.
   172137 **
   172138 **     During this stage RBU does not update the database by writing
   172139 **     directly to the target tables. Instead it creates "imposter"
   172140 **     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
   172141 **     to update each b-tree individually. All updates required by each
   172142 **     b-tree are completed before moving on to the next, and all
   172143 **     updates are done in sorted key order.
   172144 **
   172145 **  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
   172146 **     location using a call to rename(2). Before doing this the RBU
   172147 **     module takes an EXCLUSIVE lock on the database file, ensuring
   172148 **     that there are no other active readers.
   172149 **
   172150 **     Once the EXCLUSIVE lock is released, any other database readers
   172151 **     detect the new *-wal file and read the database in wal mode. At
   172152 **     this point they see the new version of the database - including
   172153 **     the updates made as part of the RBU update.
   172154 **
   172155 **  3) The new *-wal file is checkpointed. This proceeds in the same way
   172156 **     as a regular database checkpoint, except that a single frame is
   172157 **     checkpointed each time sqlite3rbu_step() is called. If the RBU
   172158 **     handle is closed before the entire *-wal file is checkpointed,
   172159 **     the checkpoint progress is saved in the RBU database and the
   172160 **     checkpoint can be resumed by another RBU client at some point in
   172161 **     the future.
   172162 **
   172163 ** POTENTIAL PROBLEMS
   172164 **
   172165 **  The rename() call might not be portable. And RBU is not currently
   172166 **  syncing the directory after renaming the file.
   172167 **
   172168 **  When state is saved, any commit to the *-oal file and the commit to
   172169 **  the RBU update database are not atomic. So if the power fails at the
   172170 **  wrong moment they might get out of sync. As the main database will be
   172171 **  committed before the RBU update database this will likely either just
   172172 **  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
   172173 **  constraint violations).
   172174 **
   172175 **  If some client does modify the target database mid RBU update, or some
   172176 **  other error occurs, the RBU extension will keep throwing errors. It's
   172177 **  not really clear how to get out of this state. The system could just
   172178 **  by delete the RBU update database and *-oal file and have the device
   172179 **  download the update again and start over.
   172180 **
   172181 **  At present, for an UPDATE, both the new.* and old.* records are
   172182 **  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
   172183 **  fields are collected.  This means we're probably writing a lot more
   172184 **  data to disk when saving the state of an ongoing update to the RBU
   172185 **  update database than is strictly necessary.
   172186 **
   172187 */
   172188 
   172189 /* #include <assert.h> */
   172190 /* #include <string.h> */
   172191 /* #include <stdio.h> */
   172192 
   172193 /* #include "sqlite3.h" */
   172194 
   172195 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
   172196 /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
   172197 /************** Begin file sqlite3rbu.h **************************************/
   172198 /*
   172199 ** 2014 August 30
   172200 **
   172201 ** The author disclaims copyright to this source code.  In place of
   172202 ** a legal notice, here is a blessing:
   172203 **
   172204 **    May you do good and not evil.
   172205 **    May you find forgiveness for yourself and forgive others.
   172206 **    May you share freely, never taking more than you give.
   172207 **
   172208 *************************************************************************
   172209 **
   172210 ** This file contains the public interface for the RBU extension.
   172211 */
   172212 
   172213 /*
   172214 ** SUMMARY
   172215 **
   172216 ** Writing a transaction containing a large number of operations on
   172217 ** b-tree indexes that are collectively larger than the available cache
   172218 ** memory can be very inefficient.
   172219 **
   172220 ** The problem is that in order to update a b-tree, the leaf page (at least)
   172221 ** containing the entry being inserted or deleted must be modified. If the
   172222 ** working set of leaves is larger than the available cache memory, then a
   172223 ** single leaf that is modified more than once as part of the transaction
   172224 ** may be loaded from or written to the persistent media multiple times.
   172225 ** Additionally, because the index updates are likely to be applied in
   172226 ** random order, access to pages within the database is also likely to be in
   172227 ** random order, which is itself quite inefficient.
   172228 **
   172229 ** One way to improve the situation is to sort the operations on each index
   172230 ** by index key before applying them to the b-tree. This leads to an IO
   172231 ** pattern that resembles a single linear scan through the index b-tree,
   172232 ** and all but guarantees each modified leaf page is loaded and stored
   172233 ** exactly once. SQLite uses this trick to improve the performance of
   172234 ** CREATE INDEX commands. This extension allows it to be used to improve
   172235 ** the performance of large transactions on existing databases.
   172236 **
   172237 ** Additionally, this extension allows the work involved in writing the
   172238 ** large transaction to be broken down into sub-transactions performed
   172239 ** sequentially by separate processes. This is useful if the system cannot
   172240 ** guarantee that a single update process will run for long enough to apply
   172241 ** the entire update, for example because the update is being applied on a
   172242 ** mobile device that is frequently rebooted. Even after the writer process
   172243 ** has committed one or more sub-transactions, other database clients continue
   172244 ** to read from the original database snapshot. In other words, partially
   172245 ** applied transactions are not visible to other clients.
   172246 **
   172247 ** "RBU" stands for "Resumable Bulk Update". As in a large database update
   172248 ** transmitted via a wireless network to a mobile device. A transaction
   172249 ** applied using this extension is hence refered to as an "RBU update".
   172250 **
   172251 **
   172252 ** LIMITATIONS
   172253 **
   172254 ** An "RBU update" transaction is subject to the following limitations:
   172255 **
   172256 **   * The transaction must consist of INSERT, UPDATE and DELETE operations
   172257 **     only.
   172258 **
   172259 **   * INSERT statements may not use any default values.
   172260 **
   172261 **   * UPDATE and DELETE statements must identify their target rows by
   172262 **     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
   172263 **     KEY fields may not be updated or deleted. If the table being written
   172264 **     has no PRIMARY KEY, affected rows must be identified by rowid.
   172265 **
   172266 **   * UPDATE statements may not modify PRIMARY KEY columns.
   172267 **
   172268 **   * No triggers will be fired.
   172269 **
   172270 **   * No foreign key violations are detected or reported.
   172271 **
   172272 **   * CHECK constraints are not enforced.
   172273 **
   172274 **   * No constraint handling mode except for "OR ROLLBACK" is supported.
   172275 **
   172276 **
   172277 ** PREPARATION
   172278 **
   172279 ** An "RBU update" is stored as a separate SQLite database. A database
   172280 ** containing an RBU update is an "RBU database". For each table in the
   172281 ** target database to be updated, the RBU database should contain a table
   172282 ** named "data_<target name>" containing the same set of columns as the
   172283 ** target table, and one more - "rbu_control". The data_% table should
   172284 ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
   172285 ** the same type as the corresponding column in the target database.
   172286 ** The "rbu_control" column should have no type at all. For example, if
   172287 ** the target database contains:
   172288 **
   172289 **   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
   172290 **
   172291 ** Then the RBU database should contain:
   172292 **
   172293 **   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
   172294 **
   172295 ** The order of the columns in the data_% table does not matter.
   172296 **
   172297 ** Instead of a regular table, the RBU database may also contain virtual
   172298 ** tables or view named using the data_<target> naming scheme.
   172299 **
   172300 ** Instead of the plain data_<target> naming scheme, RBU database tables
   172301 ** may also be named data<integer>_<target>, where <integer> is any sequence
   172302 ** of zero or more numeric characters (0-9). This can be significant because
   172303 ** tables within the RBU database are always processed in order sorted by
   172304 ** name. By judicious selection of the <integer> portion of the names
   172305 ** of the RBU tables the user can therefore control the order in which they
   172306 ** are processed. This can be useful, for example, to ensure that "external
   172307 ** content" FTS4 tables are updated before their underlying content tables.
   172308 **
   172309 ** If the target database table is a virtual table or a table that has no
   172310 ** PRIMARY KEY declaration, the data_% table must also contain a column
   172311 ** named "rbu_rowid". This column is mapped to the tables implicit primary
   172312 ** key column - "rowid". Virtual tables for which the "rowid" column does
   172313 ** not function like a primary key value cannot be updated using RBU. For
   172314 ** example, if the target db contains either of the following:
   172315 **
   172316 **   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
   172317 **   CREATE TABLE x1(a, b)
   172318 **
   172319 ** then the RBU database should contain:
   172320 **
   172321 **   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
   172322 **
   172323 ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
   172324 ** target table must be present in the input table. For virtual tables,
   172325 ** hidden columns are optional - they are updated by RBU if present in
   172326 ** the input table, or not otherwise. For example, to write to an fts4
   172327 ** table with a hidden languageid column such as:
   172328 **
   172329 **   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
   172330 **
   172331 ** Either of the following input table schemas may be used:
   172332 **
   172333 **   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
   172334 **   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
   172335 **
   172336 ** For each row to INSERT into the target database as part of the RBU
   172337 ** update, the corresponding data_% table should contain a single record
   172338 ** with the "rbu_control" column set to contain integer value 0. The
   172339 ** other columns should be set to the values that make up the new record
   172340 ** to insert.
   172341 **
   172342 ** If the target database table has an INTEGER PRIMARY KEY, it is not
   172343 ** possible to insert a NULL value into the IPK column. Attempting to
   172344 ** do so results in an SQLITE_MISMATCH error.
   172345 **
   172346 ** For each row to DELETE from the target database as part of the RBU
   172347 ** update, the corresponding data_% table should contain a single record
   172348 ** with the "rbu_control" column set to contain integer value 1. The
   172349 ** real primary key values of the row to delete should be stored in the
   172350 ** corresponding columns of the data_% table. The values stored in the
   172351 ** other columns are not used.
   172352 **
   172353 ** For each row to UPDATE from the target database as part of the RBU
   172354 ** update, the corresponding data_% table should contain a single record
   172355 ** with the "rbu_control" column set to contain a value of type text.
   172356 ** The real primary key values identifying the row to update should be
   172357 ** stored in the corresponding columns of the data_% table row, as should
   172358 ** the new values of all columns being update. The text value in the
   172359 ** "rbu_control" column must contain the same number of characters as
   172360 ** there are columns in the target database table, and must consist entirely
   172361 ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
   172362 ** each column that is being updated, the corresponding character is set to
   172363 ** 'x'. For those that remain as they are, the corresponding character of the
   172364 ** rbu_control value should be set to '.'. For example, given the tables
   172365 ** above, the update statement:
   172366 **
   172367 **   UPDATE t1 SET c = 'usa' WHERE a = 4;
   172368 **
   172369 ** is represented by the data_t1 row created by:
   172370 **
   172371 **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
   172372 **
   172373 ** Instead of an 'x' character, characters of the rbu_control value specified
   172374 ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
   172375 ** target table with the value stored in the corresponding data_% column, the
   172376 ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
   172377 ** the target table column. rbu_delta() is invoked with two arguments - the
   172378 ** original value currently stored in the target table column and the
   172379 ** value specified in the data_xxx table.
   172380 **
   172381 ** For example, this row:
   172382 **
   172383 **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
   172384 **
   172385 ** is similar to an UPDATE statement such as:
   172386 **
   172387 **   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
   172388 **
   172389 ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
   172390 ** ota_control string, the contents of the data_xxx table column is assumed
   172391 ** to be a "fossil delta" - a patch to be applied to a blob value in the
   172392 ** format used by the fossil source-code management system. In this case
   172393 ** the existing value within the target database table must be of type BLOB.
   172394 ** It is replaced by the result of applying the specified fossil delta to
   172395 ** itself.
   172396 **
   172397 ** If the target database table is a virtual table or a table with no PRIMARY
   172398 ** KEY, the rbu_control value should not include a character corresponding
   172399 ** to the rbu_rowid value. For example, this:
   172400 **
   172401 **   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
   172402 **       VALUES(NULL, 'usa', 12, '.x');
   172403 **
   172404 ** causes a result similar to:
   172405 **
   172406 **   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
   172407 **
   172408 ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
   172409 ** However, RBU is more efficient if reading the rows in from each data_xxx
   172410 ** table in "rowid" order is roughly the same as reading them sorted by
   172411 ** the PRIMARY KEY of the corresponding target database table. In other
   172412 ** words, rows should be sorted using the destination table PRIMARY KEY
   172413 ** fields before they are inserted into the data_xxx tables.
   172414 **
   172415 ** USAGE
   172416 **
   172417 ** The API declared below allows an application to apply an RBU update
   172418 ** stored on disk to an existing target database. Essentially, the
   172419 ** application:
   172420 **
   172421 **     1) Opens an RBU handle using the sqlite3rbu_open() function.
   172422 **
   172423 **     2) Registers any required virtual table modules with the database
   172424 **        handle returned by sqlite3rbu_db(). Also, if required, register
   172425 **        the rbu_delta() implementation.
   172426 **
   172427 **     3) Calls the sqlite3rbu_step() function one or more times on
   172428 **        the new handle. Each call to sqlite3rbu_step() performs a single
   172429 **        b-tree operation, so thousands of calls may be required to apply
   172430 **        a complete update.
   172431 **
   172432 **     4) Calls sqlite3rbu_close() to close the RBU update handle. If
   172433 **        sqlite3rbu_step() has been called enough times to completely
   172434 **        apply the update to the target database, then the RBU database
   172435 **        is marked as fully applied. Otherwise, the state of the RBU
   172436 **        update application is saved in the RBU database for later
   172437 **        resumption.
   172438 **
   172439 ** See comments below for more detail on APIs.
   172440 **
   172441 ** If an update is only partially applied to the target database by the
   172442 ** time sqlite3rbu_close() is called, various state information is saved
   172443 ** within the RBU database. This allows subsequent processes to automatically
   172444 ** resume the RBU update from where it left off.
   172445 **
   172446 ** To remove all RBU extension state information, returning an RBU database
   172447 ** to its original contents, it is sufficient to drop all tables that begin
   172448 ** with the prefix "rbu_"
   172449 **
   172450 ** DATABASE LOCKING
   172451 **
   172452 ** An RBU update may not be applied to a database in WAL mode. Attempting
   172453 ** to do so is an error (SQLITE_ERROR).
   172454 **
   172455 ** While an RBU handle is open, a SHARED lock may be held on the target
   172456 ** database file. This means it is possible for other clients to read the
   172457 ** database, but not to write it.
   172458 **
   172459 ** If an RBU update is started and then suspended before it is completed,
   172460 ** then an external client writes to the database, then attempting to resume
   172461 ** the suspended RBU update is also an error (SQLITE_BUSY).
   172462 */
   172463 
   172464 #ifndef _SQLITE3RBU_H
   172465 #define _SQLITE3RBU_H
   172466 
   172467 /* #include "sqlite3.h"              ** Required for error code definitions ** */
   172468 
   172469 #if 0
   172470 extern "C" {
   172471 #endif
   172472 
   172473 typedef struct sqlite3rbu sqlite3rbu;
   172474 
   172475 /*
   172476 ** Open an RBU handle.
   172477 **
   172478 ** Argument zTarget is the path to the target database. Argument zRbu is
   172479 ** the path to the RBU database. Each call to this function must be matched
   172480 ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
   172481 ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
   172482 ** or zRbu begin with "file:", it will be interpreted as an SQLite
   172483 ** database URI, not a regular file name.
   172484 **
   172485 ** If the zState argument is passed a NULL value, the RBU extension stores
   172486 ** the current state of the update (how many rows have been updated, which
   172487 ** indexes are yet to be updated etc.) within the RBU database itself. This
   172488 ** can be convenient, as it means that the RBU application does not need to
   172489 ** organize removing a separate state file after the update is concluded.
   172490 ** Or, if zState is non-NULL, it must be a path to a database file in which
   172491 ** the RBU extension can store the state of the update.
   172492 **
   172493 ** When resuming an RBU update, the zState argument must be passed the same
   172494 ** value as when the RBU update was started.
   172495 **
   172496 ** Once the RBU update is finished, the RBU extension does not
   172497 ** automatically remove any zState database file, even if it created it.
   172498 **
   172499 ** By default, RBU uses the default VFS to access the files on disk. To
   172500 ** use a VFS other than the default, an SQLite "file:" URI containing a
   172501 ** "vfs=..." option may be passed as the zTarget option.
   172502 **
   172503 ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
   172504 ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
   172505 ** not work out of the box with zipvfs. Refer to the comment describing
   172506 ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
   172507 */
   172508 SQLITE_API sqlite3rbu *sqlite3rbu_open(
   172509   const char *zTarget,
   172510   const char *zRbu,
   172511   const char *zState
   172512 );
   172513 
   172514 /*
   172515 ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
   172516 ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
   172517 ** that it can be suspended and resumed like an RBU update.
   172518 **
   172519 ** The second argument to this function identifies a database in which
   172520 ** to store the state of the RBU vacuum operation if it is suspended. The
   172521 ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
   172522 ** operation, the state database should either not exist or be empty
   172523 ** (contain no tables). If an RBU vacuum is suspended by calling
   172524 ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
   172525 ** returned SQLITE_DONE, the vacuum state is stored in the state database.
   172526 ** The vacuum can be resumed by calling this function to open a new RBU
   172527 ** handle specifying the same target and state databases.
   172528 **
   172529 ** If the second argument passed to this function is NULL, then the
   172530 ** name of the state database is "<database>-vacuum", where <database>
   172531 ** is the name of the target database file. In this case, on UNIX, if the
   172532 ** state database is not already present in the file-system, it is created
   172533 ** with the same permissions as the target db is made.
   172534 **
   172535 ** This function does not delete the state database after an RBU vacuum
   172536 ** is completed, even if it created it. However, if the call to
   172537 ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
   172538 ** of the state tables within the state database are zeroed. This way,
   172539 ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
   172540 ** new RBU vacuum operation.
   172541 **
   172542 ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
   172543 ** describing the sqlite3rbu_create_vfs() API function below for
   172544 ** a description of the complications associated with using RBU with
   172545 ** zipvfs databases.
   172546 */
   172547 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
   172548   const char *zTarget,
   172549   const char *zState
   172550 );
   172551 
   172552 /*
   172553 ** Configure a limit for the amount of temp space that may be used by
   172554 ** the RBU handle passed as the first argument. The new limit is specified
   172555 ** in bytes by the second parameter. If it is positive, the limit is updated.
   172556 ** If the second parameter to this function is passed zero, then the limit
   172557 ** is removed entirely. If the second parameter is negative, the limit is
   172558 ** not modified (this is useful for querying the current limit).
   172559 **
   172560 ** In all cases the returned value is the current limit in bytes (zero
   172561 ** indicates unlimited).
   172562 **
   172563 ** If the temp space limit is exceeded during operation, an SQLITE_FULL
   172564 ** error is returned.
   172565 */
   172566 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
   172567 
   172568 /*
   172569 ** Return the current amount of temp file space, in bytes, currently used by
   172570 ** the RBU handle passed as the only argument.
   172571 */
   172572 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
   172573 
   172574 /*
   172575 ** Internally, each RBU connection uses a separate SQLite database
   172576 ** connection to access the target and rbu update databases. This
   172577 ** API allows the application direct access to these database handles.
   172578 **
   172579 ** The first argument passed to this function must be a valid, open, RBU
   172580 ** handle. The second argument should be passed zero to access the target
   172581 ** database handle, or non-zero to access the rbu update database handle.
   172582 ** Accessing the underlying database handles may be useful in the
   172583 ** following scenarios:
   172584 **
   172585 **   * If any target tables are virtual tables, it may be necessary to
   172586 **     call sqlite3_create_module() on the target database handle to
   172587 **     register the required virtual table implementations.
   172588 **
   172589 **   * If the data_xxx tables in the RBU source database are virtual
   172590 **     tables, the application may need to call sqlite3_create_module() on
   172591 **     the rbu update db handle to any required virtual table
   172592 **     implementations.
   172593 **
   172594 **   * If the application uses the "rbu_delta()" feature described above,
   172595 **     it must use sqlite3_create_function() or similar to register the
   172596 **     rbu_delta() implementation with the target database handle.
   172597 **
   172598 ** If an error has occurred, either while opening or stepping the RBU object,
   172599 ** this function may return NULL. The error code and message may be collected
   172600 ** when sqlite3rbu_close() is called.
   172601 **
   172602 ** Database handles returned by this function remain valid until the next
   172603 ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
   172604 */
   172605 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
   172606 
   172607 /*
   172608 ** Do some work towards applying the RBU update to the target db.
   172609 **
   172610 ** Return SQLITE_DONE if the update has been completely applied, or
   172611 ** SQLITE_OK if no error occurs but there remains work to do to apply
   172612 ** the RBU update. If an error does occur, some other error code is
   172613 ** returned.
   172614 **
   172615 ** Once a call to sqlite3rbu_step() has returned a value other than
   172616 ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
   172617 ** that immediately return the same value.
   172618 */
   172619 SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
   172620 
   172621 /*
   172622 ** Force RBU to save its state to disk.
   172623 **
   172624 ** If a power failure or application crash occurs during an update, following
   172625 ** system recovery RBU may resume the update from the point at which the state
   172626 ** was last saved. In other words, from the most recent successful call to
   172627 ** sqlite3rbu_close() or this function.
   172628 **
   172629 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
   172630 */
   172631 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
   172632 
   172633 /*
   172634 ** Close an RBU handle.
   172635 **
   172636 ** If the RBU update has been completely applied, mark the RBU database
   172637 ** as fully applied. Otherwise, assuming no error has occurred, save the
   172638 ** current state of the RBU update appliation to the RBU database.
   172639 **
   172640 ** If an error has already occurred as part of an sqlite3rbu_step()
   172641 ** or sqlite3rbu_open() call, or if one occurs within this function, an
   172642 ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
   172643 ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
   172644 ** English language error message. It is the responsibility of the caller to
   172645 ** eventually free any such buffer using sqlite3_free().
   172646 **
   172647 ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
   172648 ** update has been partially applied, or SQLITE_DONE if it has been
   172649 ** completely applied.
   172650 */
   172651 SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
   172652 
   172653 /*
   172654 ** Return the total number of key-value operations (inserts, deletes or
   172655 ** updates) that have been performed on the target database since the
   172656 ** current RBU update was started.
   172657 */
   172658 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
   172659 
   172660 /*
   172661 ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
   172662 ** progress indications for the two stages of an RBU update. This API may
   172663 ** be useful for driving GUI progress indicators and similar.
   172664 **
   172665 ** An RBU update is divided into two stages:
   172666 **
   172667 **   * Stage 1, in which changes are accumulated in an oal/wal file, and
   172668 **   * Stage 2, in which the contents of the wal file are copied into the
   172669 **     main database.
   172670 **
   172671 ** The update is visible to non-RBU clients during stage 2. During stage 1
   172672 ** non-RBU reader clients may see the original database.
   172673 **
   172674 ** If this API is called during stage 2 of the update, output variable
   172675 ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
   172676 ** to a value between 0 and 10000 to indicate the permyriadage progress of
   172677 ** stage 2. A value of 5000 indicates that stage 2 is half finished,
   172678 ** 9000 indicates that it is 90% finished, and so on.
   172679 **
   172680 ** If this API is called during stage 1 of the update, output variable
   172681 ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
   172682 ** value to which (*pnOne) is set depends on whether or not the RBU
   172683 ** database contains an "rbu_count" table. The rbu_count table, if it
   172684 ** exists, must contain the same columns as the following:
   172685 **
   172686 **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
   172687 **
   172688 ** There must be one row in the table for each source (data_xxx) table within
   172689 ** the RBU database. The 'tbl' column should contain the name of the source
   172690 ** table. The 'cnt' column should contain the number of rows within the
   172691 ** source table.
   172692 **
   172693 ** If the rbu_count table is present and populated correctly and this
   172694 ** API is called during stage 1, the *pnOne output variable is set to the
   172695 ** permyriadage progress of the same stage. If the rbu_count table does
   172696 ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
   172697 ** table exists but is not correctly populated, the value of the *pnOne
   172698 ** output variable during stage 1 is undefined.
   172699 */
   172700 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
   172701 
   172702 /*
   172703 ** Obtain an indication as to the current stage of an RBU update or vacuum.
   172704 ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
   172705 ** defined in this file. Return values should be interpreted as follows:
   172706 **
   172707 ** SQLITE_RBU_STATE_OAL:
   172708 **   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
   172709 **   may either add further data to the *-oal file, or compute data that will
   172710 **   be added by a subsequent call.
   172711 **
   172712 ** SQLITE_RBU_STATE_MOVE:
   172713 **   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
   172714 **   will move the *-oal file to the equivalent *-wal path. If the current
   172715 **   operation is an RBU update, then the updated version of the database
   172716 **   file will become visible to ordinary SQLite clients following the next
   172717 **   call to sqlite3rbu_step().
   172718 **
   172719 ** SQLITE_RBU_STATE_CHECKPOINT:
   172720 **   RBU is currently performing an incremental checkpoint. The next call to
   172721 **   sqlite3rbu_step() will copy a page of data from the *-wal file into
   172722 **   the target database file.
   172723 **
   172724 ** SQLITE_RBU_STATE_DONE:
   172725 **   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
   172726 **   will immediately return SQLITE_DONE.
   172727 **
   172728 ** SQLITE_RBU_STATE_ERROR:
   172729 **   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
   172730 **   immediately return the SQLite error code associated with the error.
   172731 */
   172732 #define SQLITE_RBU_STATE_OAL        1
   172733 #define SQLITE_RBU_STATE_MOVE       2
   172734 #define SQLITE_RBU_STATE_CHECKPOINT 3
   172735 #define SQLITE_RBU_STATE_DONE       4
   172736 #define SQLITE_RBU_STATE_ERROR      5
   172737 
   172738 SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
   172739 
   172740 /*
   172741 ** Create an RBU VFS named zName that accesses the underlying file-system
   172742 ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
   172743 ** then the new RBU VFS uses the default system VFS to access the file-system.
   172744 ** The new object is registered as a non-default VFS with SQLite before
   172745 ** returning.
   172746 **
   172747 ** Part of the RBU implementation uses a custom VFS object. Usually, this
   172748 ** object is created and deleted automatically by RBU.
   172749 **
   172750 ** The exception is for applications that also use zipvfs. In this case,
   172751 ** the custom VFS must be explicitly created by the user before the RBU
   172752 ** handle is opened. The RBU VFS should be installed so that the zipvfs
   172753 ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
   172754 ** (for example multiplexor) to access the file-system. For example,
   172755 ** to assemble an RBU enabled VFS stack that uses both zipvfs and
   172756 ** multiplexor (error checking omitted):
   172757 **
   172758 **     // Create a VFS named "multiplex" (not the default).
   172759 **     sqlite3_multiplex_initialize(0, 0);
   172760 **
   172761 **     // Create an rbu VFS named "rbu" that uses multiplexor. If the
   172762 **     // second argument were replaced with NULL, the "rbu" VFS would
   172763 **     // access the file-system via the system default VFS, bypassing the
   172764 **     // multiplexor.
   172765 **     sqlite3rbu_create_vfs("rbu", "multiplex");
   172766 **
   172767 **     // Create a zipvfs VFS named "zipvfs" that uses rbu.
   172768 **     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
   172769 **
   172770 **     // Make zipvfs the default VFS.
   172771 **     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
   172772 **
   172773 ** Because the default VFS created above includes a RBU functionality, it
   172774 ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
   172775 ** that does not include the RBU layer results in an error.
   172776 **
   172777 ** The overhead of adding the "rbu" VFS to the system is negligible for
   172778 ** non-RBU users. There is no harm in an application accessing the
   172779 ** file-system via "rbu" all the time, even if it only uses RBU functionality
   172780 ** occasionally.
   172781 */
   172782 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
   172783 
   172784 /*
   172785 ** Deregister and destroy an RBU vfs created by an earlier call to
   172786 ** sqlite3rbu_create_vfs().
   172787 **
   172788 ** VFS objects are not reference counted. If a VFS object is destroyed
   172789 ** before all database handles that use it have been closed, the results
   172790 ** are undefined.
   172791 */
   172792 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
   172793 
   172794 #if 0
   172795 }  /* end of the 'extern "C"' block */
   172796 #endif
   172797 
   172798 #endif /* _SQLITE3RBU_H */
   172799 
   172800 /************** End of sqlite3rbu.h ******************************************/
   172801 /************** Continuing where we left off in sqlite3rbu.c *****************/
   172802 
   172803 #if defined(_WIN32_WCE)
   172804 /* #include "windows.h" */
   172805 #endif
   172806 
   172807 /* Maximum number of prepared UPDATE statements held by this module */
   172808 #define SQLITE_RBU_UPDATE_CACHESIZE 16
   172809 
   172810 /* Delta checksums disabled by default.  Compile with -DRBU_ENABLE_DELTA_CKSUM
   172811 ** to enable checksum verification.
   172812 */
   172813 #ifndef RBU_ENABLE_DELTA_CKSUM
   172814 # define RBU_ENABLE_DELTA_CKSUM 0
   172815 #endif
   172816 
   172817 /*
   172818 ** Swap two objects of type TYPE.
   172819 */
   172820 #if !defined(SQLITE_AMALGAMATION)
   172821 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   172822 #endif
   172823 
   172824 /*
   172825 ** The rbu_state table is used to save the state of a partially applied
   172826 ** update so that it can be resumed later. The table consists of integer
   172827 ** keys mapped to values as follows:
   172828 **
   172829 ** RBU_STATE_STAGE:
   172830 **   May be set to integer values 1, 2, 4 or 5. As follows:
   172831 **       1: the *-rbu file is currently under construction.
   172832 **       2: the *-rbu file has been constructed, but not yet moved
   172833 **          to the *-wal path.
   172834 **       4: the checkpoint is underway.
   172835 **       5: the rbu update has been checkpointed.
   172836 **
   172837 ** RBU_STATE_TBL:
   172838 **   Only valid if STAGE==1. The target database name of the table
   172839 **   currently being written.
   172840 **
   172841 ** RBU_STATE_IDX:
   172842 **   Only valid if STAGE==1. The target database name of the index
   172843 **   currently being written, or NULL if the main table is currently being
   172844 **   updated.
   172845 **
   172846 ** RBU_STATE_ROW:
   172847 **   Only valid if STAGE==1. Number of rows already processed for the current
   172848 **   table/index.
   172849 **
   172850 ** RBU_STATE_PROGRESS:
   172851 **   Trbul number of sqlite3rbu_step() calls made so far as part of this
   172852 **   rbu update.
   172853 **
   172854 ** RBU_STATE_CKPT:
   172855 **   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
   172856 **   header created by recovering the *-wal file. This is used to detect
   172857 **   cases when another client appends frames to the *-wal file in the
   172858 **   middle of an incremental checkpoint (an incremental checkpoint cannot
   172859 **   be continued if this happens).
   172860 **
   172861 ** RBU_STATE_COOKIE:
   172862 **   Valid if STAGE==1. The current change-counter cookie value in the
   172863 **   target db file.
   172864 **
   172865 ** RBU_STATE_OALSZ:
   172866 **   Valid if STAGE==1. The size in bytes of the *-oal file.
   172867 */
   172868 #define RBU_STATE_STAGE        1
   172869 #define RBU_STATE_TBL          2
   172870 #define RBU_STATE_IDX          3
   172871 #define RBU_STATE_ROW          4
   172872 #define RBU_STATE_PROGRESS     5
   172873 #define RBU_STATE_CKPT         6
   172874 #define RBU_STATE_COOKIE       7
   172875 #define RBU_STATE_OALSZ        8
   172876 #define RBU_STATE_PHASEONESTEP 9
   172877 
   172878 #define RBU_STAGE_OAL         1
   172879 #define RBU_STAGE_MOVE        2
   172880 #define RBU_STAGE_CAPTURE     3
   172881 #define RBU_STAGE_CKPT        4
   172882 #define RBU_STAGE_DONE        5
   172883 
   172884 
   172885 #define RBU_CREATE_STATE \
   172886   "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
   172887 
   172888 typedef struct RbuFrame RbuFrame;
   172889 typedef struct RbuObjIter RbuObjIter;
   172890 typedef struct RbuState RbuState;
   172891 typedef struct rbu_vfs rbu_vfs;
   172892 typedef struct rbu_file rbu_file;
   172893 typedef struct RbuUpdateStmt RbuUpdateStmt;
   172894 
   172895 #if !defined(SQLITE_AMALGAMATION)
   172896 typedef unsigned int u32;
   172897 typedef unsigned short u16;
   172898 typedef unsigned char u8;
   172899 typedef sqlite3_int64 i64;
   172900 #endif
   172901 
   172902 /*
   172903 ** These values must match the values defined in wal.c for the equivalent
   172904 ** locks. These are not magic numbers as they are part of the SQLite file
   172905 ** format.
   172906 */
   172907 #define WAL_LOCK_WRITE  0
   172908 #define WAL_LOCK_CKPT   1
   172909 #define WAL_LOCK_READ0  3
   172910 
   172911 #define SQLITE_FCNTL_RBUCNT    5149216
   172912 
   172913 /*
   172914 ** A structure to store values read from the rbu_state table in memory.
   172915 */
   172916 struct RbuState {
   172917   int eStage;
   172918   char *zTbl;
   172919   char *zIdx;
   172920   i64 iWalCksum;
   172921   int nRow;
   172922   i64 nProgress;
   172923   u32 iCookie;
   172924   i64 iOalSz;
   172925   i64 nPhaseOneStep;
   172926 };
   172927 
   172928 struct RbuUpdateStmt {
   172929   char *zMask;                    /* Copy of update mask used with pUpdate */
   172930   sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
   172931   RbuUpdateStmt *pNext;
   172932 };
   172933 
   172934 /*
   172935 ** An iterator of this type is used to iterate through all objects in
   172936 ** the target database that require updating. For each such table, the
   172937 ** iterator visits, in order:
   172938 **
   172939 **     * the table itself,
   172940 **     * each index of the table (zero or more points to visit), and
   172941 **     * a special "cleanup table" state.
   172942 **
   172943 ** abIndexed:
   172944 **   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
   172945 **   it points to an array of flags nTblCol elements in size. The flag is
   172946 **   set for each column that is either a part of the PK or a part of an
   172947 **   index. Or clear otherwise.
   172948 **
   172949 */
   172950 struct RbuObjIter {
   172951   sqlite3_stmt *pTblIter;         /* Iterate through tables */
   172952   sqlite3_stmt *pIdxIter;         /* Index iterator */
   172953   int nTblCol;                    /* Size of azTblCol[] array */
   172954   char **azTblCol;                /* Array of unquoted target column names */
   172955   char **azTblType;               /* Array of target column types */
   172956   int *aiSrcOrder;                /* src table col -> target table col */
   172957   u8 *abTblPk;                    /* Array of flags, set on target PK columns */
   172958   u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
   172959   u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
   172960   int eType;                      /* Table type - an RBU_PK_XXX value */
   172961 
   172962   /* Output variables. zTbl==0 implies EOF. */
   172963   int bCleanup;                   /* True in "cleanup" state */
   172964   const char *zTbl;               /* Name of target db table */
   172965   const char *zDataTbl;           /* Name of rbu db table (or null) */
   172966   const char *zIdx;               /* Name of target db index (or null) */
   172967   int iTnum;                      /* Root page of current object */
   172968   int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
   172969   int bUnique;                    /* Current index is unique */
   172970   int nIndex;                     /* Number of aux. indexes on table zTbl */
   172971 
   172972   /* Statements created by rbuObjIterPrepareAll() */
   172973   int nCol;                       /* Number of columns in current object */
   172974   sqlite3_stmt *pSelect;          /* Source data */
   172975   sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
   172976   sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
   172977   sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
   172978 
   172979   /* Last UPDATE used (for PK b-tree updates only), or NULL. */
   172980   RbuUpdateStmt *pRbuUpdate;
   172981 };
   172982 
   172983 /*
   172984 ** Values for RbuObjIter.eType
   172985 **
   172986 **     0: Table does not exist (error)
   172987 **     1: Table has an implicit rowid.
   172988 **     2: Table has an explicit IPK column.
   172989 **     3: Table has an external PK index.
   172990 **     4: Table is WITHOUT ROWID.
   172991 **     5: Table is a virtual table.
   172992 */
   172993 #define RBU_PK_NOTABLE        0
   172994 #define RBU_PK_NONE           1
   172995 #define RBU_PK_IPK            2
   172996 #define RBU_PK_EXTERNAL       3
   172997 #define RBU_PK_WITHOUT_ROWID  4
   172998 #define RBU_PK_VTAB           5
   172999 
   173000 
   173001 /*
   173002 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
   173003 ** one of the following operations.
   173004 */
   173005 #define RBU_INSERT     1          /* Insert on a main table b-tree */
   173006 #define RBU_DELETE     2          /* Delete a row from a main table b-tree */
   173007 #define RBU_REPLACE    3          /* Delete and then insert a row */
   173008 #define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
   173009 #define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
   173010 
   173011 #define RBU_UPDATE     6          /* Update a row in a main table b-tree */
   173012 
   173013 /*
   173014 ** A single step of an incremental checkpoint - frame iWalFrame of the wal
   173015 ** file should be copied to page iDbPage of the database file.
   173016 */
   173017 struct RbuFrame {
   173018   u32 iDbPage;
   173019   u32 iWalFrame;
   173020 };
   173021 
   173022 /*
   173023 ** RBU handle.
   173024 **
   173025 ** nPhaseOneStep:
   173026 **   If the RBU database contains an rbu_count table, this value is set to
   173027 **   a running estimate of the number of b-tree operations required to
   173028 **   finish populating the *-oal file. This allows the sqlite3_bp_progress()
   173029 **   API to calculate the permyriadage progress of populating the *-oal file
   173030 **   using the formula:
   173031 **
   173032 **     permyriadage = (10000 * nProgress) / nPhaseOneStep
   173033 **
   173034 **   nPhaseOneStep is initialized to the sum of:
   173035 **
   173036 **     nRow * (nIndex + 1)
   173037 **
   173038 **   for all source tables in the RBU database, where nRow is the number
   173039 **   of rows in the source table and nIndex the number of indexes on the
   173040 **   corresponding target database table.
   173041 **
   173042 **   This estimate is accurate if the RBU update consists entirely of
   173043 **   INSERT operations. However, it is inaccurate if:
   173044 **
   173045 **     * the RBU update contains any UPDATE operations. If the PK specified
   173046 **       for an UPDATE operation does not exist in the target table, then
   173047 **       no b-tree operations are required on index b-trees. Or if the
   173048 **       specified PK does exist, then (nIndex*2) such operations are
   173049 **       required (one delete and one insert on each index b-tree).
   173050 **
   173051 **     * the RBU update contains any DELETE operations for which the specified
   173052 **       PK does not exist. In this case no operations are required on index
   173053 **       b-trees.
   173054 **
   173055 **     * the RBU update contains REPLACE operations. These are similar to
   173056 **       UPDATE operations.
   173057 **
   173058 **   nPhaseOneStep is updated to account for the conditions above during the
   173059 **   first pass of each source table. The updated nPhaseOneStep value is
   173060 **   stored in the rbu_state table if the RBU update is suspended.
   173061 */
   173062 struct sqlite3rbu {
   173063   int eStage;                     /* Value of RBU_STATE_STAGE field */
   173064   sqlite3 *dbMain;                /* target database handle */
   173065   sqlite3 *dbRbu;                 /* rbu database handle */
   173066   char *zTarget;                  /* Path to target db */
   173067   char *zRbu;                     /* Path to rbu db */
   173068   char *zState;                   /* Path to state db (or NULL if zRbu) */
   173069   char zStateDb[5];               /* Db name for state ("stat" or "main") */
   173070   int rc;                         /* Value returned by last rbu_step() call */
   173071   char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
   173072   int nStep;                      /* Rows processed for current object */
   173073   int nProgress;                  /* Rows processed for all objects */
   173074   RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
   173075   const char *zVfsName;           /* Name of automatically created rbu vfs */
   173076   rbu_file *pTargetFd;            /* File handle open on target db */
   173077   int nPagePerSector;             /* Pages per sector for pTargetFd */
   173078   i64 iOalSz;
   173079   i64 nPhaseOneStep;
   173080 
   173081   /* The following state variables are used as part of the incremental
   173082   ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
   173083   ** function rbuSetupCheckpoint() for details.  */
   173084   u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
   173085   u32 mLock;
   173086   int nFrame;                     /* Entries in aFrame[] array */
   173087   int nFrameAlloc;                /* Allocated size of aFrame[] array */
   173088   RbuFrame *aFrame;
   173089   int pgsz;
   173090   u8 *aBuf;
   173091   i64 iWalCksum;
   173092   i64 szTemp;                     /* Current size of all temp files in use */
   173093   i64 szTempLimit;                /* Total size limit for temp files */
   173094 
   173095   /* Used in RBU vacuum mode only */
   173096   int nRbu;                       /* Number of RBU VFS in the stack */
   173097   rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
   173098 };
   173099 
   173100 /*
   173101 ** An rbu VFS is implemented using an instance of this structure.
   173102 **
   173103 ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
   173104 ** It is NULL for RBU VFS objects created explicitly using
   173105 ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
   173106 ** space used by the RBU handle.
   173107 */
   173108 struct rbu_vfs {
   173109   sqlite3_vfs base;               /* rbu VFS shim methods */
   173110   sqlite3_vfs *pRealVfs;          /* Underlying VFS */
   173111   sqlite3_mutex *mutex;           /* Mutex to protect pMain */
   173112   sqlite3rbu *pRbu;               /* Owner RBU object */
   173113   rbu_file *pMain;                /* Linked list of main db files */
   173114 };
   173115 
   173116 /*
   173117 ** Each file opened by an rbu VFS is represented by an instance of
   173118 ** the following structure.
   173119 **
   173120 ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
   173121 ** "sz" is set to the current size of the database file.
   173122 */
   173123 struct rbu_file {
   173124   sqlite3_file base;              /* sqlite3_file methods */
   173125   sqlite3_file *pReal;            /* Underlying file handle */
   173126   rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
   173127   sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
   173128   i64 sz;                         /* Size of file in bytes (temp only) */
   173129 
   173130   int openFlags;                  /* Flags this file was opened with */
   173131   u32 iCookie;                    /* Cookie value for main db files */
   173132   u8 iWriteVer;                   /* "write-version" value for main db files */
   173133   u8 bNolock;                     /* True to fail EXCLUSIVE locks */
   173134 
   173135   int nShm;                       /* Number of entries in apShm[] array */
   173136   char **apShm;                   /* Array of mmap'd *-shm regions */
   173137   char *zDel;                     /* Delete this when closing file */
   173138 
   173139   const char *zWal;               /* Wal filename for this main db file */
   173140   rbu_file *pWalFd;               /* Wal file descriptor for this main db */
   173141   rbu_file *pMainNext;            /* Next MAIN_DB file */
   173142 };
   173143 
   173144 /*
   173145 ** True for an RBU vacuum handle, or false otherwise.
   173146 */
   173147 #define rbuIsVacuum(p) ((p)->zTarget==0)
   173148 
   173149 
   173150 /*************************************************************************
   173151 ** The following three functions, found below:
   173152 **
   173153 **   rbuDeltaGetInt()
   173154 **   rbuDeltaChecksum()
   173155 **   rbuDeltaApply()
   173156 **
   173157 ** are lifted from the fossil source code (http://fossil-scm.org). They
   173158 ** are used to implement the scalar SQL function rbu_fossil_delta().
   173159 */
   173160 
   173161 /*
   173162 ** Read bytes from *pz and convert them into a positive integer.  When
   173163 ** finished, leave *pz pointing to the first character past the end of
   173164 ** the integer.  The *pLen parameter holds the length of the string
   173165 ** in *pz and is decremented once for each character in the integer.
   173166 */
   173167 static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
   173168   static const signed char zValue[] = {
   173169     -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
   173170     -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
   173171     -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
   173172      0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
   173173     -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
   173174     25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
   173175     -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
   173176     52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
   173177   };
   173178   unsigned int v = 0;
   173179   int c;
   173180   unsigned char *z = (unsigned char*)*pz;
   173181   unsigned char *zStart = z;
   173182   while( (c = zValue[0x7f&*(z++)])>=0 ){
   173183      v = (v<<6) + c;
   173184   }
   173185   z--;
   173186   *pLen -= z - zStart;
   173187   *pz = (char*)z;
   173188   return v;
   173189 }
   173190 
   173191 #if RBU_ENABLE_DELTA_CKSUM
   173192 /*
   173193 ** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
   173194 */
   173195 static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
   173196   const unsigned char *z = (const unsigned char *)zIn;
   173197   unsigned sum0 = 0;
   173198   unsigned sum1 = 0;
   173199   unsigned sum2 = 0;
   173200   unsigned sum3 = 0;
   173201   while(N >= 16){
   173202     sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
   173203     sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
   173204     sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
   173205     sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
   173206     z += 16;
   173207     N -= 16;
   173208   }
   173209   while(N >= 4){
   173210     sum0 += z[0];
   173211     sum1 += z[1];
   173212     sum2 += z[2];
   173213     sum3 += z[3];
   173214     z += 4;
   173215     N -= 4;
   173216   }
   173217   sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
   173218   switch(N){
   173219     case 3:   sum3 += (z[2] << 8);
   173220     case 2:   sum3 += (z[1] << 16);
   173221     case 1:   sum3 += (z[0] << 24);
   173222     default:  ;
   173223   }
   173224   return sum3;
   173225 }
   173226 #endif
   173227 
   173228 /*
   173229 ** Apply a delta.
   173230 **
   173231 ** The output buffer should be big enough to hold the whole output
   173232 ** file and a NUL terminator at the end.  The delta_output_size()
   173233 ** routine will determine this size for you.
   173234 **
   173235 ** The delta string should be null-terminated.  But the delta string
   173236 ** may contain embedded NUL characters (if the input and output are
   173237 ** binary files) so we also have to pass in the length of the delta in
   173238 ** the lenDelta parameter.
   173239 **
   173240 ** This function returns the size of the output file in bytes (excluding
   173241 ** the final NUL terminator character).  Except, if the delta string is
   173242 ** malformed or intended for use with a source file other than zSrc,
   173243 ** then this routine returns -1.
   173244 **
   173245 ** Refer to the delta_create() documentation above for a description
   173246 ** of the delta file format.
   173247 */
   173248 static int rbuDeltaApply(
   173249   const char *zSrc,      /* The source or pattern file */
   173250   int lenSrc,            /* Length of the source file */
   173251   const char *zDelta,    /* Delta to apply to the pattern */
   173252   int lenDelta,          /* Length of the delta */
   173253   char *zOut             /* Write the output into this preallocated buffer */
   173254 ){
   173255   unsigned int limit;
   173256   unsigned int total = 0;
   173257 #if RBU_ENABLE_DELTA_CKSUM
   173258   char *zOrigOut = zOut;
   173259 #endif
   173260 
   173261   limit = rbuDeltaGetInt(&zDelta, &lenDelta);
   173262   if( *zDelta!='\n' ){
   173263     /* ERROR: size integer not terminated by "\n" */
   173264     return -1;
   173265   }
   173266   zDelta++; lenDelta--;
   173267   while( *zDelta && lenDelta>0 ){
   173268     unsigned int cnt, ofst;
   173269     cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
   173270     switch( zDelta[0] ){
   173271       case '@': {
   173272         zDelta++; lenDelta--;
   173273         ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
   173274         if( lenDelta>0 && zDelta[0]!=',' ){
   173275           /* ERROR: copy command not terminated by ',' */
   173276           return -1;
   173277         }
   173278         zDelta++; lenDelta--;
   173279         total += cnt;
   173280         if( total>limit ){
   173281           /* ERROR: copy exceeds output file size */
   173282           return -1;
   173283         }
   173284         if( (int)(ofst+cnt) > lenSrc ){
   173285           /* ERROR: copy extends past end of input */
   173286           return -1;
   173287         }
   173288         memcpy(zOut, &zSrc[ofst], cnt);
   173289         zOut += cnt;
   173290         break;
   173291       }
   173292       case ':': {
   173293         zDelta++; lenDelta--;
   173294         total += cnt;
   173295         if( total>limit ){
   173296           /* ERROR:  insert command gives an output larger than predicted */
   173297           return -1;
   173298         }
   173299         if( (int)cnt>lenDelta ){
   173300           /* ERROR: insert count exceeds size of delta */
   173301           return -1;
   173302         }
   173303         memcpy(zOut, zDelta, cnt);
   173304         zOut += cnt;
   173305         zDelta += cnt;
   173306         lenDelta -= cnt;
   173307         break;
   173308       }
   173309       case ';': {
   173310         zDelta++; lenDelta--;
   173311         zOut[0] = 0;
   173312 #if RBU_ENABLE_DELTA_CKSUM
   173313         if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
   173314           /* ERROR:  bad checksum */
   173315           return -1;
   173316         }
   173317 #endif
   173318         if( total!=limit ){
   173319           /* ERROR: generated size does not match predicted size */
   173320           return -1;
   173321         }
   173322         return total;
   173323       }
   173324       default: {
   173325         /* ERROR: unknown delta operator */
   173326         return -1;
   173327       }
   173328     }
   173329   }
   173330   /* ERROR: unterminated delta */
   173331   return -1;
   173332 }
   173333 
   173334 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
   173335   int size;
   173336   size = rbuDeltaGetInt(&zDelta, &lenDelta);
   173337   if( *zDelta!='\n' ){
   173338     /* ERROR: size integer not terminated by "\n" */
   173339     return -1;
   173340   }
   173341   return size;
   173342 }
   173343 
   173344 /*
   173345 ** End of code taken from fossil.
   173346 *************************************************************************/
   173347 
   173348 /*
   173349 ** Implementation of SQL scalar function rbu_fossil_delta().
   173350 **
   173351 ** This function applies a fossil delta patch to a blob. Exactly two
   173352 ** arguments must be passed to this function. The first is the blob to
   173353 ** patch and the second the patch to apply. If no error occurs, this
   173354 ** function returns the patched blob.
   173355 */
   173356 static void rbuFossilDeltaFunc(
   173357   sqlite3_context *context,
   173358   int argc,
   173359   sqlite3_value **argv
   173360 ){
   173361   const char *aDelta;
   173362   int nDelta;
   173363   const char *aOrig;
   173364   int nOrig;
   173365 
   173366   int nOut;
   173367   int nOut2;
   173368   char *aOut;
   173369 
   173370   assert( argc==2 );
   173371 
   173372   nOrig = sqlite3_value_bytes(argv[0]);
   173373   aOrig = (const char*)sqlite3_value_blob(argv[0]);
   173374   nDelta = sqlite3_value_bytes(argv[1]);
   173375   aDelta = (const char*)sqlite3_value_blob(argv[1]);
   173376 
   173377   /* Figure out the size of the output */
   173378   nOut = rbuDeltaOutputSize(aDelta, nDelta);
   173379   if( nOut<0 ){
   173380     sqlite3_result_error(context, "corrupt fossil delta", -1);
   173381     return;
   173382   }
   173383 
   173384   aOut = sqlite3_malloc(nOut+1);
   173385   if( aOut==0 ){
   173386     sqlite3_result_error_nomem(context);
   173387   }else{
   173388     nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
   173389     if( nOut2!=nOut ){
   173390       sqlite3_result_error(context, "corrupt fossil delta", -1);
   173391     }else{
   173392       sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
   173393     }
   173394   }
   173395 }
   173396 
   173397 
   173398 /*
   173399 ** Prepare the SQL statement in buffer zSql against database handle db.
   173400 ** If successful, set *ppStmt to point to the new statement and return
   173401 ** SQLITE_OK.
   173402 **
   173403 ** Otherwise, if an error does occur, set *ppStmt to NULL and return
   173404 ** an SQLite error code. Additionally, set output variable *pzErrmsg to
   173405 ** point to a buffer containing an error message. It is the responsibility
   173406 ** of the caller to (eventually) free this buffer using sqlite3_free().
   173407 */
   173408 static int prepareAndCollectError(
   173409   sqlite3 *db,
   173410   sqlite3_stmt **ppStmt,
   173411   char **pzErrmsg,
   173412   const char *zSql
   173413 ){
   173414   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
   173415   if( rc!=SQLITE_OK ){
   173416     *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   173417     *ppStmt = 0;
   173418   }
   173419   return rc;
   173420 }
   173421 
   173422 /*
   173423 ** Reset the SQL statement passed as the first argument. Return a copy
   173424 ** of the value returned by sqlite3_reset().
   173425 **
   173426 ** If an error has occurred, then set *pzErrmsg to point to a buffer
   173427 ** containing an error message. It is the responsibility of the caller
   173428 ** to eventually free this buffer using sqlite3_free().
   173429 */
   173430 static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
   173431   int rc = sqlite3_reset(pStmt);
   173432   if( rc!=SQLITE_OK ){
   173433     *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
   173434   }
   173435   return rc;
   173436 }
   173437 
   173438 /*
   173439 ** Unless it is NULL, argument zSql points to a buffer allocated using
   173440 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
   173441 ** statement against database db and frees the buffer. If statement
   173442 ** compilation is successful, *ppStmt is set to point to the new statement
   173443 ** handle and SQLITE_OK is returned.
   173444 **
   173445 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
   173446 ** returned. In this case, *pzErrmsg may also be set to point to an error
   173447 ** message. It is the responsibility of the caller to free this error message
   173448 ** buffer using sqlite3_free().
   173449 **
   173450 ** If argument zSql is NULL, this function assumes that an OOM has occurred.
   173451 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
   173452 */
   173453 static int prepareFreeAndCollectError(
   173454   sqlite3 *db,
   173455   sqlite3_stmt **ppStmt,
   173456   char **pzErrmsg,
   173457   char *zSql
   173458 ){
   173459   int rc;
   173460   assert( *pzErrmsg==0 );
   173461   if( zSql==0 ){
   173462     rc = SQLITE_NOMEM;
   173463     *ppStmt = 0;
   173464   }else{
   173465     rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
   173466     sqlite3_free(zSql);
   173467   }
   173468   return rc;
   173469 }
   173470 
   173471 /*
   173472 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
   173473 ** by an earlier call to rbuObjIterCacheTableInfo().
   173474 */
   173475 static void rbuObjIterFreeCols(RbuObjIter *pIter){
   173476   int i;
   173477   for(i=0; i<pIter->nTblCol; i++){
   173478     sqlite3_free(pIter->azTblCol[i]);
   173479     sqlite3_free(pIter->azTblType[i]);
   173480   }
   173481   sqlite3_free(pIter->azTblCol);
   173482   pIter->azTblCol = 0;
   173483   pIter->azTblType = 0;
   173484   pIter->aiSrcOrder = 0;
   173485   pIter->abTblPk = 0;
   173486   pIter->abNotNull = 0;
   173487   pIter->nTblCol = 0;
   173488   pIter->eType = 0;               /* Invalid value */
   173489 }
   173490 
   173491 /*
   173492 ** Finalize all statements and free all allocations that are specific to
   173493 ** the current object (table/index pair).
   173494 */
   173495 static void rbuObjIterClearStatements(RbuObjIter *pIter){
   173496   RbuUpdateStmt *pUp;
   173497 
   173498   sqlite3_finalize(pIter->pSelect);
   173499   sqlite3_finalize(pIter->pInsert);
   173500   sqlite3_finalize(pIter->pDelete);
   173501   sqlite3_finalize(pIter->pTmpInsert);
   173502   pUp = pIter->pRbuUpdate;
   173503   while( pUp ){
   173504     RbuUpdateStmt *pTmp = pUp->pNext;
   173505     sqlite3_finalize(pUp->pUpdate);
   173506     sqlite3_free(pUp);
   173507     pUp = pTmp;
   173508   }
   173509 
   173510   pIter->pSelect = 0;
   173511   pIter->pInsert = 0;
   173512   pIter->pDelete = 0;
   173513   pIter->pRbuUpdate = 0;
   173514   pIter->pTmpInsert = 0;
   173515   pIter->nCol = 0;
   173516 }
   173517 
   173518 /*
   173519 ** Clean up any resources allocated as part of the iterator object passed
   173520 ** as the only argument.
   173521 */
   173522 static void rbuObjIterFinalize(RbuObjIter *pIter){
   173523   rbuObjIterClearStatements(pIter);
   173524   sqlite3_finalize(pIter->pTblIter);
   173525   sqlite3_finalize(pIter->pIdxIter);
   173526   rbuObjIterFreeCols(pIter);
   173527   memset(pIter, 0, sizeof(RbuObjIter));
   173528 }
   173529 
   173530 /*
   173531 ** Advance the iterator to the next position.
   173532 **
   173533 ** If no error occurs, SQLITE_OK is returned and the iterator is left
   173534 ** pointing to the next entry. Otherwise, an error code and message is
   173535 ** left in the RBU handle passed as the first argument. A copy of the
   173536 ** error code is returned.
   173537 */
   173538 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
   173539   int rc = p->rc;
   173540   if( rc==SQLITE_OK ){
   173541 
   173542     /* Free any SQLite statements used while processing the previous object */
   173543     rbuObjIterClearStatements(pIter);
   173544     if( pIter->zIdx==0 ){
   173545       rc = sqlite3_exec(p->dbMain,
   173546           "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
   173547           "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
   173548           "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
   173549           "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
   173550           , 0, 0, &p->zErrmsg
   173551       );
   173552     }
   173553 
   173554     if( rc==SQLITE_OK ){
   173555       if( pIter->bCleanup ){
   173556         rbuObjIterFreeCols(pIter);
   173557         pIter->bCleanup = 0;
   173558         rc = sqlite3_step(pIter->pTblIter);
   173559         if( rc!=SQLITE_ROW ){
   173560           rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
   173561           pIter->zTbl = 0;
   173562         }else{
   173563           pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
   173564           pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
   173565           rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
   173566         }
   173567       }else{
   173568         if( pIter->zIdx==0 ){
   173569           sqlite3_stmt *pIdx = pIter->pIdxIter;
   173570           rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
   173571         }
   173572         if( rc==SQLITE_OK ){
   173573           rc = sqlite3_step(pIter->pIdxIter);
   173574           if( rc!=SQLITE_ROW ){
   173575             rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
   173576             pIter->bCleanup = 1;
   173577             pIter->zIdx = 0;
   173578           }else{
   173579             pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
   173580             pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
   173581             pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
   173582             rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
   173583           }
   173584         }
   173585       }
   173586     }
   173587   }
   173588 
   173589   if( rc!=SQLITE_OK ){
   173590     rbuObjIterFinalize(pIter);
   173591     p->rc = rc;
   173592   }
   173593   return rc;
   173594 }
   173595 
   173596 
   173597 /*
   173598 ** The implementation of the rbu_target_name() SQL function. This function
   173599 ** accepts one or two arguments. The first argument is the name of a table -
   173600 ** the name of a table in the RBU database.  The second, if it is present, is 1
   173601 ** for a view or 0 for a table.
   173602 **
   173603 ** For a non-vacuum RBU handle, if the table name matches the pattern:
   173604 **
   173605 **     data[0-9]_<name>
   173606 **
   173607 ** where <name> is any sequence of 1 or more characters, <name> is returned.
   173608 ** Otherwise, if the only argument does not match the above pattern, an SQL
   173609 ** NULL is returned.
   173610 **
   173611 **     "data_t1"     -> "t1"
   173612 **     "data0123_t2" -> "t2"
   173613 **     "dataAB_t3"   -> NULL
   173614 **
   173615 ** For an rbu vacuum handle, a copy of the first argument is returned if
   173616 ** the second argument is either missing or 0 (not a view).
   173617 */
   173618 static void rbuTargetNameFunc(
   173619   sqlite3_context *pCtx,
   173620   int argc,
   173621   sqlite3_value **argv
   173622 ){
   173623   sqlite3rbu *p = sqlite3_user_data(pCtx);
   173624   const char *zIn;
   173625   assert( argc==1 || argc==2 );
   173626 
   173627   zIn = (const char*)sqlite3_value_text(argv[0]);
   173628   if( zIn ){
   173629     if( rbuIsVacuum(p) ){
   173630       if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
   173631         sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
   173632       }
   173633     }else{
   173634       if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
   173635         int i;
   173636         for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
   173637         if( zIn[i]=='_' && zIn[i+1] ){
   173638           sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
   173639         }
   173640       }
   173641     }
   173642   }
   173643 }
   173644 
   173645 /*
   173646 ** Initialize the iterator structure passed as the second argument.
   173647 **
   173648 ** If no error occurs, SQLITE_OK is returned and the iterator is left
   173649 ** pointing to the first entry. Otherwise, an error code and message is
   173650 ** left in the RBU handle passed as the first argument. A copy of the
   173651 ** error code is returned.
   173652 */
   173653 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
   173654   int rc;
   173655   memset(pIter, 0, sizeof(RbuObjIter));
   173656 
   173657   rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
   173658     sqlite3_mprintf(
   173659       "SELECT rbu_target_name(name, type='view') AS target, name "
   173660       "FROM sqlite_master "
   173661       "WHERE type IN ('table', 'view') AND target IS NOT NULL "
   173662       " %s "
   173663       "ORDER BY name"
   173664   , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
   173665 
   173666   if( rc==SQLITE_OK ){
   173667     rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
   173668         "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
   173669         "  FROM main.sqlite_master "
   173670         "  WHERE type='index' AND tbl_name = ?"
   173671     );
   173672   }
   173673 
   173674   pIter->bCleanup = 1;
   173675   p->rc = rc;
   173676   return rbuObjIterNext(p, pIter);
   173677 }
   173678 
   173679 /*
   173680 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
   173681 ** an error code is stored in the RBU handle passed as the first argument.
   173682 **
   173683 ** If an error has already occurred (p->rc is already set to something other
   173684 ** than SQLITE_OK), then this function returns NULL without modifying the
   173685 ** stored error code. In this case it still calls sqlite3_free() on any
   173686 ** printf() parameters associated with %z conversions.
   173687 */
   173688 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
   173689   char *zSql = 0;
   173690   va_list ap;
   173691   va_start(ap, zFmt);
   173692   zSql = sqlite3_vmprintf(zFmt, ap);
   173693   if( p->rc==SQLITE_OK ){
   173694     if( zSql==0 ) p->rc = SQLITE_NOMEM;
   173695   }else{
   173696     sqlite3_free(zSql);
   173697     zSql = 0;
   173698   }
   173699   va_end(ap);
   173700   return zSql;
   173701 }
   173702 
   173703 /*
   173704 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
   173705 ** arguments are the usual subsitution values. This function performs
   173706 ** the printf() style substitutions and executes the result as an SQL
   173707 ** statement on the RBU handles database.
   173708 **
   173709 ** If an error occurs, an error code and error message is stored in the
   173710 ** RBU handle. If an error has already occurred when this function is
   173711 ** called, it is a no-op.
   173712 */
   173713 static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
   173714   va_list ap;
   173715   char *zSql;
   173716   va_start(ap, zFmt);
   173717   zSql = sqlite3_vmprintf(zFmt, ap);
   173718   if( p->rc==SQLITE_OK ){
   173719     if( zSql==0 ){
   173720       p->rc = SQLITE_NOMEM;
   173721     }else{
   173722       p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
   173723     }
   173724   }
   173725   sqlite3_free(zSql);
   173726   va_end(ap);
   173727   return p->rc;
   173728 }
   173729 
   173730 /*
   173731 ** Attempt to allocate and return a pointer to a zeroed block of nByte
   173732 ** bytes.
   173733 **
   173734 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
   173735 ** error code in the rbu handle passed as the first argument. Or, if an
   173736 ** error has already occurred when this function is called, return NULL
   173737 ** immediately without attempting the allocation or modifying the stored
   173738 ** error code.
   173739 */
   173740 static void *rbuMalloc(sqlite3rbu *p, int nByte){
   173741   void *pRet = 0;
   173742   if( p->rc==SQLITE_OK ){
   173743     assert( nByte>0 );
   173744     pRet = sqlite3_malloc64(nByte);
   173745     if( pRet==0 ){
   173746       p->rc = SQLITE_NOMEM;
   173747     }else{
   173748       memset(pRet, 0, nByte);
   173749     }
   173750   }
   173751   return pRet;
   173752 }
   173753 
   173754 
   173755 /*
   173756 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
   173757 ** there is room for at least nCol elements. If an OOM occurs, store an
   173758 ** error code in the RBU handle passed as the first argument.
   173759 */
   173760 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
   173761   int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
   173762   char **azNew;
   173763 
   173764   azNew = (char**)rbuMalloc(p, nByte);
   173765   if( azNew ){
   173766     pIter->azTblCol = azNew;
   173767     pIter->azTblType = &azNew[nCol];
   173768     pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
   173769     pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
   173770     pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
   173771     pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
   173772   }
   173773 }
   173774 
   173775 /*
   173776 ** The first argument must be a nul-terminated string. This function
   173777 ** returns a copy of the string in memory obtained from sqlite3_malloc().
   173778 ** It is the responsibility of the caller to eventually free this memory
   173779 ** using sqlite3_free().
   173780 **
   173781 ** If an OOM condition is encountered when attempting to allocate memory,
   173782 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
   173783 ** if the allocation succeeds, (*pRc) is left unchanged.
   173784 */
   173785 static char *rbuStrndup(const char *zStr, int *pRc){
   173786   char *zRet = 0;
   173787 
   173788   assert( *pRc==SQLITE_OK );
   173789   if( zStr ){
   173790     size_t nCopy = strlen(zStr) + 1;
   173791     zRet = (char*)sqlite3_malloc64(nCopy);
   173792     if( zRet ){
   173793       memcpy(zRet, zStr, nCopy);
   173794     }else{
   173795       *pRc = SQLITE_NOMEM;
   173796     }
   173797   }
   173798 
   173799   return zRet;
   173800 }
   173801 
   173802 /*
   173803 ** Finalize the statement passed as the second argument.
   173804 **
   173805 ** If the sqlite3_finalize() call indicates that an error occurs, and the
   173806 ** rbu handle error code is not already set, set the error code and error
   173807 ** message accordingly.
   173808 */
   173809 static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
   173810   sqlite3 *db = sqlite3_db_handle(pStmt);
   173811   int rc = sqlite3_finalize(pStmt);
   173812   if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
   173813     p->rc = rc;
   173814     p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   173815   }
   173816 }
   173817 
   173818 /* Determine the type of a table.
   173819 **
   173820 **   peType is of type (int*), a pointer to an output parameter of type
   173821 **   (int). This call sets the output parameter as follows, depending
   173822 **   on the type of the table specified by parameters dbName and zTbl.
   173823 **
   173824 **     RBU_PK_NOTABLE:       No such table.
   173825 **     RBU_PK_NONE:          Table has an implicit rowid.
   173826 **     RBU_PK_IPK:           Table has an explicit IPK column.
   173827 **     RBU_PK_EXTERNAL:      Table has an external PK index.
   173828 **     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
   173829 **     RBU_PK_VTAB:          Table is a virtual table.
   173830 **
   173831 **   Argument *piPk is also of type (int*), and also points to an output
   173832 **   parameter. Unless the table has an external primary key index
   173833 **   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
   173834 **   if the table does have an external primary key index, then *piPk
   173835 **   is set to the root page number of the primary key index before
   173836 **   returning.
   173837 **
   173838 ** ALGORITHM:
   173839 **
   173840 **   if( no entry exists in sqlite_master ){
   173841 **     return RBU_PK_NOTABLE
   173842 **   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
   173843 **     return RBU_PK_VTAB
   173844 **   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
   173845 **     if( the index that is the pk exists in sqlite_master ){
   173846 **       *piPK = rootpage of that index.
   173847 **       return RBU_PK_EXTERNAL
   173848 **     }else{
   173849 **       return RBU_PK_WITHOUT_ROWID
   173850 **     }
   173851 **   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
   173852 **     return RBU_PK_IPK
   173853 **   }else{
   173854 **     return RBU_PK_NONE
   173855 **   }
   173856 */
   173857 static void rbuTableType(
   173858   sqlite3rbu *p,
   173859   const char *zTab,
   173860   int *peType,
   173861   int *piTnum,
   173862   int *piPk
   173863 ){
   173864   /*
   173865   ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
   173866   ** 1) PRAGMA index_list = ?
   173867   ** 2) SELECT count(*) FROM sqlite_master where name=%Q
   173868   ** 3) PRAGMA table_info = ?
   173869   */
   173870   sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
   173871 
   173872   *peType = RBU_PK_NOTABLE;
   173873   *piPk = 0;
   173874 
   173875   assert( p->rc==SQLITE_OK );
   173876   p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
   173877     sqlite3_mprintf(
   173878           "SELECT (sql LIKE 'create virtual%%'), rootpage"
   173879           "  FROM sqlite_master"
   173880           " WHERE name=%Q", zTab
   173881   ));
   173882   if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
   173883     /* Either an error, or no such table. */
   173884     goto rbuTableType_end;
   173885   }
   173886   if( sqlite3_column_int(aStmt[0], 0) ){
   173887     *peType = RBU_PK_VTAB;                     /* virtual table */
   173888     goto rbuTableType_end;
   173889   }
   173890   *piTnum = sqlite3_column_int(aStmt[0], 1);
   173891 
   173892   p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
   173893     sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
   173894   );
   173895   if( p->rc ) goto rbuTableType_end;
   173896   while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
   173897     const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
   173898     const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
   173899     if( zOrig && zIdx && zOrig[0]=='p' ){
   173900       p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
   173901           sqlite3_mprintf(
   173902             "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
   173903       ));
   173904       if( p->rc==SQLITE_OK ){
   173905         if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
   173906           *piPk = sqlite3_column_int(aStmt[2], 0);
   173907           *peType = RBU_PK_EXTERNAL;
   173908         }else{
   173909           *peType = RBU_PK_WITHOUT_ROWID;
   173910         }
   173911       }
   173912       goto rbuTableType_end;
   173913     }
   173914   }
   173915 
   173916   p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
   173917     sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
   173918   );
   173919   if( p->rc==SQLITE_OK ){
   173920     while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
   173921       if( sqlite3_column_int(aStmt[3],5)>0 ){
   173922         *peType = RBU_PK_IPK;                /* explicit IPK column */
   173923         goto rbuTableType_end;
   173924       }
   173925     }
   173926     *peType = RBU_PK_NONE;
   173927   }
   173928 
   173929 rbuTableType_end: {
   173930     unsigned int i;
   173931     for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
   173932       rbuFinalize(p, aStmt[i]);
   173933     }
   173934   }
   173935 }
   173936 
   173937 /*
   173938 ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
   173939 ** the pIter->abIndexed[] array.
   173940 */
   173941 static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
   173942   sqlite3_stmt *pList = 0;
   173943   int bIndex = 0;
   173944 
   173945   if( p->rc==SQLITE_OK ){
   173946     memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
   173947     p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
   173948         sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
   173949     );
   173950   }
   173951 
   173952   pIter->nIndex = 0;
   173953   while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
   173954     const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
   173955     sqlite3_stmt *pXInfo = 0;
   173956     if( zIdx==0 ) break;
   173957     p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
   173958         sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
   173959     );
   173960     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
   173961       int iCid = sqlite3_column_int(pXInfo, 1);
   173962       if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
   173963     }
   173964     rbuFinalize(p, pXInfo);
   173965     bIndex = 1;
   173966     pIter->nIndex++;
   173967   }
   173968 
   173969   if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
   173970     /* "PRAGMA index_list" includes the main PK b-tree */
   173971     pIter->nIndex--;
   173972   }
   173973 
   173974   rbuFinalize(p, pList);
   173975   if( bIndex==0 ) pIter->abIndexed = 0;
   173976 }
   173977 
   173978 
   173979 /*
   173980 ** If they are not already populated, populate the pIter->azTblCol[],
   173981 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
   173982 ** the table (not index) that the iterator currently points to.
   173983 **
   173984 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
   173985 ** an error does occur, an error code and error message are also left in
   173986 ** the RBU handle.
   173987 */
   173988 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
   173989   if( pIter->azTblCol==0 ){
   173990     sqlite3_stmt *pStmt = 0;
   173991     int nCol = 0;
   173992     int i;                        /* for() loop iterator variable */
   173993     int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
   173994     int iOrder = 0;
   173995     int iTnum = 0;
   173996 
   173997     /* Figure out the type of table this step will deal with. */
   173998     assert( pIter->eType==0 );
   173999     rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
   174000     if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
   174001       p->rc = SQLITE_ERROR;
   174002       p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
   174003     }
   174004     if( p->rc ) return p->rc;
   174005     if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
   174006 
   174007     assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
   174008          || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
   174009          || pIter->eType==RBU_PK_VTAB
   174010     );
   174011 
   174012     /* Populate the azTblCol[] and nTblCol variables based on the columns
   174013     ** of the input table. Ignore any input table columns that begin with
   174014     ** "rbu_".  */
   174015     p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
   174016         sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
   174017     );
   174018     if( p->rc==SQLITE_OK ){
   174019       nCol = sqlite3_column_count(pStmt);
   174020       rbuAllocateIterArrays(p, pIter, nCol);
   174021     }
   174022     for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
   174023       const char *zName = (const char*)sqlite3_column_name(pStmt, i);
   174024       if( sqlite3_strnicmp("rbu_", zName, 4) ){
   174025         char *zCopy = rbuStrndup(zName, &p->rc);
   174026         pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
   174027         pIter->azTblCol[pIter->nTblCol++] = zCopy;
   174028       }
   174029       else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
   174030         bRbuRowid = 1;
   174031       }
   174032     }
   174033     sqlite3_finalize(pStmt);
   174034     pStmt = 0;
   174035 
   174036     if( p->rc==SQLITE_OK
   174037      && rbuIsVacuum(p)==0
   174038      && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
   174039     ){
   174040       p->rc = SQLITE_ERROR;
   174041       p->zErrmsg = sqlite3_mprintf(
   174042           "table %q %s rbu_rowid column", pIter->zDataTbl,
   174043           (bRbuRowid ? "may not have" : "requires")
   174044       );
   174045     }
   174046 
   174047     /* Check that all non-HIDDEN columns in the destination table are also
   174048     ** present in the input table. Populate the abTblPk[], azTblType[] and
   174049     ** aiTblOrder[] arrays at the same time.  */
   174050     if( p->rc==SQLITE_OK ){
   174051       p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
   174052           sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
   174053       );
   174054     }
   174055     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   174056       const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
   174057       if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
   174058       for(i=iOrder; i<pIter->nTblCol; i++){
   174059         if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
   174060       }
   174061       if( i==pIter->nTblCol ){
   174062         p->rc = SQLITE_ERROR;
   174063         p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
   174064             pIter->zDataTbl, zName
   174065         );
   174066       }else{
   174067         int iPk = sqlite3_column_int(pStmt, 5);
   174068         int bNotNull = sqlite3_column_int(pStmt, 3);
   174069         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
   174070 
   174071         if( i!=iOrder ){
   174072           SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
   174073           SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
   174074         }
   174075 
   174076         pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
   174077         pIter->abTblPk[iOrder] = (iPk!=0);
   174078         pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
   174079         iOrder++;
   174080       }
   174081     }
   174082 
   174083     rbuFinalize(p, pStmt);
   174084     rbuObjIterCacheIndexedCols(p, pIter);
   174085     assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
   174086     assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
   174087   }
   174088 
   174089   return p->rc;
   174090 }
   174091 
   174092 /*
   174093 ** This function constructs and returns a pointer to a nul-terminated
   174094 ** string containing some SQL clause or list based on one or more of the
   174095 ** column names currently stored in the pIter->azTblCol[] array.
   174096 */
   174097 static char *rbuObjIterGetCollist(
   174098   sqlite3rbu *p,                  /* RBU object */
   174099   RbuObjIter *pIter               /* Object iterator for column names */
   174100 ){
   174101   char *zList = 0;
   174102   const char *zSep = "";
   174103   int i;
   174104   for(i=0; i<pIter->nTblCol; i++){
   174105     const char *z = pIter->azTblCol[i];
   174106     zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
   174107     zSep = ", ";
   174108   }
   174109   return zList;
   174110 }
   174111 
   174112 /*
   174113 ** This function is used to create a SELECT list (the list of SQL
   174114 ** expressions that follows a SELECT keyword) for a SELECT statement
   174115 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
   174116 ** index object currently indicated by the iterator object passed as the
   174117 ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
   174118 ** to obtain the required information.
   174119 **
   174120 ** If the index is of the following form:
   174121 **
   174122 **   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
   174123 **
   174124 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
   174125 ** "ipk", the returned string is:
   174126 **
   174127 **   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
   174128 **
   174129 ** As well as the returned string, three other malloc'd strings are
   174130 ** returned via output parameters. As follows:
   174131 **
   174132 **   pzImposterCols: ...
   174133 **   pzImposterPk: ...
   174134 **   pzWhere: ...
   174135 */
   174136 static char *rbuObjIterGetIndexCols(
   174137   sqlite3rbu *p,                  /* RBU object */
   174138   RbuObjIter *pIter,              /* Object iterator for column names */
   174139   char **pzImposterCols,          /* OUT: Columns for imposter table */
   174140   char **pzImposterPk,            /* OUT: Imposter PK clause */
   174141   char **pzWhere,                 /* OUT: WHERE clause */
   174142   int *pnBind                     /* OUT: Trbul number of columns */
   174143 ){
   174144   int rc = p->rc;                 /* Error code */
   174145   int rc2;                        /* sqlite3_finalize() return code */
   174146   char *zRet = 0;                 /* String to return */
   174147   char *zImpCols = 0;             /* String to return via *pzImposterCols */
   174148   char *zImpPK = 0;               /* String to return via *pzImposterPK */
   174149   char *zWhere = 0;               /* String to return via *pzWhere */
   174150   int nBind = 0;                  /* Value to return via *pnBind */
   174151   const char *zCom = "";          /* Set to ", " later on */
   174152   const char *zAnd = "";          /* Set to " AND " later on */
   174153   sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
   174154 
   174155   if( rc==SQLITE_OK ){
   174156     assert( p->zErrmsg==0 );
   174157     rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
   174158         sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
   174159     );
   174160   }
   174161 
   174162   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
   174163     int iCid = sqlite3_column_int(pXInfo, 1);
   174164     int bDesc = sqlite3_column_int(pXInfo, 3);
   174165     const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
   174166     const char *zCol;
   174167     const char *zType;
   174168 
   174169     if( iCid<0 ){
   174170       /* An integer primary key. If the table has an explicit IPK, use
   174171       ** its name. Otherwise, use "rbu_rowid".  */
   174172       if( pIter->eType==RBU_PK_IPK ){
   174173         int i;
   174174         for(i=0; pIter->abTblPk[i]==0; i++);
   174175         assert( i<pIter->nTblCol );
   174176         zCol = pIter->azTblCol[i];
   174177       }else if( rbuIsVacuum(p) ){
   174178         zCol = "_rowid_";
   174179       }else{
   174180         zCol = "rbu_rowid";
   174181       }
   174182       zType = "INTEGER";
   174183     }else{
   174184       zCol = pIter->azTblCol[iCid];
   174185       zType = pIter->azTblType[iCid];
   174186     }
   174187 
   174188     zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
   174189     if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
   174190       const char *zOrder = (bDesc ? " DESC" : "");
   174191       zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
   174192           zImpPK, zCom, nBind, zCol, zOrder
   174193       );
   174194     }
   174195     zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
   174196         zImpCols, zCom, nBind, zCol, zType, zCollate
   174197     );
   174198     zWhere = sqlite3_mprintf(
   174199         "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
   174200     );
   174201     if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
   174202     zCom = ", ";
   174203     zAnd = " AND ";
   174204     nBind++;
   174205   }
   174206 
   174207   rc2 = sqlite3_finalize(pXInfo);
   174208   if( rc==SQLITE_OK ) rc = rc2;
   174209 
   174210   if( rc!=SQLITE_OK ){
   174211     sqlite3_free(zRet);
   174212     sqlite3_free(zImpCols);
   174213     sqlite3_free(zImpPK);
   174214     sqlite3_free(zWhere);
   174215     zRet = 0;
   174216     zImpCols = 0;
   174217     zImpPK = 0;
   174218     zWhere = 0;
   174219     p->rc = rc;
   174220   }
   174221 
   174222   *pzImposterCols = zImpCols;
   174223   *pzImposterPk = zImpPK;
   174224   *pzWhere = zWhere;
   174225   *pnBind = nBind;
   174226   return zRet;
   174227 }
   174228 
   174229 /*
   174230 ** Assuming the current table columns are "a", "b" and "c", and the zObj
   174231 ** paramter is passed "old", return a string of the form:
   174232 **
   174233 **     "old.a, old.b, old.b"
   174234 **
   174235 ** With the column names escaped.
   174236 **
   174237 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
   174238 ** the text ", old._rowid_" to the returned value.
   174239 */
   174240 static char *rbuObjIterGetOldlist(
   174241   sqlite3rbu *p,
   174242   RbuObjIter *pIter,
   174243   const char *zObj
   174244 ){
   174245   char *zList = 0;
   174246   if( p->rc==SQLITE_OK && pIter->abIndexed ){
   174247     const char *zS = "";
   174248     int i;
   174249     for(i=0; i<pIter->nTblCol; i++){
   174250       if( pIter->abIndexed[i] ){
   174251         const char *zCol = pIter->azTblCol[i];
   174252         zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
   174253       }else{
   174254         zList = sqlite3_mprintf("%z%sNULL", zList, zS);
   174255       }
   174256       zS = ", ";
   174257       if( zList==0 ){
   174258         p->rc = SQLITE_NOMEM;
   174259         break;
   174260       }
   174261     }
   174262 
   174263     /* For a table with implicit rowids, append "old._rowid_" to the list. */
   174264     if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
   174265       zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
   174266     }
   174267   }
   174268   return zList;
   174269 }
   174270 
   174271 /*
   174272 ** Return an expression that can be used in a WHERE clause to match the
   174273 ** primary key of the current table. For example, if the table is:
   174274 **
   174275 **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
   174276 **
   174277 ** Return the string:
   174278 **
   174279 **   "b = ?1 AND c = ?2"
   174280 */
   174281 static char *rbuObjIterGetWhere(
   174282   sqlite3rbu *p,
   174283   RbuObjIter *pIter
   174284 ){
   174285   char *zList = 0;
   174286   if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
   174287     zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
   174288   }else if( pIter->eType==RBU_PK_EXTERNAL ){
   174289     const char *zSep = "";
   174290     int i;
   174291     for(i=0; i<pIter->nTblCol; i++){
   174292       if( pIter->abTblPk[i] ){
   174293         zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
   174294         zSep = " AND ";
   174295       }
   174296     }
   174297     zList = rbuMPrintf(p,
   174298         "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
   174299     );
   174300 
   174301   }else{
   174302     const char *zSep = "";
   174303     int i;
   174304     for(i=0; i<pIter->nTblCol; i++){
   174305       if( pIter->abTblPk[i] ){
   174306         const char *zCol = pIter->azTblCol[i];
   174307         zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
   174308         zSep = " AND ";
   174309       }
   174310     }
   174311   }
   174312   return zList;
   174313 }
   174314 
   174315 /*
   174316 ** The SELECT statement iterating through the keys for the current object
   174317 ** (p->objiter.pSelect) currently points to a valid row. However, there
   174318 ** is something wrong with the rbu_control value in the rbu_control value
   174319 ** stored in the (p->nCol+1)'th column. Set the error code and error message
   174320 ** of the RBU handle to something reflecting this.
   174321 */
   174322 static void rbuBadControlError(sqlite3rbu *p){
   174323   p->rc = SQLITE_ERROR;
   174324   p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
   174325 }
   174326 
   174327 
   174328 /*
   174329 ** Return a nul-terminated string containing the comma separated list of
   174330 ** assignments that should be included following the "SET" keyword of
   174331 ** an UPDATE statement used to update the table object that the iterator
   174332 ** passed as the second argument currently points to if the rbu_control
   174333 ** column of the data_xxx table entry is set to zMask.
   174334 **
   174335 ** The memory for the returned string is obtained from sqlite3_malloc().
   174336 ** It is the responsibility of the caller to eventually free it using
   174337 ** sqlite3_free().
   174338 **
   174339 ** If an OOM error is encountered when allocating space for the new
   174340 ** string, an error code is left in the rbu handle passed as the first
   174341 ** argument and NULL is returned. Or, if an error has already occurred
   174342 ** when this function is called, NULL is returned immediately, without
   174343 ** attempting the allocation or modifying the stored error code.
   174344 */
   174345 static char *rbuObjIterGetSetlist(
   174346   sqlite3rbu *p,
   174347   RbuObjIter *pIter,
   174348   const char *zMask
   174349 ){
   174350   char *zList = 0;
   174351   if( p->rc==SQLITE_OK ){
   174352     int i;
   174353 
   174354     if( (int)strlen(zMask)!=pIter->nTblCol ){
   174355       rbuBadControlError(p);
   174356     }else{
   174357       const char *zSep = "";
   174358       for(i=0; i<pIter->nTblCol; i++){
   174359         char c = zMask[pIter->aiSrcOrder[i]];
   174360         if( c=='x' ){
   174361           zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
   174362               zList, zSep, pIter->azTblCol[i], i+1
   174363           );
   174364           zSep = ", ";
   174365         }
   174366         else if( c=='d' ){
   174367           zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
   174368               zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
   174369           );
   174370           zSep = ", ";
   174371         }
   174372         else if( c=='f' ){
   174373           zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
   174374               zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
   174375           );
   174376           zSep = ", ";
   174377         }
   174378       }
   174379     }
   174380   }
   174381   return zList;
   174382 }
   174383 
   174384 /*
   174385 ** Return a nul-terminated string consisting of nByte comma separated
   174386 ** "?" expressions. For example, if nByte is 3, return a pointer to
   174387 ** a buffer containing the string "?,?,?".
   174388 **
   174389 ** The memory for the returned string is obtained from sqlite3_malloc().
   174390 ** It is the responsibility of the caller to eventually free it using
   174391 ** sqlite3_free().
   174392 **
   174393 ** If an OOM error is encountered when allocating space for the new
   174394 ** string, an error code is left in the rbu handle passed as the first
   174395 ** argument and NULL is returned. Or, if an error has already occurred
   174396 ** when this function is called, NULL is returned immediately, without
   174397 ** attempting the allocation or modifying the stored error code.
   174398 */
   174399 static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
   174400   char *zRet = 0;
   174401   int nByte = nBind*2 + 1;
   174402 
   174403   zRet = (char*)rbuMalloc(p, nByte);
   174404   if( zRet ){
   174405     int i;
   174406     for(i=0; i<nBind; i++){
   174407       zRet[i*2] = '?';
   174408       zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
   174409     }
   174410   }
   174411   return zRet;
   174412 }
   174413 
   174414 /*
   174415 ** The iterator currently points to a table (not index) of type
   174416 ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
   174417 ** declaration for the corresponding imposter table. For example,
   174418 ** if the iterator points to a table created as:
   174419 **
   174420 **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
   174421 **
   174422 ** this function returns:
   174423 **
   174424 **   PRIMARY KEY("b", "a" DESC)
   174425 */
   174426 static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
   174427   char *z = 0;
   174428   assert( pIter->zIdx==0 );
   174429   if( p->rc==SQLITE_OK ){
   174430     const char *zSep = "PRIMARY KEY(";
   174431     sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
   174432     sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
   174433 
   174434     p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
   174435         sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
   174436     );
   174437     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
   174438       const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
   174439       if( zOrig && strcmp(zOrig, "pk")==0 ){
   174440         const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
   174441         if( zIdx ){
   174442           p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
   174443               sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
   174444           );
   174445         }
   174446         break;
   174447       }
   174448     }
   174449     rbuFinalize(p, pXList);
   174450 
   174451     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
   174452       if( sqlite3_column_int(pXInfo, 5) ){
   174453         /* int iCid = sqlite3_column_int(pXInfo, 0); */
   174454         const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
   174455         const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
   174456         z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
   174457         zSep = ", ";
   174458       }
   174459     }
   174460     z = rbuMPrintf(p, "%z)", z);
   174461     rbuFinalize(p, pXInfo);
   174462   }
   174463   return z;
   174464 }
   174465 
   174466 /*
   174467 ** This function creates the second imposter table used when writing to
   174468 ** a table b-tree where the table has an external primary key. If the
   174469 ** iterator passed as the second argument does not currently point to
   174470 ** a table (not index) with an external primary key, this function is a
   174471 ** no-op.
   174472 **
   174473 ** Assuming the iterator does point to a table with an external PK, this
   174474 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
   174475 ** used to access that PK index. For example, if the target table is
   174476 ** declared as follows:
   174477 **
   174478 **   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
   174479 **
   174480 ** then the imposter table schema is:
   174481 **
   174482 **   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
   174483 **
   174484 */
   174485 static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
   174486   if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
   174487     int tnum = pIter->iPkTnum;    /* Root page of PK index */
   174488     sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
   174489     const char *zIdx = 0;         /* Name of PK index */
   174490     sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
   174491     const char *zComma = "";
   174492     char *zCols = 0;              /* Used to build up list of table cols */
   174493     char *zPk = 0;                /* Used to build up table PK declaration */
   174494 
   174495     /* Figure out the name of the primary key index for the current table.
   174496     ** This is needed for the argument to "PRAGMA index_xinfo". Set
   174497     ** zIdx to point to a nul-terminated string containing this name. */
   174498     p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
   174499         "SELECT name FROM sqlite_master WHERE rootpage = ?"
   174500     );
   174501     if( p->rc==SQLITE_OK ){
   174502       sqlite3_bind_int(pQuery, 1, tnum);
   174503       if( SQLITE_ROW==sqlite3_step(pQuery) ){
   174504         zIdx = (const char*)sqlite3_column_text(pQuery, 0);
   174505       }
   174506     }
   174507     if( zIdx ){
   174508       p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
   174509           sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
   174510       );
   174511     }
   174512     rbuFinalize(p, pQuery);
   174513 
   174514     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
   174515       int bKey = sqlite3_column_int(pXInfo, 5);
   174516       if( bKey ){
   174517         int iCid = sqlite3_column_int(pXInfo, 1);
   174518         int bDesc = sqlite3_column_int(pXInfo, 3);
   174519         const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
   174520         zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
   174521             iCid, pIter->azTblType[iCid], zCollate
   174522         );
   174523         zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
   174524         zComma = ", ";
   174525       }
   174526     }
   174527     zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
   174528     rbuFinalize(p, pXInfo);
   174529 
   174530     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
   174531     rbuMPrintfExec(p, p->dbMain,
   174532         "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
   174533         zCols, zPk
   174534     );
   174535     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
   174536   }
   174537 }
   174538 
   174539 /*
   174540 ** If an error has already occurred when this function is called, it
   174541 ** immediately returns zero (without doing any work). Or, if an error
   174542 ** occurs during the execution of this function, it sets the error code
   174543 ** in the sqlite3rbu object indicated by the first argument and returns
   174544 ** zero.
   174545 **
   174546 ** The iterator passed as the second argument is guaranteed to point to
   174547 ** a table (not an index) when this function is called. This function
   174548 ** attempts to create any imposter table required to write to the main
   174549 ** table b-tree of the table before returning. Non-zero is returned if
   174550 ** an imposter table are created, or zero otherwise.
   174551 **
   174552 ** An imposter table is required in all cases except RBU_PK_VTAB. Only
   174553 ** virtual tables are written to directly. The imposter table has the
   174554 ** same schema as the actual target table (less any UNIQUE constraints).
   174555 ** More precisely, the "same schema" means the same columns, types,
   174556 ** collation sequences. For tables that do not have an external PRIMARY
   174557 ** KEY, it also means the same PRIMARY KEY declaration.
   174558 */
   174559 static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
   174560   if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
   174561     int tnum = pIter->iTnum;
   174562     const char *zComma = "";
   174563     char *zSql = 0;
   174564     int iCol;
   174565     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
   174566 
   174567     for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
   174568       const char *zPk = "";
   174569       const char *zCol = pIter->azTblCol[iCol];
   174570       const char *zColl = 0;
   174571 
   174572       p->rc = sqlite3_table_column_metadata(
   174573           p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
   174574       );
   174575 
   174576       if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
   174577         /* If the target table column is an "INTEGER PRIMARY KEY", add
   174578         ** "PRIMARY KEY" to the imposter table column declaration. */
   174579         zPk = "PRIMARY KEY ";
   174580       }
   174581       zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
   174582           zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
   174583           (pIter->abNotNull[iCol] ? " NOT NULL" : "")
   174584       );
   174585       zComma = ", ";
   174586     }
   174587 
   174588     if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
   174589       char *zPk = rbuWithoutRowidPK(p, pIter);
   174590       if( zPk ){
   174591         zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
   174592       }
   174593     }
   174594 
   174595     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
   174596     rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
   174597         pIter->zTbl, zSql,
   174598         (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
   174599     );
   174600     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
   174601   }
   174602 }
   174603 
   174604 /*
   174605 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
   174606 ** Specifically a statement of the form:
   174607 **
   174608 **     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
   174609 **
   174610 ** The number of bound variables is equal to the number of columns in
   174611 ** the target table, plus one (for the rbu_control column), plus one more
   174612 ** (for the rbu_rowid column) if the target table is an implicit IPK or
   174613 ** virtual table.
   174614 */
   174615 static void rbuObjIterPrepareTmpInsert(
   174616   sqlite3rbu *p,
   174617   RbuObjIter *pIter,
   174618   const char *zCollist,
   174619   const char *zRbuRowid
   174620 ){
   174621   int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
   174622   char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
   174623   if( zBind ){
   174624     assert( pIter->pTmpInsert==0 );
   174625     p->rc = prepareFreeAndCollectError(
   174626         p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
   174627           "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
   174628           p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
   174629     ));
   174630   }
   174631 }
   174632 
   174633 static void rbuTmpInsertFunc(
   174634   sqlite3_context *pCtx,
   174635   int nVal,
   174636   sqlite3_value **apVal
   174637 ){
   174638   sqlite3rbu *p = sqlite3_user_data(pCtx);
   174639   int rc = SQLITE_OK;
   174640   int i;
   174641 
   174642   assert( sqlite3_value_int(apVal[0])!=0
   174643       || p->objiter.eType==RBU_PK_EXTERNAL
   174644       || p->objiter.eType==RBU_PK_NONE
   174645   );
   174646   if( sqlite3_value_int(apVal[0])!=0 ){
   174647     p->nPhaseOneStep += p->objiter.nIndex;
   174648   }
   174649 
   174650   for(i=0; rc==SQLITE_OK && i<nVal; i++){
   174651     rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
   174652   }
   174653   if( rc==SQLITE_OK ){
   174654     sqlite3_step(p->objiter.pTmpInsert);
   174655     rc = sqlite3_reset(p->objiter.pTmpInsert);
   174656   }
   174657 
   174658   if( rc!=SQLITE_OK ){
   174659     sqlite3_result_error_code(pCtx, rc);
   174660   }
   174661 }
   174662 
   174663 /*
   174664 ** Ensure that the SQLite statement handles required to update the
   174665 ** target database object currently indicated by the iterator passed
   174666 ** as the second argument are available.
   174667 */
   174668 static int rbuObjIterPrepareAll(
   174669   sqlite3rbu *p,
   174670   RbuObjIter *pIter,
   174671   int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
   174672 ){
   174673   assert( pIter->bCleanup==0 );
   174674   if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
   174675     const int tnum = pIter->iTnum;
   174676     char *zCollist = 0;           /* List of indexed columns */
   174677     char **pz = &p->zErrmsg;
   174678     const char *zIdx = pIter->zIdx;
   174679     char *zLimit = 0;
   174680 
   174681     if( nOffset ){
   174682       zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
   174683       if( !zLimit ) p->rc = SQLITE_NOMEM;
   174684     }
   174685 
   174686     if( zIdx ){
   174687       const char *zTbl = pIter->zTbl;
   174688       char *zImposterCols = 0;    /* Columns for imposter table */
   174689       char *zImposterPK = 0;      /* Primary key declaration for imposter */
   174690       char *zWhere = 0;           /* WHERE clause on PK columns */
   174691       char *zBind = 0;
   174692       int nBind = 0;
   174693 
   174694       assert( pIter->eType!=RBU_PK_VTAB );
   174695       zCollist = rbuObjIterGetIndexCols(
   174696           p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
   174697       );
   174698       zBind = rbuObjIterGetBindlist(p, nBind);
   174699 
   174700       /* Create the imposter table used to write to this index. */
   174701       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
   174702       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
   174703       rbuMPrintfExec(p, p->dbMain,
   174704           "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
   174705           zTbl, zImposterCols, zImposterPK
   174706       );
   174707       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
   174708 
   174709       /* Create the statement to insert index entries */
   174710       pIter->nCol = nBind;
   174711       if( p->rc==SQLITE_OK ){
   174712         p->rc = prepareFreeAndCollectError(
   174713             p->dbMain, &pIter->pInsert, &p->zErrmsg,
   174714           sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
   174715         );
   174716       }
   174717 
   174718       /* And to delete index entries */
   174719       if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
   174720         p->rc = prepareFreeAndCollectError(
   174721             p->dbMain, &pIter->pDelete, &p->zErrmsg,
   174722           sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
   174723         );
   174724       }
   174725 
   174726       /* Create the SELECT statement to read keys in sorted order */
   174727       if( p->rc==SQLITE_OK ){
   174728         char *zSql;
   174729         if( rbuIsVacuum(p) ){
   174730           zSql = sqlite3_mprintf(
   174731               "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
   174732               zCollist,
   174733               pIter->zDataTbl,
   174734               zCollist, zLimit
   174735           );
   174736         }else
   174737 
   174738         if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
   174739           zSql = sqlite3_mprintf(
   174740               "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
   174741               zCollist, p->zStateDb, pIter->zDataTbl,
   174742               zCollist, zLimit
   174743           );
   174744         }else{
   174745           zSql = sqlite3_mprintf(
   174746               "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
   174747               "UNION ALL "
   174748               "SELECT %s, rbu_control FROM '%q' "
   174749               "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
   174750               "ORDER BY %s%s",
   174751               zCollist, p->zStateDb, pIter->zDataTbl,
   174752               zCollist, pIter->zDataTbl,
   174753               zCollist, zLimit
   174754           );
   174755         }
   174756         p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
   174757       }
   174758 
   174759       sqlite3_free(zImposterCols);
   174760       sqlite3_free(zImposterPK);
   174761       sqlite3_free(zWhere);
   174762       sqlite3_free(zBind);
   174763     }else{
   174764       int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
   174765                     ||(pIter->eType==RBU_PK_NONE)
   174766                     ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
   174767       const char *zTbl = pIter->zTbl;       /* Table this step applies to */
   174768       const char *zWrite;                   /* Imposter table name */
   174769 
   174770       char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
   174771       char *zWhere = rbuObjIterGetWhere(p, pIter);
   174772       char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
   174773       char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
   174774 
   174775       zCollist = rbuObjIterGetCollist(p, pIter);
   174776       pIter->nCol = pIter->nTblCol;
   174777 
   174778       /* Create the imposter table or tables (if required). */
   174779       rbuCreateImposterTable(p, pIter);
   174780       rbuCreateImposterTable2(p, pIter);
   174781       zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
   174782 
   174783       /* Create the INSERT statement to write to the target PK b-tree */
   174784       if( p->rc==SQLITE_OK ){
   174785         p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
   174786             sqlite3_mprintf(
   174787               "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
   174788               zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
   174789             )
   174790         );
   174791       }
   174792 
   174793       /* Create the DELETE statement to write to the target PK b-tree.
   174794       ** Because it only performs INSERT operations, this is not required for
   174795       ** an rbu vacuum handle.  */
   174796       if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
   174797         p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
   174798             sqlite3_mprintf(
   174799               "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
   174800             )
   174801         );
   174802       }
   174803 
   174804       if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
   174805         const char *zRbuRowid = "";
   174806         if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
   174807           zRbuRowid = ", rbu_rowid";
   174808         }
   174809 
   174810         /* Create the rbu_tmp_xxx table and the triggers to populate it. */
   174811         rbuMPrintfExec(p, p->dbRbu,
   174812             "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
   174813             "SELECT *%s FROM '%q' WHERE 0;"
   174814             , p->zStateDb, pIter->zDataTbl
   174815             , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
   174816             , pIter->zDataTbl
   174817         );
   174818 
   174819         rbuMPrintfExec(p, p->dbMain,
   174820             "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
   174821             "BEGIN "
   174822             "  SELECT rbu_tmp_insert(3, %s);"
   174823             "END;"
   174824 
   174825             "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
   174826             "BEGIN "
   174827             "  SELECT rbu_tmp_insert(3, %s);"
   174828             "END;"
   174829 
   174830             "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
   174831             "BEGIN "
   174832             "  SELECT rbu_tmp_insert(4, %s);"
   174833             "END;",
   174834             zWrite, zTbl, zOldlist,
   174835             zWrite, zTbl, zOldlist,
   174836             zWrite, zTbl, zNewlist
   174837         );
   174838 
   174839         if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
   174840           rbuMPrintfExec(p, p->dbMain,
   174841               "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
   174842               "BEGIN "
   174843               "  SELECT rbu_tmp_insert(0, %s);"
   174844               "END;",
   174845               zWrite, zTbl, zNewlist
   174846           );
   174847         }
   174848 
   174849         rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
   174850       }
   174851 
   174852       /* Create the SELECT statement to read keys from data_xxx */
   174853       if( p->rc==SQLITE_OK ){
   174854         const char *zRbuRowid = "";
   174855         if( bRbuRowid ){
   174856           zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
   174857         }
   174858         p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
   174859             sqlite3_mprintf(
   174860               "SELECT %s,%s rbu_control%s FROM '%q'%s",
   174861               zCollist,
   174862               (rbuIsVacuum(p) ? "0 AS " : ""),
   174863               zRbuRowid,
   174864               pIter->zDataTbl, zLimit
   174865             )
   174866         );
   174867       }
   174868 
   174869       sqlite3_free(zWhere);
   174870       sqlite3_free(zOldlist);
   174871       sqlite3_free(zNewlist);
   174872       sqlite3_free(zBindings);
   174873     }
   174874     sqlite3_free(zCollist);
   174875     sqlite3_free(zLimit);
   174876   }
   174877 
   174878   return p->rc;
   174879 }
   174880 
   174881 /*
   174882 ** Set output variable *ppStmt to point to an UPDATE statement that may
   174883 ** be used to update the imposter table for the main table b-tree of the
   174884 ** table object that pIter currently points to, assuming that the
   174885 ** rbu_control column of the data_xyz table contains zMask.
   174886 **
   174887 ** If the zMask string does not specify any columns to update, then this
   174888 ** is not an error. Output variable *ppStmt is set to NULL in this case.
   174889 */
   174890 static int rbuGetUpdateStmt(
   174891   sqlite3rbu *p,                  /* RBU handle */
   174892   RbuObjIter *pIter,              /* Object iterator */
   174893   const char *zMask,              /* rbu_control value ('x.x.') */
   174894   sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
   174895 ){
   174896   RbuUpdateStmt **pp;
   174897   RbuUpdateStmt *pUp = 0;
   174898   int nUp = 0;
   174899 
   174900   /* In case an error occurs */
   174901   *ppStmt = 0;
   174902 
   174903   /* Search for an existing statement. If one is found, shift it to the front
   174904   ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
   174905   ** to the number of statements currently in the cache and pUp to the
   174906   ** last object in the list.  */
   174907   for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
   174908     pUp = *pp;
   174909     if( strcmp(pUp->zMask, zMask)==0 ){
   174910       *pp = pUp->pNext;
   174911       pUp->pNext = pIter->pRbuUpdate;
   174912       pIter->pRbuUpdate = pUp;
   174913       *ppStmt = pUp->pUpdate;
   174914       return SQLITE_OK;
   174915     }
   174916     nUp++;
   174917   }
   174918   assert( pUp==0 || pUp->pNext==0 );
   174919 
   174920   if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
   174921     for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
   174922     *pp = 0;
   174923     sqlite3_finalize(pUp->pUpdate);
   174924     pUp->pUpdate = 0;
   174925   }else{
   174926     pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
   174927   }
   174928 
   174929   if( pUp ){
   174930     char *zWhere = rbuObjIterGetWhere(p, pIter);
   174931     char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
   174932     char *zUpdate = 0;
   174933 
   174934     pUp->zMask = (char*)&pUp[1];
   174935     memcpy(pUp->zMask, zMask, pIter->nTblCol);
   174936     pUp->pNext = pIter->pRbuUpdate;
   174937     pIter->pRbuUpdate = pUp;
   174938 
   174939     if( zSet ){
   174940       const char *zPrefix = "";
   174941 
   174942       if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
   174943       zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
   174944           zPrefix, pIter->zTbl, zSet, zWhere
   174945       );
   174946       p->rc = prepareFreeAndCollectError(
   174947           p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
   174948       );
   174949       *ppStmt = pUp->pUpdate;
   174950     }
   174951     sqlite3_free(zWhere);
   174952     sqlite3_free(zSet);
   174953   }
   174954 
   174955   return p->rc;
   174956 }
   174957 
   174958 static sqlite3 *rbuOpenDbhandle(
   174959   sqlite3rbu *p,
   174960   const char *zName,
   174961   int bUseVfs
   174962 ){
   174963   sqlite3 *db = 0;
   174964   if( p->rc==SQLITE_OK ){
   174965     const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
   174966     p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
   174967     if( p->rc ){
   174968       p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   174969       sqlite3_close(db);
   174970       db = 0;
   174971     }
   174972   }
   174973   return db;
   174974 }
   174975 
   174976 /*
   174977 ** Free an RbuState object allocated by rbuLoadState().
   174978 */
   174979 static void rbuFreeState(RbuState *p){
   174980   if( p ){
   174981     sqlite3_free(p->zTbl);
   174982     sqlite3_free(p->zIdx);
   174983     sqlite3_free(p);
   174984   }
   174985 }
   174986 
   174987 /*
   174988 ** Allocate an RbuState object and load the contents of the rbu_state
   174989 ** table into it. Return a pointer to the new object. It is the
   174990 ** responsibility of the caller to eventually free the object using
   174991 ** sqlite3_free().
   174992 **
   174993 ** If an error occurs, leave an error code and message in the rbu handle
   174994 ** and return NULL.
   174995 */
   174996 static RbuState *rbuLoadState(sqlite3rbu *p){
   174997   RbuState *pRet = 0;
   174998   sqlite3_stmt *pStmt = 0;
   174999   int rc;
   175000   int rc2;
   175001 
   175002   pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
   175003   if( pRet==0 ) return 0;
   175004 
   175005   rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
   175006       sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
   175007   );
   175008   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   175009     switch( sqlite3_column_int(pStmt, 0) ){
   175010       case RBU_STATE_STAGE:
   175011         pRet->eStage = sqlite3_column_int(pStmt, 1);
   175012         if( pRet->eStage!=RBU_STAGE_OAL
   175013          && pRet->eStage!=RBU_STAGE_MOVE
   175014          && pRet->eStage!=RBU_STAGE_CKPT
   175015         ){
   175016           p->rc = SQLITE_CORRUPT;
   175017         }
   175018         break;
   175019 
   175020       case RBU_STATE_TBL:
   175021         pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
   175022         break;
   175023 
   175024       case RBU_STATE_IDX:
   175025         pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
   175026         break;
   175027 
   175028       case RBU_STATE_ROW:
   175029         pRet->nRow = sqlite3_column_int(pStmt, 1);
   175030         break;
   175031 
   175032       case RBU_STATE_PROGRESS:
   175033         pRet->nProgress = sqlite3_column_int64(pStmt, 1);
   175034         break;
   175035 
   175036       case RBU_STATE_CKPT:
   175037         pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
   175038         break;
   175039 
   175040       case RBU_STATE_COOKIE:
   175041         pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
   175042         break;
   175043 
   175044       case RBU_STATE_OALSZ:
   175045         pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
   175046         break;
   175047 
   175048       case RBU_STATE_PHASEONESTEP:
   175049         pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
   175050         break;
   175051 
   175052       default:
   175053         rc = SQLITE_CORRUPT;
   175054         break;
   175055     }
   175056   }
   175057   rc2 = sqlite3_finalize(pStmt);
   175058   if( rc==SQLITE_OK ) rc = rc2;
   175059 
   175060   p->rc = rc;
   175061   return pRet;
   175062 }
   175063 
   175064 
   175065 /*
   175066 ** Open the database handle and attach the RBU database as "rbu". If an
   175067 ** error occurs, leave an error code and message in the RBU handle.
   175068 */
   175069 static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
   175070   assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
   175071   assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
   175072 
   175073   /* Open the RBU database */
   175074   p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
   175075 
   175076   if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
   175077     sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
   175078     if( p->zState==0 ){
   175079       const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
   175080       p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
   175081     }
   175082   }
   175083 
   175084   /* If using separate RBU and state databases, attach the state database to
   175085   ** the RBU db handle now.  */
   175086   if( p->zState ){
   175087     rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
   175088     memcpy(p->zStateDb, "stat", 4);
   175089   }else{
   175090     memcpy(p->zStateDb, "main", 4);
   175091   }
   175092 
   175093 #if 0
   175094   if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
   175095     p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
   175096   }
   175097 #endif
   175098 
   175099   /* If it has not already been created, create the rbu_state table */
   175100   rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
   175101 
   175102 #if 0
   175103   if( rbuIsVacuum(p) ){
   175104     if( p->rc==SQLITE_OK ){
   175105       int rc2;
   175106       int bOk = 0;
   175107       sqlite3_stmt *pCnt = 0;
   175108       p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
   175109           "SELECT count(*) FROM stat.sqlite_master"
   175110       );
   175111       if( p->rc==SQLITE_OK
   175112        && sqlite3_step(pCnt)==SQLITE_ROW
   175113        && 1==sqlite3_column_int(pCnt, 0)
   175114       ){
   175115         bOk = 1;
   175116       }
   175117       rc2 = sqlite3_finalize(pCnt);
   175118       if( p->rc==SQLITE_OK ) p->rc = rc2;
   175119 
   175120       if( p->rc==SQLITE_OK && bOk==0 ){
   175121         p->rc = SQLITE_ERROR;
   175122         p->zErrmsg = sqlite3_mprintf("invalid state database");
   175123       }
   175124 
   175125       if( p->rc==SQLITE_OK ){
   175126         p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
   175127       }
   175128     }
   175129   }
   175130 #endif
   175131 
   175132   if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
   175133     int bOpen = 0;
   175134     int rc;
   175135     p->nRbu = 0;
   175136     p->pRbuFd = 0;
   175137     rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
   175138     if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
   175139     if( p->eStage>=RBU_STAGE_MOVE ){
   175140       bOpen = 1;
   175141     }else{
   175142       RbuState *pState = rbuLoadState(p);
   175143       if( pState ){
   175144         bOpen = (pState->eStage>=RBU_STAGE_MOVE);
   175145         rbuFreeState(pState);
   175146       }
   175147     }
   175148     if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
   175149   }
   175150 
   175151   p->eStage = 0;
   175152   if( p->rc==SQLITE_OK && p->dbMain==0 ){
   175153     if( !rbuIsVacuum(p) ){
   175154       p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
   175155     }else if( p->pRbuFd->pWalFd ){
   175156       if( pbRetry ){
   175157         p->pRbuFd->bNolock = 0;
   175158         sqlite3_close(p->dbRbu);
   175159         sqlite3_close(p->dbMain);
   175160         p->dbMain = 0;
   175161         p->dbRbu = 0;
   175162         *pbRetry = 1;
   175163         return;
   175164       }
   175165       p->rc = SQLITE_ERROR;
   175166       p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
   175167     }else{
   175168       char *zTarget;
   175169       char *zExtra = 0;
   175170       if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
   175171         zExtra = &p->zRbu[5];
   175172         while( *zExtra ){
   175173           if( *zExtra++=='?' ) break;
   175174         }
   175175         if( *zExtra=='\0' ) zExtra = 0;
   175176       }
   175177 
   175178       zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
   175179           sqlite3_db_filename(p->dbRbu, "main"),
   175180           (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
   175181       );
   175182 
   175183       if( zTarget==0 ){
   175184         p->rc = SQLITE_NOMEM;
   175185         return;
   175186       }
   175187       p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
   175188       sqlite3_free(zTarget);
   175189     }
   175190   }
   175191 
   175192   if( p->rc==SQLITE_OK ){
   175193     p->rc = sqlite3_create_function(p->dbMain,
   175194         "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
   175195     );
   175196   }
   175197 
   175198   if( p->rc==SQLITE_OK ){
   175199     p->rc = sqlite3_create_function(p->dbMain,
   175200         "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
   175201     );
   175202   }
   175203 
   175204   if( p->rc==SQLITE_OK ){
   175205     p->rc = sqlite3_create_function(p->dbRbu,
   175206         "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
   175207     );
   175208   }
   175209 
   175210   if( p->rc==SQLITE_OK ){
   175211     p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
   175212   }
   175213   rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
   175214 
   175215   /* Mark the database file just opened as an RBU target database. If
   175216   ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
   175217   ** This is an error.  */
   175218   if( p->rc==SQLITE_OK ){
   175219     p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
   175220   }
   175221 
   175222   if( p->rc==SQLITE_NOTFOUND ){
   175223     p->rc = SQLITE_ERROR;
   175224     p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
   175225   }
   175226 }
   175227 
   175228 /*
   175229 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
   175230 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
   175231 **
   175232 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
   175233 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
   175234 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
   175235 ** three characters, then shorten the suffix on z[] to be the last three
   175236 ** characters of the original suffix.
   175237 **
   175238 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
   175239 ** do the suffix shortening regardless of URI parameter.
   175240 **
   175241 ** Examples:
   175242 **
   175243 **     test.db-journal    =>   test.nal
   175244 **     test.db-wal        =>   test.wal
   175245 **     test.db-shm        =>   test.shm
   175246 **     test.db-mj7f3319fa =>   test.9fa
   175247 */
   175248 static void rbuFileSuffix3(const char *zBase, char *z){
   175249 #ifdef SQLITE_ENABLE_8_3_NAMES
   175250 #if SQLITE_ENABLE_8_3_NAMES<2
   175251   if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
   175252 #endif
   175253   {
   175254     int i, sz;
   175255     sz = (int)strlen(z)&0xffffff;
   175256     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
   175257     if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
   175258   }
   175259 #endif
   175260 }
   175261 
   175262 /*
   175263 ** Return the current wal-index header checksum for the target database
   175264 ** as a 64-bit integer.
   175265 **
   175266 ** The checksum is store in the first page of xShmMap memory as an 8-byte
   175267 ** blob starting at byte offset 40.
   175268 */
   175269 static i64 rbuShmChecksum(sqlite3rbu *p){
   175270   i64 iRet = 0;
   175271   if( p->rc==SQLITE_OK ){
   175272     sqlite3_file *pDb = p->pTargetFd->pReal;
   175273     u32 volatile *ptr;
   175274     p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
   175275     if( p->rc==SQLITE_OK ){
   175276       iRet = ((i64)ptr[10] << 32) + ptr[11];
   175277     }
   175278   }
   175279   return iRet;
   175280 }
   175281 
   175282 /*
   175283 ** This function is called as part of initializing or reinitializing an
   175284 ** incremental checkpoint.
   175285 **
   175286 ** It populates the sqlite3rbu.aFrame[] array with the set of
   175287 ** (wal frame -> db page) copy operations required to checkpoint the
   175288 ** current wal file, and obtains the set of shm locks required to safely
   175289 ** perform the copy operations directly on the file-system.
   175290 **
   175291 ** If argument pState is not NULL, then the incremental checkpoint is
   175292 ** being resumed. In this case, if the checksum of the wal-index-header
   175293 ** following recovery is not the same as the checksum saved in the RbuState
   175294 ** object, then the rbu handle is set to DONE state. This occurs if some
   175295 ** other client appends a transaction to the wal file in the middle of
   175296 ** an incremental checkpoint.
   175297 */
   175298 static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
   175299 
   175300   /* If pState is NULL, then the wal file may not have been opened and
   175301   ** recovered. Running a read-statement here to ensure that doing so
   175302   ** does not interfere with the "capture" process below.  */
   175303   if( pState==0 ){
   175304     p->eStage = 0;
   175305     if( p->rc==SQLITE_OK ){
   175306       p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
   175307     }
   175308   }
   175309 
   175310   /* Assuming no error has occurred, run a "restart" checkpoint with the
   175311   ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
   175312   ** special behaviour in the rbu VFS:
   175313   **
   175314   **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
   175315   **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
   175316   **     proceed with running a passive checkpoint instead of failing).
   175317   **
   175318   **   * Attempts to read from the *-wal file or write to the database file
   175319   **     do not perform any IO. Instead, the frame/page combinations that
   175320   **     would be read/written are recorded in the sqlite3rbu.aFrame[]
   175321   **     array.
   175322   **
   175323   **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
   175324   **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
   175325   **     no-ops. These locks will not be released until the connection
   175326   **     is closed.
   175327   **
   175328   **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
   175329   **     error.
   175330   **
   175331   ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
   175332   ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
   175333   ** array populated with a set of (frame -> page) mappings. Because the
   175334   ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
   175335   ** data from the wal file into the database file according to the
   175336   ** contents of aFrame[].
   175337   */
   175338   if( p->rc==SQLITE_OK ){
   175339     int rc2;
   175340     p->eStage = RBU_STAGE_CAPTURE;
   175341     rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
   175342     if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
   175343   }
   175344 
   175345   if( p->rc==SQLITE_OK && p->nFrame>0 ){
   175346     p->eStage = RBU_STAGE_CKPT;
   175347     p->nStep = (pState ? pState->nRow : 0);
   175348     p->aBuf = rbuMalloc(p, p->pgsz);
   175349     p->iWalCksum = rbuShmChecksum(p);
   175350   }
   175351 
   175352   if( p->rc==SQLITE_OK ){
   175353     if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
   175354       p->rc = SQLITE_DONE;
   175355       p->eStage = RBU_STAGE_DONE;
   175356     }else{
   175357       int nSectorSize;
   175358       sqlite3_file *pDb = p->pTargetFd->pReal;
   175359       sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
   175360       assert( p->nPagePerSector==0 );
   175361       nSectorSize = pDb->pMethods->xSectorSize(pDb);
   175362       if( nSectorSize>p->pgsz ){
   175363         p->nPagePerSector = nSectorSize / p->pgsz;
   175364       }else{
   175365         p->nPagePerSector = 1;
   175366       }
   175367 
   175368       /* Call xSync() on the wal file. This causes SQLite to sync the
   175369       ** directory in which the target database and the wal file reside, in
   175370       ** case it has not been synced since the rename() call in
   175371       ** rbuMoveOalFile(). */
   175372       p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
   175373     }
   175374   }
   175375 }
   175376 
   175377 /*
   175378 ** Called when iAmt bytes are read from offset iOff of the wal file while
   175379 ** the rbu object is in capture mode. Record the frame number of the frame
   175380 ** being read in the aFrame[] array.
   175381 */
   175382 static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
   175383   const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
   175384   u32 iFrame;
   175385 
   175386   if( pRbu->mLock!=mReq ){
   175387     pRbu->rc = SQLITE_BUSY;
   175388     return SQLITE_INTERNAL;
   175389   }
   175390 
   175391   pRbu->pgsz = iAmt;
   175392   if( pRbu->nFrame==pRbu->nFrameAlloc ){
   175393     int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
   175394     RbuFrame *aNew;
   175395     aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
   175396     if( aNew==0 ) return SQLITE_NOMEM;
   175397     pRbu->aFrame = aNew;
   175398     pRbu->nFrameAlloc = nNew;
   175399   }
   175400 
   175401   iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
   175402   if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
   175403   pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
   175404   pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
   175405   pRbu->nFrame++;
   175406   return SQLITE_OK;
   175407 }
   175408 
   175409 /*
   175410 ** Called when a page of data is written to offset iOff of the database
   175411 ** file while the rbu handle is in capture mode. Record the page number
   175412 ** of the page being written in the aFrame[] array.
   175413 */
   175414 static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
   175415   pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
   175416   return SQLITE_OK;
   175417 }
   175418 
   175419 /*
   175420 ** This is called as part of an incremental checkpoint operation. Copy
   175421 ** a single frame of data from the wal file into the database file, as
   175422 ** indicated by the RbuFrame object.
   175423 */
   175424 static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
   175425   sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
   175426   sqlite3_file *pDb = p->pTargetFd->pReal;
   175427   i64 iOff;
   175428 
   175429   assert( p->rc==SQLITE_OK );
   175430   iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
   175431   p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
   175432   if( p->rc ) return;
   175433 
   175434   iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
   175435   p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
   175436 }
   175437 
   175438 
   175439 /*
   175440 ** Take an EXCLUSIVE lock on the database file.
   175441 */
   175442 static void rbuLockDatabase(sqlite3rbu *p){
   175443   sqlite3_file *pReal = p->pTargetFd->pReal;
   175444   assert( p->rc==SQLITE_OK );
   175445   p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
   175446   if( p->rc==SQLITE_OK ){
   175447     p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
   175448   }
   175449 }
   175450 
   175451 #if defined(_WIN32_WCE)
   175452 static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
   175453   int nChar;
   175454   LPWSTR zWideFilename;
   175455 
   175456   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   175457   if( nChar==0 ){
   175458     return 0;
   175459   }
   175460   zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
   175461   if( zWideFilename==0 ){
   175462     return 0;
   175463   }
   175464   memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
   175465   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
   175466                                 nChar);
   175467   if( nChar==0 ){
   175468     sqlite3_free(zWideFilename);
   175469     zWideFilename = 0;
   175470   }
   175471   return zWideFilename;
   175472 }
   175473 #endif
   175474 
   175475 /*
   175476 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
   175477 ** on the database file. This proc moves the *-oal file to the *-wal path,
   175478 ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
   175479 ** If an error occurs, leave an error code and error message in the rbu
   175480 ** handle.
   175481 */
   175482 static void rbuMoveOalFile(sqlite3rbu *p){
   175483   const char *zBase = sqlite3_db_filename(p->dbMain, "main");
   175484   const char *zMove = zBase;
   175485   char *zOal;
   175486   char *zWal;
   175487 
   175488   if( rbuIsVacuum(p) ){
   175489     zMove = sqlite3_db_filename(p->dbRbu, "main");
   175490   }
   175491   zOal = sqlite3_mprintf("%s-oal", zMove);
   175492   zWal = sqlite3_mprintf("%s-wal", zMove);
   175493 
   175494   assert( p->eStage==RBU_STAGE_MOVE );
   175495   assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
   175496   if( zWal==0 || zOal==0 ){
   175497     p->rc = SQLITE_NOMEM;
   175498   }else{
   175499     /* Move the *-oal file to *-wal. At this point connection p->db is
   175500     ** holding a SHARED lock on the target database file (because it is
   175501     ** in WAL mode). So no other connection may be writing the db.
   175502     **
   175503     ** In order to ensure that there are no database readers, an EXCLUSIVE
   175504     ** lock is obtained here before the *-oal is moved to *-wal.
   175505     */
   175506     rbuLockDatabase(p);
   175507     if( p->rc==SQLITE_OK ){
   175508       rbuFileSuffix3(zBase, zWal);
   175509       rbuFileSuffix3(zBase, zOal);
   175510 
   175511       /* Re-open the databases. */
   175512       rbuObjIterFinalize(&p->objiter);
   175513       sqlite3_close(p->dbRbu);
   175514       sqlite3_close(p->dbMain);
   175515       p->dbMain = 0;
   175516       p->dbRbu = 0;
   175517 
   175518 #if defined(_WIN32_WCE)
   175519       {
   175520         LPWSTR zWideOal;
   175521         LPWSTR zWideWal;
   175522 
   175523         zWideOal = rbuWinUtf8ToUnicode(zOal);
   175524         if( zWideOal ){
   175525           zWideWal = rbuWinUtf8ToUnicode(zWal);
   175526           if( zWideWal ){
   175527             if( MoveFileW(zWideOal, zWideWal) ){
   175528               p->rc = SQLITE_OK;
   175529             }else{
   175530               p->rc = SQLITE_IOERR;
   175531             }
   175532             sqlite3_free(zWideWal);
   175533           }else{
   175534             p->rc = SQLITE_IOERR_NOMEM;
   175535           }
   175536           sqlite3_free(zWideOal);
   175537         }else{
   175538           p->rc = SQLITE_IOERR_NOMEM;
   175539         }
   175540       }
   175541 #else
   175542       p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
   175543 #endif
   175544 
   175545       if( p->rc==SQLITE_OK ){
   175546         rbuOpenDatabase(p, 0);
   175547         rbuSetupCheckpoint(p, 0);
   175548       }
   175549     }
   175550   }
   175551 
   175552   sqlite3_free(zWal);
   175553   sqlite3_free(zOal);
   175554 }
   175555 
   175556 /*
   175557 ** The SELECT statement iterating through the keys for the current object
   175558 ** (p->objiter.pSelect) currently points to a valid row. This function
   175559 ** determines the type of operation requested by this row and returns
   175560 ** one of the following values to indicate the result:
   175561 **
   175562 **     * RBU_INSERT
   175563 **     * RBU_DELETE
   175564 **     * RBU_IDX_DELETE
   175565 **     * RBU_UPDATE
   175566 **
   175567 ** If RBU_UPDATE is returned, then output variable *pzMask is set to
   175568 ** point to the text value indicating the columns to update.
   175569 **
   175570 ** If the rbu_control field contains an invalid value, an error code and
   175571 ** message are left in the RBU handle and zero returned.
   175572 */
   175573 static int rbuStepType(sqlite3rbu *p, const char **pzMask){
   175574   int iCol = p->objiter.nCol;     /* Index of rbu_control column */
   175575   int res = 0;                    /* Return value */
   175576 
   175577   switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
   175578     case SQLITE_INTEGER: {
   175579       int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
   175580       switch( iVal ){
   175581         case 0: res = RBU_INSERT;     break;
   175582         case 1: res = RBU_DELETE;     break;
   175583         case 2: res = RBU_REPLACE;    break;
   175584         case 3: res = RBU_IDX_DELETE; break;
   175585         case 4: res = RBU_IDX_INSERT; break;
   175586       }
   175587       break;
   175588     }
   175589 
   175590     case SQLITE_TEXT: {
   175591       const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
   175592       if( z==0 ){
   175593         p->rc = SQLITE_NOMEM;
   175594       }else{
   175595         *pzMask = (const char*)z;
   175596       }
   175597       res = RBU_UPDATE;
   175598 
   175599       break;
   175600     }
   175601 
   175602     default:
   175603       break;
   175604   }
   175605 
   175606   if( res==0 ){
   175607     rbuBadControlError(p);
   175608   }
   175609   return res;
   175610 }
   175611 
   175612 #ifdef SQLITE_DEBUG
   175613 /*
   175614 ** Assert that column iCol of statement pStmt is named zName.
   175615 */
   175616 static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
   175617   const char *zCol = sqlite3_column_name(pStmt, iCol);
   175618   assert( 0==sqlite3_stricmp(zName, zCol) );
   175619 }
   175620 #else
   175621 # define assertColumnName(x,y,z)
   175622 #endif
   175623 
   175624 /*
   175625 ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
   175626 ** RBU_IDX_DELETE. This function performs the work of a single
   175627 ** sqlite3rbu_step() call for the type of operation specified by eType.
   175628 */
   175629 static void rbuStepOneOp(sqlite3rbu *p, int eType){
   175630   RbuObjIter *pIter = &p->objiter;
   175631   sqlite3_value *pVal;
   175632   sqlite3_stmt *pWriter;
   175633   int i;
   175634 
   175635   assert( p->rc==SQLITE_OK );
   175636   assert( eType!=RBU_DELETE || pIter->zIdx==0 );
   175637   assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
   175638        || eType==RBU_INSERT || eType==RBU_IDX_INSERT
   175639   );
   175640 
   175641   /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
   175642   ** statement below does actually delete a row, nPhaseOneStep will be
   175643   ** incremented by the same amount when SQL function rbu_tmp_insert()
   175644   ** is invoked by the trigger.  */
   175645   if( eType==RBU_DELETE ){
   175646     p->nPhaseOneStep -= p->objiter.nIndex;
   175647   }
   175648 
   175649   if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
   175650     pWriter = pIter->pDelete;
   175651   }else{
   175652     pWriter = pIter->pInsert;
   175653   }
   175654 
   175655   for(i=0; i<pIter->nCol; i++){
   175656     /* If this is an INSERT into a table b-tree and the table has an
   175657     ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
   175658     ** to write a NULL into the IPK column. That is not permitted.  */
   175659     if( eType==RBU_INSERT
   175660      && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
   175661      && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
   175662     ){
   175663       p->rc = SQLITE_MISMATCH;
   175664       p->zErrmsg = sqlite3_mprintf("datatype mismatch");
   175665       return;
   175666     }
   175667 
   175668     if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
   175669       continue;
   175670     }
   175671 
   175672     pVal = sqlite3_column_value(pIter->pSelect, i);
   175673     p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
   175674     if( p->rc ) return;
   175675   }
   175676   if( pIter->zIdx==0 ){
   175677     if( pIter->eType==RBU_PK_VTAB
   175678      || pIter->eType==RBU_PK_NONE
   175679      || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
   175680     ){
   175681       /* For a virtual table, or a table with no primary key, the
   175682       ** SELECT statement is:
   175683       **
   175684       **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
   175685       **
   175686       ** Hence column_value(pIter->nCol+1).
   175687       */
   175688       assertColumnName(pIter->pSelect, pIter->nCol+1,
   175689           rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
   175690       );
   175691       pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
   175692       p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
   175693     }
   175694   }
   175695   if( p->rc==SQLITE_OK ){
   175696     sqlite3_step(pWriter);
   175697     p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
   175698   }
   175699 }
   175700 
   175701 /*
   175702 ** This function does the work for an sqlite3rbu_step() call.
   175703 **
   175704 ** The object-iterator (p->objiter) currently points to a valid object,
   175705 ** and the input cursor (p->objiter.pSelect) currently points to a valid
   175706 ** input row. Perform whatever processing is required and return.
   175707 **
   175708 ** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
   175709 ** and message is left in the RBU handle and a copy of the error code
   175710 ** returned.
   175711 */
   175712 static int rbuStep(sqlite3rbu *p){
   175713   RbuObjIter *pIter = &p->objiter;
   175714   const char *zMask = 0;
   175715   int eType = rbuStepType(p, &zMask);
   175716 
   175717   if( eType ){
   175718     assert( eType==RBU_INSERT     || eType==RBU_DELETE
   175719          || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
   175720          || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
   175721     );
   175722     assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
   175723 
   175724     if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
   175725       rbuBadControlError(p);
   175726     }
   175727     else if( eType==RBU_REPLACE ){
   175728       if( pIter->zIdx==0 ){
   175729         p->nPhaseOneStep += p->objiter.nIndex;
   175730         rbuStepOneOp(p, RBU_DELETE);
   175731       }
   175732       if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
   175733     }
   175734     else if( eType!=RBU_UPDATE ){
   175735       rbuStepOneOp(p, eType);
   175736     }
   175737     else{
   175738       sqlite3_value *pVal;
   175739       sqlite3_stmt *pUpdate = 0;
   175740       assert( eType==RBU_UPDATE );
   175741       p->nPhaseOneStep -= p->objiter.nIndex;
   175742       rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
   175743       if( pUpdate ){
   175744         int i;
   175745         for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
   175746           char c = zMask[pIter->aiSrcOrder[i]];
   175747           pVal = sqlite3_column_value(pIter->pSelect, i);
   175748           if( pIter->abTblPk[i] || c!='.' ){
   175749             p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
   175750           }
   175751         }
   175752         if( p->rc==SQLITE_OK
   175753          && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
   175754         ){
   175755           /* Bind the rbu_rowid value to column _rowid_ */
   175756           assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
   175757           pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
   175758           p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
   175759         }
   175760         if( p->rc==SQLITE_OK ){
   175761           sqlite3_step(pUpdate);
   175762           p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
   175763         }
   175764       }
   175765     }
   175766   }
   175767   return p->rc;
   175768 }
   175769 
   175770 /*
   175771 ** Increment the schema cookie of the main database opened by p->dbMain.
   175772 **
   175773 ** Or, if this is an RBU vacuum, set the schema cookie of the main db
   175774 ** opened by p->dbMain to one more than the schema cookie of the main
   175775 ** db opened by p->dbRbu.
   175776 */
   175777 static void rbuIncrSchemaCookie(sqlite3rbu *p){
   175778   if( p->rc==SQLITE_OK ){
   175779     sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
   175780     int iCookie = 1000000;
   175781     sqlite3_stmt *pStmt;
   175782 
   175783     p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
   175784         "PRAGMA schema_version"
   175785     );
   175786     if( p->rc==SQLITE_OK ){
   175787       /* Coverage: it may be that this sqlite3_step() cannot fail. There
   175788       ** is already a transaction open, so the prepared statement cannot
   175789       ** throw an SQLITE_SCHEMA exception. The only database page the
   175790       ** statement reads is page 1, which is guaranteed to be in the cache.
   175791       ** And no memory allocations are required.  */
   175792       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   175793         iCookie = sqlite3_column_int(pStmt, 0);
   175794       }
   175795       rbuFinalize(p, pStmt);
   175796     }
   175797     if( p->rc==SQLITE_OK ){
   175798       rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
   175799     }
   175800   }
   175801 }
   175802 
   175803 /*
   175804 ** Update the contents of the rbu_state table within the rbu database. The
   175805 ** value stored in the RBU_STATE_STAGE column is eStage. All other values
   175806 ** are determined by inspecting the rbu handle passed as the first argument.
   175807 */
   175808 static void rbuSaveState(sqlite3rbu *p, int eStage){
   175809   if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
   175810     sqlite3_stmt *pInsert = 0;
   175811     rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
   175812     int rc;
   175813 
   175814     assert( p->zErrmsg==0 );
   175815     rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
   175816         sqlite3_mprintf(
   175817           "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
   175818           "(%d, %d), "
   175819           "(%d, %Q), "
   175820           "(%d, %Q), "
   175821           "(%d, %d), "
   175822           "(%d, %d), "
   175823           "(%d, %lld), "
   175824           "(%d, %lld), "
   175825           "(%d, %lld), "
   175826           "(%d, %lld) ",
   175827           p->zStateDb,
   175828           RBU_STATE_STAGE, eStage,
   175829           RBU_STATE_TBL, p->objiter.zTbl,
   175830           RBU_STATE_IDX, p->objiter.zIdx,
   175831           RBU_STATE_ROW, p->nStep,
   175832           RBU_STATE_PROGRESS, p->nProgress,
   175833           RBU_STATE_CKPT, p->iWalCksum,
   175834           RBU_STATE_COOKIE, (i64)pFd->iCookie,
   175835           RBU_STATE_OALSZ, p->iOalSz,
   175836           RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
   175837       )
   175838     );
   175839     assert( pInsert==0 || rc==SQLITE_OK );
   175840 
   175841     if( rc==SQLITE_OK ){
   175842       sqlite3_step(pInsert);
   175843       rc = sqlite3_finalize(pInsert);
   175844     }
   175845     if( rc!=SQLITE_OK ) p->rc = rc;
   175846   }
   175847 }
   175848 
   175849 
   175850 /*
   175851 ** The second argument passed to this function is the name of a PRAGMA
   175852 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
   175853 ** This function executes the following on sqlite3rbu.dbRbu:
   175854 **
   175855 **   "PRAGMA main.$zPragma"
   175856 **
   175857 ** where $zPragma is the string passed as the second argument, then
   175858 ** on sqlite3rbu.dbMain:
   175859 **
   175860 **   "PRAGMA main.$zPragma = $val"
   175861 **
   175862 ** where $val is the value returned by the first PRAGMA invocation.
   175863 **
   175864 ** In short, it copies the value  of the specified PRAGMA setting from
   175865 ** dbRbu to dbMain.
   175866 */
   175867 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
   175868   if( p->rc==SQLITE_OK ){
   175869     sqlite3_stmt *pPragma = 0;
   175870     p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
   175871         sqlite3_mprintf("PRAGMA main.%s", zPragma)
   175872     );
   175873     if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
   175874       p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
   175875           zPragma, sqlite3_column_int(pPragma, 0)
   175876       );
   175877     }
   175878     rbuFinalize(p, pPragma);
   175879   }
   175880 }
   175881 
   175882 /*
   175883 ** The RBU handle passed as the only argument has just been opened and
   175884 ** the state database is empty. If this RBU handle was opened for an
   175885 ** RBU vacuum operation, create the schema in the target db.
   175886 */
   175887 static void rbuCreateTargetSchema(sqlite3rbu *p){
   175888   sqlite3_stmt *pSql = 0;
   175889   sqlite3_stmt *pInsert = 0;
   175890 
   175891   assert( rbuIsVacuum(p) );
   175892   p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
   175893   if( p->rc==SQLITE_OK ){
   175894     p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
   175895       "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
   175896       " AND name!='sqlite_sequence' "
   175897       " ORDER BY type DESC"
   175898     );
   175899   }
   175900 
   175901   while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
   175902     const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
   175903     p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
   175904   }
   175905   rbuFinalize(p, pSql);
   175906   if( p->rc!=SQLITE_OK ) return;
   175907 
   175908   if( p->rc==SQLITE_OK ){
   175909     p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
   175910         "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
   175911     );
   175912   }
   175913 
   175914   if( p->rc==SQLITE_OK ){
   175915     p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
   175916         "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
   175917     );
   175918   }
   175919 
   175920   while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
   175921     int i;
   175922     for(i=0; i<5; i++){
   175923       sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
   175924     }
   175925     sqlite3_step(pInsert);
   175926     p->rc = sqlite3_reset(pInsert);
   175927   }
   175928   if( p->rc==SQLITE_OK ){
   175929     p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
   175930   }
   175931 
   175932   rbuFinalize(p, pSql);
   175933   rbuFinalize(p, pInsert);
   175934 }
   175935 
   175936 /*
   175937 ** Step the RBU object.
   175938 */
   175939 SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
   175940   if( p ){
   175941     switch( p->eStage ){
   175942       case RBU_STAGE_OAL: {
   175943         RbuObjIter *pIter = &p->objiter;
   175944 
   175945         /* If this is an RBU vacuum operation and the state table was empty
   175946         ** when this handle was opened, create the target database schema. */
   175947         if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
   175948           rbuCreateTargetSchema(p);
   175949           rbuCopyPragma(p, "user_version");
   175950           rbuCopyPragma(p, "application_id");
   175951         }
   175952 
   175953         while( p->rc==SQLITE_OK && pIter->zTbl ){
   175954 
   175955           if( pIter->bCleanup ){
   175956             /* Clean up the rbu_tmp_xxx table for the previous table. It
   175957             ** cannot be dropped as there are currently active SQL statements.
   175958             ** But the contents can be deleted.  */
   175959             if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
   175960               rbuMPrintfExec(p, p->dbRbu,
   175961                   "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
   175962               );
   175963             }
   175964           }else{
   175965             rbuObjIterPrepareAll(p, pIter, 0);
   175966 
   175967             /* Advance to the next row to process. */
   175968             if( p->rc==SQLITE_OK ){
   175969               int rc = sqlite3_step(pIter->pSelect);
   175970               if( rc==SQLITE_ROW ){
   175971                 p->nProgress++;
   175972                 p->nStep++;
   175973                 return rbuStep(p);
   175974               }
   175975               p->rc = sqlite3_reset(pIter->pSelect);
   175976               p->nStep = 0;
   175977             }
   175978           }
   175979 
   175980           rbuObjIterNext(p, pIter);
   175981         }
   175982 
   175983         if( p->rc==SQLITE_OK ){
   175984           assert( pIter->zTbl==0 );
   175985           rbuSaveState(p, RBU_STAGE_MOVE);
   175986           rbuIncrSchemaCookie(p);
   175987           if( p->rc==SQLITE_OK ){
   175988             p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
   175989           }
   175990           if( p->rc==SQLITE_OK ){
   175991             p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
   175992           }
   175993           p->eStage = RBU_STAGE_MOVE;
   175994         }
   175995         break;
   175996       }
   175997 
   175998       case RBU_STAGE_MOVE: {
   175999         if( p->rc==SQLITE_OK ){
   176000           rbuMoveOalFile(p);
   176001           p->nProgress++;
   176002         }
   176003         break;
   176004       }
   176005 
   176006       case RBU_STAGE_CKPT: {
   176007         if( p->rc==SQLITE_OK ){
   176008           if( p->nStep>=p->nFrame ){
   176009             sqlite3_file *pDb = p->pTargetFd->pReal;
   176010 
   176011             /* Sync the db file */
   176012             p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
   176013 
   176014             /* Update nBackfill */
   176015             if( p->rc==SQLITE_OK ){
   176016               void volatile *ptr;
   176017               p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
   176018               if( p->rc==SQLITE_OK ){
   176019                 ((u32 volatile*)ptr)[24] = p->iMaxFrame;
   176020               }
   176021             }
   176022 
   176023             if( p->rc==SQLITE_OK ){
   176024               p->eStage = RBU_STAGE_DONE;
   176025               p->rc = SQLITE_DONE;
   176026             }
   176027           }else{
   176028             /* At one point the following block copied a single frame from the
   176029             ** wal file to the database file. So that one call to sqlite3rbu_step()
   176030             ** checkpointed a single frame.
   176031             **
   176032             ** However, if the sector-size is larger than the page-size, and the
   176033             ** application calls sqlite3rbu_savestate() or close() immediately
   176034             ** after this step, then rbu_step() again, then a power failure occurs,
   176035             ** then the database page written here may be damaged. Work around
   176036             ** this by checkpointing frames until the next page in the aFrame[]
   176037             ** lies on a different disk sector to the current one. */
   176038             u32 iSector;
   176039             do{
   176040               RbuFrame *pFrame = &p->aFrame[p->nStep];
   176041               iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
   176042               rbuCheckpointFrame(p, pFrame);
   176043               p->nStep++;
   176044             }while( p->nStep<p->nFrame
   176045                  && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
   176046                  && p->rc==SQLITE_OK
   176047             );
   176048           }
   176049           p->nProgress++;
   176050         }
   176051         break;
   176052       }
   176053 
   176054       default:
   176055         break;
   176056     }
   176057     return p->rc;
   176058   }else{
   176059     return SQLITE_NOMEM;
   176060   }
   176061 }
   176062 
   176063 /*
   176064 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
   176065 ** otherwise. Either or both argument may be NULL. Two NULL values are
   176066 ** considered equal, and NULL is considered distinct from all other values.
   176067 */
   176068 static int rbuStrCompare(const char *z1, const char *z2){
   176069   if( z1==0 && z2==0 ) return 0;
   176070   if( z1==0 || z2==0 ) return 1;
   176071   return (sqlite3_stricmp(z1, z2)!=0);
   176072 }
   176073 
   176074 /*
   176075 ** This function is called as part of sqlite3rbu_open() when initializing
   176076 ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
   176077 ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
   176078 ** things so that the next call to sqlite3rbu_step() continues on from
   176079 ** where the previous rbu handle left off.
   176080 **
   176081 ** If an error occurs, an error code and error message are left in the
   176082 ** rbu handle passed as the first argument.
   176083 */
   176084 static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
   176085   assert( p->rc==SQLITE_OK );
   176086   if( pState->zTbl ){
   176087     RbuObjIter *pIter = &p->objiter;
   176088     int rc = SQLITE_OK;
   176089 
   176090     while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
   176091        || rbuStrCompare(pIter->zIdx, pState->zIdx)
   176092        || rbuStrCompare(pIter->zTbl, pState->zTbl)
   176093     )){
   176094       rc = rbuObjIterNext(p, pIter);
   176095     }
   176096 
   176097     if( rc==SQLITE_OK && !pIter->zTbl ){
   176098       rc = SQLITE_ERROR;
   176099       p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
   176100     }
   176101 
   176102     if( rc==SQLITE_OK ){
   176103       p->nStep = pState->nRow;
   176104       rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
   176105     }
   176106 
   176107     p->rc = rc;
   176108   }
   176109 }
   176110 
   176111 /*
   176112 ** If there is a "*-oal" file in the file-system corresponding to the
   176113 ** target database in the file-system, delete it. If an error occurs,
   176114 ** leave an error code and error message in the rbu handle.
   176115 */
   176116 static void rbuDeleteOalFile(sqlite3rbu *p){
   176117   char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
   176118   if( zOal ){
   176119     sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
   176120     assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
   176121     pVfs->xDelete(pVfs, zOal, 0);
   176122     sqlite3_free(zOal);
   176123   }
   176124 }
   176125 
   176126 /*
   176127 ** Allocate a private rbu VFS for the rbu handle passed as the only
   176128 ** argument. This VFS will be used unless the call to sqlite3rbu_open()
   176129 ** specified a URI with a vfs=? option in place of a target database
   176130 ** file name.
   176131 */
   176132 static void rbuCreateVfs(sqlite3rbu *p){
   176133   int rnd;
   176134   char zRnd[64];
   176135 
   176136   assert( p->rc==SQLITE_OK );
   176137   sqlite3_randomness(sizeof(int), (void*)&rnd);
   176138   sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
   176139   p->rc = sqlite3rbu_create_vfs(zRnd, 0);
   176140   if( p->rc==SQLITE_OK ){
   176141     sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
   176142     assert( pVfs );
   176143     p->zVfsName = pVfs->zName;
   176144     ((rbu_vfs*)pVfs)->pRbu = p;
   176145   }
   176146 }
   176147 
   176148 /*
   176149 ** Destroy the private VFS created for the rbu handle passed as the only
   176150 ** argument by an earlier call to rbuCreateVfs().
   176151 */
   176152 static void rbuDeleteVfs(sqlite3rbu *p){
   176153   if( p->zVfsName ){
   176154     sqlite3rbu_destroy_vfs(p->zVfsName);
   176155     p->zVfsName = 0;
   176156   }
   176157 }
   176158 
   176159 /*
   176160 ** This user-defined SQL function is invoked with a single argument - the
   176161 ** name of a table expected to appear in the target database. It returns
   176162 ** the number of auxilliary indexes on the table.
   176163 */
   176164 static void rbuIndexCntFunc(
   176165   sqlite3_context *pCtx,
   176166   int nVal,
   176167   sqlite3_value **apVal
   176168 ){
   176169   sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
   176170   sqlite3_stmt *pStmt = 0;
   176171   char *zErrmsg = 0;
   176172   int rc;
   176173 
   176174   assert( nVal==1 );
   176175 
   176176   rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
   176177       sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
   176178         "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
   176179   );
   176180   if( rc!=SQLITE_OK ){
   176181     sqlite3_result_error(pCtx, zErrmsg, -1);
   176182   }else{
   176183     int nIndex = 0;
   176184     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   176185       nIndex = sqlite3_column_int(pStmt, 0);
   176186     }
   176187     rc = sqlite3_finalize(pStmt);
   176188     if( rc==SQLITE_OK ){
   176189       sqlite3_result_int(pCtx, nIndex);
   176190     }else{
   176191       sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
   176192     }
   176193   }
   176194 
   176195   sqlite3_free(zErrmsg);
   176196 }
   176197 
   176198 /*
   176199 ** If the RBU database contains the rbu_count table, use it to initialize
   176200 ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
   176201 ** is assumed to contain the same columns as:
   176202 **
   176203 **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
   176204 **
   176205 ** There should be one row in the table for each data_xxx table in the
   176206 ** database. The 'tbl' column should contain the name of a data_xxx table,
   176207 ** and the cnt column the number of rows it contains.
   176208 **
   176209 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
   176210 ** for all rows in the rbu_count table, where nIndex is the number of
   176211 ** indexes on the corresponding target database table.
   176212 */
   176213 static void rbuInitPhaseOneSteps(sqlite3rbu *p){
   176214   if( p->rc==SQLITE_OK ){
   176215     sqlite3_stmt *pStmt = 0;
   176216     int bExists = 0;                /* True if rbu_count exists */
   176217 
   176218     p->nPhaseOneStep = -1;
   176219 
   176220     p->rc = sqlite3_create_function(p->dbRbu,
   176221         "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
   176222     );
   176223 
   176224     /* Check for the rbu_count table. If it does not exist, or if an error
   176225     ** occurs, nPhaseOneStep will be left set to -1. */
   176226     if( p->rc==SQLITE_OK ){
   176227       p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
   176228           "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
   176229       );
   176230     }
   176231     if( p->rc==SQLITE_OK ){
   176232       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   176233         bExists = 1;
   176234       }
   176235       p->rc = sqlite3_finalize(pStmt);
   176236     }
   176237 
   176238     if( p->rc==SQLITE_OK && bExists ){
   176239       p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
   176240           "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
   176241           "FROM rbu_count"
   176242       );
   176243       if( p->rc==SQLITE_OK ){
   176244         if( SQLITE_ROW==sqlite3_step(pStmt) ){
   176245           p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
   176246         }
   176247         p->rc = sqlite3_finalize(pStmt);
   176248       }
   176249     }
   176250   }
   176251 }
   176252 
   176253 
   176254 static sqlite3rbu *openRbuHandle(
   176255   const char *zTarget,
   176256   const char *zRbu,
   176257   const char *zState
   176258 ){
   176259   sqlite3rbu *p;
   176260   size_t nTarget = zTarget ? strlen(zTarget) : 0;
   176261   size_t nRbu = strlen(zRbu);
   176262   size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
   176263 
   176264   p = (sqlite3rbu*)sqlite3_malloc64(nByte);
   176265   if( p ){
   176266     RbuState *pState = 0;
   176267 
   176268     /* Create the custom VFS. */
   176269     memset(p, 0, sizeof(sqlite3rbu));
   176270     rbuCreateVfs(p);
   176271 
   176272     /* Open the target, RBU and state databases */
   176273     if( p->rc==SQLITE_OK ){
   176274       char *pCsr = (char*)&p[1];
   176275       int bRetry = 0;
   176276       if( zTarget ){
   176277         p->zTarget = pCsr;
   176278         memcpy(p->zTarget, zTarget, nTarget+1);
   176279         pCsr += nTarget+1;
   176280       }
   176281       p->zRbu = pCsr;
   176282       memcpy(p->zRbu, zRbu, nRbu+1);
   176283       pCsr += nRbu+1;
   176284       if( zState ){
   176285         p->zState = rbuMPrintf(p, "%s", zState);
   176286       }
   176287 
   176288       /* If the first attempt to open the database file fails and the bRetry
   176289       ** flag it set, this means that the db was not opened because it seemed
   176290       ** to be a wal-mode db. But, this may have happened due to an earlier
   176291       ** RBU vacuum operation leaving an old wal file in the directory.
   176292       ** If this is the case, it will have been checkpointed and deleted
   176293       ** when the handle was closed and a second attempt to open the
   176294       ** database may succeed.  */
   176295       rbuOpenDatabase(p, &bRetry);
   176296       if( bRetry ){
   176297         rbuOpenDatabase(p, 0);
   176298       }
   176299     }
   176300 
   176301     if( p->rc==SQLITE_OK ){
   176302       pState = rbuLoadState(p);
   176303       assert( pState || p->rc!=SQLITE_OK );
   176304       if( p->rc==SQLITE_OK ){
   176305 
   176306         if( pState->eStage==0 ){
   176307           rbuDeleteOalFile(p);
   176308           rbuInitPhaseOneSteps(p);
   176309           p->eStage = RBU_STAGE_OAL;
   176310         }else{
   176311           p->eStage = pState->eStage;
   176312           p->nPhaseOneStep = pState->nPhaseOneStep;
   176313         }
   176314         p->nProgress = pState->nProgress;
   176315         p->iOalSz = pState->iOalSz;
   176316       }
   176317     }
   176318     assert( p->rc!=SQLITE_OK || p->eStage!=0 );
   176319 
   176320     if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
   176321       if( p->eStage==RBU_STAGE_OAL ){
   176322         p->rc = SQLITE_ERROR;
   176323         p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
   176324       }else if( p->eStage==RBU_STAGE_MOVE ){
   176325         p->eStage = RBU_STAGE_CKPT;
   176326         p->nStep = 0;
   176327       }
   176328     }
   176329 
   176330     if( p->rc==SQLITE_OK
   176331      && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
   176332      && pState->eStage!=0
   176333     ){
   176334       rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
   176335       if( pFd->iCookie!=pState->iCookie ){
   176336         /* At this point (pTargetFd->iCookie) contains the value of the
   176337         ** change-counter cookie (the thing that gets incremented when a
   176338         ** transaction is committed in rollback mode) currently stored on
   176339         ** page 1 of the database file. */
   176340         p->rc = SQLITE_BUSY;
   176341         p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
   176342             (rbuIsVacuum(p) ? "vacuum" : "update")
   176343         );
   176344       }
   176345     }
   176346 
   176347     if( p->rc==SQLITE_OK ){
   176348       if( p->eStage==RBU_STAGE_OAL ){
   176349         sqlite3 *db = p->dbMain;
   176350         p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
   176351 
   176352         /* Point the object iterator at the first object */
   176353         if( p->rc==SQLITE_OK ){
   176354           p->rc = rbuObjIterFirst(p, &p->objiter);
   176355         }
   176356 
   176357         /* If the RBU database contains no data_xxx tables, declare the RBU
   176358         ** update finished.  */
   176359         if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
   176360           p->rc = SQLITE_DONE;
   176361           p->eStage = RBU_STAGE_DONE;
   176362         }else{
   176363           if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
   176364             rbuCopyPragma(p, "page_size");
   176365             rbuCopyPragma(p, "auto_vacuum");
   176366           }
   176367 
   176368           /* Open transactions both databases. The *-oal file is opened or
   176369           ** created at this point. */
   176370           if( p->rc==SQLITE_OK ){
   176371             p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
   176372           }
   176373 
   176374           /* Check if the main database is a zipvfs db. If it is, set the upper
   176375           ** level pager to use "journal_mode=off". This prevents it from
   176376           ** generating a large journal using a temp file.  */
   176377           if( p->rc==SQLITE_OK ){
   176378             int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
   176379             if( frc==SQLITE_OK ){
   176380               p->rc = sqlite3_exec(
   176381                 db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
   176382             }
   176383           }
   176384 
   176385           if( p->rc==SQLITE_OK ){
   176386             rbuSetupOal(p, pState);
   176387           }
   176388         }
   176389       }else if( p->eStage==RBU_STAGE_MOVE ){
   176390         /* no-op */
   176391       }else if( p->eStage==RBU_STAGE_CKPT ){
   176392         rbuSetupCheckpoint(p, pState);
   176393       }else if( p->eStage==RBU_STAGE_DONE ){
   176394         p->rc = SQLITE_DONE;
   176395       }else{
   176396         p->rc = SQLITE_CORRUPT;
   176397       }
   176398     }
   176399 
   176400     rbuFreeState(pState);
   176401   }
   176402 
   176403   return p;
   176404 }
   176405 
   176406 /*
   176407 ** Allocate and return an RBU handle with all fields zeroed except for the
   176408 ** error code, which is set to SQLITE_MISUSE.
   176409 */
   176410 static sqlite3rbu *rbuMisuseError(void){
   176411   sqlite3rbu *pRet;
   176412   pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
   176413   if( pRet ){
   176414     memset(pRet, 0, sizeof(sqlite3rbu));
   176415     pRet->rc = SQLITE_MISUSE;
   176416   }
   176417   return pRet;
   176418 }
   176419 
   176420 /*
   176421 ** Open and return a new RBU handle.
   176422 */
   176423 SQLITE_API sqlite3rbu *sqlite3rbu_open(
   176424   const char *zTarget,
   176425   const char *zRbu,
   176426   const char *zState
   176427 ){
   176428   if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
   176429   /* TODO: Check that zTarget and zRbu are non-NULL */
   176430   return openRbuHandle(zTarget, zRbu, zState);
   176431 }
   176432 
   176433 /*
   176434 ** Open a handle to begin or resume an RBU VACUUM operation.
   176435 */
   176436 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
   176437   const char *zTarget,
   176438   const char *zState
   176439 ){
   176440   if( zTarget==0 ){ return rbuMisuseError(); }
   176441   /* TODO: Check that both arguments are non-NULL */
   176442   return openRbuHandle(0, zTarget, zState);
   176443 }
   176444 
   176445 /*
   176446 ** Return the database handle used by pRbu.
   176447 */
   176448 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
   176449   sqlite3 *db = 0;
   176450   if( pRbu ){
   176451     db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
   176452   }
   176453   return db;
   176454 }
   176455 
   176456 
   176457 /*
   176458 ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
   176459 ** then edit any error message string so as to remove all occurrences of
   176460 ** the pattern "rbu_imp_[0-9]*".
   176461 */
   176462 static void rbuEditErrmsg(sqlite3rbu *p){
   176463   if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
   176464     unsigned int i;
   176465     size_t nErrmsg = strlen(p->zErrmsg);
   176466     for(i=0; i<(nErrmsg-8); i++){
   176467       if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
   176468         int nDel = 8;
   176469         while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
   176470         memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
   176471         nErrmsg -= nDel;
   176472       }
   176473     }
   176474   }
   176475 }
   176476 
   176477 /*
   176478 ** Close the RBU handle.
   176479 */
   176480 SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
   176481   int rc;
   176482   if( p ){
   176483 
   176484     /* Commit the transaction to the *-oal file. */
   176485     if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
   176486       p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
   176487     }
   176488 
   176489     /* Sync the db file if currently doing an incremental checkpoint */
   176490     if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
   176491       sqlite3_file *pDb = p->pTargetFd->pReal;
   176492       p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
   176493     }
   176494 
   176495     rbuSaveState(p, p->eStage);
   176496 
   176497     if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
   176498       p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
   176499     }
   176500 
   176501     /* Close any open statement handles. */
   176502     rbuObjIterFinalize(&p->objiter);
   176503 
   176504     /* If this is an RBU vacuum handle and the vacuum has either finished
   176505     ** successfully or encountered an error, delete the contents of the
   176506     ** state table. This causes the next call to sqlite3rbu_vacuum()
   176507     ** specifying the current target and state databases to start a new
   176508     ** vacuum from scratch.  */
   176509     if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
   176510       int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
   176511       if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
   176512     }
   176513 
   176514     /* Close the open database handle and VFS object. */
   176515     sqlite3_close(p->dbRbu);
   176516     sqlite3_close(p->dbMain);
   176517     assert( p->szTemp==0 );
   176518     rbuDeleteVfs(p);
   176519     sqlite3_free(p->aBuf);
   176520     sqlite3_free(p->aFrame);
   176521 
   176522     rbuEditErrmsg(p);
   176523     rc = p->rc;
   176524     if( pzErrmsg ){
   176525       *pzErrmsg = p->zErrmsg;
   176526     }else{
   176527       sqlite3_free(p->zErrmsg);
   176528     }
   176529     sqlite3_free(p->zState);
   176530     sqlite3_free(p);
   176531   }else{
   176532     rc = SQLITE_NOMEM;
   176533     *pzErrmsg = 0;
   176534   }
   176535   return rc;
   176536 }
   176537 
   176538 /*
   176539 ** Return the total number of key-value operations (inserts, deletes or
   176540 ** updates) that have been performed on the target database since the
   176541 ** current RBU update was started.
   176542 */
   176543 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
   176544   return pRbu->nProgress;
   176545 }
   176546 
   176547 /*
   176548 ** Return permyriadage progress indications for the two main stages of
   176549 ** an RBU update.
   176550 */
   176551 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
   176552   const int MAX_PROGRESS = 10000;
   176553   switch( p->eStage ){
   176554     case RBU_STAGE_OAL:
   176555       if( p->nPhaseOneStep>0 ){
   176556         *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
   176557       }else{
   176558         *pnOne = -1;
   176559       }
   176560       *pnTwo = 0;
   176561       break;
   176562 
   176563     case RBU_STAGE_MOVE:
   176564       *pnOne = MAX_PROGRESS;
   176565       *pnTwo = 0;
   176566       break;
   176567 
   176568     case RBU_STAGE_CKPT:
   176569       *pnOne = MAX_PROGRESS;
   176570       *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
   176571       break;
   176572 
   176573     case RBU_STAGE_DONE:
   176574       *pnOne = MAX_PROGRESS;
   176575       *pnTwo = MAX_PROGRESS;
   176576       break;
   176577 
   176578     default:
   176579       assert( 0 );
   176580   }
   176581 }
   176582 
   176583 /*
   176584 ** Return the current state of the RBU vacuum or update operation.
   176585 */
   176586 SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
   176587   int aRes[] = {
   176588     0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
   176589     0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
   176590   };
   176591 
   176592   assert( RBU_STAGE_OAL==1 );
   176593   assert( RBU_STAGE_MOVE==2 );
   176594   assert( RBU_STAGE_CKPT==4 );
   176595   assert( RBU_STAGE_DONE==5 );
   176596   assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
   176597   assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
   176598   assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
   176599   assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
   176600 
   176601   if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
   176602     return SQLITE_RBU_STATE_ERROR;
   176603   }else{
   176604     assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
   176605     assert( p->eStage==RBU_STAGE_OAL
   176606          || p->eStage==RBU_STAGE_MOVE
   176607          || p->eStage==RBU_STAGE_CKPT
   176608          || p->eStage==RBU_STAGE_DONE
   176609     );
   176610     return aRes[p->eStage];
   176611   }
   176612 }
   176613 
   176614 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
   176615   int rc = p->rc;
   176616   if( rc==SQLITE_DONE ) return SQLITE_OK;
   176617 
   176618   assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
   176619   if( p->eStage==RBU_STAGE_OAL ){
   176620     assert( rc!=SQLITE_DONE );
   176621     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
   176622   }
   176623 
   176624   /* Sync the db file */
   176625   if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
   176626     sqlite3_file *pDb = p->pTargetFd->pReal;
   176627     rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
   176628   }
   176629 
   176630   p->rc = rc;
   176631   rbuSaveState(p, p->eStage);
   176632   rc = p->rc;
   176633 
   176634   if( p->eStage==RBU_STAGE_OAL ){
   176635     assert( rc!=SQLITE_DONE );
   176636     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
   176637     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
   176638     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
   176639   }
   176640 
   176641   p->rc = rc;
   176642   return rc;
   176643 }
   176644 
   176645 /**************************************************************************
   176646 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
   176647 ** of a standard VFS in the following ways:
   176648 **
   176649 ** 1. Whenever the first page of a main database file is read or
   176650 **    written, the value of the change-counter cookie is stored in
   176651 **    rbu_file.iCookie. Similarly, the value of the "write-version"
   176652 **    database header field is stored in rbu_file.iWriteVer. This ensures
   176653 **    that the values are always trustworthy within an open transaction.
   176654 **
   176655 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
   176656 **    member variable of the associated database file descriptor is set
   176657 **    to point to the new file. A mutex protected linked list of all main
   176658 **    db fds opened using a particular RBU VFS is maintained at
   176659 **    rbu_vfs.pMain to facilitate this.
   176660 **
   176661 ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
   176662 **    object can be marked as the target database of an RBU update. This
   176663 **    turns on the following extra special behaviour:
   176664 **
   176665 ** 3a. If xAccess() is called to check if there exists a *-wal file
   176666 **     associated with an RBU target database currently in RBU_STAGE_OAL
   176667 **     stage (preparing the *-oal file), the following special handling
   176668 **     applies:
   176669 **
   176670 **      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
   176671 **        target database may not be in wal mode already.
   176672 **
   176673 **      * if the *-wal file does not exist, set the output parameter to
   176674 **        non-zero (to tell SQLite that it does exist) anyway.
   176675 **
   176676 **     Then, when xOpen() is called to open the *-wal file associated with
   176677 **     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
   176678 **     file, the rbu vfs opens the corresponding *-oal file instead.
   176679 **
   176680 ** 3b. The *-shm pages returned by xShmMap() for a target db file in
   176681 **     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
   176682 **     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
   176683 **     are no-ops on target database files in RBU_STAGE_OAL mode. This is
   176684 **     because assert() statements in some VFS implementations fail if
   176685 **     xShmLock() is called before xShmMap().
   176686 **
   176687 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
   176688 **     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
   176689 **     fails with an SQLITE_BUSY error. This is to stop RBU connections
   176690 **     from automatically checkpointing a *-wal (or *-oal) file from within
   176691 **     sqlite3_close().
   176692 **
   176693 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
   176694 **     all xWrite() calls on the target database file perform no IO.
   176695 **     Instead the frame and page numbers that would be read and written
   176696 **     are recorded. Additionally, successful attempts to obtain exclusive
   176697 **     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
   176698 **     database file are recorded. xShmLock() calls to unlock the same
   176699 **     locks are no-ops (so that once obtained, these locks are never
   176700 **     relinquished). Finally, calls to xSync() on the target database
   176701 **     file fail with SQLITE_INTERNAL errors.
   176702 */
   176703 
   176704 static void rbuUnlockShm(rbu_file *p){
   176705   assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
   176706   if( p->pRbu ){
   176707     int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
   176708     int i;
   176709     for(i=0; i<SQLITE_SHM_NLOCK;i++){
   176710       if( (1<<i) & p->pRbu->mLock ){
   176711         xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
   176712       }
   176713     }
   176714     p->pRbu->mLock = 0;
   176715   }
   176716 }
   176717 
   176718 /*
   176719 */
   176720 static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
   176721   sqlite3rbu *pRbu = pFd->pRbu;
   176722   i64 nDiff = nNew - pFd->sz;
   176723   pRbu->szTemp += nDiff;
   176724   pFd->sz = nNew;
   176725   assert( pRbu->szTemp>=0 );
   176726   if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
   176727   return SQLITE_OK;
   176728 }
   176729 
   176730 /*
   176731 ** Close an rbu file.
   176732 */
   176733 static int rbuVfsClose(sqlite3_file *pFile){
   176734   rbu_file *p = (rbu_file*)pFile;
   176735   int rc;
   176736   int i;
   176737 
   176738   /* Free the contents of the apShm[] array. And the array itself. */
   176739   for(i=0; i<p->nShm; i++){
   176740     sqlite3_free(p->apShm[i]);
   176741   }
   176742   sqlite3_free(p->apShm);
   176743   p->apShm = 0;
   176744   sqlite3_free(p->zDel);
   176745 
   176746   if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
   176747     rbu_file **pp;
   176748     sqlite3_mutex_enter(p->pRbuVfs->mutex);
   176749     for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
   176750     *pp = p->pMainNext;
   176751     sqlite3_mutex_leave(p->pRbuVfs->mutex);
   176752     rbuUnlockShm(p);
   176753     p->pReal->pMethods->xShmUnmap(p->pReal, 0);
   176754   }
   176755   else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
   176756     rbuUpdateTempSize(p, 0);
   176757   }
   176758 
   176759   /* Close the underlying file handle */
   176760   rc = p->pReal->pMethods->xClose(p->pReal);
   176761   return rc;
   176762 }
   176763 
   176764 
   176765 /*
   176766 ** Read and return an unsigned 32-bit big-endian integer from the buffer
   176767 ** passed as the only argument.
   176768 */
   176769 static u32 rbuGetU32(u8 *aBuf){
   176770   return ((u32)aBuf[0] << 24)
   176771        + ((u32)aBuf[1] << 16)
   176772        + ((u32)aBuf[2] <<  8)
   176773        + ((u32)aBuf[3]);
   176774 }
   176775 
   176776 /*
   176777 ** Write an unsigned 32-bit value in big-endian format to the supplied
   176778 ** buffer.
   176779 */
   176780 static void rbuPutU32(u8 *aBuf, u32 iVal){
   176781   aBuf[0] = (iVal >> 24) & 0xFF;
   176782   aBuf[1] = (iVal >> 16) & 0xFF;
   176783   aBuf[2] = (iVal >>  8) & 0xFF;
   176784   aBuf[3] = (iVal >>  0) & 0xFF;
   176785 }
   176786 
   176787 static void rbuPutU16(u8 *aBuf, u16 iVal){
   176788   aBuf[0] = (iVal >>  8) & 0xFF;
   176789   aBuf[1] = (iVal >>  0) & 0xFF;
   176790 }
   176791 
   176792 /*
   176793 ** Read data from an rbuVfs-file.
   176794 */
   176795 static int rbuVfsRead(
   176796   sqlite3_file *pFile,
   176797   void *zBuf,
   176798   int iAmt,
   176799   sqlite_int64 iOfst
   176800 ){
   176801   rbu_file *p = (rbu_file*)pFile;
   176802   sqlite3rbu *pRbu = p->pRbu;
   176803   int rc;
   176804 
   176805   if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
   176806     assert( p->openFlags & SQLITE_OPEN_WAL );
   176807     rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
   176808   }else{
   176809     if( pRbu && pRbu->eStage==RBU_STAGE_OAL
   176810      && (p->openFlags & SQLITE_OPEN_WAL)
   176811      && iOfst>=pRbu->iOalSz
   176812     ){
   176813       rc = SQLITE_OK;
   176814       memset(zBuf, 0, iAmt);
   176815     }else{
   176816       rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
   176817 #if 1
   176818       /* If this is being called to read the first page of the target
   176819       ** database as part of an rbu vacuum operation, synthesize the
   176820       ** contents of the first page if it does not yet exist. Otherwise,
   176821       ** SQLite will not check for a *-wal file.  */
   176822       if( pRbu && rbuIsVacuum(pRbu)
   176823           && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
   176824           && (p->openFlags & SQLITE_OPEN_MAIN_DB)
   176825           && pRbu->rc==SQLITE_OK
   176826       ){
   176827         sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
   176828         rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
   176829         if( rc==SQLITE_OK ){
   176830           u8 *aBuf = (u8*)zBuf;
   176831           u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
   176832           rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
   176833           rbuPutU32(&aBuf[36], 0);          /* number of free pages */
   176834           rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
   176835           rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
   176836           rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
   176837 
   176838           if( iAmt>100 ){
   176839             memset(&aBuf[100], 0, iAmt-100);
   176840             rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
   176841             aBuf[100] = 0x0D;
   176842           }
   176843         }
   176844       }
   176845 #endif
   176846     }
   176847     if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
   176848       /* These look like magic numbers. But they are stable, as they are part
   176849        ** of the definition of the SQLite file format, which may not change. */
   176850       u8 *pBuf = (u8*)zBuf;
   176851       p->iCookie = rbuGetU32(&pBuf[24]);
   176852       p->iWriteVer = pBuf[19];
   176853     }
   176854   }
   176855   return rc;
   176856 }
   176857 
   176858 /*
   176859 ** Write data to an rbuVfs-file.
   176860 */
   176861 static int rbuVfsWrite(
   176862   sqlite3_file *pFile,
   176863   const void *zBuf,
   176864   int iAmt,
   176865   sqlite_int64 iOfst
   176866 ){
   176867   rbu_file *p = (rbu_file*)pFile;
   176868   sqlite3rbu *pRbu = p->pRbu;
   176869   int rc;
   176870 
   176871   if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
   176872     assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
   176873     rc = rbuCaptureDbWrite(p->pRbu, iOfst);
   176874   }else{
   176875     if( pRbu ){
   176876       if( pRbu->eStage==RBU_STAGE_OAL
   176877        && (p->openFlags & SQLITE_OPEN_WAL)
   176878        && iOfst>=pRbu->iOalSz
   176879       ){
   176880         pRbu->iOalSz = iAmt + iOfst;
   176881       }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
   176882         i64 szNew = iAmt+iOfst;
   176883         if( szNew>p->sz ){
   176884           rc = rbuUpdateTempSize(p, szNew);
   176885           if( rc!=SQLITE_OK ) return rc;
   176886         }
   176887       }
   176888     }
   176889     rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
   176890     if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
   176891       /* These look like magic numbers. But they are stable, as they are part
   176892       ** of the definition of the SQLite file format, which may not change. */
   176893       u8 *pBuf = (u8*)zBuf;
   176894       p->iCookie = rbuGetU32(&pBuf[24]);
   176895       p->iWriteVer = pBuf[19];
   176896     }
   176897   }
   176898   return rc;
   176899 }
   176900 
   176901 /*
   176902 ** Truncate an rbuVfs-file.
   176903 */
   176904 static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
   176905   rbu_file *p = (rbu_file*)pFile;
   176906   if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
   176907     int rc = rbuUpdateTempSize(p, size);
   176908     if( rc!=SQLITE_OK ) return rc;
   176909   }
   176910   return p->pReal->pMethods->xTruncate(p->pReal, size);
   176911 }
   176912 
   176913 /*
   176914 ** Sync an rbuVfs-file.
   176915 */
   176916 static int rbuVfsSync(sqlite3_file *pFile, int flags){
   176917   rbu_file *p = (rbu_file *)pFile;
   176918   if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
   176919     if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
   176920       return SQLITE_INTERNAL;
   176921     }
   176922     return SQLITE_OK;
   176923   }
   176924   return p->pReal->pMethods->xSync(p->pReal, flags);
   176925 }
   176926 
   176927 /*
   176928 ** Return the current file-size of an rbuVfs-file.
   176929 */
   176930 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
   176931   rbu_file *p = (rbu_file *)pFile;
   176932   int rc;
   176933   rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
   176934 
   176935   /* If this is an RBU vacuum operation and this is the target database,
   176936   ** pretend that it has at least one page. Otherwise, SQLite will not
   176937   ** check for the existance of a *-wal file. rbuVfsRead() contains
   176938   ** similar logic.  */
   176939   if( rc==SQLITE_OK && *pSize==0
   176940    && p->pRbu && rbuIsVacuum(p->pRbu)
   176941    && (p->openFlags & SQLITE_OPEN_MAIN_DB)
   176942   ){
   176943     *pSize = 1024;
   176944   }
   176945   return rc;
   176946 }
   176947 
   176948 /*
   176949 ** Lock an rbuVfs-file.
   176950 */
   176951 static int rbuVfsLock(sqlite3_file *pFile, int eLock){
   176952   rbu_file *p = (rbu_file*)pFile;
   176953   sqlite3rbu *pRbu = p->pRbu;
   176954   int rc = SQLITE_OK;
   176955 
   176956   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
   176957   if( eLock==SQLITE_LOCK_EXCLUSIVE
   176958    && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
   176959   ){
   176960     /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
   176961     ** prevents it from checkpointing the database from sqlite3_close(). */
   176962     rc = SQLITE_BUSY;
   176963   }else{
   176964     rc = p->pReal->pMethods->xLock(p->pReal, eLock);
   176965   }
   176966 
   176967   return rc;
   176968 }
   176969 
   176970 /*
   176971 ** Unlock an rbuVfs-file.
   176972 */
   176973 static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
   176974   rbu_file *p = (rbu_file *)pFile;
   176975   return p->pReal->pMethods->xUnlock(p->pReal, eLock);
   176976 }
   176977 
   176978 /*
   176979 ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
   176980 */
   176981 static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
   176982   rbu_file *p = (rbu_file *)pFile;
   176983   return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
   176984 }
   176985 
   176986 /*
   176987 ** File control method. For custom operations on an rbuVfs-file.
   176988 */
   176989 static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
   176990   rbu_file *p = (rbu_file *)pFile;
   176991   int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
   176992   int rc;
   176993 
   176994   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
   176995        || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
   176996   );
   176997   if( op==SQLITE_FCNTL_RBU ){
   176998     sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
   176999 
   177000     /* First try to find another RBU vfs lower down in the vfs stack. If
   177001     ** one is found, this vfs will operate in pass-through mode. The lower
   177002     ** level vfs will do the special RBU handling.  */
   177003     rc = xControl(p->pReal, op, pArg);
   177004 
   177005     if( rc==SQLITE_NOTFOUND ){
   177006       /* Now search for a zipvfs instance lower down in the VFS stack. If
   177007       ** one is found, this is an error.  */
   177008       void *dummy = 0;
   177009       rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
   177010       if( rc==SQLITE_OK ){
   177011         rc = SQLITE_ERROR;
   177012         pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
   177013       }else if( rc==SQLITE_NOTFOUND ){
   177014         pRbu->pTargetFd = p;
   177015         p->pRbu = pRbu;
   177016         if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
   177017         rc = SQLITE_OK;
   177018       }
   177019     }
   177020     return rc;
   177021   }
   177022   else if( op==SQLITE_FCNTL_RBUCNT ){
   177023     sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
   177024     pRbu->nRbu++;
   177025     pRbu->pRbuFd = p;
   177026     p->bNolock = 1;
   177027   }
   177028 
   177029   rc = xControl(p->pReal, op, pArg);
   177030   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
   177031     rbu_vfs *pRbuVfs = p->pRbuVfs;
   177032     char *zIn = *(char**)pArg;
   177033     char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
   177034     *(char**)pArg = zOut;
   177035     if( zOut==0 ) rc = SQLITE_NOMEM;
   177036   }
   177037 
   177038   return rc;
   177039 }
   177040 
   177041 /*
   177042 ** Return the sector-size in bytes for an rbuVfs-file.
   177043 */
   177044 static int rbuVfsSectorSize(sqlite3_file *pFile){
   177045   rbu_file *p = (rbu_file *)pFile;
   177046   return p->pReal->pMethods->xSectorSize(p->pReal);
   177047 }
   177048 
   177049 /*
   177050 ** Return the device characteristic flags supported by an rbuVfs-file.
   177051 */
   177052 static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
   177053   rbu_file *p = (rbu_file *)pFile;
   177054   return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
   177055 }
   177056 
   177057 /*
   177058 ** Take or release a shared-memory lock.
   177059 */
   177060 static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
   177061   rbu_file *p = (rbu_file*)pFile;
   177062   sqlite3rbu *pRbu = p->pRbu;
   177063   int rc = SQLITE_OK;
   177064 
   177065 #ifdef SQLITE_AMALGAMATION
   177066     assert( WAL_CKPT_LOCK==1 );
   177067 #endif
   177068 
   177069   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
   177070   if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
   177071     /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
   177072     ** taking this lock also prevents any checkpoints from occurring.
   177073     ** todo: really, it's not clear why this might occur, as
   177074     ** wal_autocheckpoint ought to be turned off.  */
   177075     if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
   177076   }else{
   177077     int bCapture = 0;
   177078     if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
   177079      && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
   177080      && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
   177081     ){
   177082       bCapture = 1;
   177083     }
   177084 
   177085     if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
   177086       rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
   177087       if( bCapture && rc==SQLITE_OK ){
   177088         pRbu->mLock |= (1 << ofst);
   177089       }
   177090     }
   177091   }
   177092 
   177093   return rc;
   177094 }
   177095 
   177096 /*
   177097 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
   177098 */
   177099 static int rbuVfsShmMap(
   177100   sqlite3_file *pFile,
   177101   int iRegion,
   177102   int szRegion,
   177103   int isWrite,
   177104   void volatile **pp
   177105 ){
   177106   rbu_file *p = (rbu_file*)pFile;
   177107   int rc = SQLITE_OK;
   177108   int eStage = (p->pRbu ? p->pRbu->eStage : 0);
   177109 
   177110   /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
   177111   ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
   177112   ** instead of a file on disk.  */
   177113   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
   177114   if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
   177115     if( iRegion<=p->nShm ){
   177116       int nByte = (iRegion+1) * sizeof(char*);
   177117       char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
   177118       if( apNew==0 ){
   177119         rc = SQLITE_NOMEM;
   177120       }else{
   177121         memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
   177122         p->apShm = apNew;
   177123         p->nShm = iRegion+1;
   177124       }
   177125     }
   177126 
   177127     if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
   177128       char *pNew = (char*)sqlite3_malloc64(szRegion);
   177129       if( pNew==0 ){
   177130         rc = SQLITE_NOMEM;
   177131       }else{
   177132         memset(pNew, 0, szRegion);
   177133         p->apShm[iRegion] = pNew;
   177134       }
   177135     }
   177136 
   177137     if( rc==SQLITE_OK ){
   177138       *pp = p->apShm[iRegion];
   177139     }else{
   177140       *pp = 0;
   177141     }
   177142   }else{
   177143     assert( p->apShm==0 );
   177144     rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
   177145   }
   177146 
   177147   return rc;
   177148 }
   177149 
   177150 /*
   177151 ** Memory barrier.
   177152 */
   177153 static void rbuVfsShmBarrier(sqlite3_file *pFile){
   177154   rbu_file *p = (rbu_file *)pFile;
   177155   p->pReal->pMethods->xShmBarrier(p->pReal);
   177156 }
   177157 
   177158 /*
   177159 ** The xShmUnmap method.
   177160 */
   177161 static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
   177162   rbu_file *p = (rbu_file*)pFile;
   177163   int rc = SQLITE_OK;
   177164   int eStage = (p->pRbu ? p->pRbu->eStage : 0);
   177165 
   177166   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
   177167   if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
   177168     /* no-op */
   177169   }else{
   177170     /* Release the checkpointer and writer locks */
   177171     rbuUnlockShm(p);
   177172     rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
   177173   }
   177174   return rc;
   177175 }
   177176 
   177177 /*
   177178 ** Given that zWal points to a buffer containing a wal file name passed to
   177179 ** either the xOpen() or xAccess() VFS method, return a pointer to the
   177180 ** file-handle opened by the same database connection on the corresponding
   177181 ** database file.
   177182 */
   177183 static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
   177184   rbu_file *pDb;
   177185   sqlite3_mutex_enter(pRbuVfs->mutex);
   177186   for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
   177187   sqlite3_mutex_leave(pRbuVfs->mutex);
   177188   return pDb;
   177189 }
   177190 
   177191 /*
   177192 ** A main database named zName has just been opened. The following
   177193 ** function returns a pointer to a buffer owned by SQLite that contains
   177194 ** the name of the *-wal file this db connection will use. SQLite
   177195 ** happens to pass a pointer to this buffer when using xAccess()
   177196 ** or xOpen() to operate on the *-wal file.
   177197 */
   177198 static const char *rbuMainToWal(const char *zName, int flags){
   177199   int n = (int)strlen(zName);
   177200   const char *z = &zName[n];
   177201   if( flags & SQLITE_OPEN_URI ){
   177202     int odd = 0;
   177203     while( 1 ){
   177204       if( z[0]==0 ){
   177205         odd = 1 - odd;
   177206         if( odd && z[1]==0 ) break;
   177207       }
   177208       z++;
   177209     }
   177210     z += 2;
   177211   }else{
   177212     while( *z==0 ) z++;
   177213   }
   177214   z += (n + 8 + 1);
   177215   return z;
   177216 }
   177217 
   177218 /*
   177219 ** Open an rbu file handle.
   177220 */
   177221 static int rbuVfsOpen(
   177222   sqlite3_vfs *pVfs,
   177223   const char *zName,
   177224   sqlite3_file *pFile,
   177225   int flags,
   177226   int *pOutFlags
   177227 ){
   177228   static sqlite3_io_methods rbuvfs_io_methods = {
   177229     2,                            /* iVersion */
   177230     rbuVfsClose,                  /* xClose */
   177231     rbuVfsRead,                   /* xRead */
   177232     rbuVfsWrite,                  /* xWrite */
   177233     rbuVfsTruncate,               /* xTruncate */
   177234     rbuVfsSync,                   /* xSync */
   177235     rbuVfsFileSize,               /* xFileSize */
   177236     rbuVfsLock,                   /* xLock */
   177237     rbuVfsUnlock,                 /* xUnlock */
   177238     rbuVfsCheckReservedLock,      /* xCheckReservedLock */
   177239     rbuVfsFileControl,            /* xFileControl */
   177240     rbuVfsSectorSize,             /* xSectorSize */
   177241     rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
   177242     rbuVfsShmMap,                 /* xShmMap */
   177243     rbuVfsShmLock,                /* xShmLock */
   177244     rbuVfsShmBarrier,             /* xShmBarrier */
   177245     rbuVfsShmUnmap,               /* xShmUnmap */
   177246     0, 0                          /* xFetch, xUnfetch */
   177247   };
   177248   rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
   177249   sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
   177250   rbu_file *pFd = (rbu_file *)pFile;
   177251   int rc = SQLITE_OK;
   177252   const char *zOpen = zName;
   177253   int oflags = flags;
   177254 
   177255   memset(pFd, 0, sizeof(rbu_file));
   177256   pFd->pReal = (sqlite3_file*)&pFd[1];
   177257   pFd->pRbuVfs = pRbuVfs;
   177258   pFd->openFlags = flags;
   177259   if( zName ){
   177260     if( flags & SQLITE_OPEN_MAIN_DB ){
   177261       /* A main database has just been opened. The following block sets
   177262       ** (pFd->zWal) to point to a buffer owned by SQLite that contains
   177263       ** the name of the *-wal file this db connection will use. SQLite
   177264       ** happens to pass a pointer to this buffer when using xAccess()
   177265       ** or xOpen() to operate on the *-wal file.  */
   177266       pFd->zWal = rbuMainToWal(zName, flags);
   177267     }
   177268     else if( flags & SQLITE_OPEN_WAL ){
   177269       rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
   177270       if( pDb ){
   177271         if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
   177272           /* This call is to open a *-wal file. Intead, open the *-oal. This
   177273           ** code ensures that the string passed to xOpen() is terminated by a
   177274           ** pair of '\0' bytes in case the VFS attempts to extract a URI
   177275           ** parameter from it.  */
   177276           const char *zBase = zName;
   177277           size_t nCopy;
   177278           char *zCopy;
   177279           if( rbuIsVacuum(pDb->pRbu) ){
   177280             zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
   177281             zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
   177282           }
   177283           nCopy = strlen(zBase);
   177284           zCopy = sqlite3_malloc64(nCopy+2);
   177285           if( zCopy ){
   177286             memcpy(zCopy, zBase, nCopy);
   177287             zCopy[nCopy-3] = 'o';
   177288             zCopy[nCopy] = '\0';
   177289             zCopy[nCopy+1] = '\0';
   177290             zOpen = (const char*)(pFd->zDel = zCopy);
   177291           }else{
   177292             rc = SQLITE_NOMEM;
   177293           }
   177294           pFd->pRbu = pDb->pRbu;
   177295         }
   177296         pDb->pWalFd = pFd;
   177297       }
   177298     }
   177299   }else{
   177300     pFd->pRbu = pRbuVfs->pRbu;
   177301   }
   177302 
   177303   if( oflags & SQLITE_OPEN_MAIN_DB
   177304    && sqlite3_uri_boolean(zName, "rbu_memory", 0)
   177305   ){
   177306     assert( oflags & SQLITE_OPEN_MAIN_DB );
   177307     oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   177308               SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   177309     zOpen = 0;
   177310   }
   177311 
   177312   if( rc==SQLITE_OK ){
   177313     rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
   177314   }
   177315   if( pFd->pReal->pMethods ){
   177316     /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
   177317     ** pointer and, if the file is a main database file, link it into the
   177318     ** mutex protected linked list of all such files.  */
   177319     pFile->pMethods = &rbuvfs_io_methods;
   177320     if( flags & SQLITE_OPEN_MAIN_DB ){
   177321       sqlite3_mutex_enter(pRbuVfs->mutex);
   177322       pFd->pMainNext = pRbuVfs->pMain;
   177323       pRbuVfs->pMain = pFd;
   177324       sqlite3_mutex_leave(pRbuVfs->mutex);
   177325     }
   177326   }else{
   177327     sqlite3_free(pFd->zDel);
   177328   }
   177329 
   177330   return rc;
   177331 }
   177332 
   177333 /*
   177334 ** Delete the file located at zPath.
   177335 */
   177336 static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   177337   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177338   return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
   177339 }
   177340 
   177341 /*
   177342 ** Test for access permissions. Return true if the requested permission
   177343 ** is available, or false otherwise.
   177344 */
   177345 static int rbuVfsAccess(
   177346   sqlite3_vfs *pVfs,
   177347   const char *zPath,
   177348   int flags,
   177349   int *pResOut
   177350 ){
   177351   rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
   177352   sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
   177353   int rc;
   177354 
   177355   rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
   177356 
   177357   /* If this call is to check if a *-wal file associated with an RBU target
   177358   ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
   177359   ** the following special handling is activated:
   177360   **
   177361   **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
   177362   **      ensures that the RBU extension never tries to update a database
   177363   **      in wal mode, even if the first page of the database file has
   177364   **      been damaged.
   177365   **
   177366   **   b) if the *-wal file does not exist, claim that it does anyway,
   177367   **      causing SQLite to call xOpen() to open it. This call will also
   177368   **      be intercepted (see the rbuVfsOpen() function) and the *-oal
   177369   **      file opened instead.
   177370   */
   177371   if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
   177372     rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
   177373     if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
   177374       if( *pResOut ){
   177375         rc = SQLITE_CANTOPEN;
   177376       }else{
   177377         sqlite3_int64 sz = 0;
   177378         rc = rbuVfsFileSize(&pDb->base, &sz);
   177379         *pResOut = (sz>0);
   177380       }
   177381     }
   177382   }
   177383 
   177384   return rc;
   177385 }
   177386 
   177387 /*
   177388 ** Populate buffer zOut with the full canonical pathname corresponding
   177389 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
   177390 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
   177391 */
   177392 static int rbuVfsFullPathname(
   177393   sqlite3_vfs *pVfs,
   177394   const char *zPath,
   177395   int nOut,
   177396   char *zOut
   177397 ){
   177398   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177399   return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
   177400 }
   177401 
   177402 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   177403 /*
   177404 ** Open the dynamic library located at zPath and return a handle.
   177405 */
   177406 static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   177407   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177408   return pRealVfs->xDlOpen(pRealVfs, zPath);
   177409 }
   177410 
   177411 /*
   177412 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
   177413 ** utf-8 string describing the most recent error encountered associated
   177414 ** with dynamic libraries.
   177415 */
   177416 static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
   177417   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177418   pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
   177419 }
   177420 
   177421 /*
   177422 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
   177423 */
   177424 static void (*rbuVfsDlSym(
   177425   sqlite3_vfs *pVfs,
   177426   void *pArg,
   177427   const char *zSym
   177428 ))(void){
   177429   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177430   return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
   177431 }
   177432 
   177433 /*
   177434 ** Close the dynamic library handle pHandle.
   177435 */
   177436 static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
   177437   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177438   pRealVfs->xDlClose(pRealVfs, pHandle);
   177439 }
   177440 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   177441 
   177442 /*
   177443 ** Populate the buffer pointed to by zBufOut with nByte bytes of
   177444 ** random data.
   177445 */
   177446 static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   177447   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177448   return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
   177449 }
   177450 
   177451 /*
   177452 ** Sleep for nMicro microseconds. Return the number of microseconds
   177453 ** actually slept.
   177454 */
   177455 static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
   177456   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177457   return pRealVfs->xSleep(pRealVfs, nMicro);
   177458 }
   177459 
   177460 /*
   177461 ** Return the current time as a Julian Day number in *pTimeOut.
   177462 */
   177463 static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
   177464   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
   177465   return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
   177466 }
   177467 
   177468 /*
   177469 ** No-op.
   177470 */
   177471 static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
   177472   return 0;
   177473 }
   177474 
   177475 /*
   177476 ** Deregister and destroy an RBU vfs created by an earlier call to
   177477 ** sqlite3rbu_create_vfs().
   177478 */
   177479 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
   177480   sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
   177481   if( pVfs && pVfs->xOpen==rbuVfsOpen ){
   177482     sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
   177483     sqlite3_vfs_unregister(pVfs);
   177484     sqlite3_free(pVfs);
   177485   }
   177486 }
   177487 
   177488 /*
   177489 ** Create an RBU VFS named zName that accesses the underlying file-system
   177490 ** via existing VFS zParent. The new object is registered as a non-default
   177491 ** VFS with SQLite before returning.
   177492 */
   177493 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
   177494 
   177495   /* Template for VFS */
   177496   static sqlite3_vfs vfs_template = {
   177497     1,                            /* iVersion */
   177498     0,                            /* szOsFile */
   177499     0,                            /* mxPathname */
   177500     0,                            /* pNext */
   177501     0,                            /* zName */
   177502     0,                            /* pAppData */
   177503     rbuVfsOpen,                   /* xOpen */
   177504     rbuVfsDelete,                 /* xDelete */
   177505     rbuVfsAccess,                 /* xAccess */
   177506     rbuVfsFullPathname,           /* xFullPathname */
   177507 
   177508 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   177509     rbuVfsDlOpen,                 /* xDlOpen */
   177510     rbuVfsDlError,                /* xDlError */
   177511     rbuVfsDlSym,                  /* xDlSym */
   177512     rbuVfsDlClose,                /* xDlClose */
   177513 #else
   177514     0, 0, 0, 0,
   177515 #endif
   177516 
   177517     rbuVfsRandomness,             /* xRandomness */
   177518     rbuVfsSleep,                  /* xSleep */
   177519     rbuVfsCurrentTime,            /* xCurrentTime */
   177520     rbuVfsGetLastError,           /* xGetLastError */
   177521     0,                            /* xCurrentTimeInt64 (version 2) */
   177522     0, 0, 0                       /* Unimplemented version 3 methods */
   177523   };
   177524 
   177525   rbu_vfs *pNew = 0;              /* Newly allocated VFS */
   177526   int rc = SQLITE_OK;
   177527   size_t nName;
   177528   size_t nByte;
   177529 
   177530   nName = strlen(zName);
   177531   nByte = sizeof(rbu_vfs) + nName + 1;
   177532   pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
   177533   if( pNew==0 ){
   177534     rc = SQLITE_NOMEM;
   177535   }else{
   177536     sqlite3_vfs *pParent;           /* Parent VFS */
   177537     memset(pNew, 0, nByte);
   177538     pParent = sqlite3_vfs_find(zParent);
   177539     if( pParent==0 ){
   177540       rc = SQLITE_NOTFOUND;
   177541     }else{
   177542       char *zSpace;
   177543       memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
   177544       pNew->base.mxPathname = pParent->mxPathname;
   177545       pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
   177546       pNew->pRealVfs = pParent;
   177547       pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
   177548       memcpy(zSpace, zName, nName);
   177549 
   177550       /* Allocate the mutex and register the new VFS (not as the default) */
   177551       pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
   177552       if( pNew->mutex==0 ){
   177553         rc = SQLITE_NOMEM;
   177554       }else{
   177555         rc = sqlite3_vfs_register(&pNew->base, 0);
   177556       }
   177557     }
   177558 
   177559     if( rc!=SQLITE_OK ){
   177560       sqlite3_mutex_free(pNew->mutex);
   177561       sqlite3_free(pNew);
   177562     }
   177563   }
   177564 
   177565   return rc;
   177566 }
   177567 
   177568 /*
   177569 ** Configure the aggregate temp file size limit for this RBU handle.
   177570 */
   177571 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
   177572   if( n>=0 ){
   177573     pRbu->szTempLimit = n;
   177574   }
   177575   return pRbu->szTempLimit;
   177576 }
   177577 
   177578 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
   177579   return pRbu->szTemp;
   177580 }
   177581 
   177582 
   177583 /**************************************************************************/
   177584 
   177585 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
   177586 
   177587 /************** End of sqlite3rbu.c ******************************************/
   177588 /************** Begin file dbstat.c ******************************************/
   177589 /*
   177590 ** 2010 July 12
   177591 **
   177592 ** The author disclaims copyright to this source code.  In place of
   177593 ** a legal notice, here is a blessing:
   177594 **
   177595 **    May you do good and not evil.
   177596 **    May you find forgiveness for yourself and forgive others.
   177597 **    May you share freely, never taking more than you give.
   177598 **
   177599 ******************************************************************************
   177600 **
   177601 ** This file contains an implementation of the "dbstat" virtual table.
   177602 **
   177603 ** The dbstat virtual table is used to extract low-level formatting
   177604 ** information from an SQLite database in order to implement the
   177605 ** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
   177606 ** for an example implementation.
   177607 **
   177608 ** Additional information is available on the "dbstat.html" page of the
   177609 ** official SQLite documentation.
   177610 */
   177611 
   177612 /* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
   177613 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
   177614     && !defined(SQLITE_OMIT_VIRTUALTABLE)
   177615 
   177616 /*
   177617 ** Page paths:
   177618 **
   177619 **   The value of the 'path' column describes the path taken from the
   177620 **   root-node of the b-tree structure to each page. The value of the
   177621 **   root-node path is '/'.
   177622 **
   177623 **   The value of the path for the left-most child page of the root of
   177624 **   a b-tree is '/000/'. (Btrees store content ordered from left to right
   177625 **   so the pages to the left have smaller keys than the pages to the right.)
   177626 **   The next to left-most child of the root page is
   177627 **   '/001', and so on, each sibling page identified by a 3-digit hex
   177628 **   value. The children of the 451st left-most sibling have paths such
   177629 **   as '/1c2/000/, '/1c2/001/' etc.
   177630 **
   177631 **   Overflow pages are specified by appending a '+' character and a
   177632 **   six-digit hexadecimal value to the path to the cell they are linked
   177633 **   from. For example, the three overflow pages in a chain linked from
   177634 **   the left-most cell of the 450th child of the root page are identified
   177635 **   by the paths:
   177636 **
   177637 **      '/1c2/000+000000'         // First page in overflow chain
   177638 **      '/1c2/000+000001'         // Second page in overflow chain
   177639 **      '/1c2/000+000002'         // Third page in overflow chain
   177640 **
   177641 **   If the paths are sorted using the BINARY collation sequence, then
   177642 **   the overflow pages associated with a cell will appear earlier in the
   177643 **   sort-order than its child page:
   177644 **
   177645 **      '/1c2/000/'               // Left-most child of 451st child of root
   177646 */
   177647 #define VTAB_SCHEMA                                                         \
   177648   "CREATE TABLE xx( "                                                       \
   177649   "  name       TEXT,             /* Name of table or index */"             \
   177650   "  path       TEXT,             /* Path to page from root */"             \
   177651   "  pageno     INTEGER,          /* Page number */"                        \
   177652   "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
   177653   "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
   177654   "  payload    INTEGER,          /* Bytes of payload on this page */"      \
   177655   "  unused     INTEGER,          /* Bytes of unused space on this page */" \
   177656   "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
   177657   "  pgoffset   INTEGER,          /* Offset of page in file */"             \
   177658   "  pgsize     INTEGER,          /* Size of the page */"                   \
   177659   "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
   177660   ");"
   177661 
   177662 
   177663 typedef struct StatTable StatTable;
   177664 typedef struct StatCursor StatCursor;
   177665 typedef struct StatPage StatPage;
   177666 typedef struct StatCell StatCell;
   177667 
   177668 struct StatCell {
   177669   int nLocal;                     /* Bytes of local payload */
   177670   u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
   177671   int nOvfl;                      /* Entries in aOvfl[] */
   177672   u32 *aOvfl;                     /* Array of overflow page numbers */
   177673   int nLastOvfl;                  /* Bytes of payload on final overflow page */
   177674   int iOvfl;                      /* Iterates through aOvfl[] */
   177675 };
   177676 
   177677 struct StatPage {
   177678   u32 iPgno;
   177679   DbPage *pPg;
   177680   int iCell;
   177681 
   177682   char *zPath;                    /* Path to this page */
   177683 
   177684   /* Variables populated by statDecodePage(): */
   177685   u8 flags;                       /* Copy of flags byte */
   177686   int nCell;                      /* Number of cells on page */
   177687   int nUnused;                    /* Number of unused bytes on page */
   177688   StatCell *aCell;                /* Array of parsed cells */
   177689   u32 iRightChildPg;              /* Right-child page number (or 0) */
   177690   int nMxPayload;                 /* Largest payload of any cell on this page */
   177691 };
   177692 
   177693 struct StatCursor {
   177694   sqlite3_vtab_cursor base;
   177695   sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
   177696   int isEof;                      /* After pStmt has returned SQLITE_DONE */
   177697   int iDb;                        /* Schema used for this query */
   177698 
   177699   StatPage aPage[32];
   177700   int iPage;                      /* Current entry in aPage[] */
   177701 
   177702   /* Values to return. */
   177703   char *zName;                    /* Value of 'name' column */
   177704   char *zPath;                    /* Value of 'path' column */
   177705   u32 iPageno;                    /* Value of 'pageno' column */
   177706   char *zPagetype;                /* Value of 'pagetype' column */
   177707   int nCell;                      /* Value of 'ncell' column */
   177708   int nPayload;                   /* Value of 'payload' column */
   177709   int nUnused;                    /* Value of 'unused' column */
   177710   int nMxPayload;                 /* Value of 'mx_payload' column */
   177711   i64 iOffset;                    /* Value of 'pgOffset' column */
   177712   int szPage;                     /* Value of 'pgSize' column */
   177713 };
   177714 
   177715 struct StatTable {
   177716   sqlite3_vtab base;
   177717   sqlite3 *db;
   177718   int iDb;                        /* Index of database to analyze */
   177719 };
   177720 
   177721 #ifndef get2byte
   177722 # define get2byte(x)   ((x)[0]<<8 | (x)[1])
   177723 #endif
   177724 
   177725 /*
   177726 ** Connect to or create a statvfs virtual table.
   177727 */
   177728 static int statConnect(
   177729   sqlite3 *db,
   177730   void *pAux,
   177731   int argc, const char *const*argv,
   177732   sqlite3_vtab **ppVtab,
   177733   char **pzErr
   177734 ){
   177735   StatTable *pTab = 0;
   177736   int rc = SQLITE_OK;
   177737   int iDb;
   177738 
   177739   if( argc>=4 ){
   177740     Token nm;
   177741     sqlite3TokenInit(&nm, (char*)argv[3]);
   177742     iDb = sqlite3FindDb(db, &nm);
   177743     if( iDb<0 ){
   177744       *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
   177745       return SQLITE_ERROR;
   177746     }
   177747   }else{
   177748     iDb = 0;
   177749   }
   177750   rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
   177751   if( rc==SQLITE_OK ){
   177752     pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
   177753     if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
   177754   }
   177755 
   177756   assert( rc==SQLITE_OK || pTab==0 );
   177757   if( rc==SQLITE_OK ){
   177758     memset(pTab, 0, sizeof(StatTable));
   177759     pTab->db = db;
   177760     pTab->iDb = iDb;
   177761   }
   177762 
   177763   *ppVtab = (sqlite3_vtab*)pTab;
   177764   return rc;
   177765 }
   177766 
   177767 /*
   177768 ** Disconnect from or destroy a statvfs virtual table.
   177769 */
   177770 static int statDisconnect(sqlite3_vtab *pVtab){
   177771   sqlite3_free(pVtab);
   177772   return SQLITE_OK;
   177773 }
   177774 
   177775 /*
   177776 ** There is no "best-index". This virtual table always does a linear
   177777 ** scan.  However, a schema=? constraint should cause this table to
   177778 ** operate on a different database schema, so check for it.
   177779 **
   177780 ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
   177781 */
   177782 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   177783   int i;
   177784 
   177785   pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
   177786 
   177787   /* Look for a valid schema=? constraint.  If found, change the idxNum to
   177788   ** 1 and request the value of that constraint be sent to xFilter.  And
   177789   ** lower the cost estimate to encourage the constrained version to be
   177790   ** used.
   177791   */
   177792   for(i=0; i<pIdxInfo->nConstraint; i++){
   177793     if( pIdxInfo->aConstraint[i].usable==0 ) continue;
   177794     if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   177795     if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
   177796     pIdxInfo->idxNum = 1;
   177797     pIdxInfo->estimatedCost = 1.0;
   177798     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
   177799     pIdxInfo->aConstraintUsage[i].omit = 1;
   177800     break;
   177801   }
   177802 
   177803 
   177804   /* Records are always returned in ascending order of (name, path).
   177805   ** If this will satisfy the client, set the orderByConsumed flag so that
   177806   ** SQLite does not do an external sort.
   177807   */
   177808   if( ( pIdxInfo->nOrderBy==1
   177809      && pIdxInfo->aOrderBy[0].iColumn==0
   177810      && pIdxInfo->aOrderBy[0].desc==0
   177811      ) ||
   177812       ( pIdxInfo->nOrderBy==2
   177813      && pIdxInfo->aOrderBy[0].iColumn==0
   177814      && pIdxInfo->aOrderBy[0].desc==0
   177815      && pIdxInfo->aOrderBy[1].iColumn==1
   177816      && pIdxInfo->aOrderBy[1].desc==0
   177817      )
   177818   ){
   177819     pIdxInfo->orderByConsumed = 1;
   177820   }
   177821 
   177822   return SQLITE_OK;
   177823 }
   177824 
   177825 /*
   177826 ** Open a new statvfs cursor.
   177827 */
   177828 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   177829   StatTable *pTab = (StatTable *)pVTab;
   177830   StatCursor *pCsr;
   177831 
   177832   pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
   177833   if( pCsr==0 ){
   177834     return SQLITE_NOMEM_BKPT;
   177835   }else{
   177836     memset(pCsr, 0, sizeof(StatCursor));
   177837     pCsr->base.pVtab = pVTab;
   177838     pCsr->iDb = pTab->iDb;
   177839   }
   177840 
   177841   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   177842   return SQLITE_OK;
   177843 }
   177844 
   177845 static void statClearPage(StatPage *p){
   177846   int i;
   177847   if( p->aCell ){
   177848     for(i=0; i<p->nCell; i++){
   177849       sqlite3_free(p->aCell[i].aOvfl);
   177850     }
   177851     sqlite3_free(p->aCell);
   177852   }
   177853   sqlite3PagerUnref(p->pPg);
   177854   sqlite3_free(p->zPath);
   177855   memset(p, 0, sizeof(StatPage));
   177856 }
   177857 
   177858 static void statResetCsr(StatCursor *pCsr){
   177859   int i;
   177860   sqlite3_reset(pCsr->pStmt);
   177861   for(i=0; i<ArraySize(pCsr->aPage); i++){
   177862     statClearPage(&pCsr->aPage[i]);
   177863   }
   177864   pCsr->iPage = 0;
   177865   sqlite3_free(pCsr->zPath);
   177866   pCsr->zPath = 0;
   177867   pCsr->isEof = 0;
   177868 }
   177869 
   177870 /*
   177871 ** Close a statvfs cursor.
   177872 */
   177873 static int statClose(sqlite3_vtab_cursor *pCursor){
   177874   StatCursor *pCsr = (StatCursor *)pCursor;
   177875   statResetCsr(pCsr);
   177876   sqlite3_finalize(pCsr->pStmt);
   177877   sqlite3_free(pCsr);
   177878   return SQLITE_OK;
   177879 }
   177880 
   177881 static void getLocalPayload(
   177882   int nUsable,                    /* Usable bytes per page */
   177883   u8 flags,                       /* Page flags */
   177884   int nTotal,                     /* Total record (payload) size */
   177885   int *pnLocal                    /* OUT: Bytes stored locally */
   177886 ){
   177887   int nLocal;
   177888   int nMinLocal;
   177889   int nMaxLocal;
   177890 
   177891   if( flags==0x0D ){              /* Table leaf node */
   177892     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
   177893     nMaxLocal = nUsable - 35;
   177894   }else{                          /* Index interior and leaf nodes */
   177895     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
   177896     nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
   177897   }
   177898 
   177899   nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
   177900   if( nLocal>nMaxLocal ) nLocal = nMinLocal;
   177901   *pnLocal = nLocal;
   177902 }
   177903 
   177904 static int statDecodePage(Btree *pBt, StatPage *p){
   177905   int nUnused;
   177906   int iOff;
   177907   int nHdr;
   177908   int isLeaf;
   177909   int szPage;
   177910 
   177911   u8 *aData = sqlite3PagerGetData(p->pPg);
   177912   u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
   177913 
   177914   p->flags = aHdr[0];
   177915   p->nCell = get2byte(&aHdr[3]);
   177916   p->nMxPayload = 0;
   177917 
   177918   isLeaf = (p->flags==0x0A || p->flags==0x0D);
   177919   nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
   177920 
   177921   nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
   177922   nUnused += (int)aHdr[7];
   177923   iOff = get2byte(&aHdr[1]);
   177924   while( iOff ){
   177925     nUnused += get2byte(&aData[iOff+2]);
   177926     iOff = get2byte(&aData[iOff]);
   177927   }
   177928   p->nUnused = nUnused;
   177929   p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
   177930   szPage = sqlite3BtreeGetPageSize(pBt);
   177931 
   177932   if( p->nCell ){
   177933     int i;                        /* Used to iterate through cells */
   177934     int nUsable;                  /* Usable bytes per page */
   177935 
   177936     sqlite3BtreeEnter(pBt);
   177937     nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
   177938     sqlite3BtreeLeave(pBt);
   177939     p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
   177940     if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
   177941     memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
   177942 
   177943     for(i=0; i<p->nCell; i++){
   177944       StatCell *pCell = &p->aCell[i];
   177945 
   177946       iOff = get2byte(&aData[nHdr+i*2]);
   177947       if( !isLeaf ){
   177948         pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
   177949         iOff += 4;
   177950       }
   177951       if( p->flags==0x05 ){
   177952         /* A table interior node. nPayload==0. */
   177953       }else{
   177954         u32 nPayload;             /* Bytes of payload total (local+overflow) */
   177955         int nLocal;               /* Bytes of payload stored locally */
   177956         iOff += getVarint32(&aData[iOff], nPayload);
   177957         if( p->flags==0x0D ){
   177958           u64 dummy;
   177959           iOff += sqlite3GetVarint(&aData[iOff], &dummy);
   177960         }
   177961         if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
   177962         getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
   177963         pCell->nLocal = nLocal;
   177964         assert( nLocal>=0 );
   177965         assert( nPayload>=(u32)nLocal );
   177966         assert( nLocal<=(nUsable-35) );
   177967         if( nPayload>(u32)nLocal ){
   177968           int j;
   177969           int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
   177970           pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
   177971           pCell->nOvfl = nOvfl;
   177972           pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
   177973           if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
   177974           pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
   177975           for(j=1; j<nOvfl; j++){
   177976             int rc;
   177977             u32 iPrev = pCell->aOvfl[j-1];
   177978             DbPage *pPg = 0;
   177979             rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
   177980             if( rc!=SQLITE_OK ){
   177981               assert( pPg==0 );
   177982               return rc;
   177983             }
   177984             pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
   177985             sqlite3PagerUnref(pPg);
   177986           }
   177987         }
   177988       }
   177989     }
   177990   }
   177991 
   177992   return SQLITE_OK;
   177993 }
   177994 
   177995 /*
   177996 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
   177997 ** the current value of pCsr->iPageno.
   177998 */
   177999 static void statSizeAndOffset(StatCursor *pCsr){
   178000   StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
   178001   Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
   178002   Pager *pPager = sqlite3BtreePager(pBt);
   178003   sqlite3_file *fd;
   178004   sqlite3_int64 x[2];
   178005 
   178006   /* The default page size and offset */
   178007   pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
   178008   pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
   178009 
   178010   /* If connected to a ZIPVFS backend, override the page size and
   178011   ** offset with actual values obtained from ZIPVFS.
   178012   */
   178013   fd = sqlite3PagerFile(pPager);
   178014   x[0] = pCsr->iPageno;
   178015   if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
   178016     pCsr->iOffset = x[0];
   178017     pCsr->szPage = (int)x[1];
   178018   }
   178019 }
   178020 
   178021 /*
   178022 ** Move a statvfs cursor to the next entry in the file.
   178023 */
   178024 static int statNext(sqlite3_vtab_cursor *pCursor){
   178025   int rc;
   178026   int nPayload;
   178027   char *z;
   178028   StatCursor *pCsr = (StatCursor *)pCursor;
   178029   StatTable *pTab = (StatTable *)pCursor->pVtab;
   178030   Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
   178031   Pager *pPager = sqlite3BtreePager(pBt);
   178032 
   178033   sqlite3_free(pCsr->zPath);
   178034   pCsr->zPath = 0;
   178035 
   178036 statNextRestart:
   178037   if( pCsr->aPage[0].pPg==0 ){
   178038     rc = sqlite3_step(pCsr->pStmt);
   178039     if( rc==SQLITE_ROW ){
   178040       int nPage;
   178041       u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
   178042       sqlite3PagerPagecount(pPager, &nPage);
   178043       if( nPage==0 ){
   178044         pCsr->isEof = 1;
   178045         return sqlite3_reset(pCsr->pStmt);
   178046       }
   178047       rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
   178048       pCsr->aPage[0].iPgno = iRoot;
   178049       pCsr->aPage[0].iCell = 0;
   178050       pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
   178051       pCsr->iPage = 0;
   178052       if( z==0 ) rc = SQLITE_NOMEM_BKPT;
   178053     }else{
   178054       pCsr->isEof = 1;
   178055       return sqlite3_reset(pCsr->pStmt);
   178056     }
   178057   }else{
   178058 
   178059     /* Page p itself has already been visited. */
   178060     StatPage *p = &pCsr->aPage[pCsr->iPage];
   178061 
   178062     while( p->iCell<p->nCell ){
   178063       StatCell *pCell = &p->aCell[p->iCell];
   178064       if( pCell->iOvfl<pCell->nOvfl ){
   178065         int nUsable;
   178066         sqlite3BtreeEnter(pBt);
   178067         nUsable = sqlite3BtreeGetPageSize(pBt) -
   178068                         sqlite3BtreeGetReserveNoMutex(pBt);
   178069         sqlite3BtreeLeave(pBt);
   178070         pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
   178071         pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
   178072         pCsr->zPagetype = "overflow";
   178073         pCsr->nCell = 0;
   178074         pCsr->nMxPayload = 0;
   178075         pCsr->zPath = z = sqlite3_mprintf(
   178076             "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
   178077         );
   178078         if( pCell->iOvfl<pCell->nOvfl-1 ){
   178079           pCsr->nUnused = 0;
   178080           pCsr->nPayload = nUsable - 4;
   178081         }else{
   178082           pCsr->nPayload = pCell->nLastOvfl;
   178083           pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
   178084         }
   178085         pCell->iOvfl++;
   178086         statSizeAndOffset(pCsr);
   178087         return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
   178088       }
   178089       if( p->iRightChildPg ) break;
   178090       p->iCell++;
   178091     }
   178092 
   178093     if( !p->iRightChildPg || p->iCell>p->nCell ){
   178094       statClearPage(p);
   178095       if( pCsr->iPage==0 ) return statNext(pCursor);
   178096       pCsr->iPage--;
   178097       goto statNextRestart; /* Tail recursion */
   178098     }
   178099     pCsr->iPage++;
   178100     assert( p==&pCsr->aPage[pCsr->iPage-1] );
   178101 
   178102     if( p->iCell==p->nCell ){
   178103       p[1].iPgno = p->iRightChildPg;
   178104     }else{
   178105       p[1].iPgno = p->aCell[p->iCell].iChildPg;
   178106     }
   178107     rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
   178108     p[1].iCell = 0;
   178109     p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
   178110     p->iCell++;
   178111     if( z==0 ) rc = SQLITE_NOMEM_BKPT;
   178112   }
   178113 
   178114 
   178115   /* Populate the StatCursor fields with the values to be returned
   178116   ** by the xColumn() and xRowid() methods.
   178117   */
   178118   if( rc==SQLITE_OK ){
   178119     int i;
   178120     StatPage *p = &pCsr->aPage[pCsr->iPage];
   178121     pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
   178122     pCsr->iPageno = p->iPgno;
   178123 
   178124     rc = statDecodePage(pBt, p);
   178125     if( rc==SQLITE_OK ){
   178126       statSizeAndOffset(pCsr);
   178127 
   178128       switch( p->flags ){
   178129         case 0x05:             /* table internal */
   178130         case 0x02:             /* index internal */
   178131           pCsr->zPagetype = "internal";
   178132           break;
   178133         case 0x0D:             /* table leaf */
   178134         case 0x0A:             /* index leaf */
   178135           pCsr->zPagetype = "leaf";
   178136           break;
   178137         default:
   178138           pCsr->zPagetype = "corrupted";
   178139           break;
   178140       }
   178141       pCsr->nCell = p->nCell;
   178142       pCsr->nUnused = p->nUnused;
   178143       pCsr->nMxPayload = p->nMxPayload;
   178144       pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
   178145       if( z==0 ) rc = SQLITE_NOMEM_BKPT;
   178146       nPayload = 0;
   178147       for(i=0; i<p->nCell; i++){
   178148         nPayload += p->aCell[i].nLocal;
   178149       }
   178150       pCsr->nPayload = nPayload;
   178151     }
   178152   }
   178153 
   178154   return rc;
   178155 }
   178156 
   178157 static int statEof(sqlite3_vtab_cursor *pCursor){
   178158   StatCursor *pCsr = (StatCursor *)pCursor;
   178159   return pCsr->isEof;
   178160 }
   178161 
   178162 static int statFilter(
   178163   sqlite3_vtab_cursor *pCursor,
   178164   int idxNum, const char *idxStr,
   178165   int argc, sqlite3_value **argv
   178166 ){
   178167   StatCursor *pCsr = (StatCursor *)pCursor;
   178168   StatTable *pTab = (StatTable*)(pCursor->pVtab);
   178169   char *zSql;
   178170   int rc = SQLITE_OK;
   178171   char *zMaster;
   178172 
   178173   if( idxNum==1 ){
   178174     const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
   178175     pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
   178176     if( pCsr->iDb<0 ){
   178177       sqlite3_free(pCursor->pVtab->zErrMsg);
   178178       pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
   178179       return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
   178180     }
   178181   }else{
   178182     pCsr->iDb = pTab->iDb;
   178183   }
   178184   statResetCsr(pCsr);
   178185   sqlite3_finalize(pCsr->pStmt);
   178186   pCsr->pStmt = 0;
   178187   zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
   178188   zSql = sqlite3_mprintf(
   178189       "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
   178190       "  UNION ALL  "
   178191       "SELECT name, rootpage, type"
   178192       "  FROM \"%w\".%s WHERE rootpage!=0"
   178193       "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
   178194   if( zSql==0 ){
   178195     return SQLITE_NOMEM_BKPT;
   178196   }else{
   178197     rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
   178198     sqlite3_free(zSql);
   178199   }
   178200 
   178201   if( rc==SQLITE_OK ){
   178202     rc = statNext(pCursor);
   178203   }
   178204   return rc;
   178205 }
   178206 
   178207 static int statColumn(
   178208   sqlite3_vtab_cursor *pCursor,
   178209   sqlite3_context *ctx,
   178210   int i
   178211 ){
   178212   StatCursor *pCsr = (StatCursor *)pCursor;
   178213   switch( i ){
   178214     case 0:            /* name */
   178215       sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
   178216       break;
   178217     case 1:            /* path */
   178218       sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
   178219       break;
   178220     case 2:            /* pageno */
   178221       sqlite3_result_int64(ctx, pCsr->iPageno);
   178222       break;
   178223     case 3:            /* pagetype */
   178224       sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
   178225       break;
   178226     case 4:            /* ncell */
   178227       sqlite3_result_int(ctx, pCsr->nCell);
   178228       break;
   178229     case 5:            /* payload */
   178230       sqlite3_result_int(ctx, pCsr->nPayload);
   178231       break;
   178232     case 6:            /* unused */
   178233       sqlite3_result_int(ctx, pCsr->nUnused);
   178234       break;
   178235     case 7:            /* mx_payload */
   178236       sqlite3_result_int(ctx, pCsr->nMxPayload);
   178237       break;
   178238     case 8:            /* pgoffset */
   178239       sqlite3_result_int64(ctx, pCsr->iOffset);
   178240       break;
   178241     case 9:            /* pgsize */
   178242       sqlite3_result_int(ctx, pCsr->szPage);
   178243       break;
   178244     default: {          /* schema */
   178245       sqlite3 *db = sqlite3_context_db_handle(ctx);
   178246       int iDb = pCsr->iDb;
   178247       sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
   178248       break;
   178249     }
   178250   }
   178251   return SQLITE_OK;
   178252 }
   178253 
   178254 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   178255   StatCursor *pCsr = (StatCursor *)pCursor;
   178256   *pRowid = pCsr->iPageno;
   178257   return SQLITE_OK;
   178258 }
   178259 
   178260 /*
   178261 ** Invoke this routine to register the "dbstat" virtual table module
   178262 */
   178263 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
   178264   static sqlite3_module dbstat_module = {
   178265     0,                            /* iVersion */
   178266     statConnect,                  /* xCreate */
   178267     statConnect,                  /* xConnect */
   178268     statBestIndex,                /* xBestIndex */
   178269     statDisconnect,               /* xDisconnect */
   178270     statDisconnect,               /* xDestroy */
   178271     statOpen,                     /* xOpen - open a cursor */
   178272     statClose,                    /* xClose - close a cursor */
   178273     statFilter,                   /* xFilter - configure scan constraints */
   178274     statNext,                     /* xNext - advance a cursor */
   178275     statEof,                      /* xEof - check for end of scan */
   178276     statColumn,                   /* xColumn - read data */
   178277     statRowid,                    /* xRowid - read data */
   178278     0,                            /* xUpdate */
   178279     0,                            /* xBegin */
   178280     0,                            /* xSync */
   178281     0,                            /* xCommit */
   178282     0,                            /* xRollback */
   178283     0,                            /* xFindMethod */
   178284     0,                            /* xRename */
   178285     0,                            /* xSavepoint */
   178286     0,                            /* xRelease */
   178287     0,                            /* xRollbackTo */
   178288   };
   178289   return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
   178290 }
   178291 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
   178292 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
   178293 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
   178294 
   178295 /************** End of dbstat.c **********************************************/
   178296 /************** Begin file dbpage.c ******************************************/
   178297 /*
   178298 ** 2017-10-11
   178299 **
   178300 ** The author disclaims copyright to this source code.  In place of
   178301 ** a legal notice, here is a blessing:
   178302 **
   178303 **    May you do good and not evil.
   178304 **    May you find forgiveness for yourself and forgive others.
   178305 **    May you share freely, never taking more than you give.
   178306 **
   178307 ******************************************************************************
   178308 **
   178309 ** This file contains an implementation of the "sqlite_dbpage" virtual table.
   178310 **
   178311 ** The sqlite_dbpage virtual table is used to read or write whole raw
   178312 ** pages of the database file.  The pager interface is used so that
   178313 ** uncommitted changes and changes recorded in the WAL file are correctly
   178314 ** retrieved.
   178315 **
   178316 ** Usage example:
   178317 **
   178318 **    SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
   178319 **
   178320 ** This is an eponymous virtual table so it does not need to be created before
   178321 ** use.  The optional argument to the sqlite_dbpage() table name is the
   178322 ** schema for the database file that is to be read.  The default schema is
   178323 ** "main".
   178324 **
   178325 ** The data field of sqlite_dbpage table can be updated.  The new
   178326 ** value must be a BLOB which is the correct page size, otherwise the
   178327 ** update fails.  Rows may not be deleted or inserted.
   178328 */
   178329 
   178330 /* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
   178331 #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
   178332     && !defined(SQLITE_OMIT_VIRTUALTABLE)
   178333 
   178334 typedef struct DbpageTable DbpageTable;
   178335 typedef struct DbpageCursor DbpageCursor;
   178336 
   178337 struct DbpageCursor {
   178338   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
   178339   int pgno;                       /* Current page number */
   178340   int mxPgno;                     /* Last page to visit on this scan */
   178341   Pager *pPager;                  /* Pager being read/written */
   178342   DbPage *pPage1;                 /* Page 1 of the database */
   178343   int iDb;                        /* Index of database to analyze */
   178344   int szPage;                     /* Size of each page in bytes */
   178345 };
   178346 
   178347 struct DbpageTable {
   178348   sqlite3_vtab base;              /* Base class.  Must be first */
   178349   sqlite3 *db;                    /* The database */
   178350 };
   178351 
   178352 /* Columns */
   178353 #define DBPAGE_COLUMN_PGNO    0
   178354 #define DBPAGE_COLUMN_DATA    1
   178355 #define DBPAGE_COLUMN_SCHEMA  2
   178356 
   178357 
   178358 
   178359 /*
   178360 ** Connect to or create a dbpagevfs virtual table.
   178361 */
   178362 static int dbpageConnect(
   178363   sqlite3 *db,
   178364   void *pAux,
   178365   int argc, const char *const*argv,
   178366   sqlite3_vtab **ppVtab,
   178367   char **pzErr
   178368 ){
   178369   DbpageTable *pTab = 0;
   178370   int rc = SQLITE_OK;
   178371 
   178372   rc = sqlite3_declare_vtab(db,
   178373           "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
   178374   if( rc==SQLITE_OK ){
   178375     pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
   178376     if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
   178377   }
   178378 
   178379   assert( rc==SQLITE_OK || pTab==0 );
   178380   if( rc==SQLITE_OK ){
   178381     memset(pTab, 0, sizeof(DbpageTable));
   178382     pTab->db = db;
   178383   }
   178384 
   178385   *ppVtab = (sqlite3_vtab*)pTab;
   178386   return rc;
   178387 }
   178388 
   178389 /*
   178390 ** Disconnect from or destroy a dbpagevfs virtual table.
   178391 */
   178392 static int dbpageDisconnect(sqlite3_vtab *pVtab){
   178393   sqlite3_free(pVtab);
   178394   return SQLITE_OK;
   178395 }
   178396 
   178397 /*
   178398 ** idxNum:
   178399 **
   178400 **     0     schema=main, full table scan
   178401 **     1     schema=main, pgno=?1
   178402 **     2     schema=?1, full table scan
   178403 **     3     schema=?1, pgno=?2
   178404 */
   178405 static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   178406   int i;
   178407   int iPlan = 0;
   178408 
   178409   /* If there is a schema= constraint, it must be honored.  Report a
   178410   ** ridiculously large estimated cost if the schema= constraint is
   178411   ** unavailable
   178412   */
   178413   for(i=0; i<pIdxInfo->nConstraint; i++){
   178414     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
   178415     if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
   178416     if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   178417     if( !p->usable ){
   178418       /* No solution.  Use the default SQLITE_BIG_DBL cost */
   178419       pIdxInfo->estimatedRows = 0x7fffffff;
   178420       return SQLITE_OK;
   178421     }
   178422     iPlan = 2;
   178423     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
   178424     pIdxInfo->aConstraintUsage[i].omit = 1;
   178425     break;
   178426   }
   178427 
   178428   /* If we reach this point, it means that either there is no schema=
   178429   ** constraint (in which case we use the "main" schema) or else the
   178430   ** schema constraint was accepted.  Lower the estimated cost accordingly
   178431   */
   178432   pIdxInfo->estimatedCost = 1.0e6;
   178433 
   178434   /* Check for constraints against pgno */
   178435   for(i=0; i<pIdxInfo->nConstraint; i++){
   178436     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
   178437     if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   178438       pIdxInfo->estimatedRows = 1;
   178439       pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
   178440       pIdxInfo->estimatedCost = 1.0;
   178441       pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
   178442       pIdxInfo->aConstraintUsage[i].omit = 1;
   178443       iPlan |= 1;
   178444       break;
   178445     }
   178446   }
   178447   pIdxInfo->idxNum = iPlan;
   178448 
   178449   if( pIdxInfo->nOrderBy>=1
   178450    && pIdxInfo->aOrderBy[0].iColumn<=0
   178451    && pIdxInfo->aOrderBy[0].desc==0
   178452   ){
   178453     pIdxInfo->orderByConsumed = 1;
   178454   }
   178455   return SQLITE_OK;
   178456 }
   178457 
   178458 /*
   178459 ** Open a new dbpagevfs cursor.
   178460 */
   178461 static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   178462   DbpageCursor *pCsr;
   178463 
   178464   pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
   178465   if( pCsr==0 ){
   178466     return SQLITE_NOMEM_BKPT;
   178467   }else{
   178468     memset(pCsr, 0, sizeof(DbpageCursor));
   178469     pCsr->base.pVtab = pVTab;
   178470     pCsr->pgno = -1;
   178471   }
   178472 
   178473   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   178474   return SQLITE_OK;
   178475 }
   178476 
   178477 /*
   178478 ** Close a dbpagevfs cursor.
   178479 */
   178480 static int dbpageClose(sqlite3_vtab_cursor *pCursor){
   178481   DbpageCursor *pCsr = (DbpageCursor *)pCursor;
   178482   if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
   178483   sqlite3_free(pCsr);
   178484   return SQLITE_OK;
   178485 }
   178486 
   178487 /*
   178488 ** Move a dbpagevfs cursor to the next entry in the file.
   178489 */
   178490 static int dbpageNext(sqlite3_vtab_cursor *pCursor){
   178491   int rc = SQLITE_OK;
   178492   DbpageCursor *pCsr = (DbpageCursor *)pCursor;
   178493   pCsr->pgno++;
   178494   return rc;
   178495 }
   178496 
   178497 static int dbpageEof(sqlite3_vtab_cursor *pCursor){
   178498   DbpageCursor *pCsr = (DbpageCursor *)pCursor;
   178499   return pCsr->pgno > pCsr->mxPgno;
   178500 }
   178501 
   178502 /*
   178503 ** idxNum:
   178504 **
   178505 **     0     schema=main, full table scan
   178506 **     1     schema=main, pgno=?1
   178507 **     2     schema=?1, full table scan
   178508 **     3     schema=?1, pgno=?2
   178509 **
   178510 ** idxStr is not used
   178511 */
   178512 static int dbpageFilter(
   178513   sqlite3_vtab_cursor *pCursor,
   178514   int idxNum, const char *idxStr,
   178515   int argc, sqlite3_value **argv
   178516 ){
   178517   DbpageCursor *pCsr = (DbpageCursor *)pCursor;
   178518   DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
   178519   int rc;
   178520   sqlite3 *db = pTab->db;
   178521   Btree *pBt;
   178522 
   178523   /* Default setting is no rows of result */
   178524   pCsr->pgno = 1;
   178525   pCsr->mxPgno = 0;
   178526 
   178527   if( idxNum & 2 ){
   178528     const char *zSchema;
   178529     assert( argc>=1 );
   178530     zSchema = (const char*)sqlite3_value_text(argv[0]);
   178531     pCsr->iDb = sqlite3FindDbName(db, zSchema);
   178532     if( pCsr->iDb<0 ) return SQLITE_OK;
   178533   }else{
   178534     pCsr->iDb = 0;
   178535   }
   178536   pBt = db->aDb[pCsr->iDb].pBt;
   178537   if( pBt==0 ) return SQLITE_OK;
   178538   pCsr->pPager = sqlite3BtreePager(pBt);
   178539   pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
   178540   pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
   178541   if( idxNum & 1 ){
   178542     assert( argc>(idxNum>>1) );
   178543     pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
   178544     if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
   178545       pCsr->pgno = 1;
   178546       pCsr->mxPgno = 0;
   178547     }else{
   178548       pCsr->mxPgno = pCsr->pgno;
   178549     }
   178550   }else{
   178551     assert( pCsr->pgno==1 );
   178552   }
   178553   if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
   178554   rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
   178555   return rc;
   178556 }
   178557 
   178558 static int dbpageColumn(
   178559   sqlite3_vtab_cursor *pCursor,
   178560   sqlite3_context *ctx,
   178561   int i
   178562 ){
   178563   DbpageCursor *pCsr = (DbpageCursor *)pCursor;
   178564   int rc = SQLITE_OK;
   178565   switch( i ){
   178566     case 0: {           /* pgno */
   178567       sqlite3_result_int(ctx, pCsr->pgno);
   178568       break;
   178569     }
   178570     case 1: {           /* data */
   178571       DbPage *pDbPage = 0;
   178572       rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
   178573       if( rc==SQLITE_OK ){
   178574         sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
   178575                             SQLITE_TRANSIENT);
   178576       }
   178577       sqlite3PagerUnref(pDbPage);
   178578       break;
   178579     }
   178580     default: {          /* schema */
   178581       sqlite3 *db = sqlite3_context_db_handle(ctx);
   178582       sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
   178583       break;
   178584     }
   178585   }
   178586   return SQLITE_OK;
   178587 }
   178588 
   178589 static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   178590   DbpageCursor *pCsr = (DbpageCursor *)pCursor;
   178591   *pRowid = pCsr->pgno;
   178592   return SQLITE_OK;
   178593 }
   178594 
   178595 static int dbpageUpdate(
   178596   sqlite3_vtab *pVtab,
   178597   int argc,
   178598   sqlite3_value **argv,
   178599   sqlite_int64 *pRowid
   178600 ){
   178601   DbpageTable *pTab = (DbpageTable *)pVtab;
   178602   Pgno pgno;
   178603   DbPage *pDbPage = 0;
   178604   int rc = SQLITE_OK;
   178605   char *zErr = 0;
   178606   const char *zSchema;
   178607   int iDb;
   178608   Btree *pBt;
   178609   Pager *pPager;
   178610   int szPage;
   178611 
   178612   if( argc==1 ){
   178613     zErr = "cannot delete";
   178614     goto update_fail;
   178615   }
   178616   pgno = sqlite3_value_int(argv[0]);
   178617   if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
   178618     zErr = "cannot insert";
   178619     goto update_fail;
   178620   }
   178621   zSchema = (const char*)sqlite3_value_text(argv[4]);
   178622   iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
   178623   if( iDb<0 ){
   178624     zErr = "no such schema";
   178625     goto update_fail;
   178626   }
   178627   pBt = pTab->db->aDb[iDb].pBt;
   178628   if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
   178629     zErr = "bad page number";
   178630     goto update_fail;
   178631   }
   178632   szPage = sqlite3BtreeGetPageSize(pBt);
   178633   if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
   178634    || sqlite3_value_bytes(argv[3])!=szPage
   178635   ){
   178636     zErr = "bad page value";
   178637     goto update_fail;
   178638   }
   178639   pPager = sqlite3BtreePager(pBt);
   178640   rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
   178641   if( rc==SQLITE_OK ){
   178642     rc = sqlite3PagerWrite(pDbPage);
   178643     if( rc==SQLITE_OK ){
   178644       memcpy(sqlite3PagerGetData(pDbPage),
   178645              sqlite3_value_blob(argv[3]),
   178646              szPage);
   178647     }
   178648   }
   178649   sqlite3PagerUnref(pDbPage);
   178650   return rc;
   178651 
   178652 update_fail:
   178653   sqlite3_free(pVtab->zErrMsg);
   178654   pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
   178655   return SQLITE_ERROR;
   178656 }
   178657 
   178658 /* Since we do not know in advance which database files will be
   178659 ** written by the sqlite_dbpage virtual table, start a write transaction
   178660 ** on them all.
   178661 */
   178662 static int dbpageBegin(sqlite3_vtab *pVtab){
   178663   DbpageTable *pTab = (DbpageTable *)pVtab;
   178664   sqlite3 *db = pTab->db;
   178665   int i;
   178666   for(i=0; i<db->nDb; i++){
   178667     Btree *pBt = db->aDb[i].pBt;
   178668     if( pBt ) sqlite3BtreeBeginTrans(pBt, 1);
   178669   }
   178670   return SQLITE_OK;
   178671 }
   178672 
   178673 
   178674 /*
   178675 ** Invoke this routine to register the "dbpage" virtual table module
   178676 */
   178677 SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
   178678   static sqlite3_module dbpage_module = {
   178679     0,                            /* iVersion */
   178680     dbpageConnect,                /* xCreate */
   178681     dbpageConnect,                /* xConnect */
   178682     dbpageBestIndex,              /* xBestIndex */
   178683     dbpageDisconnect,             /* xDisconnect */
   178684     dbpageDisconnect,             /* xDestroy */
   178685     dbpageOpen,                   /* xOpen - open a cursor */
   178686     dbpageClose,                  /* xClose - close a cursor */
   178687     dbpageFilter,                 /* xFilter - configure scan constraints */
   178688     dbpageNext,                   /* xNext - advance a cursor */
   178689     dbpageEof,                    /* xEof - check for end of scan */
   178690     dbpageColumn,                 /* xColumn - read data */
   178691     dbpageRowid,                  /* xRowid - read data */
   178692     dbpageUpdate,                 /* xUpdate */
   178693     dbpageBegin,                  /* xBegin */
   178694     0,                            /* xSync */
   178695     0,                            /* xCommit */
   178696     0,                            /* xRollback */
   178697     0,                            /* xFindMethod */
   178698     0,                            /* xRename */
   178699     0,                            /* xSavepoint */
   178700     0,                            /* xRelease */
   178701     0,                            /* xRollbackTo */
   178702   };
   178703   return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
   178704 }
   178705 #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
   178706 SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
   178707 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
   178708 
   178709 /************** End of dbpage.c **********************************************/
   178710 /************** Begin file sqlite3session.c **********************************/
   178711 
   178712 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
   178713 /* #include "sqlite3session.h" */
   178714 /* #include <assert.h> */
   178715 /* #include <string.h> */
   178716 
   178717 #ifndef SQLITE_AMALGAMATION
   178718 /* # include "sqliteInt.h" */
   178719 /* # include "vdbeInt.h" */
   178720 #endif
   178721 
   178722 typedef struct SessionTable SessionTable;
   178723 typedef struct SessionChange SessionChange;
   178724 typedef struct SessionBuffer SessionBuffer;
   178725 typedef struct SessionInput SessionInput;
   178726 
   178727 /*
   178728 ** Minimum chunk size used by streaming versions of functions.
   178729 */
   178730 #ifndef SESSIONS_STRM_CHUNK_SIZE
   178731 # ifdef SQLITE_TEST
   178732 #   define SESSIONS_STRM_CHUNK_SIZE 64
   178733 # else
   178734 #   define SESSIONS_STRM_CHUNK_SIZE 1024
   178735 # endif
   178736 #endif
   178737 
   178738 typedef struct SessionHook SessionHook;
   178739 struct SessionHook {
   178740   void *pCtx;
   178741   int (*xOld)(void*,int,sqlite3_value**);
   178742   int (*xNew)(void*,int,sqlite3_value**);
   178743   int (*xCount)(void*);
   178744   int (*xDepth)(void*);
   178745 };
   178746 
   178747 /*
   178748 ** Session handle structure.
   178749 */
   178750 struct sqlite3_session {
   178751   sqlite3 *db;                    /* Database handle session is attached to */
   178752   char *zDb;                      /* Name of database session is attached to */
   178753   int bEnable;                    /* True if currently recording */
   178754   int bIndirect;                  /* True if all changes are indirect */
   178755   int bAutoAttach;                /* True to auto-attach tables */
   178756   int rc;                         /* Non-zero if an error has occurred */
   178757   void *pFilterCtx;               /* First argument to pass to xTableFilter */
   178758   int (*xTableFilter)(void *pCtx, const char *zTab);
   178759   sqlite3_value *pZeroBlob;       /* Value containing X'' */
   178760   sqlite3_session *pNext;         /* Next session object on same db. */
   178761   SessionTable *pTable;           /* List of attached tables */
   178762   SessionHook hook;               /* APIs to grab new and old data with */
   178763 };
   178764 
   178765 /*
   178766 ** Instances of this structure are used to build strings or binary records.
   178767 */
   178768 struct SessionBuffer {
   178769   u8 *aBuf;                       /* Pointer to changeset buffer */
   178770   int nBuf;                       /* Size of buffer aBuf */
   178771   int nAlloc;                     /* Size of allocation containing aBuf */
   178772 };
   178773 
   178774 /*
   178775 ** An object of this type is used internally as an abstraction for
   178776 ** input data. Input data may be supplied either as a single large buffer
   178777 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
   178778 **  sqlite3changeset_start_strm()).
   178779 */
   178780 struct SessionInput {
   178781   int bNoDiscard;                 /* If true, discard no data */
   178782   int iCurrent;                   /* Offset in aData[] of current change */
   178783   int iNext;                      /* Offset in aData[] of next change */
   178784   u8 *aData;                      /* Pointer to buffer containing changeset */
   178785   int nData;                      /* Number of bytes in aData */
   178786 
   178787   SessionBuffer buf;              /* Current read buffer */
   178788   int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
   178789   void *pIn;                                /* First argument to xInput */
   178790   int bEof;                       /* Set to true after xInput finished */
   178791 };
   178792 
   178793 /*
   178794 ** Structure for changeset iterators.
   178795 */
   178796 struct sqlite3_changeset_iter {
   178797   SessionInput in;                /* Input buffer or stream */
   178798   SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
   178799   int bPatchset;                  /* True if this is a patchset */
   178800   int rc;                         /* Iterator error code */
   178801   sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
   178802   char *zTab;                     /* Current table */
   178803   int nCol;                       /* Number of columns in zTab */
   178804   int op;                         /* Current operation */
   178805   int bIndirect;                  /* True if current change was indirect */
   178806   u8 *abPK;                       /* Primary key array */
   178807   sqlite3_value **apValue;        /* old.* and new.* values */
   178808 };
   178809 
   178810 /*
   178811 ** Each session object maintains a set of the following structures, one
   178812 ** for each table the session object is monitoring. The structures are
   178813 ** stored in a linked list starting at sqlite3_session.pTable.
   178814 **
   178815 ** The keys of the SessionTable.aChange[] hash table are all rows that have
   178816 ** been modified in any way since the session object was attached to the
   178817 ** table.
   178818 **
   178819 ** The data associated with each hash-table entry is a structure containing
   178820 ** a subset of the initial values that the modified row contained at the
   178821 ** start of the session. Or no initial values if the row was inserted.
   178822 */
   178823 struct SessionTable {
   178824   SessionTable *pNext;
   178825   char *zName;                    /* Local name of table */
   178826   int nCol;                       /* Number of columns in table zName */
   178827   int bStat1;                     /* True if this is sqlite_stat1 */
   178828   const char **azCol;             /* Column names */
   178829   u8 *abPK;                       /* Array of primary key flags */
   178830   int nEntry;                     /* Total number of entries in hash table */
   178831   int nChange;                    /* Size of apChange[] array */
   178832   SessionChange **apChange;       /* Hash table buckets */
   178833 };
   178834 
   178835 /*
   178836 ** RECORD FORMAT:
   178837 **
   178838 ** The following record format is similar to (but not compatible with) that
   178839 ** used in SQLite database files. This format is used as part of the
   178840 ** change-set binary format, and so must be architecture independent.
   178841 **
   178842 ** Unlike the SQLite database record format, each field is self-contained -
   178843 ** there is no separation of header and data. Each field begins with a
   178844 ** single byte describing its type, as follows:
   178845 **
   178846 **       0x00: Undefined value.
   178847 **       0x01: Integer value.
   178848 **       0x02: Real value.
   178849 **       0x03: Text value.
   178850 **       0x04: Blob value.
   178851 **       0x05: SQL NULL value.
   178852 **
   178853 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
   178854 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
   178855 ** only of the single type byte. For other types of values, the type byte
   178856 ** is followed by:
   178857 **
   178858 **   Text values:
   178859 **     A varint containing the number of bytes in the value (encoded using
   178860 **     UTF-8). Followed by a buffer containing the UTF-8 representation
   178861 **     of the text value. There is no nul terminator.
   178862 **
   178863 **   Blob values:
   178864 **     A varint containing the number of bytes in the value, followed by
   178865 **     a buffer containing the value itself.
   178866 **
   178867 **   Integer values:
   178868 **     An 8-byte big-endian integer value.
   178869 **
   178870 **   Real values:
   178871 **     An 8-byte big-endian IEEE 754-2008 real value.
   178872 **
   178873 ** Varint values are encoded in the same way as varints in the SQLite
   178874 ** record format.
   178875 **
   178876 ** CHANGESET FORMAT:
   178877 **
   178878 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
   178879 ** one or more tables. Operations on a single table are grouped together,
   178880 ** but may occur in any order (i.e. deletes, updates and inserts are all
   178881 ** mixed together).
   178882 **
   178883 ** Each group of changes begins with a table header:
   178884 **
   178885 **   1 byte: Constant 0x54 (capital 'T')
   178886 **   Varint: Number of columns in the table.
   178887 **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
   178888 **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
   178889 **
   178890 ** Followed by one or more changes to the table.
   178891 **
   178892 **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
   178893 **   1 byte: The "indirect-change" flag.
   178894 **   old.* record: (delete and update only)
   178895 **   new.* record: (insert and update only)
   178896 **
   178897 ** The "old.*" and "new.*" records, if present, are N field records in the
   178898 ** format described above under "RECORD FORMAT", where N is the number of
   178899 ** columns in the table. The i'th field of each record is associated with
   178900 ** the i'th column of the table, counting from left to right in the order
   178901 ** in which columns were declared in the CREATE TABLE statement.
   178902 **
   178903 ** The new.* record that is part of each INSERT change contains the values
   178904 ** that make up the new row. Similarly, the old.* record that is part of each
   178905 ** DELETE change contains the values that made up the row that was deleted
   178906 ** from the database. In the changeset format, the records that are part
   178907 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
   178908 ** fields.
   178909 **
   178910 ** Within the old.* record associated with an UPDATE change, all fields
   178911 ** associated with table columns that are not PRIMARY KEY columns and are
   178912 ** not modified by the UPDATE change are set to "undefined". Other fields
   178913 ** are set to the values that made up the row before the UPDATE that the
   178914 ** change records took place. Within the new.* record, fields associated
   178915 ** with table columns modified by the UPDATE change contain the new
   178916 ** values. Fields associated with table columns that are not modified
   178917 ** are set to "undefined".
   178918 **
   178919 ** PATCHSET FORMAT:
   178920 **
   178921 ** A patchset is also a collection of changes. It is similar to a changeset,
   178922 ** but leaves undefined those fields that are not useful if no conflict
   178923 ** resolution is required when applying the changeset.
   178924 **
   178925 ** Each group of changes begins with a table header:
   178926 **
   178927 **   1 byte: Constant 0x50 (capital 'P')
   178928 **   Varint: Number of columns in the table.
   178929 **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
   178930 **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
   178931 **
   178932 ** Followed by one or more changes to the table.
   178933 **
   178934 **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
   178935 **   1 byte: The "indirect-change" flag.
   178936 **   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
   178937 **                   full record for INSERT).
   178938 **
   178939 ** As in the changeset format, each field of the single record that is part
   178940 ** of a patchset change is associated with the correspondingly positioned
   178941 ** table column, counting from left to right within the CREATE TABLE
   178942 ** statement.
   178943 **
   178944 ** For a DELETE change, all fields within the record except those associated
   178945 ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
   178946 ** contain the values identifying the row to delete.
   178947 **
   178948 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
   178949 ** columns and columns that are modified by the UPDATE are set to "undefined".
   178950 ** PRIMARY KEY fields contain the values identifying the table row to update,
   178951 ** and fields associated with modified columns contain the new column values.
   178952 **
   178953 ** The records associated with INSERT changes are in the same format as for
   178954 ** changesets. It is not possible for a record associated with an INSERT
   178955 ** change to contain a field set to "undefined".
   178956 */
   178957 
   178958 /*
   178959 ** For each row modified during a session, there exists a single instance of
   178960 ** this structure stored in a SessionTable.aChange[] hash table.
   178961 */
   178962 struct SessionChange {
   178963   int op;                         /* One of UPDATE, DELETE, INSERT */
   178964   int bIndirect;                  /* True if this change is "indirect" */
   178965   int nRecord;                    /* Number of bytes in buffer aRecord[] */
   178966   u8 *aRecord;                    /* Buffer containing old.* record */
   178967   SessionChange *pNext;           /* For hash-table collisions */
   178968 };
   178969 
   178970 /*
   178971 ** Write a varint with value iVal into the buffer at aBuf. Return the
   178972 ** number of bytes written.
   178973 */
   178974 static int sessionVarintPut(u8 *aBuf, int iVal){
   178975   return putVarint32(aBuf, iVal);
   178976 }
   178977 
   178978 /*
   178979 ** Return the number of bytes required to store value iVal as a varint.
   178980 */
   178981 static int sessionVarintLen(int iVal){
   178982   return sqlite3VarintLen(iVal);
   178983 }
   178984 
   178985 /*
   178986 ** Read a varint value from aBuf[] into *piVal. Return the number of
   178987 ** bytes read.
   178988 */
   178989 static int sessionVarintGet(u8 *aBuf, int *piVal){
   178990   return getVarint32(aBuf, *piVal);
   178991 }
   178992 
   178993 /* Load an unaligned and unsigned 32-bit integer */
   178994 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
   178995 
   178996 /*
   178997 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
   178998 ** the value read.
   178999 */
   179000 static sqlite3_int64 sessionGetI64(u8 *aRec){
   179001   u64 x = SESSION_UINT32(aRec);
   179002   u32 y = SESSION_UINT32(aRec+4);
   179003   x = (x<<32) + y;
   179004   return (sqlite3_int64)x;
   179005 }
   179006 
   179007 /*
   179008 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
   179009 */
   179010 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
   179011   aBuf[0] = (i>>56) & 0xFF;
   179012   aBuf[1] = (i>>48) & 0xFF;
   179013   aBuf[2] = (i>>40) & 0xFF;
   179014   aBuf[3] = (i>>32) & 0xFF;
   179015   aBuf[4] = (i>>24) & 0xFF;
   179016   aBuf[5] = (i>>16) & 0xFF;
   179017   aBuf[6] = (i>> 8) & 0xFF;
   179018   aBuf[7] = (i>> 0) & 0xFF;
   179019 }
   179020 
   179021 /*
   179022 ** This function is used to serialize the contents of value pValue (see
   179023 ** comment titled "RECORD FORMAT" above).
   179024 **
   179025 ** If it is non-NULL, the serialized form of the value is written to
   179026 ** buffer aBuf. *pnWrite is set to the number of bytes written before
   179027 ** returning. Or, if aBuf is NULL, the only thing this function does is
   179028 ** set *pnWrite.
   179029 **
   179030 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
   179031 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
   179032 ** SQLITE_NOMEM is returned.
   179033 */
   179034 static int sessionSerializeValue(
   179035   u8 *aBuf,                       /* If non-NULL, write serialized value here */
   179036   sqlite3_value *pValue,          /* Value to serialize */
   179037   int *pnWrite                    /* IN/OUT: Increment by bytes written */
   179038 ){
   179039   int nByte;                      /* Size of serialized value in bytes */
   179040 
   179041   if( pValue ){
   179042     int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
   179043 
   179044     eType = sqlite3_value_type(pValue);
   179045     if( aBuf ) aBuf[0] = eType;
   179046 
   179047     switch( eType ){
   179048       case SQLITE_NULL:
   179049         nByte = 1;
   179050         break;
   179051 
   179052       case SQLITE_INTEGER:
   179053       case SQLITE_FLOAT:
   179054         if( aBuf ){
   179055           /* TODO: SQLite does something special to deal with mixed-endian
   179056           ** floating point values (e.g. ARM7). This code probably should
   179057           ** too.  */
   179058           u64 i;
   179059           if( eType==SQLITE_INTEGER ){
   179060             i = (u64)sqlite3_value_int64(pValue);
   179061           }else{
   179062             double r;
   179063             assert( sizeof(double)==8 && sizeof(u64)==8 );
   179064             r = sqlite3_value_double(pValue);
   179065             memcpy(&i, &r, 8);
   179066           }
   179067           sessionPutI64(&aBuf[1], i);
   179068         }
   179069         nByte = 9;
   179070         break;
   179071 
   179072       default: {
   179073         u8 *z;
   179074         int n;
   179075         int nVarint;
   179076 
   179077         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
   179078         if( eType==SQLITE_TEXT ){
   179079           z = (u8 *)sqlite3_value_text(pValue);
   179080         }else{
   179081           z = (u8 *)sqlite3_value_blob(pValue);
   179082         }
   179083         n = sqlite3_value_bytes(pValue);
   179084         if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
   179085         nVarint = sessionVarintLen(n);
   179086 
   179087         if( aBuf ){
   179088           sessionVarintPut(&aBuf[1], n);
   179089           if( n ) memcpy(&aBuf[nVarint + 1], z, n);
   179090         }
   179091 
   179092         nByte = 1 + nVarint + n;
   179093         break;
   179094       }
   179095     }
   179096   }else{
   179097     nByte = 1;
   179098     if( aBuf ) aBuf[0] = '\0';
   179099   }
   179100 
   179101   if( pnWrite ) *pnWrite += nByte;
   179102   return SQLITE_OK;
   179103 }
   179104 
   179105 
   179106 /*
   179107 ** This macro is used to calculate hash key values for data structures. In
   179108 ** order to use this macro, the entire data structure must be represented
   179109 ** as a series of unsigned integers. In order to calculate a hash-key value
   179110 ** for a data structure represented as three such integers, the macro may
   179111 ** then be used as follows:
   179112 **
   179113 **    int hash_key_value;
   179114 **    hash_key_value = HASH_APPEND(0, <value 1>);
   179115 **    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
   179116 **    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
   179117 **
   179118 ** In practice, the data structures this macro is used for are the primary
   179119 ** key values of modified rows.
   179120 */
   179121 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
   179122 
   179123 /*
   179124 ** Append the hash of the 64-bit integer passed as the second argument to the
   179125 ** hash-key value passed as the first. Return the new hash-key value.
   179126 */
   179127 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
   179128   h = HASH_APPEND(h, i & 0xFFFFFFFF);
   179129   return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
   179130 }
   179131 
   179132 /*
   179133 ** Append the hash of the blob passed via the second and third arguments to
   179134 ** the hash-key value passed as the first. Return the new hash-key value.
   179135 */
   179136 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
   179137   int i;
   179138   for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
   179139   return h;
   179140 }
   179141 
   179142 /*
   179143 ** Append the hash of the data type passed as the second argument to the
   179144 ** hash-key value passed as the first. Return the new hash-key value.
   179145 */
   179146 static unsigned int sessionHashAppendType(unsigned int h, int eType){
   179147   return HASH_APPEND(h, eType);
   179148 }
   179149 
   179150 /*
   179151 ** This function may only be called from within a pre-update callback.
   179152 ** It calculates a hash based on the primary key values of the old.* or
   179153 ** new.* row currently available and, assuming no error occurs, writes it to
   179154 ** *piHash before returning. If the primary key contains one or more NULL
   179155 ** values, *pbNullPK is set to true before returning.
   179156 **
   179157 ** If an error occurs, an SQLite error code is returned and the final values
   179158 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
   179159 ** and the output variables are set as described above.
   179160 */
   179161 static int sessionPreupdateHash(
   179162   sqlite3_session *pSession,      /* Session object that owns pTab */
   179163   SessionTable *pTab,             /* Session table handle */
   179164   int bNew,                       /* True to hash the new.* PK */
   179165   int *piHash,                    /* OUT: Hash value */
   179166   int *pbNullPK                   /* OUT: True if there are NULL values in PK */
   179167 ){
   179168   unsigned int h = 0;             /* Hash value to return */
   179169   int i;                          /* Used to iterate through columns */
   179170 
   179171   assert( *pbNullPK==0 );
   179172   assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
   179173   for(i=0; i<pTab->nCol; i++){
   179174     if( pTab->abPK[i] ){
   179175       int rc;
   179176       int eType;
   179177       sqlite3_value *pVal;
   179178 
   179179       if( bNew ){
   179180         rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
   179181       }else{
   179182         rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
   179183       }
   179184       if( rc!=SQLITE_OK ) return rc;
   179185 
   179186       eType = sqlite3_value_type(pVal);
   179187       h = sessionHashAppendType(h, eType);
   179188       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   179189         i64 iVal;
   179190         if( eType==SQLITE_INTEGER ){
   179191           iVal = sqlite3_value_int64(pVal);
   179192         }else{
   179193           double rVal = sqlite3_value_double(pVal);
   179194           assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
   179195           memcpy(&iVal, &rVal, 8);
   179196         }
   179197         h = sessionHashAppendI64(h, iVal);
   179198       }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
   179199         const u8 *z;
   179200         int n;
   179201         if( eType==SQLITE_TEXT ){
   179202           z = (const u8 *)sqlite3_value_text(pVal);
   179203         }else{
   179204           z = (const u8 *)sqlite3_value_blob(pVal);
   179205         }
   179206         n = sqlite3_value_bytes(pVal);
   179207         if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
   179208         h = sessionHashAppendBlob(h, n, z);
   179209       }else{
   179210         assert( eType==SQLITE_NULL );
   179211         assert( pTab->bStat1==0 || i!=1 );
   179212         *pbNullPK = 1;
   179213       }
   179214     }
   179215   }
   179216 
   179217   *piHash = (h % pTab->nChange);
   179218   return SQLITE_OK;
   179219 }
   179220 
   179221 /*
   179222 ** The buffer that the argument points to contains a serialized SQL value.
   179223 ** Return the number of bytes of space occupied by the value (including
   179224 ** the type byte).
   179225 */
   179226 static int sessionSerialLen(u8 *a){
   179227   int e = *a;
   179228   int n;
   179229   if( e==0 ) return 1;
   179230   if( e==SQLITE_NULL ) return 1;
   179231   if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
   179232   return sessionVarintGet(&a[1], &n) + 1 + n;
   179233 }
   179234 
   179235 /*
   179236 ** Based on the primary key values stored in change aRecord, calculate a
   179237 ** hash key. Assume the has table has nBucket buckets. The hash keys
   179238 ** calculated by this function are compatible with those calculated by
   179239 ** sessionPreupdateHash().
   179240 **
   179241 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
   179242 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
   179243 */
   179244 static unsigned int sessionChangeHash(
   179245   SessionTable *pTab,             /* Table handle */
   179246   int bPkOnly,                    /* Record consists of PK fields only */
   179247   u8 *aRecord,                    /* Change record */
   179248   int nBucket                     /* Assume this many buckets in hash table */
   179249 ){
   179250   unsigned int h = 0;             /* Value to return */
   179251   int i;                          /* Used to iterate through columns */
   179252   u8 *a = aRecord;                /* Used to iterate through change record */
   179253 
   179254   for(i=0; i<pTab->nCol; i++){
   179255     int eType = *a;
   179256     int isPK = pTab->abPK[i];
   179257     if( bPkOnly && isPK==0 ) continue;
   179258 
   179259     /* It is not possible for eType to be SQLITE_NULL here. The session
   179260     ** module does not record changes for rows with NULL values stored in
   179261     ** primary key columns. */
   179262     assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
   179263          || eType==SQLITE_TEXT || eType==SQLITE_BLOB
   179264          || eType==SQLITE_NULL || eType==0
   179265     );
   179266     assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
   179267 
   179268     if( isPK ){
   179269       a++;
   179270       h = sessionHashAppendType(h, eType);
   179271       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   179272         h = sessionHashAppendI64(h, sessionGetI64(a));
   179273         a += 8;
   179274       }else{
   179275         int n;
   179276         a += sessionVarintGet(a, &n);
   179277         h = sessionHashAppendBlob(h, n, a);
   179278         a += n;
   179279       }
   179280     }else{
   179281       a += sessionSerialLen(a);
   179282     }
   179283   }
   179284   return (h % nBucket);
   179285 }
   179286 
   179287 /*
   179288 ** Arguments aLeft and aRight are pointers to change records for table pTab.
   179289 ** This function returns true if the two records apply to the same row (i.e.
   179290 ** have the same values stored in the primary key columns), or false
   179291 ** otherwise.
   179292 */
   179293 static int sessionChangeEqual(
   179294   SessionTable *pTab,             /* Table used for PK definition */
   179295   int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
   179296   u8 *aLeft,                      /* Change record */
   179297   int bRightPkOnly,               /* True if aRight[] contains PK fields only */
   179298   u8 *aRight                      /* Change record */
   179299 ){
   179300   u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
   179301   u8 *a2 = aRight;                /* Cursor to iterate through aRight */
   179302   int iCol;                       /* Used to iterate through table columns */
   179303 
   179304   for(iCol=0; iCol<pTab->nCol; iCol++){
   179305     if( pTab->abPK[iCol] ){
   179306       int n1 = sessionSerialLen(a1);
   179307       int n2 = sessionSerialLen(a2);
   179308 
   179309       if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
   179310         return 0;
   179311       }
   179312       a1 += n1;
   179313       a2 += n2;
   179314     }else{
   179315       if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
   179316       if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
   179317     }
   179318   }
   179319 
   179320   return 1;
   179321 }
   179322 
   179323 /*
   179324 ** Arguments aLeft and aRight both point to buffers containing change
   179325 ** records with nCol columns. This function "merges" the two records into
   179326 ** a single records which is written to the buffer at *paOut. *paOut is
   179327 ** then set to point to one byte after the last byte written before
   179328 ** returning.
   179329 **
   179330 ** The merging of records is done as follows: For each column, if the
   179331 ** aRight record contains a value for the column, copy the value from
   179332 ** their. Otherwise, if aLeft contains a value, copy it. If neither
   179333 ** record contains a value for a given column, then neither does the
   179334 ** output record.
   179335 */
   179336 static void sessionMergeRecord(
   179337   u8 **paOut,
   179338   int nCol,
   179339   u8 *aLeft,
   179340   u8 *aRight
   179341 ){
   179342   u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
   179343   u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
   179344   u8 *aOut = *paOut;              /* Output cursor */
   179345   int iCol;                       /* Used to iterate from 0 to nCol */
   179346 
   179347   for(iCol=0; iCol<nCol; iCol++){
   179348     int n1 = sessionSerialLen(a1);
   179349     int n2 = sessionSerialLen(a2);
   179350     if( *a2 ){
   179351       memcpy(aOut, a2, n2);
   179352       aOut += n2;
   179353     }else{
   179354       memcpy(aOut, a1, n1);
   179355       aOut += n1;
   179356     }
   179357     a1 += n1;
   179358     a2 += n2;
   179359   }
   179360 
   179361   *paOut = aOut;
   179362 }
   179363 
   179364 /*
   179365 ** This is a helper function used by sessionMergeUpdate().
   179366 **
   179367 ** When this function is called, both *paOne and *paTwo point to a value
   179368 ** within a change record. Before it returns, both have been advanced so
   179369 ** as to point to the next value in the record.
   179370 **
   179371 ** If, when this function is called, *paTwo points to a valid value (i.e.
   179372 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
   179373 ** pointer is returned and *pnVal is set to the number of bytes in the
   179374 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
   179375 ** set to the number of bytes in the value at *paOne. If *paOne points
   179376 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
   179377 **
   179378 **   if( *paTwo is valid ) return *paTwo;
   179379 **   return *paOne;
   179380 **
   179381 */
   179382 static u8 *sessionMergeValue(
   179383   u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
   179384   u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
   179385   int *pnVal                      /* OUT: Bytes in returned value */
   179386 ){
   179387   u8 *a1 = *paOne;
   179388   u8 *a2 = *paTwo;
   179389   u8 *pRet = 0;
   179390   int n1;
   179391 
   179392   assert( a1 );
   179393   if( a2 ){
   179394     int n2 = sessionSerialLen(a2);
   179395     if( *a2 ){
   179396       *pnVal = n2;
   179397       pRet = a2;
   179398     }
   179399     *paTwo = &a2[n2];
   179400   }
   179401 
   179402   n1 = sessionSerialLen(a1);
   179403   if( pRet==0 ){
   179404     *pnVal = n1;
   179405     pRet = a1;
   179406   }
   179407   *paOne = &a1[n1];
   179408 
   179409   return pRet;
   179410 }
   179411 
   179412 /*
   179413 ** This function is used by changeset_concat() to merge two UPDATE changes
   179414 ** on the same row.
   179415 */
   179416 static int sessionMergeUpdate(
   179417   u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
   179418   SessionTable *pTab,             /* Table change pertains to */
   179419   int bPatchset,                  /* True if records are patchset records */
   179420   u8 *aOldRecord1,                /* old.* record for first change */
   179421   u8 *aOldRecord2,                /* old.* record for second change */
   179422   u8 *aNewRecord1,                /* new.* record for first change */
   179423   u8 *aNewRecord2                 /* new.* record for second change */
   179424 ){
   179425   u8 *aOld1 = aOldRecord1;
   179426   u8 *aOld2 = aOldRecord2;
   179427   u8 *aNew1 = aNewRecord1;
   179428   u8 *aNew2 = aNewRecord2;
   179429 
   179430   u8 *aOut = *paOut;
   179431   int i;
   179432 
   179433   if( bPatchset==0 ){
   179434     int bRequired = 0;
   179435 
   179436     assert( aOldRecord1 && aNewRecord1 );
   179437 
   179438     /* Write the old.* vector first. */
   179439     for(i=0; i<pTab->nCol; i++){
   179440       int nOld;
   179441       u8 *aOld;
   179442       int nNew;
   179443       u8 *aNew;
   179444 
   179445       aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
   179446       aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
   179447       if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
   179448         if( pTab->abPK[i]==0 ) bRequired = 1;
   179449         memcpy(aOut, aOld, nOld);
   179450         aOut += nOld;
   179451       }else{
   179452         *(aOut++) = '\0';
   179453       }
   179454     }
   179455 
   179456     if( !bRequired ) return 0;
   179457   }
   179458 
   179459   /* Write the new.* vector */
   179460   aOld1 = aOldRecord1;
   179461   aOld2 = aOldRecord2;
   179462   aNew1 = aNewRecord1;
   179463   aNew2 = aNewRecord2;
   179464   for(i=0; i<pTab->nCol; i++){
   179465     int nOld;
   179466     u8 *aOld;
   179467     int nNew;
   179468     u8 *aNew;
   179469 
   179470     aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
   179471     aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
   179472     if( bPatchset==0
   179473      && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
   179474     ){
   179475       *(aOut++) = '\0';
   179476     }else{
   179477       memcpy(aOut, aNew, nNew);
   179478       aOut += nNew;
   179479     }
   179480   }
   179481 
   179482   *paOut = aOut;
   179483   return 1;
   179484 }
   179485 
   179486 /*
   179487 ** This function is only called from within a pre-update-hook callback.
   179488 ** It determines if the current pre-update-hook change affects the same row
   179489 ** as the change stored in argument pChange. If so, it returns true. Otherwise
   179490 ** if the pre-update-hook does not affect the same row as pChange, it returns
   179491 ** false.
   179492 */
   179493 static int sessionPreupdateEqual(
   179494   sqlite3_session *pSession,      /* Session object that owns SessionTable */
   179495   SessionTable *pTab,             /* Table associated with change */
   179496   SessionChange *pChange,         /* Change to compare to */
   179497   int op                          /* Current pre-update operation */
   179498 ){
   179499   int iCol;                       /* Used to iterate through columns */
   179500   u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
   179501 
   179502   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
   179503   for(iCol=0; iCol<pTab->nCol; iCol++){
   179504     if( !pTab->abPK[iCol] ){
   179505       a += sessionSerialLen(a);
   179506     }else{
   179507       sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
   179508       int rc;                     /* Error code from preupdate_new/old */
   179509       int eType = *a++;           /* Type of value from change record */
   179510 
   179511       /* The following calls to preupdate_new() and preupdate_old() can not
   179512       ** fail. This is because they cache their return values, and by the
   179513       ** time control flows to here they have already been called once from
   179514       ** within sessionPreupdateHash(). The first two asserts below verify
   179515       ** this (that the method has already been called). */
   179516       if( op==SQLITE_INSERT ){
   179517         /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
   179518         rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
   179519       }else{
   179520         /* assert( db->pPreUpdate->pUnpacked ); */
   179521         rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
   179522       }
   179523       assert( rc==SQLITE_OK );
   179524       if( sqlite3_value_type(pVal)!=eType ) return 0;
   179525 
   179526       /* A SessionChange object never has a NULL value in a PK column */
   179527       assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
   179528            || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
   179529       );
   179530 
   179531       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   179532         i64 iVal = sessionGetI64(a);
   179533         a += 8;
   179534         if( eType==SQLITE_INTEGER ){
   179535           if( sqlite3_value_int64(pVal)!=iVal ) return 0;
   179536         }else{
   179537           double rVal;
   179538           assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
   179539           memcpy(&rVal, &iVal, 8);
   179540           if( sqlite3_value_double(pVal)!=rVal ) return 0;
   179541         }
   179542       }else{
   179543         int n;
   179544         const u8 *z;
   179545         a += sessionVarintGet(a, &n);
   179546         if( sqlite3_value_bytes(pVal)!=n ) return 0;
   179547         if( eType==SQLITE_TEXT ){
   179548           z = sqlite3_value_text(pVal);
   179549         }else{
   179550           z = sqlite3_value_blob(pVal);
   179551         }
   179552         if( memcmp(a, z, n) ) return 0;
   179553         a += n;
   179554       }
   179555     }
   179556   }
   179557 
   179558   return 1;
   179559 }
   179560 
   179561 /*
   179562 ** If required, grow the hash table used to store changes on table pTab
   179563 ** (part of the session pSession). If a fatal OOM error occurs, set the
   179564 ** session object to failed and return SQLITE_ERROR. Otherwise, return
   179565 ** SQLITE_OK.
   179566 **
   179567 ** It is possible that a non-fatal OOM error occurs in this function. In
   179568 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
   179569 ** Growing the hash table in this case is a performance optimization only,
   179570 ** it is not required for correct operation.
   179571 */
   179572 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
   179573   if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
   179574     int i;
   179575     SessionChange **apNew;
   179576     int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
   179577 
   179578     apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
   179579     if( apNew==0 ){
   179580       if( pTab->nChange==0 ){
   179581         return SQLITE_ERROR;
   179582       }
   179583       return SQLITE_OK;
   179584     }
   179585     memset(apNew, 0, sizeof(SessionChange *) * nNew);
   179586 
   179587     for(i=0; i<pTab->nChange; i++){
   179588       SessionChange *p;
   179589       SessionChange *pNext;
   179590       for(p=pTab->apChange[i]; p; p=pNext){
   179591         int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
   179592         int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
   179593         pNext = p->pNext;
   179594         p->pNext = apNew[iHash];
   179595         apNew[iHash] = p;
   179596       }
   179597     }
   179598 
   179599     sqlite3_free(pTab->apChange);
   179600     pTab->nChange = nNew;
   179601     pTab->apChange = apNew;
   179602   }
   179603 
   179604   return SQLITE_OK;
   179605 }
   179606 
   179607 /*
   179608 ** This function queries the database for the names of the columns of table
   179609 ** zThis, in schema zDb.
   179610 **
   179611 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
   179612 ** of columns in the database table and variable *pzTab is set to point to a
   179613 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
   179614 ** point to an array of pointers to column names. And *pabPK (again, if not
   179615 ** NULL) is set to point to an array of booleans - true if the corresponding
   179616 ** column is part of the primary key.
   179617 **
   179618 ** For example, if the table is declared as:
   179619 **
   179620 **     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
   179621 **
   179622 ** Then the four output variables are populated as follows:
   179623 **
   179624 **     *pnCol  = 4
   179625 **     *pzTab  = "tbl1"
   179626 **     *pazCol = {"w", "x", "y", "z"}
   179627 **     *pabPK  = {1, 0, 0, 1}
   179628 **
   179629 ** All returned buffers are part of the same single allocation, which must
   179630 ** be freed using sqlite3_free() by the caller
   179631 */
   179632 static int sessionTableInfo(
   179633   sqlite3 *db,                    /* Database connection */
   179634   const char *zDb,                /* Name of attached database (e.g. "main") */
   179635   const char *zThis,              /* Table name */
   179636   int *pnCol,                     /* OUT: number of columns */
   179637   const char **pzTab,             /* OUT: Copy of zThis */
   179638   const char ***pazCol,           /* OUT: Array of column names for table */
   179639   u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
   179640 ){
   179641   char *zPragma;
   179642   sqlite3_stmt *pStmt;
   179643   int rc;
   179644   int nByte;
   179645   int nDbCol = 0;
   179646   int nThis;
   179647   int i;
   179648   u8 *pAlloc = 0;
   179649   char **azCol = 0;
   179650   u8 *abPK = 0;
   179651 
   179652   assert( pazCol && pabPK );
   179653 
   179654   nThis = sqlite3Strlen30(zThis);
   179655   if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
   179656     rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
   179657     if( rc==SQLITE_OK ){
   179658       /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
   179659       zPragma = sqlite3_mprintf(
   179660           "SELECT 0, 'tbl',  '', 0, '', 1     UNION ALL "
   179661           "SELECT 1, 'idx',  '', 0, '', 2     UNION ALL "
   179662           "SELECT 2, 'stat', '', 0, '', 0"
   179663       );
   179664     }else if( rc==SQLITE_ERROR ){
   179665       zPragma = sqlite3_mprintf("");
   179666     }else{
   179667       return rc;
   179668     }
   179669   }else{
   179670     zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
   179671   }
   179672   if( !zPragma ) return SQLITE_NOMEM;
   179673 
   179674   rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
   179675   sqlite3_free(zPragma);
   179676   if( rc!=SQLITE_OK ) return rc;
   179677 
   179678   nByte = nThis + 1;
   179679   while( SQLITE_ROW==sqlite3_step(pStmt) ){
   179680     nByte += sqlite3_column_bytes(pStmt, 1);
   179681     nDbCol++;
   179682   }
   179683   rc = sqlite3_reset(pStmt);
   179684 
   179685   if( rc==SQLITE_OK ){
   179686     nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
   179687     pAlloc = sqlite3_malloc(nByte);
   179688     if( pAlloc==0 ){
   179689       rc = SQLITE_NOMEM;
   179690     }
   179691   }
   179692   if( rc==SQLITE_OK ){
   179693     azCol = (char **)pAlloc;
   179694     pAlloc = (u8 *)&azCol[nDbCol];
   179695     abPK = (u8 *)pAlloc;
   179696     pAlloc = &abPK[nDbCol];
   179697     if( pzTab ){
   179698       memcpy(pAlloc, zThis, nThis+1);
   179699       *pzTab = (char *)pAlloc;
   179700       pAlloc += nThis+1;
   179701     }
   179702 
   179703     i = 0;
   179704     while( SQLITE_ROW==sqlite3_step(pStmt) ){
   179705       int nName = sqlite3_column_bytes(pStmt, 1);
   179706       const unsigned char *zName = sqlite3_column_text(pStmt, 1);
   179707       if( zName==0 ) break;
   179708       memcpy(pAlloc, zName, nName+1);
   179709       azCol[i] = (char *)pAlloc;
   179710       pAlloc += nName+1;
   179711       abPK[i] = sqlite3_column_int(pStmt, 5);
   179712       i++;
   179713     }
   179714     rc = sqlite3_reset(pStmt);
   179715 
   179716   }
   179717 
   179718   /* If successful, populate the output variables. Otherwise, zero them and
   179719   ** free any allocation made. An error code will be returned in this case.
   179720   */
   179721   if( rc==SQLITE_OK ){
   179722     *pazCol = (const char **)azCol;
   179723     *pabPK = abPK;
   179724     *pnCol = nDbCol;
   179725   }else{
   179726     *pazCol = 0;
   179727     *pabPK = 0;
   179728     *pnCol = 0;
   179729     if( pzTab ) *pzTab = 0;
   179730     sqlite3_free(azCol);
   179731   }
   179732   sqlite3_finalize(pStmt);
   179733   return rc;
   179734 }
   179735 
   179736 /*
   179737 ** This function is only called from within a pre-update handler for a
   179738 ** write to table pTab, part of session pSession. If this is the first
   179739 ** write to this table, initalize the SessionTable.nCol, azCol[] and
   179740 ** abPK[] arrays accordingly.
   179741 **
   179742 ** If an error occurs, an error code is stored in sqlite3_session.rc and
   179743 ** non-zero returned. Or, if no error occurs but the table has no primary
   179744 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
   179745 ** indicate that updates on this table should be ignored. SessionTable.abPK
   179746 ** is set to NULL in this case.
   179747 */
   179748 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
   179749   if( pTab->nCol==0 ){
   179750     u8 *abPK;
   179751     assert( pTab->azCol==0 || pTab->abPK==0 );
   179752     pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
   179753         pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
   179754     );
   179755     if( pSession->rc==SQLITE_OK ){
   179756       int i;
   179757       for(i=0; i<pTab->nCol; i++){
   179758         if( abPK[i] ){
   179759           pTab->abPK = abPK;
   179760           break;
   179761         }
   179762       }
   179763       if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
   179764         pTab->bStat1 = 1;
   179765       }
   179766     }
   179767   }
   179768   return (pSession->rc || pTab->abPK==0);
   179769 }
   179770 
   179771 /*
   179772 ** Versions of the four methods in object SessionHook for use with the
   179773 ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
   179774 ** blob each time a NULL value is read from the "idx" column of the
   179775 ** sqlite_stat1 table.
   179776 */
   179777 typedef struct SessionStat1Ctx SessionStat1Ctx;
   179778 struct SessionStat1Ctx {
   179779   SessionHook hook;
   179780   sqlite3_session *pSession;
   179781 };
   179782 static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
   179783   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
   179784   sqlite3_value *pVal = 0;
   179785   int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
   179786   if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
   179787     pVal = p->pSession->pZeroBlob;
   179788   }
   179789   *ppVal = pVal;
   179790   return rc;
   179791 }
   179792 static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
   179793   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
   179794   sqlite3_value *pVal = 0;
   179795   int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
   179796   if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
   179797     pVal = p->pSession->pZeroBlob;
   179798   }
   179799   *ppVal = pVal;
   179800   return rc;
   179801 }
   179802 static int sessionStat1Count(void *pCtx){
   179803   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
   179804   return p->hook.xCount(p->hook.pCtx);
   179805 }
   179806 static int sessionStat1Depth(void *pCtx){
   179807   SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
   179808   return p->hook.xDepth(p->hook.pCtx);
   179809 }
   179810 
   179811 
   179812 /*
   179813 ** This function is only called from with a pre-update-hook reporting a
   179814 ** change on table pTab (attached to session pSession). The type of change
   179815 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
   179816 **
   179817 ** Unless one is already present or an error occurs, an entry is added
   179818 ** to the changed-rows hash table associated with table pTab.
   179819 */
   179820 static void sessionPreupdateOneChange(
   179821   int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
   179822   sqlite3_session *pSession,      /* Session object pTab is attached to */
   179823   SessionTable *pTab              /* Table that change applies to */
   179824 ){
   179825   int iHash;
   179826   int bNull = 0;
   179827   int rc = SQLITE_OK;
   179828   SessionStat1Ctx stat1;
   179829 
   179830   if( pSession->rc ) return;
   179831 
   179832   /* Load table details if required */
   179833   if( sessionInitTable(pSession, pTab) ) return;
   179834 
   179835   /* Check the number of columns in this xPreUpdate call matches the
   179836   ** number of columns in the table.  */
   179837   if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
   179838     pSession->rc = SQLITE_SCHEMA;
   179839     return;
   179840   }
   179841 
   179842   /* Grow the hash table if required */
   179843   if( sessionGrowHash(0, pTab) ){
   179844     pSession->rc = SQLITE_NOMEM;
   179845     return;
   179846   }
   179847 
   179848   if( pTab->bStat1 ){
   179849     stat1.hook = pSession->hook;
   179850     stat1.pSession = pSession;
   179851     pSession->hook.pCtx = (void*)&stat1;
   179852     pSession->hook.xNew = sessionStat1New;
   179853     pSession->hook.xOld = sessionStat1Old;
   179854     pSession->hook.xCount = sessionStat1Count;
   179855     pSession->hook.xDepth = sessionStat1Depth;
   179856     if( pSession->pZeroBlob==0 ){
   179857       sqlite3_value *p = sqlite3ValueNew(0);
   179858       if( p==0 ){
   179859         rc = SQLITE_NOMEM;
   179860         goto error_out;
   179861       }
   179862       sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
   179863       pSession->pZeroBlob = p;
   179864     }
   179865   }
   179866 
   179867   /* Calculate the hash-key for this change. If the primary key of the row
   179868   ** includes a NULL value, exit early. Such changes are ignored by the
   179869   ** session module. */
   179870   rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
   179871   if( rc!=SQLITE_OK ) goto error_out;
   179872 
   179873   if( bNull==0 ){
   179874     /* Search the hash table for an existing record for this row. */
   179875     SessionChange *pC;
   179876     for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
   179877       if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
   179878     }
   179879 
   179880     if( pC==0 ){
   179881       /* Create a new change object containing all the old values (if
   179882       ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
   179883       ** values (if this is an INSERT). */
   179884       SessionChange *pChange; /* New change object */
   179885       int nByte;              /* Number of bytes to allocate */
   179886       int i;                  /* Used to iterate through columns */
   179887 
   179888       assert( rc==SQLITE_OK );
   179889       pTab->nEntry++;
   179890 
   179891       /* Figure out how large an allocation is required */
   179892       nByte = sizeof(SessionChange);
   179893       for(i=0; i<pTab->nCol; i++){
   179894         sqlite3_value *p = 0;
   179895         if( op!=SQLITE_INSERT ){
   179896           TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
   179897           assert( trc==SQLITE_OK );
   179898         }else if( pTab->abPK[i] ){
   179899           TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
   179900           assert( trc==SQLITE_OK );
   179901         }
   179902 
   179903         /* This may fail if SQLite value p contains a utf-16 string that must
   179904         ** be converted to utf-8 and an OOM error occurs while doing so. */
   179905         rc = sessionSerializeValue(0, p, &nByte);
   179906         if( rc!=SQLITE_OK ) goto error_out;
   179907       }
   179908 
   179909       /* Allocate the change object */
   179910       pChange = (SessionChange *)sqlite3_malloc(nByte);
   179911       if( !pChange ){
   179912         rc = SQLITE_NOMEM;
   179913         goto error_out;
   179914       }else{
   179915         memset(pChange, 0, sizeof(SessionChange));
   179916         pChange->aRecord = (u8 *)&pChange[1];
   179917       }
   179918 
   179919       /* Populate the change object. None of the preupdate_old(),
   179920       ** preupdate_new() or SerializeValue() calls below may fail as all
   179921       ** required values and encodings have already been cached in memory.
   179922       ** It is not possible for an OOM to occur in this block. */
   179923       nByte = 0;
   179924       for(i=0; i<pTab->nCol; i++){
   179925         sqlite3_value *p = 0;
   179926         if( op!=SQLITE_INSERT ){
   179927           pSession->hook.xOld(pSession->hook.pCtx, i, &p);
   179928         }else if( pTab->abPK[i] ){
   179929           pSession->hook.xNew(pSession->hook.pCtx, i, &p);
   179930         }
   179931         sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
   179932       }
   179933 
   179934       /* Add the change to the hash-table */
   179935       if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
   179936         pChange->bIndirect = 1;
   179937       }
   179938       pChange->nRecord = nByte;
   179939       pChange->op = op;
   179940       pChange->pNext = pTab->apChange[iHash];
   179941       pTab->apChange[iHash] = pChange;
   179942 
   179943     }else if( pC->bIndirect ){
   179944       /* If the existing change is considered "indirect", but this current
   179945       ** change is "direct", mark the change object as direct. */
   179946       if( pSession->hook.xDepth(pSession->hook.pCtx)==0
   179947        && pSession->bIndirect==0
   179948       ){
   179949         pC->bIndirect = 0;
   179950       }
   179951     }
   179952   }
   179953 
   179954   /* If an error has occurred, mark the session object as failed. */
   179955  error_out:
   179956   if( pTab->bStat1 ){
   179957     pSession->hook = stat1.hook;
   179958   }
   179959   if( rc!=SQLITE_OK ){
   179960     pSession->rc = rc;
   179961   }
   179962 }
   179963 
   179964 static int sessionFindTable(
   179965   sqlite3_session *pSession,
   179966   const char *zName,
   179967   SessionTable **ppTab
   179968 ){
   179969   int rc = SQLITE_OK;
   179970   int nName = sqlite3Strlen30(zName);
   179971   SessionTable *pRet;
   179972 
   179973   /* Search for an existing table */
   179974   for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
   179975     if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
   179976   }
   179977 
   179978   if( pRet==0 && pSession->bAutoAttach ){
   179979     /* If there is a table-filter configured, invoke it. If it returns 0,
   179980     ** do not automatically add the new table. */
   179981     if( pSession->xTableFilter==0
   179982      || pSession->xTableFilter(pSession->pFilterCtx, zName)
   179983     ){
   179984       rc = sqlite3session_attach(pSession, zName);
   179985       if( rc==SQLITE_OK ){
   179986         for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
   179987         assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
   179988       }
   179989     }
   179990   }
   179991 
   179992   assert( rc==SQLITE_OK || pRet==0 );
   179993   *ppTab = pRet;
   179994   return rc;
   179995 }
   179996 
   179997 /*
   179998 ** The 'pre-update' hook registered by this module with SQLite databases.
   179999 */
   180000 static void xPreUpdate(
   180001   void *pCtx,                     /* Copy of third arg to preupdate_hook() */
   180002   sqlite3 *db,                    /* Database handle */
   180003   int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
   180004   char const *zDb,                /* Database name */
   180005   char const *zName,              /* Table name */
   180006   sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
   180007   sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
   180008 ){
   180009   sqlite3_session *pSession;
   180010   int nDb = sqlite3Strlen30(zDb);
   180011 
   180012   assert( sqlite3_mutex_held(db->mutex) );
   180013 
   180014   for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
   180015     SessionTable *pTab;
   180016 
   180017     /* If this session is attached to a different database ("main", "temp"
   180018     ** etc.), or if it is not currently enabled, there is nothing to do. Skip
   180019     ** to the next session object attached to this database. */
   180020     if( pSession->bEnable==0 ) continue;
   180021     if( pSession->rc ) continue;
   180022     if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
   180023 
   180024     pSession->rc = sessionFindTable(pSession, zName, &pTab);
   180025     if( pTab ){
   180026       assert( pSession->rc==SQLITE_OK );
   180027       sessionPreupdateOneChange(op, pSession, pTab);
   180028       if( op==SQLITE_UPDATE ){
   180029         sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
   180030       }
   180031     }
   180032   }
   180033 }
   180034 
   180035 /*
   180036 ** The pre-update hook implementations.
   180037 */
   180038 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
   180039   return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
   180040 }
   180041 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
   180042   return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
   180043 }
   180044 static int sessionPreupdateCount(void *pCtx){
   180045   return sqlite3_preupdate_count((sqlite3*)pCtx);
   180046 }
   180047 static int sessionPreupdateDepth(void *pCtx){
   180048   return sqlite3_preupdate_depth((sqlite3*)pCtx);
   180049 }
   180050 
   180051 /*
   180052 ** Install the pre-update hooks on the session object passed as the only
   180053 ** argument.
   180054 */
   180055 static void sessionPreupdateHooks(
   180056   sqlite3_session *pSession
   180057 ){
   180058   pSession->hook.pCtx = (void*)pSession->db;
   180059   pSession->hook.xOld = sessionPreupdateOld;
   180060   pSession->hook.xNew = sessionPreupdateNew;
   180061   pSession->hook.xCount = sessionPreupdateCount;
   180062   pSession->hook.xDepth = sessionPreupdateDepth;
   180063 }
   180064 
   180065 typedef struct SessionDiffCtx SessionDiffCtx;
   180066 struct SessionDiffCtx {
   180067   sqlite3_stmt *pStmt;
   180068   int nOldOff;
   180069 };
   180070 
   180071 /*
   180072 ** The diff hook implementations.
   180073 */
   180074 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
   180075   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
   180076   *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
   180077   return SQLITE_OK;
   180078 }
   180079 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
   180080   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
   180081   *ppVal = sqlite3_column_value(p->pStmt, iVal);
   180082    return SQLITE_OK;
   180083 }
   180084 static int sessionDiffCount(void *pCtx){
   180085   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
   180086   return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
   180087 }
   180088 static int sessionDiffDepth(void *pCtx){
   180089   return 0;
   180090 }
   180091 
   180092 /*
   180093 ** Install the diff hooks on the session object passed as the only
   180094 ** argument.
   180095 */
   180096 static void sessionDiffHooks(
   180097   sqlite3_session *pSession,
   180098   SessionDiffCtx *pDiffCtx
   180099 ){
   180100   pSession->hook.pCtx = (void*)pDiffCtx;
   180101   pSession->hook.xOld = sessionDiffOld;
   180102   pSession->hook.xNew = sessionDiffNew;
   180103   pSession->hook.xCount = sessionDiffCount;
   180104   pSession->hook.xDepth = sessionDiffDepth;
   180105 }
   180106 
   180107 static char *sessionExprComparePK(
   180108   int nCol,
   180109   const char *zDb1, const char *zDb2,
   180110   const char *zTab,
   180111   const char **azCol, u8 *abPK
   180112 ){
   180113   int i;
   180114   const char *zSep = "";
   180115   char *zRet = 0;
   180116 
   180117   for(i=0; i<nCol; i++){
   180118     if( abPK[i] ){
   180119       zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
   180120           zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
   180121       );
   180122       zSep = " AND ";
   180123       if( zRet==0 ) break;
   180124     }
   180125   }
   180126 
   180127   return zRet;
   180128 }
   180129 
   180130 static char *sessionExprCompareOther(
   180131   int nCol,
   180132   const char *zDb1, const char *zDb2,
   180133   const char *zTab,
   180134   const char **azCol, u8 *abPK
   180135 ){
   180136   int i;
   180137   const char *zSep = "";
   180138   char *zRet = 0;
   180139   int bHave = 0;
   180140 
   180141   for(i=0; i<nCol; i++){
   180142     if( abPK[i]==0 ){
   180143       bHave = 1;
   180144       zRet = sqlite3_mprintf(
   180145           "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
   180146           zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
   180147       );
   180148       zSep = " OR ";
   180149       if( zRet==0 ) break;
   180150     }
   180151   }
   180152 
   180153   if( bHave==0 ){
   180154     assert( zRet==0 );
   180155     zRet = sqlite3_mprintf("0");
   180156   }
   180157 
   180158   return zRet;
   180159 }
   180160 
   180161 static char *sessionSelectFindNew(
   180162   int nCol,
   180163   const char *zDb1,      /* Pick rows in this db only */
   180164   const char *zDb2,      /* But not in this one */
   180165   const char *zTbl,      /* Table name */
   180166   const char *zExpr
   180167 ){
   180168   char *zRet = sqlite3_mprintf(
   180169       "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
   180170       "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
   180171       ")",
   180172       zDb1, zTbl, zDb2, zTbl, zExpr
   180173   );
   180174   return zRet;
   180175 }
   180176 
   180177 static int sessionDiffFindNew(
   180178   int op,
   180179   sqlite3_session *pSession,
   180180   SessionTable *pTab,
   180181   const char *zDb1,
   180182   const char *zDb2,
   180183   char *zExpr
   180184 ){
   180185   int rc = SQLITE_OK;
   180186   char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
   180187 
   180188   if( zStmt==0 ){
   180189     rc = SQLITE_NOMEM;
   180190   }else{
   180191     sqlite3_stmt *pStmt;
   180192     rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
   180193     if( rc==SQLITE_OK ){
   180194       SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
   180195       pDiffCtx->pStmt = pStmt;
   180196       pDiffCtx->nOldOff = 0;
   180197       while( SQLITE_ROW==sqlite3_step(pStmt) ){
   180198         sessionPreupdateOneChange(op, pSession, pTab);
   180199       }
   180200       rc = sqlite3_finalize(pStmt);
   180201     }
   180202     sqlite3_free(zStmt);
   180203   }
   180204 
   180205   return rc;
   180206 }
   180207 
   180208 static int sessionDiffFindModified(
   180209   sqlite3_session *pSession,
   180210   SessionTable *pTab,
   180211   const char *zFrom,
   180212   const char *zExpr
   180213 ){
   180214   int rc = SQLITE_OK;
   180215 
   180216   char *zExpr2 = sessionExprCompareOther(pTab->nCol,
   180217       pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
   180218   );
   180219   if( zExpr2==0 ){
   180220     rc = SQLITE_NOMEM;
   180221   }else{
   180222     char *zStmt = sqlite3_mprintf(
   180223         "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
   180224         pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
   180225     );
   180226     if( zStmt==0 ){
   180227       rc = SQLITE_NOMEM;
   180228     }else{
   180229       sqlite3_stmt *pStmt;
   180230       rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
   180231 
   180232       if( rc==SQLITE_OK ){
   180233         SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
   180234         pDiffCtx->pStmt = pStmt;
   180235         pDiffCtx->nOldOff = pTab->nCol;
   180236         while( SQLITE_ROW==sqlite3_step(pStmt) ){
   180237           sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
   180238         }
   180239         rc = sqlite3_finalize(pStmt);
   180240       }
   180241       sqlite3_free(zStmt);
   180242     }
   180243   }
   180244 
   180245   return rc;
   180246 }
   180247 
   180248 SQLITE_API int sqlite3session_diff(
   180249   sqlite3_session *pSession,
   180250   const char *zFrom,
   180251   const char *zTbl,
   180252   char **pzErrMsg
   180253 ){
   180254   const char *zDb = pSession->zDb;
   180255   int rc = pSession->rc;
   180256   SessionDiffCtx d;
   180257 
   180258   memset(&d, 0, sizeof(d));
   180259   sessionDiffHooks(pSession, &d);
   180260 
   180261   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
   180262   if( pzErrMsg ) *pzErrMsg = 0;
   180263   if( rc==SQLITE_OK ){
   180264     char *zExpr = 0;
   180265     sqlite3 *db = pSession->db;
   180266     SessionTable *pTo;            /* Table zTbl */
   180267 
   180268     /* Locate and if necessary initialize the target table object */
   180269     rc = sessionFindTable(pSession, zTbl, &pTo);
   180270     if( pTo==0 ) goto diff_out;
   180271     if( sessionInitTable(pSession, pTo) ){
   180272       rc = pSession->rc;
   180273       goto diff_out;
   180274     }
   180275 
   180276     /* Check the table schemas match */
   180277     if( rc==SQLITE_OK ){
   180278       int bHasPk = 0;
   180279       int bMismatch = 0;
   180280       int nCol;                   /* Columns in zFrom.zTbl */
   180281       u8 *abPK;
   180282       const char **azCol = 0;
   180283       rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
   180284       if( rc==SQLITE_OK ){
   180285         if( pTo->nCol!=nCol ){
   180286           bMismatch = 1;
   180287         }else{
   180288           int i;
   180289           for(i=0; i<nCol; i++){
   180290             if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
   180291             if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
   180292             if( abPK[i] ) bHasPk = 1;
   180293           }
   180294         }
   180295       }
   180296       sqlite3_free((char*)azCol);
   180297       if( bMismatch ){
   180298         *pzErrMsg = sqlite3_mprintf("table schemas do not match");
   180299         rc = SQLITE_SCHEMA;
   180300       }
   180301       if( bHasPk==0 ){
   180302         /* Ignore tables with no primary keys */
   180303         goto diff_out;
   180304       }
   180305     }
   180306 
   180307     if( rc==SQLITE_OK ){
   180308       zExpr = sessionExprComparePK(pTo->nCol,
   180309           zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
   180310       );
   180311     }
   180312 
   180313     /* Find new rows */
   180314     if( rc==SQLITE_OK ){
   180315       rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
   180316     }
   180317 
   180318     /* Find old rows */
   180319     if( rc==SQLITE_OK ){
   180320       rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
   180321     }
   180322 
   180323     /* Find modified rows */
   180324     if( rc==SQLITE_OK ){
   180325       rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
   180326     }
   180327 
   180328     sqlite3_free(zExpr);
   180329   }
   180330 
   180331  diff_out:
   180332   sessionPreupdateHooks(pSession);
   180333   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
   180334   return rc;
   180335 }
   180336 
   180337 /*
   180338 ** Create a session object. This session object will record changes to
   180339 ** database zDb attached to connection db.
   180340 */
   180341 SQLITE_API int sqlite3session_create(
   180342   sqlite3 *db,                    /* Database handle */
   180343   const char *zDb,                /* Name of db (e.g. "main") */
   180344   sqlite3_session **ppSession     /* OUT: New session object */
   180345 ){
   180346   sqlite3_session *pNew;          /* Newly allocated session object */
   180347   sqlite3_session *pOld;          /* Session object already attached to db */
   180348   int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
   180349 
   180350   /* Zero the output value in case an error occurs. */
   180351   *ppSession = 0;
   180352 
   180353   /* Allocate and populate the new session object. */
   180354   pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
   180355   if( !pNew ) return SQLITE_NOMEM;
   180356   memset(pNew, 0, sizeof(sqlite3_session));
   180357   pNew->db = db;
   180358   pNew->zDb = (char *)&pNew[1];
   180359   pNew->bEnable = 1;
   180360   memcpy(pNew->zDb, zDb, nDb+1);
   180361   sessionPreupdateHooks(pNew);
   180362 
   180363   /* Add the new session object to the linked list of session objects
   180364   ** attached to database handle $db. Do this under the cover of the db
   180365   ** handle mutex.  */
   180366   sqlite3_mutex_enter(sqlite3_db_mutex(db));
   180367   pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
   180368   pNew->pNext = pOld;
   180369   sqlite3_mutex_leave(sqlite3_db_mutex(db));
   180370 
   180371   *ppSession = pNew;
   180372   return SQLITE_OK;
   180373 }
   180374 
   180375 /*
   180376 ** Free the list of table objects passed as the first argument. The contents
   180377 ** of the changed-rows hash tables are also deleted.
   180378 */
   180379 static void sessionDeleteTable(SessionTable *pList){
   180380   SessionTable *pNext;
   180381   SessionTable *pTab;
   180382 
   180383   for(pTab=pList; pTab; pTab=pNext){
   180384     int i;
   180385     pNext = pTab->pNext;
   180386     for(i=0; i<pTab->nChange; i++){
   180387       SessionChange *p;
   180388       SessionChange *pNextChange;
   180389       for(p=pTab->apChange[i]; p; p=pNextChange){
   180390         pNextChange = p->pNext;
   180391         sqlite3_free(p);
   180392       }
   180393     }
   180394     sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
   180395     sqlite3_free(pTab->apChange);
   180396     sqlite3_free(pTab);
   180397   }
   180398 }
   180399 
   180400 /*
   180401 ** Delete a session object previously allocated using sqlite3session_create().
   180402 */
   180403 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
   180404   sqlite3 *db = pSession->db;
   180405   sqlite3_session *pHead;
   180406   sqlite3_session **pp;
   180407 
   180408   /* Unlink the session from the linked list of sessions attached to the
   180409   ** database handle. Hold the db mutex while doing so.  */
   180410   sqlite3_mutex_enter(sqlite3_db_mutex(db));
   180411   pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
   180412   for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
   180413     if( (*pp)==pSession ){
   180414       *pp = (*pp)->pNext;
   180415       if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
   180416       break;
   180417     }
   180418   }
   180419   sqlite3_mutex_leave(sqlite3_db_mutex(db));
   180420   sqlite3ValueFree(pSession->pZeroBlob);
   180421 
   180422   /* Delete all attached table objects. And the contents of their
   180423   ** associated hash-tables. */
   180424   sessionDeleteTable(pSession->pTable);
   180425 
   180426   /* Free the session object itself. */
   180427   sqlite3_free(pSession);
   180428 }
   180429 
   180430 /*
   180431 ** Set a table filter on a Session Object.
   180432 */
   180433 SQLITE_API void sqlite3session_table_filter(
   180434   sqlite3_session *pSession,
   180435   int(*xFilter)(void*, const char*),
   180436   void *pCtx                      /* First argument passed to xFilter */
   180437 ){
   180438   pSession->bAutoAttach = 1;
   180439   pSession->pFilterCtx = pCtx;
   180440   pSession->xTableFilter = xFilter;
   180441 }
   180442 
   180443 /*
   180444 ** Attach a table to a session. All subsequent changes made to the table
   180445 ** while the session object is enabled will be recorded.
   180446 **
   180447 ** Only tables that have a PRIMARY KEY defined may be attached. It does
   180448 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
   180449 ** or not.
   180450 */
   180451 SQLITE_API int sqlite3session_attach(
   180452   sqlite3_session *pSession,      /* Session object */
   180453   const char *zName               /* Table name */
   180454 ){
   180455   int rc = SQLITE_OK;
   180456   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
   180457 
   180458   if( !zName ){
   180459     pSession->bAutoAttach = 1;
   180460   }else{
   180461     SessionTable *pTab;           /* New table object (if required) */
   180462     int nName;                    /* Number of bytes in string zName */
   180463 
   180464     /* First search for an existing entry. If one is found, this call is
   180465     ** a no-op. Return early. */
   180466     nName = sqlite3Strlen30(zName);
   180467     for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
   180468       if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
   180469     }
   180470 
   180471     if( !pTab ){
   180472       /* Allocate new SessionTable object. */
   180473       pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
   180474       if( !pTab ){
   180475         rc = SQLITE_NOMEM;
   180476       }else{
   180477         /* Populate the new SessionTable object and link it into the list.
   180478         ** The new object must be linked onto the end of the list, not
   180479         ** simply added to the start of it in order to ensure that tables
   180480         ** appear in the correct order when a changeset or patchset is
   180481         ** eventually generated. */
   180482         SessionTable **ppTab;
   180483         memset(pTab, 0, sizeof(SessionTable));
   180484         pTab->zName = (char *)&pTab[1];
   180485         memcpy(pTab->zName, zName, nName+1);
   180486         for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
   180487         *ppTab = pTab;
   180488       }
   180489     }
   180490   }
   180491 
   180492   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
   180493   return rc;
   180494 }
   180495 
   180496 /*
   180497 ** Ensure that there is room in the buffer to append nByte bytes of data.
   180498 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
   180499 **
   180500 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
   180501 ** set *pRc to SQLITE_NOMEM and return non-zero.
   180502 */
   180503 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
   180504   if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
   180505     u8 *aNew;
   180506     int nNew = p->nAlloc ? p->nAlloc : 128;
   180507     do {
   180508       nNew = nNew*2;
   180509     }while( nNew<(p->nBuf+nByte) );
   180510 
   180511     aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
   180512     if( 0==aNew ){
   180513       *pRc = SQLITE_NOMEM;
   180514     }else{
   180515       p->aBuf = aNew;
   180516       p->nAlloc = nNew;
   180517     }
   180518   }
   180519   return (*pRc!=SQLITE_OK);
   180520 }
   180521 
   180522 /*
   180523 ** Append the value passed as the second argument to the buffer passed
   180524 ** as the first.
   180525 **
   180526 ** This function is a no-op if *pRc is non-zero when it is called.
   180527 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
   180528 ** before returning.
   180529 */
   180530 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
   180531   int rc = *pRc;
   180532   if( rc==SQLITE_OK ){
   180533     int nByte = 0;
   180534     rc = sessionSerializeValue(0, pVal, &nByte);
   180535     sessionBufferGrow(p, nByte, &rc);
   180536     if( rc==SQLITE_OK ){
   180537       rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
   180538       p->nBuf += nByte;
   180539     }else{
   180540       *pRc = rc;
   180541     }
   180542   }
   180543 }
   180544 
   180545 /*
   180546 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
   180547 ** called. Otherwise, append a single byte to the buffer.
   180548 **
   180549 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
   180550 ** returning.
   180551 */
   180552 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
   180553   if( 0==sessionBufferGrow(p, 1, pRc) ){
   180554     p->aBuf[p->nBuf++] = v;
   180555   }
   180556 }
   180557 
   180558 /*
   180559 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
   180560 ** called. Otherwise, append a single varint to the buffer.
   180561 **
   180562 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
   180563 ** returning.
   180564 */
   180565 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
   180566   if( 0==sessionBufferGrow(p, 9, pRc) ){
   180567     p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
   180568   }
   180569 }
   180570 
   180571 /*
   180572 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
   180573 ** called. Otherwise, append a blob of data to the buffer.
   180574 **
   180575 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
   180576 ** returning.
   180577 */
   180578 static void sessionAppendBlob(
   180579   SessionBuffer *p,
   180580   const u8 *aBlob,
   180581   int nBlob,
   180582   int *pRc
   180583 ){
   180584   if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
   180585     memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
   180586     p->nBuf += nBlob;
   180587   }
   180588 }
   180589 
   180590 /*
   180591 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
   180592 ** called. Otherwise, append a string to the buffer. All bytes in the string
   180593 ** up to (but not including) the nul-terminator are written to the buffer.
   180594 **
   180595 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
   180596 ** returning.
   180597 */
   180598 static void sessionAppendStr(
   180599   SessionBuffer *p,
   180600   const char *zStr,
   180601   int *pRc
   180602 ){
   180603   int nStr = sqlite3Strlen30(zStr);
   180604   if( 0==sessionBufferGrow(p, nStr, pRc) ){
   180605     memcpy(&p->aBuf[p->nBuf], zStr, nStr);
   180606     p->nBuf += nStr;
   180607   }
   180608 }
   180609 
   180610 /*
   180611 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
   180612 ** called. Otherwise, append the string representation of integer iVal
   180613 ** to the buffer. No nul-terminator is written.
   180614 **
   180615 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
   180616 ** returning.
   180617 */
   180618 static void sessionAppendInteger(
   180619   SessionBuffer *p,               /* Buffer to append to */
   180620   int iVal,                       /* Value to write the string rep. of */
   180621   int *pRc                        /* IN/OUT: Error code */
   180622 ){
   180623   char aBuf[24];
   180624   sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
   180625   sessionAppendStr(p, aBuf, pRc);
   180626 }
   180627 
   180628 /*
   180629 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
   180630 ** called. Otherwise, append the string zStr enclosed in quotes (") and
   180631 ** with any embedded quote characters escaped to the buffer. No
   180632 ** nul-terminator byte is written.
   180633 **
   180634 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
   180635 ** returning.
   180636 */
   180637 static void sessionAppendIdent(
   180638   SessionBuffer *p,               /* Buffer to a append to */
   180639   const char *zStr,               /* String to quote, escape and append */
   180640   int *pRc                        /* IN/OUT: Error code */
   180641 ){
   180642   int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
   180643   if( 0==sessionBufferGrow(p, nStr, pRc) ){
   180644     char *zOut = (char *)&p->aBuf[p->nBuf];
   180645     const char *zIn = zStr;
   180646     *zOut++ = '"';
   180647     while( *zIn ){
   180648       if( *zIn=='"' ) *zOut++ = '"';
   180649       *zOut++ = *(zIn++);
   180650     }
   180651     *zOut++ = '"';
   180652     p->nBuf = (int)((u8 *)zOut - p->aBuf);
   180653   }
   180654 }
   180655 
   180656 /*
   180657 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
   180658 ** called. Otherwse, it appends the serialized version of the value stored
   180659 ** in column iCol of the row that SQL statement pStmt currently points
   180660 ** to to the buffer.
   180661 */
   180662 static void sessionAppendCol(
   180663   SessionBuffer *p,               /* Buffer to append to */
   180664   sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
   180665   int iCol,                       /* Column to read value from */
   180666   int *pRc                        /* IN/OUT: Error code */
   180667 ){
   180668   if( *pRc==SQLITE_OK ){
   180669     int eType = sqlite3_column_type(pStmt, iCol);
   180670     sessionAppendByte(p, (u8)eType, pRc);
   180671     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   180672       sqlite3_int64 i;
   180673       u8 aBuf[8];
   180674       if( eType==SQLITE_INTEGER ){
   180675         i = sqlite3_column_int64(pStmt, iCol);
   180676       }else{
   180677         double r = sqlite3_column_double(pStmt, iCol);
   180678         memcpy(&i, &r, 8);
   180679       }
   180680       sessionPutI64(aBuf, i);
   180681       sessionAppendBlob(p, aBuf, 8, pRc);
   180682     }
   180683     if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
   180684       u8 *z;
   180685       int nByte;
   180686       if( eType==SQLITE_BLOB ){
   180687         z = (u8 *)sqlite3_column_blob(pStmt, iCol);
   180688       }else{
   180689         z = (u8 *)sqlite3_column_text(pStmt, iCol);
   180690       }
   180691       nByte = sqlite3_column_bytes(pStmt, iCol);
   180692       if( z || (eType==SQLITE_BLOB && nByte==0) ){
   180693         sessionAppendVarint(p, nByte, pRc);
   180694         sessionAppendBlob(p, z, nByte, pRc);
   180695       }else{
   180696         *pRc = SQLITE_NOMEM;
   180697       }
   180698     }
   180699   }
   180700 }
   180701 
   180702 /*
   180703 **
   180704 ** This function appends an update change to the buffer (see the comments
   180705 ** under "CHANGESET FORMAT" at the top of the file). An update change
   180706 ** consists of:
   180707 **
   180708 **   1 byte:  SQLITE_UPDATE (0x17)
   180709 **   n bytes: old.* record (see RECORD FORMAT)
   180710 **   m bytes: new.* record (see RECORD FORMAT)
   180711 **
   180712 ** The SessionChange object passed as the third argument contains the
   180713 ** values that were stored in the row when the session began (the old.*
   180714 ** values). The statement handle passed as the second argument points
   180715 ** at the current version of the row (the new.* values).
   180716 **
   180717 ** If all of the old.* values are equal to their corresponding new.* value
   180718 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
   180719 **
   180720 ** Otherwise, the old.* record contains all primary key values and the
   180721 ** original values of any fields that have been modified. The new.* record
   180722 ** contains the new values of only those fields that have been modified.
   180723 */
   180724 static int sessionAppendUpdate(
   180725   SessionBuffer *pBuf,            /* Buffer to append to */
   180726   int bPatchset,                  /* True for "patchset", 0 for "changeset" */
   180727   sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
   180728   SessionChange *p,               /* Object containing old values */
   180729   u8 *abPK                        /* Boolean array - true for PK columns */
   180730 ){
   180731   int rc = SQLITE_OK;
   180732   SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
   180733   int bNoop = 1;                /* Set to zero if any values are modified */
   180734   int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
   180735   int i;                        /* Used to iterate through columns */
   180736   u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
   180737 
   180738   sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
   180739   sessionAppendByte(pBuf, p->bIndirect, &rc);
   180740   for(i=0; i<sqlite3_column_count(pStmt); i++){
   180741     int bChanged = 0;
   180742     int nAdvance;
   180743     int eType = *pCsr;
   180744     switch( eType ){
   180745       case SQLITE_NULL:
   180746         nAdvance = 1;
   180747         if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   180748           bChanged = 1;
   180749         }
   180750         break;
   180751 
   180752       case SQLITE_FLOAT:
   180753       case SQLITE_INTEGER: {
   180754         nAdvance = 9;
   180755         if( eType==sqlite3_column_type(pStmt, i) ){
   180756           sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
   180757           if( eType==SQLITE_INTEGER ){
   180758             if( iVal==sqlite3_column_int64(pStmt, i) ) break;
   180759           }else{
   180760             double dVal;
   180761             memcpy(&dVal, &iVal, 8);
   180762             if( dVal==sqlite3_column_double(pStmt, i) ) break;
   180763           }
   180764         }
   180765         bChanged = 1;
   180766         break;
   180767       }
   180768 
   180769       default: {
   180770         int n;
   180771         int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
   180772         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
   180773         nAdvance = nHdr + n;
   180774         if( eType==sqlite3_column_type(pStmt, i)
   180775          && n==sqlite3_column_bytes(pStmt, i)
   180776          && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
   180777         ){
   180778           break;
   180779         }
   180780         bChanged = 1;
   180781       }
   180782     }
   180783 
   180784     /* If at least one field has been modified, this is not a no-op. */
   180785     if( bChanged ) bNoop = 0;
   180786 
   180787     /* Add a field to the old.* record. This is omitted if this modules is
   180788     ** currently generating a patchset. */
   180789     if( bPatchset==0 ){
   180790       if( bChanged || abPK[i] ){
   180791         sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
   180792       }else{
   180793         sessionAppendByte(pBuf, 0, &rc);
   180794       }
   180795     }
   180796 
   180797     /* Add a field to the new.* record. Or the only record if currently
   180798     ** generating a patchset.  */
   180799     if( bChanged || (bPatchset && abPK[i]) ){
   180800       sessionAppendCol(&buf2, pStmt, i, &rc);
   180801     }else{
   180802       sessionAppendByte(&buf2, 0, &rc);
   180803     }
   180804 
   180805     pCsr += nAdvance;
   180806   }
   180807 
   180808   if( bNoop ){
   180809     pBuf->nBuf = nRewind;
   180810   }else{
   180811     sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
   180812   }
   180813   sqlite3_free(buf2.aBuf);
   180814 
   180815   return rc;
   180816 }
   180817 
   180818 /*
   180819 ** Append a DELETE change to the buffer passed as the first argument. Use
   180820 ** the changeset format if argument bPatchset is zero, or the patchset
   180821 ** format otherwise.
   180822 */
   180823 static int sessionAppendDelete(
   180824   SessionBuffer *pBuf,            /* Buffer to append to */
   180825   int bPatchset,                  /* True for "patchset", 0 for "changeset" */
   180826   SessionChange *p,               /* Object containing old values */
   180827   int nCol,                       /* Number of columns in table */
   180828   u8 *abPK                        /* Boolean array - true for PK columns */
   180829 ){
   180830   int rc = SQLITE_OK;
   180831 
   180832   sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
   180833   sessionAppendByte(pBuf, p->bIndirect, &rc);
   180834 
   180835   if( bPatchset==0 ){
   180836     sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
   180837   }else{
   180838     int i;
   180839     u8 *a = p->aRecord;
   180840     for(i=0; i<nCol; i++){
   180841       u8 *pStart = a;
   180842       int eType = *a++;
   180843 
   180844       switch( eType ){
   180845         case 0:
   180846         case SQLITE_NULL:
   180847           assert( abPK[i]==0 );
   180848           break;
   180849 
   180850         case SQLITE_FLOAT:
   180851         case SQLITE_INTEGER:
   180852           a += 8;
   180853           break;
   180854 
   180855         default: {
   180856           int n;
   180857           a += sessionVarintGet(a, &n);
   180858           a += n;
   180859           break;
   180860         }
   180861       }
   180862       if( abPK[i] ){
   180863         sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
   180864       }
   180865     }
   180866     assert( (a - p->aRecord)==p->nRecord );
   180867   }
   180868 
   180869   return rc;
   180870 }
   180871 
   180872 /*
   180873 ** Formulate and prepare a SELECT statement to retrieve a row from table
   180874 ** zTab in database zDb based on its primary key. i.e.
   180875 **
   180876 **   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
   180877 */
   180878 static int sessionSelectStmt(
   180879   sqlite3 *db,                    /* Database handle */
   180880   const char *zDb,                /* Database name */
   180881   const char *zTab,               /* Table name */
   180882   int nCol,                       /* Number of columns in table */
   180883   const char **azCol,             /* Names of table columns */
   180884   u8 *abPK,                       /* PRIMARY KEY  array */
   180885   sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
   180886 ){
   180887   int rc = SQLITE_OK;
   180888   char *zSql = 0;
   180889   int nSql = -1;
   180890 
   180891   if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
   180892     zSql = sqlite3_mprintf(
   180893         "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
   180894         "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
   180895     );
   180896   }else{
   180897     int i;
   180898     const char *zSep = "";
   180899     SessionBuffer buf = {0, 0, 0};
   180900 
   180901     sessionAppendStr(&buf, "SELECT * FROM ", &rc);
   180902     sessionAppendIdent(&buf, zDb, &rc);
   180903     sessionAppendStr(&buf, ".", &rc);
   180904     sessionAppendIdent(&buf, zTab, &rc);
   180905     sessionAppendStr(&buf, " WHERE ", &rc);
   180906     for(i=0; i<nCol; i++){
   180907       if( abPK[i] ){
   180908         sessionAppendStr(&buf, zSep, &rc);
   180909         sessionAppendIdent(&buf, azCol[i], &rc);
   180910         sessionAppendStr(&buf, " IS ?", &rc);
   180911         sessionAppendInteger(&buf, i+1, &rc);
   180912         zSep = " AND ";
   180913       }
   180914     }
   180915     zSql = (char*)buf.aBuf;
   180916     nSql = buf.nBuf;
   180917   }
   180918 
   180919   if( rc==SQLITE_OK ){
   180920     rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
   180921   }
   180922   sqlite3_free(zSql);
   180923   return rc;
   180924 }
   180925 
   180926 /*
   180927 ** Bind the PRIMARY KEY values from the change passed in argument pChange
   180928 ** to the SELECT statement passed as the first argument. The SELECT statement
   180929 ** is as prepared by function sessionSelectStmt().
   180930 **
   180931 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
   180932 ** error code (e.g. SQLITE_NOMEM) otherwise.
   180933 */
   180934 static int sessionSelectBind(
   180935   sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
   180936   int nCol,                       /* Number of columns in table */
   180937   u8 *abPK,                       /* PRIMARY KEY array */
   180938   SessionChange *pChange          /* Change structure */
   180939 ){
   180940   int i;
   180941   int rc = SQLITE_OK;
   180942   u8 *a = pChange->aRecord;
   180943 
   180944   for(i=0; i<nCol && rc==SQLITE_OK; i++){
   180945     int eType = *a++;
   180946 
   180947     switch( eType ){
   180948       case 0:
   180949       case SQLITE_NULL:
   180950         assert( abPK[i]==0 );
   180951         break;
   180952 
   180953       case SQLITE_INTEGER: {
   180954         if( abPK[i] ){
   180955           i64 iVal = sessionGetI64(a);
   180956           rc = sqlite3_bind_int64(pSelect, i+1, iVal);
   180957         }
   180958         a += 8;
   180959         break;
   180960       }
   180961 
   180962       case SQLITE_FLOAT: {
   180963         if( abPK[i] ){
   180964           double rVal;
   180965           i64 iVal = sessionGetI64(a);
   180966           memcpy(&rVal, &iVal, 8);
   180967           rc = sqlite3_bind_double(pSelect, i+1, rVal);
   180968         }
   180969         a += 8;
   180970         break;
   180971       }
   180972 
   180973       case SQLITE_TEXT: {
   180974         int n;
   180975         a += sessionVarintGet(a, &n);
   180976         if( abPK[i] ){
   180977           rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
   180978         }
   180979         a += n;
   180980         break;
   180981       }
   180982 
   180983       default: {
   180984         int n;
   180985         assert( eType==SQLITE_BLOB );
   180986         a += sessionVarintGet(a, &n);
   180987         if( abPK[i] ){
   180988           rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
   180989         }
   180990         a += n;
   180991         break;
   180992       }
   180993     }
   180994   }
   180995 
   180996   return rc;
   180997 }
   180998 
   180999 /*
   181000 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
   181001 ** is called. Otherwise, append a serialized table header (part of the binary
   181002 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
   181003 ** SQLite error code before returning.
   181004 */
   181005 static void sessionAppendTableHdr(
   181006   SessionBuffer *pBuf,            /* Append header to this buffer */
   181007   int bPatchset,                  /* Use the patchset format if true */
   181008   SessionTable *pTab,             /* Table object to append header for */
   181009   int *pRc                        /* IN/OUT: Error code */
   181010 ){
   181011   /* Write a table header */
   181012   sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
   181013   sessionAppendVarint(pBuf, pTab->nCol, pRc);
   181014   sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
   181015   sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
   181016 }
   181017 
   181018 /*
   181019 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
   181020 ** (if it is non-zero) based on the current contents of the session object
   181021 ** passed as the first argument.
   181022 **
   181023 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
   181024 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
   181025 ** occurs, an SQLite error code is returned and both output variables set
   181026 ** to 0.
   181027 */
   181028 static int sessionGenerateChangeset(
   181029   sqlite3_session *pSession,      /* Session object */
   181030   int bPatchset,                  /* True for patchset, false for changeset */
   181031   int (*xOutput)(void *pOut, const void *pData, int nData),
   181032   void *pOut,                     /* First argument for xOutput */
   181033   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
   181034   void **ppChangeset              /* OUT: Buffer containing changeset */
   181035 ){
   181036   sqlite3 *db = pSession->db;     /* Source database handle */
   181037   SessionTable *pTab;             /* Used to iterate through attached tables */
   181038   SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
   181039   int rc;                         /* Return code */
   181040 
   181041   assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
   181042 
   181043   /* Zero the output variables in case an error occurs. If this session
   181044   ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
   181045   ** this call will be a no-op.  */
   181046   if( xOutput==0 ){
   181047     *pnChangeset = 0;
   181048     *ppChangeset = 0;
   181049   }
   181050 
   181051   if( pSession->rc ) return pSession->rc;
   181052   rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
   181053   if( rc!=SQLITE_OK ) return rc;
   181054 
   181055   sqlite3_mutex_enter(sqlite3_db_mutex(db));
   181056 
   181057   for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
   181058     if( pTab->nEntry ){
   181059       const char *zName = pTab->zName;
   181060       int nCol;                   /* Number of columns in table */
   181061       u8 *abPK;                   /* Primary key array */
   181062       const char **azCol = 0;     /* Table columns */
   181063       int i;                      /* Used to iterate through hash buckets */
   181064       sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
   181065       int nRewind = buf.nBuf;     /* Initial size of write buffer */
   181066       int nNoop;                  /* Size of buffer after writing tbl header */
   181067 
   181068       /* Check the table schema is still Ok. */
   181069       rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
   181070       if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
   181071         rc = SQLITE_SCHEMA;
   181072       }
   181073 
   181074       /* Write a table header */
   181075       sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
   181076 
   181077       /* Build and compile a statement to execute: */
   181078       if( rc==SQLITE_OK ){
   181079         rc = sessionSelectStmt(
   181080             db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
   181081       }
   181082 
   181083       nNoop = buf.nBuf;
   181084       for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
   181085         SessionChange *p;         /* Used to iterate through changes */
   181086 
   181087         for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
   181088           rc = sessionSelectBind(pSel, nCol, abPK, p);
   181089           if( rc!=SQLITE_OK ) continue;
   181090           if( sqlite3_step(pSel)==SQLITE_ROW ){
   181091             if( p->op==SQLITE_INSERT ){
   181092               int iCol;
   181093               sessionAppendByte(&buf, SQLITE_INSERT, &rc);
   181094               sessionAppendByte(&buf, p->bIndirect, &rc);
   181095               for(iCol=0; iCol<nCol; iCol++){
   181096                 sessionAppendCol(&buf, pSel, iCol, &rc);
   181097               }
   181098             }else{
   181099               rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
   181100             }
   181101           }else if( p->op!=SQLITE_INSERT ){
   181102             rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
   181103           }
   181104           if( rc==SQLITE_OK ){
   181105             rc = sqlite3_reset(pSel);
   181106           }
   181107 
   181108           /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
   181109           ** its contents to the xOutput() callback. */
   181110           if( xOutput
   181111            && rc==SQLITE_OK
   181112            && buf.nBuf>nNoop
   181113            && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
   181114           ){
   181115             rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
   181116             nNoop = -1;
   181117             buf.nBuf = 0;
   181118           }
   181119 
   181120         }
   181121       }
   181122 
   181123       sqlite3_finalize(pSel);
   181124       if( buf.nBuf==nNoop ){
   181125         buf.nBuf = nRewind;
   181126       }
   181127       sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
   181128     }
   181129   }
   181130 
   181131   if( rc==SQLITE_OK ){
   181132     if( xOutput==0 ){
   181133       *pnChangeset = buf.nBuf;
   181134       *ppChangeset = buf.aBuf;
   181135       buf.aBuf = 0;
   181136     }else if( buf.nBuf>0 ){
   181137       rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
   181138     }
   181139   }
   181140 
   181141   sqlite3_free(buf.aBuf);
   181142   sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
   181143   sqlite3_mutex_leave(sqlite3_db_mutex(db));
   181144   return rc;
   181145 }
   181146 
   181147 /*
   181148 ** Obtain a changeset object containing all changes recorded by the
   181149 ** session object passed as the first argument.
   181150 **
   181151 ** It is the responsibility of the caller to eventually free the buffer
   181152 ** using sqlite3_free().
   181153 */
   181154 SQLITE_API int sqlite3session_changeset(
   181155   sqlite3_session *pSession,      /* Session object */
   181156   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
   181157   void **ppChangeset              /* OUT: Buffer containing changeset */
   181158 ){
   181159   return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
   181160 }
   181161 
   181162 /*
   181163 ** Streaming version of sqlite3session_changeset().
   181164 */
   181165 SQLITE_API int sqlite3session_changeset_strm(
   181166   sqlite3_session *pSession,
   181167   int (*xOutput)(void *pOut, const void *pData, int nData),
   181168   void *pOut
   181169 ){
   181170   return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
   181171 }
   181172 
   181173 /*
   181174 ** Streaming version of sqlite3session_patchset().
   181175 */
   181176 SQLITE_API int sqlite3session_patchset_strm(
   181177   sqlite3_session *pSession,
   181178   int (*xOutput)(void *pOut, const void *pData, int nData),
   181179   void *pOut
   181180 ){
   181181   return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
   181182 }
   181183 
   181184 /*
   181185 ** Obtain a patchset object containing all changes recorded by the
   181186 ** session object passed as the first argument.
   181187 **
   181188 ** It is the responsibility of the caller to eventually free the buffer
   181189 ** using sqlite3_free().
   181190 */
   181191 SQLITE_API int sqlite3session_patchset(
   181192   sqlite3_session *pSession,      /* Session object */
   181193   int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
   181194   void **ppPatchset               /* OUT: Buffer containing changeset */
   181195 ){
   181196   return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
   181197 }
   181198 
   181199 /*
   181200 ** Enable or disable the session object passed as the first argument.
   181201 */
   181202 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
   181203   int ret;
   181204   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
   181205   if( bEnable>=0 ){
   181206     pSession->bEnable = bEnable;
   181207   }
   181208   ret = pSession->bEnable;
   181209   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
   181210   return ret;
   181211 }
   181212 
   181213 /*
   181214 ** Enable or disable the session object passed as the first argument.
   181215 */
   181216 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
   181217   int ret;
   181218   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
   181219   if( bIndirect>=0 ){
   181220     pSession->bIndirect = bIndirect;
   181221   }
   181222   ret = pSession->bIndirect;
   181223   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
   181224   return ret;
   181225 }
   181226 
   181227 /*
   181228 ** Return true if there have been no changes to monitored tables recorded
   181229 ** by the session object passed as the only argument.
   181230 */
   181231 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
   181232   int ret = 0;
   181233   SessionTable *pTab;
   181234 
   181235   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
   181236   for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
   181237     ret = (pTab->nEntry>0);
   181238   }
   181239   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
   181240 
   181241   return (ret==0);
   181242 }
   181243 
   181244 /*
   181245 ** Do the work for either sqlite3changeset_start() or start_strm().
   181246 */
   181247 static int sessionChangesetStart(
   181248   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
   181249   int (*xInput)(void *pIn, void *pData, int *pnData),
   181250   void *pIn,
   181251   int nChangeset,                 /* Size of buffer pChangeset in bytes */
   181252   void *pChangeset                /* Pointer to buffer containing changeset */
   181253 ){
   181254   sqlite3_changeset_iter *pRet;   /* Iterator to return */
   181255   int nByte;                      /* Number of bytes to allocate for iterator */
   181256 
   181257   assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
   181258 
   181259   /* Zero the output variable in case an error occurs. */
   181260   *pp = 0;
   181261 
   181262   /* Allocate and initialize the iterator structure. */
   181263   nByte = sizeof(sqlite3_changeset_iter);
   181264   pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
   181265   if( !pRet ) return SQLITE_NOMEM;
   181266   memset(pRet, 0, sizeof(sqlite3_changeset_iter));
   181267   pRet->in.aData = (u8 *)pChangeset;
   181268   pRet->in.nData = nChangeset;
   181269   pRet->in.xInput = xInput;
   181270   pRet->in.pIn = pIn;
   181271   pRet->in.bEof = (xInput ? 0 : 1);
   181272 
   181273   /* Populate the output variable and return success. */
   181274   *pp = pRet;
   181275   return SQLITE_OK;
   181276 }
   181277 
   181278 /*
   181279 ** Create an iterator used to iterate through the contents of a changeset.
   181280 */
   181281 SQLITE_API int sqlite3changeset_start(
   181282   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
   181283   int nChangeset,                 /* Size of buffer pChangeset in bytes */
   181284   void *pChangeset                /* Pointer to buffer containing changeset */
   181285 ){
   181286   return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
   181287 }
   181288 
   181289 /*
   181290 ** Streaming version of sqlite3changeset_start().
   181291 */
   181292 SQLITE_API int sqlite3changeset_start_strm(
   181293   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
   181294   int (*xInput)(void *pIn, void *pData, int *pnData),
   181295   void *pIn
   181296 ){
   181297   return sessionChangesetStart(pp, xInput, pIn, 0, 0);
   181298 }
   181299 
   181300 /*
   181301 ** If the SessionInput object passed as the only argument is a streaming
   181302 ** object and the buffer is full, discard some data to free up space.
   181303 */
   181304 static void sessionDiscardData(SessionInput *pIn){
   181305   if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
   181306     int nMove = pIn->buf.nBuf - pIn->iNext;
   181307     assert( nMove>=0 );
   181308     if( nMove>0 ){
   181309       memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
   181310     }
   181311     pIn->buf.nBuf -= pIn->iNext;
   181312     pIn->iNext = 0;
   181313     pIn->nData = pIn->buf.nBuf;
   181314   }
   181315 }
   181316 
   181317 /*
   181318 ** Ensure that there are at least nByte bytes available in the buffer. Or,
   181319 ** if there are not nByte bytes remaining in the input, that all available
   181320 ** data is in the buffer.
   181321 **
   181322 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
   181323 */
   181324 static int sessionInputBuffer(SessionInput *pIn, int nByte){
   181325   int rc = SQLITE_OK;
   181326   if( pIn->xInput ){
   181327     while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
   181328       int nNew = SESSIONS_STRM_CHUNK_SIZE;
   181329 
   181330       if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
   181331       if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
   181332         rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
   181333         if( nNew==0 ){
   181334           pIn->bEof = 1;
   181335         }else{
   181336           pIn->buf.nBuf += nNew;
   181337         }
   181338       }
   181339 
   181340       pIn->aData = pIn->buf.aBuf;
   181341       pIn->nData = pIn->buf.nBuf;
   181342     }
   181343   }
   181344   return rc;
   181345 }
   181346 
   181347 /*
   181348 ** When this function is called, *ppRec points to the start of a record
   181349 ** that contains nCol values. This function advances the pointer *ppRec
   181350 ** until it points to the byte immediately following that record.
   181351 */
   181352 static void sessionSkipRecord(
   181353   u8 **ppRec,                     /* IN/OUT: Record pointer */
   181354   int nCol                        /* Number of values in record */
   181355 ){
   181356   u8 *aRec = *ppRec;
   181357   int i;
   181358   for(i=0; i<nCol; i++){
   181359     int eType = *aRec++;
   181360     if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
   181361       int nByte;
   181362       aRec += sessionVarintGet((u8*)aRec, &nByte);
   181363       aRec += nByte;
   181364     }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   181365       aRec += 8;
   181366     }
   181367   }
   181368 
   181369   *ppRec = aRec;
   181370 }
   181371 
   181372 /*
   181373 ** This function sets the value of the sqlite3_value object passed as the
   181374 ** first argument to a copy of the string or blob held in the aData[]
   181375 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
   181376 ** error occurs.
   181377 */
   181378 static int sessionValueSetStr(
   181379   sqlite3_value *pVal,            /* Set the value of this object */
   181380   u8 *aData,                      /* Buffer containing string or blob data */
   181381   int nData,                      /* Size of buffer aData[] in bytes */
   181382   u8 enc                          /* String encoding (0 for blobs) */
   181383 ){
   181384   /* In theory this code could just pass SQLITE_TRANSIENT as the final
   181385   ** argument to sqlite3ValueSetStr() and have the copy created
   181386   ** automatically. But doing so makes it difficult to detect any OOM
   181387   ** error. Hence the code to create the copy externally. */
   181388   u8 *aCopy = sqlite3_malloc(nData+1);
   181389   if( aCopy==0 ) return SQLITE_NOMEM;
   181390   memcpy(aCopy, aData, nData);
   181391   sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
   181392   return SQLITE_OK;
   181393 }
   181394 
   181395 /*
   181396 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
   181397 ** for details.
   181398 **
   181399 ** When this function is called, *paChange points to the start of the record
   181400 ** to deserialize. Assuming no error occurs, *paChange is set to point to
   181401 ** one byte after the end of the same record before this function returns.
   181402 ** If the argument abPK is NULL, then the record contains nCol values. Or,
   181403 ** if abPK is other than NULL, then the record contains only the PK fields
   181404 ** (in other words, it is a patchset DELETE record).
   181405 **
   181406 ** If successful, each element of the apOut[] array (allocated by the caller)
   181407 ** is set to point to an sqlite3_value object containing the value read
   181408 ** from the corresponding position in the record. If that value is not
   181409 ** included in the record (i.e. because the record is part of an UPDATE change
   181410 ** and the field was not modified), the corresponding element of apOut[] is
   181411 ** set to NULL.
   181412 **
   181413 ** It is the responsibility of the caller to free all sqlite_value structures
   181414 ** using sqlite3_free().
   181415 **
   181416 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
   181417 ** The apOut[] array may have been partially populated in this case.
   181418 */
   181419 static int sessionReadRecord(
   181420   SessionInput *pIn,              /* Input data */
   181421   int nCol,                       /* Number of values in record */
   181422   u8 *abPK,                       /* Array of primary key flags, or NULL */
   181423   sqlite3_value **apOut           /* Write values to this array */
   181424 ){
   181425   int i;                          /* Used to iterate through columns */
   181426   int rc = SQLITE_OK;
   181427 
   181428   for(i=0; i<nCol && rc==SQLITE_OK; i++){
   181429     int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
   181430     if( abPK && abPK[i]==0 ) continue;
   181431     rc = sessionInputBuffer(pIn, 9);
   181432     if( rc==SQLITE_OK ){
   181433       eType = pIn->aData[pIn->iNext++];
   181434     }
   181435 
   181436     assert( apOut[i]==0 );
   181437     if( eType ){
   181438       apOut[i] = sqlite3ValueNew(0);
   181439       if( !apOut[i] ) rc = SQLITE_NOMEM;
   181440     }
   181441 
   181442     if( rc==SQLITE_OK ){
   181443       u8 *aVal = &pIn->aData[pIn->iNext];
   181444       if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
   181445         int nByte;
   181446         pIn->iNext += sessionVarintGet(aVal, &nByte);
   181447         rc = sessionInputBuffer(pIn, nByte);
   181448         if( rc==SQLITE_OK ){
   181449           u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
   181450           rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
   181451         }
   181452         pIn->iNext += nByte;
   181453       }
   181454       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   181455         sqlite3_int64 v = sessionGetI64(aVal);
   181456         if( eType==SQLITE_INTEGER ){
   181457           sqlite3VdbeMemSetInt64(apOut[i], v);
   181458         }else{
   181459           double d;
   181460           memcpy(&d, &v, 8);
   181461           sqlite3VdbeMemSetDouble(apOut[i], d);
   181462         }
   181463         pIn->iNext += 8;
   181464       }
   181465     }
   181466   }
   181467 
   181468   return rc;
   181469 }
   181470 
   181471 /*
   181472 ** The input pointer currently points to the second byte of a table-header.
   181473 ** Specifically, to the following:
   181474 **
   181475 **   + number of columns in table (varint)
   181476 **   + array of PK flags (1 byte per column),
   181477 **   + table name (nul terminated).
   181478 **
   181479 ** This function ensures that all of the above is present in the input
   181480 ** buffer (i.e. that it can be accessed without any calls to xInput()).
   181481 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   181482 ** The input pointer is not moved.
   181483 */
   181484 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
   181485   int rc = SQLITE_OK;
   181486   int nCol = 0;
   181487   int nRead = 0;
   181488 
   181489   rc = sessionInputBuffer(pIn, 9);
   181490   if( rc==SQLITE_OK ){
   181491     nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
   181492     rc = sessionInputBuffer(pIn, nRead+nCol+100);
   181493     nRead += nCol;
   181494   }
   181495 
   181496   while( rc==SQLITE_OK ){
   181497     while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
   181498       nRead++;
   181499     }
   181500     if( (pIn->iNext + nRead)<pIn->nData ) break;
   181501     rc = sessionInputBuffer(pIn, nRead + 100);
   181502   }
   181503   *pnByte = nRead+1;
   181504   return rc;
   181505 }
   181506 
   181507 /*
   181508 ** The input pointer currently points to the first byte of the first field
   181509 ** of a record consisting of nCol columns. This function ensures the entire
   181510 ** record is buffered. It does not move the input pointer.
   181511 **
   181512 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
   181513 ** the record in bytes. Otherwise, an SQLite error code is returned. The
   181514 ** final value of *pnByte is undefined in this case.
   181515 */
   181516 static int sessionChangesetBufferRecord(
   181517   SessionInput *pIn,              /* Input data */
   181518   int nCol,                       /* Number of columns in record */
   181519   int *pnByte                     /* OUT: Size of record in bytes */
   181520 ){
   181521   int rc = SQLITE_OK;
   181522   int nByte = 0;
   181523   int i;
   181524   for(i=0; rc==SQLITE_OK && i<nCol; i++){
   181525     int eType;
   181526     rc = sessionInputBuffer(pIn, nByte + 10);
   181527     if( rc==SQLITE_OK ){
   181528       eType = pIn->aData[pIn->iNext + nByte++];
   181529       if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
   181530         int n;
   181531         nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
   181532         nByte += n;
   181533         rc = sessionInputBuffer(pIn, nByte);
   181534       }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   181535         nByte += 8;
   181536       }
   181537     }
   181538   }
   181539   *pnByte = nByte;
   181540   return rc;
   181541 }
   181542 
   181543 /*
   181544 ** The input pointer currently points to the second byte of a table-header.
   181545 ** Specifically, to the following:
   181546 **
   181547 **   + number of columns in table (varint)
   181548 **   + array of PK flags (1 byte per column),
   181549 **   + table name (nul terminated).
   181550 **
   181551 ** This function decodes the table-header and populates the p->nCol,
   181552 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
   181553 ** also allocated or resized according to the new value of p->nCol. The
   181554 ** input pointer is left pointing to the byte following the table header.
   181555 **
   181556 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
   181557 ** is returned and the final values of the various fields enumerated above
   181558 ** are undefined.
   181559 */
   181560 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
   181561   int rc;
   181562   int nCopy;
   181563   assert( p->rc==SQLITE_OK );
   181564 
   181565   rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
   181566   if( rc==SQLITE_OK ){
   181567     int nByte;
   181568     int nVarint;
   181569     nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
   181570     nCopy -= nVarint;
   181571     p->in.iNext += nVarint;
   181572     nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
   181573     p->tblhdr.nBuf = 0;
   181574     sessionBufferGrow(&p->tblhdr, nByte, &rc);
   181575   }
   181576 
   181577   if( rc==SQLITE_OK ){
   181578     int iPK = sizeof(sqlite3_value*)*p->nCol*2;
   181579     memset(p->tblhdr.aBuf, 0, iPK);
   181580     memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
   181581     p->in.iNext += nCopy;
   181582   }
   181583 
   181584   p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
   181585   p->abPK = (u8*)&p->apValue[p->nCol*2];
   181586   p->zTab = (char*)&p->abPK[p->nCol];
   181587   return (p->rc = rc);
   181588 }
   181589 
   181590 /*
   181591 ** Advance the changeset iterator to the next change.
   181592 **
   181593 ** If both paRec and pnRec are NULL, then this function works like the public
   181594 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
   181595 ** sqlite3changeset_new() and old() APIs may be used to query for values.
   181596 **
   181597 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
   181598 ** record is written to *paRec before returning and the number of bytes in
   181599 ** the record to *pnRec.
   181600 **
   181601 ** Either way, this function returns SQLITE_ROW if the iterator is
   181602 ** successfully advanced to the next change in the changeset, an SQLite
   181603 ** error code if an error occurs, or SQLITE_DONE if there are no further
   181604 ** changes in the changeset.
   181605 */
   181606 static int sessionChangesetNext(
   181607   sqlite3_changeset_iter *p,      /* Changeset iterator */
   181608   u8 **paRec,                     /* If non-NULL, store record pointer here */
   181609   int *pnRec                      /* If non-NULL, store size of record here */
   181610 ){
   181611   int i;
   181612   u8 op;
   181613 
   181614   assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
   181615 
   181616   /* If the iterator is in the error-state, return immediately. */
   181617   if( p->rc!=SQLITE_OK ) return p->rc;
   181618 
   181619   /* Free the current contents of p->apValue[], if any. */
   181620   if( p->apValue ){
   181621     for(i=0; i<p->nCol*2; i++){
   181622       sqlite3ValueFree(p->apValue[i]);
   181623     }
   181624     memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
   181625   }
   181626 
   181627   /* Make sure the buffer contains at least 10 bytes of input data, or all
   181628   ** remaining data if there are less than 10 bytes available. This is
   181629   ** sufficient either for the 'T' or 'P' byte and the varint that follows
   181630   ** it, or for the two single byte values otherwise. */
   181631   p->rc = sessionInputBuffer(&p->in, 2);
   181632   if( p->rc!=SQLITE_OK ) return p->rc;
   181633 
   181634   /* If the iterator is already at the end of the changeset, return DONE. */
   181635   if( p->in.iNext>=p->in.nData ){
   181636     return SQLITE_DONE;
   181637   }
   181638 
   181639   sessionDiscardData(&p->in);
   181640   p->in.iCurrent = p->in.iNext;
   181641 
   181642   op = p->in.aData[p->in.iNext++];
   181643   while( op=='T' || op=='P' ){
   181644     p->bPatchset = (op=='P');
   181645     if( sessionChangesetReadTblhdr(p) ) return p->rc;
   181646     if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
   181647     p->in.iCurrent = p->in.iNext;
   181648     if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
   181649     op = p->in.aData[p->in.iNext++];
   181650   }
   181651 
   181652   p->op = op;
   181653   p->bIndirect = p->in.aData[p->in.iNext++];
   181654   if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
   181655     return (p->rc = SQLITE_CORRUPT_BKPT);
   181656   }
   181657 
   181658   if( paRec ){
   181659     int nVal;                     /* Number of values to buffer */
   181660     if( p->bPatchset==0 && op==SQLITE_UPDATE ){
   181661       nVal = p->nCol * 2;
   181662     }else if( p->bPatchset && op==SQLITE_DELETE ){
   181663       nVal = 0;
   181664       for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
   181665     }else{
   181666       nVal = p->nCol;
   181667     }
   181668     p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
   181669     if( p->rc!=SQLITE_OK ) return p->rc;
   181670     *paRec = &p->in.aData[p->in.iNext];
   181671     p->in.iNext += *pnRec;
   181672   }else{
   181673 
   181674     /* If this is an UPDATE or DELETE, read the old.* record. */
   181675     if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
   181676       u8 *abPK = p->bPatchset ? p->abPK : 0;
   181677       p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
   181678       if( p->rc!=SQLITE_OK ) return p->rc;
   181679     }
   181680 
   181681     /* If this is an INSERT or UPDATE, read the new.* record. */
   181682     if( p->op!=SQLITE_DELETE ){
   181683       p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
   181684       if( p->rc!=SQLITE_OK ) return p->rc;
   181685     }
   181686 
   181687     if( p->bPatchset && p->op==SQLITE_UPDATE ){
   181688       /* If this is an UPDATE that is part of a patchset, then all PK and
   181689       ** modified fields are present in the new.* record. The old.* record
   181690       ** is currently completely empty. This block shifts the PK fields from
   181691       ** new.* to old.*, to accommodate the code that reads these arrays.  */
   181692       for(i=0; i<p->nCol; i++){
   181693         assert( p->apValue[i]==0 );
   181694         assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
   181695         if( p->abPK[i] ){
   181696           p->apValue[i] = p->apValue[i+p->nCol];
   181697           p->apValue[i+p->nCol] = 0;
   181698         }
   181699       }
   181700     }
   181701   }
   181702 
   181703   return SQLITE_ROW;
   181704 }
   181705 
   181706 /*
   181707 ** Advance an iterator created by sqlite3changeset_start() to the next
   181708 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
   181709 ** or SQLITE_CORRUPT.
   181710 **
   181711 ** This function may not be called on iterators passed to a conflict handler
   181712 ** callback by changeset_apply().
   181713 */
   181714 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
   181715   return sessionChangesetNext(p, 0, 0);
   181716 }
   181717 
   181718 /*
   181719 ** The following function extracts information on the current change
   181720 ** from a changeset iterator. It may only be called after changeset_next()
   181721 ** has returned SQLITE_ROW.
   181722 */
   181723 SQLITE_API int sqlite3changeset_op(
   181724   sqlite3_changeset_iter *pIter,  /* Iterator handle */
   181725   const char **pzTab,             /* OUT: Pointer to table name */
   181726   int *pnCol,                     /* OUT: Number of columns in table */
   181727   int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
   181728   int *pbIndirect                 /* OUT: True if change is indirect */
   181729 ){
   181730   *pOp = pIter->op;
   181731   *pnCol = pIter->nCol;
   181732   *pzTab = pIter->zTab;
   181733   if( pbIndirect ) *pbIndirect = pIter->bIndirect;
   181734   return SQLITE_OK;
   181735 }
   181736 
   181737 /*
   181738 ** Return information regarding the PRIMARY KEY and number of columns in
   181739 ** the database table affected by the change that pIter currently points
   181740 ** to. This function may only be called after changeset_next() returns
   181741 ** SQLITE_ROW.
   181742 */
   181743 SQLITE_API int sqlite3changeset_pk(
   181744   sqlite3_changeset_iter *pIter,  /* Iterator object */
   181745   unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
   181746   int *pnCol                      /* OUT: Number of entries in output array */
   181747 ){
   181748   *pabPK = pIter->abPK;
   181749   if( pnCol ) *pnCol = pIter->nCol;
   181750   return SQLITE_OK;
   181751 }
   181752 
   181753 /*
   181754 ** This function may only be called while the iterator is pointing to an
   181755 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
   181756 ** Otherwise, SQLITE_MISUSE is returned.
   181757 **
   181758 ** It sets *ppValue to point to an sqlite3_value structure containing the
   181759 ** iVal'th value in the old.* record. Or, if that particular value is not
   181760 ** included in the record (because the change is an UPDATE and the field
   181761 ** was not modified and is not a PK column), set *ppValue to NULL.
   181762 **
   181763 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
   181764 ** not modified. Otherwise, SQLITE_OK.
   181765 */
   181766 SQLITE_API int sqlite3changeset_old(
   181767   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   181768   int iVal,                       /* Index of old.* value to retrieve */
   181769   sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
   181770 ){
   181771   if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
   181772     return SQLITE_MISUSE;
   181773   }
   181774   if( iVal<0 || iVal>=pIter->nCol ){
   181775     return SQLITE_RANGE;
   181776   }
   181777   *ppValue = pIter->apValue[iVal];
   181778   return SQLITE_OK;
   181779 }
   181780 
   181781 /*
   181782 ** This function may only be called while the iterator is pointing to an
   181783 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
   181784 ** Otherwise, SQLITE_MISUSE is returned.
   181785 **
   181786 ** It sets *ppValue to point to an sqlite3_value structure containing the
   181787 ** iVal'th value in the new.* record. Or, if that particular value is not
   181788 ** included in the record (because the change is an UPDATE and the field
   181789 ** was not modified), set *ppValue to NULL.
   181790 **
   181791 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
   181792 ** not modified. Otherwise, SQLITE_OK.
   181793 */
   181794 SQLITE_API int sqlite3changeset_new(
   181795   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   181796   int iVal,                       /* Index of new.* value to retrieve */
   181797   sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
   181798 ){
   181799   if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
   181800     return SQLITE_MISUSE;
   181801   }
   181802   if( iVal<0 || iVal>=pIter->nCol ){
   181803     return SQLITE_RANGE;
   181804   }
   181805   *ppValue = pIter->apValue[pIter->nCol+iVal];
   181806   return SQLITE_OK;
   181807 }
   181808 
   181809 /*
   181810 ** The following two macros are used internally. They are similar to the
   181811 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
   181812 ** they omit all error checking and return a pointer to the requested value.
   181813 */
   181814 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
   181815 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
   181816 
   181817 /*
   181818 ** This function may only be called with a changeset iterator that has been
   181819 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
   181820 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
   181821 **
   181822 ** If successful, *ppValue is set to point to an sqlite3_value structure
   181823 ** containing the iVal'th value of the conflicting record.
   181824 **
   181825 ** If value iVal is out-of-range or some other error occurs, an SQLite error
   181826 ** code is returned. Otherwise, SQLITE_OK.
   181827 */
   181828 SQLITE_API int sqlite3changeset_conflict(
   181829   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   181830   int iVal,                       /* Index of conflict record value to fetch */
   181831   sqlite3_value **ppValue         /* OUT: Value from conflicting row */
   181832 ){
   181833   if( !pIter->pConflict ){
   181834     return SQLITE_MISUSE;
   181835   }
   181836   if( iVal<0 || iVal>=pIter->nCol ){
   181837     return SQLITE_RANGE;
   181838   }
   181839   *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
   181840   return SQLITE_OK;
   181841 }
   181842 
   181843 /*
   181844 ** This function may only be called with an iterator passed to an
   181845 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
   181846 ** it sets the output variable to the total number of known foreign key
   181847 ** violations in the destination database and returns SQLITE_OK.
   181848 **
   181849 ** In all other cases this function returns SQLITE_MISUSE.
   181850 */
   181851 SQLITE_API int sqlite3changeset_fk_conflicts(
   181852   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   181853   int *pnOut                      /* OUT: Number of FK violations */
   181854 ){
   181855   if( pIter->pConflict || pIter->apValue ){
   181856     return SQLITE_MISUSE;
   181857   }
   181858   *pnOut = pIter->nCol;
   181859   return SQLITE_OK;
   181860 }
   181861 
   181862 
   181863 /*
   181864 ** Finalize an iterator allocated with sqlite3changeset_start().
   181865 **
   181866 ** This function may not be called on iterators passed to a conflict handler
   181867 ** callback by changeset_apply().
   181868 */
   181869 SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
   181870   int rc = SQLITE_OK;
   181871   if( p ){
   181872     int i;                        /* Used to iterate through p->apValue[] */
   181873     rc = p->rc;
   181874     if( p->apValue ){
   181875       for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
   181876     }
   181877     sqlite3_free(p->tblhdr.aBuf);
   181878     sqlite3_free(p->in.buf.aBuf);
   181879     sqlite3_free(p);
   181880   }
   181881   return rc;
   181882 }
   181883 
   181884 static int sessionChangesetInvert(
   181885   SessionInput *pInput,           /* Input changeset */
   181886   int (*xOutput)(void *pOut, const void *pData, int nData),
   181887   void *pOut,
   181888   int *pnInverted,                /* OUT: Number of bytes in output changeset */
   181889   void **ppInverted               /* OUT: Inverse of pChangeset */
   181890 ){
   181891   int rc = SQLITE_OK;             /* Return value */
   181892   SessionBuffer sOut;             /* Output buffer */
   181893   int nCol = 0;                   /* Number of cols in current table */
   181894   u8 *abPK = 0;                   /* PK array for current table */
   181895   sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
   181896   SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
   181897 
   181898   /* Initialize the output buffer */
   181899   memset(&sOut, 0, sizeof(SessionBuffer));
   181900 
   181901   /* Zero the output variables in case an error occurs. */
   181902   if( ppInverted ){
   181903     *ppInverted = 0;
   181904     *pnInverted = 0;
   181905   }
   181906 
   181907   while( 1 ){
   181908     u8 eType;
   181909 
   181910     /* Test for EOF. */
   181911     if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
   181912     if( pInput->iNext>=pInput->nData ) break;
   181913     eType = pInput->aData[pInput->iNext];
   181914 
   181915     switch( eType ){
   181916       case 'T': {
   181917         /* A 'table' record consists of:
   181918         **
   181919         **   * A constant 'T' character,
   181920         **   * Number of columns in said table (a varint),
   181921         **   * An array of nCol bytes (sPK),
   181922         **   * A nul-terminated table name.
   181923         */
   181924         int nByte;
   181925         int nVar;
   181926         pInput->iNext++;
   181927         if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
   181928           goto finished_invert;
   181929         }
   181930         nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
   181931         sPK.nBuf = 0;
   181932         sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
   181933         sessionAppendByte(&sOut, eType, &rc);
   181934         sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
   181935         if( rc ) goto finished_invert;
   181936 
   181937         pInput->iNext += nByte;
   181938         sqlite3_free(apVal);
   181939         apVal = 0;
   181940         abPK = sPK.aBuf;
   181941         break;
   181942       }
   181943 
   181944       case SQLITE_INSERT:
   181945       case SQLITE_DELETE: {
   181946         int nByte;
   181947         int bIndirect = pInput->aData[pInput->iNext+1];
   181948         int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
   181949         pInput->iNext += 2;
   181950         assert( rc==SQLITE_OK );
   181951         rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
   181952         sessionAppendByte(&sOut, eType2, &rc);
   181953         sessionAppendByte(&sOut, bIndirect, &rc);
   181954         sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
   181955         pInput->iNext += nByte;
   181956         if( rc ) goto finished_invert;
   181957         break;
   181958       }
   181959 
   181960       case SQLITE_UPDATE: {
   181961         int iCol;
   181962 
   181963         if( 0==apVal ){
   181964           apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
   181965           if( 0==apVal ){
   181966             rc = SQLITE_NOMEM;
   181967             goto finished_invert;
   181968           }
   181969           memset(apVal, 0, sizeof(apVal[0])*nCol*2);
   181970         }
   181971 
   181972         /* Write the header for the new UPDATE change. Same as the original. */
   181973         sessionAppendByte(&sOut, eType, &rc);
   181974         sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
   181975 
   181976         /* Read the old.* and new.* records for the update change. */
   181977         pInput->iNext += 2;
   181978         rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
   181979         if( rc==SQLITE_OK ){
   181980           rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
   181981         }
   181982 
   181983         /* Write the new old.* record. Consists of the PK columns from the
   181984         ** original old.* record, and the other values from the original
   181985         ** new.* record. */
   181986         for(iCol=0; iCol<nCol; iCol++){
   181987           sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
   181988           sessionAppendValue(&sOut, pVal, &rc);
   181989         }
   181990 
   181991         /* Write the new new.* record. Consists of a copy of all values
   181992         ** from the original old.* record, except for the PK columns, which
   181993         ** are set to "undefined". */
   181994         for(iCol=0; iCol<nCol; iCol++){
   181995           sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
   181996           sessionAppendValue(&sOut, pVal, &rc);
   181997         }
   181998 
   181999         for(iCol=0; iCol<nCol*2; iCol++){
   182000           sqlite3ValueFree(apVal[iCol]);
   182001         }
   182002         memset(apVal, 0, sizeof(apVal[0])*nCol*2);
   182003         if( rc!=SQLITE_OK ){
   182004           goto finished_invert;
   182005         }
   182006 
   182007         break;
   182008       }
   182009 
   182010       default:
   182011         rc = SQLITE_CORRUPT_BKPT;
   182012         goto finished_invert;
   182013     }
   182014 
   182015     assert( rc==SQLITE_OK );
   182016     if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
   182017       rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
   182018       sOut.nBuf = 0;
   182019       if( rc!=SQLITE_OK ) goto finished_invert;
   182020     }
   182021   }
   182022 
   182023   assert( rc==SQLITE_OK );
   182024   if( pnInverted ){
   182025     *pnInverted = sOut.nBuf;
   182026     *ppInverted = sOut.aBuf;
   182027     sOut.aBuf = 0;
   182028   }else if( sOut.nBuf>0 ){
   182029     rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
   182030   }
   182031 
   182032  finished_invert:
   182033   sqlite3_free(sOut.aBuf);
   182034   sqlite3_free(apVal);
   182035   sqlite3_free(sPK.aBuf);
   182036   return rc;
   182037 }
   182038 
   182039 
   182040 /*
   182041 ** Invert a changeset object.
   182042 */
   182043 SQLITE_API int sqlite3changeset_invert(
   182044   int nChangeset,                 /* Number of bytes in input */
   182045   const void *pChangeset,         /* Input changeset */
   182046   int *pnInverted,                /* OUT: Number of bytes in output changeset */
   182047   void **ppInverted               /* OUT: Inverse of pChangeset */
   182048 ){
   182049   SessionInput sInput;
   182050 
   182051   /* Set up the input stream */
   182052   memset(&sInput, 0, sizeof(SessionInput));
   182053   sInput.nData = nChangeset;
   182054   sInput.aData = (u8*)pChangeset;
   182055 
   182056   return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
   182057 }
   182058 
   182059 /*
   182060 ** Streaming version of sqlite3changeset_invert().
   182061 */
   182062 SQLITE_API int sqlite3changeset_invert_strm(
   182063   int (*xInput)(void *pIn, void *pData, int *pnData),
   182064   void *pIn,
   182065   int (*xOutput)(void *pOut, const void *pData, int nData),
   182066   void *pOut
   182067 ){
   182068   SessionInput sInput;
   182069   int rc;
   182070 
   182071   /* Set up the input stream */
   182072   memset(&sInput, 0, sizeof(SessionInput));
   182073   sInput.xInput = xInput;
   182074   sInput.pIn = pIn;
   182075 
   182076   rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
   182077   sqlite3_free(sInput.buf.aBuf);
   182078   return rc;
   182079 }
   182080 
   182081 typedef struct SessionApplyCtx SessionApplyCtx;
   182082 struct SessionApplyCtx {
   182083   sqlite3 *db;
   182084   sqlite3_stmt *pDelete;          /* DELETE statement */
   182085   sqlite3_stmt *pUpdate;          /* UPDATE statement */
   182086   sqlite3_stmt *pInsert;          /* INSERT statement */
   182087   sqlite3_stmt *pSelect;          /* SELECT statement */
   182088   int nCol;                       /* Size of azCol[] and abPK[] arrays */
   182089   const char **azCol;             /* Array of column names */
   182090   u8 *abPK;                       /* Boolean array - true if column is in PK */
   182091   int bStat1;                     /* True if table is sqlite_stat1 */
   182092   int bDeferConstraints;          /* True to defer constraints */
   182093   SessionBuffer constraints;      /* Deferred constraints are stored here */
   182094 };
   182095 
   182096 /*
   182097 ** Formulate a statement to DELETE a row from database db. Assuming a table
   182098 ** structure like this:
   182099 **
   182100 **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
   182101 **
   182102 ** The DELETE statement looks like this:
   182103 **
   182104 **     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
   182105 **
   182106 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
   182107 ** matching b and d values, or 1 otherwise. The second case comes up if the
   182108 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
   182109 **
   182110 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
   182111 ** pointing to the prepared version of the SQL statement.
   182112 */
   182113 static int sessionDeleteRow(
   182114   sqlite3 *db,                    /* Database handle */
   182115   const char *zTab,               /* Table name */
   182116   SessionApplyCtx *p              /* Session changeset-apply context */
   182117 ){
   182118   int i;
   182119   const char *zSep = "";
   182120   int rc = SQLITE_OK;
   182121   SessionBuffer buf = {0, 0, 0};
   182122   int nPk = 0;
   182123 
   182124   sessionAppendStr(&buf, "DELETE FROM ", &rc);
   182125   sessionAppendIdent(&buf, zTab, &rc);
   182126   sessionAppendStr(&buf, " WHERE ", &rc);
   182127 
   182128   for(i=0; i<p->nCol; i++){
   182129     if( p->abPK[i] ){
   182130       nPk++;
   182131       sessionAppendStr(&buf, zSep, &rc);
   182132       sessionAppendIdent(&buf, p->azCol[i], &rc);
   182133       sessionAppendStr(&buf, " = ?", &rc);
   182134       sessionAppendInteger(&buf, i+1, &rc);
   182135       zSep = " AND ";
   182136     }
   182137   }
   182138 
   182139   if( nPk<p->nCol ){
   182140     sessionAppendStr(&buf, " AND (?", &rc);
   182141     sessionAppendInteger(&buf, p->nCol+1, &rc);
   182142     sessionAppendStr(&buf, " OR ", &rc);
   182143 
   182144     zSep = "";
   182145     for(i=0; i<p->nCol; i++){
   182146       if( !p->abPK[i] ){
   182147         sessionAppendStr(&buf, zSep, &rc);
   182148         sessionAppendIdent(&buf, p->azCol[i], &rc);
   182149         sessionAppendStr(&buf, " IS ?", &rc);
   182150         sessionAppendInteger(&buf, i+1, &rc);
   182151         zSep = "AND ";
   182152       }
   182153     }
   182154     sessionAppendStr(&buf, ")", &rc);
   182155   }
   182156 
   182157   if( rc==SQLITE_OK ){
   182158     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
   182159   }
   182160   sqlite3_free(buf.aBuf);
   182161 
   182162   return rc;
   182163 }
   182164 
   182165 /*
   182166 ** Formulate and prepare a statement to UPDATE a row from database db.
   182167 ** Assuming a table structure like this:
   182168 **
   182169 **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
   182170 **
   182171 ** The UPDATE statement looks like this:
   182172 **
   182173 **     UPDATE x SET
   182174 **     a = CASE WHEN ?2  THEN ?3  ELSE a END,
   182175 **     b = CASE WHEN ?5  THEN ?6  ELSE b END,
   182176 **     c = CASE WHEN ?8  THEN ?9  ELSE c END,
   182177 **     d = CASE WHEN ?11 THEN ?12 ELSE d END
   182178 **     WHERE a = ?1 AND c = ?7 AND (?13 OR
   182179 **       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
   182180 **     )
   182181 **
   182182 ** For each column in the table, there are three variables to bind:
   182183 **
   182184 **     ?(i*3+1)    The old.* value of the column, if any.
   182185 **     ?(i*3+2)    A boolean flag indicating that the value is being modified.
   182186 **     ?(i*3+3)    The new.* value of the column, if any.
   182187 **
   182188 ** Also, a boolean flag that, if set to true, causes the statement to update
   182189 ** a row even if the non-PK values do not match. This is required if the
   182190 ** conflict-handler is invoked with CHANGESET_DATA and returns
   182191 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
   182192 **
   182193 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
   182194 ** pointing to the prepared version of the SQL statement.
   182195 */
   182196 static int sessionUpdateRow(
   182197   sqlite3 *db,                    /* Database handle */
   182198   const char *zTab,               /* Table name */
   182199   SessionApplyCtx *p              /* Session changeset-apply context */
   182200 ){
   182201   int rc = SQLITE_OK;
   182202   int i;
   182203   const char *zSep = "";
   182204   SessionBuffer buf = {0, 0, 0};
   182205 
   182206   /* Append "UPDATE tbl SET " */
   182207   sessionAppendStr(&buf, "UPDATE ", &rc);
   182208   sessionAppendIdent(&buf, zTab, &rc);
   182209   sessionAppendStr(&buf, " SET ", &rc);
   182210 
   182211   /* Append the assignments */
   182212   for(i=0; i<p->nCol; i++){
   182213     sessionAppendStr(&buf, zSep, &rc);
   182214     sessionAppendIdent(&buf, p->azCol[i], &rc);
   182215     sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
   182216     sessionAppendInteger(&buf, i*3+2, &rc);
   182217     sessionAppendStr(&buf, " THEN ?", &rc);
   182218     sessionAppendInteger(&buf, i*3+3, &rc);
   182219     sessionAppendStr(&buf, " ELSE ", &rc);
   182220     sessionAppendIdent(&buf, p->azCol[i], &rc);
   182221     sessionAppendStr(&buf, " END", &rc);
   182222     zSep = ", ";
   182223   }
   182224 
   182225   /* Append the PK part of the WHERE clause */
   182226   sessionAppendStr(&buf, " WHERE ", &rc);
   182227   for(i=0; i<p->nCol; i++){
   182228     if( p->abPK[i] ){
   182229       sessionAppendIdent(&buf, p->azCol[i], &rc);
   182230       sessionAppendStr(&buf, " = ?", &rc);
   182231       sessionAppendInteger(&buf, i*3+1, &rc);
   182232       sessionAppendStr(&buf, " AND ", &rc);
   182233     }
   182234   }
   182235 
   182236   /* Append the non-PK part of the WHERE clause */
   182237   sessionAppendStr(&buf, " (?", &rc);
   182238   sessionAppendInteger(&buf, p->nCol*3+1, &rc);
   182239   sessionAppendStr(&buf, " OR 1", &rc);
   182240   for(i=0; i<p->nCol; i++){
   182241     if( !p->abPK[i] ){
   182242       sessionAppendStr(&buf, " AND (?", &rc);
   182243       sessionAppendInteger(&buf, i*3+2, &rc);
   182244       sessionAppendStr(&buf, "=0 OR ", &rc);
   182245       sessionAppendIdent(&buf, p->azCol[i], &rc);
   182246       sessionAppendStr(&buf, " IS ?", &rc);
   182247       sessionAppendInteger(&buf, i*3+1, &rc);
   182248       sessionAppendStr(&buf, ")", &rc);
   182249     }
   182250   }
   182251   sessionAppendStr(&buf, ")", &rc);
   182252 
   182253   if( rc==SQLITE_OK ){
   182254     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
   182255   }
   182256   sqlite3_free(buf.aBuf);
   182257 
   182258   return rc;
   182259 }
   182260 
   182261 
   182262 /*
   182263 ** Formulate and prepare an SQL statement to query table zTab by primary
   182264 ** key. Assuming the following table structure:
   182265 **
   182266 **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
   182267 **
   182268 ** The SELECT statement looks like this:
   182269 **
   182270 **     SELECT * FROM x WHERE a = ?1 AND c = ?3
   182271 **
   182272 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
   182273 ** pointing to the prepared version of the SQL statement.
   182274 */
   182275 static int sessionSelectRow(
   182276   sqlite3 *db,                    /* Database handle */
   182277   const char *zTab,               /* Table name */
   182278   SessionApplyCtx *p              /* Session changeset-apply context */
   182279 ){
   182280   return sessionSelectStmt(
   182281       db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
   182282 }
   182283 
   182284 /*
   182285 ** Formulate and prepare an INSERT statement to add a record to table zTab.
   182286 ** For example:
   182287 **
   182288 **     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
   182289 **
   182290 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
   182291 ** pointing to the prepared version of the SQL statement.
   182292 */
   182293 static int sessionInsertRow(
   182294   sqlite3 *db,                    /* Database handle */
   182295   const char *zTab,               /* Table name */
   182296   SessionApplyCtx *p              /* Session changeset-apply context */
   182297 ){
   182298   int rc = SQLITE_OK;
   182299   int i;
   182300   SessionBuffer buf = {0, 0, 0};
   182301 
   182302   sessionAppendStr(&buf, "INSERT INTO main.", &rc);
   182303   sessionAppendIdent(&buf, zTab, &rc);
   182304   sessionAppendStr(&buf, "(", &rc);
   182305   for(i=0; i<p->nCol; i++){
   182306     if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
   182307     sessionAppendIdent(&buf, p->azCol[i], &rc);
   182308   }
   182309 
   182310   sessionAppendStr(&buf, ") VALUES(?", &rc);
   182311   for(i=1; i<p->nCol; i++){
   182312     sessionAppendStr(&buf, ", ?", &rc);
   182313   }
   182314   sessionAppendStr(&buf, ")", &rc);
   182315 
   182316   if( rc==SQLITE_OK ){
   182317     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
   182318   }
   182319   sqlite3_free(buf.aBuf);
   182320   return rc;
   182321 }
   182322 
   182323 static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
   182324   return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
   182325 }
   182326 
   182327 /*
   182328 ** Prepare statements for applying changes to the sqlite_stat1 table.
   182329 ** These are similar to those created by sessionSelectRow(),
   182330 ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
   182331 ** other tables.
   182332 */
   182333 static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
   182334   int rc = sessionSelectRow(db, "sqlite_stat1", p);
   182335   if( rc==SQLITE_OK ){
   182336     rc = sessionPrepare(db, &p->pInsert,
   182337         "INSERT INTO main.sqlite_stat1 VALUES(?1, "
   182338         "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
   182339         "?3)"
   182340     );
   182341   }
   182342   if( rc==SQLITE_OK ){
   182343     rc = sessionPrepare(db, &p->pUpdate,
   182344         "UPDATE main.sqlite_stat1 SET "
   182345         "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
   182346         "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
   182347         "stat = CASE WHEN ?8 THEN ?9 ELSE stat END  "
   182348         "WHERE tbl=?1 AND idx IS "
   182349         "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
   182350         "AND (?10 OR ?8=0 OR stat IS ?7)"
   182351     );
   182352   }
   182353   if( rc==SQLITE_OK ){
   182354     rc = sessionPrepare(db, &p->pDelete,
   182355         "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
   182356         "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
   182357         "AND (?4 OR stat IS ?3)"
   182358     );
   182359   }
   182360   assert( rc==SQLITE_OK );
   182361   return rc;
   182362 }
   182363 
   182364 /*
   182365 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
   182366 ** See comments in the body of this function for details.
   182367 */
   182368 static int sessionBindValue(
   182369   sqlite3_stmt *pStmt,            /* Statement to bind value to */
   182370   int i,                          /* Parameter number to bind to */
   182371   sqlite3_value *pVal             /* Value to bind */
   182372 ){
   182373   int eType = sqlite3_value_type(pVal);
   182374   /* COVERAGE: The (pVal->z==0) branch is never true using current versions
   182375   ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
   182376   ** the (pVal->z) variable remains as it was or the type of the value is
   182377   ** set to SQLITE_NULL.  */
   182378   if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
   182379     /* This condition occurs when an earlier OOM in a call to
   182380     ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
   182381     ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
   182382     return SQLITE_NOMEM;
   182383   }
   182384   return sqlite3_bind_value(pStmt, i, pVal);
   182385 }
   182386 
   182387 /*
   182388 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
   182389 ** transfers new.* values from the current iterator entry to statement
   182390 ** pStmt. The table being inserted into has nCol columns.
   182391 **
   182392 ** New.* value $i from the iterator is bound to variable ($i+1) of
   182393 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
   182394 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
   182395 ** to an array nCol elements in size. In this case only those values for
   182396 ** which abPK[$i] is true are read from the iterator and bound to the
   182397 ** statement.
   182398 **
   182399 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
   182400 */
   182401 static int sessionBindRow(
   182402   sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
   182403   int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
   182404   int nCol,                       /* Number of columns */
   182405   u8 *abPK,                       /* If not NULL, bind only if true */
   182406   sqlite3_stmt *pStmt             /* Bind values to this statement */
   182407 ){
   182408   int i;
   182409   int rc = SQLITE_OK;
   182410 
   182411   /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
   182412   ** argument iterator points to a suitable entry. Make sure that xValue
   182413   ** is one of these to guarantee that it is safe to ignore the return
   182414   ** in the code below. */
   182415   assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
   182416 
   182417   for(i=0; rc==SQLITE_OK && i<nCol; i++){
   182418     if( !abPK || abPK[i] ){
   182419       sqlite3_value *pVal;
   182420       (void)xValue(pIter, i, &pVal);
   182421       rc = sessionBindValue(pStmt, i+1, pVal);
   182422     }
   182423   }
   182424   return rc;
   182425 }
   182426 
   182427 /*
   182428 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
   182429 ** This function binds the primary key values from the change that changeset
   182430 ** iterator pIter points to to the SELECT and attempts to seek to the table
   182431 ** entry. If a row is found, the SELECT statement left pointing at the row
   182432 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
   182433 ** has occured, the statement is reset and SQLITE_OK is returned. If an
   182434 ** error occurs, the statement is reset and an SQLite error code is returned.
   182435 **
   182436 ** If this function returns SQLITE_ROW, the caller must eventually reset()
   182437 ** statement pSelect. If any other value is returned, the statement does
   182438 ** not require a reset().
   182439 **
   182440 ** If the iterator currently points to an INSERT record, bind values from the
   182441 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
   182442 ** UPDATE, bind values from the old.* record.
   182443 */
   182444 static int sessionSeekToRow(
   182445   sqlite3 *db,                    /* Database handle */
   182446   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   182447   u8 *abPK,                       /* Primary key flags array */
   182448   sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
   182449 ){
   182450   int rc;                         /* Return code */
   182451   int nCol;                       /* Number of columns in table */
   182452   int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
   182453   const char *zDummy;             /* Unused */
   182454 
   182455   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
   182456   rc = sessionBindRow(pIter,
   182457       op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
   182458       nCol, abPK, pSelect
   182459   );
   182460 
   182461   if( rc==SQLITE_OK ){
   182462     rc = sqlite3_step(pSelect);
   182463     if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
   182464   }
   182465 
   182466   return rc;
   182467 }
   182468 
   182469 /*
   182470 ** Invoke the conflict handler for the change that the changeset iterator
   182471 ** currently points to.
   182472 **
   182473 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
   182474 ** If argument pbReplace is NULL, then the type of conflict handler invoked
   182475 ** depends solely on eType, as follows:
   182476 **
   182477 **    eType value                 Value passed to xConflict
   182478 **    -------------------------------------------------
   182479 **    CHANGESET_DATA              CHANGESET_NOTFOUND
   182480 **    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
   182481 **
   182482 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
   182483 ** record with the same primary key as the record about to be deleted, updated
   182484 ** or inserted. If such a record can be found, it is available to the conflict
   182485 ** handler as the "conflicting" record. In this case the type of conflict
   182486 ** handler invoked is as follows:
   182487 **
   182488 **    eType value         PK Record found?   Value passed to xConflict
   182489 **    ----------------------------------------------------------------
   182490 **    CHANGESET_DATA      Yes                CHANGESET_DATA
   182491 **    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
   182492 **    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
   182493 **    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
   182494 **
   182495 ** If pbReplace is not NULL, and a record with a matching PK is found, and
   182496 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
   182497 ** is set to non-zero before returning SQLITE_OK.
   182498 **
   182499 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
   182500 ** returned. Or, if the conflict handler returns an invalid value,
   182501 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
   182502 ** this function returns SQLITE_OK.
   182503 */
   182504 static int sessionConflictHandler(
   182505   int eType,                      /* Either CHANGESET_DATA or CONFLICT */
   182506   SessionApplyCtx *p,             /* changeset_apply() context */
   182507   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   182508   int(*xConflict)(void *, int, sqlite3_changeset_iter*),
   182509   void *pCtx,                     /* First argument for conflict handler */
   182510   int *pbReplace                  /* OUT: Set to true if PK row is found */
   182511 ){
   182512   int res = 0;                    /* Value returned by conflict handler */
   182513   int rc;
   182514   int nCol;
   182515   int op;
   182516   const char *zDummy;
   182517 
   182518   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
   182519 
   182520   assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
   182521   assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
   182522   assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
   182523 
   182524   /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
   182525   if( pbReplace ){
   182526     rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
   182527   }else{
   182528     rc = SQLITE_OK;
   182529   }
   182530 
   182531   if( rc==SQLITE_ROW ){
   182532     /* There exists another row with the new.* primary key. */
   182533     pIter->pConflict = p->pSelect;
   182534     res = xConflict(pCtx, eType, pIter);
   182535     pIter->pConflict = 0;
   182536     rc = sqlite3_reset(p->pSelect);
   182537   }else if( rc==SQLITE_OK ){
   182538     if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
   182539       /* Instead of invoking the conflict handler, append the change blob
   182540       ** to the SessionApplyCtx.constraints buffer. */
   182541       u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
   182542       int nBlob = pIter->in.iNext - pIter->in.iCurrent;
   182543       sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
   182544       res = SQLITE_CHANGESET_OMIT;
   182545     }else{
   182546       /* No other row with the new.* primary key. */
   182547       res = xConflict(pCtx, eType+1, pIter);
   182548       if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
   182549     }
   182550   }
   182551 
   182552   if( rc==SQLITE_OK ){
   182553     switch( res ){
   182554       case SQLITE_CHANGESET_REPLACE:
   182555         assert( pbReplace );
   182556         *pbReplace = 1;
   182557         break;
   182558 
   182559       case SQLITE_CHANGESET_OMIT:
   182560         break;
   182561 
   182562       case SQLITE_CHANGESET_ABORT:
   182563         rc = SQLITE_ABORT;
   182564         break;
   182565 
   182566       default:
   182567         rc = SQLITE_MISUSE;
   182568         break;
   182569     }
   182570   }
   182571 
   182572   return rc;
   182573 }
   182574 
   182575 /*
   182576 ** Attempt to apply the change that the iterator passed as the first argument
   182577 ** currently points to to the database. If a conflict is encountered, invoke
   182578 ** the conflict handler callback.
   182579 **
   182580 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
   182581 ** one is encountered, update or delete the row with the matching primary key
   182582 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
   182583 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
   182584 ** to true before returning. In this case the caller will invoke this function
   182585 ** again, this time with pbRetry set to NULL.
   182586 **
   182587 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
   182588 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
   182589 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
   182590 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
   182591 ** before retrying. In this case the caller attempts to remove the conflicting
   182592 ** row before invoking this function again, this time with pbReplace set
   182593 ** to NULL.
   182594 **
   182595 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
   182596 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
   182597 ** returned.
   182598 */
   182599 static int sessionApplyOneOp(
   182600   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
   182601   SessionApplyCtx *p,             /* changeset_apply() context */
   182602   int(*xConflict)(void *, int, sqlite3_changeset_iter *),
   182603   void *pCtx,                     /* First argument for the conflict handler */
   182604   int *pbReplace,                 /* OUT: True to remove PK row and retry */
   182605   int *pbRetry                    /* OUT: True to retry. */
   182606 ){
   182607   const char *zDummy;
   182608   int op;
   182609   int nCol;
   182610   int rc = SQLITE_OK;
   182611 
   182612   assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
   182613   assert( p->azCol && p->abPK );
   182614   assert( !pbReplace || *pbReplace==0 );
   182615 
   182616   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
   182617 
   182618   if( op==SQLITE_DELETE ){
   182619 
   182620     /* Bind values to the DELETE statement. If conflict handling is required,
   182621     ** bind values for all columns and set bound variable (nCol+1) to true.
   182622     ** Or, if conflict handling is not required, bind just the PK column
   182623     ** values and, if it exists, set (nCol+1) to false. Conflict handling
   182624     ** is not required if:
   182625     **
   182626     **   * this is a patchset, or
   182627     **   * (pbRetry==0), or
   182628     **   * all columns of the table are PK columns (in this case there is
   182629     **     no (nCol+1) variable to bind to).
   182630     */
   182631     u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
   182632     rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
   182633     if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
   182634       rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
   182635     }
   182636     if( rc!=SQLITE_OK ) return rc;
   182637 
   182638     sqlite3_step(p->pDelete);
   182639     rc = sqlite3_reset(p->pDelete);
   182640     if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
   182641       rc = sessionConflictHandler(
   182642           SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
   182643       );
   182644     }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
   182645       rc = sessionConflictHandler(
   182646           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
   182647       );
   182648     }
   182649 
   182650   }else if( op==SQLITE_UPDATE ){
   182651     int i;
   182652 
   182653     /* Bind values to the UPDATE statement. */
   182654     for(i=0; rc==SQLITE_OK && i<nCol; i++){
   182655       sqlite3_value *pOld = sessionChangesetOld(pIter, i);
   182656       sqlite3_value *pNew = sessionChangesetNew(pIter, i);
   182657 
   182658       sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
   182659       if( pOld ){
   182660         rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
   182661       }
   182662       if( rc==SQLITE_OK && pNew ){
   182663         rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
   182664       }
   182665     }
   182666     if( rc==SQLITE_OK ){
   182667       sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
   182668     }
   182669     if( rc!=SQLITE_OK ) return rc;
   182670 
   182671     /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
   182672     ** the result will be SQLITE_OK with 0 rows modified. */
   182673     sqlite3_step(p->pUpdate);
   182674     rc = sqlite3_reset(p->pUpdate);
   182675 
   182676     if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
   182677       /* A NOTFOUND or DATA error. Search the table to see if it contains
   182678       ** a row with a matching primary key. If so, this is a DATA conflict.
   182679       ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
   182680 
   182681       rc = sessionConflictHandler(
   182682           SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
   182683       );
   182684 
   182685     }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
   182686       /* This is always a CONSTRAINT conflict. */
   182687       rc = sessionConflictHandler(
   182688           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
   182689       );
   182690     }
   182691 
   182692   }else{
   182693     assert( op==SQLITE_INSERT );
   182694     if( p->bStat1 ){
   182695       /* Check if there is a conflicting row. For sqlite_stat1, this needs
   182696       ** to be done using a SELECT, as there is no PRIMARY KEY in the
   182697       ** database schema to throw an exception if a duplicate is inserted.  */
   182698       rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
   182699       if( rc==SQLITE_ROW ){
   182700         rc = SQLITE_CONSTRAINT;
   182701         sqlite3_reset(p->pSelect);
   182702       }
   182703     }
   182704 
   182705     if( rc==SQLITE_OK ){
   182706       rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
   182707       if( rc!=SQLITE_OK ) return rc;
   182708 
   182709       sqlite3_step(p->pInsert);
   182710       rc = sqlite3_reset(p->pInsert);
   182711     }
   182712 
   182713     if( (rc&0xff)==SQLITE_CONSTRAINT ){
   182714       rc = sessionConflictHandler(
   182715           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
   182716       );
   182717     }
   182718   }
   182719 
   182720   return rc;
   182721 }
   182722 
   182723 /*
   182724 ** Attempt to apply the change that the iterator passed as the first argument
   182725 ** currently points to to the database. If a conflict is encountered, invoke
   182726 ** the conflict handler callback.
   182727 **
   182728 ** The difference between this function and sessionApplyOne() is that this
   182729 ** function handles the case where the conflict-handler is invoked and
   182730 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
   182731 ** retried in some manner.
   182732 */
   182733 static int sessionApplyOneWithRetry(
   182734   sqlite3 *db,                    /* Apply change to "main" db of this handle */
   182735   sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
   182736   SessionApplyCtx *pApply,        /* Apply context */
   182737   int(*xConflict)(void*, int, sqlite3_changeset_iter*),
   182738   void *pCtx                      /* First argument passed to xConflict */
   182739 ){
   182740   int bReplace = 0;
   182741   int bRetry = 0;
   182742   int rc;
   182743 
   182744   rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
   182745   assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
   182746 
   182747   /* If the bRetry flag is set, the change has not been applied due to an
   182748   ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
   182749   ** a row with the correct PK is present in the db, but one or more other
   182750   ** fields do not contain the expected values) and the conflict handler
   182751   ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
   182752   ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
   182753   ** the SQLITE_CHANGESET_DATA problem.  */
   182754   if( bRetry ){
   182755     assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
   182756     rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
   182757   }
   182758 
   182759   /* If the bReplace flag is set, the change is an INSERT that has not
   182760   ** been performed because the database already contains a row with the
   182761   ** specified primary key and the conflict handler returned
   182762   ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
   182763   ** before reattempting the INSERT.  */
   182764   else if( bReplace ){
   182765     assert( pIter->op==SQLITE_INSERT );
   182766     rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
   182767     if( rc==SQLITE_OK ){
   182768       rc = sessionBindRow(pIter,
   182769           sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
   182770       sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
   182771     }
   182772     if( rc==SQLITE_OK ){
   182773       sqlite3_step(pApply->pDelete);
   182774       rc = sqlite3_reset(pApply->pDelete);
   182775     }
   182776     if( rc==SQLITE_OK ){
   182777       rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
   182778     }
   182779     if( rc==SQLITE_OK ){
   182780       rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
   182781     }
   182782   }
   182783 
   182784   return rc;
   182785 }
   182786 
   182787 /*
   182788 ** Retry the changes accumulated in the pApply->constraints buffer.
   182789 */
   182790 static int sessionRetryConstraints(
   182791   sqlite3 *db,
   182792   int bPatchset,
   182793   const char *zTab,
   182794   SessionApplyCtx *pApply,
   182795   int(*xConflict)(void*, int, sqlite3_changeset_iter*),
   182796   void *pCtx                      /* First argument passed to xConflict */
   182797 ){
   182798   int rc = SQLITE_OK;
   182799 
   182800   while( pApply->constraints.nBuf ){
   182801     sqlite3_changeset_iter *pIter2 = 0;
   182802     SessionBuffer cons = pApply->constraints;
   182803     memset(&pApply->constraints, 0, sizeof(SessionBuffer));
   182804 
   182805     rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
   182806     if( rc==SQLITE_OK ){
   182807       int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
   182808       int rc2;
   182809       pIter2->bPatchset = bPatchset;
   182810       pIter2->zTab = (char*)zTab;
   182811       pIter2->nCol = pApply->nCol;
   182812       pIter2->abPK = pApply->abPK;
   182813       sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
   182814       pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
   182815       if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
   182816 
   182817       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
   182818         rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
   182819       }
   182820 
   182821       rc2 = sqlite3changeset_finalize(pIter2);
   182822       if( rc==SQLITE_OK ) rc = rc2;
   182823     }
   182824     assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
   182825 
   182826     sqlite3_free(cons.aBuf);
   182827     if( rc!=SQLITE_OK ) break;
   182828     if( pApply->constraints.nBuf>=cons.nBuf ){
   182829       /* No progress was made on the last round. */
   182830       pApply->bDeferConstraints = 0;
   182831     }
   182832   }
   182833 
   182834   return rc;
   182835 }
   182836 
   182837 /*
   182838 ** Argument pIter is a changeset iterator that has been initialized, but
   182839 ** not yet passed to sqlite3changeset_next(). This function applies the
   182840 ** changeset to the main database attached to handle "db". The supplied
   182841 ** conflict handler callback is invoked to resolve any conflicts encountered
   182842 ** while applying the change.
   182843 */
   182844 static int sessionChangesetApply(
   182845   sqlite3 *db,                    /* Apply change to "main" db of this handle */
   182846   sqlite3_changeset_iter *pIter,  /* Changeset to apply */
   182847   int(*xFilter)(
   182848     void *pCtx,                   /* Copy of sixth arg to _apply() */
   182849     const char *zTab              /* Table name */
   182850   ),
   182851   int(*xConflict)(
   182852     void *pCtx,                   /* Copy of fifth arg to _apply() */
   182853     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
   182854     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
   182855   ),
   182856   void *pCtx                      /* First argument passed to xConflict */
   182857 ){
   182858   int schemaMismatch = 0;
   182859   int rc;                         /* Return code */
   182860   const char *zTab = 0;           /* Name of current table */
   182861   int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
   182862   SessionApplyCtx sApply;         /* changeset_apply() context object */
   182863   int bPatchset;
   182864 
   182865   assert( xConflict!=0 );
   182866 
   182867   pIter->in.bNoDiscard = 1;
   182868   memset(&sApply, 0, sizeof(sApply));
   182869   sqlite3_mutex_enter(sqlite3_db_mutex(db));
   182870   rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
   182871   if( rc==SQLITE_OK ){
   182872     rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
   182873   }
   182874   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
   182875     int nCol;
   182876     int op;
   182877     const char *zNew;
   182878 
   182879     sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
   182880 
   182881     if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
   182882       u8 *abPK;
   182883 
   182884       rc = sessionRetryConstraints(
   182885           db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
   182886       );
   182887       if( rc!=SQLITE_OK ) break;
   182888 
   182889       sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
   182890       sqlite3_finalize(sApply.pDelete);
   182891       sqlite3_finalize(sApply.pUpdate);
   182892       sqlite3_finalize(sApply.pInsert);
   182893       sqlite3_finalize(sApply.pSelect);
   182894       memset(&sApply, 0, sizeof(sApply));
   182895       sApply.db = db;
   182896       sApply.bDeferConstraints = 1;
   182897 
   182898       /* If an xFilter() callback was specified, invoke it now. If the
   182899       ** xFilter callback returns zero, skip this table. If it returns
   182900       ** non-zero, proceed. */
   182901       schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
   182902       if( schemaMismatch ){
   182903         zTab = sqlite3_mprintf("%s", zNew);
   182904         if( zTab==0 ){
   182905           rc = SQLITE_NOMEM;
   182906           break;
   182907         }
   182908         nTab = (int)strlen(zTab);
   182909         sApply.azCol = (const char **)zTab;
   182910       }else{
   182911         int nMinCol = 0;
   182912         int i;
   182913 
   182914         sqlite3changeset_pk(pIter, &abPK, 0);
   182915         rc = sessionTableInfo(
   182916             db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
   182917         );
   182918         if( rc!=SQLITE_OK ) break;
   182919         for(i=0; i<sApply.nCol; i++){
   182920           if( sApply.abPK[i] ) nMinCol = i+1;
   182921         }
   182922 
   182923         if( sApply.nCol==0 ){
   182924           schemaMismatch = 1;
   182925           sqlite3_log(SQLITE_SCHEMA,
   182926               "sqlite3changeset_apply(): no such table: %s", zTab
   182927           );
   182928         }
   182929         else if( sApply.nCol<nCol ){
   182930           schemaMismatch = 1;
   182931           sqlite3_log(SQLITE_SCHEMA,
   182932               "sqlite3changeset_apply(): table %s has %d columns, "
   182933               "expected %d or more",
   182934               zTab, sApply.nCol, nCol
   182935           );
   182936         }
   182937         else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
   182938           schemaMismatch = 1;
   182939           sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
   182940               "primary key mismatch for table %s", zTab
   182941           );
   182942         }
   182943         else{
   182944           sApply.nCol = nCol;
   182945           if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
   182946             if( (rc = sessionStat1Sql(db, &sApply) ) ){
   182947               break;
   182948             }
   182949             sApply.bStat1 = 1;
   182950           }else{
   182951             if((rc = sessionSelectRow(db, zTab, &sApply))
   182952                 || (rc = sessionUpdateRow(db, zTab, &sApply))
   182953                 || (rc = sessionDeleteRow(db, zTab, &sApply))
   182954                 || (rc = sessionInsertRow(db, zTab, &sApply))
   182955               ){
   182956               break;
   182957             }
   182958             sApply.bStat1 = 0;
   182959           }
   182960         }
   182961         nTab = sqlite3Strlen30(zTab);
   182962       }
   182963     }
   182964 
   182965     /* If there is a schema mismatch on the current table, proceed to the
   182966     ** next change. A log message has already been issued. */
   182967     if( schemaMismatch ) continue;
   182968 
   182969     rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
   182970   }
   182971 
   182972   bPatchset = pIter->bPatchset;
   182973   if( rc==SQLITE_OK ){
   182974     rc = sqlite3changeset_finalize(pIter);
   182975   }else{
   182976     sqlite3changeset_finalize(pIter);
   182977   }
   182978 
   182979   if( rc==SQLITE_OK ){
   182980     rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
   182981   }
   182982 
   182983   if( rc==SQLITE_OK ){
   182984     int nFk, notUsed;
   182985     sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
   182986     if( nFk!=0 ){
   182987       int res = SQLITE_CHANGESET_ABORT;
   182988       sqlite3_changeset_iter sIter;
   182989       memset(&sIter, 0, sizeof(sIter));
   182990       sIter.nCol = nFk;
   182991       res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
   182992       if( res!=SQLITE_CHANGESET_OMIT ){
   182993         rc = SQLITE_CONSTRAINT;
   182994       }
   182995     }
   182996   }
   182997   sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
   182998 
   182999   if( rc==SQLITE_OK ){
   183000     rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
   183001   }else{
   183002     sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
   183003     sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
   183004   }
   183005 
   183006   sqlite3_finalize(sApply.pInsert);
   183007   sqlite3_finalize(sApply.pDelete);
   183008   sqlite3_finalize(sApply.pUpdate);
   183009   sqlite3_finalize(sApply.pSelect);
   183010   sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
   183011   sqlite3_free((char*)sApply.constraints.aBuf);
   183012   sqlite3_mutex_leave(sqlite3_db_mutex(db));
   183013   return rc;
   183014 }
   183015 
   183016 /*
   183017 ** Apply the changeset passed via pChangeset/nChangeset to the main database
   183018 ** attached to handle "db". Invoke the supplied conflict handler callback
   183019 ** to resolve any conflicts encountered while applying the change.
   183020 */
   183021 SQLITE_API int sqlite3changeset_apply(
   183022   sqlite3 *db,                    /* Apply change to "main" db of this handle */
   183023   int nChangeset,                 /* Size of changeset in bytes */
   183024   void *pChangeset,               /* Changeset blob */
   183025   int(*xFilter)(
   183026     void *pCtx,                   /* Copy of sixth arg to _apply() */
   183027     const char *zTab              /* Table name */
   183028   ),
   183029   int(*xConflict)(
   183030     void *pCtx,                   /* Copy of fifth arg to _apply() */
   183031     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
   183032     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
   183033   ),
   183034   void *pCtx                      /* First argument passed to xConflict */
   183035 ){
   183036   sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
   183037   int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
   183038   if( rc==SQLITE_OK ){
   183039     rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
   183040   }
   183041   return rc;
   183042 }
   183043 
   183044 /*
   183045 ** Apply the changeset passed via xInput/pIn to the main database
   183046 ** attached to handle "db". Invoke the supplied conflict handler callback
   183047 ** to resolve any conflicts encountered while applying the change.
   183048 */
   183049 SQLITE_API int sqlite3changeset_apply_strm(
   183050   sqlite3 *db,                    /* Apply change to "main" db of this handle */
   183051   int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
   183052   void *pIn,                                          /* First arg for xInput */
   183053   int(*xFilter)(
   183054     void *pCtx,                   /* Copy of sixth arg to _apply() */
   183055     const char *zTab              /* Table name */
   183056   ),
   183057   int(*xConflict)(
   183058     void *pCtx,                   /* Copy of sixth arg to _apply() */
   183059     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
   183060     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
   183061   ),
   183062   void *pCtx                      /* First argument passed to xConflict */
   183063 ){
   183064   sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
   183065   int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
   183066   if( rc==SQLITE_OK ){
   183067     rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
   183068   }
   183069   return rc;
   183070 }
   183071 
   183072 /*
   183073 ** sqlite3_changegroup handle.
   183074 */
   183075 struct sqlite3_changegroup {
   183076   int rc;                         /* Error code */
   183077   int bPatch;                     /* True to accumulate patchsets */
   183078   SessionTable *pList;            /* List of tables in current patch */
   183079 };
   183080 
   183081 /*
   183082 ** This function is called to merge two changes to the same row together as
   183083 ** part of an sqlite3changeset_concat() operation. A new change object is
   183084 ** allocated and a pointer to it stored in *ppNew.
   183085 */
   183086 static int sessionChangeMerge(
   183087   SessionTable *pTab,             /* Table structure */
   183088   int bPatchset,                  /* True for patchsets */
   183089   SessionChange *pExist,          /* Existing change */
   183090   int op2,                        /* Second change operation */
   183091   int bIndirect,                  /* True if second change is indirect */
   183092   u8 *aRec,                       /* Second change record */
   183093   int nRec,                       /* Number of bytes in aRec */
   183094   SessionChange **ppNew           /* OUT: Merged change */
   183095 ){
   183096   SessionChange *pNew = 0;
   183097 
   183098   if( !pExist ){
   183099     pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
   183100     if( !pNew ){
   183101       return SQLITE_NOMEM;
   183102     }
   183103     memset(pNew, 0, sizeof(SessionChange));
   183104     pNew->op = op2;
   183105     pNew->bIndirect = bIndirect;
   183106     pNew->nRecord = nRec;
   183107     pNew->aRecord = (u8*)&pNew[1];
   183108     memcpy(pNew->aRecord, aRec, nRec);
   183109   }else{
   183110     int op1 = pExist->op;
   183111 
   183112     /*
   183113     **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
   183114     **   op1=INSERT, op2=UPDATE      ->      INSERT.
   183115     **   op1=INSERT, op2=DELETE      ->      (none)
   183116     **
   183117     **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
   183118     **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
   183119     **   op1=UPDATE, op2=DELETE      ->      DELETE.
   183120     **
   183121     **   op1=DELETE, op2=INSERT      ->      UPDATE.
   183122     **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
   183123     **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
   183124     */
   183125     if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
   183126      || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
   183127      || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
   183128      || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
   183129     ){
   183130       pNew = pExist;
   183131     }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
   183132       sqlite3_free(pExist);
   183133       assert( pNew==0 );
   183134     }else{
   183135       u8 *aExist = pExist->aRecord;
   183136       int nByte;
   183137       u8 *aCsr;
   183138 
   183139       /* Allocate a new SessionChange object. Ensure that the aRecord[]
   183140       ** buffer of the new object is large enough to hold any record that
   183141       ** may be generated by combining the input records.  */
   183142       nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
   183143       pNew = (SessionChange *)sqlite3_malloc(nByte);
   183144       if( !pNew ){
   183145         sqlite3_free(pExist);
   183146         return SQLITE_NOMEM;
   183147       }
   183148       memset(pNew, 0, sizeof(SessionChange));
   183149       pNew->bIndirect = (bIndirect && pExist->bIndirect);
   183150       aCsr = pNew->aRecord = (u8 *)&pNew[1];
   183151 
   183152       if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
   183153         u8 *a1 = aRec;
   183154         assert( op2==SQLITE_UPDATE );
   183155         pNew->op = SQLITE_INSERT;
   183156         if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
   183157         sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
   183158       }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
   183159         assert( op2==SQLITE_INSERT );
   183160         pNew->op = SQLITE_UPDATE;
   183161         if( bPatchset ){
   183162           memcpy(aCsr, aRec, nRec);
   183163           aCsr += nRec;
   183164         }else{
   183165           if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
   183166             sqlite3_free(pNew);
   183167             pNew = 0;
   183168           }
   183169         }
   183170       }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
   183171         u8 *a1 = aExist;
   183172         u8 *a2 = aRec;
   183173         assert( op1==SQLITE_UPDATE );
   183174         if( bPatchset==0 ){
   183175           sessionSkipRecord(&a1, pTab->nCol);
   183176           sessionSkipRecord(&a2, pTab->nCol);
   183177         }
   183178         pNew->op = SQLITE_UPDATE;
   183179         if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
   183180           sqlite3_free(pNew);
   183181           pNew = 0;
   183182         }
   183183       }else{                                /* UPDATE + DELETE */
   183184         assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
   183185         pNew->op = SQLITE_DELETE;
   183186         if( bPatchset ){
   183187           memcpy(aCsr, aRec, nRec);
   183188           aCsr += nRec;
   183189         }else{
   183190           sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
   183191         }
   183192       }
   183193 
   183194       if( pNew ){
   183195         pNew->nRecord = (int)(aCsr - pNew->aRecord);
   183196       }
   183197       sqlite3_free(pExist);
   183198     }
   183199   }
   183200 
   183201   *ppNew = pNew;
   183202   return SQLITE_OK;
   183203 }
   183204 
   183205 /*
   183206 ** Add all changes in the changeset traversed by the iterator passed as
   183207 ** the first argument to the changegroup hash tables.
   183208 */
   183209 static int sessionChangesetToHash(
   183210   sqlite3_changeset_iter *pIter,   /* Iterator to read from */
   183211   sqlite3_changegroup *pGrp        /* Changegroup object to add changeset to */
   183212 ){
   183213   u8 *aRec;
   183214   int nRec;
   183215   int rc = SQLITE_OK;
   183216   SessionTable *pTab = 0;
   183217 
   183218 
   183219   while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
   183220     const char *zNew;
   183221     int nCol;
   183222     int op;
   183223     int iHash;
   183224     int bIndirect;
   183225     SessionChange *pChange;
   183226     SessionChange *pExist = 0;
   183227     SessionChange **pp;
   183228 
   183229     if( pGrp->pList==0 ){
   183230       pGrp->bPatch = pIter->bPatchset;
   183231     }else if( pIter->bPatchset!=pGrp->bPatch ){
   183232       rc = SQLITE_ERROR;
   183233       break;
   183234     }
   183235 
   183236     sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
   183237     if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
   183238       /* Search the list for a matching table */
   183239       int nNew = (int)strlen(zNew);
   183240       u8 *abPK;
   183241 
   183242       sqlite3changeset_pk(pIter, &abPK, 0);
   183243       for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
   183244         if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
   183245       }
   183246       if( !pTab ){
   183247         SessionTable **ppTab;
   183248 
   183249         pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
   183250         if( !pTab ){
   183251           rc = SQLITE_NOMEM;
   183252           break;
   183253         }
   183254         memset(pTab, 0, sizeof(SessionTable));
   183255         pTab->nCol = nCol;
   183256         pTab->abPK = (u8*)&pTab[1];
   183257         memcpy(pTab->abPK, abPK, nCol);
   183258         pTab->zName = (char*)&pTab->abPK[nCol];
   183259         memcpy(pTab->zName, zNew, nNew+1);
   183260 
   183261         /* The new object must be linked on to the end of the list, not
   183262         ** simply added to the start of it. This is to ensure that the
   183263         ** tables within the output of sqlite3changegroup_output() are in
   183264         ** the right order.  */
   183265         for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
   183266         *ppTab = pTab;
   183267       }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
   183268         rc = SQLITE_SCHEMA;
   183269         break;
   183270       }
   183271     }
   183272 
   183273     if( sessionGrowHash(pIter->bPatchset, pTab) ){
   183274       rc = SQLITE_NOMEM;
   183275       break;
   183276     }
   183277     iHash = sessionChangeHash(
   183278         pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
   183279     );
   183280 
   183281     /* Search for existing entry. If found, remove it from the hash table.
   183282     ** Code below may link it back in.
   183283     */
   183284     for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
   183285       int bPkOnly1 = 0;
   183286       int bPkOnly2 = 0;
   183287       if( pIter->bPatchset ){
   183288         bPkOnly1 = (*pp)->op==SQLITE_DELETE;
   183289         bPkOnly2 = op==SQLITE_DELETE;
   183290       }
   183291       if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
   183292         pExist = *pp;
   183293         *pp = (*pp)->pNext;
   183294         pTab->nEntry--;
   183295         break;
   183296       }
   183297     }
   183298 
   183299     rc = sessionChangeMerge(pTab,
   183300         pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
   183301     );
   183302     if( rc ) break;
   183303     if( pChange ){
   183304       pChange->pNext = pTab->apChange[iHash];
   183305       pTab->apChange[iHash] = pChange;
   183306       pTab->nEntry++;
   183307     }
   183308   }
   183309 
   183310   if( rc==SQLITE_OK ) rc = pIter->rc;
   183311   return rc;
   183312 }
   183313 
   183314 /*
   183315 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
   183316 ** added to the changegroup object passed as the first argument.
   183317 **
   183318 ** If xOutput is not NULL, then the changeset/patchset is returned to the
   183319 ** user via one or more calls to xOutput, as with the other streaming
   183320 ** interfaces.
   183321 **
   183322 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
   183323 ** buffer containing the output changeset before this function returns. In
   183324 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
   183325 ** is the responsibility of the caller to free the output buffer using
   183326 ** sqlite3_free() when it is no longer required.
   183327 **
   183328 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
   183329 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
   183330 ** are both set to 0 before returning.
   183331 */
   183332 static int sessionChangegroupOutput(
   183333   sqlite3_changegroup *pGrp,
   183334   int (*xOutput)(void *pOut, const void *pData, int nData),
   183335   void *pOut,
   183336   int *pnOut,
   183337   void **ppOut
   183338 ){
   183339   int rc = SQLITE_OK;
   183340   SessionBuffer buf = {0, 0, 0};
   183341   SessionTable *pTab;
   183342   assert( xOutput==0 || (ppOut==0 && pnOut==0) );
   183343 
   183344   /* Create the serialized output changeset based on the contents of the
   183345   ** hash tables attached to the SessionTable objects in list p->pList.
   183346   */
   183347   for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
   183348     int i;
   183349     if( pTab->nEntry==0 ) continue;
   183350 
   183351     sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
   183352     for(i=0; i<pTab->nChange; i++){
   183353       SessionChange *p;
   183354       for(p=pTab->apChange[i]; p; p=p->pNext){
   183355         sessionAppendByte(&buf, p->op, &rc);
   183356         sessionAppendByte(&buf, p->bIndirect, &rc);
   183357         sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
   183358       }
   183359     }
   183360 
   183361     if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
   183362       rc = xOutput(pOut, buf.aBuf, buf.nBuf);
   183363       buf.nBuf = 0;
   183364     }
   183365   }
   183366 
   183367   if( rc==SQLITE_OK ){
   183368     if( xOutput ){
   183369       if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
   183370     }else{
   183371       *ppOut = buf.aBuf;
   183372       *pnOut = buf.nBuf;
   183373       buf.aBuf = 0;
   183374     }
   183375   }
   183376   sqlite3_free(buf.aBuf);
   183377 
   183378   return rc;
   183379 }
   183380 
   183381 /*
   183382 ** Allocate a new, empty, sqlite3_changegroup.
   183383 */
   183384 SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
   183385   int rc = SQLITE_OK;             /* Return code */
   183386   sqlite3_changegroup *p;         /* New object */
   183387   p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
   183388   if( p==0 ){
   183389     rc = SQLITE_NOMEM;
   183390   }else{
   183391     memset(p, 0, sizeof(sqlite3_changegroup));
   183392   }
   183393   *pp = p;
   183394   return rc;
   183395 }
   183396 
   183397 /*
   183398 ** Add the changeset currently stored in buffer pData, size nData bytes,
   183399 ** to changeset-group p.
   183400 */
   183401 SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
   183402   sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
   183403   int rc;                         /* Return code */
   183404 
   183405   rc = sqlite3changeset_start(&pIter, nData, pData);
   183406   if( rc==SQLITE_OK ){
   183407     rc = sessionChangesetToHash(pIter, pGrp);
   183408   }
   183409   sqlite3changeset_finalize(pIter);
   183410   return rc;
   183411 }
   183412 
   183413 /*
   183414 ** Obtain a buffer containing a changeset representing the concatenation
   183415 ** of all changesets added to the group so far.
   183416 */
   183417 SQLITE_API int sqlite3changegroup_output(
   183418     sqlite3_changegroup *pGrp,
   183419     int *pnData,
   183420     void **ppData
   183421 ){
   183422   return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
   183423 }
   183424 
   183425 /*
   183426 ** Streaming versions of changegroup_add().
   183427 */
   183428 SQLITE_API int sqlite3changegroup_add_strm(
   183429   sqlite3_changegroup *pGrp,
   183430   int (*xInput)(void *pIn, void *pData, int *pnData),
   183431   void *pIn
   183432 ){
   183433   sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
   183434   int rc;                         /* Return code */
   183435 
   183436   rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
   183437   if( rc==SQLITE_OK ){
   183438     rc = sessionChangesetToHash(pIter, pGrp);
   183439   }
   183440   sqlite3changeset_finalize(pIter);
   183441   return rc;
   183442 }
   183443 
   183444 /*
   183445 ** Streaming versions of changegroup_output().
   183446 */
   183447 SQLITE_API int sqlite3changegroup_output_strm(
   183448   sqlite3_changegroup *pGrp,
   183449   int (*xOutput)(void *pOut, const void *pData, int nData),
   183450   void *pOut
   183451 ){
   183452   return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
   183453 }
   183454 
   183455 /*
   183456 ** Delete a changegroup object.
   183457 */
   183458 SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
   183459   if( pGrp ){
   183460     sessionDeleteTable(pGrp->pList);
   183461     sqlite3_free(pGrp);
   183462   }
   183463 }
   183464 
   183465 /*
   183466 ** Combine two changesets together.
   183467 */
   183468 SQLITE_API int sqlite3changeset_concat(
   183469   int nLeft,                      /* Number of bytes in lhs input */
   183470   void *pLeft,                    /* Lhs input changeset */
   183471   int nRight                      /* Number of bytes in rhs input */,
   183472   void *pRight,                   /* Rhs input changeset */
   183473   int *pnOut,                     /* OUT: Number of bytes in output changeset */
   183474   void **ppOut                    /* OUT: changeset (left <concat> right) */
   183475 ){
   183476   sqlite3_changegroup *pGrp;
   183477   int rc;
   183478 
   183479   rc = sqlite3changegroup_new(&pGrp);
   183480   if( rc==SQLITE_OK ){
   183481     rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
   183482   }
   183483   if( rc==SQLITE_OK ){
   183484     rc = sqlite3changegroup_add(pGrp, nRight, pRight);
   183485   }
   183486   if( rc==SQLITE_OK ){
   183487     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
   183488   }
   183489   sqlite3changegroup_delete(pGrp);
   183490 
   183491   return rc;
   183492 }
   183493 
   183494 /*
   183495 ** Streaming version of sqlite3changeset_concat().
   183496 */
   183497 SQLITE_API int sqlite3changeset_concat_strm(
   183498   int (*xInputA)(void *pIn, void *pData, int *pnData),
   183499   void *pInA,
   183500   int (*xInputB)(void *pIn, void *pData, int *pnData),
   183501   void *pInB,
   183502   int (*xOutput)(void *pOut, const void *pData, int nData),
   183503   void *pOut
   183504 ){
   183505   sqlite3_changegroup *pGrp;
   183506   int rc;
   183507 
   183508   rc = sqlite3changegroup_new(&pGrp);
   183509   if( rc==SQLITE_OK ){
   183510     rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
   183511   }
   183512   if( rc==SQLITE_OK ){
   183513     rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
   183514   }
   183515   if( rc==SQLITE_OK ){
   183516     rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
   183517   }
   183518   sqlite3changegroup_delete(pGrp);
   183519 
   183520   return rc;
   183521 }
   183522 
   183523 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
   183524 
   183525 /************** End of sqlite3session.c **************************************/
   183526 /************** Begin file json1.c *******************************************/
   183527 /*
   183528 ** 2015-08-12
   183529 **
   183530 ** The author disclaims copyright to this source code.  In place of
   183531 ** a legal notice, here is a blessing:
   183532 **
   183533 **    May you do good and not evil.
   183534 **    May you find forgiveness for yourself and forgive others.
   183535 **    May you share freely, never taking more than you give.
   183536 **
   183537 ******************************************************************************
   183538 **
   183539 ** This SQLite extension implements JSON functions.  The interface is
   183540 ** modeled after MySQL JSON functions:
   183541 **
   183542 **     https://dev.mysql.com/doc/refman/5.7/en/json.html
   183543 **
   183544 ** For the time being, all JSON is stored as pure text.  (We might add
   183545 ** a JSONB type in the future which stores a binary encoding of JSON in
   183546 ** a BLOB, but there is no support for JSONB in the current implementation.
   183547 ** This implementation parses JSON text at 250 MB/s, so it is hard to see
   183548 ** how JSONB might improve on that.)
   183549 */
   183550 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
   183551 #if !defined(SQLITEINT_H)
   183552 /* #include "sqlite3ext.h" */
   183553 #endif
   183554 SQLITE_EXTENSION_INIT1
   183555 /* #include <assert.h> */
   183556 /* #include <string.h> */
   183557 /* #include <stdlib.h> */
   183558 /* #include <stdarg.h> */
   183559 
   183560 /* Mark a function parameter as unused, to suppress nuisance compiler
   183561 ** warnings. */
   183562 #ifndef UNUSED_PARAM
   183563 # define UNUSED_PARAM(X)  (void)(X)
   183564 #endif
   183565 
   183566 #ifndef LARGEST_INT64
   183567 # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
   183568 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
   183569 #endif
   183570 
   183571 /*
   183572 ** Versions of isspace(), isalnum() and isdigit() to which it is safe
   183573 ** to pass signed char values.
   183574 */
   183575 #ifdef sqlite3Isdigit
   183576    /* Use the SQLite core versions if this routine is part of the
   183577    ** SQLite amalgamation */
   183578 #  define safe_isdigit(x)  sqlite3Isdigit(x)
   183579 #  define safe_isalnum(x)  sqlite3Isalnum(x)
   183580 #  define safe_isxdigit(x) sqlite3Isxdigit(x)
   183581 #else
   183582    /* Use the standard library for separate compilation */
   183583 #include <ctype.h>  /* amalgamator: keep */
   183584 #  define safe_isdigit(x)  isdigit((unsigned char)(x))
   183585 #  define safe_isalnum(x)  isalnum((unsigned char)(x))
   183586 #  define safe_isxdigit(x) isxdigit((unsigned char)(x))
   183587 #endif
   183588 
   183589 /*
   183590 ** Growing our own isspace() routine this way is twice as fast as
   183591 ** the library isspace() function, resulting in a 7% overall performance
   183592 ** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
   183593 */
   183594 static const char jsonIsSpace[] = {
   183595   0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
   183596   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183597   1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183598   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183599   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183600   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183601   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183602   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183603   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183604   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183605   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183606   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183607   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183608   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183609   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183610   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   183611 };
   183612 #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
   183613 
   183614 #ifndef SQLITE_AMALGAMATION
   183615   /* Unsigned integer types.  These are already defined in the sqliteInt.h,
   183616   ** but the definitions need to be repeated for separate compilation. */
   183617   typedef sqlite3_uint64 u64;
   183618   typedef unsigned int u32;
   183619   typedef unsigned short int u16;
   183620   typedef unsigned char u8;
   183621 #endif
   183622 
   183623 /* Objects */
   183624 typedef struct JsonString JsonString;
   183625 typedef struct JsonNode JsonNode;
   183626 typedef struct JsonParse JsonParse;
   183627 
   183628 /* An instance of this object represents a JSON string
   183629 ** under construction.  Really, this is a generic string accumulator
   183630 ** that can be and is used to create strings other than JSON.
   183631 */
   183632 struct JsonString {
   183633   sqlite3_context *pCtx;   /* Function context - put error messages here */
   183634   char *zBuf;              /* Append JSON content here */
   183635   u64 nAlloc;              /* Bytes of storage available in zBuf[] */
   183636   u64 nUsed;               /* Bytes of zBuf[] currently used */
   183637   u8 bStatic;              /* True if zBuf is static space */
   183638   u8 bErr;                 /* True if an error has been encountered */
   183639   char zSpace[100];        /* Initial static space */
   183640 };
   183641 
   183642 /* JSON type values
   183643 */
   183644 #define JSON_NULL     0
   183645 #define JSON_TRUE     1
   183646 #define JSON_FALSE    2
   183647 #define JSON_INT      3
   183648 #define JSON_REAL     4
   183649 #define JSON_STRING   5
   183650 #define JSON_ARRAY    6
   183651 #define JSON_OBJECT   7
   183652 
   183653 /* The "subtype" set for JSON values */
   183654 #define JSON_SUBTYPE  74    /* Ascii for "J" */
   183655 
   183656 /*
   183657 ** Names of the various JSON types:
   183658 */
   183659 static const char * const jsonType[] = {
   183660   "null", "true", "false", "integer", "real", "text", "array", "object"
   183661 };
   183662 
   183663 /* Bit values for the JsonNode.jnFlag field
   183664 */
   183665 #define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
   183666 #define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
   183667 #define JNODE_REMOVE  0x04         /* Do not output */
   183668 #define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
   183669 #define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
   183670 #define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
   183671 #define JNODE_LABEL   0x40         /* Is a label of an object */
   183672 
   183673 
   183674 /* A single node of parsed JSON
   183675 */
   183676 struct JsonNode {
   183677   u8 eType;              /* One of the JSON_ type values */
   183678   u8 jnFlags;            /* JNODE flags */
   183679   u32 n;                 /* Bytes of content, or number of sub-nodes */
   183680   union {
   183681     const char *zJContent; /* Content for INT, REAL, and STRING */
   183682     u32 iAppend;           /* More terms for ARRAY and OBJECT */
   183683     u32 iKey;              /* Key for ARRAY objects in json_tree() */
   183684     u32 iReplace;          /* Replacement content for JNODE_REPLACE */
   183685     JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */
   183686   } u;
   183687 };
   183688 
   183689 /* A completely parsed JSON string
   183690 */
   183691 struct JsonParse {
   183692   u32 nNode;         /* Number of slots of aNode[] used */
   183693   u32 nAlloc;        /* Number of slots of aNode[] allocated */
   183694   JsonNode *aNode;   /* Array of nodes containing the parse */
   183695   const char *zJson; /* Original JSON string */
   183696   u32 *aUp;          /* Index of parent of each node */
   183697   u8 oom;            /* Set to true if out of memory */
   183698   u8 nErr;           /* Number of errors seen */
   183699   u16 iDepth;        /* Nesting depth */
   183700   int nJson;         /* Length of the zJson string in bytes */
   183701 };
   183702 
   183703 /*
   183704 ** Maximum nesting depth of JSON for this implementation.
   183705 **
   183706 ** This limit is needed to avoid a stack overflow in the recursive
   183707 ** descent parser.  A depth of 2000 is far deeper than any sane JSON
   183708 ** should go.
   183709 */
   183710 #define JSON_MAX_DEPTH  2000
   183711 
   183712 /**************************************************************************
   183713 ** Utility routines for dealing with JsonString objects
   183714 **************************************************************************/
   183715 
   183716 /* Set the JsonString object to an empty string
   183717 */
   183718 static void jsonZero(JsonString *p){
   183719   p->zBuf = p->zSpace;
   183720   p->nAlloc = sizeof(p->zSpace);
   183721   p->nUsed = 0;
   183722   p->bStatic = 1;
   183723 }
   183724 
   183725 /* Initialize the JsonString object
   183726 */
   183727 static void jsonInit(JsonString *p, sqlite3_context *pCtx){
   183728   p->pCtx = pCtx;
   183729   p->bErr = 0;
   183730   jsonZero(p);
   183731 }
   183732 
   183733 
   183734 /* Free all allocated memory and reset the JsonString object back to its
   183735 ** initial state.
   183736 */
   183737 static void jsonReset(JsonString *p){
   183738   if( !p->bStatic ) sqlite3_free(p->zBuf);
   183739   jsonZero(p);
   183740 }
   183741 
   183742 
   183743 /* Report an out-of-memory (OOM) condition
   183744 */
   183745 static void jsonOom(JsonString *p){
   183746   p->bErr = 1;
   183747   sqlite3_result_error_nomem(p->pCtx);
   183748   jsonReset(p);
   183749 }
   183750 
   183751 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
   183752 ** Return zero on success.  Return non-zero on an OOM error
   183753 */
   183754 static int jsonGrow(JsonString *p, u32 N){
   183755   u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
   183756   char *zNew;
   183757   if( p->bStatic ){
   183758     if( p->bErr ) return 1;
   183759     zNew = sqlite3_malloc64(nTotal);
   183760     if( zNew==0 ){
   183761       jsonOom(p);
   183762       return SQLITE_NOMEM;
   183763     }
   183764     memcpy(zNew, p->zBuf, (size_t)p->nUsed);
   183765     p->zBuf = zNew;
   183766     p->bStatic = 0;
   183767   }else{
   183768     zNew = sqlite3_realloc64(p->zBuf, nTotal);
   183769     if( zNew==0 ){
   183770       jsonOom(p);
   183771       return SQLITE_NOMEM;
   183772     }
   183773     p->zBuf = zNew;
   183774   }
   183775   p->nAlloc = nTotal;
   183776   return SQLITE_OK;
   183777 }
   183778 
   183779 /* Append N bytes from zIn onto the end of the JsonString string.
   183780 */
   183781 static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
   183782   if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
   183783   memcpy(p->zBuf+p->nUsed, zIn, N);
   183784   p->nUsed += N;
   183785 }
   183786 
   183787 /* Append formatted text (not to exceed N bytes) to the JsonString.
   183788 */
   183789 static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
   183790   va_list ap;
   183791   if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
   183792   va_start(ap, zFormat);
   183793   sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
   183794   va_end(ap);
   183795   p->nUsed += (int)strlen(p->zBuf+p->nUsed);
   183796 }
   183797 
   183798 /* Append a single character
   183799 */
   183800 static void jsonAppendChar(JsonString *p, char c){
   183801   if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
   183802   p->zBuf[p->nUsed++] = c;
   183803 }
   183804 
   183805 /* Append a comma separator to the output buffer, if the previous
   183806 ** character is not '[' or '{'.
   183807 */
   183808 static void jsonAppendSeparator(JsonString *p){
   183809   char c;
   183810   if( p->nUsed==0 ) return;
   183811   c = p->zBuf[p->nUsed-1];
   183812   if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
   183813 }
   183814 
   183815 /* Append the N-byte string in zIn to the end of the JsonString string
   183816 ** under construction.  Enclose the string in "..." and escape
   183817 ** any double-quotes or backslash characters contained within the
   183818 ** string.
   183819 */
   183820 static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
   183821   u32 i;
   183822   if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
   183823   p->zBuf[p->nUsed++] = '"';
   183824   for(i=0; i<N; i++){
   183825     unsigned char c = ((unsigned const char*)zIn)[i];
   183826     if( c=='"' || c=='\\' ){
   183827       json_simple_escape:
   183828       if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
   183829       p->zBuf[p->nUsed++] = '\\';
   183830     }else if( c<=0x1f ){
   183831       static const char aSpecial[] = {
   183832          0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
   183833          0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
   183834       };
   183835       assert( sizeof(aSpecial)==32 );
   183836       assert( aSpecial['\b']=='b' );
   183837       assert( aSpecial['\f']=='f' );
   183838       assert( aSpecial['\n']=='n' );
   183839       assert( aSpecial['\r']=='r' );
   183840       assert( aSpecial['\t']=='t' );
   183841       if( aSpecial[c] ){
   183842         c = aSpecial[c];
   183843         goto json_simple_escape;
   183844       }
   183845       if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
   183846       p->zBuf[p->nUsed++] = '\\';
   183847       p->zBuf[p->nUsed++] = 'u';
   183848       p->zBuf[p->nUsed++] = '0';
   183849       p->zBuf[p->nUsed++] = '0';
   183850       p->zBuf[p->nUsed++] = '0' + (c>>4);
   183851       c = "0123456789abcdef"[c&0xf];
   183852     }
   183853     p->zBuf[p->nUsed++] = c;
   183854   }
   183855   p->zBuf[p->nUsed++] = '"';
   183856   assert( p->nUsed<p->nAlloc );
   183857 }
   183858 
   183859 /*
   183860 ** Append a function parameter value to the JSON string under
   183861 ** construction.
   183862 */
   183863 static void jsonAppendValue(
   183864   JsonString *p,                 /* Append to this JSON string */
   183865   sqlite3_value *pValue          /* Value to append */
   183866 ){
   183867   switch( sqlite3_value_type(pValue) ){
   183868     case SQLITE_NULL: {
   183869       jsonAppendRaw(p, "null", 4);
   183870       break;
   183871     }
   183872     case SQLITE_INTEGER:
   183873     case SQLITE_FLOAT: {
   183874       const char *z = (const char*)sqlite3_value_text(pValue);
   183875       u32 n = (u32)sqlite3_value_bytes(pValue);
   183876       jsonAppendRaw(p, z, n);
   183877       break;
   183878     }
   183879     case SQLITE_TEXT: {
   183880       const char *z = (const char*)sqlite3_value_text(pValue);
   183881       u32 n = (u32)sqlite3_value_bytes(pValue);
   183882       if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
   183883         jsonAppendRaw(p, z, n);
   183884       }else{
   183885         jsonAppendString(p, z, n);
   183886       }
   183887       break;
   183888     }
   183889     default: {
   183890       if( p->bErr==0 ){
   183891         sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
   183892         p->bErr = 2;
   183893         jsonReset(p);
   183894       }
   183895       break;
   183896     }
   183897   }
   183898 }
   183899 
   183900 
   183901 /* Make the JSON in p the result of the SQL function.
   183902 */
   183903 static void jsonResult(JsonString *p){
   183904   if( p->bErr==0 ){
   183905     sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
   183906                           p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
   183907                           SQLITE_UTF8);
   183908     jsonZero(p);
   183909   }
   183910   assert( p->bStatic );
   183911 }
   183912 
   183913 /**************************************************************************
   183914 ** Utility routines for dealing with JsonNode and JsonParse objects
   183915 **************************************************************************/
   183916 
   183917 /*
   183918 ** Return the number of consecutive JsonNode slots need to represent
   183919 ** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
   183920 ** OBJECT types, the number might be larger.
   183921 **
   183922 ** Appended elements are not counted.  The value returned is the number
   183923 ** by which the JsonNode counter should increment in order to go to the
   183924 ** next peer value.
   183925 */
   183926 static u32 jsonNodeSize(JsonNode *pNode){
   183927   return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
   183928 }
   183929 
   183930 /*
   183931 ** Reclaim all memory allocated by a JsonParse object.  But do not
   183932 ** delete the JsonParse object itself.
   183933 */
   183934 static void jsonParseReset(JsonParse *pParse){
   183935   sqlite3_free(pParse->aNode);
   183936   pParse->aNode = 0;
   183937   pParse->nNode = 0;
   183938   pParse->nAlloc = 0;
   183939   sqlite3_free(pParse->aUp);
   183940   pParse->aUp = 0;
   183941 }
   183942 
   183943 /*
   183944 ** Free a JsonParse object that was obtained from sqlite3_malloc().
   183945 */
   183946 static void jsonParseFree(JsonParse *pParse){
   183947   jsonParseReset(pParse);
   183948   sqlite3_free(pParse);
   183949 }
   183950 
   183951 /*
   183952 ** Convert the JsonNode pNode into a pure JSON string and
   183953 ** append to pOut.  Subsubstructure is also included.  Return
   183954 ** the number of JsonNode objects that are encoded.
   183955 */
   183956 static void jsonRenderNode(
   183957   JsonNode *pNode,               /* The node to render */
   183958   JsonString *pOut,              /* Write JSON here */
   183959   sqlite3_value **aReplace       /* Replacement values */
   183960 ){
   183961   if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
   183962     if( pNode->jnFlags & JNODE_REPLACE ){
   183963       jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
   183964       return;
   183965     }
   183966     pNode = pNode->u.pPatch;
   183967   }
   183968   switch( pNode->eType ){
   183969     default: {
   183970       assert( pNode->eType==JSON_NULL );
   183971       jsonAppendRaw(pOut, "null", 4);
   183972       break;
   183973     }
   183974     case JSON_TRUE: {
   183975       jsonAppendRaw(pOut, "true", 4);
   183976       break;
   183977     }
   183978     case JSON_FALSE: {
   183979       jsonAppendRaw(pOut, "false", 5);
   183980       break;
   183981     }
   183982     case JSON_STRING: {
   183983       if( pNode->jnFlags & JNODE_RAW ){
   183984         jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
   183985         break;
   183986       }
   183987       /* Fall through into the next case */
   183988     }
   183989     case JSON_REAL:
   183990     case JSON_INT: {
   183991       jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
   183992       break;
   183993     }
   183994     case JSON_ARRAY: {
   183995       u32 j = 1;
   183996       jsonAppendChar(pOut, '[');
   183997       for(;;){
   183998         while( j<=pNode->n ){
   183999           if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
   184000             jsonAppendSeparator(pOut);
   184001             jsonRenderNode(&pNode[j], pOut, aReplace);
   184002           }
   184003           j += jsonNodeSize(&pNode[j]);
   184004         }
   184005         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
   184006         pNode = &pNode[pNode->u.iAppend];
   184007         j = 1;
   184008       }
   184009       jsonAppendChar(pOut, ']');
   184010       break;
   184011     }
   184012     case JSON_OBJECT: {
   184013       u32 j = 1;
   184014       jsonAppendChar(pOut, '{');
   184015       for(;;){
   184016         while( j<=pNode->n ){
   184017           if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
   184018             jsonAppendSeparator(pOut);
   184019             jsonRenderNode(&pNode[j], pOut, aReplace);
   184020             jsonAppendChar(pOut, ':');
   184021             jsonRenderNode(&pNode[j+1], pOut, aReplace);
   184022           }
   184023           j += 1 + jsonNodeSize(&pNode[j+1]);
   184024         }
   184025         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
   184026         pNode = &pNode[pNode->u.iAppend];
   184027         j = 1;
   184028       }
   184029       jsonAppendChar(pOut, '}');
   184030       break;
   184031     }
   184032   }
   184033 }
   184034 
   184035 /*
   184036 ** Return a JsonNode and all its descendents as a JSON string.
   184037 */
   184038 static void jsonReturnJson(
   184039   JsonNode *pNode,            /* Node to return */
   184040   sqlite3_context *pCtx,      /* Return value for this function */
   184041   sqlite3_value **aReplace    /* Array of replacement values */
   184042 ){
   184043   JsonString s;
   184044   jsonInit(&s, pCtx);
   184045   jsonRenderNode(pNode, &s, aReplace);
   184046   jsonResult(&s);
   184047   sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
   184048 }
   184049 
   184050 /*
   184051 ** Make the JsonNode the return value of the function.
   184052 */
   184053 static void jsonReturn(
   184054   JsonNode *pNode,            /* Node to return */
   184055   sqlite3_context *pCtx,      /* Return value for this function */
   184056   sqlite3_value **aReplace    /* Array of replacement values */
   184057 ){
   184058   switch( pNode->eType ){
   184059     default: {
   184060       assert( pNode->eType==JSON_NULL );
   184061       sqlite3_result_null(pCtx);
   184062       break;
   184063     }
   184064     case JSON_TRUE: {
   184065       sqlite3_result_int(pCtx, 1);
   184066       break;
   184067     }
   184068     case JSON_FALSE: {
   184069       sqlite3_result_int(pCtx, 0);
   184070       break;
   184071     }
   184072     case JSON_INT: {
   184073       sqlite3_int64 i = 0;
   184074       const char *z = pNode->u.zJContent;
   184075       if( z[0]=='-' ){ z++; }
   184076       while( z[0]>='0' && z[0]<='9' ){
   184077         unsigned v = *(z++) - '0';
   184078         if( i>=LARGEST_INT64/10 ){
   184079           if( i>LARGEST_INT64/10 ) goto int_as_real;
   184080           if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
   184081           if( v==9 ) goto int_as_real;
   184082           if( v==8 ){
   184083             if( pNode->u.zJContent[0]=='-' ){
   184084               sqlite3_result_int64(pCtx, SMALLEST_INT64);
   184085               goto int_done;
   184086             }else{
   184087               goto int_as_real;
   184088             }
   184089           }
   184090         }
   184091         i = i*10 + v;
   184092       }
   184093       if( pNode->u.zJContent[0]=='-' ){ i = -i; }
   184094       sqlite3_result_int64(pCtx, i);
   184095       int_done:
   184096       break;
   184097       int_as_real: /* fall through to real */;
   184098     }
   184099     case JSON_REAL: {
   184100       double r;
   184101 #ifdef SQLITE_AMALGAMATION
   184102       const char *z = pNode->u.zJContent;
   184103       sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
   184104 #else
   184105       r = strtod(pNode->u.zJContent, 0);
   184106 #endif
   184107       sqlite3_result_double(pCtx, r);
   184108       break;
   184109     }
   184110     case JSON_STRING: {
   184111 #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
   184112       ** json_insert() and json_replace() and those routines do not
   184113       ** call jsonReturn() */
   184114       if( pNode->jnFlags & JNODE_RAW ){
   184115         sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
   184116                             SQLITE_TRANSIENT);
   184117       }else
   184118 #endif
   184119       assert( (pNode->jnFlags & JNODE_RAW)==0 );
   184120       if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
   184121         /* JSON formatted without any backslash-escapes */
   184122         sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
   184123                             SQLITE_TRANSIENT);
   184124       }else{
   184125         /* Translate JSON formatted string into raw text */
   184126         u32 i;
   184127         u32 n = pNode->n;
   184128         const char *z = pNode->u.zJContent;
   184129         char *zOut;
   184130         u32 j;
   184131         zOut = sqlite3_malloc( n+1 );
   184132         if( zOut==0 ){
   184133           sqlite3_result_error_nomem(pCtx);
   184134           break;
   184135         }
   184136         for(i=1, j=0; i<n-1; i++){
   184137           char c = z[i];
   184138           if( c!='\\' ){
   184139             zOut[j++] = c;
   184140           }else{
   184141             c = z[++i];
   184142             if( c=='u' ){
   184143               u32 v = 0, k;
   184144               for(k=0; k<4; i++, k++){
   184145                 assert( i<n-2 );
   184146                 c = z[i+1];
   184147                 assert( safe_isxdigit(c) );
   184148                 if( c<='9' ) v = v*16 + c - '0';
   184149                 else if( c<='F' ) v = v*16 + c - 'A' + 10;
   184150                 else v = v*16 + c - 'a' + 10;
   184151               }
   184152               if( v==0 ) break;
   184153               if( v<=0x7f ){
   184154                 zOut[j++] = (char)v;
   184155               }else if( v<=0x7ff ){
   184156                 zOut[j++] = (char)(0xc0 | (v>>6));
   184157                 zOut[j++] = 0x80 | (v&0x3f);
   184158               }else{
   184159                 zOut[j++] = (char)(0xe0 | (v>>12));
   184160                 zOut[j++] = 0x80 | ((v>>6)&0x3f);
   184161                 zOut[j++] = 0x80 | (v&0x3f);
   184162               }
   184163             }else{
   184164               if( c=='b' ){
   184165                 c = '\b';
   184166               }else if( c=='f' ){
   184167                 c = '\f';
   184168               }else if( c=='n' ){
   184169                 c = '\n';
   184170               }else if( c=='r' ){
   184171                 c = '\r';
   184172               }else if( c=='t' ){
   184173                 c = '\t';
   184174               }
   184175               zOut[j++] = c;
   184176             }
   184177           }
   184178         }
   184179         zOut[j] = 0;
   184180         sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
   184181       }
   184182       break;
   184183     }
   184184     case JSON_ARRAY:
   184185     case JSON_OBJECT: {
   184186       jsonReturnJson(pNode, pCtx, aReplace);
   184187       break;
   184188     }
   184189   }
   184190 }
   184191 
   184192 /* Forward reference */
   184193 static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
   184194 
   184195 /*
   184196 ** A macro to hint to the compiler that a function should not be
   184197 ** inlined.
   184198 */
   184199 #if defined(__GNUC__)
   184200 #  define JSON_NOINLINE  __attribute__((noinline))
   184201 #elif defined(_MSC_VER) && _MSC_VER>=1310
   184202 #  define JSON_NOINLINE  __declspec(noinline)
   184203 #else
   184204 #  define JSON_NOINLINE
   184205 #endif
   184206 
   184207 
   184208 static JSON_NOINLINE int jsonParseAddNodeExpand(
   184209   JsonParse *pParse,        /* Append the node to this object */
   184210   u32 eType,                /* Node type */
   184211   u32 n,                    /* Content size or sub-node count */
   184212   const char *zContent      /* Content */
   184213 ){
   184214   u32 nNew;
   184215   JsonNode *pNew;
   184216   assert( pParse->nNode>=pParse->nAlloc );
   184217   if( pParse->oom ) return -1;
   184218   nNew = pParse->nAlloc*2 + 10;
   184219   pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
   184220   if( pNew==0 ){
   184221     pParse->oom = 1;
   184222     return -1;
   184223   }
   184224   pParse->nAlloc = nNew;
   184225   pParse->aNode = pNew;
   184226   assert( pParse->nNode<pParse->nAlloc );
   184227   return jsonParseAddNode(pParse, eType, n, zContent);
   184228 }
   184229 
   184230 /*
   184231 ** Create a new JsonNode instance based on the arguments and append that
   184232 ** instance to the JsonParse.  Return the index in pParse->aNode[] of the
   184233 ** new node, or -1 if a memory allocation fails.
   184234 */
   184235 static int jsonParseAddNode(
   184236   JsonParse *pParse,        /* Append the node to this object */
   184237   u32 eType,                /* Node type */
   184238   u32 n,                    /* Content size or sub-node count */
   184239   const char *zContent      /* Content */
   184240 ){
   184241   JsonNode *p;
   184242   if( pParse->nNode>=pParse->nAlloc ){
   184243     return jsonParseAddNodeExpand(pParse, eType, n, zContent);
   184244   }
   184245   p = &pParse->aNode[pParse->nNode];
   184246   p->eType = (u8)eType;
   184247   p->jnFlags = 0;
   184248   p->n = n;
   184249   p->u.zJContent = zContent;
   184250   return pParse->nNode++;
   184251 }
   184252 
   184253 /*
   184254 ** Return true if z[] begins with 4 (or more) hexadecimal digits
   184255 */
   184256 static int jsonIs4Hex(const char *z){
   184257   int i;
   184258   for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
   184259   return 1;
   184260 }
   184261 
   184262 /*
   184263 ** Parse a single JSON value which begins at pParse->zJson[i].  Return the
   184264 ** index of the first character past the end of the value parsed.
   184265 **
   184266 ** Return negative for a syntax error.  Special cases:  return -2 if the
   184267 ** first non-whitespace character is '}' and return -3 if the first
   184268 ** non-whitespace character is ']'.
   184269 */
   184270 static int jsonParseValue(JsonParse *pParse, u32 i){
   184271   char c;
   184272   u32 j;
   184273   int iThis;
   184274   int x;
   184275   JsonNode *pNode;
   184276   const char *z = pParse->zJson;
   184277   while( safe_isspace(z[i]) ){ i++; }
   184278   if( (c = z[i])=='{' ){
   184279     /* Parse object */
   184280     iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
   184281     if( iThis<0 ) return -1;
   184282     for(j=i+1;;j++){
   184283       while( safe_isspace(z[j]) ){ j++; }
   184284       if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
   184285       x = jsonParseValue(pParse, j);
   184286       if( x<0 ){
   184287         pParse->iDepth--;
   184288         if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
   184289         return -1;
   184290       }
   184291       if( pParse->oom ) return -1;
   184292       pNode = &pParse->aNode[pParse->nNode-1];
   184293       if( pNode->eType!=JSON_STRING ) return -1;
   184294       pNode->jnFlags |= JNODE_LABEL;
   184295       j = x;
   184296       while( safe_isspace(z[j]) ){ j++; }
   184297       if( z[j]!=':' ) return -1;
   184298       j++;
   184299       x = jsonParseValue(pParse, j);
   184300       pParse->iDepth--;
   184301       if( x<0 ) return -1;
   184302       j = x;
   184303       while( safe_isspace(z[j]) ){ j++; }
   184304       c = z[j];
   184305       if( c==',' ) continue;
   184306       if( c!='}' ) return -1;
   184307       break;
   184308     }
   184309     pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
   184310     return j+1;
   184311   }else if( c=='[' ){
   184312     /* Parse array */
   184313     iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
   184314     if( iThis<0 ) return -1;
   184315     for(j=i+1;;j++){
   184316       while( safe_isspace(z[j]) ){ j++; }
   184317       if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
   184318       x = jsonParseValue(pParse, j);
   184319       pParse->iDepth--;
   184320       if( x<0 ){
   184321         if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
   184322         return -1;
   184323       }
   184324       j = x;
   184325       while( safe_isspace(z[j]) ){ j++; }
   184326       c = z[j];
   184327       if( c==',' ) continue;
   184328       if( c!=']' ) return -1;
   184329       break;
   184330     }
   184331     pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
   184332     return j+1;
   184333   }else if( c=='"' ){
   184334     /* Parse string */
   184335     u8 jnFlags = 0;
   184336     j = i+1;
   184337     for(;;){
   184338       c = z[j];
   184339       if( (c & ~0x1f)==0 ){
   184340         /* Control characters are not allowed in strings */
   184341         return -1;
   184342       }
   184343       if( c=='\\' ){
   184344         c = z[++j];
   184345         if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
   184346            || c=='n' || c=='r' || c=='t'
   184347            || (c=='u' && jsonIs4Hex(z+j+1)) ){
   184348           jnFlags = JNODE_ESCAPE;
   184349         }else{
   184350           return -1;
   184351         }
   184352       }else if( c=='"' ){
   184353         break;
   184354       }
   184355       j++;
   184356     }
   184357     jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
   184358     if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
   184359     return j+1;
   184360   }else if( c=='n'
   184361          && strncmp(z+i,"null",4)==0
   184362          && !safe_isalnum(z[i+4]) ){
   184363     jsonParseAddNode(pParse, JSON_NULL, 0, 0);
   184364     return i+4;
   184365   }else if( c=='t'
   184366          && strncmp(z+i,"true",4)==0
   184367          && !safe_isalnum(z[i+4]) ){
   184368     jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
   184369     return i+4;
   184370   }else if( c=='f'
   184371          && strncmp(z+i,"false",5)==0
   184372          && !safe_isalnum(z[i+5]) ){
   184373     jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
   184374     return i+5;
   184375   }else if( c=='-' || (c>='0' && c<='9') ){
   184376     /* Parse number */
   184377     u8 seenDP = 0;
   184378     u8 seenE = 0;
   184379     assert( '-' < '0' );
   184380     if( c<='0' ){
   184381       j = c=='-' ? i+1 : i;
   184382       if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
   184383     }
   184384     j = i+1;
   184385     for(;; j++){
   184386       c = z[j];
   184387       if( c>='0' && c<='9' ) continue;
   184388       if( c=='.' ){
   184389         if( z[j-1]=='-' ) return -1;
   184390         if( seenDP ) return -1;
   184391         seenDP = 1;
   184392         continue;
   184393       }
   184394       if( c=='e' || c=='E' ){
   184395         if( z[j-1]<'0' ) return -1;
   184396         if( seenE ) return -1;
   184397         seenDP = seenE = 1;
   184398         c = z[j+1];
   184399         if( c=='+' || c=='-' ){
   184400           j++;
   184401           c = z[j+1];
   184402         }
   184403         if( c<'0' || c>'9' ) return -1;
   184404         continue;
   184405       }
   184406       break;
   184407     }
   184408     if( z[j-1]<'0' ) return -1;
   184409     jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
   184410                         j - i, &z[i]);
   184411     return j;
   184412   }else if( c=='}' ){
   184413     return -2;  /* End of {...} */
   184414   }else if( c==']' ){
   184415     return -3;  /* End of [...] */
   184416   }else if( c==0 ){
   184417     return 0;   /* End of file */
   184418   }else{
   184419     return -1;  /* Syntax error */
   184420   }
   184421 }
   184422 
   184423 /*
   184424 ** Parse a complete JSON string.  Return 0 on success or non-zero if there
   184425 ** are any errors.  If an error occurs, free all memory associated with
   184426 ** pParse.
   184427 **
   184428 ** pParse is uninitialized when this routine is called.
   184429 */
   184430 static int jsonParse(
   184431   JsonParse *pParse,           /* Initialize and fill this JsonParse object */
   184432   sqlite3_context *pCtx,       /* Report errors here */
   184433   const char *zJson            /* Input JSON text to be parsed */
   184434 ){
   184435   int i;
   184436   memset(pParse, 0, sizeof(*pParse));
   184437   if( zJson==0 ) return 1;
   184438   pParse->zJson = zJson;
   184439   i = jsonParseValue(pParse, 0);
   184440   if( pParse->oom ) i = -1;
   184441   if( i>0 ){
   184442     assert( pParse->iDepth==0 );
   184443     while( safe_isspace(zJson[i]) ) i++;
   184444     if( zJson[i] ) i = -1;
   184445   }
   184446   if( i<=0 ){
   184447     if( pCtx!=0 ){
   184448       if( pParse->oom ){
   184449         sqlite3_result_error_nomem(pCtx);
   184450       }else{
   184451         sqlite3_result_error(pCtx, "malformed JSON", -1);
   184452       }
   184453     }
   184454     jsonParseReset(pParse);
   184455     return 1;
   184456   }
   184457   return 0;
   184458 }
   184459 
   184460 /* Mark node i of pParse as being a child of iParent.  Call recursively
   184461 ** to fill in all the descendants of node i.
   184462 */
   184463 static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
   184464   JsonNode *pNode = &pParse->aNode[i];
   184465   u32 j;
   184466   pParse->aUp[i] = iParent;
   184467   switch( pNode->eType ){
   184468     case JSON_ARRAY: {
   184469       for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
   184470         jsonParseFillInParentage(pParse, i+j, i);
   184471       }
   184472       break;
   184473     }
   184474     case JSON_OBJECT: {
   184475       for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
   184476         pParse->aUp[i+j] = i;
   184477         jsonParseFillInParentage(pParse, i+j+1, i);
   184478       }
   184479       break;
   184480     }
   184481     default: {
   184482       break;
   184483     }
   184484   }
   184485 }
   184486 
   184487 /*
   184488 ** Compute the parentage of all nodes in a completed parse.
   184489 */
   184490 static int jsonParseFindParents(JsonParse *pParse){
   184491   u32 *aUp;
   184492   assert( pParse->aUp==0 );
   184493   aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
   184494   if( aUp==0 ){
   184495     pParse->oom = 1;
   184496     return SQLITE_NOMEM;
   184497   }
   184498   jsonParseFillInParentage(pParse, 0, 0);
   184499   return SQLITE_OK;
   184500 }
   184501 
   184502 /*
   184503 ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
   184504 */
   184505 #define JSON_CACHE_ID  (-429938)
   184506 
   184507 /*
   184508 ** Obtain a complete parse of the JSON found in the first argument
   184509 ** of the argv array.  Use the sqlite3_get_auxdata() cache for this
   184510 ** parse if it is available.  If the cache is not available or if it
   184511 ** is no longer valid, parse the JSON again and return the new parse,
   184512 ** and also register the new parse so that it will be available for
   184513 ** future sqlite3_get_auxdata() calls.
   184514 */
   184515 static JsonParse *jsonParseCached(
   184516   sqlite3_context *pCtx,
   184517   sqlite3_value **argv
   184518 ){
   184519   const char *zJson = (const char*)sqlite3_value_text(argv[0]);
   184520   int nJson = sqlite3_value_bytes(argv[0]);
   184521   JsonParse *p;
   184522   if( zJson==0 ) return 0;
   184523   p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
   184524   if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
   184525     p->nErr = 0;
   184526     return p; /* The cached entry matches, so return it */
   184527   }
   184528   p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
   184529   if( p==0 ){
   184530     sqlite3_result_error_nomem(pCtx);
   184531     return 0;
   184532   }
   184533   memset(p, 0, sizeof(*p));
   184534   p->zJson = (char*)&p[1];
   184535   memcpy((char*)p->zJson, zJson, nJson+1);
   184536   if( jsonParse(p, pCtx, p->zJson) ){
   184537     sqlite3_free(p);
   184538     return 0;
   184539   }
   184540   p->nJson = nJson;
   184541   sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
   184542   return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
   184543 }
   184544 
   184545 /*
   184546 ** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
   184547 ** a match.
   184548 */
   184549 static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
   184550   if( pNode->jnFlags & JNODE_RAW ){
   184551     if( pNode->n!=nKey ) return 0;
   184552     return strncmp(pNode->u.zJContent, zKey, nKey)==0;
   184553   }else{
   184554     if( pNode->n!=nKey+2 ) return 0;
   184555     return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
   184556   }
   184557 }
   184558 
   184559 /* forward declaration */
   184560 static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
   184561 
   184562 /*
   184563 ** Search along zPath to find the node specified.  Return a pointer
   184564 ** to that node, or NULL if zPath is malformed or if there is no such
   184565 ** node.
   184566 **
   184567 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
   184568 ** possible to do so and if no existing node corresponds to zPath.  If
   184569 ** new nodes are appended *pApnd is set to 1.
   184570 */
   184571 static JsonNode *jsonLookupStep(
   184572   JsonParse *pParse,      /* The JSON to search */
   184573   u32 iRoot,              /* Begin the search at this node */
   184574   const char *zPath,      /* The path to search */
   184575   int *pApnd,             /* Append nodes to complete path if not NULL */
   184576   const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
   184577 ){
   184578   u32 i, j, nKey;
   184579   const char *zKey;
   184580   JsonNode *pRoot = &pParse->aNode[iRoot];
   184581   if( zPath[0]==0 ) return pRoot;
   184582   if( zPath[0]=='.' ){
   184583     if( pRoot->eType!=JSON_OBJECT ) return 0;
   184584     zPath++;
   184585     if( zPath[0]=='"' ){
   184586       zKey = zPath + 1;
   184587       for(i=1; zPath[i] && zPath[i]!='"'; i++){}
   184588       nKey = i-1;
   184589       if( zPath[i] ){
   184590         i++;
   184591       }else{
   184592         *pzErr = zPath;
   184593         return 0;
   184594       }
   184595     }else{
   184596       zKey = zPath;
   184597       for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
   184598       nKey = i;
   184599     }
   184600     if( nKey==0 ){
   184601       *pzErr = zPath;
   184602       return 0;
   184603     }
   184604     j = 1;
   184605     for(;;){
   184606       while( j<=pRoot->n ){
   184607         if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
   184608           return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
   184609         }
   184610         j++;
   184611         j += jsonNodeSize(&pRoot[j]);
   184612       }
   184613       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
   184614       iRoot += pRoot->u.iAppend;
   184615       pRoot = &pParse->aNode[iRoot];
   184616       j = 1;
   184617     }
   184618     if( pApnd ){
   184619       u32 iStart, iLabel;
   184620       JsonNode *pNode;
   184621       iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
   184622       iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
   184623       zPath += i;
   184624       pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
   184625       if( pParse->oom ) return 0;
   184626       if( pNode ){
   184627         pRoot = &pParse->aNode[iRoot];
   184628         pRoot->u.iAppend = iStart - iRoot;
   184629         pRoot->jnFlags |= JNODE_APPEND;
   184630         pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
   184631       }
   184632       return pNode;
   184633     }
   184634   }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
   184635     if( pRoot->eType!=JSON_ARRAY ) return 0;
   184636     i = 0;
   184637     j = 1;
   184638     while( safe_isdigit(zPath[j]) ){
   184639       i = i*10 + zPath[j] - '0';
   184640       j++;
   184641     }
   184642     if( zPath[j]!=']' ){
   184643       *pzErr = zPath;
   184644       return 0;
   184645     }
   184646     zPath += j + 1;
   184647     j = 1;
   184648     for(;;){
   184649       while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
   184650         if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
   184651         j += jsonNodeSize(&pRoot[j]);
   184652       }
   184653       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
   184654       iRoot += pRoot->u.iAppend;
   184655       pRoot = &pParse->aNode[iRoot];
   184656       j = 1;
   184657     }
   184658     if( j<=pRoot->n ){
   184659       return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
   184660     }
   184661     if( i==0 && pApnd ){
   184662       u32 iStart;
   184663       JsonNode *pNode;
   184664       iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
   184665       pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
   184666       if( pParse->oom ) return 0;
   184667       if( pNode ){
   184668         pRoot = &pParse->aNode[iRoot];
   184669         pRoot->u.iAppend = iStart - iRoot;
   184670         pRoot->jnFlags |= JNODE_APPEND;
   184671       }
   184672       return pNode;
   184673     }
   184674   }else{
   184675     *pzErr = zPath;
   184676   }
   184677   return 0;
   184678 }
   184679 
   184680 /*
   184681 ** Append content to pParse that will complete zPath.  Return a pointer
   184682 ** to the inserted node, or return NULL if the append fails.
   184683 */
   184684 static JsonNode *jsonLookupAppend(
   184685   JsonParse *pParse,     /* Append content to the JSON parse */
   184686   const char *zPath,     /* Description of content to append */
   184687   int *pApnd,            /* Set this flag to 1 */
   184688   const char **pzErr     /* Make this point to any syntax error */
   184689 ){
   184690   *pApnd = 1;
   184691   if( zPath[0]==0 ){
   184692     jsonParseAddNode(pParse, JSON_NULL, 0, 0);
   184693     return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
   184694   }
   184695   if( zPath[0]=='.' ){
   184696     jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
   184697   }else if( strncmp(zPath,"[0]",3)==0 ){
   184698     jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
   184699   }else{
   184700     return 0;
   184701   }
   184702   if( pParse->oom ) return 0;
   184703   return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
   184704 }
   184705 
   184706 /*
   184707 ** Return the text of a syntax error message on a JSON path.  Space is
   184708 ** obtained from sqlite3_malloc().
   184709 */
   184710 static char *jsonPathSyntaxError(const char *zErr){
   184711   return sqlite3_mprintf("JSON path error near '%q'", zErr);
   184712 }
   184713 
   184714 /*
   184715 ** Do a node lookup using zPath.  Return a pointer to the node on success.
   184716 ** Return NULL if not found or if there is an error.
   184717 **
   184718 ** On an error, write an error message into pCtx and increment the
   184719 ** pParse->nErr counter.
   184720 **
   184721 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
   184722 ** nodes are appended.
   184723 */
   184724 static JsonNode *jsonLookup(
   184725   JsonParse *pParse,      /* The JSON to search */
   184726   const char *zPath,      /* The path to search */
   184727   int *pApnd,             /* Append nodes to complete path if not NULL */
   184728   sqlite3_context *pCtx   /* Report errors here, if not NULL */
   184729 ){
   184730   const char *zErr = 0;
   184731   JsonNode *pNode = 0;
   184732   char *zMsg;
   184733 
   184734   if( zPath==0 ) return 0;
   184735   if( zPath[0]!='$' ){
   184736     zErr = zPath;
   184737     goto lookup_err;
   184738   }
   184739   zPath++;
   184740   pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
   184741   if( zErr==0 ) return pNode;
   184742 
   184743 lookup_err:
   184744   pParse->nErr++;
   184745   assert( zErr!=0 && pCtx!=0 );
   184746   zMsg = jsonPathSyntaxError(zErr);
   184747   if( zMsg ){
   184748     sqlite3_result_error(pCtx, zMsg, -1);
   184749     sqlite3_free(zMsg);
   184750   }else{
   184751     sqlite3_result_error_nomem(pCtx);
   184752   }
   184753   return 0;
   184754 }
   184755 
   184756 
   184757 /*
   184758 ** Report the wrong number of arguments for json_insert(), json_replace()
   184759 ** or json_set().
   184760 */
   184761 static void jsonWrongNumArgs(
   184762   sqlite3_context *pCtx,
   184763   const char *zFuncName
   184764 ){
   184765   char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
   184766                                zFuncName);
   184767   sqlite3_result_error(pCtx, zMsg, -1);
   184768   sqlite3_free(zMsg);
   184769 }
   184770 
   184771 /*
   184772 ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
   184773 */
   184774 static void jsonRemoveAllNulls(JsonNode *pNode){
   184775   int i, n;
   184776   assert( pNode->eType==JSON_OBJECT );
   184777   n = pNode->n;
   184778   for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
   184779     switch( pNode[i].eType ){
   184780       case JSON_NULL:
   184781         pNode[i].jnFlags |= JNODE_REMOVE;
   184782         break;
   184783       case JSON_OBJECT:
   184784         jsonRemoveAllNulls(&pNode[i]);
   184785         break;
   184786     }
   184787   }
   184788 }
   184789 
   184790 
   184791 /****************************************************************************
   184792 ** SQL functions used for testing and debugging
   184793 ****************************************************************************/
   184794 
   184795 #ifdef SQLITE_DEBUG
   184796 /*
   184797 ** The json_parse(JSON) function returns a string which describes
   184798 ** a parse of the JSON provided.  Or it returns NULL if JSON is not
   184799 ** well-formed.
   184800 */
   184801 static void jsonParseFunc(
   184802   sqlite3_context *ctx,
   184803   int argc,
   184804   sqlite3_value **argv
   184805 ){
   184806   JsonString s;       /* Output string - not real JSON */
   184807   JsonParse x;        /* The parse */
   184808   u32 i;
   184809 
   184810   assert( argc==1 );
   184811   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
   184812   jsonParseFindParents(&x);
   184813   jsonInit(&s, ctx);
   184814   for(i=0; i<x.nNode; i++){
   184815     const char *zType;
   184816     if( x.aNode[i].jnFlags & JNODE_LABEL ){
   184817       assert( x.aNode[i].eType==JSON_STRING );
   184818       zType = "label";
   184819     }else{
   184820       zType = jsonType[x.aNode[i].eType];
   184821     }
   184822     jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
   184823                i, zType, x.aNode[i].n, x.aUp[i]);
   184824     if( x.aNode[i].u.zJContent!=0 ){
   184825       jsonAppendRaw(&s, " ", 1);
   184826       jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
   184827     }
   184828     jsonAppendRaw(&s, "\n", 1);
   184829   }
   184830   jsonParseReset(&x);
   184831   jsonResult(&s);
   184832 }
   184833 
   184834 /*
   184835 ** The json_test1(JSON) function return true (1) if the input is JSON
   184836 ** text generated by another json function.  It returns (0) if the input
   184837 ** is not known to be JSON.
   184838 */
   184839 static void jsonTest1Func(
   184840   sqlite3_context *ctx,
   184841   int argc,
   184842   sqlite3_value **argv
   184843 ){
   184844   UNUSED_PARAM(argc);
   184845   sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
   184846 }
   184847 #endif /* SQLITE_DEBUG */
   184848 
   184849 /****************************************************************************
   184850 ** Scalar SQL function implementations
   184851 ****************************************************************************/
   184852 
   184853 /*
   184854 ** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
   184855 ** corresponding to the SQL value input.  Mostly this means putting
   184856 ** double-quotes around strings and returning the unquoted string "null"
   184857 ** when given a NULL input.
   184858 */
   184859 static void jsonQuoteFunc(
   184860   sqlite3_context *ctx,
   184861   int argc,
   184862   sqlite3_value **argv
   184863 ){
   184864   JsonString jx;
   184865   UNUSED_PARAM(argc);
   184866 
   184867   jsonInit(&jx, ctx);
   184868   jsonAppendValue(&jx, argv[0]);
   184869   jsonResult(&jx);
   184870   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
   184871 }
   184872 
   184873 /*
   184874 ** Implementation of the json_array(VALUE,...) function.  Return a JSON
   184875 ** array that contains all values given in arguments.  Or if any argument
   184876 ** is a BLOB, throw an error.
   184877 */
   184878 static void jsonArrayFunc(
   184879   sqlite3_context *ctx,
   184880   int argc,
   184881   sqlite3_value **argv
   184882 ){
   184883   int i;
   184884   JsonString jx;
   184885 
   184886   jsonInit(&jx, ctx);
   184887   jsonAppendChar(&jx, '[');
   184888   for(i=0; i<argc; i++){
   184889     jsonAppendSeparator(&jx);
   184890     jsonAppendValue(&jx, argv[i]);
   184891   }
   184892   jsonAppendChar(&jx, ']');
   184893   jsonResult(&jx);
   184894   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
   184895 }
   184896 
   184897 
   184898 /*
   184899 ** json_array_length(JSON)
   184900 ** json_array_length(JSON, PATH)
   184901 **
   184902 ** Return the number of elements in the top-level JSON array.
   184903 ** Return 0 if the input is not a well-formed JSON array.
   184904 */
   184905 static void jsonArrayLengthFunc(
   184906   sqlite3_context *ctx,
   184907   int argc,
   184908   sqlite3_value **argv
   184909 ){
   184910   JsonParse *p;          /* The parse */
   184911   sqlite3_int64 n = 0;
   184912   u32 i;
   184913   JsonNode *pNode;
   184914 
   184915   p = jsonParseCached(ctx, argv);
   184916   if( p==0 ) return;
   184917   assert( p->nNode );
   184918   if( argc==2 ){
   184919     const char *zPath = (const char*)sqlite3_value_text(argv[1]);
   184920     pNode = jsonLookup(p, zPath, 0, ctx);
   184921   }else{
   184922     pNode = p->aNode;
   184923   }
   184924   if( pNode==0 ){
   184925     return;
   184926   }
   184927   if( pNode->eType==JSON_ARRAY ){
   184928     assert( (pNode->jnFlags & JNODE_APPEND)==0 );
   184929     for(i=1; i<=pNode->n; n++){
   184930       i += jsonNodeSize(&pNode[i]);
   184931     }
   184932   }
   184933   sqlite3_result_int64(ctx, n);
   184934 }
   184935 
   184936 /*
   184937 ** json_extract(JSON, PATH, ...)
   184938 **
   184939 ** Return the element described by PATH.  Return NULL if there is no
   184940 ** PATH element.  If there are multiple PATHs, then return a JSON array
   184941 ** with the result from each path.  Throw an error if the JSON or any PATH
   184942 ** is malformed.
   184943 */
   184944 static void jsonExtractFunc(
   184945   sqlite3_context *ctx,
   184946   int argc,
   184947   sqlite3_value **argv
   184948 ){
   184949   JsonParse *p;          /* The parse */
   184950   JsonNode *pNode;
   184951   const char *zPath;
   184952   JsonString jx;
   184953   int i;
   184954 
   184955   if( argc<2 ) return;
   184956   p = jsonParseCached(ctx, argv);
   184957   if( p==0 ) return;
   184958   jsonInit(&jx, ctx);
   184959   jsonAppendChar(&jx, '[');
   184960   for(i=1; i<argc; i++){
   184961     zPath = (const char*)sqlite3_value_text(argv[i]);
   184962     pNode = jsonLookup(p, zPath, 0, ctx);
   184963     if( p->nErr ) break;
   184964     if( argc>2 ){
   184965       jsonAppendSeparator(&jx);
   184966       if( pNode ){
   184967         jsonRenderNode(pNode, &jx, 0);
   184968       }else{
   184969         jsonAppendRaw(&jx, "null", 4);
   184970       }
   184971     }else if( pNode ){
   184972       jsonReturn(pNode, ctx, 0);
   184973     }
   184974   }
   184975   if( argc>2 && i==argc ){
   184976     jsonAppendChar(&jx, ']');
   184977     jsonResult(&jx);
   184978     sqlite3_result_subtype(ctx, JSON_SUBTYPE);
   184979   }
   184980   jsonReset(&jx);
   184981 }
   184982 
   184983 /* This is the RFC 7396 MergePatch algorithm.
   184984 */
   184985 static JsonNode *jsonMergePatch(
   184986   JsonParse *pParse,   /* The JSON parser that contains the TARGET */
   184987   u32 iTarget,         /* Node of the TARGET in pParse */
   184988   JsonNode *pPatch     /* The PATCH */
   184989 ){
   184990   u32 i, j;
   184991   u32 iRoot;
   184992   JsonNode *pTarget;
   184993   if( pPatch->eType!=JSON_OBJECT ){
   184994     return pPatch;
   184995   }
   184996   assert( iTarget>=0 && iTarget<pParse->nNode );
   184997   pTarget = &pParse->aNode[iTarget];
   184998   assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
   184999   if( pTarget->eType!=JSON_OBJECT ){
   185000     jsonRemoveAllNulls(pPatch);
   185001     return pPatch;
   185002   }
   185003   iRoot = iTarget;
   185004   for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
   185005     u32 nKey;
   185006     const char *zKey;
   185007     assert( pPatch[i].eType==JSON_STRING );
   185008     assert( pPatch[i].jnFlags & JNODE_LABEL );
   185009     nKey = pPatch[i].n;
   185010     zKey = pPatch[i].u.zJContent;
   185011     assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
   185012     for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
   185013       assert( pTarget[j].eType==JSON_STRING );
   185014       assert( pTarget[j].jnFlags & JNODE_LABEL );
   185015       assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
   185016       if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
   185017         if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
   185018         if( pPatch[i+1].eType==JSON_NULL ){
   185019           pTarget[j+1].jnFlags |= JNODE_REMOVE;
   185020         }else{
   185021           JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
   185022           if( pNew==0 ) return 0;
   185023           pTarget = &pParse->aNode[iTarget];
   185024           if( pNew!=&pTarget[j+1] ){
   185025             pTarget[j+1].u.pPatch = pNew;
   185026             pTarget[j+1].jnFlags |= JNODE_PATCH;
   185027           }
   185028         }
   185029         break;
   185030       }
   185031     }
   185032     if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
   185033       int iStart, iPatch;
   185034       iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
   185035       jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
   185036       iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
   185037       if( pParse->oom ) return 0;
   185038       jsonRemoveAllNulls(pPatch);
   185039       pTarget = &pParse->aNode[iTarget];
   185040       pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
   185041       pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
   185042       iRoot = iStart;
   185043       pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
   185044       pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
   185045     }
   185046   }
   185047   return pTarget;
   185048 }
   185049 
   185050 /*
   185051 ** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
   185052 ** object that is the result of running the RFC 7396 MergePatch() algorithm
   185053 ** on the two arguments.
   185054 */
   185055 static void jsonPatchFunc(
   185056   sqlite3_context *ctx,
   185057   int argc,
   185058   sqlite3_value **argv
   185059 ){
   185060   JsonParse x;     /* The JSON that is being patched */
   185061   JsonParse y;     /* The patch */
   185062   JsonNode *pResult;   /* The result of the merge */
   185063 
   185064   UNUSED_PARAM(argc);
   185065   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
   185066   if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
   185067     jsonParseReset(&x);
   185068     return;
   185069   }
   185070   pResult = jsonMergePatch(&x, 0, y.aNode);
   185071   assert( pResult!=0 || x.oom );
   185072   if( pResult ){
   185073     jsonReturnJson(pResult, ctx, 0);
   185074   }else{
   185075     sqlite3_result_error_nomem(ctx);
   185076   }
   185077   jsonParseReset(&x);
   185078   jsonParseReset(&y);
   185079 }
   185080 
   185081 
   185082 /*
   185083 ** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
   185084 ** object that contains all name/value given in arguments.  Or if any name
   185085 ** is not a string or if any value is a BLOB, throw an error.
   185086 */
   185087 static void jsonObjectFunc(
   185088   sqlite3_context *ctx,
   185089   int argc,
   185090   sqlite3_value **argv
   185091 ){
   185092   int i;
   185093   JsonString jx;
   185094   const char *z;
   185095   u32 n;
   185096 
   185097   if( argc&1 ){
   185098     sqlite3_result_error(ctx, "json_object() requires an even number "
   185099                                   "of arguments", -1);
   185100     return;
   185101   }
   185102   jsonInit(&jx, ctx);
   185103   jsonAppendChar(&jx, '{');
   185104   for(i=0; i<argc; i+=2){
   185105     if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
   185106       sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
   185107       jsonReset(&jx);
   185108       return;
   185109     }
   185110     jsonAppendSeparator(&jx);
   185111     z = (const char*)sqlite3_value_text(argv[i]);
   185112     n = (u32)sqlite3_value_bytes(argv[i]);
   185113     jsonAppendString(&jx, z, n);
   185114     jsonAppendChar(&jx, ':');
   185115     jsonAppendValue(&jx, argv[i+1]);
   185116   }
   185117   jsonAppendChar(&jx, '}');
   185118   jsonResult(&jx);
   185119   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
   185120 }
   185121 
   185122 
   185123 /*
   185124 ** json_remove(JSON, PATH, ...)
   185125 **
   185126 ** Remove the named elements from JSON and return the result.  malformed
   185127 ** JSON or PATH arguments result in an error.
   185128 */
   185129 static void jsonRemoveFunc(
   185130   sqlite3_context *ctx,
   185131   int argc,
   185132   sqlite3_value **argv
   185133 ){
   185134   JsonParse x;          /* The parse */
   185135   JsonNode *pNode;
   185136   const char *zPath;
   185137   u32 i;
   185138 
   185139   if( argc<1 ) return;
   185140   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
   185141   assert( x.nNode );
   185142   for(i=1; i<(u32)argc; i++){
   185143     zPath = (const char*)sqlite3_value_text(argv[i]);
   185144     if( zPath==0 ) goto remove_done;
   185145     pNode = jsonLookup(&x, zPath, 0, ctx);
   185146     if( x.nErr ) goto remove_done;
   185147     if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
   185148   }
   185149   if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
   185150     jsonReturnJson(x.aNode, ctx, 0);
   185151   }
   185152 remove_done:
   185153   jsonParseReset(&x);
   185154 }
   185155 
   185156 /*
   185157 ** json_replace(JSON, PATH, VALUE, ...)
   185158 **
   185159 ** Replace the value at PATH with VALUE.  If PATH does not already exist,
   185160 ** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
   185161 */
   185162 static void jsonReplaceFunc(
   185163   sqlite3_context *ctx,
   185164   int argc,
   185165   sqlite3_value **argv
   185166 ){
   185167   JsonParse x;          /* The parse */
   185168   JsonNode *pNode;
   185169   const char *zPath;
   185170   u32 i;
   185171 
   185172   if( argc<1 ) return;
   185173   if( (argc&1)==0 ) {
   185174     jsonWrongNumArgs(ctx, "replace");
   185175     return;
   185176   }
   185177   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
   185178   assert( x.nNode );
   185179   for(i=1; i<(u32)argc; i+=2){
   185180     zPath = (const char*)sqlite3_value_text(argv[i]);
   185181     pNode = jsonLookup(&x, zPath, 0, ctx);
   185182     if( x.nErr ) goto replace_err;
   185183     if( pNode ){
   185184       pNode->jnFlags |= (u8)JNODE_REPLACE;
   185185       pNode->u.iReplace = i + 1;
   185186     }
   185187   }
   185188   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
   185189     sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
   185190   }else{
   185191     jsonReturnJson(x.aNode, ctx, argv);
   185192   }
   185193 replace_err:
   185194   jsonParseReset(&x);
   185195 }
   185196 
   185197 /*
   185198 ** json_set(JSON, PATH, VALUE, ...)
   185199 **
   185200 ** Set the value at PATH to VALUE.  Create the PATH if it does not already
   185201 ** exist.  Overwrite existing values that do exist.
   185202 ** If JSON or PATH is malformed, throw an error.
   185203 **
   185204 ** json_insert(JSON, PATH, VALUE, ...)
   185205 **
   185206 ** Create PATH and initialize it to VALUE.  If PATH already exists, this
   185207 ** routine is a no-op.  If JSON or PATH is malformed, throw an error.
   185208 */
   185209 static void jsonSetFunc(
   185210   sqlite3_context *ctx,
   185211   int argc,
   185212   sqlite3_value **argv
   185213 ){
   185214   JsonParse x;          /* The parse */
   185215   JsonNode *pNode;
   185216   const char *zPath;
   185217   u32 i;
   185218   int bApnd;
   185219   int bIsSet = *(int*)sqlite3_user_data(ctx);
   185220 
   185221   if( argc<1 ) return;
   185222   if( (argc&1)==0 ) {
   185223     jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
   185224     return;
   185225   }
   185226   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
   185227   assert( x.nNode );
   185228   for(i=1; i<(u32)argc; i+=2){
   185229     zPath = (const char*)sqlite3_value_text(argv[i]);
   185230     bApnd = 0;
   185231     pNode = jsonLookup(&x, zPath, &bApnd, ctx);
   185232     if( x.oom ){
   185233       sqlite3_result_error_nomem(ctx);
   185234       goto jsonSetDone;
   185235     }else if( x.nErr ){
   185236       goto jsonSetDone;
   185237     }else if( pNode && (bApnd || bIsSet) ){
   185238       pNode->jnFlags |= (u8)JNODE_REPLACE;
   185239       pNode->u.iReplace = i + 1;
   185240     }
   185241   }
   185242   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
   185243     sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
   185244   }else{
   185245     jsonReturnJson(x.aNode, ctx, argv);
   185246   }
   185247 jsonSetDone:
   185248   jsonParseReset(&x);
   185249 }
   185250 
   185251 /*
   185252 ** json_type(JSON)
   185253 ** json_type(JSON, PATH)
   185254 **
   185255 ** Return the top-level "type" of a JSON string.  Throw an error if
   185256 ** either the JSON or PATH inputs are not well-formed.
   185257 */
   185258 static void jsonTypeFunc(
   185259   sqlite3_context *ctx,
   185260   int argc,
   185261   sqlite3_value **argv
   185262 ){
   185263   JsonParse x;          /* The parse */
   185264   const char *zPath;
   185265   JsonNode *pNode;
   185266 
   185267   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
   185268   assert( x.nNode );
   185269   if( argc==2 ){
   185270     zPath = (const char*)sqlite3_value_text(argv[1]);
   185271     pNode = jsonLookup(&x, zPath, 0, ctx);
   185272   }else{
   185273     pNode = x.aNode;
   185274   }
   185275   if( pNode ){
   185276     sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
   185277   }
   185278   jsonParseReset(&x);
   185279 }
   185280 
   185281 /*
   185282 ** json_valid(JSON)
   185283 **
   185284 ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
   185285 ** Return 0 otherwise.
   185286 */
   185287 static void jsonValidFunc(
   185288   sqlite3_context *ctx,
   185289   int argc,
   185290   sqlite3_value **argv
   185291 ){
   185292   JsonParse x;          /* The parse */
   185293   int rc = 0;
   185294 
   185295   UNUSED_PARAM(argc);
   185296   if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
   185297     rc = 1;
   185298   }
   185299   jsonParseReset(&x);
   185300   sqlite3_result_int(ctx, rc);
   185301 }
   185302 
   185303 
   185304 /****************************************************************************
   185305 ** Aggregate SQL function implementations
   185306 ****************************************************************************/
   185307 /*
   185308 ** json_group_array(VALUE)
   185309 **
   185310 ** Return a JSON array composed of all values in the aggregate.
   185311 */
   185312 static void jsonArrayStep(
   185313   sqlite3_context *ctx,
   185314   int argc,
   185315   sqlite3_value **argv
   185316 ){
   185317   JsonString *pStr;
   185318   UNUSED_PARAM(argc);
   185319   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
   185320   if( pStr ){
   185321     if( pStr->zBuf==0 ){
   185322       jsonInit(pStr, ctx);
   185323       jsonAppendChar(pStr, '[');
   185324     }else{
   185325       jsonAppendChar(pStr, ',');
   185326       pStr->pCtx = ctx;
   185327     }
   185328     jsonAppendValue(pStr, argv[0]);
   185329   }
   185330 }
   185331 static void jsonArrayFinal(sqlite3_context *ctx){
   185332   JsonString *pStr;
   185333   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
   185334   if( pStr ){
   185335     pStr->pCtx = ctx;
   185336     jsonAppendChar(pStr, ']');
   185337     if( pStr->bErr ){
   185338       if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
   185339       assert( pStr->bStatic );
   185340     }else{
   185341       sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
   185342                           pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
   185343       pStr->bStatic = 1;
   185344     }
   185345   }else{
   185346     sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
   185347   }
   185348   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
   185349 }
   185350 
   185351 /*
   185352 ** json_group_obj(NAME,VALUE)
   185353 **
   185354 ** Return a JSON object composed of all names and values in the aggregate.
   185355 */
   185356 static void jsonObjectStep(
   185357   sqlite3_context *ctx,
   185358   int argc,
   185359   sqlite3_value **argv
   185360 ){
   185361   JsonString *pStr;
   185362   const char *z;
   185363   u32 n;
   185364   UNUSED_PARAM(argc);
   185365   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
   185366   if( pStr ){
   185367     if( pStr->zBuf==0 ){
   185368       jsonInit(pStr, ctx);
   185369       jsonAppendChar(pStr, '{');
   185370     }else{
   185371       jsonAppendChar(pStr, ',');
   185372       pStr->pCtx = ctx;
   185373     }
   185374     z = (const char*)sqlite3_value_text(argv[0]);
   185375     n = (u32)sqlite3_value_bytes(argv[0]);
   185376     jsonAppendString(pStr, z, n);
   185377     jsonAppendChar(pStr, ':');
   185378     jsonAppendValue(pStr, argv[1]);
   185379   }
   185380 }
   185381 static void jsonObjectFinal(sqlite3_context *ctx){
   185382   JsonString *pStr;
   185383   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
   185384   if( pStr ){
   185385     jsonAppendChar(pStr, '}');
   185386     if( pStr->bErr ){
   185387       if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
   185388       assert( pStr->bStatic );
   185389     }else{
   185390       sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
   185391                           pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
   185392       pStr->bStatic = 1;
   185393     }
   185394   }else{
   185395     sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
   185396   }
   185397   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
   185398 }
   185399 
   185400 
   185401 #ifndef SQLITE_OMIT_VIRTUALTABLE
   185402 /****************************************************************************
   185403 ** The json_each virtual table
   185404 ****************************************************************************/
   185405 typedef struct JsonEachCursor JsonEachCursor;
   185406 struct JsonEachCursor {
   185407   sqlite3_vtab_cursor base;  /* Base class - must be first */
   185408   u32 iRowid;                /* The rowid */
   185409   u32 iBegin;                /* The first node of the scan */
   185410   u32 i;                     /* Index in sParse.aNode[] of current row */
   185411   u32 iEnd;                  /* EOF when i equals or exceeds this value */
   185412   u8 eType;                  /* Type of top-level element */
   185413   u8 bRecursive;             /* True for json_tree().  False for json_each() */
   185414   char *zJson;               /* Input JSON */
   185415   char *zRoot;               /* Path by which to filter zJson */
   185416   JsonParse sParse;          /* Parse of the input JSON */
   185417 };
   185418 
   185419 /* Constructor for the json_each virtual table */
   185420 static int jsonEachConnect(
   185421   sqlite3 *db,
   185422   void *pAux,
   185423   int argc, const char *const*argv,
   185424   sqlite3_vtab **ppVtab,
   185425   char **pzErr
   185426 ){
   185427   sqlite3_vtab *pNew;
   185428   int rc;
   185429 
   185430 /* Column numbers */
   185431 #define JEACH_KEY     0
   185432 #define JEACH_VALUE   1
   185433 #define JEACH_TYPE    2
   185434 #define JEACH_ATOM    3
   185435 #define JEACH_ID      4
   185436 #define JEACH_PARENT  5
   185437 #define JEACH_FULLKEY 6
   185438 #define JEACH_PATH    7
   185439 #define JEACH_JSON    8
   185440 #define JEACH_ROOT    9
   185441 
   185442   UNUSED_PARAM(pzErr);
   185443   UNUSED_PARAM(argv);
   185444   UNUSED_PARAM(argc);
   185445   UNUSED_PARAM(pAux);
   185446   rc = sqlite3_declare_vtab(db,
   185447      "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
   185448                     "json HIDDEN,root HIDDEN)");
   185449   if( rc==SQLITE_OK ){
   185450     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
   185451     if( pNew==0 ) return SQLITE_NOMEM;
   185452     memset(pNew, 0, sizeof(*pNew));
   185453   }
   185454   return rc;
   185455 }
   185456 
   185457 /* destructor for json_each virtual table */
   185458 static int jsonEachDisconnect(sqlite3_vtab *pVtab){
   185459   sqlite3_free(pVtab);
   185460   return SQLITE_OK;
   185461 }
   185462 
   185463 /* constructor for a JsonEachCursor object for json_each(). */
   185464 static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   185465   JsonEachCursor *pCur;
   185466 
   185467   UNUSED_PARAM(p);
   185468   pCur = sqlite3_malloc( sizeof(*pCur) );
   185469   if( pCur==0 ) return SQLITE_NOMEM;
   185470   memset(pCur, 0, sizeof(*pCur));
   185471   *ppCursor = &pCur->base;
   185472   return SQLITE_OK;
   185473 }
   185474 
   185475 /* constructor for a JsonEachCursor object for json_tree(). */
   185476 static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   185477   int rc = jsonEachOpenEach(p, ppCursor);
   185478   if( rc==SQLITE_OK ){
   185479     JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
   185480     pCur->bRecursive = 1;
   185481   }
   185482   return rc;
   185483 }
   185484 
   185485 /* Reset a JsonEachCursor back to its original state.  Free any memory
   185486 ** held. */
   185487 static void jsonEachCursorReset(JsonEachCursor *p){
   185488   sqlite3_free(p->zJson);
   185489   sqlite3_free(p->zRoot);
   185490   jsonParseReset(&p->sParse);
   185491   p->iRowid = 0;
   185492   p->i = 0;
   185493   p->iEnd = 0;
   185494   p->eType = 0;
   185495   p->zJson = 0;
   185496   p->zRoot = 0;
   185497 }
   185498 
   185499 /* Destructor for a jsonEachCursor object */
   185500 static int jsonEachClose(sqlite3_vtab_cursor *cur){
   185501   JsonEachCursor *p = (JsonEachCursor*)cur;
   185502   jsonEachCursorReset(p);
   185503   sqlite3_free(cur);
   185504   return SQLITE_OK;
   185505 }
   185506 
   185507 /* Return TRUE if the jsonEachCursor object has been advanced off the end
   185508 ** of the JSON object */
   185509 static int jsonEachEof(sqlite3_vtab_cursor *cur){
   185510   JsonEachCursor *p = (JsonEachCursor*)cur;
   185511   return p->i >= p->iEnd;
   185512 }
   185513 
   185514 /* Advance the cursor to the next element for json_tree() */
   185515 static int jsonEachNext(sqlite3_vtab_cursor *cur){
   185516   JsonEachCursor *p = (JsonEachCursor*)cur;
   185517   if( p->bRecursive ){
   185518     if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
   185519     p->i++;
   185520     p->iRowid++;
   185521     if( p->i<p->iEnd ){
   185522       u32 iUp = p->sParse.aUp[p->i];
   185523       JsonNode *pUp = &p->sParse.aNode[iUp];
   185524       p->eType = pUp->eType;
   185525       if( pUp->eType==JSON_ARRAY ){
   185526         if( iUp==p->i-1 ){
   185527           pUp->u.iKey = 0;
   185528         }else{
   185529           pUp->u.iKey++;
   185530         }
   185531       }
   185532     }
   185533   }else{
   185534     switch( p->eType ){
   185535       case JSON_ARRAY: {
   185536         p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
   185537         p->iRowid++;
   185538         break;
   185539       }
   185540       case JSON_OBJECT: {
   185541         p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
   185542         p->iRowid++;
   185543         break;
   185544       }
   185545       default: {
   185546         p->i = p->iEnd;
   185547         break;
   185548       }
   185549     }
   185550   }
   185551   return SQLITE_OK;
   185552 }
   185553 
   185554 /* Append the name of the path for element i to pStr
   185555 */
   185556 static void jsonEachComputePath(
   185557   JsonEachCursor *p,       /* The cursor */
   185558   JsonString *pStr,        /* Write the path here */
   185559   u32 i                    /* Path to this element */
   185560 ){
   185561   JsonNode *pNode, *pUp;
   185562   u32 iUp;
   185563   if( i==0 ){
   185564     jsonAppendChar(pStr, '$');
   185565     return;
   185566   }
   185567   iUp = p->sParse.aUp[i];
   185568   jsonEachComputePath(p, pStr, iUp);
   185569   pNode = &p->sParse.aNode[i];
   185570   pUp = &p->sParse.aNode[iUp];
   185571   if( pUp->eType==JSON_ARRAY ){
   185572     jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
   185573   }else{
   185574     assert( pUp->eType==JSON_OBJECT );
   185575     if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
   185576     assert( pNode->eType==JSON_STRING );
   185577     assert( pNode->jnFlags & JNODE_LABEL );
   185578     jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
   185579   }
   185580 }
   185581 
   185582 /* Return the value of a column */
   185583 static int jsonEachColumn(
   185584   sqlite3_vtab_cursor *cur,   /* The cursor */
   185585   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   185586   int i                       /* Which column to return */
   185587 ){
   185588   JsonEachCursor *p = (JsonEachCursor*)cur;
   185589   JsonNode *pThis = &p->sParse.aNode[p->i];
   185590   switch( i ){
   185591     case JEACH_KEY: {
   185592       if( p->i==0 ) break;
   185593       if( p->eType==JSON_OBJECT ){
   185594         jsonReturn(pThis, ctx, 0);
   185595       }else if( p->eType==JSON_ARRAY ){
   185596         u32 iKey;
   185597         if( p->bRecursive ){
   185598           if( p->iRowid==0 ) break;
   185599           iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
   185600         }else{
   185601           iKey = p->iRowid;
   185602         }
   185603         sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
   185604       }
   185605       break;
   185606     }
   185607     case JEACH_VALUE: {
   185608       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
   185609       jsonReturn(pThis, ctx, 0);
   185610       break;
   185611     }
   185612     case JEACH_TYPE: {
   185613       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
   185614       sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
   185615       break;
   185616     }
   185617     case JEACH_ATOM: {
   185618       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
   185619       if( pThis->eType>=JSON_ARRAY ) break;
   185620       jsonReturn(pThis, ctx, 0);
   185621       break;
   185622     }
   185623     case JEACH_ID: {
   185624       sqlite3_result_int64(ctx,
   185625          (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
   185626       break;
   185627     }
   185628     case JEACH_PARENT: {
   185629       if( p->i>p->iBegin && p->bRecursive ){
   185630         sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
   185631       }
   185632       break;
   185633     }
   185634     case JEACH_FULLKEY: {
   185635       JsonString x;
   185636       jsonInit(&x, ctx);
   185637       if( p->bRecursive ){
   185638         jsonEachComputePath(p, &x, p->i);
   185639       }else{
   185640         if( p->zRoot ){
   185641           jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
   185642         }else{
   185643           jsonAppendChar(&x, '$');
   185644         }
   185645         if( p->eType==JSON_ARRAY ){
   185646           jsonPrintf(30, &x, "[%d]", p->iRowid);
   185647         }else{
   185648           jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
   185649         }
   185650       }
   185651       jsonResult(&x);
   185652       break;
   185653     }
   185654     case JEACH_PATH: {
   185655       if( p->bRecursive ){
   185656         JsonString x;
   185657         jsonInit(&x, ctx);
   185658         jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
   185659         jsonResult(&x);
   185660         break;
   185661       }
   185662       /* For json_each() path and root are the same so fall through
   185663       ** into the root case */
   185664     }
   185665     default: {
   185666       const char *zRoot = p->zRoot;
   185667       if( zRoot==0 ) zRoot = "$";
   185668       sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
   185669       break;
   185670     }
   185671     case JEACH_JSON: {
   185672       assert( i==JEACH_JSON );
   185673       sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
   185674       break;
   185675     }
   185676   }
   185677   return SQLITE_OK;
   185678 }
   185679 
   185680 /* Return the current rowid value */
   185681 static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   185682   JsonEachCursor *p = (JsonEachCursor*)cur;
   185683   *pRowid = p->iRowid;
   185684   return SQLITE_OK;
   185685 }
   185686 
   185687 /* The query strategy is to look for an equality constraint on the json
   185688 ** column.  Without such a constraint, the table cannot operate.  idxNum is
   185689 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
   185690 ** and 0 otherwise.
   185691 */
   185692 static int jsonEachBestIndex(
   185693   sqlite3_vtab *tab,
   185694   sqlite3_index_info *pIdxInfo
   185695 ){
   185696   int i;
   185697   int jsonIdx = -1;
   185698   int rootIdx = -1;
   185699   const struct sqlite3_index_constraint *pConstraint;
   185700 
   185701   UNUSED_PARAM(tab);
   185702   pConstraint = pIdxInfo->aConstraint;
   185703   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
   185704     if( pConstraint->usable==0 ) continue;
   185705     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   185706     switch( pConstraint->iColumn ){
   185707       case JEACH_JSON:   jsonIdx = i;    break;
   185708       case JEACH_ROOT:   rootIdx = i;    break;
   185709       default:           /* no-op */     break;
   185710     }
   185711   }
   185712   if( jsonIdx<0 ){
   185713     pIdxInfo->idxNum = 0;
   185714     pIdxInfo->estimatedCost = 1e99;
   185715   }else{
   185716     pIdxInfo->estimatedCost = 1.0;
   185717     pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
   185718     pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
   185719     if( rootIdx<0 ){
   185720       pIdxInfo->idxNum = 1;
   185721     }else{
   185722       pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
   185723       pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
   185724       pIdxInfo->idxNum = 3;
   185725     }
   185726   }
   185727   return SQLITE_OK;
   185728 }
   185729 
   185730 /* Start a search on a new JSON string */
   185731 static int jsonEachFilter(
   185732   sqlite3_vtab_cursor *cur,
   185733   int idxNum, const char *idxStr,
   185734   int argc, sqlite3_value **argv
   185735 ){
   185736   JsonEachCursor *p = (JsonEachCursor*)cur;
   185737   const char *z;
   185738   const char *zRoot = 0;
   185739   sqlite3_int64 n;
   185740 
   185741   UNUSED_PARAM(idxStr);
   185742   UNUSED_PARAM(argc);
   185743   jsonEachCursorReset(p);
   185744   if( idxNum==0 ) return SQLITE_OK;
   185745   z = (const char*)sqlite3_value_text(argv[0]);
   185746   if( z==0 ) return SQLITE_OK;
   185747   n = sqlite3_value_bytes(argv[0]);
   185748   p->zJson = sqlite3_malloc64( n+1 );
   185749   if( p->zJson==0 ) return SQLITE_NOMEM;
   185750   memcpy(p->zJson, z, (size_t)n+1);
   185751   if( jsonParse(&p->sParse, 0, p->zJson) ){
   185752     int rc = SQLITE_NOMEM;
   185753     if( p->sParse.oom==0 ){
   185754       sqlite3_free(cur->pVtab->zErrMsg);
   185755       cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
   185756       if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
   185757     }
   185758     jsonEachCursorReset(p);
   185759     return rc;
   185760   }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
   185761     jsonEachCursorReset(p);
   185762     return SQLITE_NOMEM;
   185763   }else{
   185764     JsonNode *pNode = 0;
   185765     if( idxNum==3 ){
   185766       const char *zErr = 0;
   185767       zRoot = (const char*)sqlite3_value_text(argv[1]);
   185768       if( zRoot==0 ) return SQLITE_OK;
   185769       n = sqlite3_value_bytes(argv[1]);
   185770       p->zRoot = sqlite3_malloc64( n+1 );
   185771       if( p->zRoot==0 ) return SQLITE_NOMEM;
   185772       memcpy(p->zRoot, zRoot, (size_t)n+1);
   185773       if( zRoot[0]!='$' ){
   185774         zErr = zRoot;
   185775       }else{
   185776         pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
   185777       }
   185778       if( zErr ){
   185779         sqlite3_free(cur->pVtab->zErrMsg);
   185780         cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
   185781         jsonEachCursorReset(p);
   185782         return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
   185783       }else if( pNode==0 ){
   185784         return SQLITE_OK;
   185785       }
   185786     }else{
   185787       pNode = p->sParse.aNode;
   185788     }
   185789     p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
   185790     p->eType = pNode->eType;
   185791     if( p->eType>=JSON_ARRAY ){
   185792       pNode->u.iKey = 0;
   185793       p->iEnd = p->i + pNode->n + 1;
   185794       if( p->bRecursive ){
   185795         p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
   185796         if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
   185797           p->i--;
   185798         }
   185799       }else{
   185800         p->i++;
   185801       }
   185802     }else{
   185803       p->iEnd = p->i+1;
   185804     }
   185805   }
   185806   return SQLITE_OK;
   185807 }
   185808 
   185809 /* The methods of the json_each virtual table */
   185810 static sqlite3_module jsonEachModule = {
   185811   0,                         /* iVersion */
   185812   0,                         /* xCreate */
   185813   jsonEachConnect,           /* xConnect */
   185814   jsonEachBestIndex,         /* xBestIndex */
   185815   jsonEachDisconnect,        /* xDisconnect */
   185816   0,                         /* xDestroy */
   185817   jsonEachOpenEach,          /* xOpen - open a cursor */
   185818   jsonEachClose,             /* xClose - close a cursor */
   185819   jsonEachFilter,            /* xFilter - configure scan constraints */
   185820   jsonEachNext,              /* xNext - advance a cursor */
   185821   jsonEachEof,               /* xEof - check for end of scan */
   185822   jsonEachColumn,            /* xColumn - read data */
   185823   jsonEachRowid,             /* xRowid - read data */
   185824   0,                         /* xUpdate */
   185825   0,                         /* xBegin */
   185826   0,                         /* xSync */
   185827   0,                         /* xCommit */
   185828   0,                         /* xRollback */
   185829   0,                         /* xFindMethod */
   185830   0,                         /* xRename */
   185831   0,                         /* xSavepoint */
   185832   0,                         /* xRelease */
   185833   0                          /* xRollbackTo */
   185834 };
   185835 
   185836 /* The methods of the json_tree virtual table. */
   185837 static sqlite3_module jsonTreeModule = {
   185838   0,                         /* iVersion */
   185839   0,                         /* xCreate */
   185840   jsonEachConnect,           /* xConnect */
   185841   jsonEachBestIndex,         /* xBestIndex */
   185842   jsonEachDisconnect,        /* xDisconnect */
   185843   0,                         /* xDestroy */
   185844   jsonEachOpenTree,          /* xOpen - open a cursor */
   185845   jsonEachClose,             /* xClose - close a cursor */
   185846   jsonEachFilter,            /* xFilter - configure scan constraints */
   185847   jsonEachNext,              /* xNext - advance a cursor */
   185848   jsonEachEof,               /* xEof - check for end of scan */
   185849   jsonEachColumn,            /* xColumn - read data */
   185850   jsonEachRowid,             /* xRowid - read data */
   185851   0,                         /* xUpdate */
   185852   0,                         /* xBegin */
   185853   0,                         /* xSync */
   185854   0,                         /* xCommit */
   185855   0,                         /* xRollback */
   185856   0,                         /* xFindMethod */
   185857   0,                         /* xRename */
   185858   0,                         /* xSavepoint */
   185859   0,                         /* xRelease */
   185860   0                          /* xRollbackTo */
   185861 };
   185862 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   185863 
   185864 /****************************************************************************
   185865 ** The following routines are the only publically visible identifiers in this
   185866 ** file.  Call the following routines in order to register the various SQL
   185867 ** functions and the virtual table implemented by this file.
   185868 ****************************************************************************/
   185869 
   185870 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
   185871   int rc = SQLITE_OK;
   185872   unsigned int i;
   185873   static const struct {
   185874      const char *zName;
   185875      int nArg;
   185876      int flag;
   185877      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   185878   } aFunc[] = {
   185879     { "json",                 1, 0,   jsonRemoveFunc        },
   185880     { "json_array",          -1, 0,   jsonArrayFunc         },
   185881     { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
   185882     { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
   185883     { "json_extract",        -1, 0,   jsonExtractFunc       },
   185884     { "json_insert",         -1, 0,   jsonSetFunc           },
   185885     { "json_object",         -1, 0,   jsonObjectFunc        },
   185886     { "json_patch",           2, 0,   jsonPatchFunc         },
   185887     { "json_quote",           1, 0,   jsonQuoteFunc         },
   185888     { "json_remove",         -1, 0,   jsonRemoveFunc        },
   185889     { "json_replace",        -1, 0,   jsonReplaceFunc       },
   185890     { "json_set",            -1, 1,   jsonSetFunc           },
   185891     { "json_type",            1, 0,   jsonTypeFunc          },
   185892     { "json_type",            2, 0,   jsonTypeFunc          },
   185893     { "json_valid",           1, 0,   jsonValidFunc         },
   185894 
   185895 #if SQLITE_DEBUG
   185896     /* DEBUG and TESTING functions */
   185897     { "json_parse",           1, 0,   jsonParseFunc         },
   185898     { "json_test1",           1, 0,   jsonTest1Func         },
   185899 #endif
   185900   };
   185901   static const struct {
   185902      const char *zName;
   185903      int nArg;
   185904      void (*xStep)(sqlite3_context*,int,sqlite3_value**);
   185905      void (*xFinal)(sqlite3_context*);
   185906   } aAgg[] = {
   185907     { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
   185908     { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
   185909   };
   185910 #ifndef SQLITE_OMIT_VIRTUALTABLE
   185911   static const struct {
   185912      const char *zName;
   185913      sqlite3_module *pModule;
   185914   } aMod[] = {
   185915     { "json_each",            &jsonEachModule               },
   185916     { "json_tree",            &jsonTreeModule               },
   185917   };
   185918 #endif
   185919   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
   185920     rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
   185921                                  SQLITE_UTF8 | SQLITE_DETERMINISTIC,
   185922                                  (void*)&aFunc[i].flag,
   185923                                  aFunc[i].xFunc, 0, 0);
   185924   }
   185925   for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
   185926     rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
   185927                                  SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
   185928                                  0, aAgg[i].xStep, aAgg[i].xFinal);
   185929   }
   185930 #ifndef SQLITE_OMIT_VIRTUALTABLE
   185931   for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
   185932     rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
   185933   }
   185934 #endif
   185935   return rc;
   185936 }
   185937 
   185938 
   185939 #ifndef SQLITE_CORE
   185940 #ifdef _WIN32
   185941 __declspec(dllexport)
   185942 #endif
   185943 SQLITE_API int sqlite3_json_init(
   185944   sqlite3 *db,
   185945   char **pzErrMsg,
   185946   const sqlite3_api_routines *pApi
   185947 ){
   185948   SQLITE_EXTENSION_INIT2(pApi);
   185949   (void)pzErrMsg;  /* Unused parameter */
   185950   return sqlite3Json1Init(db);
   185951 }
   185952 #endif
   185953 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
   185954 
   185955 /************** End of json1.c ***********************************************/
   185956 /************** Begin file fts5.c ********************************************/
   185957 
   185958 
   185959 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
   185960 
   185961 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   185962 # define NDEBUG 1
   185963 #endif
   185964 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
   185965 # undef NDEBUG
   185966 #endif
   185967 
   185968 /*
   185969 ** 2014 May 31
   185970 **
   185971 ** The author disclaims copyright to this source code.  In place of
   185972 ** a legal notice, here is a blessing:
   185973 **
   185974 **    May you do good and not evil.
   185975 **    May you find forgiveness for yourself and forgive others.
   185976 **    May you share freely, never taking more than you give.
   185977 **
   185978 ******************************************************************************
   185979 **
   185980 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
   185981 ** FTS5 may be extended with:
   185982 **
   185983 **     * custom tokenizers, and
   185984 **     * custom auxiliary functions.
   185985 */
   185986 
   185987 
   185988 #ifndef _FTS5_H
   185989 #define _FTS5_H
   185990 
   185991 /* #include "sqlite3.h" */
   185992 
   185993 #if 0
   185994 extern "C" {
   185995 #endif
   185996 
   185997 /*************************************************************************
   185998 ** CUSTOM AUXILIARY FUNCTIONS
   185999 **
   186000 ** Virtual table implementations may overload SQL functions by implementing
   186001 ** the sqlite3_module.xFindFunction() method.
   186002 */
   186003 
   186004 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
   186005 typedef struct Fts5Context Fts5Context;
   186006 typedef struct Fts5PhraseIter Fts5PhraseIter;
   186007 
   186008 typedef void (*fts5_extension_function)(
   186009   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
   186010   Fts5Context *pFts,              /* First arg to pass to pApi functions */
   186011   sqlite3_context *pCtx,          /* Context for returning result/error */
   186012   int nVal,                       /* Number of values in apVal[] array */
   186013   sqlite3_value **apVal           /* Array of trailing arguments */
   186014 );
   186015 
   186016 struct Fts5PhraseIter {
   186017   const unsigned char *a;
   186018   const unsigned char *b;
   186019 };
   186020 
   186021 /*
   186022 ** EXTENSION API FUNCTIONS
   186023 **
   186024 ** xUserData(pFts):
   186025 **   Return a copy of the context pointer the extension function was
   186026 **   registered with.
   186027 **
   186028 ** xColumnTotalSize(pFts, iCol, pnToken):
   186029 **   If parameter iCol is less than zero, set output variable *pnToken
   186030 **   to the total number of tokens in the FTS5 table. Or, if iCol is
   186031 **   non-negative but less than the number of columns in the table, return
   186032 **   the total number of tokens in column iCol, considering all rows in
   186033 **   the FTS5 table.
   186034 **
   186035 **   If parameter iCol is greater than or equal to the number of columns
   186036 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
   186037 **   an OOM condition or IO error), an appropriate SQLite error code is
   186038 **   returned.
   186039 **
   186040 ** xColumnCount(pFts):
   186041 **   Return the number of columns in the table.
   186042 **
   186043 ** xColumnSize(pFts, iCol, pnToken):
   186044 **   If parameter iCol is less than zero, set output variable *pnToken
   186045 **   to the total number of tokens in the current row. Or, if iCol is
   186046 **   non-negative but less than the number of columns in the table, set
   186047 **   *pnToken to the number of tokens in column iCol of the current row.
   186048 **
   186049 **   If parameter iCol is greater than or equal to the number of columns
   186050 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
   186051 **   an OOM condition or IO error), an appropriate SQLite error code is
   186052 **   returned.
   186053 **
   186054 **   This function may be quite inefficient if used with an FTS5 table
   186055 **   created with the "columnsize=0" option.
   186056 **
   186057 ** xColumnText:
   186058 **   This function attempts to retrieve the text of column iCol of the
   186059 **   current document. If successful, (*pz) is set to point to a buffer
   186060 **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
   186061 **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
   186062 **   if an error occurs, an SQLite error code is returned and the final values
   186063 **   of (*pz) and (*pn) are undefined.
   186064 **
   186065 ** xPhraseCount:
   186066 **   Returns the number of phrases in the current query expression.
   186067 **
   186068 ** xPhraseSize:
   186069 **   Returns the number of tokens in phrase iPhrase of the query. Phrases
   186070 **   are numbered starting from zero.
   186071 **
   186072 ** xInstCount:
   186073 **   Set *pnInst to the total number of occurrences of all phrases within
   186074 **   the query within the current row. Return SQLITE_OK if successful, or
   186075 **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
   186076 **
   186077 **   This API can be quite slow if used with an FTS5 table created with the
   186078 **   "detail=none" or "detail=column" option. If the FTS5 table is created
   186079 **   with either "detail=none" or "detail=column" and "content=" option
   186080 **   (i.e. if it is a contentless table), then this API always returns 0.
   186081 **
   186082 ** xInst:
   186083 **   Query for the details of phrase match iIdx within the current row.
   186084 **   Phrase matches are numbered starting from zero, so the iIdx argument
   186085 **   should be greater than or equal to zero and smaller than the value
   186086 **   output by xInstCount().
   186087 **
   186088 **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
   186089 **   to the column in which it occurs and *piOff the token offset of the
   186090 **   first token of the phrase. The exception is if the table was created
   186091 **   with the offsets=0 option specified. In this case *piOff is always
   186092 **   set to -1.
   186093 **
   186094 **   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
   186095 **   if an error occurs.
   186096 **
   186097 **   This API can be quite slow if used with an FTS5 table created with the
   186098 **   "detail=none" or "detail=column" option.
   186099 **
   186100 ** xRowid:
   186101 **   Returns the rowid of the current row.
   186102 **
   186103 ** xTokenize:
   186104 **   Tokenize text using the tokenizer belonging to the FTS5 table.
   186105 **
   186106 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
   186107 **   This API function is used to query the FTS table for phrase iPhrase
   186108 **   of the current query. Specifically, a query equivalent to:
   186109 **
   186110 **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
   186111 **
   186112 **   with $p set to a phrase equivalent to the phrase iPhrase of the
   186113 **   current query is executed. Any column filter that applies to
   186114 **   phrase iPhrase of the current query is included in $p. For each
   186115 **   row visited, the callback function passed as the fourth argument
   186116 **   is invoked. The context and API objects passed to the callback
   186117 **   function may be used to access the properties of each matched row.
   186118 **   Invoking Api.xUserData() returns a copy of the pointer passed as
   186119 **   the third argument to pUserData.
   186120 **
   186121 **   If the callback function returns any value other than SQLITE_OK, the
   186122 **   query is abandoned and the xQueryPhrase function returns immediately.
   186123 **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
   186124 **   Otherwise, the error code is propagated upwards.
   186125 **
   186126 **   If the query runs to completion without incident, SQLITE_OK is returned.
   186127 **   Or, if some error occurs before the query completes or is aborted by
   186128 **   the callback, an SQLite error code is returned.
   186129 **
   186130 **
   186131 ** xSetAuxdata(pFts5, pAux, xDelete)
   186132 **
   186133 **   Save the pointer passed as the second argument as the extension functions
   186134 **   "auxiliary data". The pointer may then be retrieved by the current or any
   186135 **   future invocation of the same fts5 extension function made as part of
   186136 **   of the same MATCH query using the xGetAuxdata() API.
   186137 **
   186138 **   Each extension function is allocated a single auxiliary data slot for
   186139 **   each FTS query (MATCH expression). If the extension function is invoked
   186140 **   more than once for a single FTS query, then all invocations share a
   186141 **   single auxiliary data context.
   186142 **
   186143 **   If there is already an auxiliary data pointer when this function is
   186144 **   invoked, then it is replaced by the new pointer. If an xDelete callback
   186145 **   was specified along with the original pointer, it is invoked at this
   186146 **   point.
   186147 **
   186148 **   The xDelete callback, if one is specified, is also invoked on the
   186149 **   auxiliary data pointer after the FTS5 query has finished.
   186150 **
   186151 **   If an error (e.g. an OOM condition) occurs within this function, an
   186152 **   the auxiliary data is set to NULL and an error code returned. If the
   186153 **   xDelete parameter was not NULL, it is invoked on the auxiliary data
   186154 **   pointer before returning.
   186155 **
   186156 **
   186157 ** xGetAuxdata(pFts5, bClear)
   186158 **
   186159 **   Returns the current auxiliary data pointer for the fts5 extension
   186160 **   function. See the xSetAuxdata() method for details.
   186161 **
   186162 **   If the bClear argument is non-zero, then the auxiliary data is cleared
   186163 **   (set to NULL) before this function returns. In this case the xDelete,
   186164 **   if any, is not invoked.
   186165 **
   186166 **
   186167 ** xRowCount(pFts5, pnRow)
   186168 **
   186169 **   This function is used to retrieve the total number of rows in the table.
   186170 **   In other words, the same value that would be returned by:
   186171 **
   186172 **        SELECT count(*) FROM ftstable;
   186173 **
   186174 ** xPhraseFirst()
   186175 **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
   186176 **   method, to iterate through all instances of a single query phrase within
   186177 **   the current row. This is the same information as is accessible via the
   186178 **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
   186179 **   to use, this API may be faster under some circumstances. To iterate
   186180 **   through instances of phrase iPhrase, use the following code:
   186181 **
   186182 **       Fts5PhraseIter iter;
   186183 **       int iCol, iOff;
   186184 **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
   186185 **           iCol>=0;
   186186 **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
   186187 **       ){
   186188 **         // An instance of phrase iPhrase at offset iOff of column iCol
   186189 **       }
   186190 **
   186191 **   The Fts5PhraseIter structure is defined above. Applications should not
   186192 **   modify this structure directly - it should only be used as shown above
   186193 **   with the xPhraseFirst() and xPhraseNext() API methods (and by
   186194 **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
   186195 **
   186196 **   This API can be quite slow if used with an FTS5 table created with the
   186197 **   "detail=none" or "detail=column" option. If the FTS5 table is created
   186198 **   with either "detail=none" or "detail=column" and "content=" option
   186199 **   (i.e. if it is a contentless table), then this API always iterates
   186200 **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
   186201 **
   186202 ** xPhraseNext()
   186203 **   See xPhraseFirst above.
   186204 **
   186205 ** xPhraseFirstColumn()
   186206 **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
   186207 **   and xPhraseNext() APIs described above. The difference is that instead
   186208 **   of iterating through all instances of a phrase in the current row, these
   186209 **   APIs are used to iterate through the set of columns in the current row
   186210 **   that contain one or more instances of a specified phrase. For example:
   186211 **
   186212 **       Fts5PhraseIter iter;
   186213 **       int iCol;
   186214 **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
   186215 **           iCol>=0;
   186216 **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
   186217 **       ){
   186218 **         // Column iCol contains at least one instance of phrase iPhrase
   186219 **       }
   186220 **
   186221 **   This API can be quite slow if used with an FTS5 table created with the
   186222 **   "detail=none" option. If the FTS5 table is created with either
   186223 **   "detail=none" "content=" option (i.e. if it is a contentless table),
   186224 **   then this API always iterates through an empty set (all calls to
   186225 **   xPhraseFirstColumn() set iCol to -1).
   186226 **
   186227 **   The information accessed using this API and its companion
   186228 **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
   186229 **   (or xInst/xInstCount). The chief advantage of this API is that it is
   186230 **   significantly more efficient than those alternatives when used with
   186231 **   "detail=column" tables.
   186232 **
   186233 ** xPhraseNextColumn()
   186234 **   See xPhraseFirstColumn above.
   186235 */
   186236 struct Fts5ExtensionApi {
   186237   int iVersion;                   /* Currently always set to 3 */
   186238 
   186239   void *(*xUserData)(Fts5Context*);
   186240 
   186241   int (*xColumnCount)(Fts5Context*);
   186242   int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
   186243   int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
   186244 
   186245   int (*xTokenize)(Fts5Context*,
   186246     const char *pText, int nText, /* Text to tokenize */
   186247     void *pCtx,                   /* Context passed to xToken() */
   186248     int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
   186249   );
   186250 
   186251   int (*xPhraseCount)(Fts5Context*);
   186252   int (*xPhraseSize)(Fts5Context*, int iPhrase);
   186253 
   186254   int (*xInstCount)(Fts5Context*, int *pnInst);
   186255   int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
   186256 
   186257   sqlite3_int64 (*xRowid)(Fts5Context*);
   186258   int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
   186259   int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
   186260 
   186261   int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
   186262     int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
   186263   );
   186264   int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
   186265   void *(*xGetAuxdata)(Fts5Context*, int bClear);
   186266 
   186267   int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
   186268   void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
   186269 
   186270   int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
   186271   void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
   186272 };
   186273 
   186274 /*
   186275 ** CUSTOM AUXILIARY FUNCTIONS
   186276 *************************************************************************/
   186277 
   186278 /*************************************************************************
   186279 ** CUSTOM TOKENIZERS
   186280 **
   186281 ** Applications may also register custom tokenizer types. A tokenizer
   186282 ** is registered by providing fts5 with a populated instance of the
   186283 ** following structure. All structure methods must be defined, setting
   186284 ** any member of the fts5_tokenizer struct to NULL leads to undefined
   186285 ** behaviour. The structure methods are expected to function as follows:
   186286 **
   186287 ** xCreate:
   186288 **   This function is used to allocate and initialize a tokenizer instance.
   186289 **   A tokenizer instance is required to actually tokenize text.
   186290 **
   186291 **   The first argument passed to this function is a copy of the (void*)
   186292 **   pointer provided by the application when the fts5_tokenizer object
   186293 **   was registered with FTS5 (the third argument to xCreateTokenizer()).
   186294 **   The second and third arguments are an array of nul-terminated strings
   186295 **   containing the tokenizer arguments, if any, specified following the
   186296 **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
   186297 **   to create the FTS5 table.
   186298 **
   186299 **   The final argument is an output variable. If successful, (*ppOut)
   186300 **   should be set to point to the new tokenizer handle and SQLITE_OK
   186301 **   returned. If an error occurs, some value other than SQLITE_OK should
   186302 **   be returned. In this case, fts5 assumes that the final value of *ppOut
   186303 **   is undefined.
   186304 **
   186305 ** xDelete:
   186306 **   This function is invoked to delete a tokenizer handle previously
   186307 **   allocated using xCreate(). Fts5 guarantees that this function will
   186308 **   be invoked exactly once for each successful call to xCreate().
   186309 **
   186310 ** xTokenize:
   186311 **   This function is expected to tokenize the nText byte string indicated
   186312 **   by argument pText. pText may or may not be nul-terminated. The first
   186313 **   argument passed to this function is a pointer to an Fts5Tokenizer object
   186314 **   returned by an earlier call to xCreate().
   186315 **
   186316 **   The second argument indicates the reason that FTS5 is requesting
   186317 **   tokenization of the supplied text. This is always one of the following
   186318 **   four values:
   186319 **
   186320 **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
   186321 **            or removed from the FTS table. The tokenizer is being invoked to
   186322 **            determine the set of tokens to add to (or delete from) the
   186323 **            FTS index.
   186324 **
   186325 **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
   186326 **            against the FTS index. The tokenizer is being called to tokenize
   186327 **            a bareword or quoted string specified as part of the query.
   186328 **
   186329 **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
   186330 **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
   186331 **            followed by a "*" character, indicating that the last token
   186332 **            returned by the tokenizer will be treated as a token prefix.
   186333 **
   186334 **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
   186335 **            satisfy an fts5_api.xTokenize() request made by an auxiliary
   186336 **            function. Or an fts5_api.xColumnSize() request made by the same
   186337 **            on a columnsize=0 database.
   186338 **   </ul>
   186339 **
   186340 **   For each token in the input string, the supplied callback xToken() must
   186341 **   be invoked. The first argument to it should be a copy of the pointer
   186342 **   passed as the second argument to xTokenize(). The third and fourth
   186343 **   arguments are a pointer to a buffer containing the token text, and the
   186344 **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
   186345 **   of the first byte of and first byte immediately following the text from
   186346 **   which the token is derived within the input.
   186347 **
   186348 **   The second argument passed to the xToken() callback ("tflags") should
   186349 **   normally be set to 0. The exception is if the tokenizer supports
   186350 **   synonyms. In this case see the discussion below for details.
   186351 **
   186352 **   FTS5 assumes the xToken() callback is invoked for each token in the
   186353 **   order that they occur within the input text.
   186354 **
   186355 **   If an xToken() callback returns any value other than SQLITE_OK, then
   186356 **   the tokenization should be abandoned and the xTokenize() method should
   186357 **   immediately return a copy of the xToken() return value. Or, if the
   186358 **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
   186359 **   if an error occurs with the xTokenize() implementation itself, it
   186360 **   may abandon the tokenization and return any error code other than
   186361 **   SQLITE_OK or SQLITE_DONE.
   186362 **
   186363 ** SYNONYM SUPPORT
   186364 **
   186365 **   Custom tokenizers may also support synonyms. Consider a case in which a
   186366 **   user wishes to query for a phrase such as "first place". Using the
   186367 **   built-in tokenizers, the FTS5 query 'first + place' will match instances
   186368 **   of "first place" within the document set, but not alternative forms
   186369 **   such as "1st place". In some applications, it would be better to match
   186370 **   all instances of "first place" or "1st place" regardless of which form
   186371 **   the user specified in the MATCH query text.
   186372 **
   186373 **   There are several ways to approach this in FTS5:
   186374 **
   186375 **   <ol><li> By mapping all synonyms to a single token. In this case, the
   186376 **            In the above example, this means that the tokenizer returns the
   186377 **            same token for inputs "first" and "1st". Say that token is in
   186378 **            fact "first", so that when the user inserts the document "I won
   186379 **            1st place" entries are added to the index for tokens "i", "won",
   186380 **            "first" and "place". If the user then queries for '1st + place',
   186381 **            the tokenizer substitutes "first" for "1st" and the query works
   186382 **            as expected.
   186383 **
   186384 **       <li> By adding multiple synonyms for a single term to the FTS index.
   186385 **            In this case, when tokenizing query text, the tokenizer may
   186386 **            provide multiple synonyms for a single term within the document.
   186387 **            FTS5 then queries the index for each synonym individually. For
   186388 **            example, faced with the query:
   186389 **
   186390 **   <codeblock>
   186391 **     ... MATCH 'first place'</codeblock>
   186392 **
   186393 **            the tokenizer offers both "1st" and "first" as synonyms for the
   186394 **            first token in the MATCH query and FTS5 effectively runs a query
   186395 **            similar to:
   186396 **
   186397 **   <codeblock>
   186398 **     ... MATCH '(first OR 1st) place'</codeblock>
   186399 **
   186400 **            except that, for the purposes of auxiliary functions, the query
   186401 **            still appears to contain just two phrases - "(first OR 1st)"
   186402 **            being treated as a single phrase.
   186403 **
   186404 **       <li> By adding multiple synonyms for a single term to the FTS index.
   186405 **            Using this method, when tokenizing document text, the tokenizer
   186406 **            provides multiple synonyms for each token. So that when a
   186407 **            document such as "I won first place" is tokenized, entries are
   186408 **            added to the FTS index for "i", "won", "first", "1st" and
   186409 **            "place".
   186410 **
   186411 **            This way, even if the tokenizer does not provide synonyms
   186412 **            when tokenizing query text (it should not - to do would be
   186413 **            inefficient), it doesn't matter if the user queries for
   186414 **            'first + place' or '1st + place', as there are entires in the
   186415 **            FTS index corresponding to both forms of the first token.
   186416 **   </ol>
   186417 **
   186418 **   Whether it is parsing document or query text, any call to xToken that
   186419 **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
   186420 **   is considered to supply a synonym for the previous token. For example,
   186421 **   when parsing the document "I won first place", a tokenizer that supports
   186422 **   synonyms would call xToken() 5 times, as follows:
   186423 **
   186424 **   <codeblock>
   186425 **       xToken(pCtx, 0, "i",                      1,  0,  1);
   186426 **       xToken(pCtx, 0, "won",                    3,  2,  5);
   186427 **       xToken(pCtx, 0, "first",                  5,  6, 11);
   186428 **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
   186429 **       xToken(pCtx, 0, "place",                  5, 12, 17);
   186430 **</codeblock>
   186431 **
   186432 **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
   186433 **   xToken() is called. Multiple synonyms may be specified for a single token
   186434 **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
   186435 **   There is no limit to the number of synonyms that may be provided for a
   186436 **   single token.
   186437 **
   186438 **   In many cases, method (1) above is the best approach. It does not add
   186439 **   extra data to the FTS index or require FTS5 to query for multiple terms,
   186440 **   so it is efficient in terms of disk space and query speed. However, it
   186441 **   does not support prefix queries very well. If, as suggested above, the
   186442 **   token "first" is subsituted for "1st" by the tokenizer, then the query:
   186443 **
   186444 **   <codeblock>
   186445 **     ... MATCH '1s*'</codeblock>
   186446 **
   186447 **   will not match documents that contain the token "1st" (as the tokenizer
   186448 **   will probably not map "1s" to any prefix of "first").
   186449 **
   186450 **   For full prefix support, method (3) may be preferred. In this case,
   186451 **   because the index contains entries for both "first" and "1st", prefix
   186452 **   queries such as 'fi*' or '1s*' will match correctly. However, because
   186453 **   extra entries are added to the FTS index, this method uses more space
   186454 **   within the database.
   186455 **
   186456 **   Method (2) offers a midpoint between (1) and (3). Using this method,
   186457 **   a query such as '1s*' will match documents that contain the literal
   186458 **   token "1st", but not "first" (assuming the tokenizer is not able to
   186459 **   provide synonyms for prefixes). However, a non-prefix query like '1st'
   186460 **   will match against "1st" and "first". This method does not require
   186461 **   extra disk space, as no extra entries are added to the FTS index.
   186462 **   On the other hand, it may require more CPU cycles to run MATCH queries,
   186463 **   as separate queries of the FTS index are required for each synonym.
   186464 **
   186465 **   When using methods (2) or (3), it is important that the tokenizer only
   186466 **   provide synonyms when tokenizing document text (method (2)) or query
   186467 **   text (method (3)), not both. Doing so will not cause any errors, but is
   186468 **   inefficient.
   186469 */
   186470 typedef struct Fts5Tokenizer Fts5Tokenizer;
   186471 typedef struct fts5_tokenizer fts5_tokenizer;
   186472 struct fts5_tokenizer {
   186473   int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
   186474   void (*xDelete)(Fts5Tokenizer*);
   186475   int (*xTokenize)(Fts5Tokenizer*,
   186476       void *pCtx,
   186477       int flags,            /* Mask of FTS5_TOKENIZE_* flags */
   186478       const char *pText, int nText,
   186479       int (*xToken)(
   186480         void *pCtx,         /* Copy of 2nd argument to xTokenize() */
   186481         int tflags,         /* Mask of FTS5_TOKEN_* flags */
   186482         const char *pToken, /* Pointer to buffer containing token */
   186483         int nToken,         /* Size of token in bytes */
   186484         int iStart,         /* Byte offset of token within input text */
   186485         int iEnd            /* Byte offset of end of token within input text */
   186486       )
   186487   );
   186488 };
   186489 
   186490 /* Flags that may be passed as the third argument to xTokenize() */
   186491 #define FTS5_TOKENIZE_QUERY     0x0001
   186492 #define FTS5_TOKENIZE_PREFIX    0x0002
   186493 #define FTS5_TOKENIZE_DOCUMENT  0x0004
   186494 #define FTS5_TOKENIZE_AUX       0x0008
   186495 
   186496 /* Flags that may be passed by the tokenizer implementation back to FTS5
   186497 ** as the third argument to the supplied xToken callback. */
   186498 #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
   186499 
   186500 /*
   186501 ** END OF CUSTOM TOKENIZERS
   186502 *************************************************************************/
   186503 
   186504 /*************************************************************************
   186505 ** FTS5 EXTENSION REGISTRATION API
   186506 */
   186507 typedef struct fts5_api fts5_api;
   186508 struct fts5_api {
   186509   int iVersion;                   /* Currently always set to 2 */
   186510 
   186511   /* Create a new tokenizer */
   186512   int (*xCreateTokenizer)(
   186513     fts5_api *pApi,
   186514     const char *zName,
   186515     void *pContext,
   186516     fts5_tokenizer *pTokenizer,
   186517     void (*xDestroy)(void*)
   186518   );
   186519 
   186520   /* Find an existing tokenizer */
   186521   int (*xFindTokenizer)(
   186522     fts5_api *pApi,
   186523     const char *zName,
   186524     void **ppContext,
   186525     fts5_tokenizer *pTokenizer
   186526   );
   186527 
   186528   /* Create a new auxiliary function */
   186529   int (*xCreateFunction)(
   186530     fts5_api *pApi,
   186531     const char *zName,
   186532     void *pContext,
   186533     fts5_extension_function xFunction,
   186534     void (*xDestroy)(void*)
   186535   );
   186536 };
   186537 
   186538 /*
   186539 ** END OF REGISTRATION API
   186540 *************************************************************************/
   186541 
   186542 #if 0
   186543 }  /* end of the 'extern "C"' block */
   186544 #endif
   186545 
   186546 #endif /* _FTS5_H */
   186547 
   186548 /*
   186549 ** 2014 May 31
   186550 **
   186551 ** The author disclaims copyright to this source code.  In place of
   186552 ** a legal notice, here is a blessing:
   186553 **
   186554 **    May you do good and not evil.
   186555 **    May you find forgiveness for yourself and forgive others.
   186556 **    May you share freely, never taking more than you give.
   186557 **
   186558 ******************************************************************************
   186559 **
   186560 */
   186561 #ifndef _FTS5INT_H
   186562 #define _FTS5INT_H
   186563 
   186564 /* #include "fts5.h" */
   186565 /* #include "sqlite3ext.h" */
   186566 SQLITE_EXTENSION_INIT1
   186567 
   186568 /* #include <string.h> */
   186569 /* #include <assert.h> */
   186570 
   186571 #ifndef SQLITE_AMALGAMATION
   186572 
   186573 typedef unsigned char  u8;
   186574 typedef unsigned int   u32;
   186575 typedef unsigned short u16;
   186576 typedef short i16;
   186577 typedef sqlite3_int64 i64;
   186578 typedef sqlite3_uint64 u64;
   186579 
   186580 #ifndef ArraySize
   186581 # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
   186582 #endif
   186583 
   186584 #define testcase(x)
   186585 #define ALWAYS(x) 1
   186586 #define NEVER(x) 0
   186587 
   186588 #define MIN(x,y) (((x) < (y)) ? (x) : (y))
   186589 #define MAX(x,y) (((x) > (y)) ? (x) : (y))
   186590 
   186591 /*
   186592 ** Constants for the largest and smallest possible 64-bit signed integers.
   186593 */
   186594 # define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   186595 # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
   186596 
   186597 #endif
   186598 
   186599 /* Truncate very long tokens to this many bytes. Hard limit is
   186600 ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
   186601 ** field that occurs at the start of each leaf page (see fts5_index.c). */
   186602 #define FTS5_MAX_TOKEN_SIZE 32768
   186603 
   186604 /*
   186605 ** Maximum number of prefix indexes on single FTS5 table. This must be
   186606 ** less than 32. If it is set to anything large than that, an #error
   186607 ** directive in fts5_index.c will cause the build to fail.
   186608 */
   186609 #define FTS5_MAX_PREFIX_INDEXES 31
   186610 
   186611 #define FTS5_DEFAULT_NEARDIST 10
   186612 #define FTS5_DEFAULT_RANK     "bm25"
   186613 
   186614 /* Name of rank and rowid columns */
   186615 #define FTS5_RANK_NAME "rank"
   186616 #define FTS5_ROWID_NAME "rowid"
   186617 
   186618 #ifdef SQLITE_DEBUG
   186619 # define FTS5_CORRUPT sqlite3Fts5Corrupt()
   186620 static int sqlite3Fts5Corrupt(void);
   186621 #else
   186622 # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
   186623 #endif
   186624 
   186625 /*
   186626 ** The assert_nc() macro is similar to the assert() macro, except that it
   186627 ** is used for assert() conditions that are true only if it can be
   186628 ** guranteed that the database is not corrupt.
   186629 */
   186630 #ifdef SQLITE_DEBUG
   186631 SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
   186632 # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
   186633 #else
   186634 # define assert_nc(x) assert(x)
   186635 #endif
   186636 
   186637 /* Mark a function parameter as unused, to suppress nuisance compiler
   186638 ** warnings. */
   186639 #ifndef UNUSED_PARAM
   186640 # define UNUSED_PARAM(X)  (void)(X)
   186641 #endif
   186642 
   186643 #ifndef UNUSED_PARAM2
   186644 # define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
   186645 #endif
   186646 
   186647 typedef struct Fts5Global Fts5Global;
   186648 typedef struct Fts5Colset Fts5Colset;
   186649 
   186650 /* If a NEAR() clump or phrase may only match a specific set of columns,
   186651 ** then an object of the following type is used to record the set of columns.
   186652 ** Each entry in the aiCol[] array is a column that may be matched.
   186653 **
   186654 ** This object is used by fts5_expr.c and fts5_index.c.
   186655 */
   186656 struct Fts5Colset {
   186657   int nCol;
   186658   int aiCol[1];
   186659 };
   186660 
   186661 
   186662 
   186663 /**************************************************************************
   186664 ** Interface to code in fts5_config.c. fts5_config.c contains contains code
   186665 ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
   186666 */
   186667 
   186668 typedef struct Fts5Config Fts5Config;
   186669 
   186670 /*
   186671 ** An instance of the following structure encodes all information that can
   186672 ** be gleaned from the CREATE VIRTUAL TABLE statement.
   186673 **
   186674 ** And all information loaded from the %_config table.
   186675 **
   186676 ** nAutomerge:
   186677 **   The minimum number of segments that an auto-merge operation should
   186678 **   attempt to merge together. A value of 1 sets the object to use the
   186679 **   compile time default. Zero disables auto-merge altogether.
   186680 **
   186681 ** zContent:
   186682 **
   186683 ** zContentRowid:
   186684 **   The value of the content_rowid= option, if one was specified. Or
   186685 **   the string "rowid" otherwise. This text is not quoted - if it is
   186686 **   used as part of an SQL statement it needs to be quoted appropriately.
   186687 **
   186688 ** zContentExprlist:
   186689 **
   186690 ** pzErrmsg:
   186691 **   This exists in order to allow the fts5_index.c module to return a
   186692 **   decent error message if it encounters a file-format version it does
   186693 **   not understand.
   186694 **
   186695 ** bColumnsize:
   186696 **   True if the %_docsize table is created.
   186697 **
   186698 ** bPrefixIndex:
   186699 **   This is only used for debugging. If set to false, any prefix indexes
   186700 **   are ignored. This value is configured using:
   186701 **
   186702 **       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
   186703 **
   186704 */
   186705 struct Fts5Config {
   186706   sqlite3 *db;                    /* Database handle */
   186707   char *zDb;                      /* Database holding FTS index (e.g. "main") */
   186708   char *zName;                    /* Name of FTS index */
   186709   int nCol;                       /* Number of columns */
   186710   char **azCol;                   /* Column names */
   186711   u8 *abUnindexed;                /* True for unindexed columns */
   186712   int nPrefix;                    /* Number of prefix indexes */
   186713   int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
   186714   int eContent;                   /* An FTS5_CONTENT value */
   186715   char *zContent;                 /* content table */
   186716   char *zContentRowid;            /* "content_rowid=" option value */
   186717   int bColumnsize;                /* "columnsize=" option value (dflt==1) */
   186718   int eDetail;                    /* FTS5_DETAIL_XXX value */
   186719   char *zContentExprlist;
   186720   Fts5Tokenizer *pTok;
   186721   fts5_tokenizer *pTokApi;
   186722 
   186723   /* Values loaded from the %_config table */
   186724   int iCookie;                    /* Incremented when %_config is modified */
   186725   int pgsz;                       /* Approximate page size used in %_data */
   186726   int nAutomerge;                 /* 'automerge' setting */
   186727   int nCrisisMerge;               /* Maximum allowed segments per level */
   186728   int nUsermerge;                 /* 'usermerge' setting */
   186729   int nHashSize;                  /* Bytes of memory for in-memory hash */
   186730   char *zRank;                    /* Name of rank function */
   186731   char *zRankArgs;                /* Arguments to rank function */
   186732 
   186733   /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
   186734   char **pzErrmsg;
   186735 
   186736 #ifdef SQLITE_DEBUG
   186737   int bPrefixIndex;               /* True to use prefix-indexes */
   186738 #endif
   186739 };
   186740 
   186741 /* Current expected value of %_config table 'version' field */
   186742 #define FTS5_CURRENT_VERSION 4
   186743 
   186744 #define FTS5_CONTENT_NORMAL   0
   186745 #define FTS5_CONTENT_NONE     1
   186746 #define FTS5_CONTENT_EXTERNAL 2
   186747 
   186748 #define FTS5_DETAIL_FULL    0
   186749 #define FTS5_DETAIL_NONE    1
   186750 #define FTS5_DETAIL_COLUMNS 2
   186751 
   186752 
   186753 
   186754 static int sqlite3Fts5ConfigParse(
   186755     Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
   186756 );
   186757 static void sqlite3Fts5ConfigFree(Fts5Config*);
   186758 
   186759 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
   186760 
   186761 static int sqlite3Fts5Tokenize(
   186762   Fts5Config *pConfig,            /* FTS5 Configuration object */
   186763   int flags,                      /* FTS5_TOKENIZE_* flags */
   186764   const char *pText, int nText,   /* Text to tokenize */
   186765   void *pCtx,                     /* Context passed to xToken() */
   186766   int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
   186767 );
   186768 
   186769 static void sqlite3Fts5Dequote(char *z);
   186770 
   186771 /* Load the contents of the %_config table */
   186772 static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
   186773 
   186774 /* Set the value of a single config attribute */
   186775 static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
   186776 
   186777 static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
   186778 
   186779 /*
   186780 ** End of interface to code in fts5_config.c.
   186781 **************************************************************************/
   186782 
   186783 /**************************************************************************
   186784 ** Interface to code in fts5_buffer.c.
   186785 */
   186786 
   186787 /*
   186788 ** Buffer object for the incremental building of string data.
   186789 */
   186790 typedef struct Fts5Buffer Fts5Buffer;
   186791 struct Fts5Buffer {
   186792   u8 *p;
   186793   int n;
   186794   int nSpace;
   186795 };
   186796 
   186797 static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
   186798 static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
   186799 static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
   186800 static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
   186801 static void sqlite3Fts5BufferFree(Fts5Buffer*);
   186802 static void sqlite3Fts5BufferZero(Fts5Buffer*);
   186803 static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
   186804 static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
   186805 
   186806 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
   186807 
   186808 #define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
   186809 #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
   186810 #define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
   186811 #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
   186812 #define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
   186813 
   186814 #define fts5BufferGrow(pRc,pBuf,nn) ( \
   186815   (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
   186816     sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
   186817 )
   186818 
   186819 /* Write and decode big-endian 32-bit integer values */
   186820 static void sqlite3Fts5Put32(u8*, int);
   186821 static int sqlite3Fts5Get32(const u8*);
   186822 
   186823 #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
   186824 #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
   186825 
   186826 typedef struct Fts5PoslistReader Fts5PoslistReader;
   186827 struct Fts5PoslistReader {
   186828   /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
   186829   const u8 *a;                    /* Position list to iterate through */
   186830   int n;                          /* Size of buffer at a[] in bytes */
   186831   int i;                          /* Current offset in a[] */
   186832 
   186833   u8 bFlag;                       /* For client use (any custom purpose) */
   186834 
   186835   /* Output variables */
   186836   u8 bEof;                        /* Set to true at EOF */
   186837   i64 iPos;                       /* (iCol<<32) + iPos */
   186838 };
   186839 static int sqlite3Fts5PoslistReaderInit(
   186840   const u8 *a, int n,             /* Poslist buffer to iterate through */
   186841   Fts5PoslistReader *pIter        /* Iterator object to initialize */
   186842 );
   186843 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
   186844 
   186845 typedef struct Fts5PoslistWriter Fts5PoslistWriter;
   186846 struct Fts5PoslistWriter {
   186847   i64 iPrev;
   186848 };
   186849 static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
   186850 static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
   186851 
   186852 static int sqlite3Fts5PoslistNext64(
   186853   const u8 *a, int n,             /* Buffer containing poslist */
   186854   int *pi,                        /* IN/OUT: Offset within a[] */
   186855   i64 *piOff                      /* IN/OUT: Current offset */
   186856 );
   186857 
   186858 /* Malloc utility */
   186859 static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
   186860 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
   186861 
   186862 /* Character set tests (like isspace(), isalpha() etc.) */
   186863 static int sqlite3Fts5IsBareword(char t);
   186864 
   186865 
   186866 /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
   186867 typedef struct Fts5Termset Fts5Termset;
   186868 static int sqlite3Fts5TermsetNew(Fts5Termset**);
   186869 static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
   186870 static void sqlite3Fts5TermsetFree(Fts5Termset*);
   186871 
   186872 /*
   186873 ** End of interface to code in fts5_buffer.c.
   186874 **************************************************************************/
   186875 
   186876 /**************************************************************************
   186877 ** Interface to code in fts5_index.c. fts5_index.c contains contains code
   186878 ** to access the data stored in the %_data table.
   186879 */
   186880 
   186881 typedef struct Fts5Index Fts5Index;
   186882 typedef struct Fts5IndexIter Fts5IndexIter;
   186883 
   186884 struct Fts5IndexIter {
   186885   i64 iRowid;
   186886   const u8 *pData;
   186887   int nData;
   186888   u8 bEof;
   186889 };
   186890 
   186891 #define sqlite3Fts5IterEof(x) ((x)->bEof)
   186892 
   186893 /*
   186894 ** Values used as part of the flags argument passed to IndexQuery().
   186895 */
   186896 #define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
   186897 #define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
   186898 #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
   186899 #define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
   186900 
   186901 /* The following are used internally by the fts5_index.c module. They are
   186902 ** defined here only to make it easier to avoid clashes with the flags
   186903 ** above. */
   186904 #define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
   186905 #define FTS5INDEX_QUERY_NOOUTPUT   0x0020
   186906 
   186907 /*
   186908 ** Create/destroy an Fts5Index object.
   186909 */
   186910 static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
   186911 static int sqlite3Fts5IndexClose(Fts5Index *p);
   186912 
   186913 /*
   186914 ** Return a simple checksum value based on the arguments.
   186915 */
   186916 static u64 sqlite3Fts5IndexEntryCksum(
   186917   i64 iRowid,
   186918   int iCol,
   186919   int iPos,
   186920   int iIdx,
   186921   const char *pTerm,
   186922   int nTerm
   186923 );
   186924 
   186925 /*
   186926 ** Argument p points to a buffer containing utf-8 text that is n bytes in
   186927 ** size. Return the number of bytes in the nChar character prefix of the
   186928 ** buffer, or 0 if there are less than nChar characters in total.
   186929 */
   186930 static int sqlite3Fts5IndexCharlenToBytelen(
   186931   const char *p,
   186932   int nByte,
   186933   int nChar
   186934 );
   186935 
   186936 /*
   186937 ** Open a new iterator to iterate though all rowids that match the
   186938 ** specified token or token prefix.
   186939 */
   186940 static int sqlite3Fts5IndexQuery(
   186941   Fts5Index *p,                   /* FTS index to query */
   186942   const char *pToken, int nToken, /* Token (or prefix) to query for */
   186943   int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
   186944   Fts5Colset *pColset,            /* Match these columns only */
   186945   Fts5IndexIter **ppIter          /* OUT: New iterator object */
   186946 );
   186947 
   186948 /*
   186949 ** The various operations on open token or token prefix iterators opened
   186950 ** using sqlite3Fts5IndexQuery().
   186951 */
   186952 static int sqlite3Fts5IterNext(Fts5IndexIter*);
   186953 static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
   186954 
   186955 /*
   186956 ** Close an iterator opened by sqlite3Fts5IndexQuery().
   186957 */
   186958 static void sqlite3Fts5IterClose(Fts5IndexIter*);
   186959 
   186960 /*
   186961 ** This interface is used by the fts5vocab module.
   186962 */
   186963 static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
   186964 static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
   186965 
   186966 
   186967 /*
   186968 ** Insert or remove data to or from the index. Each time a document is
   186969 ** added to or removed from the index, this function is called one or more
   186970 ** times.
   186971 **
   186972 ** For an insert, it must be called once for each token in the new document.
   186973 ** If the operation is a delete, it must be called (at least) once for each
   186974 ** unique token in the document with an iCol value less than zero. The iPos
   186975 ** argument is ignored for a delete.
   186976 */
   186977 static int sqlite3Fts5IndexWrite(
   186978   Fts5Index *p,                   /* Index to write to */
   186979   int iCol,                       /* Column token appears in (-ve -> delete) */
   186980   int iPos,                       /* Position of token within column */
   186981   const char *pToken, int nToken  /* Token to add or remove to or from index */
   186982 );
   186983 
   186984 /*
   186985 ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
   186986 ** document iDocid.
   186987 */
   186988 static int sqlite3Fts5IndexBeginWrite(
   186989   Fts5Index *p,                   /* Index to write to */
   186990   int bDelete,                    /* True if current operation is a delete */
   186991   i64 iDocid                      /* Docid to add or remove data from */
   186992 );
   186993 
   186994 /*
   186995 ** Flush any data stored in the in-memory hash tables to the database.
   186996 ** Also close any open blob handles.
   186997 */
   186998 static int sqlite3Fts5IndexSync(Fts5Index *p);
   186999 
   187000 /*
   187001 ** Discard any data stored in the in-memory hash tables. Do not write it
   187002 ** to the database. Additionally, assume that the contents of the %_data
   187003 ** table may have changed on disk. So any in-memory caches of %_data
   187004 ** records must be invalidated.
   187005 */
   187006 static int sqlite3Fts5IndexRollback(Fts5Index *p);
   187007 
   187008 /*
   187009 ** Get or set the "averages" values.
   187010 */
   187011 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
   187012 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
   187013 
   187014 /*
   187015 ** Functions called by the storage module as part of integrity-check.
   187016 */
   187017 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
   187018 
   187019 /*
   187020 ** Called during virtual module initialization to register UDF
   187021 ** fts5_decode() with SQLite
   187022 */
   187023 static int sqlite3Fts5IndexInit(sqlite3*);
   187024 
   187025 static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
   187026 
   187027 /*
   187028 ** Return the total number of entries read from the %_data table by
   187029 ** this connection since it was created.
   187030 */
   187031 static int sqlite3Fts5IndexReads(Fts5Index *p);
   187032 
   187033 static int sqlite3Fts5IndexReinit(Fts5Index *p);
   187034 static int sqlite3Fts5IndexOptimize(Fts5Index *p);
   187035 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
   187036 static int sqlite3Fts5IndexReset(Fts5Index *p);
   187037 
   187038 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
   187039 
   187040 /*
   187041 ** End of interface to code in fts5_index.c.
   187042 **************************************************************************/
   187043 
   187044 /**************************************************************************
   187045 ** Interface to code in fts5_varint.c.
   187046 */
   187047 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
   187048 static int sqlite3Fts5GetVarintLen(u32 iVal);
   187049 static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
   187050 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
   187051 
   187052 #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
   187053 #define fts5GetVarint    sqlite3Fts5GetVarint
   187054 
   187055 #define fts5FastGetVarint32(a, iOff, nVal) {      \
   187056   nVal = (a)[iOff++];                             \
   187057   if( nVal & 0x80 ){                              \
   187058     iOff--;                                       \
   187059     iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
   187060   }                                               \
   187061 }
   187062 
   187063 
   187064 /*
   187065 ** End of interface to code in fts5_varint.c.
   187066 **************************************************************************/
   187067 
   187068 
   187069 /**************************************************************************
   187070 ** Interface to code in fts5.c.
   187071 */
   187072 
   187073 static int sqlite3Fts5GetTokenizer(
   187074   Fts5Global*,
   187075   const char **azArg,
   187076   int nArg,
   187077   Fts5Tokenizer**,
   187078   fts5_tokenizer**,
   187079   char **pzErr
   187080 );
   187081 
   187082 static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
   187083 
   187084 /*
   187085 ** End of interface to code in fts5.c.
   187086 **************************************************************************/
   187087 
   187088 /**************************************************************************
   187089 ** Interface to code in fts5_hash.c.
   187090 */
   187091 typedef struct Fts5Hash Fts5Hash;
   187092 
   187093 /*
   187094 ** Create a hash table, free a hash table.
   187095 */
   187096 static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
   187097 static void sqlite3Fts5HashFree(Fts5Hash*);
   187098 
   187099 static int sqlite3Fts5HashWrite(
   187100   Fts5Hash*,
   187101   i64 iRowid,                     /* Rowid for this entry */
   187102   int iCol,                       /* Column token appears in (-ve -> delete) */
   187103   int iPos,                       /* Position of token within column */
   187104   char bByte,
   187105   const char *pToken, int nToken  /* Token to add or remove to or from index */
   187106 );
   187107 
   187108 /*
   187109 ** Empty (but do not delete) a hash table.
   187110 */
   187111 static void sqlite3Fts5HashClear(Fts5Hash*);
   187112 
   187113 static int sqlite3Fts5HashQuery(
   187114   Fts5Hash*,                      /* Hash table to query */
   187115   const char *pTerm, int nTerm,   /* Query term */
   187116   const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
   187117   int *pnDoclist                  /* OUT: Size of doclist in bytes */
   187118 );
   187119 
   187120 static int sqlite3Fts5HashScanInit(
   187121   Fts5Hash*,                      /* Hash table to query */
   187122   const char *pTerm, int nTerm    /* Query prefix */
   187123 );
   187124 static void sqlite3Fts5HashScanNext(Fts5Hash*);
   187125 static int sqlite3Fts5HashScanEof(Fts5Hash*);
   187126 static void sqlite3Fts5HashScanEntry(Fts5Hash *,
   187127   const char **pzTerm,            /* OUT: term (nul-terminated) */
   187128   const u8 **ppDoclist,           /* OUT: pointer to doclist */
   187129   int *pnDoclist                  /* OUT: size of doclist in bytes */
   187130 );
   187131 
   187132 
   187133 /*
   187134 ** End of interface to code in fts5_hash.c.
   187135 **************************************************************************/
   187136 
   187137 /**************************************************************************
   187138 ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
   187139 ** code to access the data stored in the %_content and %_docsize tables.
   187140 */
   187141 
   187142 #define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
   187143 #define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
   187144 #define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
   187145 
   187146 typedef struct Fts5Storage Fts5Storage;
   187147 
   187148 static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
   187149 static int sqlite3Fts5StorageClose(Fts5Storage *p);
   187150 static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
   187151 
   187152 static int sqlite3Fts5DropAll(Fts5Config*);
   187153 static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
   187154 
   187155 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
   187156 static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
   187157 static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
   187158 
   187159 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
   187160 
   187161 static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
   187162 static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
   187163 
   187164 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
   187165 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
   187166 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
   187167 
   187168 static int sqlite3Fts5StorageSync(Fts5Storage *p);
   187169 static int sqlite3Fts5StorageRollback(Fts5Storage *p);
   187170 
   187171 static int sqlite3Fts5StorageConfigValue(
   187172     Fts5Storage *p, const char*, sqlite3_value*, int
   187173 );
   187174 
   187175 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
   187176 static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
   187177 static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
   187178 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
   187179 static int sqlite3Fts5StorageReset(Fts5Storage *p);
   187180 
   187181 /*
   187182 ** End of interface to code in fts5_storage.c.
   187183 **************************************************************************/
   187184 
   187185 
   187186 /**************************************************************************
   187187 ** Interface to code in fts5_expr.c.
   187188 */
   187189 typedef struct Fts5Expr Fts5Expr;
   187190 typedef struct Fts5ExprNode Fts5ExprNode;
   187191 typedef struct Fts5Parse Fts5Parse;
   187192 typedef struct Fts5Token Fts5Token;
   187193 typedef struct Fts5ExprPhrase Fts5ExprPhrase;
   187194 typedef struct Fts5ExprNearset Fts5ExprNearset;
   187195 
   187196 struct Fts5Token {
   187197   const char *p;                  /* Token text (not NULL terminated) */
   187198   int n;                          /* Size of buffer p in bytes */
   187199 };
   187200 
   187201 /* Parse a MATCH expression. */
   187202 static int sqlite3Fts5ExprNew(
   187203   Fts5Config *pConfig,
   187204   int iCol,                       /* Column on LHS of MATCH operator */
   187205   const char *zExpr,
   187206   Fts5Expr **ppNew,
   187207   char **pzErr
   187208 );
   187209 
   187210 /*
   187211 ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
   187212 **     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
   187213 **     rc = sqlite3Fts5ExprNext(pExpr)
   187214 ** ){
   187215 **   // The document with rowid iRowid matches the expression!
   187216 **   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
   187217 ** }
   187218 */
   187219 static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
   187220 static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
   187221 static int sqlite3Fts5ExprEof(Fts5Expr*);
   187222 static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
   187223 
   187224 static void sqlite3Fts5ExprFree(Fts5Expr*);
   187225 
   187226 /* Called during startup to register a UDF with SQLite */
   187227 static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
   187228 
   187229 static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
   187230 static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
   187231 static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
   187232 
   187233 typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
   187234 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
   187235 static int sqlite3Fts5ExprPopulatePoslists(
   187236     Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
   187237 );
   187238 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
   187239 
   187240 static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
   187241 
   187242 static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
   187243 
   187244 /*******************************************
   187245 ** The fts5_expr.c API above this point is used by the other hand-written
   187246 ** C code in this module. The interfaces below this point are called by
   187247 ** the parser code in fts5parse.y.  */
   187248 
   187249 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
   187250 
   187251 static Fts5ExprNode *sqlite3Fts5ParseNode(
   187252   Fts5Parse *pParse,
   187253   int eType,
   187254   Fts5ExprNode *pLeft,
   187255   Fts5ExprNode *pRight,
   187256   Fts5ExprNearset *pNear
   187257 );
   187258 
   187259 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
   187260   Fts5Parse *pParse,
   187261   Fts5ExprNode *pLeft,
   187262   Fts5ExprNode *pRight
   187263 );
   187264 
   187265 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
   187266   Fts5Parse *pParse,
   187267   Fts5ExprPhrase *pPhrase,
   187268   Fts5Token *pToken,
   187269   int bPrefix
   187270 );
   187271 
   187272 static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
   187273 
   187274 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
   187275   Fts5Parse*,
   187276   Fts5ExprNearset*,
   187277   Fts5ExprPhrase*
   187278 );
   187279 
   187280 static Fts5Colset *sqlite3Fts5ParseColset(
   187281   Fts5Parse*,
   187282   Fts5Colset*,
   187283   Fts5Token *
   187284 );
   187285 
   187286 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
   187287 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
   187288 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
   187289 
   187290 static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
   187291 static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
   187292 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
   187293 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
   187294 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
   187295 
   187296 /*
   187297 ** End of interface to code in fts5_expr.c.
   187298 **************************************************************************/
   187299 
   187300 
   187301 
   187302 /**************************************************************************
   187303 ** Interface to code in fts5_aux.c.
   187304 */
   187305 
   187306 static int sqlite3Fts5AuxInit(fts5_api*);
   187307 /*
   187308 ** End of interface to code in fts5_aux.c.
   187309 **************************************************************************/
   187310 
   187311 /**************************************************************************
   187312 ** Interface to code in fts5_tokenizer.c.
   187313 */
   187314 
   187315 static int sqlite3Fts5TokenizerInit(fts5_api*);
   187316 /*
   187317 ** End of interface to code in fts5_tokenizer.c.
   187318 **************************************************************************/
   187319 
   187320 /**************************************************************************
   187321 ** Interface to code in fts5_vocab.c.
   187322 */
   187323 
   187324 static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
   187325 
   187326 /*
   187327 ** End of interface to code in fts5_vocab.c.
   187328 **************************************************************************/
   187329 
   187330 
   187331 /**************************************************************************
   187332 ** Interface to automatically generated code in fts5_unicode2.c.
   187333 */
   187334 static int sqlite3Fts5UnicodeIsalnum(int c);
   187335 static int sqlite3Fts5UnicodeIsdiacritic(int c);
   187336 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
   187337 /*
   187338 ** End of interface to code in fts5_unicode2.c.
   187339 **************************************************************************/
   187340 
   187341 #endif
   187342 
   187343 #define FTS5_OR                               1
   187344 #define FTS5_AND                              2
   187345 #define FTS5_NOT                              3
   187346 #define FTS5_TERM                             4
   187347 #define FTS5_COLON                            5
   187348 #define FTS5_MINUS                            6
   187349 #define FTS5_LCP                              7
   187350 #define FTS5_RCP                              8
   187351 #define FTS5_STRING                           9
   187352 #define FTS5_LP                              10
   187353 #define FTS5_RP                              11
   187354 #define FTS5_CARET                           12
   187355 #define FTS5_COMMA                           13
   187356 #define FTS5_PLUS                            14
   187357 #define FTS5_STAR                            15
   187358 
   187359 /*
   187360 ** 2000-05-29
   187361 **
   187362 ** The author disclaims copyright to this source code.  In place of
   187363 ** a legal notice, here is a blessing:
   187364 **
   187365 **    May you do good and not evil.
   187366 **    May you find forgiveness for yourself and forgive others.
   187367 **    May you share freely, never taking more than you give.
   187368 **
   187369 *************************************************************************
   187370 ** Driver template for the LEMON parser generator.
   187371 **
   187372 ** The "lemon" program processes an LALR(1) input grammar file, then uses
   187373 ** this template to construct a parser.  The "lemon" program inserts text
   187374 ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
   187375 ** interstitial "-" characters) contained in this template is changed into
   187376 ** the value of the %name directive from the grammar.  Otherwise, the content
   187377 ** of this template is copied straight through into the generate parser
   187378 ** source file.
   187379 **
   187380 ** The following is the concatenation of all %include directives from the
   187381 ** input grammar file:
   187382 */
   187383 /* #include <stdio.h> */
   187384 /************ Begin %include sections from the grammar ************************/
   187385 
   187386 /* #include "fts5Int.h" */
   187387 /* #include "fts5parse.h" */
   187388 
   187389 /*
   187390 ** Disable all error recovery processing in the parser push-down
   187391 ** automaton.
   187392 */
   187393 #define fts5YYNOERRORRECOVERY 1
   187394 
   187395 /*
   187396 ** Make fts5yytestcase() the same as testcase()
   187397 */
   187398 #define fts5yytestcase(X) testcase(X)
   187399 
   187400 /*
   187401 ** Indicate that sqlite3ParserFree() will never be called with a null
   187402 ** pointer.
   187403 */
   187404 #define fts5YYPARSEFREENOTNULL 1
   187405 
   187406 /*
   187407 ** Alternative datatype for the argument to the malloc() routine passed
   187408 ** into sqlite3ParserAlloc().  The default is size_t.
   187409 */
   187410 #define fts5YYMALLOCARGTYPE  u64
   187411 
   187412 /**************** End of %include directives **********************************/
   187413 /* These constants specify the various numeric values for terminal symbols
   187414 ** in a format understandable to "makeheaders".  This section is blank unless
   187415 ** "lemon" is run with the "-m" command-line option.
   187416 ***************** Begin makeheaders token definitions *************************/
   187417 /**************** End makeheaders token definitions ***************************/
   187418 
   187419 /* The next sections is a series of control #defines.
   187420 ** various aspects of the generated parser.
   187421 **    fts5YYCODETYPE         is the data type used to store the integer codes
   187422 **                       that represent terminal and non-terminal symbols.
   187423 **                       "unsigned char" is used if there are fewer than
   187424 **                       256 symbols.  Larger types otherwise.
   187425 **    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
   187426 **                       any terminal or nonterminal symbol.
   187427 **    fts5YYFALLBACK         If defined, this indicates that one or more tokens
   187428 **                       (also known as: "terminal symbols") have fall-back
   187429 **                       values which should be used if the original symbol
   187430 **                       would not parse.  This permits keywords to sometimes
   187431 **                       be used as identifiers, for example.
   187432 **    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
   187433 **                       that indicate what to do in response to the next
   187434 **                       token.
   187435 **    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
   187436 **                       symbols.  Background: A "minor type" is a semantic
   187437 **                       value associated with a terminal or non-terminal
   187438 **                       symbols.  For example, for an "ID" terminal symbol,
   187439 **                       the minor type might be the name of the identifier.
   187440 **                       Each non-terminal can have a different minor type.
   187441 **                       Terminal symbols all have the same minor type, though.
   187442 **                       This macros defines the minor type for terminal
   187443 **                       symbols.
   187444 **    fts5YYMINORTYPE        is the data type used for all minor types.
   187445 **                       This is typically a union of many types, one of
   187446 **                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
   187447 **                       for terminal symbols is called "fts5yy0".
   187448 **    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   187449 **                       zero the stack is dynamically sized using realloc()
   187450 **    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
   187451 **    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
   187452 **    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
   187453 **    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
   187454 **    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
   187455 **                       defined, then do no error processing.
   187456 **    fts5YYNSTATE           the combined number of states.
   187457 **    fts5YYNRULE            the number of rules in the grammar
   187458 **    fts5YYNFTS5TOKEN           Number of terminal symbols
   187459 **    fts5YY_MAX_SHIFT       Maximum value for shift actions
   187460 **    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
   187461 **    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
   187462 **    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
   187463 **    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
   187464 **    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
   187465 **    fts5YY_MIN_REDUCE      Minimum value for reduce actions
   187466 **    fts5YY_MAX_REDUCE      Maximum value for reduce actions
   187467 */
   187468 #ifndef INTERFACE
   187469 # define INTERFACE 1
   187470 #endif
   187471 /************* Begin control #defines *****************************************/
   187472 #define fts5YYCODETYPE unsigned char
   187473 #define fts5YYNOCODE 29
   187474 #define fts5YYACTIONTYPE unsigned char
   187475 #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
   187476 typedef union {
   187477   int fts5yyinit;
   187478   sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
   187479   int fts5yy4;
   187480   Fts5ExprPhrase* fts5yy11;
   187481   Fts5ExprNearset* fts5yy14;
   187482   Fts5Colset* fts5yy43;
   187483   Fts5ExprNode* fts5yy54;
   187484 } fts5YYMINORTYPE;
   187485 #ifndef fts5YYSTACKDEPTH
   187486 #define fts5YYSTACKDEPTH 100
   187487 #endif
   187488 #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
   187489 #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
   187490 #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
   187491 #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
   187492 #define fts5YYNSTATE             35
   187493 #define fts5YYNRULE              28
   187494 #define fts5YYNFTS5TOKEN             16
   187495 #define fts5YY_MAX_SHIFT         34
   187496 #define fts5YY_MIN_SHIFTREDUCE   52
   187497 #define fts5YY_MAX_SHIFTREDUCE   79
   187498 #define fts5YY_ERROR_ACTION      80
   187499 #define fts5YY_ACCEPT_ACTION     81
   187500 #define fts5YY_NO_ACTION         82
   187501 #define fts5YY_MIN_REDUCE        83
   187502 #define fts5YY_MAX_REDUCE        110
   187503 /************* End control #defines *******************************************/
   187504 
   187505 /* Define the fts5yytestcase() macro to be a no-op if is not already defined
   187506 ** otherwise.
   187507 **
   187508 ** Applications can choose to define fts5yytestcase() in the %include section
   187509 ** to a macro that can assist in verifying code coverage.  For production
   187510 ** code the fts5yytestcase() macro should be turned off.  But it is useful
   187511 ** for testing.
   187512 */
   187513 #ifndef fts5yytestcase
   187514 # define fts5yytestcase(X)
   187515 #endif
   187516 
   187517 
   187518 /* Next are the tables used to determine what action to take based on the
   187519 ** current state and lookahead token.  These tables are used to implement
   187520 ** functions that take a state number and lookahead value and return an
   187521 ** action integer.
   187522 **
   187523 ** Suppose the action integer is N.  Then the action is determined as
   187524 ** follows
   187525 **
   187526 **   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
   187527 **                                      token onto the stack and goto state N.
   187528 **
   187529 **   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
   187530 **     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
   187531 **
   187532 **   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
   187533 **
   187534 **   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
   187535 **
   187536 **   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
   187537 **                                      slots in the fts5yy_action[] table.
   187538 **
   187539 **   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
   187540 **     and fts5YY_MAX_REDUCE
   187541 **
   187542 ** The action table is constructed as a single large table named fts5yy_action[].
   187543 ** Given state S and lookahead X, the action is computed as either:
   187544 **
   187545 **    (A)   N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
   187546 **    (B)   N = fts5yy_default[S]
   187547 **
   187548 ** The (A) formula is preferred.  The B formula is used instead if
   187549 ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
   187550 **
   187551 ** The formulas above are for computing the action when the lookahead is
   187552 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   187553 ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
   187554 ** the fts5yy_shift_ofst[] array.
   187555 **
   187556 ** The following are the tables generated in this section:
   187557 **
   187558 **  fts5yy_action[]        A single table containing all actions.
   187559 **  fts5yy_lookahead[]     A table containing the lookahead for each entry in
   187560 **                     fts5yy_action.  Used to detect hash collisions.
   187561 **  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
   187562 **                     shifting terminals.
   187563 **  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
   187564 **                     shifting non-terminals after a reduce.
   187565 **  fts5yy_default[]       Default action for each state.
   187566 **
   187567 *********** Begin parsing tables **********************************************/
   187568 #define fts5YY_ACTTAB_COUNT (105)
   187569 static const fts5YYACTIONTYPE fts5yy_action[] = {
   187570  /*     0 */    81,   20,   96,    6,   28,   99,   98,   26,   26,   18,
   187571  /*    10 */    96,    6,   28,   17,   98,   56,   26,   19,   96,    6,
   187572  /*    20 */    28,   14,   98,  108,   26,   92,   96,    6,   28,   25,
   187573  /*    30 */    98,   78,   26,   21,   96,    6,   28,  107,   98,   58,
   187574  /*    40 */    26,   29,   96,    6,   28,   32,   98,   22,   26,   24,
   187575  /*    50 */    16,   23,   11,    1,   14,   13,   24,   16,   31,   11,
   187576  /*    60 */     3,   97,   13,   27,    8,   98,   82,   26,    7,    4,
   187577  /*    70 */     5,    3,    4,    5,    3,   83,    4,    5,    3,   63,
   187578  /*    80 */    33,   34,   62,   12,    2,   86,   13,   10,   12,   71,
   187579  /*    90 */    10,   13,   78,    5,    3,   78,    9,   30,   75,   82,
   187580  /*   100 */    54,   57,   53,   57,   15,
   187581 };
   187582 static const fts5YYCODETYPE fts5yy_lookahead[] = {
   187583  /*     0 */    17,   18,   19,   20,   21,   23,   23,   25,   25,   18,
   187584  /*    10 */    19,   20,   21,    7,   23,    9,   25,   18,   19,   20,
   187585  /*    20 */    21,    9,   23,   27,   25,   18,   19,   20,   21,   25,
   187586  /*    30 */    23,   15,   25,   18,   19,   20,   21,   27,   23,    9,
   187587  /*    40 */    25,   18,   19,   20,   21,   14,   23,   22,   25,    6,
   187588  /*    50 */     7,   22,    9,   10,    9,   12,    6,    7,   13,    9,
   187589  /*    60 */     3,   19,   12,   21,    5,   23,   28,   25,    5,    1,
   187590  /*    70 */     2,    3,    1,    2,    3,    0,    1,    2,    3,   11,
   187591  /*    80 */    25,   26,   11,    9,   10,    5,   12,   10,    9,   11,
   187592  /*    90 */    10,   12,   15,    2,    3,   15,   24,   25,    9,   28,
   187593  /*   100 */     8,    9,    8,    9,    9,   28,   28,   28,   28,   28,
   187594  /*   110 */    28,   28,   28,   28,   28,   28,   28,   28,   28,   28,
   187595  /*   120 */    28,
   187596 };
   187597 #define fts5YY_SHIFT_COUNT    (34)
   187598 #define fts5YY_SHIFT_MIN      (0)
   187599 #define fts5YY_SHIFT_MAX      (95)
   187600 static const unsigned char fts5yy_shift_ofst[] = {
   187601  /*     0 */    43,   43,   43,   43,   43,   43,   50,   74,   79,   45,
   187602  /*    10 */    12,   80,   77,   12,   16,   16,   30,   30,   68,   71,
   187603  /*    20 */    75,   91,   92,   94,    6,   31,   31,   59,   63,   57,
   187604  /*    30 */    31,   89,   95,   31,   78,
   187605 };
   187606 #define fts5YY_REDUCE_COUNT (17)
   187607 #define fts5YY_REDUCE_MIN   (-18)
   187608 #define fts5YY_REDUCE_MAX   (72)
   187609 static const signed char fts5yy_reduce_ofst[] = {
   187610  /*     0 */   -17,   -9,   -1,    7,   15,   23,   42,  -18,  -18,   55,
   187611  /*    10 */    72,   -4,   -4,    4,   -4,   10,   25,   29,
   187612 };
   187613 static const fts5YYACTIONTYPE fts5yy_default[] = {
   187614  /*     0 */    80,   80,   80,   80,   80,   80,   95,   80,   80,  105,
   187615  /*    10 */    80,  110,  110,   80,  110,  110,   80,   80,   80,   80,
   187616  /*    20 */    80,   91,   80,   80,   80,  101,  100,   80,   80,   90,
   187617  /*    30 */   103,   80,   80,  104,   80,
   187618 };
   187619 /********** End of lemon-generated parsing tables *****************************/
   187620 
   187621 /* The next table maps tokens (terminal symbols) into fallback tokens.
   187622 ** If a construct like the following:
   187623 **
   187624 **      %fallback ID X Y Z.
   187625 **
   187626 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   187627 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   187628 ** but it does not parse, the type of the token is changed to ID and
   187629 ** the parse is retried before an error is thrown.
   187630 **
   187631 ** This feature can be used, for example, to cause some keywords in a language
   187632 ** to revert to identifiers if they keyword does not apply in the context where
   187633 ** it appears.
   187634 */
   187635 #ifdef fts5YYFALLBACK
   187636 static const fts5YYCODETYPE fts5yyFallback[] = {
   187637 };
   187638 #endif /* fts5YYFALLBACK */
   187639 
   187640 /* The following structure represents a single element of the
   187641 ** parser's stack.  Information stored includes:
   187642 **
   187643 **   +  The state number for the parser at this level of the stack.
   187644 **
   187645 **   +  The value of the token stored at this level of the stack.
   187646 **      (In other words, the "major" token.)
   187647 **
   187648 **   +  The semantic value stored at this level of the stack.  This is
   187649 **      the information used by the action routines in the grammar.
   187650 **      It is sometimes called the "minor" token.
   187651 **
   187652 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
   187653 ** actually contains the reduce action for the second half of the
   187654 ** SHIFTREDUCE.
   187655 */
   187656 struct fts5yyStackEntry {
   187657   fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
   187658   fts5YYCODETYPE major;      /* The major token value.  This is the code
   187659                          ** number for the token at this stack level */
   187660   fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   187661                          ** is the value of the token  */
   187662 };
   187663 typedef struct fts5yyStackEntry fts5yyStackEntry;
   187664 
   187665 /* The state of the parser is completely contained in an instance of
   187666 ** the following structure */
   187667 struct fts5yyParser {
   187668   fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
   187669 #ifdef fts5YYTRACKMAXSTACKDEPTH
   187670   int fts5yyhwm;                    /* High-water mark of the stack */
   187671 #endif
   187672 #ifndef fts5YYNOERRORRECOVERY
   187673   int fts5yyerrcnt;                 /* Shifts left before out of the error */
   187674 #endif
   187675   sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
   187676 #if fts5YYSTACKDEPTH<=0
   187677   int fts5yystksz;                  /* Current side of the stack */
   187678   fts5yyStackEntry *fts5yystack;        /* The parser's stack */
   187679   fts5yyStackEntry fts5yystk0;          /* First stack entry */
   187680 #else
   187681   fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
   187682   fts5yyStackEntry *fts5yystackEnd;            /* Last entry in the stack */
   187683 #endif
   187684 };
   187685 typedef struct fts5yyParser fts5yyParser;
   187686 
   187687 #ifndef NDEBUG
   187688 /* #include <stdio.h> */
   187689 static FILE *fts5yyTraceFILE = 0;
   187690 static char *fts5yyTracePrompt = 0;
   187691 #endif /* NDEBUG */
   187692 
   187693 #ifndef NDEBUG
   187694 /*
   187695 ** Turn parser tracing on by giving a stream to which to write the trace
   187696 ** and a prompt to preface each trace message.  Tracing is turned off
   187697 ** by making either argument NULL
   187698 **
   187699 ** Inputs:
   187700 ** <ul>
   187701 ** <li> A FILE* to which trace output should be written.
   187702 **      If NULL, then tracing is turned off.
   187703 ** <li> A prefix string written at the beginning of every
   187704 **      line of trace output.  If NULL, then tracing is
   187705 **      turned off.
   187706 ** </ul>
   187707 **
   187708 ** Outputs:
   187709 ** None.
   187710 */
   187711 static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   187712   fts5yyTraceFILE = TraceFILE;
   187713   fts5yyTracePrompt = zTracePrompt;
   187714   if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
   187715   else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
   187716 }
   187717 #endif /* NDEBUG */
   187718 
   187719 #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
   187720 /* For tracing shifts, the names of all terminals and nonterminals
   187721 ** are required.  The following table supplies these names */
   187722 static const char *const fts5yyTokenName[] = {
   187723   /*    0 */ "$",
   187724   /*    1 */ "OR",
   187725   /*    2 */ "AND",
   187726   /*    3 */ "NOT",
   187727   /*    4 */ "TERM",
   187728   /*    5 */ "COLON",
   187729   /*    6 */ "MINUS",
   187730   /*    7 */ "LCP",
   187731   /*    8 */ "RCP",
   187732   /*    9 */ "STRING",
   187733   /*   10 */ "LP",
   187734   /*   11 */ "RP",
   187735   /*   12 */ "CARET",
   187736   /*   13 */ "COMMA",
   187737   /*   14 */ "PLUS",
   187738   /*   15 */ "STAR",
   187739   /*   16 */ "error",
   187740   /*   17 */ "input",
   187741   /*   18 */ "expr",
   187742   /*   19 */ "cnearset",
   187743   /*   20 */ "exprlist",
   187744   /*   21 */ "colset",
   187745   /*   22 */ "colsetlist",
   187746   /*   23 */ "nearset",
   187747   /*   24 */ "nearphrases",
   187748   /*   25 */ "phrase",
   187749   /*   26 */ "neardist_opt",
   187750   /*   27 */ "star_opt",
   187751 };
   187752 #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
   187753 
   187754 #ifndef NDEBUG
   187755 /* For tracing reduce actions, the names of all rules are required.
   187756 */
   187757 static const char *const fts5yyRuleName[] = {
   187758  /*   0 */ "input ::= expr",
   187759  /*   1 */ "colset ::= MINUS LCP colsetlist RCP",
   187760  /*   2 */ "colset ::= LCP colsetlist RCP",
   187761  /*   3 */ "colset ::= STRING",
   187762  /*   4 */ "colset ::= MINUS STRING",
   187763  /*   5 */ "colsetlist ::= colsetlist STRING",
   187764  /*   6 */ "colsetlist ::= STRING",
   187765  /*   7 */ "expr ::= expr AND expr",
   187766  /*   8 */ "expr ::= expr OR expr",
   187767  /*   9 */ "expr ::= expr NOT expr",
   187768  /*  10 */ "expr ::= colset COLON LP expr RP",
   187769  /*  11 */ "expr ::= LP expr RP",
   187770  /*  12 */ "expr ::= exprlist",
   187771  /*  13 */ "exprlist ::= cnearset",
   187772  /*  14 */ "exprlist ::= exprlist cnearset",
   187773  /*  15 */ "cnearset ::= nearset",
   187774  /*  16 */ "cnearset ::= colset COLON nearset",
   187775  /*  17 */ "nearset ::= phrase",
   187776  /*  18 */ "nearset ::= CARET phrase",
   187777  /*  19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
   187778  /*  20 */ "nearphrases ::= phrase",
   187779  /*  21 */ "nearphrases ::= nearphrases phrase",
   187780  /*  22 */ "neardist_opt ::=",
   187781  /*  23 */ "neardist_opt ::= COMMA STRING",
   187782  /*  24 */ "phrase ::= phrase PLUS STRING star_opt",
   187783  /*  25 */ "phrase ::= STRING star_opt",
   187784  /*  26 */ "star_opt ::= STAR",
   187785  /*  27 */ "star_opt ::=",
   187786 };
   187787 #endif /* NDEBUG */
   187788 
   187789 
   187790 #if fts5YYSTACKDEPTH<=0
   187791 /*
   187792 ** Try to increase the size of the parser stack.  Return the number
   187793 ** of errors.  Return 0 on success.
   187794 */
   187795 static int fts5yyGrowStack(fts5yyParser *p){
   187796   int newSize;
   187797   int idx;
   187798   fts5yyStackEntry *pNew;
   187799 
   187800   newSize = p->fts5yystksz*2 + 100;
   187801   idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
   187802   if( p->fts5yystack==&p->fts5yystk0 ){
   187803     pNew = malloc(newSize*sizeof(pNew[0]));
   187804     if( pNew ) pNew[0] = p->fts5yystk0;
   187805   }else{
   187806     pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
   187807   }
   187808   if( pNew ){
   187809     p->fts5yystack = pNew;
   187810     p->fts5yytos = &p->fts5yystack[idx];
   187811 #ifndef NDEBUG
   187812     if( fts5yyTraceFILE ){
   187813       fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
   187814               fts5yyTracePrompt, p->fts5yystksz, newSize);
   187815     }
   187816 #endif
   187817     p->fts5yystksz = newSize;
   187818   }
   187819   return pNew==0;
   187820 }
   187821 #endif
   187822 
   187823 /* Datatype of the argument to the memory allocated passed as the
   187824 ** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
   187825 ** putting an appropriate #define in the %include section of the input
   187826 ** grammar.
   187827 */
   187828 #ifndef fts5YYMALLOCARGTYPE
   187829 # define fts5YYMALLOCARGTYPE size_t
   187830 #endif
   187831 
   187832 /* Initialize a new parser that has already been allocated.
   187833 */
   187834 static void sqlite3Fts5ParserInit(void *fts5yypParser){
   187835   fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
   187836 #ifdef fts5YYTRACKMAXSTACKDEPTH
   187837   pParser->fts5yyhwm = 0;
   187838 #endif
   187839 #if fts5YYSTACKDEPTH<=0
   187840   pParser->fts5yytos = NULL;
   187841   pParser->fts5yystack = NULL;
   187842   pParser->fts5yystksz = 0;
   187843   if( fts5yyGrowStack(pParser) ){
   187844     pParser->fts5yystack = &pParser->fts5yystk0;
   187845     pParser->fts5yystksz = 1;
   187846   }
   187847 #endif
   187848 #ifndef fts5YYNOERRORRECOVERY
   187849   pParser->fts5yyerrcnt = -1;
   187850 #endif
   187851   pParser->fts5yytos = pParser->fts5yystack;
   187852   pParser->fts5yystack[0].stateno = 0;
   187853   pParser->fts5yystack[0].major = 0;
   187854 #if fts5YYSTACKDEPTH>0
   187855   pParser->fts5yystackEnd = &pParser->fts5yystack[fts5YYSTACKDEPTH-1];
   187856 #endif
   187857 }
   187858 
   187859 #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
   187860 /*
   187861 ** This function allocates a new parser.
   187862 ** The only argument is a pointer to a function which works like
   187863 ** malloc.
   187864 **
   187865 ** Inputs:
   187866 ** A pointer to the function used to allocate memory.
   187867 **
   187868 ** Outputs:
   187869 ** A pointer to a parser.  This pointer is used in subsequent calls
   187870 ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
   187871 */
   187872 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
   187873   fts5yyParser *pParser;
   187874   pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
   187875   if( pParser ) sqlite3Fts5ParserInit(pParser);
   187876   return pParser;
   187877 }
   187878 #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
   187879 
   187880 
   187881 /* The following function deletes the "minor type" or semantic value
   187882 ** associated with a symbol.  The symbol can be either a terminal
   187883 ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
   187884 ** a pointer to the value to be deleted.  The code used to do the
   187885 ** deletions is derived from the %destructor and/or %token_destructor
   187886 ** directives of the input grammar.
   187887 */
   187888 static void fts5yy_destructor(
   187889   fts5yyParser *fts5yypParser,    /* The parser */
   187890   fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
   187891   fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
   187892 ){
   187893   sqlite3Fts5ParserARG_FETCH;
   187894   switch( fts5yymajor ){
   187895     /* Here is inserted the actions which take place when a
   187896     ** terminal or non-terminal is destroyed.  This can happen
   187897     ** when the symbol is popped from the stack during a
   187898     ** reduce or during error processing or when a parser is
   187899     ** being destroyed before it is finished parsing.
   187900     **
   187901     ** Note: during a reduce, the only symbols destroyed are those
   187902     ** which appear on the RHS of the rule, but which are *not* used
   187903     ** inside the C code.
   187904     */
   187905 /********* Begin destructor definitions ***************************************/
   187906     case 17: /* input */
   187907 {
   187908  (void)pParse;
   187909 }
   187910       break;
   187911     case 18: /* expr */
   187912     case 19: /* cnearset */
   187913     case 20: /* exprlist */
   187914 {
   187915  sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy54));
   187916 }
   187917       break;
   187918     case 21: /* colset */
   187919     case 22: /* colsetlist */
   187920 {
   187921  sqlite3_free((fts5yypminor->fts5yy43));
   187922 }
   187923       break;
   187924     case 23: /* nearset */
   187925     case 24: /* nearphrases */
   187926 {
   187927  sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy14));
   187928 }
   187929       break;
   187930     case 25: /* phrase */
   187931 {
   187932  sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
   187933 }
   187934       break;
   187935 /********* End destructor definitions *****************************************/
   187936     default:  break;   /* If no destructor action specified: do nothing */
   187937   }
   187938 }
   187939 
   187940 /*
   187941 ** Pop the parser's stack once.
   187942 **
   187943 ** If there is a destructor routine associated with the token which
   187944 ** is popped from the stack, then call it.
   187945 */
   187946 static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
   187947   fts5yyStackEntry *fts5yytos;
   187948   assert( pParser->fts5yytos!=0 );
   187949   assert( pParser->fts5yytos > pParser->fts5yystack );
   187950   fts5yytos = pParser->fts5yytos--;
   187951 #ifndef NDEBUG
   187952   if( fts5yyTraceFILE ){
   187953     fprintf(fts5yyTraceFILE,"%sPopping %s\n",
   187954       fts5yyTracePrompt,
   187955       fts5yyTokenName[fts5yytos->major]);
   187956   }
   187957 #endif
   187958   fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
   187959 }
   187960 
   187961 /*
   187962 ** Clear all secondary memory allocations from the parser
   187963 */
   187964 static void sqlite3Fts5ParserFinalize(void *p){
   187965   fts5yyParser *pParser = (fts5yyParser*)p;
   187966   while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
   187967 #if fts5YYSTACKDEPTH<=0
   187968   if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
   187969 #endif
   187970 }
   187971 
   187972 #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
   187973 /*
   187974 ** Deallocate and destroy a parser.  Destructors are called for
   187975 ** all stack elements before shutting the parser down.
   187976 **
   187977 ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
   187978 ** is defined in a %include section of the input grammar) then it is
   187979 ** assumed that the input pointer is never NULL.
   187980 */
   187981 static void sqlite3Fts5ParserFree(
   187982   void *p,                    /* The parser to be deleted */
   187983   void (*freeProc)(void*)     /* Function used to reclaim memory */
   187984 ){
   187985 #ifndef fts5YYPARSEFREENEVERNULL
   187986   if( p==0 ) return;
   187987 #endif
   187988   sqlite3Fts5ParserFinalize(p);
   187989   (*freeProc)(p);
   187990 }
   187991 #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
   187992 
   187993 /*
   187994 ** Return the peak depth of the stack for a parser.
   187995 */
   187996 #ifdef fts5YYTRACKMAXSTACKDEPTH
   187997 static int sqlite3Fts5ParserStackPeak(void *p){
   187998   fts5yyParser *pParser = (fts5yyParser*)p;
   187999   return pParser->fts5yyhwm;
   188000 }
   188001 #endif
   188002 
   188003 /* This array of booleans keeps track of the parser statement
   188004 ** coverage.  The element fts5yycoverage[X][Y] is set when the parser
   188005 ** is in state X and has a lookahead token Y.  In a well-tested
   188006 ** systems, every element of this matrix should end up being set.
   188007 */
   188008 #if defined(fts5YYCOVERAGE)
   188009 static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
   188010 #endif
   188011 
   188012 /*
   188013 ** Write into out a description of every state/lookahead combination that
   188014 **
   188015 **   (1)  has not been used by the parser, and
   188016 **   (2)  is not a syntax error.
   188017 **
   188018 ** Return the number of missed state/lookahead combinations.
   188019 */
   188020 #if defined(fts5YYCOVERAGE)
   188021 static int sqlite3Fts5ParserCoverage(FILE *out){
   188022   int stateno, iLookAhead, i;
   188023   int nMissed = 0;
   188024   for(stateno=0; stateno<fts5YYNSTATE; stateno++){
   188025     i = fts5yy_shift_ofst[stateno];
   188026     for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
   188027       if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
   188028       if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
   188029       if( out ){
   188030         fprintf(out,"State %d lookahead %s %s\n", stateno,
   188031                 fts5yyTokenName[iLookAhead],
   188032                 fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
   188033       }
   188034     }
   188035   }
   188036   return nMissed;
   188037 }
   188038 #endif
   188039 
   188040 /*
   188041 ** Find the appropriate action for a parser given the terminal
   188042 ** look-ahead token iLookAhead.
   188043 */
   188044 static unsigned int fts5yy_find_shift_action(
   188045   fts5yyParser *pParser,        /* The parser */
   188046   fts5YYCODETYPE iLookAhead     /* The look-ahead token */
   188047 ){
   188048   int i;
   188049   int stateno = pParser->fts5yytos->stateno;
   188050 
   188051   if( stateno>fts5YY_MAX_SHIFT ) return stateno;
   188052   assert( stateno <= fts5YY_SHIFT_COUNT );
   188053 #if defined(fts5YYCOVERAGE)
   188054   fts5yycoverage[stateno][iLookAhead] = 1;
   188055 #endif
   188056   do{
   188057     i = fts5yy_shift_ofst[stateno];
   188058     assert( i>=0 && i+fts5YYNFTS5TOKEN<=sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0]) );
   188059     assert( iLookAhead!=fts5YYNOCODE );
   188060     assert( iLookAhead < fts5YYNFTS5TOKEN );
   188061     i += iLookAhead;
   188062     if( fts5yy_lookahead[i]!=iLookAhead ){
   188063 #ifdef fts5YYFALLBACK
   188064       fts5YYCODETYPE iFallback;            /* Fallback token */
   188065       if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
   188066              && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
   188067 #ifndef NDEBUG
   188068         if( fts5yyTraceFILE ){
   188069           fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
   188070              fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
   188071         }
   188072 #endif
   188073         assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
   188074         iLookAhead = iFallback;
   188075         continue;
   188076       }
   188077 #endif
   188078 #ifdef fts5YYWILDCARD
   188079       {
   188080         int j = i - iLookAhead + fts5YYWILDCARD;
   188081         if(
   188082 #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
   188083           j>=0 &&
   188084 #endif
   188085 #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
   188086           j<fts5YY_ACTTAB_COUNT &&
   188087 #endif
   188088           fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
   188089         ){
   188090 #ifndef NDEBUG
   188091           if( fts5yyTraceFILE ){
   188092             fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
   188093                fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
   188094                fts5yyTokenName[fts5YYWILDCARD]);
   188095           }
   188096 #endif /* NDEBUG */
   188097           return fts5yy_action[j];
   188098         }
   188099       }
   188100 #endif /* fts5YYWILDCARD */
   188101       return fts5yy_default[stateno];
   188102     }else{
   188103       return fts5yy_action[i];
   188104     }
   188105   }while(1);
   188106 }
   188107 
   188108 /*
   188109 ** Find the appropriate action for a parser given the non-terminal
   188110 ** look-ahead token iLookAhead.
   188111 */
   188112 static int fts5yy_find_reduce_action(
   188113   int stateno,              /* Current state number */
   188114   fts5YYCODETYPE iLookAhead     /* The look-ahead token */
   188115 ){
   188116   int i;
   188117 #ifdef fts5YYERRORSYMBOL
   188118   if( stateno>fts5YY_REDUCE_COUNT ){
   188119     return fts5yy_default[stateno];
   188120   }
   188121 #else
   188122   assert( stateno<=fts5YY_REDUCE_COUNT );
   188123 #endif
   188124   i = fts5yy_reduce_ofst[stateno];
   188125   assert( iLookAhead!=fts5YYNOCODE );
   188126   i += iLookAhead;
   188127 #ifdef fts5YYERRORSYMBOL
   188128   if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
   188129     return fts5yy_default[stateno];
   188130   }
   188131 #else
   188132   assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
   188133   assert( fts5yy_lookahead[i]==iLookAhead );
   188134 #endif
   188135   return fts5yy_action[i];
   188136 }
   188137 
   188138 /*
   188139 ** The following routine is called if the stack overflows.
   188140 */
   188141 static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
   188142    sqlite3Fts5ParserARG_FETCH;
   188143 #ifndef NDEBUG
   188144    if( fts5yyTraceFILE ){
   188145      fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
   188146    }
   188147 #endif
   188148    while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
   188149    /* Here code is inserted which will execute if the parser
   188150    ** stack every overflows */
   188151 /******** Begin %stack_overflow code ******************************************/
   188152 
   188153   sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
   188154 /******** End %stack_overflow code ********************************************/
   188155    sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   188156 }
   188157 
   188158 /*
   188159 ** Print tracing information for a SHIFT action
   188160 */
   188161 #ifndef NDEBUG
   188162 static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
   188163   if( fts5yyTraceFILE ){
   188164     if( fts5yyNewState<fts5YYNSTATE ){
   188165       fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
   188166          fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
   188167          fts5yyNewState);
   188168     }else{
   188169       fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
   188170          fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
   188171          fts5yyNewState - fts5YY_MIN_REDUCE);
   188172     }
   188173   }
   188174 }
   188175 #else
   188176 # define fts5yyTraceShift(X,Y,Z)
   188177 #endif
   188178 
   188179 /*
   188180 ** Perform a shift action.
   188181 */
   188182 static void fts5yy_shift(
   188183   fts5yyParser *fts5yypParser,          /* The parser to be shifted */
   188184   int fts5yyNewState,               /* The new state to shift in */
   188185   int fts5yyMajor,                  /* The major token to shift in */
   188186   sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
   188187 ){
   188188   fts5yyStackEntry *fts5yytos;
   188189   fts5yypParser->fts5yytos++;
   188190 #ifdef fts5YYTRACKMAXSTACKDEPTH
   188191   if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
   188192     fts5yypParser->fts5yyhwm++;
   188193     assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
   188194   }
   188195 #endif
   188196 #if fts5YYSTACKDEPTH>0
   188197   if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
   188198     fts5yypParser->fts5yytos--;
   188199     fts5yyStackOverflow(fts5yypParser);
   188200     return;
   188201   }
   188202 #else
   188203   if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
   188204     if( fts5yyGrowStack(fts5yypParser) ){
   188205       fts5yypParser->fts5yytos--;
   188206       fts5yyStackOverflow(fts5yypParser);
   188207       return;
   188208     }
   188209   }
   188210 #endif
   188211   if( fts5yyNewState > fts5YY_MAX_SHIFT ){
   188212     fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
   188213   }
   188214   fts5yytos = fts5yypParser->fts5yytos;
   188215   fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
   188216   fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
   188217   fts5yytos->minor.fts5yy0 = fts5yyMinor;
   188218   fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
   188219 }
   188220 
   188221 /* The following table contains information about every rule that
   188222 ** is used during the reduce.
   188223 */
   188224 static const struct {
   188225   fts5YYCODETYPE lhs;       /* Symbol on the left-hand side of the rule */
   188226   signed char nrhs;     /* Negative of the number of RHS symbols in the rule */
   188227 } fts5yyRuleInfo[] = {
   188228   {   17,   -1 }, /* (0) input ::= expr */
   188229   {   21,   -4 }, /* (1) colset ::= MINUS LCP colsetlist RCP */
   188230   {   21,   -3 }, /* (2) colset ::= LCP colsetlist RCP */
   188231   {   21,   -1 }, /* (3) colset ::= STRING */
   188232   {   21,   -2 }, /* (4) colset ::= MINUS STRING */
   188233   {   22,   -2 }, /* (5) colsetlist ::= colsetlist STRING */
   188234   {   22,   -1 }, /* (6) colsetlist ::= STRING */
   188235   {   18,   -3 }, /* (7) expr ::= expr AND expr */
   188236   {   18,   -3 }, /* (8) expr ::= expr OR expr */
   188237   {   18,   -3 }, /* (9) expr ::= expr NOT expr */
   188238   {   18,   -5 }, /* (10) expr ::= colset COLON LP expr RP */
   188239   {   18,   -3 }, /* (11) expr ::= LP expr RP */
   188240   {   18,   -1 }, /* (12) expr ::= exprlist */
   188241   {   20,   -1 }, /* (13) exprlist ::= cnearset */
   188242   {   20,   -2 }, /* (14) exprlist ::= exprlist cnearset */
   188243   {   19,   -1 }, /* (15) cnearset ::= nearset */
   188244   {   19,   -3 }, /* (16) cnearset ::= colset COLON nearset */
   188245   {   23,   -1 }, /* (17) nearset ::= phrase */
   188246   {   23,   -2 }, /* (18) nearset ::= CARET phrase */
   188247   {   23,   -5 }, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
   188248   {   24,   -1 }, /* (20) nearphrases ::= phrase */
   188249   {   24,   -2 }, /* (21) nearphrases ::= nearphrases phrase */
   188250   {   26,    0 }, /* (22) neardist_opt ::= */
   188251   {   26,   -2 }, /* (23) neardist_opt ::= COMMA STRING */
   188252   {   25,   -4 }, /* (24) phrase ::= phrase PLUS STRING star_opt */
   188253   {   25,   -2 }, /* (25) phrase ::= STRING star_opt */
   188254   {   27,   -1 }, /* (26) star_opt ::= STAR */
   188255   {   27,    0 }, /* (27) star_opt ::= */
   188256 };
   188257 
   188258 static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
   188259 
   188260 /*
   188261 ** Perform a reduce action and the shift that must immediately
   188262 ** follow the reduce.
   188263 **
   188264 ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
   188265 ** access to the lookahead token (if any).  The fts5yyLookahead will be fts5YYNOCODE
   188266 ** if the lookahead token has already been consumed.  As this procedure is
   188267 ** only called from one place, optimizing compilers will in-line it, which
   188268 ** means that the extra parameters have no performance impact.
   188269 */
   188270 static void fts5yy_reduce(
   188271   fts5yyParser *fts5yypParser,         /* The parser */
   188272   unsigned int fts5yyruleno,       /* Number of the rule by which to reduce */
   188273   int fts5yyLookahead,             /* Lookahead token, or fts5YYNOCODE if none */
   188274   sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken  /* Value of the lookahead token */
   188275 ){
   188276   int fts5yygoto;                     /* The next state */
   188277   int fts5yyact;                      /* The next action */
   188278   fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
   188279   int fts5yysize;                     /* Amount to pop the stack */
   188280   sqlite3Fts5ParserARG_FETCH;
   188281   (void)fts5yyLookahead;
   188282   (void)fts5yyLookaheadToken;
   188283   fts5yymsp = fts5yypParser->fts5yytos;
   188284 #ifndef NDEBUG
   188285   if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
   188286     fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
   188287     if( fts5yysize ){
   188288       fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
   188289         fts5yyTracePrompt,
   188290         fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
   188291     }else{
   188292       fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
   188293         fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
   188294     }
   188295   }
   188296 #endif /* NDEBUG */
   188297 
   188298   /* Check that the stack is large enough to grow by a single entry
   188299   ** if the RHS of the rule is empty.  This ensures that there is room
   188300   ** enough on the stack to push the LHS value */
   188301   if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
   188302 #ifdef fts5YYTRACKMAXSTACKDEPTH
   188303     if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
   188304       fts5yypParser->fts5yyhwm++;
   188305       assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
   188306     }
   188307 #endif
   188308 #if fts5YYSTACKDEPTH>0
   188309     if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
   188310       fts5yyStackOverflow(fts5yypParser);
   188311       return;
   188312     }
   188313 #else
   188314     if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
   188315       if( fts5yyGrowStack(fts5yypParser) ){
   188316         fts5yyStackOverflow(fts5yypParser);
   188317         return;
   188318       }
   188319       fts5yymsp = fts5yypParser->fts5yytos;
   188320     }
   188321 #endif
   188322   }
   188323 
   188324   switch( fts5yyruleno ){
   188325   /* Beginning here are the reduction cases.  A typical example
   188326   ** follows:
   188327   **   case 0:
   188328   **  #line <lineno> <grammarfile>
   188329   **     { ... }           // User supplied code
   188330   **  #line <lineno> <thisfile>
   188331   **     break;
   188332   */
   188333 /********** Begin reduce actions **********************************************/
   188334         fts5YYMINORTYPE fts5yylhsminor;
   188335       case 0: /* input ::= expr */
   188336 { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy54); }
   188337         break;
   188338       case 1: /* colset ::= MINUS LCP colsetlist RCP */
   188339 {
   188340     fts5yymsp[-3].minor.fts5yy43 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy43);
   188341 }
   188342         break;
   188343       case 2: /* colset ::= LCP colsetlist RCP */
   188344 { fts5yymsp[-2].minor.fts5yy43 = fts5yymsp[-1].minor.fts5yy43; }
   188345         break;
   188346       case 3: /* colset ::= STRING */
   188347 {
   188348   fts5yylhsminor.fts5yy43 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
   188349 }
   188350   fts5yymsp[0].minor.fts5yy43 = fts5yylhsminor.fts5yy43;
   188351         break;
   188352       case 4: /* colset ::= MINUS STRING */
   188353 {
   188354   fts5yymsp[-1].minor.fts5yy43 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
   188355   fts5yymsp[-1].minor.fts5yy43 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy43);
   188356 }
   188357         break;
   188358       case 5: /* colsetlist ::= colsetlist STRING */
   188359 {
   188360   fts5yylhsminor.fts5yy43 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy43, &fts5yymsp[0].minor.fts5yy0); }
   188361   fts5yymsp[-1].minor.fts5yy43 = fts5yylhsminor.fts5yy43;
   188362         break;
   188363       case 6: /* colsetlist ::= STRING */
   188364 {
   188365   fts5yylhsminor.fts5yy43 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
   188366 }
   188367   fts5yymsp[0].minor.fts5yy43 = fts5yylhsminor.fts5yy43;
   188368         break;
   188369       case 7: /* expr ::= expr AND expr */
   188370 {
   188371   fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54, 0);
   188372 }
   188373   fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188374         break;
   188375       case 8: /* expr ::= expr OR expr */
   188376 {
   188377   fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54, 0);
   188378 }
   188379   fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188380         break;
   188381       case 9: /* expr ::= expr NOT expr */
   188382 {
   188383   fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54, 0);
   188384 }
   188385   fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188386         break;
   188387       case 10: /* expr ::= colset COLON LP expr RP */
   188388 {
   188389   sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy54, fts5yymsp[-4].minor.fts5yy43);
   188390   fts5yylhsminor.fts5yy54 = fts5yymsp[-1].minor.fts5yy54;
   188391 }
   188392   fts5yymsp[-4].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188393         break;
   188394       case 11: /* expr ::= LP expr RP */
   188395 {fts5yymsp[-2].minor.fts5yy54 = fts5yymsp[-1].minor.fts5yy54;}
   188396         break;
   188397       case 12: /* expr ::= exprlist */
   188398       case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
   188399 {fts5yylhsminor.fts5yy54 = fts5yymsp[0].minor.fts5yy54;}
   188400   fts5yymsp[0].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188401         break;
   188402       case 14: /* exprlist ::= exprlist cnearset */
   188403 {
   188404   fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54);
   188405 }
   188406   fts5yymsp[-1].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188407         break;
   188408       case 15: /* cnearset ::= nearset */
   188409 {
   188410   fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy14);
   188411 }
   188412   fts5yymsp[0].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188413         break;
   188414       case 16: /* cnearset ::= colset COLON nearset */
   188415 {
   188416   fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy14);
   188417   sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy54, fts5yymsp[-2].minor.fts5yy43);
   188418 }
   188419   fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
   188420         break;
   188421       case 17: /* nearset ::= phrase */
   188422 { fts5yylhsminor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
   188423   fts5yymsp[0].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
   188424         break;
   188425       case 18: /* nearset ::= CARET phrase */
   188426 {
   188427   sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy11);
   188428   fts5yymsp[-1].minor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
   188429 }
   188430         break;
   188431       case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
   188432 {
   188433   sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
   188434   sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy14, &fts5yymsp[-1].minor.fts5yy0);
   188435   fts5yylhsminor.fts5yy14 = fts5yymsp[-2].minor.fts5yy14;
   188436 }
   188437   fts5yymsp[-4].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
   188438         break;
   188439       case 20: /* nearphrases ::= phrase */
   188440 {
   188441   fts5yylhsminor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
   188442 }
   188443   fts5yymsp[0].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
   188444         break;
   188445       case 21: /* nearphrases ::= nearphrases phrase */
   188446 {
   188447   fts5yylhsminor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy14, fts5yymsp[0].minor.fts5yy11);
   188448 }
   188449   fts5yymsp[-1].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
   188450         break;
   188451       case 22: /* neardist_opt ::= */
   188452 { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
   188453         break;
   188454       case 23: /* neardist_opt ::= COMMA STRING */
   188455 { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
   188456         break;
   188457       case 24: /* phrase ::= phrase PLUS STRING star_opt */
   188458 {
   188459   fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
   188460 }
   188461   fts5yymsp[-3].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
   188462         break;
   188463       case 25: /* phrase ::= STRING star_opt */
   188464 {
   188465   fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
   188466 }
   188467   fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
   188468         break;
   188469       case 26: /* star_opt ::= STAR */
   188470 { fts5yymsp[0].minor.fts5yy4 = 1; }
   188471         break;
   188472       case 27: /* star_opt ::= */
   188473 { fts5yymsp[1].minor.fts5yy4 = 0; }
   188474         break;
   188475       default:
   188476         break;
   188477 /********** End reduce actions ************************************************/
   188478   };
   188479   assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
   188480   fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
   188481   fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
   188482   fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
   188483 
   188484   /* There are no SHIFTREDUCE actions on nonterminals because the table
   188485   ** generator has simplified them to pure REDUCE actions. */
   188486   assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
   188487 
   188488   /* It is not possible for a REDUCE to be followed by an error */
   188489   assert( fts5yyact!=fts5YY_ERROR_ACTION );
   188490 
   188491   fts5yymsp += fts5yysize+1;
   188492   fts5yypParser->fts5yytos = fts5yymsp;
   188493   fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
   188494   fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
   188495   fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
   188496 }
   188497 
   188498 /*
   188499 ** The following code executes when the parse fails
   188500 */
   188501 #ifndef fts5YYNOERRORRECOVERY
   188502 static void fts5yy_parse_failed(
   188503   fts5yyParser *fts5yypParser           /* The parser */
   188504 ){
   188505   sqlite3Fts5ParserARG_FETCH;
   188506 #ifndef NDEBUG
   188507   if( fts5yyTraceFILE ){
   188508     fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
   188509   }
   188510 #endif
   188511   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
   188512   /* Here code is inserted which will be executed whenever the
   188513   ** parser fails */
   188514 /************ Begin %parse_failure code ***************************************/
   188515 /************ End %parse_failure code *****************************************/
   188516   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   188517 }
   188518 #endif /* fts5YYNOERRORRECOVERY */
   188519 
   188520 /*
   188521 ** The following code executes when a syntax error first occurs.
   188522 */
   188523 static void fts5yy_syntax_error(
   188524   fts5yyParser *fts5yypParser,           /* The parser */
   188525   int fts5yymajor,                   /* The major type of the error token */
   188526   sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
   188527 ){
   188528   sqlite3Fts5ParserARG_FETCH;
   188529 #define FTS5TOKEN fts5yyminor
   188530 /************ Begin %syntax_error code ****************************************/
   188531 
   188532   UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
   188533   sqlite3Fts5ParseError(
   188534     pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
   188535   );
   188536 /************ End %syntax_error code ******************************************/
   188537   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   188538 }
   188539 
   188540 /*
   188541 ** The following is executed when the parser accepts
   188542 */
   188543 static void fts5yy_accept(
   188544   fts5yyParser *fts5yypParser           /* The parser */
   188545 ){
   188546   sqlite3Fts5ParserARG_FETCH;
   188547 #ifndef NDEBUG
   188548   if( fts5yyTraceFILE ){
   188549     fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
   188550   }
   188551 #endif
   188552 #ifndef fts5YYNOERRORRECOVERY
   188553   fts5yypParser->fts5yyerrcnt = -1;
   188554 #endif
   188555   assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
   188556   /* Here code is inserted which will be executed whenever the
   188557   ** parser accepts */
   188558 /*********** Begin %parse_accept code *****************************************/
   188559 /*********** End %parse_accept code *******************************************/
   188560   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   188561 }
   188562 
   188563 /* The main parser program.
   188564 ** The first argument is a pointer to a structure obtained from
   188565 ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
   188566 ** The second argument is the major token number.  The third is
   188567 ** the minor token.  The fourth optional argument is whatever the
   188568 ** user wants (and specified in the grammar) and is available for
   188569 ** use by the action routines.
   188570 **
   188571 ** Inputs:
   188572 ** <ul>
   188573 ** <li> A pointer to the parser (an opaque structure.)
   188574 ** <li> The major token number.
   188575 ** <li> The minor token number.
   188576 ** <li> An option argument of a grammar-specified type.
   188577 ** </ul>
   188578 **
   188579 ** Outputs:
   188580 ** None.
   188581 */
   188582 static void sqlite3Fts5Parser(
   188583   void *fts5yyp,                   /* The parser */
   188584   int fts5yymajor,                 /* The major token code number */
   188585   sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
   188586   sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
   188587 ){
   188588   fts5YYMINORTYPE fts5yyminorunion;
   188589   unsigned int fts5yyact;   /* The parser action. */
   188590 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
   188591   int fts5yyendofinput;     /* True if we are at the end of input */
   188592 #endif
   188593 #ifdef fts5YYERRORSYMBOL
   188594   int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
   188595 #endif
   188596   fts5yyParser *fts5yypParser;  /* The parser */
   188597 
   188598   fts5yypParser = (fts5yyParser*)fts5yyp;
   188599   assert( fts5yypParser->fts5yytos!=0 );
   188600 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
   188601   fts5yyendofinput = (fts5yymajor==0);
   188602 #endif
   188603   sqlite3Fts5ParserARG_STORE;
   188604 
   188605 #ifndef NDEBUG
   188606   if( fts5yyTraceFILE ){
   188607     int stateno = fts5yypParser->fts5yytos->stateno;
   188608     if( stateno < fts5YY_MIN_REDUCE ){
   188609       fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
   188610               fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],stateno);
   188611     }else{
   188612       fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
   188613               fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],stateno-fts5YY_MIN_REDUCE);
   188614     }
   188615   }
   188616 #endif
   188617 
   188618   do{
   188619     fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
   188620     if( fts5yyact >= fts5YY_MIN_REDUCE ){
   188621       fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,fts5yyminor);
   188622     }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
   188623       fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
   188624 #ifndef fts5YYNOERRORRECOVERY
   188625       fts5yypParser->fts5yyerrcnt--;
   188626 #endif
   188627       fts5yymajor = fts5YYNOCODE;
   188628     }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
   188629       fts5yypParser->fts5yytos--;
   188630       fts5yy_accept(fts5yypParser);
   188631       return;
   188632     }else{
   188633       assert( fts5yyact == fts5YY_ERROR_ACTION );
   188634       fts5yyminorunion.fts5yy0 = fts5yyminor;
   188635 #ifdef fts5YYERRORSYMBOL
   188636       int fts5yymx;
   188637 #endif
   188638 #ifndef NDEBUG
   188639       if( fts5yyTraceFILE ){
   188640         fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
   188641       }
   188642 #endif
   188643 #ifdef fts5YYERRORSYMBOL
   188644       /* A syntax error has occurred.
   188645       ** The response to an error depends upon whether or not the
   188646       ** grammar defines an error token "ERROR".
   188647       **
   188648       ** This is what we do if the grammar does define ERROR:
   188649       **
   188650       **  * Call the %syntax_error function.
   188651       **
   188652       **  * Begin popping the stack until we enter a state where
   188653       **    it is legal to shift the error symbol, then shift
   188654       **    the error symbol.
   188655       **
   188656       **  * Set the error count to three.
   188657       **
   188658       **  * Begin accepting and shifting new tokens.  No new error
   188659       **    processing will occur until three tokens have been
   188660       **    shifted successfully.
   188661       **
   188662       */
   188663       if( fts5yypParser->fts5yyerrcnt<0 ){
   188664         fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
   188665       }
   188666       fts5yymx = fts5yypParser->fts5yytos->major;
   188667       if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
   188668 #ifndef NDEBUG
   188669         if( fts5yyTraceFILE ){
   188670           fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
   188671              fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
   188672         }
   188673 #endif
   188674         fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
   188675         fts5yymajor = fts5YYNOCODE;
   188676       }else{
   188677         while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
   188678             && fts5yymx != fts5YYERRORSYMBOL
   188679             && (fts5yyact = fts5yy_find_reduce_action(
   188680                         fts5yypParser->fts5yytos->stateno,
   188681                         fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
   188682         ){
   188683           fts5yy_pop_parser_stack(fts5yypParser);
   188684         }
   188685         if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
   188686           fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
   188687           fts5yy_parse_failed(fts5yypParser);
   188688 #ifndef fts5YYNOERRORRECOVERY
   188689           fts5yypParser->fts5yyerrcnt = -1;
   188690 #endif
   188691           fts5yymajor = fts5YYNOCODE;
   188692         }else if( fts5yymx!=fts5YYERRORSYMBOL ){
   188693           fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
   188694         }
   188695       }
   188696       fts5yypParser->fts5yyerrcnt = 3;
   188697       fts5yyerrorhit = 1;
   188698 #elif defined(fts5YYNOERRORRECOVERY)
   188699       /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
   188700       ** do any kind of error recovery.  Instead, simply invoke the syntax
   188701       ** error routine and continue going as if nothing had happened.
   188702       **
   188703       ** Applications can set this macro (for example inside %include) if
   188704       ** they intend to abandon the parse upon the first syntax error seen.
   188705       */
   188706       fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
   188707       fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
   188708       fts5yymajor = fts5YYNOCODE;
   188709 
   188710 #else  /* fts5YYERRORSYMBOL is not defined */
   188711       /* This is what we do if the grammar does not define ERROR:
   188712       **
   188713       **  * Report an error message, and throw away the input token.
   188714       **
   188715       **  * If the input token is $, then fail the parse.
   188716       **
   188717       ** As before, subsequent error messages are suppressed until
   188718       ** three input tokens have been successfully shifted.
   188719       */
   188720       if( fts5yypParser->fts5yyerrcnt<=0 ){
   188721         fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
   188722       }
   188723       fts5yypParser->fts5yyerrcnt = 3;
   188724       fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
   188725       if( fts5yyendofinput ){
   188726         fts5yy_parse_failed(fts5yypParser);
   188727 #ifndef fts5YYNOERRORRECOVERY
   188728         fts5yypParser->fts5yyerrcnt = -1;
   188729 #endif
   188730       }
   188731       fts5yymajor = fts5YYNOCODE;
   188732 #endif
   188733     }
   188734   }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
   188735 #ifndef NDEBUG
   188736   if( fts5yyTraceFILE ){
   188737     fts5yyStackEntry *i;
   188738     char cDiv = '[';
   188739     fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
   188740     for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
   188741       fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
   188742       cDiv = ' ';
   188743     }
   188744     fprintf(fts5yyTraceFILE,"]\n");
   188745   }
   188746 #endif
   188747   return;
   188748 }
   188749 
   188750 /*
   188751 ** 2014 May 31
   188752 **
   188753 ** The author disclaims copyright to this source code.  In place of
   188754 ** a legal notice, here is a blessing:
   188755 **
   188756 **    May you do good and not evil.
   188757 **    May you find forgiveness for yourself and forgive others.
   188758 **    May you share freely, never taking more than you give.
   188759 **
   188760 ******************************************************************************
   188761 */
   188762 
   188763 
   188764 /* #include "fts5Int.h" */
   188765 #include <math.h>                 /* amalgamator: keep */
   188766 
   188767 /*
   188768 ** Object used to iterate through all "coalesced phrase instances" in
   188769 ** a single column of the current row. If the phrase instances in the
   188770 ** column being considered do not overlap, this object simply iterates
   188771 ** through them. Or, if they do overlap (share one or more tokens in
   188772 ** common), each set of overlapping instances is treated as a single
   188773 ** match. See documentation for the highlight() auxiliary function for
   188774 ** details.
   188775 **
   188776 ** Usage is:
   188777 **
   188778 **   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
   188779 **      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
   188780 **      rc = fts5CInstIterNext(&iter)
   188781 **   ){
   188782 **     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
   188783 **   }
   188784 **
   188785 */
   188786 typedef struct CInstIter CInstIter;
   188787 struct CInstIter {
   188788   const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
   188789   Fts5Context *pFts;              /* First arg to pass to pApi functions */
   188790   int iCol;                       /* Column to search */
   188791   int iInst;                      /* Next phrase instance index */
   188792   int nInst;                      /* Total number of phrase instances */
   188793 
   188794   /* Output variables */
   188795   int iStart;                     /* First token in coalesced phrase instance */
   188796   int iEnd;                       /* Last token in coalesced phrase instance */
   188797 };
   188798 
   188799 /*
   188800 ** Advance the iterator to the next coalesced phrase instance. Return
   188801 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
   188802 */
   188803 static int fts5CInstIterNext(CInstIter *pIter){
   188804   int rc = SQLITE_OK;
   188805   pIter->iStart = -1;
   188806   pIter->iEnd = -1;
   188807 
   188808   while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
   188809     int ip; int ic; int io;
   188810     rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
   188811     if( rc==SQLITE_OK ){
   188812       if( ic==pIter->iCol ){
   188813         int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
   188814         if( pIter->iStart<0 ){
   188815           pIter->iStart = io;
   188816           pIter->iEnd = iEnd;
   188817         }else if( io<=pIter->iEnd ){
   188818           if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
   188819         }else{
   188820           break;
   188821         }
   188822       }
   188823       pIter->iInst++;
   188824     }
   188825   }
   188826 
   188827   return rc;
   188828 }
   188829 
   188830 /*
   188831 ** Initialize the iterator object indicated by the final parameter to
   188832 ** iterate through coalesced phrase instances in column iCol.
   188833 */
   188834 static int fts5CInstIterInit(
   188835   const Fts5ExtensionApi *pApi,
   188836   Fts5Context *pFts,
   188837   int iCol,
   188838   CInstIter *pIter
   188839 ){
   188840   int rc;
   188841 
   188842   memset(pIter, 0, sizeof(CInstIter));
   188843   pIter->pApi = pApi;
   188844   pIter->pFts = pFts;
   188845   pIter->iCol = iCol;
   188846   rc = pApi->xInstCount(pFts, &pIter->nInst);
   188847 
   188848   if( rc==SQLITE_OK ){
   188849     rc = fts5CInstIterNext(pIter);
   188850   }
   188851 
   188852   return rc;
   188853 }
   188854 
   188855 
   188856 
   188857 /*************************************************************************
   188858 ** Start of highlight() implementation.
   188859 */
   188860 typedef struct HighlightContext HighlightContext;
   188861 struct HighlightContext {
   188862   CInstIter iter;                 /* Coalesced Instance Iterator */
   188863   int iPos;                       /* Current token offset in zIn[] */
   188864   int iRangeStart;                /* First token to include */
   188865   int iRangeEnd;                  /* If non-zero, last token to include */
   188866   const char *zOpen;              /* Opening highlight */
   188867   const char *zClose;             /* Closing highlight */
   188868   const char *zIn;                /* Input text */
   188869   int nIn;                        /* Size of input text in bytes */
   188870   int iOff;                       /* Current offset within zIn[] */
   188871   char *zOut;                     /* Output value */
   188872 };
   188873 
   188874 /*
   188875 ** Append text to the HighlightContext output string - p->zOut. Argument
   188876 ** z points to a buffer containing n bytes of text to append. If n is
   188877 ** negative, everything up until the first '\0' is appended to the output.
   188878 **
   188879 ** If *pRc is set to any value other than SQLITE_OK when this function is
   188880 ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
   188881 ** *pRc is set to an error code before returning.
   188882 */
   188883 static void fts5HighlightAppend(
   188884   int *pRc,
   188885   HighlightContext *p,
   188886   const char *z, int n
   188887 ){
   188888   if( *pRc==SQLITE_OK ){
   188889     if( n<0 ) n = (int)strlen(z);
   188890     p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
   188891     if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
   188892   }
   188893 }
   188894 
   188895 /*
   188896 ** Tokenizer callback used by implementation of highlight() function.
   188897 */
   188898 static int fts5HighlightCb(
   188899   void *pContext,                 /* Pointer to HighlightContext object */
   188900   int tflags,                     /* Mask of FTS5_TOKEN_* flags */
   188901   const char *pToken,             /* Buffer containing token */
   188902   int nToken,                     /* Size of token in bytes */
   188903   int iStartOff,                  /* Start offset of token */
   188904   int iEndOff                     /* End offset of token */
   188905 ){
   188906   HighlightContext *p = (HighlightContext*)pContext;
   188907   int rc = SQLITE_OK;
   188908   int iPos;
   188909 
   188910   UNUSED_PARAM2(pToken, nToken);
   188911 
   188912   if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
   188913   iPos = p->iPos++;
   188914 
   188915   if( p->iRangeEnd>0 ){
   188916     if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
   188917     if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
   188918   }
   188919 
   188920   if( iPos==p->iter.iStart ){
   188921     fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
   188922     fts5HighlightAppend(&rc, p, p->zOpen, -1);
   188923     p->iOff = iStartOff;
   188924   }
   188925 
   188926   if( iPos==p->iter.iEnd ){
   188927     if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
   188928       fts5HighlightAppend(&rc, p, p->zOpen, -1);
   188929     }
   188930     fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
   188931     fts5HighlightAppend(&rc, p, p->zClose, -1);
   188932     p->iOff = iEndOff;
   188933     if( rc==SQLITE_OK ){
   188934       rc = fts5CInstIterNext(&p->iter);
   188935     }
   188936   }
   188937 
   188938   if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
   188939     fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
   188940     p->iOff = iEndOff;
   188941     if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
   188942       fts5HighlightAppend(&rc, p, p->zClose, -1);
   188943     }
   188944   }
   188945 
   188946   return rc;
   188947 }
   188948 
   188949 /*
   188950 ** Implementation of highlight() function.
   188951 */
   188952 static void fts5HighlightFunction(
   188953   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
   188954   Fts5Context *pFts,              /* First arg to pass to pApi functions */
   188955   sqlite3_context *pCtx,          /* Context for returning result/error */
   188956   int nVal,                       /* Number of values in apVal[] array */
   188957   sqlite3_value **apVal           /* Array of trailing arguments */
   188958 ){
   188959   HighlightContext ctx;
   188960   int rc;
   188961   int iCol;
   188962 
   188963   if( nVal!=3 ){
   188964     const char *zErr = "wrong number of arguments to function highlight()";
   188965     sqlite3_result_error(pCtx, zErr, -1);
   188966     return;
   188967   }
   188968 
   188969   iCol = sqlite3_value_int(apVal[0]);
   188970   memset(&ctx, 0, sizeof(HighlightContext));
   188971   ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
   188972   ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
   188973   rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
   188974 
   188975   if( ctx.zIn ){
   188976     if( rc==SQLITE_OK ){
   188977       rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
   188978     }
   188979 
   188980     if( rc==SQLITE_OK ){
   188981       rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
   188982     }
   188983     fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
   188984 
   188985     if( rc==SQLITE_OK ){
   188986       sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
   188987     }
   188988     sqlite3_free(ctx.zOut);
   188989   }
   188990   if( rc!=SQLITE_OK ){
   188991     sqlite3_result_error_code(pCtx, rc);
   188992   }
   188993 }
   188994 /*
   188995 ** End of highlight() implementation.
   188996 **************************************************************************/
   188997 
   188998 /*
   188999 ** Context object passed to the fts5SentenceFinderCb() function.
   189000 */
   189001 typedef struct Fts5SFinder Fts5SFinder;
   189002 struct Fts5SFinder {
   189003   int iPos;                       /* Current token position */
   189004   int nFirstAlloc;                /* Allocated size of aFirst[] */
   189005   int nFirst;                     /* Number of entries in aFirst[] */
   189006   int *aFirst;                    /* Array of first token in each sentence */
   189007   const char *zDoc;               /* Document being tokenized */
   189008 };
   189009 
   189010 /*
   189011 ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
   189012 ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
   189013 ** error occurs.
   189014 */
   189015 static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
   189016   if( p->nFirstAlloc==p->nFirst ){
   189017     int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
   189018     int *aNew;
   189019 
   189020     aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
   189021     if( aNew==0 ) return SQLITE_NOMEM;
   189022     p->aFirst = aNew;
   189023     p->nFirstAlloc = nNew;
   189024   }
   189025   p->aFirst[p->nFirst++] = iAdd;
   189026   return SQLITE_OK;
   189027 }
   189028 
   189029 /*
   189030 ** This function is an xTokenize() callback used by the auxiliary snippet()
   189031 ** function. Its job is to identify tokens that are the first in a sentence.
   189032 ** For each such token, an entry is added to the SFinder.aFirst[] array.
   189033 */
   189034 static int fts5SentenceFinderCb(
   189035   void *pContext,                 /* Pointer to HighlightContext object */
   189036   int tflags,                     /* Mask of FTS5_TOKEN_* flags */
   189037   const char *pToken,             /* Buffer containing token */
   189038   int nToken,                     /* Size of token in bytes */
   189039   int iStartOff,                  /* Start offset of token */
   189040   int iEndOff                     /* End offset of token */
   189041 ){
   189042   int rc = SQLITE_OK;
   189043 
   189044   UNUSED_PARAM2(pToken, nToken);
   189045   UNUSED_PARAM(iEndOff);
   189046 
   189047   if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
   189048     Fts5SFinder *p = (Fts5SFinder*)pContext;
   189049     if( p->iPos>0 ){
   189050       int i;
   189051       char c = 0;
   189052       for(i=iStartOff-1; i>=0; i--){
   189053         c = p->zDoc[i];
   189054         if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
   189055       }
   189056       if( i!=iStartOff-1 && (c=='.' || c==':') ){
   189057         rc = fts5SentenceFinderAdd(p, p->iPos);
   189058       }
   189059     }else{
   189060       rc = fts5SentenceFinderAdd(p, 0);
   189061     }
   189062     p->iPos++;
   189063   }
   189064   return rc;
   189065 }
   189066 
   189067 static int fts5SnippetScore(
   189068   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
   189069   Fts5Context *pFts,              /* First arg to pass to pApi functions */
   189070   int nDocsize,                   /* Size of column in tokens */
   189071   unsigned char *aSeen,           /* Array with one element per query phrase */
   189072   int iCol,                       /* Column to score */
   189073   int iPos,                       /* Starting offset to score */
   189074   int nToken,                     /* Max tokens per snippet */
   189075   int *pnScore,                   /* OUT: Score */
   189076   int *piPos                      /* OUT: Adjusted offset */
   189077 ){
   189078   int rc;
   189079   int i;
   189080   int ip = 0;
   189081   int ic = 0;
   189082   int iOff = 0;
   189083   int iFirst = -1;
   189084   int nInst;
   189085   int nScore = 0;
   189086   int iLast = 0;
   189087 
   189088   rc = pApi->xInstCount(pFts, &nInst);
   189089   for(i=0; i<nInst && rc==SQLITE_OK; i++){
   189090     rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
   189091     if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
   189092       nScore += (aSeen[ip] ? 1 : 1000);
   189093       aSeen[ip] = 1;
   189094       if( iFirst<0 ) iFirst = iOff;
   189095       iLast = iOff + pApi->xPhraseSize(pFts, ip);
   189096     }
   189097   }
   189098 
   189099   *pnScore = nScore;
   189100   if( piPos ){
   189101     int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
   189102     if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
   189103     if( iAdj<0 ) iAdj = 0;
   189104     *piPos = iAdj;
   189105   }
   189106 
   189107   return rc;
   189108 }
   189109 
   189110 /*
   189111 ** Return the value in pVal interpreted as utf-8 text. Except, if pVal
   189112 ** contains a NULL value, return a pointer to a static string zero
   189113 ** bytes in length instead of a NULL pointer.
   189114 */
   189115 static const char *fts5ValueToText(sqlite3_value *pVal){
   189116   const char *zRet = (const char*)sqlite3_value_text(pVal);
   189117   return zRet ? zRet : "";
   189118 }
   189119 
   189120 /*
   189121 ** Implementation of snippet() function.
   189122 */
   189123 static void fts5SnippetFunction(
   189124   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
   189125   Fts5Context *pFts,              /* First arg to pass to pApi functions */
   189126   sqlite3_context *pCtx,          /* Context for returning result/error */
   189127   int nVal,                       /* Number of values in apVal[] array */
   189128   sqlite3_value **apVal           /* Array of trailing arguments */
   189129 ){
   189130   HighlightContext ctx;
   189131   int rc = SQLITE_OK;             /* Return code */
   189132   int iCol;                       /* 1st argument to snippet() */
   189133   const char *zEllips;            /* 4th argument to snippet() */
   189134   int nToken;                     /* 5th argument to snippet() */
   189135   int nInst = 0;                  /* Number of instance matches this row */
   189136   int i;                          /* Used to iterate through instances */
   189137   int nPhrase;                    /* Number of phrases in query */
   189138   unsigned char *aSeen;           /* Array of "seen instance" flags */
   189139   int iBestCol;                   /* Column containing best snippet */
   189140   int iBestStart = 0;             /* First token of best snippet */
   189141   int nBestScore = 0;             /* Score of best snippet */
   189142   int nColSize = 0;               /* Total size of iBestCol in tokens */
   189143   Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */
   189144   int nCol;
   189145 
   189146   if( nVal!=5 ){
   189147     const char *zErr = "wrong number of arguments to function snippet()";
   189148     sqlite3_result_error(pCtx, zErr, -1);
   189149     return;
   189150   }
   189151 
   189152   nCol = pApi->xColumnCount(pFts);
   189153   memset(&ctx, 0, sizeof(HighlightContext));
   189154   iCol = sqlite3_value_int(apVal[0]);
   189155   ctx.zOpen = fts5ValueToText(apVal[1]);
   189156   ctx.zClose = fts5ValueToText(apVal[2]);
   189157   zEllips = fts5ValueToText(apVal[3]);
   189158   nToken = sqlite3_value_int(apVal[4]);
   189159 
   189160   iBestCol = (iCol>=0 ? iCol : 0);
   189161   nPhrase = pApi->xPhraseCount(pFts);
   189162   aSeen = sqlite3_malloc(nPhrase);
   189163   if( aSeen==0 ){
   189164     rc = SQLITE_NOMEM;
   189165   }
   189166   if( rc==SQLITE_OK ){
   189167     rc = pApi->xInstCount(pFts, &nInst);
   189168   }
   189169 
   189170   memset(&sFinder, 0, sizeof(Fts5SFinder));
   189171   for(i=0; i<nCol; i++){
   189172     if( iCol<0 || iCol==i ){
   189173       int nDoc;
   189174       int nDocsize;
   189175       int ii;
   189176       sFinder.iPos = 0;
   189177       sFinder.nFirst = 0;
   189178       rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
   189179       if( rc!=SQLITE_OK ) break;
   189180       rc = pApi->xTokenize(pFts,
   189181           sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
   189182       );
   189183       if( rc!=SQLITE_OK ) break;
   189184       rc = pApi->xColumnSize(pFts, i, &nDocsize);
   189185       if( rc!=SQLITE_OK ) break;
   189186 
   189187       for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
   189188         int ip, ic, io;
   189189         int iAdj;
   189190         int nScore;
   189191         int jj;
   189192 
   189193         rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
   189194         if( ic!=i || rc!=SQLITE_OK ) continue;
   189195         memset(aSeen, 0, nPhrase);
   189196         rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
   189197             io, nToken, &nScore, &iAdj
   189198         );
   189199         if( rc==SQLITE_OK && nScore>nBestScore ){
   189200           nBestScore = nScore;
   189201           iBestCol = i;
   189202           iBestStart = iAdj;
   189203           nColSize = nDocsize;
   189204         }
   189205 
   189206         if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
   189207           for(jj=0; jj<(sFinder.nFirst-1); jj++){
   189208             if( sFinder.aFirst[jj+1]>io ) break;
   189209           }
   189210 
   189211           if( sFinder.aFirst[jj]<io ){
   189212             memset(aSeen, 0, nPhrase);
   189213             rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
   189214               sFinder.aFirst[jj], nToken, &nScore, 0
   189215             );
   189216 
   189217             nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
   189218             if( rc==SQLITE_OK && nScore>nBestScore ){
   189219               nBestScore = nScore;
   189220               iBestCol = i;
   189221               iBestStart = sFinder.aFirst[jj];
   189222               nColSize = nDocsize;
   189223             }
   189224           }
   189225         }
   189226       }
   189227     }
   189228   }
   189229 
   189230   if( rc==SQLITE_OK ){
   189231     rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
   189232   }
   189233   if( rc==SQLITE_OK && nColSize==0 ){
   189234     rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
   189235   }
   189236   if( ctx.zIn ){
   189237     if( rc==SQLITE_OK ){
   189238       rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
   189239     }
   189240 
   189241     ctx.iRangeStart = iBestStart;
   189242     ctx.iRangeEnd = iBestStart + nToken - 1;
   189243 
   189244     if( iBestStart>0 ){
   189245       fts5HighlightAppend(&rc, &ctx, zEllips, -1);
   189246     }
   189247 
   189248     /* Advance iterator ctx.iter so that it points to the first coalesced
   189249     ** phrase instance at or following position iBestStart. */
   189250     while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
   189251       rc = fts5CInstIterNext(&ctx.iter);
   189252     }
   189253 
   189254     if( rc==SQLITE_OK ){
   189255       rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
   189256     }
   189257     if( ctx.iRangeEnd>=(nColSize-1) ){
   189258       fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
   189259     }else{
   189260       fts5HighlightAppend(&rc, &ctx, zEllips, -1);
   189261     }
   189262   }
   189263   if( rc==SQLITE_OK ){
   189264     sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
   189265   }else{
   189266     sqlite3_result_error_code(pCtx, rc);
   189267   }
   189268   sqlite3_free(ctx.zOut);
   189269   sqlite3_free(aSeen);
   189270   sqlite3_free(sFinder.aFirst);
   189271 }
   189272 
   189273 /************************************************************************/
   189274 
   189275 /*
   189276 ** The first time the bm25() function is called for a query, an instance
   189277 ** of the following structure is allocated and populated.
   189278 */
   189279 typedef struct Fts5Bm25Data Fts5Bm25Data;
   189280 struct Fts5Bm25Data {
   189281   int nPhrase;                    /* Number of phrases in query */
   189282   double avgdl;                   /* Average number of tokens in each row */
   189283   double *aIDF;                   /* IDF for each phrase */
   189284   double *aFreq;                  /* Array used to calculate phrase freq. */
   189285 };
   189286 
   189287 /*
   189288 ** Callback used by fts5Bm25GetData() to count the number of rows in the
   189289 ** table matched by each individual phrase within the query.
   189290 */
   189291 static int fts5CountCb(
   189292   const Fts5ExtensionApi *pApi,
   189293   Fts5Context *pFts,
   189294   void *pUserData                 /* Pointer to sqlite3_int64 variable */
   189295 ){
   189296   sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
   189297   UNUSED_PARAM2(pApi, pFts);
   189298   (*pn)++;
   189299   return SQLITE_OK;
   189300 }
   189301 
   189302 /*
   189303 ** Set *ppData to point to the Fts5Bm25Data object for the current query.
   189304 ** If the object has not already been allocated, allocate and populate it
   189305 ** now.
   189306 */
   189307 static int fts5Bm25GetData(
   189308   const Fts5ExtensionApi *pApi,
   189309   Fts5Context *pFts,
   189310   Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
   189311 ){
   189312   int rc = SQLITE_OK;             /* Return code */
   189313   Fts5Bm25Data *p;                /* Object to return */
   189314 
   189315   p = pApi->xGetAuxdata(pFts, 0);
   189316   if( p==0 ){
   189317     int nPhrase;                  /* Number of phrases in query */
   189318     sqlite3_int64 nRow = 0;       /* Number of rows in table */
   189319     sqlite3_int64 nToken = 0;     /* Number of tokens in table */
   189320     int nByte;                    /* Bytes of space to allocate */
   189321     int i;
   189322 
   189323     /* Allocate the Fts5Bm25Data object */
   189324     nPhrase = pApi->xPhraseCount(pFts);
   189325     nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
   189326     p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
   189327     if( p==0 ){
   189328       rc = SQLITE_NOMEM;
   189329     }else{
   189330       memset(p, 0, nByte);
   189331       p->nPhrase = nPhrase;
   189332       p->aIDF = (double*)&p[1];
   189333       p->aFreq = &p->aIDF[nPhrase];
   189334     }
   189335 
   189336     /* Calculate the average document length for this FTS5 table */
   189337     if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
   189338     if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
   189339     if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
   189340 
   189341     /* Calculate an IDF for each phrase in the query */
   189342     for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
   189343       sqlite3_int64 nHit = 0;
   189344       rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
   189345       if( rc==SQLITE_OK ){
   189346         /* Calculate the IDF (Inverse Document Frequency) for phrase i.
   189347         ** This is done using the standard BM25 formula as found on wikipedia:
   189348         **
   189349         **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
   189350         **
   189351         ** where "N" is the total number of documents in the set and nHit
   189352         ** is the number that contain at least one instance of the phrase
   189353         ** under consideration.
   189354         **
   189355         ** The problem with this is that if (N < 2*nHit), the IDF is
   189356         ** negative. Which is undesirable. So the mimimum allowable IDF is
   189357         ** (1e-6) - roughly the same as a term that appears in just over
   189358         ** half of set of 5,000,000 documents.  */
   189359         double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
   189360         if( idf<=0.0 ) idf = 1e-6;
   189361         p->aIDF[i] = idf;
   189362       }
   189363     }
   189364 
   189365     if( rc!=SQLITE_OK ){
   189366       sqlite3_free(p);
   189367     }else{
   189368       rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
   189369     }
   189370     if( rc!=SQLITE_OK ) p = 0;
   189371   }
   189372   *ppData = p;
   189373   return rc;
   189374 }
   189375 
   189376 /*
   189377 ** Implementation of bm25() function.
   189378 */
   189379 static void fts5Bm25Function(
   189380   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
   189381   Fts5Context *pFts,              /* First arg to pass to pApi functions */
   189382   sqlite3_context *pCtx,          /* Context for returning result/error */
   189383   int nVal,                       /* Number of values in apVal[] array */
   189384   sqlite3_value **apVal           /* Array of trailing arguments */
   189385 ){
   189386   const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
   189387   const double b = 0.75;          /* Constant "b" from BM25 formula */
   189388   int rc = SQLITE_OK;             /* Error code */
   189389   double score = 0.0;             /* SQL function return value */
   189390   Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
   189391   int i;                          /* Iterator variable */
   189392   int nInst = 0;                  /* Value returned by xInstCount() */
   189393   double D = 0.0;                 /* Total number of tokens in row */
   189394   double *aFreq = 0;              /* Array of phrase freq. for current row */
   189395 
   189396   /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
   189397   ** for each phrase in the query for the current row. */
   189398   rc = fts5Bm25GetData(pApi, pFts, &pData);
   189399   if( rc==SQLITE_OK ){
   189400     aFreq = pData->aFreq;
   189401     memset(aFreq, 0, sizeof(double) * pData->nPhrase);
   189402     rc = pApi->xInstCount(pFts, &nInst);
   189403   }
   189404   for(i=0; rc==SQLITE_OK && i<nInst; i++){
   189405     int ip; int ic; int io;
   189406     rc = pApi->xInst(pFts, i, &ip, &ic, &io);
   189407     if( rc==SQLITE_OK ){
   189408       double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
   189409       aFreq[ip] += w;
   189410     }
   189411   }
   189412 
   189413   /* Figure out the total size of the current row in tokens. */
   189414   if( rc==SQLITE_OK ){
   189415     int nTok;
   189416     rc = pApi->xColumnSize(pFts, -1, &nTok);
   189417     D = (double)nTok;
   189418   }
   189419 
   189420   /* Determine the BM25 score for the current row. */
   189421   for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
   189422     score += pData->aIDF[i] * (
   189423       ( aFreq[i] * (k1 + 1.0) ) /
   189424       ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
   189425     );
   189426   }
   189427 
   189428   /* If no error has occurred, return the calculated score. Otherwise,
   189429   ** throw an SQL exception.  */
   189430   if( rc==SQLITE_OK ){
   189431     sqlite3_result_double(pCtx, -1.0 * score);
   189432   }else{
   189433     sqlite3_result_error_code(pCtx, rc);
   189434   }
   189435 }
   189436 
   189437 static int sqlite3Fts5AuxInit(fts5_api *pApi){
   189438   struct Builtin {
   189439     const char *zFunc;            /* Function name (nul-terminated) */
   189440     void *pUserData;              /* User-data pointer */
   189441     fts5_extension_function xFunc;/* Callback function */
   189442     void (*xDestroy)(void*);      /* Destructor function */
   189443   } aBuiltin [] = {
   189444     { "snippet",   0, fts5SnippetFunction, 0 },
   189445     { "highlight", 0, fts5HighlightFunction, 0 },
   189446     { "bm25",      0, fts5Bm25Function,    0 },
   189447   };
   189448   int rc = SQLITE_OK;             /* Return code */
   189449   int i;                          /* To iterate through builtin functions */
   189450 
   189451   for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
   189452     rc = pApi->xCreateFunction(pApi,
   189453         aBuiltin[i].zFunc,
   189454         aBuiltin[i].pUserData,
   189455         aBuiltin[i].xFunc,
   189456         aBuiltin[i].xDestroy
   189457     );
   189458   }
   189459 
   189460   return rc;
   189461 }
   189462 
   189463 
   189464 
   189465 /*
   189466 ** 2014 May 31
   189467 **
   189468 ** The author disclaims copyright to this source code.  In place of
   189469 ** a legal notice, here is a blessing:
   189470 **
   189471 **    May you do good and not evil.
   189472 **    May you find forgiveness for yourself and forgive others.
   189473 **    May you share freely, never taking more than you give.
   189474 **
   189475 ******************************************************************************
   189476 */
   189477 
   189478 
   189479 
   189480 /* #include "fts5Int.h" */
   189481 
   189482 static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
   189483   if( (u32)pBuf->nSpace<nByte ){
   189484     u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
   189485     u8 *pNew;
   189486     while( nNew<nByte ){
   189487       nNew = nNew * 2;
   189488     }
   189489     pNew = sqlite3_realloc(pBuf->p, nNew);
   189490     if( pNew==0 ){
   189491       *pRc = SQLITE_NOMEM;
   189492       return 1;
   189493     }else{
   189494       pBuf->nSpace = nNew;
   189495       pBuf->p = pNew;
   189496     }
   189497   }
   189498   return 0;
   189499 }
   189500 
   189501 
   189502 /*
   189503 ** Encode value iVal as an SQLite varint and append it to the buffer object
   189504 ** pBuf. If an OOM error occurs, set the error code in p.
   189505 */
   189506 static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
   189507   if( fts5BufferGrow(pRc, pBuf, 9) ) return;
   189508   pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
   189509 }
   189510 
   189511 static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
   189512   aBuf[0] = (iVal>>24) & 0x00FF;
   189513   aBuf[1] = (iVal>>16) & 0x00FF;
   189514   aBuf[2] = (iVal>> 8) & 0x00FF;
   189515   aBuf[3] = (iVal>> 0) & 0x00FF;
   189516 }
   189517 
   189518 static int sqlite3Fts5Get32(const u8 *aBuf){
   189519   return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
   189520 }
   189521 
   189522 /*
   189523 ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
   189524 ** the error code in p. If an error has already occurred when this function
   189525 ** is called, it is a no-op.
   189526 */
   189527 static void sqlite3Fts5BufferAppendBlob(
   189528   int *pRc,
   189529   Fts5Buffer *pBuf,
   189530   u32 nData,
   189531   const u8 *pData
   189532 ){
   189533   assert_nc( *pRc || nData>=0 );
   189534   if( nData ){
   189535     if( fts5BufferGrow(pRc, pBuf, nData) ) return;
   189536     memcpy(&pBuf->p[pBuf->n], pData, nData);
   189537     pBuf->n += nData;
   189538   }
   189539 }
   189540 
   189541 /*
   189542 ** Append the nul-terminated string zStr to the buffer pBuf. This function
   189543 ** ensures that the byte following the buffer data is set to 0x00, even
   189544 ** though this byte is not included in the pBuf->n count.
   189545 */
   189546 static void sqlite3Fts5BufferAppendString(
   189547   int *pRc,
   189548   Fts5Buffer *pBuf,
   189549   const char *zStr
   189550 ){
   189551   int nStr = (int)strlen(zStr);
   189552   sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
   189553   pBuf->n--;
   189554 }
   189555 
   189556 /*
   189557 ** Argument zFmt is a printf() style format string. This function performs
   189558 ** the printf() style processing, then appends the results to buffer pBuf.
   189559 **
   189560 ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
   189561 ** following the buffer data is set to 0x00, even though this byte is not
   189562 ** included in the pBuf->n count.
   189563 */
   189564 static void sqlite3Fts5BufferAppendPrintf(
   189565   int *pRc,
   189566   Fts5Buffer *pBuf,
   189567   char *zFmt, ...
   189568 ){
   189569   if( *pRc==SQLITE_OK ){
   189570     char *zTmp;
   189571     va_list ap;
   189572     va_start(ap, zFmt);
   189573     zTmp = sqlite3_vmprintf(zFmt, ap);
   189574     va_end(ap);
   189575 
   189576     if( zTmp==0 ){
   189577       *pRc = SQLITE_NOMEM;
   189578     }else{
   189579       sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
   189580       sqlite3_free(zTmp);
   189581     }
   189582   }
   189583 }
   189584 
   189585 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
   189586   char *zRet = 0;
   189587   if( *pRc==SQLITE_OK ){
   189588     va_list ap;
   189589     va_start(ap, zFmt);
   189590     zRet = sqlite3_vmprintf(zFmt, ap);
   189591     va_end(ap);
   189592     if( zRet==0 ){
   189593       *pRc = SQLITE_NOMEM;
   189594     }
   189595   }
   189596   return zRet;
   189597 }
   189598 
   189599 
   189600 /*
   189601 ** Free any buffer allocated by pBuf. Zero the structure before returning.
   189602 */
   189603 static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
   189604   sqlite3_free(pBuf->p);
   189605   memset(pBuf, 0, sizeof(Fts5Buffer));
   189606 }
   189607 
   189608 /*
   189609 ** Zero the contents of the buffer object. But do not free the associated
   189610 ** memory allocation.
   189611 */
   189612 static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
   189613   pBuf->n = 0;
   189614 }
   189615 
   189616 /*
   189617 ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
   189618 ** the error code in p. If an error has already occurred when this function
   189619 ** is called, it is a no-op.
   189620 */
   189621 static void sqlite3Fts5BufferSet(
   189622   int *pRc,
   189623   Fts5Buffer *pBuf,
   189624   int nData,
   189625   const u8 *pData
   189626 ){
   189627   pBuf->n = 0;
   189628   sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
   189629 }
   189630 
   189631 static int sqlite3Fts5PoslistNext64(
   189632   const u8 *a, int n,             /* Buffer containing poslist */
   189633   int *pi,                        /* IN/OUT: Offset within a[] */
   189634   i64 *piOff                      /* IN/OUT: Current offset */
   189635 ){
   189636   int i = *pi;
   189637   if( i>=n ){
   189638     /* EOF */
   189639     *piOff = -1;
   189640     return 1;
   189641   }else{
   189642     i64 iOff = *piOff;
   189643     int iVal;
   189644     fts5FastGetVarint32(a, i, iVal);
   189645     if( iVal==1 ){
   189646       fts5FastGetVarint32(a, i, iVal);
   189647       iOff = ((i64)iVal) << 32;
   189648       fts5FastGetVarint32(a, i, iVal);
   189649     }
   189650     *piOff = iOff + (iVal-2);
   189651     *pi = i;
   189652     return 0;
   189653   }
   189654 }
   189655 
   189656 
   189657 /*
   189658 ** Advance the iterator object passed as the only argument. Return true
   189659 ** if the iterator reaches EOF, or false otherwise.
   189660 */
   189661 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
   189662   if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
   189663     pIter->bEof = 1;
   189664   }
   189665   return pIter->bEof;
   189666 }
   189667 
   189668 static int sqlite3Fts5PoslistReaderInit(
   189669   const u8 *a, int n,             /* Poslist buffer to iterate through */
   189670   Fts5PoslistReader *pIter        /* Iterator object to initialize */
   189671 ){
   189672   memset(pIter, 0, sizeof(*pIter));
   189673   pIter->a = a;
   189674   pIter->n = n;
   189675   sqlite3Fts5PoslistReaderNext(pIter);
   189676   return pIter->bEof;
   189677 }
   189678 
   189679 /*
   189680 ** Append position iPos to the position list being accumulated in buffer
   189681 ** pBuf, which must be already be large enough to hold the new data.
   189682 ** The previous position written to this list is *piPrev. *piPrev is set
   189683 ** to iPos before returning.
   189684 */
   189685 static void sqlite3Fts5PoslistSafeAppend(
   189686   Fts5Buffer *pBuf,
   189687   i64 *piPrev,
   189688   i64 iPos
   189689 ){
   189690   static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
   189691   if( (iPos & colmask) != (*piPrev & colmask) ){
   189692     pBuf->p[pBuf->n++] = 1;
   189693     pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
   189694     *piPrev = (iPos & colmask);
   189695   }
   189696   pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
   189697   *piPrev = iPos;
   189698 }
   189699 
   189700 static int sqlite3Fts5PoslistWriterAppend(
   189701   Fts5Buffer *pBuf,
   189702   Fts5PoslistWriter *pWriter,
   189703   i64 iPos
   189704 ){
   189705   int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
   189706   if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
   189707   sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
   189708   return SQLITE_OK;
   189709 }
   189710 
   189711 static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
   189712   void *pRet = 0;
   189713   if( *pRc==SQLITE_OK ){
   189714     pRet = sqlite3_malloc(nByte);
   189715     if( pRet==0 ){
   189716       if( nByte>0 ) *pRc = SQLITE_NOMEM;
   189717     }else{
   189718       memset(pRet, 0, nByte);
   189719     }
   189720   }
   189721   return pRet;
   189722 }
   189723 
   189724 /*
   189725 ** Return a nul-terminated copy of the string indicated by pIn. If nIn
   189726 ** is non-negative, then it is the length of the string in bytes. Otherwise,
   189727 ** the length of the string is determined using strlen().
   189728 **
   189729 ** It is the responsibility of the caller to eventually free the returned
   189730 ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
   189731 */
   189732 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
   189733   char *zRet = 0;
   189734   if( *pRc==SQLITE_OK ){
   189735     if( nIn<0 ){
   189736       nIn = (int)strlen(pIn);
   189737     }
   189738     zRet = (char*)sqlite3_malloc(nIn+1);
   189739     if( zRet ){
   189740       memcpy(zRet, pIn, nIn);
   189741       zRet[nIn] = '\0';
   189742     }else{
   189743       *pRc = SQLITE_NOMEM;
   189744     }
   189745   }
   189746   return zRet;
   189747 }
   189748 
   189749 
   189750 /*
   189751 ** Return true if character 't' may be part of an FTS5 bareword, or false
   189752 ** otherwise. Characters that may be part of barewords:
   189753 **
   189754 **   * All non-ASCII characters,
   189755 **   * The 52 upper and lower case ASCII characters, and
   189756 **   * The 10 integer ASCII characters.
   189757 **   * The underscore character "_" (0x5F).
   189758 **   * The unicode "subsitute" character (0x1A).
   189759 */
   189760 static int sqlite3Fts5IsBareword(char t){
   189761   u8 aBareword[128] = {
   189762     0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
   189763     0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
   189764     0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
   189765     1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
   189766     0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
   189767     1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
   189768     0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
   189769     1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
   189770   };
   189771 
   189772   return (t & 0x80) || aBareword[(int)t];
   189773 }
   189774 
   189775 
   189776 /*************************************************************************
   189777 */
   189778 typedef struct Fts5TermsetEntry Fts5TermsetEntry;
   189779 struct Fts5TermsetEntry {
   189780   char *pTerm;
   189781   int nTerm;
   189782   int iIdx;                       /* Index (main or aPrefix[] entry) */
   189783   Fts5TermsetEntry *pNext;
   189784 };
   189785 
   189786 struct Fts5Termset {
   189787   Fts5TermsetEntry *apHash[512];
   189788 };
   189789 
   189790 static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
   189791   int rc = SQLITE_OK;
   189792   *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
   189793   return rc;
   189794 }
   189795 
   189796 static int sqlite3Fts5TermsetAdd(
   189797   Fts5Termset *p,
   189798   int iIdx,
   189799   const char *pTerm, int nTerm,
   189800   int *pbPresent
   189801 ){
   189802   int rc = SQLITE_OK;
   189803   *pbPresent = 0;
   189804   if( p ){
   189805     int i;
   189806     u32 hash = 13;
   189807     Fts5TermsetEntry *pEntry;
   189808 
   189809     /* Calculate a hash value for this term. This is the same hash checksum
   189810     ** used by the fts5_hash.c module. This is not important for correct
   189811     ** operation of the module, but is necessary to ensure that some tests
   189812     ** designed to produce hash table collisions really do work.  */
   189813     for(i=nTerm-1; i>=0; i--){
   189814       hash = (hash << 3) ^ hash ^ pTerm[i];
   189815     }
   189816     hash = (hash << 3) ^ hash ^ iIdx;
   189817     hash = hash % ArraySize(p->apHash);
   189818 
   189819     for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
   189820       if( pEntry->iIdx==iIdx
   189821           && pEntry->nTerm==nTerm
   189822           && memcmp(pEntry->pTerm, pTerm, nTerm)==0
   189823       ){
   189824         *pbPresent = 1;
   189825         break;
   189826       }
   189827     }
   189828 
   189829     if( pEntry==0 ){
   189830       pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
   189831       if( pEntry ){
   189832         pEntry->pTerm = (char*)&pEntry[1];
   189833         pEntry->nTerm = nTerm;
   189834         pEntry->iIdx = iIdx;
   189835         memcpy(pEntry->pTerm, pTerm, nTerm);
   189836         pEntry->pNext = p->apHash[hash];
   189837         p->apHash[hash] = pEntry;
   189838       }
   189839     }
   189840   }
   189841 
   189842   return rc;
   189843 }
   189844 
   189845 static void sqlite3Fts5TermsetFree(Fts5Termset *p){
   189846   if( p ){
   189847     u32 i;
   189848     for(i=0; i<ArraySize(p->apHash); i++){
   189849       Fts5TermsetEntry *pEntry = p->apHash[i];
   189850       while( pEntry ){
   189851         Fts5TermsetEntry *pDel = pEntry;
   189852         pEntry = pEntry->pNext;
   189853         sqlite3_free(pDel);
   189854       }
   189855     }
   189856     sqlite3_free(p);
   189857   }
   189858 }
   189859 
   189860 /*
   189861 ** 2014 Jun 09
   189862 **
   189863 ** The author disclaims copyright to this source code.  In place of
   189864 ** a legal notice, here is a blessing:
   189865 **
   189866 **    May you do good and not evil.
   189867 **    May you find forgiveness for yourself and forgive others.
   189868 **    May you share freely, never taking more than you give.
   189869 **
   189870 ******************************************************************************
   189871 **
   189872 ** This is an SQLite module implementing full-text search.
   189873 */
   189874 
   189875 
   189876 /* #include "fts5Int.h" */
   189877 
   189878 #define FTS5_DEFAULT_PAGE_SIZE   4050
   189879 #define FTS5_DEFAULT_AUTOMERGE      4
   189880 #define FTS5_DEFAULT_USERMERGE      4
   189881 #define FTS5_DEFAULT_CRISISMERGE   16
   189882 #define FTS5_DEFAULT_HASHSIZE    (1024*1024)
   189883 
   189884 /* Maximum allowed page size */
   189885 #define FTS5_MAX_PAGE_SIZE (128*1024)
   189886 
   189887 static int fts5_iswhitespace(char x){
   189888   return (x==' ');
   189889 }
   189890 
   189891 static int fts5_isopenquote(char x){
   189892   return (x=='"' || x=='\'' || x=='[' || x=='`');
   189893 }
   189894 
   189895 /*
   189896 ** Argument pIn points to a character that is part of a nul-terminated
   189897 ** string. Return a pointer to the first character following *pIn in
   189898 ** the string that is not a white-space character.
   189899 */
   189900 static const char *fts5ConfigSkipWhitespace(const char *pIn){
   189901   const char *p = pIn;
   189902   if( p ){
   189903     while( fts5_iswhitespace(*p) ){ p++; }
   189904   }
   189905   return p;
   189906 }
   189907 
   189908 /*
   189909 ** Argument pIn points to a character that is part of a nul-terminated
   189910 ** string. Return a pointer to the first character following *pIn in
   189911 ** the string that is not a "bareword" character.
   189912 */
   189913 static const char *fts5ConfigSkipBareword(const char *pIn){
   189914   const char *p = pIn;
   189915   while ( sqlite3Fts5IsBareword(*p) ) p++;
   189916   if( p==pIn ) p = 0;
   189917   return p;
   189918 }
   189919 
   189920 static int fts5_isdigit(char a){
   189921   return (a>='0' && a<='9');
   189922 }
   189923 
   189924 
   189925 
   189926 static const char *fts5ConfigSkipLiteral(const char *pIn){
   189927   const char *p = pIn;
   189928   switch( *p ){
   189929     case 'n': case 'N':
   189930       if( sqlite3_strnicmp("null", p, 4)==0 ){
   189931         p = &p[4];
   189932       }else{
   189933         p = 0;
   189934       }
   189935       break;
   189936 
   189937     case 'x': case 'X':
   189938       p++;
   189939       if( *p=='\'' ){
   189940         p++;
   189941         while( (*p>='a' && *p<='f')
   189942             || (*p>='A' && *p<='F')
   189943             || (*p>='0' && *p<='9')
   189944             ){
   189945           p++;
   189946         }
   189947         if( *p=='\'' && 0==((p-pIn)%2) ){
   189948           p++;
   189949         }else{
   189950           p = 0;
   189951         }
   189952       }else{
   189953         p = 0;
   189954       }
   189955       break;
   189956 
   189957     case '\'':
   189958       p++;
   189959       while( p ){
   189960         if( *p=='\'' ){
   189961           p++;
   189962           if( *p!='\'' ) break;
   189963         }
   189964         p++;
   189965         if( *p==0 ) p = 0;
   189966       }
   189967       break;
   189968 
   189969     default:
   189970       /* maybe a number */
   189971       if( *p=='+' || *p=='-' ) p++;
   189972       while( fts5_isdigit(*p) ) p++;
   189973 
   189974       /* At this point, if the literal was an integer, the parse is
   189975       ** finished. Or, if it is a floating point value, it may continue
   189976       ** with either a decimal point or an 'E' character. */
   189977       if( *p=='.' && fts5_isdigit(p[1]) ){
   189978         p += 2;
   189979         while( fts5_isdigit(*p) ) p++;
   189980       }
   189981       if( p==pIn ) p = 0;
   189982 
   189983       break;
   189984   }
   189985 
   189986   return p;
   189987 }
   189988 
   189989 /*
   189990 ** The first character of the string pointed to by argument z is guaranteed
   189991 ** to be an open-quote character (see function fts5_isopenquote()).
   189992 **
   189993 ** This function searches for the corresponding close-quote character within
   189994 ** the string and, if found, dequotes the string in place and adds a new
   189995 ** nul-terminator byte.
   189996 **
   189997 ** If the close-quote is found, the value returned is the byte offset of
   189998 ** the character immediately following it. Or, if the close-quote is not
   189999 ** found, -1 is returned. If -1 is returned, the buffer is left in an
   190000 ** undefined state.
   190001 */
   190002 static int fts5Dequote(char *z){
   190003   char q;
   190004   int iIn = 1;
   190005   int iOut = 0;
   190006   q = z[0];
   190007 
   190008   /* Set stack variable q to the close-quote character */
   190009   assert( q=='[' || q=='\'' || q=='"' || q=='`' );
   190010   if( q=='[' ) q = ']';
   190011 
   190012   while( ALWAYS(z[iIn]) ){
   190013     if( z[iIn]==q ){
   190014       if( z[iIn+1]!=q ){
   190015         /* Character iIn was the close quote. */
   190016         iIn++;
   190017         break;
   190018       }else{
   190019         /* Character iIn and iIn+1 form an escaped quote character. Skip
   190020         ** the input cursor past both and copy a single quote character
   190021         ** to the output buffer. */
   190022         iIn += 2;
   190023         z[iOut++] = q;
   190024       }
   190025     }else{
   190026       z[iOut++] = z[iIn++];
   190027     }
   190028   }
   190029 
   190030   z[iOut] = '\0';
   190031   return iIn;
   190032 }
   190033 
   190034 /*
   190035 ** Convert an SQL-style quoted string into a normal string by removing
   190036 ** the quote characters.  The conversion is done in-place.  If the
   190037 ** input does not begin with a quote character, then this routine
   190038 ** is a no-op.
   190039 **
   190040 ** Examples:
   190041 **
   190042 **     "abc"   becomes   abc
   190043 **     'xyz'   becomes   xyz
   190044 **     [pqr]   becomes   pqr
   190045 **     `mno`   becomes   mno
   190046 */
   190047 static void sqlite3Fts5Dequote(char *z){
   190048   char quote;                     /* Quote character (if any ) */
   190049 
   190050   assert( 0==fts5_iswhitespace(z[0]) );
   190051   quote = z[0];
   190052   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   190053     fts5Dequote(z);
   190054   }
   190055 }
   190056 
   190057 
   190058 struct Fts5Enum {
   190059   const char *zName;
   190060   int eVal;
   190061 };
   190062 typedef struct Fts5Enum Fts5Enum;
   190063 
   190064 static int fts5ConfigSetEnum(
   190065   const Fts5Enum *aEnum,
   190066   const char *zEnum,
   190067   int *peVal
   190068 ){
   190069   int nEnum = (int)strlen(zEnum);
   190070   int i;
   190071   int iVal = -1;
   190072 
   190073   for(i=0; aEnum[i].zName; i++){
   190074     if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
   190075       if( iVal>=0 ) return SQLITE_ERROR;
   190076       iVal = aEnum[i].eVal;
   190077     }
   190078   }
   190079 
   190080   *peVal = iVal;
   190081   return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
   190082 }
   190083 
   190084 /*
   190085 ** Parse a "special" CREATE VIRTUAL TABLE directive and update
   190086 ** configuration object pConfig as appropriate.
   190087 **
   190088 ** If successful, object pConfig is updated and SQLITE_OK returned. If
   190089 ** an error occurs, an SQLite error code is returned and an error message
   190090 ** may be left in *pzErr. It is the responsibility of the caller to
   190091 ** eventually free any such error message using sqlite3_free().
   190092 */
   190093 static int fts5ConfigParseSpecial(
   190094   Fts5Global *pGlobal,
   190095   Fts5Config *pConfig,            /* Configuration object to update */
   190096   const char *zCmd,               /* Special command to parse */
   190097   const char *zArg,               /* Argument to parse */
   190098   char **pzErr                    /* OUT: Error message */
   190099 ){
   190100   int rc = SQLITE_OK;
   190101   int nCmd = (int)strlen(zCmd);
   190102   if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
   190103     const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
   190104     const char *p;
   190105     int bFirst = 1;
   190106     if( pConfig->aPrefix==0 ){
   190107       pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
   190108       if( rc ) return rc;
   190109     }
   190110 
   190111     p = zArg;
   190112     while( 1 ){
   190113       int nPre = 0;
   190114 
   190115       while( p[0]==' ' ) p++;
   190116       if( bFirst==0 && p[0]==',' ){
   190117         p++;
   190118         while( p[0]==' ' ) p++;
   190119       }else if( p[0]=='\0' ){
   190120         break;
   190121       }
   190122       if( p[0]<'0' || p[0]>'9' ){
   190123         *pzErr = sqlite3_mprintf("malformed prefix=... directive");
   190124         rc = SQLITE_ERROR;
   190125         break;
   190126       }
   190127 
   190128       if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
   190129         *pzErr = sqlite3_mprintf(
   190130             "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
   190131         );
   190132         rc = SQLITE_ERROR;
   190133         break;
   190134       }
   190135 
   190136       while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
   190137         nPre = nPre*10 + (p[0] - '0');
   190138         p++;
   190139       }
   190140 
   190141       if( nPre<=0 || nPre>=1000 ){
   190142         *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
   190143         rc = SQLITE_ERROR;
   190144         break;
   190145       }
   190146 
   190147       pConfig->aPrefix[pConfig->nPrefix] = nPre;
   190148       pConfig->nPrefix++;
   190149       bFirst = 0;
   190150     }
   190151     assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
   190152     return rc;
   190153   }
   190154 
   190155   if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
   190156     const char *p = (const char*)zArg;
   190157     int nArg = (int)strlen(zArg) + 1;
   190158     char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
   190159     char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
   190160     char *pSpace = pDel;
   190161 
   190162     if( azArg && pSpace ){
   190163       if( pConfig->pTok ){
   190164         *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
   190165         rc = SQLITE_ERROR;
   190166       }else{
   190167         for(nArg=0; p && *p; nArg++){
   190168           const char *p2 = fts5ConfigSkipWhitespace(p);
   190169           if( *p2=='\'' ){
   190170             p = fts5ConfigSkipLiteral(p2);
   190171           }else{
   190172             p = fts5ConfigSkipBareword(p2);
   190173           }
   190174           if( p ){
   190175             memcpy(pSpace, p2, p-p2);
   190176             azArg[nArg] = pSpace;
   190177             sqlite3Fts5Dequote(pSpace);
   190178             pSpace += (p - p2) + 1;
   190179             p = fts5ConfigSkipWhitespace(p);
   190180           }
   190181         }
   190182         if( p==0 ){
   190183           *pzErr = sqlite3_mprintf("parse error in tokenize directive");
   190184           rc = SQLITE_ERROR;
   190185         }else{
   190186           rc = sqlite3Fts5GetTokenizer(pGlobal,
   190187               (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
   190188               pzErr
   190189           );
   190190         }
   190191       }
   190192     }
   190193 
   190194     sqlite3_free(azArg);
   190195     sqlite3_free(pDel);
   190196     return rc;
   190197   }
   190198 
   190199   if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
   190200     if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
   190201       *pzErr = sqlite3_mprintf("multiple content=... directives");
   190202       rc = SQLITE_ERROR;
   190203     }else{
   190204       if( zArg[0] ){
   190205         pConfig->eContent = FTS5_CONTENT_EXTERNAL;
   190206         pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
   190207       }else{
   190208         pConfig->eContent = FTS5_CONTENT_NONE;
   190209       }
   190210     }
   190211     return rc;
   190212   }
   190213 
   190214   if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
   190215     if( pConfig->zContentRowid ){
   190216       *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
   190217       rc = SQLITE_ERROR;
   190218     }else{
   190219       pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
   190220     }
   190221     return rc;
   190222   }
   190223 
   190224   if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
   190225     if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
   190226       *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
   190227       rc = SQLITE_ERROR;
   190228     }else{
   190229       pConfig->bColumnsize = (zArg[0]=='1');
   190230     }
   190231     return rc;
   190232   }
   190233 
   190234   if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
   190235     const Fts5Enum aDetail[] = {
   190236       { "none", FTS5_DETAIL_NONE },
   190237       { "full", FTS5_DETAIL_FULL },
   190238       { "columns", FTS5_DETAIL_COLUMNS },
   190239       { 0, 0 }
   190240     };
   190241 
   190242     if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
   190243       *pzErr = sqlite3_mprintf("malformed detail=... directive");
   190244     }
   190245     return rc;
   190246   }
   190247 
   190248   *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
   190249   return SQLITE_ERROR;
   190250 }
   190251 
   190252 /*
   190253 ** Allocate an instance of the default tokenizer ("simple") at
   190254 ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
   190255 ** code if an error occurs.
   190256 */
   190257 static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
   190258   assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
   190259   return sqlite3Fts5GetTokenizer(
   190260       pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
   190261   );
   190262 }
   190263 
   190264 /*
   190265 ** Gobble up the first bareword or quoted word from the input buffer zIn.
   190266 ** Return a pointer to the character immediately following the last in
   190267 ** the gobbled word if successful, or a NULL pointer otherwise (failed
   190268 ** to find close-quote character).
   190269 **
   190270 ** Before returning, set pzOut to point to a new buffer containing a
   190271 ** nul-terminated, dequoted copy of the gobbled word. If the word was
   190272 ** quoted, *pbQuoted is also set to 1 before returning.
   190273 **
   190274 ** If *pRc is other than SQLITE_OK when this function is called, it is
   190275 ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
   190276 ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
   190277 ** set if a parse error (failed to find close quote) occurs.
   190278 */
   190279 static const char *fts5ConfigGobbleWord(
   190280   int *pRc,                       /* IN/OUT: Error code */
   190281   const char *zIn,                /* Buffer to gobble string/bareword from */
   190282   char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
   190283   int *pbQuoted                   /* OUT: Set to true if dequoting required */
   190284 ){
   190285   const char *zRet = 0;
   190286 
   190287   int nIn = (int)strlen(zIn);
   190288   char *zOut = sqlite3_malloc(nIn+1);
   190289 
   190290   assert( *pRc==SQLITE_OK );
   190291   *pbQuoted = 0;
   190292   *pzOut = 0;
   190293 
   190294   if( zOut==0 ){
   190295     *pRc = SQLITE_NOMEM;
   190296   }else{
   190297     memcpy(zOut, zIn, nIn+1);
   190298     if( fts5_isopenquote(zOut[0]) ){
   190299       int ii = fts5Dequote(zOut);
   190300       zRet = &zIn[ii];
   190301       *pbQuoted = 1;
   190302     }else{
   190303       zRet = fts5ConfigSkipBareword(zIn);
   190304       if( zRet ){
   190305         zOut[zRet-zIn] = '\0';
   190306       }
   190307     }
   190308   }
   190309 
   190310   if( zRet==0 ){
   190311     sqlite3_free(zOut);
   190312   }else{
   190313     *pzOut = zOut;
   190314   }
   190315 
   190316   return zRet;
   190317 }
   190318 
   190319 static int fts5ConfigParseColumn(
   190320   Fts5Config *p,
   190321   char *zCol,
   190322   char *zArg,
   190323   char **pzErr
   190324 ){
   190325   int rc = SQLITE_OK;
   190326   if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
   190327    || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
   190328   ){
   190329     *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
   190330     rc = SQLITE_ERROR;
   190331   }else if( zArg ){
   190332     if( 0==sqlite3_stricmp(zArg, "unindexed") ){
   190333       p->abUnindexed[p->nCol] = 1;
   190334     }else{
   190335       *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
   190336       rc = SQLITE_ERROR;
   190337     }
   190338   }
   190339 
   190340   p->azCol[p->nCol++] = zCol;
   190341   return rc;
   190342 }
   190343 
   190344 /*
   190345 ** Populate the Fts5Config.zContentExprlist string.
   190346 */
   190347 static int fts5ConfigMakeExprlist(Fts5Config *p){
   190348   int i;
   190349   int rc = SQLITE_OK;
   190350   Fts5Buffer buf = {0, 0, 0};
   190351 
   190352   sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
   190353   if( p->eContent!=FTS5_CONTENT_NONE ){
   190354     for(i=0; i<p->nCol; i++){
   190355       if( p->eContent==FTS5_CONTENT_EXTERNAL ){
   190356         sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
   190357       }else{
   190358         sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
   190359       }
   190360     }
   190361   }
   190362 
   190363   assert( p->zContentExprlist==0 );
   190364   p->zContentExprlist = (char*)buf.p;
   190365   return rc;
   190366 }
   190367 
   190368 /*
   190369 ** Arguments nArg/azArg contain the string arguments passed to the xCreate
   190370 ** or xConnect method of the virtual table. This function attempts to
   190371 ** allocate an instance of Fts5Config containing the results of parsing
   190372 ** those arguments.
   190373 **
   190374 ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
   190375 ** new Fts5Config object. If an error occurs, an SQLite error code is
   190376 ** returned, *ppOut is set to NULL and an error message may be left in
   190377 ** *pzErr. It is the responsibility of the caller to eventually free any
   190378 ** such error message using sqlite3_free().
   190379 */
   190380 static int sqlite3Fts5ConfigParse(
   190381   Fts5Global *pGlobal,
   190382   sqlite3 *db,
   190383   int nArg,                       /* Number of arguments */
   190384   const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
   190385   Fts5Config **ppOut,             /* OUT: Results of parse */
   190386   char **pzErr                    /* OUT: Error message */
   190387 ){
   190388   int rc = SQLITE_OK;             /* Return code */
   190389   Fts5Config *pRet;               /* New object to return */
   190390   int i;
   190391   int nByte;
   190392 
   190393   *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
   190394   if( pRet==0 ) return SQLITE_NOMEM;
   190395   memset(pRet, 0, sizeof(Fts5Config));
   190396   pRet->db = db;
   190397   pRet->iCookie = -1;
   190398 
   190399   nByte = nArg * (sizeof(char*) + sizeof(u8));
   190400   pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
   190401   pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
   190402   pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
   190403   pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
   190404   pRet->bColumnsize = 1;
   190405   pRet->eDetail = FTS5_DETAIL_FULL;
   190406 #ifdef SQLITE_DEBUG
   190407   pRet->bPrefixIndex = 1;
   190408 #endif
   190409   if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
   190410     *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
   190411     rc = SQLITE_ERROR;
   190412   }
   190413 
   190414   for(i=3; rc==SQLITE_OK && i<nArg; i++){
   190415     const char *zOrig = azArg[i];
   190416     const char *z;
   190417     char *zOne = 0;
   190418     char *zTwo = 0;
   190419     int bOption = 0;
   190420     int bMustBeCol = 0;
   190421 
   190422     z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
   190423     z = fts5ConfigSkipWhitespace(z);
   190424     if( z && *z=='=' ){
   190425       bOption = 1;
   190426       z++;
   190427       if( bMustBeCol ) z = 0;
   190428     }
   190429     z = fts5ConfigSkipWhitespace(z);
   190430     if( z && z[0] ){
   190431       int bDummy;
   190432       z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
   190433       if( z && z[0] ) z = 0;
   190434     }
   190435 
   190436     if( rc==SQLITE_OK ){
   190437       if( z==0 ){
   190438         *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
   190439         rc = SQLITE_ERROR;
   190440       }else{
   190441         if( bOption ){
   190442           rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
   190443         }else{
   190444           rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
   190445           zOne = 0;
   190446         }
   190447       }
   190448     }
   190449 
   190450     sqlite3_free(zOne);
   190451     sqlite3_free(zTwo);
   190452   }
   190453 
   190454   /* If a tokenizer= option was successfully parsed, the tokenizer has
   190455   ** already been allocated. Otherwise, allocate an instance of the default
   190456   ** tokenizer (unicode61) now.  */
   190457   if( rc==SQLITE_OK && pRet->pTok==0 ){
   190458     rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
   190459   }
   190460 
   190461   /* If no zContent option was specified, fill in the default values. */
   190462   if( rc==SQLITE_OK && pRet->zContent==0 ){
   190463     const char *zTail = 0;
   190464     assert( pRet->eContent==FTS5_CONTENT_NORMAL
   190465          || pRet->eContent==FTS5_CONTENT_NONE
   190466     );
   190467     if( pRet->eContent==FTS5_CONTENT_NORMAL ){
   190468       zTail = "content";
   190469     }else if( pRet->bColumnsize ){
   190470       zTail = "docsize";
   190471     }
   190472 
   190473     if( zTail ){
   190474       pRet->zContent = sqlite3Fts5Mprintf(
   190475           &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
   190476       );
   190477     }
   190478   }
   190479 
   190480   if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
   190481     pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
   190482   }
   190483 
   190484   /* Formulate the zContentExprlist text */
   190485   if( rc==SQLITE_OK ){
   190486     rc = fts5ConfigMakeExprlist(pRet);
   190487   }
   190488 
   190489   if( rc!=SQLITE_OK ){
   190490     sqlite3Fts5ConfigFree(pRet);
   190491     *ppOut = 0;
   190492   }
   190493   return rc;
   190494 }
   190495 
   190496 /*
   190497 ** Free the configuration object passed as the only argument.
   190498 */
   190499 static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
   190500   if( pConfig ){
   190501     int i;
   190502     if( pConfig->pTok ){
   190503       pConfig->pTokApi->xDelete(pConfig->pTok);
   190504     }
   190505     sqlite3_free(pConfig->zDb);
   190506     sqlite3_free(pConfig->zName);
   190507     for(i=0; i<pConfig->nCol; i++){
   190508       sqlite3_free(pConfig->azCol[i]);
   190509     }
   190510     sqlite3_free(pConfig->azCol);
   190511     sqlite3_free(pConfig->aPrefix);
   190512     sqlite3_free(pConfig->zRank);
   190513     sqlite3_free(pConfig->zRankArgs);
   190514     sqlite3_free(pConfig->zContent);
   190515     sqlite3_free(pConfig->zContentRowid);
   190516     sqlite3_free(pConfig->zContentExprlist);
   190517     sqlite3_free(pConfig);
   190518   }
   190519 }
   190520 
   190521 /*
   190522 ** Call sqlite3_declare_vtab() based on the contents of the configuration
   190523 ** object passed as the only argument. Return SQLITE_OK if successful, or
   190524 ** an SQLite error code if an error occurs.
   190525 */
   190526 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
   190527   int i;
   190528   int rc = SQLITE_OK;
   190529   char *zSql;
   190530 
   190531   zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
   190532   for(i=0; zSql && i<pConfig->nCol; i++){
   190533     const char *zSep = (i==0?"":", ");
   190534     zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
   190535   }
   190536   zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
   190537       zSql, pConfig->zName, FTS5_RANK_NAME
   190538   );
   190539 
   190540   assert( zSql || rc==SQLITE_NOMEM );
   190541   if( zSql ){
   190542     rc = sqlite3_declare_vtab(pConfig->db, zSql);
   190543     sqlite3_free(zSql);
   190544   }
   190545 
   190546   return rc;
   190547 }
   190548 
   190549 /*
   190550 ** Tokenize the text passed via the second and third arguments.
   190551 **
   190552 ** The callback is invoked once for each token in the input text. The
   190553 ** arguments passed to it are, in order:
   190554 **
   190555 **     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
   190556 **     const char *pToken  // Pointer to buffer containing token
   190557 **     int nToken          // Size of token in bytes
   190558 **     int iStart          // Byte offset of start of token within input text
   190559 **     int iEnd            // Byte offset of end of token within input text
   190560 **     int iPos            // Position of token in input (first token is 0)
   190561 **
   190562 ** If the callback returns a non-zero value the tokenization is abandoned
   190563 ** and no further callbacks are issued.
   190564 **
   190565 ** This function returns SQLITE_OK if successful or an SQLite error code
   190566 ** if an error occurs. If the tokenization was abandoned early because
   190567 ** the callback returned SQLITE_DONE, this is not an error and this function
   190568 ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
   190569 ** because the callback returned another non-zero value, it is assumed
   190570 ** to be an SQLite error code and returned to the caller.
   190571 */
   190572 static int sqlite3Fts5Tokenize(
   190573   Fts5Config *pConfig,            /* FTS5 Configuration object */
   190574   int flags,                      /* FTS5_TOKENIZE_* flags */
   190575   const char *pText, int nText,   /* Text to tokenize */
   190576   void *pCtx,                     /* Context passed to xToken() */
   190577   int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
   190578 ){
   190579   if( pText==0 ) return SQLITE_OK;
   190580   return pConfig->pTokApi->xTokenize(
   190581       pConfig->pTok, pCtx, flags, pText, nText, xToken
   190582   );
   190583 }
   190584 
   190585 /*
   190586 ** Argument pIn points to the first character in what is expected to be
   190587 ** a comma-separated list of SQL literals followed by a ')' character.
   190588 ** If it actually is this, return a pointer to the ')'. Otherwise, return
   190589 ** NULL to indicate a parse error.
   190590 */
   190591 static const char *fts5ConfigSkipArgs(const char *pIn){
   190592   const char *p = pIn;
   190593 
   190594   while( 1 ){
   190595     p = fts5ConfigSkipWhitespace(p);
   190596     p = fts5ConfigSkipLiteral(p);
   190597     p = fts5ConfigSkipWhitespace(p);
   190598     if( p==0 || *p==')' ) break;
   190599     if( *p!=',' ){
   190600       p = 0;
   190601       break;
   190602     }
   190603     p++;
   190604   }
   190605 
   190606   return p;
   190607 }
   190608 
   190609 /*
   190610 ** Parameter zIn contains a rank() function specification. The format of
   190611 ** this is:
   190612 **
   190613 **   + Bareword (function name)
   190614 **   + Open parenthesis - "("
   190615 **   + Zero or more SQL literals in a comma separated list
   190616 **   + Close parenthesis - ")"
   190617 */
   190618 static int sqlite3Fts5ConfigParseRank(
   190619   const char *zIn,                /* Input string */
   190620   char **pzRank,                  /* OUT: Rank function name */
   190621   char **pzRankArgs               /* OUT: Rank function arguments */
   190622 ){
   190623   const char *p = zIn;
   190624   const char *pRank;
   190625   char *zRank = 0;
   190626   char *zRankArgs = 0;
   190627   int rc = SQLITE_OK;
   190628 
   190629   *pzRank = 0;
   190630   *pzRankArgs = 0;
   190631 
   190632   if( p==0 ){
   190633     rc = SQLITE_ERROR;
   190634   }else{
   190635     p = fts5ConfigSkipWhitespace(p);
   190636     pRank = p;
   190637     p = fts5ConfigSkipBareword(p);
   190638 
   190639     if( p ){
   190640       zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
   190641       if( zRank ) memcpy(zRank, pRank, p-pRank);
   190642     }else{
   190643       rc = SQLITE_ERROR;
   190644     }
   190645 
   190646     if( rc==SQLITE_OK ){
   190647       p = fts5ConfigSkipWhitespace(p);
   190648       if( *p!='(' ) rc = SQLITE_ERROR;
   190649       p++;
   190650     }
   190651     if( rc==SQLITE_OK ){
   190652       const char *pArgs;
   190653       p = fts5ConfigSkipWhitespace(p);
   190654       pArgs = p;
   190655       if( *p!=')' ){
   190656         p = fts5ConfigSkipArgs(p);
   190657         if( p==0 ){
   190658           rc = SQLITE_ERROR;
   190659         }else{
   190660           zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
   190661           if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
   190662         }
   190663       }
   190664     }
   190665   }
   190666 
   190667   if( rc!=SQLITE_OK ){
   190668     sqlite3_free(zRank);
   190669     assert( zRankArgs==0 );
   190670   }else{
   190671     *pzRank = zRank;
   190672     *pzRankArgs = zRankArgs;
   190673   }
   190674   return rc;
   190675 }
   190676 
   190677 static int sqlite3Fts5ConfigSetValue(
   190678   Fts5Config *pConfig,
   190679   const char *zKey,
   190680   sqlite3_value *pVal,
   190681   int *pbBadkey
   190682 ){
   190683   int rc = SQLITE_OK;
   190684 
   190685   if( 0==sqlite3_stricmp(zKey, "pgsz") ){
   190686     int pgsz = 0;
   190687     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
   190688       pgsz = sqlite3_value_int(pVal);
   190689     }
   190690     if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
   190691       *pbBadkey = 1;
   190692     }else{
   190693       pConfig->pgsz = pgsz;
   190694     }
   190695   }
   190696 
   190697   else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
   190698     int nHashSize = -1;
   190699     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
   190700       nHashSize = sqlite3_value_int(pVal);
   190701     }
   190702     if( nHashSize<=0 ){
   190703       *pbBadkey = 1;
   190704     }else{
   190705       pConfig->nHashSize = nHashSize;
   190706     }
   190707   }
   190708 
   190709   else if( 0==sqlite3_stricmp(zKey, "automerge") ){
   190710     int nAutomerge = -1;
   190711     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
   190712       nAutomerge = sqlite3_value_int(pVal);
   190713     }
   190714     if( nAutomerge<0 || nAutomerge>64 ){
   190715       *pbBadkey = 1;
   190716     }else{
   190717       if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
   190718       pConfig->nAutomerge = nAutomerge;
   190719     }
   190720   }
   190721 
   190722   else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
   190723     int nUsermerge = -1;
   190724     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
   190725       nUsermerge = sqlite3_value_int(pVal);
   190726     }
   190727     if( nUsermerge<2 || nUsermerge>16 ){
   190728       *pbBadkey = 1;
   190729     }else{
   190730       pConfig->nUsermerge = nUsermerge;
   190731     }
   190732   }
   190733 
   190734   else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
   190735     int nCrisisMerge = -1;
   190736     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
   190737       nCrisisMerge = sqlite3_value_int(pVal);
   190738     }
   190739     if( nCrisisMerge<0 ){
   190740       *pbBadkey = 1;
   190741     }else{
   190742       if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
   190743       pConfig->nCrisisMerge = nCrisisMerge;
   190744     }
   190745   }
   190746 
   190747   else if( 0==sqlite3_stricmp(zKey, "rank") ){
   190748     const char *zIn = (const char*)sqlite3_value_text(pVal);
   190749     char *zRank;
   190750     char *zRankArgs;
   190751     rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
   190752     if( rc==SQLITE_OK ){
   190753       sqlite3_free(pConfig->zRank);
   190754       sqlite3_free(pConfig->zRankArgs);
   190755       pConfig->zRank = zRank;
   190756       pConfig->zRankArgs = zRankArgs;
   190757     }else if( rc==SQLITE_ERROR ){
   190758       rc = SQLITE_OK;
   190759       *pbBadkey = 1;
   190760     }
   190761   }else{
   190762     *pbBadkey = 1;
   190763   }
   190764   return rc;
   190765 }
   190766 
   190767 /*
   190768 ** Load the contents of the %_config table into memory.
   190769 */
   190770 static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
   190771   const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
   190772   char *zSql;
   190773   sqlite3_stmt *p = 0;
   190774   int rc = SQLITE_OK;
   190775   int iVersion = 0;
   190776 
   190777   /* Set default values */
   190778   pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
   190779   pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
   190780   pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
   190781   pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
   190782   pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
   190783 
   190784   zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
   190785   if( zSql ){
   190786     rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
   190787     sqlite3_free(zSql);
   190788   }
   190789 
   190790   assert( rc==SQLITE_OK || p==0 );
   190791   if( rc==SQLITE_OK ){
   190792     while( SQLITE_ROW==sqlite3_step(p) ){
   190793       const char *zK = (const char*)sqlite3_column_text(p, 0);
   190794       sqlite3_value *pVal = sqlite3_column_value(p, 1);
   190795       if( 0==sqlite3_stricmp(zK, "version") ){
   190796         iVersion = sqlite3_value_int(pVal);
   190797       }else{
   190798         int bDummy = 0;
   190799         sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
   190800       }
   190801     }
   190802     rc = sqlite3_finalize(p);
   190803   }
   190804 
   190805   if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
   190806     rc = SQLITE_ERROR;
   190807     if( pConfig->pzErrmsg ){
   190808       assert( 0==*pConfig->pzErrmsg );
   190809       *pConfig->pzErrmsg = sqlite3_mprintf(
   190810           "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
   190811           iVersion, FTS5_CURRENT_VERSION
   190812       );
   190813     }
   190814   }
   190815 
   190816   if( rc==SQLITE_OK ){
   190817     pConfig->iCookie = iCookie;
   190818   }
   190819   return rc;
   190820 }
   190821 
   190822 /*
   190823 ** 2014 May 31
   190824 **
   190825 ** The author disclaims copyright to this source code.  In place of
   190826 ** a legal notice, here is a blessing:
   190827 **
   190828 **    May you do good and not evil.
   190829 **    May you find forgiveness for yourself and forgive others.
   190830 **    May you share freely, never taking more than you give.
   190831 **
   190832 ******************************************************************************
   190833 **
   190834 */
   190835 
   190836 
   190837 
   190838 /* #include "fts5Int.h" */
   190839 /* #include "fts5parse.h" */
   190840 
   190841 /*
   190842 ** All token types in the generated fts5parse.h file are greater than 0.
   190843 */
   190844 #define FTS5_EOF 0
   190845 
   190846 #define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   190847 
   190848 typedef struct Fts5ExprTerm Fts5ExprTerm;
   190849 
   190850 /*
   190851 ** Functions generated by lemon from fts5parse.y.
   190852 */
   190853 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
   190854 static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
   190855 static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
   190856 #ifndef NDEBUG
   190857 /* #include <stdio.h> */
   190858 static void sqlite3Fts5ParserTrace(FILE*, char*);
   190859 #endif
   190860 
   190861 
   190862 struct Fts5Expr {
   190863   Fts5Index *pIndex;
   190864   Fts5Config *pConfig;
   190865   Fts5ExprNode *pRoot;
   190866   int bDesc;                      /* Iterate in descending rowid order */
   190867   int nPhrase;                    /* Number of phrases in expression */
   190868   Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
   190869 };
   190870 
   190871 /*
   190872 ** eType:
   190873 **   Expression node type. Always one of:
   190874 **
   190875 **       FTS5_AND                 (nChild, apChild valid)
   190876 **       FTS5_OR                  (nChild, apChild valid)
   190877 **       FTS5_NOT                 (nChild, apChild valid)
   190878 **       FTS5_STRING              (pNear valid)
   190879 **       FTS5_TERM                (pNear valid)
   190880 */
   190881 struct Fts5ExprNode {
   190882   int eType;                      /* Node type */
   190883   int bEof;                       /* True at EOF */
   190884   int bNomatch;                   /* True if entry is not a match */
   190885 
   190886   /* Next method for this node. */
   190887   int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
   190888 
   190889   i64 iRowid;                     /* Current rowid */
   190890   Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
   190891 
   190892   /* Child nodes. For a NOT node, this array always contains 2 entries. For
   190893   ** AND or OR nodes, it contains 2 or more entries.  */
   190894   int nChild;                     /* Number of child nodes */
   190895   Fts5ExprNode *apChild[1];       /* Array of child nodes */
   190896 };
   190897 
   190898 #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
   190899 
   190900 /*
   190901 ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
   190902 ** used as if it has the same signature as the xNext() methods themselves.
   190903 */
   190904 #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
   190905 
   190906 /*
   190907 ** An instance of the following structure represents a single search term
   190908 ** or term prefix.
   190909 */
   190910 struct Fts5ExprTerm {
   190911   u8 bPrefix;                     /* True for a prefix term */
   190912   u8 bFirst;                      /* True if token must be first in column */
   190913   char *zTerm;                    /* nul-terminated term */
   190914   Fts5IndexIter *pIter;           /* Iterator for this term */
   190915   Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
   190916 };
   190917 
   190918 /*
   190919 ** A phrase. One or more terms that must appear in a contiguous sequence
   190920 ** within a document for it to match.
   190921 */
   190922 struct Fts5ExprPhrase {
   190923   Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
   190924   Fts5Buffer poslist;             /* Current position list */
   190925   int nTerm;                      /* Number of entries in aTerm[] */
   190926   Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
   190927 };
   190928 
   190929 /*
   190930 ** One or more phrases that must appear within a certain token distance of
   190931 ** each other within each matching document.
   190932 */
   190933 struct Fts5ExprNearset {
   190934   int nNear;                      /* NEAR parameter */
   190935   Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
   190936   int nPhrase;                    /* Number of entries in aPhrase[] array */
   190937   Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
   190938 };
   190939 
   190940 
   190941 /*
   190942 ** Parse context.
   190943 */
   190944 struct Fts5Parse {
   190945   Fts5Config *pConfig;
   190946   char *zErr;
   190947   int rc;
   190948   int nPhrase;                    /* Size of apPhrase array */
   190949   Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
   190950   Fts5ExprNode *pExpr;            /* Result of a successful parse */
   190951 };
   190952 
   190953 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
   190954   va_list ap;
   190955   va_start(ap, zFmt);
   190956   if( pParse->rc==SQLITE_OK ){
   190957     pParse->zErr = sqlite3_vmprintf(zFmt, ap);
   190958     pParse->rc = SQLITE_ERROR;
   190959   }
   190960   va_end(ap);
   190961 }
   190962 
   190963 static int fts5ExprIsspace(char t){
   190964   return t==' ' || t=='\t' || t=='\n' || t=='\r';
   190965 }
   190966 
   190967 /*
   190968 ** Read the first token from the nul-terminated string at *pz.
   190969 */
   190970 static int fts5ExprGetToken(
   190971   Fts5Parse *pParse,
   190972   const char **pz,                /* IN/OUT: Pointer into buffer */
   190973   Fts5Token *pToken
   190974 ){
   190975   const char *z = *pz;
   190976   int tok;
   190977 
   190978   /* Skip past any whitespace */
   190979   while( fts5ExprIsspace(*z) ) z++;
   190980 
   190981   pToken->p = z;
   190982   pToken->n = 1;
   190983   switch( *z ){
   190984     case '(':  tok = FTS5_LP;    break;
   190985     case ')':  tok = FTS5_RP;    break;
   190986     case '{':  tok = FTS5_LCP;   break;
   190987     case '}':  tok = FTS5_RCP;   break;
   190988     case ':':  tok = FTS5_COLON; break;
   190989     case ',':  tok = FTS5_COMMA; break;
   190990     case '+':  tok = FTS5_PLUS;  break;
   190991     case '*':  tok = FTS5_STAR;  break;
   190992     case '-':  tok = FTS5_MINUS; break;
   190993     case '^':  tok = FTS5_CARET; break;
   190994     case '\0': tok = FTS5_EOF;   break;
   190995 
   190996     case '"': {
   190997       const char *z2;
   190998       tok = FTS5_STRING;
   190999 
   191000       for(z2=&z[1]; 1; z2++){
   191001         if( z2[0]=='"' ){
   191002           z2++;
   191003           if( z2[0]!='"' ) break;
   191004         }
   191005         if( z2[0]=='\0' ){
   191006           sqlite3Fts5ParseError(pParse, "unterminated string");
   191007           return FTS5_EOF;
   191008         }
   191009       }
   191010       pToken->n = (z2 - z);
   191011       break;
   191012     }
   191013 
   191014     default: {
   191015       const char *z2;
   191016       if( sqlite3Fts5IsBareword(z[0])==0 ){
   191017         sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
   191018         return FTS5_EOF;
   191019       }
   191020       tok = FTS5_STRING;
   191021       for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
   191022       pToken->n = (z2 - z);
   191023       if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
   191024       if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
   191025       if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
   191026       break;
   191027     }
   191028   }
   191029 
   191030   *pz = &pToken->p[pToken->n];
   191031   return tok;
   191032 }
   191033 
   191034 static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
   191035 static void fts5ParseFree(void *p){ sqlite3_free(p); }
   191036 
   191037 static int sqlite3Fts5ExprNew(
   191038   Fts5Config *pConfig,            /* FTS5 Configuration */
   191039   int iCol,
   191040   const char *zExpr,              /* Expression text */
   191041   Fts5Expr **ppNew,
   191042   char **pzErr
   191043 ){
   191044   Fts5Parse sParse;
   191045   Fts5Token token;
   191046   const char *z = zExpr;
   191047   int t;                          /* Next token type */
   191048   void *pEngine;
   191049   Fts5Expr *pNew;
   191050 
   191051   *ppNew = 0;
   191052   *pzErr = 0;
   191053   memset(&sParse, 0, sizeof(sParse));
   191054   pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
   191055   if( pEngine==0 ){ return SQLITE_NOMEM; }
   191056   sParse.pConfig = pConfig;
   191057 
   191058   do {
   191059     t = fts5ExprGetToken(&sParse, &z, &token);
   191060     sqlite3Fts5Parser(pEngine, t, token, &sParse);
   191061   }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
   191062   sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
   191063 
   191064   /* If the LHS of the MATCH expression was a user column, apply the
   191065   ** implicit column-filter.  */
   191066   if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
   191067     int n = sizeof(Fts5Colset);
   191068     Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
   191069     if( pColset ){
   191070       pColset->nCol = 1;
   191071       pColset->aiCol[0] = iCol;
   191072       sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
   191073     }
   191074   }
   191075 
   191076   assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
   191077   if( sParse.rc==SQLITE_OK ){
   191078     *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
   191079     if( pNew==0 ){
   191080       sParse.rc = SQLITE_NOMEM;
   191081       sqlite3Fts5ParseNodeFree(sParse.pExpr);
   191082     }else{
   191083       if( !sParse.pExpr ){
   191084         const int nByte = sizeof(Fts5ExprNode);
   191085         pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
   191086         if( pNew->pRoot ){
   191087           pNew->pRoot->bEof = 1;
   191088         }
   191089       }else{
   191090         pNew->pRoot = sParse.pExpr;
   191091       }
   191092       pNew->pIndex = 0;
   191093       pNew->pConfig = pConfig;
   191094       pNew->apExprPhrase = sParse.apPhrase;
   191095       pNew->nPhrase = sParse.nPhrase;
   191096       sParse.apPhrase = 0;
   191097     }
   191098   }else{
   191099     sqlite3Fts5ParseNodeFree(sParse.pExpr);
   191100   }
   191101 
   191102   sqlite3_free(sParse.apPhrase);
   191103   *pzErr = sParse.zErr;
   191104   return sParse.rc;
   191105 }
   191106 
   191107 /*
   191108 ** Free the expression node object passed as the only argument.
   191109 */
   191110 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
   191111   if( p ){
   191112     int i;
   191113     for(i=0; i<p->nChild; i++){
   191114       sqlite3Fts5ParseNodeFree(p->apChild[i]);
   191115     }
   191116     sqlite3Fts5ParseNearsetFree(p->pNear);
   191117     sqlite3_free(p);
   191118   }
   191119 }
   191120 
   191121 /*
   191122 ** Free the expression object passed as the only argument.
   191123 */
   191124 static void sqlite3Fts5ExprFree(Fts5Expr *p){
   191125   if( p ){
   191126     sqlite3Fts5ParseNodeFree(p->pRoot);
   191127     sqlite3_free(p->apExprPhrase);
   191128     sqlite3_free(p);
   191129   }
   191130 }
   191131 
   191132 /*
   191133 ** Argument pTerm must be a synonym iterator. Return the current rowid
   191134 ** that it points to.
   191135 */
   191136 static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
   191137   i64 iRet = 0;
   191138   int bRetValid = 0;
   191139   Fts5ExprTerm *p;
   191140 
   191141   assert( pTerm->pSynonym );
   191142   assert( bDesc==0 || bDesc==1 );
   191143   for(p=pTerm; p; p=p->pSynonym){
   191144     if( 0==sqlite3Fts5IterEof(p->pIter) ){
   191145       i64 iRowid = p->pIter->iRowid;
   191146       if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
   191147         iRet = iRowid;
   191148         bRetValid = 1;
   191149       }
   191150     }
   191151   }
   191152 
   191153   if( pbEof && bRetValid==0 ) *pbEof = 1;
   191154   return iRet;
   191155 }
   191156 
   191157 /*
   191158 ** Argument pTerm must be a synonym iterator.
   191159 */
   191160 static int fts5ExprSynonymList(
   191161   Fts5ExprTerm *pTerm,
   191162   i64 iRowid,
   191163   Fts5Buffer *pBuf,               /* Use this buffer for space if required */
   191164   u8 **pa, int *pn
   191165 ){
   191166   Fts5PoslistReader aStatic[4];
   191167   Fts5PoslistReader *aIter = aStatic;
   191168   int nIter = 0;
   191169   int nAlloc = 4;
   191170   int rc = SQLITE_OK;
   191171   Fts5ExprTerm *p;
   191172 
   191173   assert( pTerm->pSynonym );
   191174   for(p=pTerm; p; p=p->pSynonym){
   191175     Fts5IndexIter *pIter = p->pIter;
   191176     if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
   191177       if( pIter->nData==0 ) continue;
   191178       if( nIter==nAlloc ){
   191179         int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
   191180         Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
   191181         if( aNew==0 ){
   191182           rc = SQLITE_NOMEM;
   191183           goto synonym_poslist_out;
   191184         }
   191185         memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
   191186         nAlloc = nAlloc*2;
   191187         if( aIter!=aStatic ) sqlite3_free(aIter);
   191188         aIter = aNew;
   191189       }
   191190       sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
   191191       assert( aIter[nIter].bEof==0 );
   191192       nIter++;
   191193     }
   191194   }
   191195 
   191196   if( nIter==1 ){
   191197     *pa = (u8*)aIter[0].a;
   191198     *pn = aIter[0].n;
   191199   }else{
   191200     Fts5PoslistWriter writer = {0};
   191201     i64 iPrev = -1;
   191202     fts5BufferZero(pBuf);
   191203     while( 1 ){
   191204       int i;
   191205       i64 iMin = FTS5_LARGEST_INT64;
   191206       for(i=0; i<nIter; i++){
   191207         if( aIter[i].bEof==0 ){
   191208           if( aIter[i].iPos==iPrev ){
   191209             if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
   191210           }
   191211           if( aIter[i].iPos<iMin ){
   191212             iMin = aIter[i].iPos;
   191213           }
   191214         }
   191215       }
   191216       if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
   191217       rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
   191218       iPrev = iMin;
   191219     }
   191220     if( rc==SQLITE_OK ){
   191221       *pa = pBuf->p;
   191222       *pn = pBuf->n;
   191223     }
   191224   }
   191225 
   191226  synonym_poslist_out:
   191227   if( aIter!=aStatic ) sqlite3_free(aIter);
   191228   return rc;
   191229 }
   191230 
   191231 
   191232 /*
   191233 ** All individual term iterators in pPhrase are guaranteed to be valid and
   191234 ** pointing to the same rowid when this function is called. This function
   191235 ** checks if the current rowid really is a match, and if so populates
   191236 ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
   191237 ** is set to true if this is really a match, or false otherwise.
   191238 **
   191239 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
   191240 ** otherwise. It is not considered an error code if the current rowid is
   191241 ** not a match.
   191242 */
   191243 static int fts5ExprPhraseIsMatch(
   191244   Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
   191245   Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
   191246   int *pbMatch                    /* OUT: Set to true if really a match */
   191247 ){
   191248   Fts5PoslistWriter writer = {0};
   191249   Fts5PoslistReader aStatic[4];
   191250   Fts5PoslistReader *aIter = aStatic;
   191251   int i;
   191252   int rc = SQLITE_OK;
   191253   int bFirst = pPhrase->aTerm[0].bFirst;
   191254 
   191255   fts5BufferZero(&pPhrase->poslist);
   191256 
   191257   /* If the aStatic[] array is not large enough, allocate a large array
   191258   ** using sqlite3_malloc(). This approach could be improved upon. */
   191259   if( pPhrase->nTerm>ArraySize(aStatic) ){
   191260     int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
   191261     aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
   191262     if( !aIter ) return SQLITE_NOMEM;
   191263   }
   191264   memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
   191265 
   191266   /* Initialize a term iterator for each term in the phrase */
   191267   for(i=0; i<pPhrase->nTerm; i++){
   191268     Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
   191269     int n = 0;
   191270     int bFlag = 0;
   191271     u8 *a = 0;
   191272     if( pTerm->pSynonym ){
   191273       Fts5Buffer buf = {0, 0, 0};
   191274       rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
   191275       if( rc ){
   191276         sqlite3_free(a);
   191277         goto ismatch_out;
   191278       }
   191279       if( a==buf.p ) bFlag = 1;
   191280     }else{
   191281       a = (u8*)pTerm->pIter->pData;
   191282       n = pTerm->pIter->nData;
   191283     }
   191284     sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
   191285     aIter[i].bFlag = (u8)bFlag;
   191286     if( aIter[i].bEof ) goto ismatch_out;
   191287   }
   191288 
   191289   while( 1 ){
   191290     int bMatch;
   191291     i64 iPos = aIter[0].iPos;
   191292     do {
   191293       bMatch = 1;
   191294       for(i=0; i<pPhrase->nTerm; i++){
   191295         Fts5PoslistReader *pPos = &aIter[i];
   191296         i64 iAdj = iPos + i;
   191297         if( pPos->iPos!=iAdj ){
   191298           bMatch = 0;
   191299           while( pPos->iPos<iAdj ){
   191300             if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
   191301           }
   191302           if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
   191303         }
   191304       }
   191305     }while( bMatch==0 );
   191306 
   191307     /* Append position iPos to the output */
   191308     if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
   191309       rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
   191310       if( rc!=SQLITE_OK ) goto ismatch_out;
   191311     }
   191312 
   191313     for(i=0; i<pPhrase->nTerm; i++){
   191314       if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
   191315     }
   191316   }
   191317 
   191318  ismatch_out:
   191319   *pbMatch = (pPhrase->poslist.n>0);
   191320   for(i=0; i<pPhrase->nTerm; i++){
   191321     if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
   191322   }
   191323   if( aIter!=aStatic ) sqlite3_free(aIter);
   191324   return rc;
   191325 }
   191326 
   191327 typedef struct Fts5LookaheadReader Fts5LookaheadReader;
   191328 struct Fts5LookaheadReader {
   191329   const u8 *a;                    /* Buffer containing position list */
   191330   int n;                          /* Size of buffer a[] in bytes */
   191331   int i;                          /* Current offset in position list */
   191332   i64 iPos;                       /* Current position */
   191333   i64 iLookahead;                 /* Next position */
   191334 };
   191335 
   191336 #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
   191337 
   191338 static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
   191339   p->iPos = p->iLookahead;
   191340   if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
   191341     p->iLookahead = FTS5_LOOKAHEAD_EOF;
   191342   }
   191343   return (p->iPos==FTS5_LOOKAHEAD_EOF);
   191344 }
   191345 
   191346 static int fts5LookaheadReaderInit(
   191347   const u8 *a, int n,             /* Buffer to read position list from */
   191348   Fts5LookaheadReader *p          /* Iterator object to initialize */
   191349 ){
   191350   memset(p, 0, sizeof(Fts5LookaheadReader));
   191351   p->a = a;
   191352   p->n = n;
   191353   fts5LookaheadReaderNext(p);
   191354   return fts5LookaheadReaderNext(p);
   191355 }
   191356 
   191357 typedef struct Fts5NearTrimmer Fts5NearTrimmer;
   191358 struct Fts5NearTrimmer {
   191359   Fts5LookaheadReader reader;     /* Input iterator */
   191360   Fts5PoslistWriter writer;       /* Writer context */
   191361   Fts5Buffer *pOut;               /* Output poslist */
   191362 };
   191363 
   191364 /*
   191365 ** The near-set object passed as the first argument contains more than
   191366 ** one phrase. All phrases currently point to the same row. The
   191367 ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
   191368 ** tests if the current row contains instances of each phrase sufficiently
   191369 ** close together to meet the NEAR constraint. Non-zero is returned if it
   191370 ** does, or zero otherwise.
   191371 **
   191372 ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
   191373 ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
   191374 ** occurs within this function (*pRc) is set accordingly before returning.
   191375 ** The return value is undefined in both these cases.
   191376 **
   191377 ** If no error occurs and non-zero (a match) is returned, the position-list
   191378 ** of each phrase object is edited to contain only those entries that
   191379 ** meet the constraint before returning.
   191380 */
   191381 static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
   191382   Fts5NearTrimmer aStatic[4];
   191383   Fts5NearTrimmer *a = aStatic;
   191384   Fts5ExprPhrase **apPhrase = pNear->apPhrase;
   191385 
   191386   int i;
   191387   int rc = *pRc;
   191388   int bMatch;
   191389 
   191390   assert( pNear->nPhrase>1 );
   191391 
   191392   /* If the aStatic[] array is not large enough, allocate a large array
   191393   ** using sqlite3_malloc(). This approach could be improved upon. */
   191394   if( pNear->nPhrase>ArraySize(aStatic) ){
   191395     int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
   191396     a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
   191397   }else{
   191398     memset(aStatic, 0, sizeof(aStatic));
   191399   }
   191400   if( rc!=SQLITE_OK ){
   191401     *pRc = rc;
   191402     return 0;
   191403   }
   191404 
   191405   /* Initialize a lookahead iterator for each phrase. After passing the
   191406   ** buffer and buffer size to the lookaside-reader init function, zero
   191407   ** the phrase poslist buffer. The new poslist for the phrase (containing
   191408   ** the same entries as the original with some entries removed on account
   191409   ** of the NEAR constraint) is written over the original even as it is
   191410   ** being read. This is safe as the entries for the new poslist are a
   191411   ** subset of the old, so it is not possible for data yet to be read to
   191412   ** be overwritten.  */
   191413   for(i=0; i<pNear->nPhrase; i++){
   191414     Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
   191415     fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
   191416     pPoslist->n = 0;
   191417     a[i].pOut = pPoslist;
   191418   }
   191419 
   191420   while( 1 ){
   191421     int iAdv;
   191422     i64 iMin;
   191423     i64 iMax;
   191424 
   191425     /* This block advances the phrase iterators until they point to a set of
   191426     ** entries that together comprise a match.  */
   191427     iMax = a[0].reader.iPos;
   191428     do {
   191429       bMatch = 1;
   191430       for(i=0; i<pNear->nPhrase; i++){
   191431         Fts5LookaheadReader *pPos = &a[i].reader;
   191432         iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
   191433         if( pPos->iPos<iMin || pPos->iPos>iMax ){
   191434           bMatch = 0;
   191435           while( pPos->iPos<iMin ){
   191436             if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
   191437           }
   191438           if( pPos->iPos>iMax ) iMax = pPos->iPos;
   191439         }
   191440       }
   191441     }while( bMatch==0 );
   191442 
   191443     /* Add an entry to each output position list */
   191444     for(i=0; i<pNear->nPhrase; i++){
   191445       i64 iPos = a[i].reader.iPos;
   191446       Fts5PoslistWriter *pWriter = &a[i].writer;
   191447       if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
   191448         sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
   191449       }
   191450     }
   191451 
   191452     iAdv = 0;
   191453     iMin = a[0].reader.iLookahead;
   191454     for(i=0; i<pNear->nPhrase; i++){
   191455       if( a[i].reader.iLookahead < iMin ){
   191456         iMin = a[i].reader.iLookahead;
   191457         iAdv = i;
   191458       }
   191459     }
   191460     if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
   191461   }
   191462 
   191463   ismatch_out: {
   191464     int bRet = a[0].pOut->n>0;
   191465     *pRc = rc;
   191466     if( a!=aStatic ) sqlite3_free(a);
   191467     return bRet;
   191468   }
   191469 }
   191470 
   191471 /*
   191472 ** Advance iterator pIter until it points to a value equal to or laster
   191473 ** than the initial value of *piLast. If this means the iterator points
   191474 ** to a value laster than *piLast, update *piLast to the new lastest value.
   191475 **
   191476 ** If the iterator reaches EOF, set *pbEof to true before returning. If
   191477 ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
   191478 ** are set, return a non-zero value. Otherwise, return zero.
   191479 */
   191480 static int fts5ExprAdvanceto(
   191481   Fts5IndexIter *pIter,           /* Iterator to advance */
   191482   int bDesc,                      /* True if iterator is "rowid DESC" */
   191483   i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
   191484   int *pRc,                       /* OUT: Error code */
   191485   int *pbEof                      /* OUT: Set to true if EOF */
   191486 ){
   191487   i64 iLast = *piLast;
   191488   i64 iRowid;
   191489 
   191490   iRowid = pIter->iRowid;
   191491   if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
   191492     int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
   191493     if( rc || sqlite3Fts5IterEof(pIter) ){
   191494       *pRc = rc;
   191495       *pbEof = 1;
   191496       return 1;
   191497     }
   191498     iRowid = pIter->iRowid;
   191499     assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
   191500   }
   191501   *piLast = iRowid;
   191502 
   191503   return 0;
   191504 }
   191505 
   191506 static int fts5ExprSynonymAdvanceto(
   191507   Fts5ExprTerm *pTerm,            /* Term iterator to advance */
   191508   int bDesc,                      /* True if iterator is "rowid DESC" */
   191509   i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
   191510   int *pRc                        /* OUT: Error code */
   191511 ){
   191512   int rc = SQLITE_OK;
   191513   i64 iLast = *piLast;
   191514   Fts5ExprTerm *p;
   191515   int bEof = 0;
   191516 
   191517   for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
   191518     if( sqlite3Fts5IterEof(p->pIter)==0 ){
   191519       i64 iRowid = p->pIter->iRowid;
   191520       if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
   191521         rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
   191522       }
   191523     }
   191524   }
   191525 
   191526   if( rc!=SQLITE_OK ){
   191527     *pRc = rc;
   191528     bEof = 1;
   191529   }else{
   191530     *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
   191531   }
   191532   return bEof;
   191533 }
   191534 
   191535 
   191536 static int fts5ExprNearTest(
   191537   int *pRc,
   191538   Fts5Expr *pExpr,                /* Expression that pNear is a part of */
   191539   Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
   191540 ){
   191541   Fts5ExprNearset *pNear = pNode->pNear;
   191542   int rc = *pRc;
   191543 
   191544   if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
   191545     Fts5ExprTerm *pTerm;
   191546     Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
   191547     pPhrase->poslist.n = 0;
   191548     for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
   191549       Fts5IndexIter *pIter = pTerm->pIter;
   191550       if( sqlite3Fts5IterEof(pIter)==0 ){
   191551         if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
   191552           pPhrase->poslist.n = 1;
   191553         }
   191554       }
   191555     }
   191556     return pPhrase->poslist.n;
   191557   }else{
   191558     int i;
   191559 
   191560     /* Check that each phrase in the nearset matches the current row.
   191561     ** Populate the pPhrase->poslist buffers at the same time. If any
   191562     ** phrase is not a match, break out of the loop early.  */
   191563     for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
   191564       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
   191565       if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
   191566        || pNear->pColset || pPhrase->aTerm[0].bFirst
   191567       ){
   191568         int bMatch = 0;
   191569         rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
   191570         if( bMatch==0 ) break;
   191571       }else{
   191572         Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
   191573         fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
   191574       }
   191575     }
   191576 
   191577     *pRc = rc;
   191578     if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
   191579       return 1;
   191580     }
   191581     return 0;
   191582   }
   191583 }
   191584 
   191585 
   191586 /*
   191587 ** Initialize all term iterators in the pNear object. If any term is found
   191588 ** to match no documents at all, return immediately without initializing any
   191589 ** further iterators.
   191590 **
   191591 ** If an error occurs, return an SQLite error code. Otherwise, return
   191592 ** SQLITE_OK. It is not considered an error if some term matches zero
   191593 ** documents.
   191594 */
   191595 static int fts5ExprNearInitAll(
   191596   Fts5Expr *pExpr,
   191597   Fts5ExprNode *pNode
   191598 ){
   191599   Fts5ExprNearset *pNear = pNode->pNear;
   191600   int i;
   191601 
   191602   assert( pNode->bNomatch==0 );
   191603   for(i=0; i<pNear->nPhrase; i++){
   191604     Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
   191605     if( pPhrase->nTerm==0 ){
   191606       pNode->bEof = 1;
   191607       return SQLITE_OK;
   191608     }else{
   191609       int j;
   191610       for(j=0; j<pPhrase->nTerm; j++){
   191611         Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
   191612         Fts5ExprTerm *p;
   191613         int bHit = 0;
   191614 
   191615         for(p=pTerm; p; p=p->pSynonym){
   191616           int rc;
   191617           if( p->pIter ){
   191618             sqlite3Fts5IterClose(p->pIter);
   191619             p->pIter = 0;
   191620           }
   191621           rc = sqlite3Fts5IndexQuery(
   191622               pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
   191623               (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
   191624               (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
   191625               pNear->pColset,
   191626               &p->pIter
   191627           );
   191628           assert( (rc==SQLITE_OK)==(p->pIter!=0) );
   191629           if( rc!=SQLITE_OK ) return rc;
   191630           if( 0==sqlite3Fts5IterEof(p->pIter) ){
   191631             bHit = 1;
   191632           }
   191633         }
   191634 
   191635         if( bHit==0 ){
   191636           pNode->bEof = 1;
   191637           return SQLITE_OK;
   191638         }
   191639       }
   191640     }
   191641   }
   191642 
   191643   pNode->bEof = 0;
   191644   return SQLITE_OK;
   191645 }
   191646 
   191647 /*
   191648 ** If pExpr is an ASC iterator, this function returns a value with the
   191649 ** same sign as:
   191650 **
   191651 **   (iLhs - iRhs)
   191652 **
   191653 ** Otherwise, if this is a DESC iterator, the opposite is returned:
   191654 **
   191655 **   (iRhs - iLhs)
   191656 */
   191657 static int fts5RowidCmp(
   191658   Fts5Expr *pExpr,
   191659   i64 iLhs,
   191660   i64 iRhs
   191661 ){
   191662   assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
   191663   if( pExpr->bDesc==0 ){
   191664     if( iLhs<iRhs ) return -1;
   191665     return (iLhs > iRhs);
   191666   }else{
   191667     if( iLhs>iRhs ) return -1;
   191668     return (iLhs < iRhs);
   191669   }
   191670 }
   191671 
   191672 static void fts5ExprSetEof(Fts5ExprNode *pNode){
   191673   int i;
   191674   pNode->bEof = 1;
   191675   pNode->bNomatch = 0;
   191676   for(i=0; i<pNode->nChild; i++){
   191677     fts5ExprSetEof(pNode->apChild[i]);
   191678   }
   191679 }
   191680 
   191681 static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
   191682   if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
   191683     Fts5ExprNearset *pNear = pNode->pNear;
   191684     int i;
   191685     for(i=0; i<pNear->nPhrase; i++){
   191686       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
   191687       pPhrase->poslist.n = 0;
   191688     }
   191689   }else{
   191690     int i;
   191691     for(i=0; i<pNode->nChild; i++){
   191692       fts5ExprNodeZeroPoslist(pNode->apChild[i]);
   191693     }
   191694   }
   191695 }
   191696 
   191697 
   191698 
   191699 /*
   191700 ** Compare the values currently indicated by the two nodes as follows:
   191701 **
   191702 **    res = (*p1) - (*p2)
   191703 **
   191704 ** Nodes that point to values that come later in the iteration order are
   191705 ** considered to be larger. Nodes at EOF are the largest of all.
   191706 **
   191707 ** This means that if the iteration order is ASC, then numerically larger
   191708 ** rowids are considered larger. Or if it is the default DESC, numerically
   191709 ** smaller rowids are larger.
   191710 */
   191711 static int fts5NodeCompare(
   191712   Fts5Expr *pExpr,
   191713   Fts5ExprNode *p1,
   191714   Fts5ExprNode *p2
   191715 ){
   191716   if( p2->bEof ) return -1;
   191717   if( p1->bEof ) return +1;
   191718   return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
   191719 }
   191720 
   191721 /*
   191722 ** All individual term iterators in pNear are guaranteed to be valid when
   191723 ** this function is called. This function checks if all term iterators
   191724 ** point to the same rowid, and if not, advances them until they do.
   191725 ** If an EOF is reached before this happens, *pbEof is set to true before
   191726 ** returning.
   191727 **
   191728 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
   191729 ** otherwise. It is not considered an error code if an iterator reaches
   191730 ** EOF.
   191731 */
   191732 static int fts5ExprNodeTest_STRING(
   191733   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
   191734   Fts5ExprNode *pNode
   191735 ){
   191736   Fts5ExprNearset *pNear = pNode->pNear;
   191737   Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
   191738   int rc = SQLITE_OK;
   191739   i64 iLast;                      /* Lastest rowid any iterator points to */
   191740   int i, j;                       /* Phrase and token index, respectively */
   191741   int bMatch;                     /* True if all terms are at the same rowid */
   191742   const int bDesc = pExpr->bDesc;
   191743 
   191744   /* Check that this node should not be FTS5_TERM */
   191745   assert( pNear->nPhrase>1
   191746        || pNear->apPhrase[0]->nTerm>1
   191747        || pNear->apPhrase[0]->aTerm[0].pSynonym
   191748        || pNear->apPhrase[0]->aTerm[0].bFirst
   191749   );
   191750 
   191751   /* Initialize iLast, the "lastest" rowid any iterator points to. If the
   191752   ** iterator skips through rowids in the default ascending order, this means
   191753   ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
   191754   ** means the minimum rowid.  */
   191755   if( pLeft->aTerm[0].pSynonym ){
   191756     iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
   191757   }else{
   191758     iLast = pLeft->aTerm[0].pIter->iRowid;
   191759   }
   191760 
   191761   do {
   191762     bMatch = 1;
   191763     for(i=0; i<pNear->nPhrase; i++){
   191764       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
   191765       for(j=0; j<pPhrase->nTerm; j++){
   191766         Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
   191767         if( pTerm->pSynonym ){
   191768           i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
   191769           if( iRowid==iLast ) continue;
   191770           bMatch = 0;
   191771           if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
   191772             pNode->bNomatch = 0;
   191773             pNode->bEof = 1;
   191774             return rc;
   191775           }
   191776         }else{
   191777           Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
   191778           if( pIter->iRowid==iLast || pIter->bEof ) continue;
   191779           bMatch = 0;
   191780           if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
   191781             return rc;
   191782           }
   191783         }
   191784       }
   191785     }
   191786   }while( bMatch==0 );
   191787 
   191788   pNode->iRowid = iLast;
   191789   pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
   191790   assert( pNode->bEof==0 || pNode->bNomatch==0 );
   191791 
   191792   return rc;
   191793 }
   191794 
   191795 /*
   191796 ** Advance the first term iterator in the first phrase of pNear. Set output
   191797 ** variable *pbEof to true if it reaches EOF or if an error occurs.
   191798 **
   191799 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   191800 ** occurs.
   191801 */
   191802 static int fts5ExprNodeNext_STRING(
   191803   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
   191804   Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
   191805   int bFromValid,
   191806   i64 iFrom
   191807 ){
   191808   Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
   191809   int rc = SQLITE_OK;
   191810 
   191811   pNode->bNomatch = 0;
   191812   if( pTerm->pSynonym ){
   191813     int bEof = 1;
   191814     Fts5ExprTerm *p;
   191815 
   191816     /* Find the firstest rowid any synonym points to. */
   191817     i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
   191818 
   191819     /* Advance each iterator that currently points to iRowid. Or, if iFrom
   191820     ** is valid - each iterator that points to a rowid before iFrom.  */
   191821     for(p=pTerm; p; p=p->pSynonym){
   191822       if( sqlite3Fts5IterEof(p->pIter)==0 ){
   191823         i64 ii = p->pIter->iRowid;
   191824         if( ii==iRowid
   191825          || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
   191826         ){
   191827           if( bFromValid ){
   191828             rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
   191829           }else{
   191830             rc = sqlite3Fts5IterNext(p->pIter);
   191831           }
   191832           if( rc!=SQLITE_OK ) break;
   191833           if( sqlite3Fts5IterEof(p->pIter)==0 ){
   191834             bEof = 0;
   191835           }
   191836         }else{
   191837           bEof = 0;
   191838         }
   191839       }
   191840     }
   191841 
   191842     /* Set the EOF flag if either all synonym iterators are at EOF or an
   191843     ** error has occurred.  */
   191844     pNode->bEof = (rc || bEof);
   191845   }else{
   191846     Fts5IndexIter *pIter = pTerm->pIter;
   191847 
   191848     assert( Fts5NodeIsString(pNode) );
   191849     if( bFromValid ){
   191850       rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
   191851     }else{
   191852       rc = sqlite3Fts5IterNext(pIter);
   191853     }
   191854 
   191855     pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
   191856   }
   191857 
   191858   if( pNode->bEof==0 ){
   191859     assert( rc==SQLITE_OK );
   191860     rc = fts5ExprNodeTest_STRING(pExpr, pNode);
   191861   }
   191862 
   191863   return rc;
   191864 }
   191865 
   191866 
   191867 static int fts5ExprNodeTest_TERM(
   191868   Fts5Expr *pExpr,                /* Expression that pNear is a part of */
   191869   Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
   191870 ){
   191871   /* As this "NEAR" object is actually a single phrase that consists
   191872   ** of a single term only, grab pointers into the poslist managed by the
   191873   ** fts5_index.c iterator object. This is much faster than synthesizing
   191874   ** a new poslist the way we have to for more complicated phrase or NEAR
   191875   ** expressions.  */
   191876   Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
   191877   Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
   191878 
   191879   assert( pNode->eType==FTS5_TERM );
   191880   assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
   191881   assert( pPhrase->aTerm[0].pSynonym==0 );
   191882 
   191883   pPhrase->poslist.n = pIter->nData;
   191884   if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
   191885     pPhrase->poslist.p = (u8*)pIter->pData;
   191886   }
   191887   pNode->iRowid = pIter->iRowid;
   191888   pNode->bNomatch = (pPhrase->poslist.n==0);
   191889   return SQLITE_OK;
   191890 }
   191891 
   191892 /*
   191893 ** xNext() method for a node of type FTS5_TERM.
   191894 */
   191895 static int fts5ExprNodeNext_TERM(
   191896   Fts5Expr *pExpr,
   191897   Fts5ExprNode *pNode,
   191898   int bFromValid,
   191899   i64 iFrom
   191900 ){
   191901   int rc;
   191902   Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
   191903 
   191904   assert( pNode->bEof==0 );
   191905   if( bFromValid ){
   191906     rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
   191907   }else{
   191908     rc = sqlite3Fts5IterNext(pIter);
   191909   }
   191910   if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
   191911     rc = fts5ExprNodeTest_TERM(pExpr, pNode);
   191912   }else{
   191913     pNode->bEof = 1;
   191914     pNode->bNomatch = 0;
   191915   }
   191916   return rc;
   191917 }
   191918 
   191919 static void fts5ExprNodeTest_OR(
   191920   Fts5Expr *pExpr,                /* Expression of which pNode is a part */
   191921   Fts5ExprNode *pNode             /* Expression node to test */
   191922 ){
   191923   Fts5ExprNode *pNext = pNode->apChild[0];
   191924   int i;
   191925 
   191926   for(i=1; i<pNode->nChild; i++){
   191927     Fts5ExprNode *pChild = pNode->apChild[i];
   191928     int cmp = fts5NodeCompare(pExpr, pNext, pChild);
   191929     if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
   191930       pNext = pChild;
   191931     }
   191932   }
   191933   pNode->iRowid = pNext->iRowid;
   191934   pNode->bEof = pNext->bEof;
   191935   pNode->bNomatch = pNext->bNomatch;
   191936 }
   191937 
   191938 static int fts5ExprNodeNext_OR(
   191939   Fts5Expr *pExpr,
   191940   Fts5ExprNode *pNode,
   191941   int bFromValid,
   191942   i64 iFrom
   191943 ){
   191944   int i;
   191945   i64 iLast = pNode->iRowid;
   191946 
   191947   for(i=0; i<pNode->nChild; i++){
   191948     Fts5ExprNode *p1 = pNode->apChild[i];
   191949     assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
   191950     if( p1->bEof==0 ){
   191951       if( (p1->iRowid==iLast)
   191952        || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
   191953       ){
   191954         int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
   191955         if( rc!=SQLITE_OK ){
   191956           pNode->bNomatch = 0;
   191957           return rc;
   191958         }
   191959       }
   191960     }
   191961   }
   191962 
   191963   fts5ExprNodeTest_OR(pExpr, pNode);
   191964   return SQLITE_OK;
   191965 }
   191966 
   191967 /*
   191968 ** Argument pNode is an FTS5_AND node.
   191969 */
   191970 static int fts5ExprNodeTest_AND(
   191971   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
   191972   Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
   191973 ){
   191974   int iChild;
   191975   i64 iLast = pAnd->iRowid;
   191976   int rc = SQLITE_OK;
   191977   int bMatch;
   191978 
   191979   assert( pAnd->bEof==0 );
   191980   do {
   191981     pAnd->bNomatch = 0;
   191982     bMatch = 1;
   191983     for(iChild=0; iChild<pAnd->nChild; iChild++){
   191984       Fts5ExprNode *pChild = pAnd->apChild[iChild];
   191985       int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
   191986       if( cmp>0 ){
   191987         /* Advance pChild until it points to iLast or laster */
   191988         rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
   191989         if( rc!=SQLITE_OK ){
   191990           pAnd->bNomatch = 0;
   191991           return rc;
   191992         }
   191993       }
   191994 
   191995       /* If the child node is now at EOF, so is the parent AND node. Otherwise,
   191996       ** the child node is guaranteed to have advanced at least as far as
   191997       ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
   191998       ** new lastest rowid seen so far.  */
   191999       assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
   192000       if( pChild->bEof ){
   192001         fts5ExprSetEof(pAnd);
   192002         bMatch = 1;
   192003         break;
   192004       }else if( iLast!=pChild->iRowid ){
   192005         bMatch = 0;
   192006         iLast = pChild->iRowid;
   192007       }
   192008 
   192009       if( pChild->bNomatch ){
   192010         pAnd->bNomatch = 1;
   192011       }
   192012     }
   192013   }while( bMatch==0 );
   192014 
   192015   if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
   192016     fts5ExprNodeZeroPoslist(pAnd);
   192017   }
   192018   pAnd->iRowid = iLast;
   192019   return SQLITE_OK;
   192020 }
   192021 
   192022 static int fts5ExprNodeNext_AND(
   192023   Fts5Expr *pExpr,
   192024   Fts5ExprNode *pNode,
   192025   int bFromValid,
   192026   i64 iFrom
   192027 ){
   192028   int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
   192029   if( rc==SQLITE_OK ){
   192030     rc = fts5ExprNodeTest_AND(pExpr, pNode);
   192031   }else{
   192032     pNode->bNomatch = 0;
   192033   }
   192034   return rc;
   192035 }
   192036 
   192037 static int fts5ExprNodeTest_NOT(
   192038   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
   192039   Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
   192040 ){
   192041   int rc = SQLITE_OK;
   192042   Fts5ExprNode *p1 = pNode->apChild[0];
   192043   Fts5ExprNode *p2 = pNode->apChild[1];
   192044   assert( pNode->nChild==2 );
   192045 
   192046   while( rc==SQLITE_OK && p1->bEof==0 ){
   192047     int cmp = fts5NodeCompare(pExpr, p1, p2);
   192048     if( cmp>0 ){
   192049       rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
   192050       cmp = fts5NodeCompare(pExpr, p1, p2);
   192051     }
   192052     assert( rc!=SQLITE_OK || cmp<=0 );
   192053     if( cmp || p2->bNomatch ) break;
   192054     rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
   192055   }
   192056   pNode->bEof = p1->bEof;
   192057   pNode->bNomatch = p1->bNomatch;
   192058   pNode->iRowid = p1->iRowid;
   192059   if( p1->bEof ){
   192060     fts5ExprNodeZeroPoslist(p2);
   192061   }
   192062   return rc;
   192063 }
   192064 
   192065 static int fts5ExprNodeNext_NOT(
   192066   Fts5Expr *pExpr,
   192067   Fts5ExprNode *pNode,
   192068   int bFromValid,
   192069   i64 iFrom
   192070 ){
   192071   int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
   192072   if( rc==SQLITE_OK ){
   192073     rc = fts5ExprNodeTest_NOT(pExpr, pNode);
   192074   }
   192075   if( rc!=SQLITE_OK ){
   192076     pNode->bNomatch = 0;
   192077   }
   192078   return rc;
   192079 }
   192080 
   192081 /*
   192082 ** If pNode currently points to a match, this function returns SQLITE_OK
   192083 ** without modifying it. Otherwise, pNode is advanced until it does point
   192084 ** to a match or EOF is reached.
   192085 */
   192086 static int fts5ExprNodeTest(
   192087   Fts5Expr *pExpr,                /* Expression of which pNode is a part */
   192088   Fts5ExprNode *pNode             /* Expression node to test */
   192089 ){
   192090   int rc = SQLITE_OK;
   192091   if( pNode->bEof==0 ){
   192092     switch( pNode->eType ){
   192093 
   192094       case FTS5_STRING: {
   192095         rc = fts5ExprNodeTest_STRING(pExpr, pNode);
   192096         break;
   192097       }
   192098 
   192099       case FTS5_TERM: {
   192100         rc = fts5ExprNodeTest_TERM(pExpr, pNode);
   192101         break;
   192102       }
   192103 
   192104       case FTS5_AND: {
   192105         rc = fts5ExprNodeTest_AND(pExpr, pNode);
   192106         break;
   192107       }
   192108 
   192109       case FTS5_OR: {
   192110         fts5ExprNodeTest_OR(pExpr, pNode);
   192111         break;
   192112       }
   192113 
   192114       default: assert( pNode->eType==FTS5_NOT ); {
   192115         rc = fts5ExprNodeTest_NOT(pExpr, pNode);
   192116         break;
   192117       }
   192118     }
   192119   }
   192120   return rc;
   192121 }
   192122 
   192123 
   192124 /*
   192125 ** Set node pNode, which is part of expression pExpr, to point to the first
   192126 ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
   192127 **
   192128 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
   192129 ** It is not an error if there are no matches.
   192130 */
   192131 static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
   192132   int rc = SQLITE_OK;
   192133   pNode->bEof = 0;
   192134   pNode->bNomatch = 0;
   192135 
   192136   if( Fts5NodeIsString(pNode) ){
   192137     /* Initialize all term iterators in the NEAR object. */
   192138     rc = fts5ExprNearInitAll(pExpr, pNode);
   192139   }else if( pNode->xNext==0 ){
   192140     pNode->bEof = 1;
   192141   }else{
   192142     int i;
   192143     int nEof = 0;
   192144     for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
   192145       Fts5ExprNode *pChild = pNode->apChild[i];
   192146       rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
   192147       assert( pChild->bEof==0 || pChild->bEof==1 );
   192148       nEof += pChild->bEof;
   192149     }
   192150     pNode->iRowid = pNode->apChild[0]->iRowid;
   192151 
   192152     switch( pNode->eType ){
   192153       case FTS5_AND:
   192154         if( nEof>0 ) fts5ExprSetEof(pNode);
   192155         break;
   192156 
   192157       case FTS5_OR:
   192158         if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
   192159         break;
   192160 
   192161       default:
   192162         assert( pNode->eType==FTS5_NOT );
   192163         pNode->bEof = pNode->apChild[0]->bEof;
   192164         break;
   192165     }
   192166   }
   192167 
   192168   if( rc==SQLITE_OK ){
   192169     rc = fts5ExprNodeTest(pExpr, pNode);
   192170   }
   192171   return rc;
   192172 }
   192173 
   192174 
   192175 /*
   192176 ** Begin iterating through the set of documents in index pIdx matched by
   192177 ** the MATCH expression passed as the first argument. If the "bDesc"
   192178 ** parameter is passed a non-zero value, iteration is in descending rowid
   192179 ** order. Or, if it is zero, in ascending order.
   192180 **
   192181 ** If iterating in ascending rowid order (bDesc==0), the first document
   192182 ** visited is that with the smallest rowid that is larger than or equal
   192183 ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
   192184 ** then the first document visited must have a rowid smaller than or
   192185 ** equal to iFirst.
   192186 **
   192187 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
   192188 ** is not considered an error if the query does not match any documents.
   192189 */
   192190 static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
   192191   Fts5ExprNode *pRoot = p->pRoot;
   192192   int rc;                         /* Return code */
   192193 
   192194   p->pIndex = pIdx;
   192195   p->bDesc = bDesc;
   192196   rc = fts5ExprNodeFirst(p, pRoot);
   192197 
   192198   /* If not at EOF but the current rowid occurs earlier than iFirst in
   192199   ** the iteration order, move to document iFirst or later. */
   192200   if( rc==SQLITE_OK
   192201    && 0==pRoot->bEof
   192202    && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
   192203   ){
   192204     rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
   192205   }
   192206 
   192207   /* If the iterator is not at a real match, skip forward until it is. */
   192208   while( pRoot->bNomatch ){
   192209     assert( pRoot->bEof==0 && rc==SQLITE_OK );
   192210     rc = fts5ExprNodeNext(p, pRoot, 0, 0);
   192211   }
   192212   return rc;
   192213 }
   192214 
   192215 /*
   192216 ** Move to the next document
   192217 **
   192218 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
   192219 ** is not considered an error if the query does not match any documents.
   192220 */
   192221 static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
   192222   int rc;
   192223   Fts5ExprNode *pRoot = p->pRoot;
   192224   assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
   192225   do {
   192226     rc = fts5ExprNodeNext(p, pRoot, 0, 0);
   192227     assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
   192228   }while( pRoot->bNomatch );
   192229   if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
   192230     pRoot->bEof = 1;
   192231   }
   192232   return rc;
   192233 }
   192234 
   192235 static int sqlite3Fts5ExprEof(Fts5Expr *p){
   192236   return p->pRoot->bEof;
   192237 }
   192238 
   192239 static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
   192240   return p->pRoot->iRowid;
   192241 }
   192242 
   192243 static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
   192244   int rc = SQLITE_OK;
   192245   *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
   192246   return rc;
   192247 }
   192248 
   192249 /*
   192250 ** Free the phrase object passed as the only argument.
   192251 */
   192252 static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
   192253   if( pPhrase ){
   192254     int i;
   192255     for(i=0; i<pPhrase->nTerm; i++){
   192256       Fts5ExprTerm *pSyn;
   192257       Fts5ExprTerm *pNext;
   192258       Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
   192259       sqlite3_free(pTerm->zTerm);
   192260       sqlite3Fts5IterClose(pTerm->pIter);
   192261       for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
   192262         pNext = pSyn->pSynonym;
   192263         sqlite3Fts5IterClose(pSyn->pIter);
   192264         fts5BufferFree((Fts5Buffer*)&pSyn[1]);
   192265         sqlite3_free(pSyn);
   192266       }
   192267     }
   192268     if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
   192269     sqlite3_free(pPhrase);
   192270   }
   192271 }
   192272 
   192273 /*
   192274 ** Set the "bFirst" flag on the first token of the phrase passed as the
   192275 ** only argument.
   192276 */
   192277 static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
   192278   if( pPhrase && pPhrase->nTerm ){
   192279     pPhrase->aTerm[0].bFirst = 1;
   192280   }
   192281 }
   192282 
   192283 /*
   192284 ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
   192285 ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
   192286 ** appended to it and the results returned.
   192287 **
   192288 ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
   192289 ** NULL returned.
   192290 */
   192291 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
   192292   Fts5Parse *pParse,              /* Parse context */
   192293   Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
   192294   Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
   192295 ){
   192296   const int SZALLOC = 8;
   192297   Fts5ExprNearset *pRet = 0;
   192298 
   192299   if( pParse->rc==SQLITE_OK ){
   192300     if( pPhrase==0 ){
   192301       return pNear;
   192302     }
   192303     if( pNear==0 ){
   192304       int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
   192305       pRet = sqlite3_malloc(nByte);
   192306       if( pRet==0 ){
   192307         pParse->rc = SQLITE_NOMEM;
   192308       }else{
   192309         memset(pRet, 0, nByte);
   192310       }
   192311     }else if( (pNear->nPhrase % SZALLOC)==0 ){
   192312       int nNew = pNear->nPhrase + SZALLOC;
   192313       int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
   192314 
   192315       pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
   192316       if( pRet==0 ){
   192317         pParse->rc = SQLITE_NOMEM;
   192318       }
   192319     }else{
   192320       pRet = pNear;
   192321     }
   192322   }
   192323 
   192324   if( pRet==0 ){
   192325     assert( pParse->rc!=SQLITE_OK );
   192326     sqlite3Fts5ParseNearsetFree(pNear);
   192327     sqlite3Fts5ParsePhraseFree(pPhrase);
   192328   }else{
   192329     if( pRet->nPhrase>0 ){
   192330       Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
   192331       assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
   192332       if( pPhrase->nTerm==0 ){
   192333         fts5ExprPhraseFree(pPhrase);
   192334         pRet->nPhrase--;
   192335         pParse->nPhrase--;
   192336         pPhrase = pLast;
   192337       }else if( pLast->nTerm==0 ){
   192338         fts5ExprPhraseFree(pLast);
   192339         pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
   192340         pParse->nPhrase--;
   192341         pRet->nPhrase--;
   192342       }
   192343     }
   192344     pRet->apPhrase[pRet->nPhrase++] = pPhrase;
   192345   }
   192346   return pRet;
   192347 }
   192348 
   192349 typedef struct TokenCtx TokenCtx;
   192350 struct TokenCtx {
   192351   Fts5ExprPhrase *pPhrase;
   192352   int rc;
   192353 };
   192354 
   192355 /*
   192356 ** Callback for tokenizing terms used by ParseTerm().
   192357 */
   192358 static int fts5ParseTokenize(
   192359   void *pContext,                 /* Pointer to Fts5InsertCtx object */
   192360   int tflags,                     /* Mask of FTS5_TOKEN_* flags */
   192361   const char *pToken,             /* Buffer containing token */
   192362   int nToken,                     /* Size of token in bytes */
   192363   int iUnused1,                   /* Start offset of token */
   192364   int iUnused2                    /* End offset of token */
   192365 ){
   192366   int rc = SQLITE_OK;
   192367   const int SZALLOC = 8;
   192368   TokenCtx *pCtx = (TokenCtx*)pContext;
   192369   Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
   192370 
   192371   UNUSED_PARAM2(iUnused1, iUnused2);
   192372 
   192373   /* If an error has already occurred, this is a no-op */
   192374   if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
   192375   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
   192376 
   192377   if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
   192378     Fts5ExprTerm *pSyn;
   192379     int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
   192380     pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
   192381     if( pSyn==0 ){
   192382       rc = SQLITE_NOMEM;
   192383     }else{
   192384       memset(pSyn, 0, nByte);
   192385       pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
   192386       memcpy(pSyn->zTerm, pToken, nToken);
   192387       pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
   192388       pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
   192389     }
   192390   }else{
   192391     Fts5ExprTerm *pTerm;
   192392     if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
   192393       Fts5ExprPhrase *pNew;
   192394       int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
   192395 
   192396       pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
   192397           sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
   192398       );
   192399       if( pNew==0 ){
   192400         rc = SQLITE_NOMEM;
   192401       }else{
   192402         if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
   192403         pCtx->pPhrase = pPhrase = pNew;
   192404         pNew->nTerm = nNew - SZALLOC;
   192405       }
   192406     }
   192407 
   192408     if( rc==SQLITE_OK ){
   192409       pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
   192410       memset(pTerm, 0, sizeof(Fts5ExprTerm));
   192411       pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
   192412     }
   192413   }
   192414 
   192415   pCtx->rc = rc;
   192416   return rc;
   192417 }
   192418 
   192419 
   192420 /*
   192421 ** Free the phrase object passed as the only argument.
   192422 */
   192423 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
   192424   fts5ExprPhraseFree(pPhrase);
   192425 }
   192426 
   192427 /*
   192428 ** Free the phrase object passed as the second argument.
   192429 */
   192430 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
   192431   if( pNear ){
   192432     int i;
   192433     for(i=0; i<pNear->nPhrase; i++){
   192434       fts5ExprPhraseFree(pNear->apPhrase[i]);
   192435     }
   192436     sqlite3_free(pNear->pColset);
   192437     sqlite3_free(pNear);
   192438   }
   192439 }
   192440 
   192441 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
   192442   assert( pParse->pExpr==0 );
   192443   pParse->pExpr = p;
   192444 }
   192445 
   192446 /*
   192447 ** This function is called by the parser to process a string token. The
   192448 ** string may or may not be quoted. In any case it is tokenized and a
   192449 ** phrase object consisting of all tokens returned.
   192450 */
   192451 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
   192452   Fts5Parse *pParse,              /* Parse context */
   192453   Fts5ExprPhrase *pAppend,        /* Phrase to append to */
   192454   Fts5Token *pToken,              /* String to tokenize */
   192455   int bPrefix                     /* True if there is a trailing "*" */
   192456 ){
   192457   Fts5Config *pConfig = pParse->pConfig;
   192458   TokenCtx sCtx;                  /* Context object passed to callback */
   192459   int rc;                         /* Tokenize return code */
   192460   char *z = 0;
   192461 
   192462   memset(&sCtx, 0, sizeof(TokenCtx));
   192463   sCtx.pPhrase = pAppend;
   192464 
   192465   rc = fts5ParseStringFromToken(pToken, &z);
   192466   if( rc==SQLITE_OK ){
   192467     int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
   192468     int n;
   192469     sqlite3Fts5Dequote(z);
   192470     n = (int)strlen(z);
   192471     rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
   192472   }
   192473   sqlite3_free(z);
   192474   if( rc || (rc = sCtx.rc) ){
   192475     pParse->rc = rc;
   192476     fts5ExprPhraseFree(sCtx.pPhrase);
   192477     sCtx.pPhrase = 0;
   192478   }else{
   192479 
   192480     if( pAppend==0 ){
   192481       if( (pParse->nPhrase % 8)==0 ){
   192482         int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
   192483         Fts5ExprPhrase **apNew;
   192484         apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
   192485         if( apNew==0 ){
   192486           pParse->rc = SQLITE_NOMEM;
   192487           fts5ExprPhraseFree(sCtx.pPhrase);
   192488           return 0;
   192489         }
   192490         pParse->apPhrase = apNew;
   192491       }
   192492       pParse->nPhrase++;
   192493     }
   192494 
   192495     if( sCtx.pPhrase==0 ){
   192496       /* This happens when parsing a token or quoted phrase that contains
   192497       ** no token characters at all. (e.g ... MATCH '""'). */
   192498       sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
   192499     }else if( sCtx.pPhrase->nTerm ){
   192500       sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
   192501     }
   192502     pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
   192503   }
   192504 
   192505   return sCtx.pPhrase;
   192506 }
   192507 
   192508 /*
   192509 ** Create a new FTS5 expression by cloning phrase iPhrase of the
   192510 ** expression passed as the second argument.
   192511 */
   192512 static int sqlite3Fts5ExprClonePhrase(
   192513   Fts5Expr *pExpr,
   192514   int iPhrase,
   192515   Fts5Expr **ppNew
   192516 ){
   192517   int rc = SQLITE_OK;             /* Return code */
   192518   Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
   192519   Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
   192520   TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
   192521 
   192522   pOrig = pExpr->apExprPhrase[iPhrase];
   192523   pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
   192524   if( rc==SQLITE_OK ){
   192525     pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
   192526         sizeof(Fts5ExprPhrase*));
   192527   }
   192528   if( rc==SQLITE_OK ){
   192529     pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
   192530         sizeof(Fts5ExprNode));
   192531   }
   192532   if( rc==SQLITE_OK ){
   192533     pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
   192534         sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
   192535   }
   192536   if( rc==SQLITE_OK ){
   192537     Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
   192538     if( pColsetOrig ){
   192539       int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
   192540       Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
   192541       if( pColset ){
   192542         memcpy(pColset, pColsetOrig, nByte);
   192543       }
   192544       pNew->pRoot->pNear->pColset = pColset;
   192545     }
   192546   }
   192547 
   192548   if( pOrig->nTerm ){
   192549     int i;                          /* Used to iterate through phrase terms */
   192550     for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
   192551       int tflags = 0;
   192552       Fts5ExprTerm *p;
   192553       for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
   192554         const char *zTerm = p->zTerm;
   192555         rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
   192556             0, 0);
   192557         tflags = FTS5_TOKEN_COLOCATED;
   192558       }
   192559       if( rc==SQLITE_OK ){
   192560         sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
   192561         sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
   192562       }
   192563     }
   192564   }else{
   192565     /* This happens when parsing a token or quoted phrase that contains
   192566     ** no token characters at all. (e.g ... MATCH '""'). */
   192567     sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
   192568   }
   192569 
   192570   if( rc==SQLITE_OK ){
   192571     /* All the allocations succeeded. Put the expression object together. */
   192572     pNew->pIndex = pExpr->pIndex;
   192573     pNew->pConfig = pExpr->pConfig;
   192574     pNew->nPhrase = 1;
   192575     pNew->apExprPhrase[0] = sCtx.pPhrase;
   192576     pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
   192577     pNew->pRoot->pNear->nPhrase = 1;
   192578     sCtx.pPhrase->pNode = pNew->pRoot;
   192579 
   192580     if( pOrig->nTerm==1
   192581      && pOrig->aTerm[0].pSynonym==0
   192582      && pOrig->aTerm[0].bFirst==0
   192583     ){
   192584       pNew->pRoot->eType = FTS5_TERM;
   192585       pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
   192586     }else{
   192587       pNew->pRoot->eType = FTS5_STRING;
   192588       pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
   192589     }
   192590   }else{
   192591     sqlite3Fts5ExprFree(pNew);
   192592     fts5ExprPhraseFree(sCtx.pPhrase);
   192593     pNew = 0;
   192594   }
   192595 
   192596   *ppNew = pNew;
   192597   return rc;
   192598 }
   192599 
   192600 
   192601 /*
   192602 ** Token pTok has appeared in a MATCH expression where the NEAR operator
   192603 ** is expected. If token pTok does not contain "NEAR", store an error
   192604 ** in the pParse object.
   192605 */
   192606 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
   192607   if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
   192608     sqlite3Fts5ParseError(
   192609         pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
   192610     );
   192611   }
   192612 }
   192613 
   192614 static void sqlite3Fts5ParseSetDistance(
   192615   Fts5Parse *pParse,
   192616   Fts5ExprNearset *pNear,
   192617   Fts5Token *p
   192618 ){
   192619   if( pNear ){
   192620     int nNear = 0;
   192621     int i;
   192622     if( p->n ){
   192623       for(i=0; i<p->n; i++){
   192624         char c = (char)p->p[i];
   192625         if( c<'0' || c>'9' ){
   192626           sqlite3Fts5ParseError(
   192627               pParse, "expected integer, got \"%.*s\"", p->n, p->p
   192628               );
   192629           return;
   192630         }
   192631         nNear = nNear * 10 + (p->p[i] - '0');
   192632       }
   192633     }else{
   192634       nNear = FTS5_DEFAULT_NEARDIST;
   192635     }
   192636     pNear->nNear = nNear;
   192637   }
   192638 }
   192639 
   192640 /*
   192641 ** The second argument passed to this function may be NULL, or it may be
   192642 ** an existing Fts5Colset object. This function returns a pointer to
   192643 ** a new colset object containing the contents of (p) with new value column
   192644 ** number iCol appended.
   192645 **
   192646 ** If an OOM error occurs, store an error code in pParse and return NULL.
   192647 ** The old colset object (if any) is not freed in this case.
   192648 */
   192649 static Fts5Colset *fts5ParseColset(
   192650   Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
   192651   Fts5Colset *p,                  /* Existing colset object */
   192652   int iCol                        /* New column to add to colset object */
   192653 ){
   192654   int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
   192655   Fts5Colset *pNew;               /* New colset object to return */
   192656 
   192657   assert( pParse->rc==SQLITE_OK );
   192658   assert( iCol>=0 && iCol<pParse->pConfig->nCol );
   192659 
   192660   pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
   192661   if( pNew==0 ){
   192662     pParse->rc = SQLITE_NOMEM;
   192663   }else{
   192664     int *aiCol = pNew->aiCol;
   192665     int i, j;
   192666     for(i=0; i<nCol; i++){
   192667       if( aiCol[i]==iCol ) return pNew;
   192668       if( aiCol[i]>iCol ) break;
   192669     }
   192670     for(j=nCol; j>i; j--){
   192671       aiCol[j] = aiCol[j-1];
   192672     }
   192673     aiCol[i] = iCol;
   192674     pNew->nCol = nCol+1;
   192675 
   192676 #ifndef NDEBUG
   192677     /* Check that the array is in order and contains no duplicate entries. */
   192678     for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
   192679 #endif
   192680   }
   192681 
   192682   return pNew;
   192683 }
   192684 
   192685 /*
   192686 ** Allocate and return an Fts5Colset object specifying the inverse of
   192687 ** the colset passed as the second argument. Free the colset passed
   192688 ** as the second argument before returning.
   192689 */
   192690 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
   192691   Fts5Colset *pRet;
   192692   int nCol = pParse->pConfig->nCol;
   192693 
   192694   pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
   192695       sizeof(Fts5Colset) + sizeof(int)*nCol
   192696   );
   192697   if( pRet ){
   192698     int i;
   192699     int iOld = 0;
   192700     for(i=0; i<nCol; i++){
   192701       if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
   192702         pRet->aiCol[pRet->nCol++] = i;
   192703       }else{
   192704         iOld++;
   192705       }
   192706     }
   192707   }
   192708 
   192709   sqlite3_free(p);
   192710   return pRet;
   192711 }
   192712 
   192713 static Fts5Colset *sqlite3Fts5ParseColset(
   192714   Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
   192715   Fts5Colset *pColset,            /* Existing colset object */
   192716   Fts5Token *p
   192717 ){
   192718   Fts5Colset *pRet = 0;
   192719   int iCol;
   192720   char *z;                        /* Dequoted copy of token p */
   192721 
   192722   z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
   192723   if( pParse->rc==SQLITE_OK ){
   192724     Fts5Config *pConfig = pParse->pConfig;
   192725     sqlite3Fts5Dequote(z);
   192726     for(iCol=0; iCol<pConfig->nCol; iCol++){
   192727       if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
   192728     }
   192729     if( iCol==pConfig->nCol ){
   192730       sqlite3Fts5ParseError(pParse, "no such column: %s", z);
   192731     }else{
   192732       pRet = fts5ParseColset(pParse, pColset, iCol);
   192733     }
   192734     sqlite3_free(z);
   192735   }
   192736 
   192737   if( pRet==0 ){
   192738     assert( pParse->rc!=SQLITE_OK );
   192739     sqlite3_free(pColset);
   192740   }
   192741 
   192742   return pRet;
   192743 }
   192744 
   192745 /*
   192746 ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
   192747 ** SQLITE_OK when this function is called, NULL is returned.
   192748 **
   192749 ** Otherwise, a copy of (*pOrig) is made into memory obtained from
   192750 ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
   192751 ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
   192752 */
   192753 static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
   192754   Fts5Colset *pRet;
   192755   if( pOrig ){
   192756     int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
   192757     pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
   192758     if( pRet ){
   192759       memcpy(pRet, pOrig, nByte);
   192760     }
   192761   }else{
   192762     pRet = 0;
   192763   }
   192764   return pRet;
   192765 }
   192766 
   192767 /*
   192768 ** Remove from colset pColset any columns that are not also in colset pMerge.
   192769 */
   192770 static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
   192771   int iIn = 0;          /* Next input in pColset */
   192772   int iMerge = 0;       /* Next input in pMerge */
   192773   int iOut = 0;         /* Next output slot in pColset */
   192774 
   192775   while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
   192776     int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
   192777     if( iDiff==0 ){
   192778       pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
   192779       iMerge++;
   192780       iIn++;
   192781     }else if( iDiff>0 ){
   192782       iMerge++;
   192783     }else{
   192784       iIn++;
   192785     }
   192786   }
   192787   pColset->nCol = iOut;
   192788 }
   192789 
   192790 /*
   192791 ** Recursively apply colset pColset to expression node pNode and all of
   192792 ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
   192793 ** of pColset. This function may use the spare copy and set (*ppFree) to
   192794 ** zero, or it may create copies of pColset using fts5CloneColset().
   192795 */
   192796 static void fts5ParseSetColset(
   192797   Fts5Parse *pParse,
   192798   Fts5ExprNode *pNode,
   192799   Fts5Colset *pColset,
   192800   Fts5Colset **ppFree
   192801 ){
   192802   if( pParse->rc==SQLITE_OK ){
   192803     assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
   192804          || pNode->eType==FTS5_AND  || pNode->eType==FTS5_OR
   192805          || pNode->eType==FTS5_NOT  || pNode->eType==FTS5_EOF
   192806     );
   192807     if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
   192808       Fts5ExprNearset *pNear = pNode->pNear;
   192809       if( pNear->pColset ){
   192810         fts5MergeColset(pNear->pColset, pColset);
   192811         if( pNear->pColset->nCol==0 ){
   192812           pNode->eType = FTS5_EOF;
   192813           pNode->xNext = 0;
   192814         }
   192815       }else if( *ppFree ){
   192816         pNear->pColset = pColset;
   192817         *ppFree = 0;
   192818       }else{
   192819         pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
   192820       }
   192821     }else{
   192822       int i;
   192823       assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
   192824       for(i=0; i<pNode->nChild; i++){
   192825         fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
   192826       }
   192827     }
   192828   }
   192829 }
   192830 
   192831 /*
   192832 ** Apply colset pColset to expression node pExpr and all of its descendents.
   192833 */
   192834 static void sqlite3Fts5ParseSetColset(
   192835   Fts5Parse *pParse,
   192836   Fts5ExprNode *pExpr,
   192837   Fts5Colset *pColset
   192838 ){
   192839   Fts5Colset *pFree = pColset;
   192840   if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
   192841     pParse->rc = SQLITE_ERROR;
   192842     pParse->zErr = sqlite3_mprintf(
   192843       "fts5: column queries are not supported (detail=none)"
   192844     );
   192845   }else{
   192846     fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
   192847   }
   192848   sqlite3_free(pFree);
   192849 }
   192850 
   192851 static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
   192852   switch( pNode->eType ){
   192853     case FTS5_STRING: {
   192854       Fts5ExprNearset *pNear = pNode->pNear;
   192855       if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
   192856        && pNear->apPhrase[0]->aTerm[0].pSynonym==0
   192857        && pNear->apPhrase[0]->aTerm[0].bFirst==0
   192858       ){
   192859         pNode->eType = FTS5_TERM;
   192860         pNode->xNext = fts5ExprNodeNext_TERM;
   192861       }else{
   192862         pNode->xNext = fts5ExprNodeNext_STRING;
   192863       }
   192864       break;
   192865     };
   192866 
   192867     case FTS5_OR: {
   192868       pNode->xNext = fts5ExprNodeNext_OR;
   192869       break;
   192870     };
   192871 
   192872     case FTS5_AND: {
   192873       pNode->xNext = fts5ExprNodeNext_AND;
   192874       break;
   192875     };
   192876 
   192877     default: assert( pNode->eType==FTS5_NOT ); {
   192878       pNode->xNext = fts5ExprNodeNext_NOT;
   192879       break;
   192880     };
   192881   }
   192882 }
   192883 
   192884 static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
   192885   if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
   192886     int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
   192887     memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
   192888     p->nChild += pSub->nChild;
   192889     sqlite3_free(pSub);
   192890   }else{
   192891     p->apChild[p->nChild++] = pSub;
   192892   }
   192893 }
   192894 
   192895 /*
   192896 ** Allocate and return a new expression object. If anything goes wrong (i.e.
   192897 ** OOM error), leave an error code in pParse and return NULL.
   192898 */
   192899 static Fts5ExprNode *sqlite3Fts5ParseNode(
   192900   Fts5Parse *pParse,              /* Parse context */
   192901   int eType,                      /* FTS5_STRING, AND, OR or NOT */
   192902   Fts5ExprNode *pLeft,            /* Left hand child expression */
   192903   Fts5ExprNode *pRight,           /* Right hand child expression */
   192904   Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
   192905 ){
   192906   Fts5ExprNode *pRet = 0;
   192907 
   192908   if( pParse->rc==SQLITE_OK ){
   192909     int nChild = 0;               /* Number of children of returned node */
   192910     int nByte;                    /* Bytes of space to allocate for this node */
   192911 
   192912     assert( (eType!=FTS5_STRING && !pNear)
   192913          || (eType==FTS5_STRING && !pLeft && !pRight)
   192914     );
   192915     if( eType==FTS5_STRING && pNear==0 ) return 0;
   192916     if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
   192917     if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
   192918 
   192919     if( eType==FTS5_NOT ){
   192920       nChild = 2;
   192921     }else if( eType==FTS5_AND || eType==FTS5_OR ){
   192922       nChild = 2;
   192923       if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
   192924       if( pRight->eType==eType ) nChild += pRight->nChild-1;
   192925     }
   192926 
   192927     nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
   192928     pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
   192929 
   192930     if( pRet ){
   192931       pRet->eType = eType;
   192932       pRet->pNear = pNear;
   192933       fts5ExprAssignXNext(pRet);
   192934       if( eType==FTS5_STRING ){
   192935         int iPhrase;
   192936         for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
   192937           pNear->apPhrase[iPhrase]->pNode = pRet;
   192938           if( pNear->apPhrase[iPhrase]->nTerm==0 ){
   192939             pRet->xNext = 0;
   192940             pRet->eType = FTS5_EOF;
   192941           }
   192942         }
   192943 
   192944         if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
   192945           Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
   192946           if( pNear->nPhrase!=1
   192947            || pPhrase->nTerm>1
   192948            || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
   192949           ){
   192950             assert( pParse->rc==SQLITE_OK );
   192951             pParse->rc = SQLITE_ERROR;
   192952             assert( pParse->zErr==0 );
   192953             pParse->zErr = sqlite3_mprintf(
   192954                 "fts5: %s queries are not supported (detail!=full)",
   192955                 pNear->nPhrase==1 ? "phrase": "NEAR"
   192956                 );
   192957             sqlite3_free(pRet);
   192958             pRet = 0;
   192959           }
   192960         }
   192961       }else{
   192962         fts5ExprAddChildren(pRet, pLeft);
   192963         fts5ExprAddChildren(pRet, pRight);
   192964       }
   192965     }
   192966   }
   192967 
   192968   if( pRet==0 ){
   192969     assert( pParse->rc!=SQLITE_OK );
   192970     sqlite3Fts5ParseNodeFree(pLeft);
   192971     sqlite3Fts5ParseNodeFree(pRight);
   192972     sqlite3Fts5ParseNearsetFree(pNear);
   192973   }
   192974   return pRet;
   192975 }
   192976 
   192977 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
   192978   Fts5Parse *pParse,              /* Parse context */
   192979   Fts5ExprNode *pLeft,            /* Left hand child expression */
   192980   Fts5ExprNode *pRight            /* Right hand child expression */
   192981 ){
   192982   Fts5ExprNode *pRet = 0;
   192983   Fts5ExprNode *pPrev;
   192984 
   192985   if( pParse->rc ){
   192986     sqlite3Fts5ParseNodeFree(pLeft);
   192987     sqlite3Fts5ParseNodeFree(pRight);
   192988   }else{
   192989 
   192990     assert( pLeft->eType==FTS5_STRING
   192991         || pLeft->eType==FTS5_TERM
   192992         || pLeft->eType==FTS5_EOF
   192993         || pLeft->eType==FTS5_AND
   192994     );
   192995     assert( pRight->eType==FTS5_STRING
   192996         || pRight->eType==FTS5_TERM
   192997         || pRight->eType==FTS5_EOF
   192998     );
   192999 
   193000     if( pLeft->eType==FTS5_AND ){
   193001       pPrev = pLeft->apChild[pLeft->nChild-1];
   193002     }else{
   193003       pPrev = pLeft;
   193004     }
   193005     assert( pPrev->eType==FTS5_STRING
   193006         || pPrev->eType==FTS5_TERM
   193007         || pPrev->eType==FTS5_EOF
   193008         );
   193009 
   193010     if( pRight->eType==FTS5_EOF ){
   193011       assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
   193012       sqlite3Fts5ParseNodeFree(pRight);
   193013       pRet = pLeft;
   193014       pParse->nPhrase--;
   193015     }
   193016     else if( pPrev->eType==FTS5_EOF ){
   193017       Fts5ExprPhrase **ap;
   193018 
   193019       if( pPrev==pLeft ){
   193020         pRet = pRight;
   193021       }else{
   193022         pLeft->apChild[pLeft->nChild-1] = pRight;
   193023         pRet = pLeft;
   193024       }
   193025 
   193026       ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
   193027       assert( ap[0]==pPrev->pNear->apPhrase[0] );
   193028       memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
   193029       pParse->nPhrase--;
   193030 
   193031       sqlite3Fts5ParseNodeFree(pPrev);
   193032     }
   193033     else{
   193034       pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
   193035     }
   193036   }
   193037 
   193038   return pRet;
   193039 }
   193040 
   193041 static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
   193042   int nByte = 0;
   193043   Fts5ExprTerm *p;
   193044   char *zQuoted;
   193045 
   193046   /* Determine the maximum amount of space required. */
   193047   for(p=pTerm; p; p=p->pSynonym){
   193048     nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
   193049   }
   193050   zQuoted = sqlite3_malloc(nByte);
   193051 
   193052   if( zQuoted ){
   193053     int i = 0;
   193054     for(p=pTerm; p; p=p->pSynonym){
   193055       char *zIn = p->zTerm;
   193056       zQuoted[i++] = '"';
   193057       while( *zIn ){
   193058         if( *zIn=='"' ) zQuoted[i++] = '"';
   193059         zQuoted[i++] = *zIn++;
   193060       }
   193061       zQuoted[i++] = '"';
   193062       if( p->pSynonym ) zQuoted[i++] = '|';
   193063     }
   193064     if( pTerm->bPrefix ){
   193065       zQuoted[i++] = ' ';
   193066       zQuoted[i++] = '*';
   193067     }
   193068     zQuoted[i++] = '\0';
   193069   }
   193070   return zQuoted;
   193071 }
   193072 
   193073 static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
   193074   char *zNew;
   193075   va_list ap;
   193076   va_start(ap, zFmt);
   193077   zNew = sqlite3_vmprintf(zFmt, ap);
   193078   va_end(ap);
   193079   if( zApp && zNew ){
   193080     char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
   193081     sqlite3_free(zNew);
   193082     zNew = zNew2;
   193083   }
   193084   sqlite3_free(zApp);
   193085   return zNew;
   193086 }
   193087 
   193088 /*
   193089 ** Compose a tcl-readable representation of expression pExpr. Return a
   193090 ** pointer to a buffer containing that representation. It is the
   193091 ** responsibility of the caller to at some point free the buffer using
   193092 ** sqlite3_free().
   193093 */
   193094 static char *fts5ExprPrintTcl(
   193095   Fts5Config *pConfig,
   193096   const char *zNearsetCmd,
   193097   Fts5ExprNode *pExpr
   193098 ){
   193099   char *zRet = 0;
   193100   if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
   193101     Fts5ExprNearset *pNear = pExpr->pNear;
   193102     int i;
   193103     int iTerm;
   193104 
   193105     zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
   193106     if( zRet==0 ) return 0;
   193107     if( pNear->pColset ){
   193108       int *aiCol = pNear->pColset->aiCol;
   193109       int nCol = pNear->pColset->nCol;
   193110       if( nCol==1 ){
   193111         zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
   193112       }else{
   193113         zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
   193114         for(i=1; i<pNear->pColset->nCol; i++){
   193115           zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
   193116         }
   193117         zRet = fts5PrintfAppend(zRet, "} ");
   193118       }
   193119       if( zRet==0 ) return 0;
   193120     }
   193121 
   193122     if( pNear->nPhrase>1 ){
   193123       zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
   193124       if( zRet==0 ) return 0;
   193125     }
   193126 
   193127     zRet = fts5PrintfAppend(zRet, "--");
   193128     if( zRet==0 ) return 0;
   193129 
   193130     for(i=0; i<pNear->nPhrase; i++){
   193131       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
   193132 
   193133       zRet = fts5PrintfAppend(zRet, " {");
   193134       for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
   193135         char *zTerm = pPhrase->aTerm[iTerm].zTerm;
   193136         zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
   193137         if( pPhrase->aTerm[iTerm].bPrefix ){
   193138           zRet = fts5PrintfAppend(zRet, "*");
   193139         }
   193140       }
   193141 
   193142       if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
   193143       if( zRet==0 ) return 0;
   193144     }
   193145 
   193146   }else{
   193147     char const *zOp = 0;
   193148     int i;
   193149     switch( pExpr->eType ){
   193150       case FTS5_AND: zOp = "AND"; break;
   193151       case FTS5_NOT: zOp = "NOT"; break;
   193152       default:
   193153         assert( pExpr->eType==FTS5_OR );
   193154         zOp = "OR";
   193155         break;
   193156     }
   193157 
   193158     zRet = sqlite3_mprintf("%s", zOp);
   193159     for(i=0; zRet && i<pExpr->nChild; i++){
   193160       char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
   193161       if( !z ){
   193162         sqlite3_free(zRet);
   193163         zRet = 0;
   193164       }else{
   193165         zRet = fts5PrintfAppend(zRet, " [%z]", z);
   193166       }
   193167     }
   193168   }
   193169 
   193170   return zRet;
   193171 }
   193172 
   193173 static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
   193174   char *zRet = 0;
   193175   if( pExpr->eType==0 ){
   193176     return sqlite3_mprintf("\"\"");
   193177   }else
   193178   if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
   193179     Fts5ExprNearset *pNear = pExpr->pNear;
   193180     int i;
   193181     int iTerm;
   193182 
   193183     if( pNear->pColset ){
   193184       int iCol = pNear->pColset->aiCol[0];
   193185       zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
   193186       if( zRet==0 ) return 0;
   193187     }
   193188 
   193189     if( pNear->nPhrase>1 ){
   193190       zRet = fts5PrintfAppend(zRet, "NEAR(");
   193191       if( zRet==0 ) return 0;
   193192     }
   193193 
   193194     for(i=0; i<pNear->nPhrase; i++){
   193195       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
   193196       if( i!=0 ){
   193197         zRet = fts5PrintfAppend(zRet, " ");
   193198         if( zRet==0 ) return 0;
   193199       }
   193200       for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
   193201         char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
   193202         if( zTerm ){
   193203           zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
   193204           sqlite3_free(zTerm);
   193205         }
   193206         if( zTerm==0 || zRet==0 ){
   193207           sqlite3_free(zRet);
   193208           return 0;
   193209         }
   193210       }
   193211     }
   193212 
   193213     if( pNear->nPhrase>1 ){
   193214       zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
   193215       if( zRet==0 ) return 0;
   193216     }
   193217 
   193218   }else{
   193219     char const *zOp = 0;
   193220     int i;
   193221 
   193222     switch( pExpr->eType ){
   193223       case FTS5_AND: zOp = " AND "; break;
   193224       case FTS5_NOT: zOp = " NOT "; break;
   193225       default:
   193226         assert( pExpr->eType==FTS5_OR );
   193227         zOp = " OR ";
   193228         break;
   193229     }
   193230 
   193231     for(i=0; i<pExpr->nChild; i++){
   193232       char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
   193233       if( z==0 ){
   193234         sqlite3_free(zRet);
   193235         zRet = 0;
   193236       }else{
   193237         int e = pExpr->apChild[i]->eType;
   193238         int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
   193239         zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
   193240             (i==0 ? "" : zOp),
   193241             (b?"(":""), z, (b?")":"")
   193242         );
   193243       }
   193244       if( zRet==0 ) break;
   193245     }
   193246   }
   193247 
   193248   return zRet;
   193249 }
   193250 
   193251 /*
   193252 ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
   193253 ** and fts5_expr_tcl() (bTcl!=0).
   193254 */
   193255 static void fts5ExprFunction(
   193256   sqlite3_context *pCtx,          /* Function call context */
   193257   int nArg,                       /* Number of args */
   193258   sqlite3_value **apVal,          /* Function arguments */
   193259   int bTcl
   193260 ){
   193261   Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
   193262   sqlite3 *db = sqlite3_context_db_handle(pCtx);
   193263   const char *zExpr = 0;
   193264   char *zErr = 0;
   193265   Fts5Expr *pExpr = 0;
   193266   int rc;
   193267   int i;
   193268 
   193269   const char **azConfig;          /* Array of arguments for Fts5Config */
   193270   const char *zNearsetCmd = "nearset";
   193271   int nConfig;                    /* Size of azConfig[] */
   193272   Fts5Config *pConfig = 0;
   193273   int iArg = 1;
   193274 
   193275   if( nArg<1 ){
   193276     zErr = sqlite3_mprintf("wrong number of arguments to function %s",
   193277         bTcl ? "fts5_expr_tcl" : "fts5_expr"
   193278     );
   193279     sqlite3_result_error(pCtx, zErr, -1);
   193280     sqlite3_free(zErr);
   193281     return;
   193282   }
   193283 
   193284   if( bTcl && nArg>1 ){
   193285     zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
   193286     iArg = 2;
   193287   }
   193288 
   193289   nConfig = 3 + (nArg-iArg);
   193290   azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
   193291   if( azConfig==0 ){
   193292     sqlite3_result_error_nomem(pCtx);
   193293     return;
   193294   }
   193295   azConfig[0] = 0;
   193296   azConfig[1] = "main";
   193297   azConfig[2] = "tbl";
   193298   for(i=3; iArg<nArg; iArg++){
   193299     azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
   193300   }
   193301 
   193302   zExpr = (const char*)sqlite3_value_text(apVal[0]);
   193303 
   193304   rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
   193305   if( rc==SQLITE_OK ){
   193306     rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
   193307   }
   193308   if( rc==SQLITE_OK ){
   193309     char *zText;
   193310     if( pExpr->pRoot->xNext==0 ){
   193311       zText = sqlite3_mprintf("");
   193312     }else if( bTcl ){
   193313       zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
   193314     }else{
   193315       zText = fts5ExprPrint(pConfig, pExpr->pRoot);
   193316     }
   193317     if( zText==0 ){
   193318       rc = SQLITE_NOMEM;
   193319     }else{
   193320       sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
   193321       sqlite3_free(zText);
   193322     }
   193323   }
   193324 
   193325   if( rc!=SQLITE_OK ){
   193326     if( zErr ){
   193327       sqlite3_result_error(pCtx, zErr, -1);
   193328       sqlite3_free(zErr);
   193329     }else{
   193330       sqlite3_result_error_code(pCtx, rc);
   193331     }
   193332   }
   193333   sqlite3_free((void *)azConfig);
   193334   sqlite3Fts5ConfigFree(pConfig);
   193335   sqlite3Fts5ExprFree(pExpr);
   193336 }
   193337 
   193338 static void fts5ExprFunctionHr(
   193339   sqlite3_context *pCtx,          /* Function call context */
   193340   int nArg,                       /* Number of args */
   193341   sqlite3_value **apVal           /* Function arguments */
   193342 ){
   193343   fts5ExprFunction(pCtx, nArg, apVal, 0);
   193344 }
   193345 static void fts5ExprFunctionTcl(
   193346   sqlite3_context *pCtx,          /* Function call context */
   193347   int nArg,                       /* Number of args */
   193348   sqlite3_value **apVal           /* Function arguments */
   193349 ){
   193350   fts5ExprFunction(pCtx, nArg, apVal, 1);
   193351 }
   193352 
   193353 /*
   193354 ** The implementation of an SQLite user-defined-function that accepts a
   193355 ** single integer as an argument. If the integer is an alpha-numeric
   193356 ** unicode code point, 1 is returned. Otherwise 0.
   193357 */
   193358 static void fts5ExprIsAlnum(
   193359   sqlite3_context *pCtx,          /* Function call context */
   193360   int nArg,                       /* Number of args */
   193361   sqlite3_value **apVal           /* Function arguments */
   193362 ){
   193363   int iCode;
   193364   if( nArg!=1 ){
   193365     sqlite3_result_error(pCtx,
   193366         "wrong number of arguments to function fts5_isalnum", -1
   193367     );
   193368     return;
   193369   }
   193370   iCode = sqlite3_value_int(apVal[0]);
   193371   sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
   193372 }
   193373 
   193374 static void fts5ExprFold(
   193375   sqlite3_context *pCtx,          /* Function call context */
   193376   int nArg,                       /* Number of args */
   193377   sqlite3_value **apVal           /* Function arguments */
   193378 ){
   193379   if( nArg!=1 && nArg!=2 ){
   193380     sqlite3_result_error(pCtx,
   193381         "wrong number of arguments to function fts5_fold", -1
   193382     );
   193383   }else{
   193384     int iCode;
   193385     int bRemoveDiacritics = 0;
   193386     iCode = sqlite3_value_int(apVal[0]);
   193387     if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
   193388     sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
   193389   }
   193390 }
   193391 
   193392 /*
   193393 ** This is called during initialization to register the fts5_expr() scalar
   193394 ** UDF with the SQLite handle passed as the only argument.
   193395 */
   193396 static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
   193397   struct Fts5ExprFunc {
   193398     const char *z;
   193399     void (*x)(sqlite3_context*,int,sqlite3_value**);
   193400   } aFunc[] = {
   193401     { "fts5_expr",     fts5ExprFunctionHr },
   193402     { "fts5_expr_tcl", fts5ExprFunctionTcl },
   193403     { "fts5_isalnum",  fts5ExprIsAlnum },
   193404     { "fts5_fold",     fts5ExprFold },
   193405   };
   193406   int i;
   193407   int rc = SQLITE_OK;
   193408   void *pCtx = (void*)pGlobal;
   193409 
   193410   for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
   193411     struct Fts5ExprFunc *p = &aFunc[i];
   193412     rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
   193413   }
   193414 
   193415   /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
   193416 #ifndef NDEBUG
   193417   (void)sqlite3Fts5ParserTrace;
   193418 #endif
   193419 
   193420   return rc;
   193421 }
   193422 
   193423 /*
   193424 ** Return the number of phrases in expression pExpr.
   193425 */
   193426 static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
   193427   return (pExpr ? pExpr->nPhrase : 0);
   193428 }
   193429 
   193430 /*
   193431 ** Return the number of terms in the iPhrase'th phrase in pExpr.
   193432 */
   193433 static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
   193434   if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
   193435   return pExpr->apExprPhrase[iPhrase]->nTerm;
   193436 }
   193437 
   193438 /*
   193439 ** This function is used to access the current position list for phrase
   193440 ** iPhrase.
   193441 */
   193442 static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
   193443   int nRet;
   193444   Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
   193445   Fts5ExprNode *pNode = pPhrase->pNode;
   193446   if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
   193447     *pa = pPhrase->poslist.p;
   193448     nRet = pPhrase->poslist.n;
   193449   }else{
   193450     *pa = 0;
   193451     nRet = 0;
   193452   }
   193453   return nRet;
   193454 }
   193455 
   193456 struct Fts5PoslistPopulator {
   193457   Fts5PoslistWriter writer;
   193458   int bOk;                        /* True if ok to populate */
   193459   int bMiss;
   193460 };
   193461 
   193462 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
   193463   Fts5PoslistPopulator *pRet;
   193464   pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
   193465   if( pRet ){
   193466     int i;
   193467     memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
   193468     for(i=0; i<pExpr->nPhrase; i++){
   193469       Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
   193470       Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
   193471       assert( pExpr->apExprPhrase[i]->nTerm==1 );
   193472       if( bLive &&
   193473           (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
   193474       ){
   193475         pRet[i].bMiss = 1;
   193476       }else{
   193477         pBuf->n = 0;
   193478       }
   193479     }
   193480   }
   193481   return pRet;
   193482 }
   193483 
   193484 struct Fts5ExprCtx {
   193485   Fts5Expr *pExpr;
   193486   Fts5PoslistPopulator *aPopulator;
   193487   i64 iOff;
   193488 };
   193489 typedef struct Fts5ExprCtx Fts5ExprCtx;
   193490 
   193491 /*
   193492 ** TODO: Make this more efficient!
   193493 */
   193494 static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
   193495   int i;
   193496   for(i=0; i<pColset->nCol; i++){
   193497     if( pColset->aiCol[i]==iCol ) return 1;
   193498   }
   193499   return 0;
   193500 }
   193501 
   193502 static int fts5ExprPopulatePoslistsCb(
   193503   void *pCtx,                /* Copy of 2nd argument to xTokenize() */
   193504   int tflags,                /* Mask of FTS5_TOKEN_* flags */
   193505   const char *pToken,        /* Pointer to buffer containing token */
   193506   int nToken,                /* Size of token in bytes */
   193507   int iUnused1,              /* Byte offset of token within input text */
   193508   int iUnused2               /* Byte offset of end of token within input text */
   193509 ){
   193510   Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
   193511   Fts5Expr *pExpr = p->pExpr;
   193512   int i;
   193513 
   193514   UNUSED_PARAM2(iUnused1, iUnused2);
   193515 
   193516   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
   193517   if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
   193518   for(i=0; i<pExpr->nPhrase; i++){
   193519     Fts5ExprTerm *pTerm;
   193520     if( p->aPopulator[i].bOk==0 ) continue;
   193521     for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
   193522       int nTerm = (int)strlen(pTerm->zTerm);
   193523       if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
   193524        && memcmp(pTerm->zTerm, pToken, nTerm)==0
   193525       ){
   193526         int rc = sqlite3Fts5PoslistWriterAppend(
   193527             &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
   193528         );
   193529         if( rc ) return rc;
   193530         break;
   193531       }
   193532     }
   193533   }
   193534   return SQLITE_OK;
   193535 }
   193536 
   193537 static int sqlite3Fts5ExprPopulatePoslists(
   193538   Fts5Config *pConfig,
   193539   Fts5Expr *pExpr,
   193540   Fts5PoslistPopulator *aPopulator,
   193541   int iCol,
   193542   const char *z, int n
   193543 ){
   193544   int i;
   193545   Fts5ExprCtx sCtx;
   193546   sCtx.pExpr = pExpr;
   193547   sCtx.aPopulator = aPopulator;
   193548   sCtx.iOff = (((i64)iCol) << 32) - 1;
   193549 
   193550   for(i=0; i<pExpr->nPhrase; i++){
   193551     Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
   193552     Fts5Colset *pColset = pNode->pNear->pColset;
   193553     if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
   193554      || aPopulator[i].bMiss
   193555     ){
   193556       aPopulator[i].bOk = 0;
   193557     }else{
   193558       aPopulator[i].bOk = 1;
   193559     }
   193560   }
   193561 
   193562   return sqlite3Fts5Tokenize(pConfig,
   193563       FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
   193564   );
   193565 }
   193566 
   193567 static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
   193568   if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
   193569     pNode->pNear->apPhrase[0]->poslist.n = 0;
   193570   }else{
   193571     int i;
   193572     for(i=0; i<pNode->nChild; i++){
   193573       fts5ExprClearPoslists(pNode->apChild[i]);
   193574     }
   193575   }
   193576 }
   193577 
   193578 static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
   193579   pNode->iRowid = iRowid;
   193580   pNode->bEof = 0;
   193581   switch( pNode->eType ){
   193582     case FTS5_TERM:
   193583     case FTS5_STRING:
   193584       return (pNode->pNear->apPhrase[0]->poslist.n>0);
   193585 
   193586     case FTS5_AND: {
   193587       int i;
   193588       for(i=0; i<pNode->nChild; i++){
   193589         if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
   193590           fts5ExprClearPoslists(pNode);
   193591           return 0;
   193592         }
   193593       }
   193594       break;
   193595     }
   193596 
   193597     case FTS5_OR: {
   193598       int i;
   193599       int bRet = 0;
   193600       for(i=0; i<pNode->nChild; i++){
   193601         if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
   193602           bRet = 1;
   193603         }
   193604       }
   193605       return bRet;
   193606     }
   193607 
   193608     default: {
   193609       assert( pNode->eType==FTS5_NOT );
   193610       if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
   193611           || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
   193612         ){
   193613         fts5ExprClearPoslists(pNode);
   193614         return 0;
   193615       }
   193616       break;
   193617     }
   193618   }
   193619   return 1;
   193620 }
   193621 
   193622 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
   193623   fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
   193624 }
   193625 
   193626 /*
   193627 ** This function is only called for detail=columns tables.
   193628 */
   193629 static int sqlite3Fts5ExprPhraseCollist(
   193630   Fts5Expr *pExpr,
   193631   int iPhrase,
   193632   const u8 **ppCollist,
   193633   int *pnCollist
   193634 ){
   193635   Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
   193636   Fts5ExprNode *pNode = pPhrase->pNode;
   193637   int rc = SQLITE_OK;
   193638 
   193639   assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
   193640   assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
   193641 
   193642   if( pNode->bEof==0
   193643    && pNode->iRowid==pExpr->pRoot->iRowid
   193644    && pPhrase->poslist.n>0
   193645   ){
   193646     Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
   193647     if( pTerm->pSynonym ){
   193648       Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
   193649       rc = fts5ExprSynonymList(
   193650           pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
   193651       );
   193652     }else{
   193653       *ppCollist = pPhrase->aTerm[0].pIter->pData;
   193654       *pnCollist = pPhrase->aTerm[0].pIter->nData;
   193655     }
   193656   }else{
   193657     *ppCollist = 0;
   193658     *pnCollist = 0;
   193659   }
   193660 
   193661   return rc;
   193662 }
   193663 
   193664 
   193665 /*
   193666 ** 2014 August 11
   193667 **
   193668 ** The author disclaims copyright to this source code.  In place of
   193669 ** a legal notice, here is a blessing:
   193670 **
   193671 **    May you do good and not evil.
   193672 **    May you find forgiveness for yourself and forgive others.
   193673 **    May you share freely, never taking more than you give.
   193674 **
   193675 ******************************************************************************
   193676 **
   193677 */
   193678 
   193679 
   193680 
   193681 /* #include "fts5Int.h" */
   193682 
   193683 typedef struct Fts5HashEntry Fts5HashEntry;
   193684 
   193685 /*
   193686 ** This file contains the implementation of an in-memory hash table used
   193687 ** to accumuluate "term -> doclist" content before it is flused to a level-0
   193688 ** segment.
   193689 */
   193690 
   193691 
   193692 struct Fts5Hash {
   193693   int eDetail;                    /* Copy of Fts5Config.eDetail */
   193694   int *pnByte;                    /* Pointer to bytes counter */
   193695   int nEntry;                     /* Number of entries currently in hash */
   193696   int nSlot;                      /* Size of aSlot[] array */
   193697   Fts5HashEntry *pScan;           /* Current ordered scan item */
   193698   Fts5HashEntry **aSlot;          /* Array of hash slots */
   193699 };
   193700 
   193701 /*
   193702 ** Each entry in the hash table is represented by an object of the
   193703 ** following type. Each object, its key (a nul-terminated string) and
   193704 ** its current data are stored in a single memory allocation. The
   193705 ** key immediately follows the object in memory. The position list
   193706 ** data immediately follows the key data in memory.
   193707 **
   193708 ** The data that follows the key is in a similar, but not identical format
   193709 ** to the doclist data stored in the database. It is:
   193710 **
   193711 **   * Rowid, as a varint
   193712 **   * Position list, without 0x00 terminator.
   193713 **   * Size of previous position list and rowid, as a 4 byte
   193714 **     big-endian integer.
   193715 **
   193716 ** iRowidOff:
   193717 **   Offset of last rowid written to data area. Relative to first byte of
   193718 **   structure.
   193719 **
   193720 ** nData:
   193721 **   Bytes of data written since iRowidOff.
   193722 */
   193723 struct Fts5HashEntry {
   193724   Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
   193725   Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
   193726 
   193727   int nAlloc;                     /* Total size of allocation */
   193728   int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
   193729   int nData;                      /* Total bytes of data (incl. structure) */
   193730   int nKey;                       /* Length of key in bytes */
   193731   u8 bDel;                        /* Set delete-flag @ iSzPoslist */
   193732   u8 bContent;                    /* Set content-flag (detail=none mode) */
   193733   i16 iCol;                       /* Column of last value written */
   193734   int iPos;                       /* Position of last value written */
   193735   i64 iRowid;                     /* Rowid of last value written */
   193736 };
   193737 
   193738 /*
   193739 ** Eqivalent to:
   193740 **
   193741 **   char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
   193742 */
   193743 #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
   193744 
   193745 
   193746 /*
   193747 ** Allocate a new hash table.
   193748 */
   193749 static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
   193750   int rc = SQLITE_OK;
   193751   Fts5Hash *pNew;
   193752 
   193753   *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
   193754   if( pNew==0 ){
   193755     rc = SQLITE_NOMEM;
   193756   }else{
   193757     int nByte;
   193758     memset(pNew, 0, sizeof(Fts5Hash));
   193759     pNew->pnByte = pnByte;
   193760     pNew->eDetail = pConfig->eDetail;
   193761 
   193762     pNew->nSlot = 1024;
   193763     nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
   193764     pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
   193765     if( pNew->aSlot==0 ){
   193766       sqlite3_free(pNew);
   193767       *ppNew = 0;
   193768       rc = SQLITE_NOMEM;
   193769     }else{
   193770       memset(pNew->aSlot, 0, nByte);
   193771     }
   193772   }
   193773   return rc;
   193774 }
   193775 
   193776 /*
   193777 ** Free a hash table object.
   193778 */
   193779 static void sqlite3Fts5HashFree(Fts5Hash *pHash){
   193780   if( pHash ){
   193781     sqlite3Fts5HashClear(pHash);
   193782     sqlite3_free(pHash->aSlot);
   193783     sqlite3_free(pHash);
   193784   }
   193785 }
   193786 
   193787 /*
   193788 ** Empty (but do not delete) a hash table.
   193789 */
   193790 static void sqlite3Fts5HashClear(Fts5Hash *pHash){
   193791   int i;
   193792   for(i=0; i<pHash->nSlot; i++){
   193793     Fts5HashEntry *pNext;
   193794     Fts5HashEntry *pSlot;
   193795     for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
   193796       pNext = pSlot->pHashNext;
   193797       sqlite3_free(pSlot);
   193798     }
   193799   }
   193800   memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
   193801   pHash->nEntry = 0;
   193802 }
   193803 
   193804 static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
   193805   int i;
   193806   unsigned int h = 13;
   193807   for(i=n-1; i>=0; i--){
   193808     h = (h << 3) ^ h ^ p[i];
   193809   }
   193810   return (h % nSlot);
   193811 }
   193812 
   193813 static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
   193814   int i;
   193815   unsigned int h = 13;
   193816   for(i=n-1; i>=0; i--){
   193817     h = (h << 3) ^ h ^ p[i];
   193818   }
   193819   h = (h << 3) ^ h ^ b;
   193820   return (h % nSlot);
   193821 }
   193822 
   193823 /*
   193824 ** Resize the hash table by doubling the number of slots.
   193825 */
   193826 static int fts5HashResize(Fts5Hash *pHash){
   193827   int nNew = pHash->nSlot*2;
   193828   int i;
   193829   Fts5HashEntry **apNew;
   193830   Fts5HashEntry **apOld = pHash->aSlot;
   193831 
   193832   apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
   193833   if( !apNew ) return SQLITE_NOMEM;
   193834   memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
   193835 
   193836   for(i=0; i<pHash->nSlot; i++){
   193837     while( apOld[i] ){
   193838       unsigned int iHash;
   193839       Fts5HashEntry *p = apOld[i];
   193840       apOld[i] = p->pHashNext;
   193841       iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
   193842                           (int)strlen(fts5EntryKey(p)));
   193843       p->pHashNext = apNew[iHash];
   193844       apNew[iHash] = p;
   193845     }
   193846   }
   193847 
   193848   sqlite3_free(apOld);
   193849   pHash->nSlot = nNew;
   193850   pHash->aSlot = apNew;
   193851   return SQLITE_OK;
   193852 }
   193853 
   193854 static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
   193855   if( p->iSzPoslist ){
   193856     u8 *pPtr = (u8*)p;
   193857     if( pHash->eDetail==FTS5_DETAIL_NONE ){
   193858       assert( p->nData==p->iSzPoslist );
   193859       if( p->bDel ){
   193860         pPtr[p->nData++] = 0x00;
   193861         if( p->bContent ){
   193862           pPtr[p->nData++] = 0x00;
   193863         }
   193864       }
   193865     }else{
   193866       int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
   193867       int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
   193868 
   193869       assert( p->bDel==0 || p->bDel==1 );
   193870       if( nPos<=127 ){
   193871         pPtr[p->iSzPoslist] = (u8)nPos;
   193872       }else{
   193873         int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
   193874         memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
   193875         sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
   193876         p->nData += (nByte-1);
   193877       }
   193878     }
   193879 
   193880     p->iSzPoslist = 0;
   193881     p->bDel = 0;
   193882     p->bContent = 0;
   193883   }
   193884 }
   193885 
   193886 /*
   193887 ** Add an entry to the in-memory hash table. The key is the concatenation
   193888 ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
   193889 **
   193890 **     (bByte || pToken) -> (iRowid,iCol,iPos)
   193891 **
   193892 ** Or, if iCol is negative, then the value is a delete marker.
   193893 */
   193894 static int sqlite3Fts5HashWrite(
   193895   Fts5Hash *pHash,
   193896   i64 iRowid,                     /* Rowid for this entry */
   193897   int iCol,                       /* Column token appears in (-ve -> delete) */
   193898   int iPos,                       /* Position of token within column */
   193899   char bByte,                     /* First byte of token */
   193900   const char *pToken, int nToken  /* Token to add or remove to or from index */
   193901 ){
   193902   unsigned int iHash;
   193903   Fts5HashEntry *p;
   193904   u8 *pPtr;
   193905   int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
   193906   int bNew;                       /* If non-delete entry should be written */
   193907 
   193908   bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
   193909 
   193910   /* Attempt to locate an existing hash entry */
   193911   iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
   193912   for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
   193913     char *zKey = fts5EntryKey(p);
   193914     if( zKey[0]==bByte
   193915      && p->nKey==nToken
   193916      && memcmp(&zKey[1], pToken, nToken)==0
   193917     ){
   193918       break;
   193919     }
   193920   }
   193921 
   193922   /* If an existing hash entry cannot be found, create a new one. */
   193923   if( p==0 ){
   193924     /* Figure out how much space to allocate */
   193925     char *zKey;
   193926     int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
   193927     if( nByte<128 ) nByte = 128;
   193928 
   193929     /* Grow the Fts5Hash.aSlot[] array if necessary. */
   193930     if( (pHash->nEntry*2)>=pHash->nSlot ){
   193931       int rc = fts5HashResize(pHash);
   193932       if( rc!=SQLITE_OK ) return rc;
   193933       iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
   193934     }
   193935 
   193936     /* Allocate new Fts5HashEntry and add it to the hash table. */
   193937     p = (Fts5HashEntry*)sqlite3_malloc(nByte);
   193938     if( !p ) return SQLITE_NOMEM;
   193939     memset(p, 0, sizeof(Fts5HashEntry));
   193940     p->nAlloc = nByte;
   193941     zKey = fts5EntryKey(p);
   193942     zKey[0] = bByte;
   193943     memcpy(&zKey[1], pToken, nToken);
   193944     assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
   193945     p->nKey = nToken;
   193946     zKey[nToken+1] = '\0';
   193947     p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
   193948     p->pHashNext = pHash->aSlot[iHash];
   193949     pHash->aSlot[iHash] = p;
   193950     pHash->nEntry++;
   193951 
   193952     /* Add the first rowid field to the hash-entry */
   193953     p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
   193954     p->iRowid = iRowid;
   193955 
   193956     p->iSzPoslist = p->nData;
   193957     if( pHash->eDetail!=FTS5_DETAIL_NONE ){
   193958       p->nData += 1;
   193959       p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
   193960     }
   193961 
   193962     nIncr += p->nData;
   193963   }else{
   193964 
   193965     /* Appending to an existing hash-entry. Check that there is enough
   193966     ** space to append the largest possible new entry. Worst case scenario
   193967     ** is:
   193968     **
   193969     **     + 9 bytes for a new rowid,
   193970     **     + 4 byte reserved for the "poslist size" varint.
   193971     **     + 1 byte for a "new column" byte,
   193972     **     + 3 bytes for a new column number (16-bit max) as a varint,
   193973     **     + 5 bytes for the new position offset (32-bit max).
   193974     */
   193975     if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
   193976       int nNew = p->nAlloc * 2;
   193977       Fts5HashEntry *pNew;
   193978       Fts5HashEntry **pp;
   193979       pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
   193980       if( pNew==0 ) return SQLITE_NOMEM;
   193981       pNew->nAlloc = nNew;
   193982       for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
   193983       *pp = pNew;
   193984       p = pNew;
   193985     }
   193986     nIncr -= p->nData;
   193987   }
   193988   assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
   193989 
   193990   pPtr = (u8*)p;
   193991 
   193992   /* If this is a new rowid, append the 4-byte size field for the previous
   193993   ** entry, and the new rowid for this entry.  */
   193994   if( iRowid!=p->iRowid ){
   193995     fts5HashAddPoslistSize(pHash, p);
   193996     p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
   193997     p->iRowid = iRowid;
   193998     bNew = 1;
   193999     p->iSzPoslist = p->nData;
   194000     if( pHash->eDetail!=FTS5_DETAIL_NONE ){
   194001       p->nData += 1;
   194002       p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
   194003       p->iPos = 0;
   194004     }
   194005   }
   194006 
   194007   if( iCol>=0 ){
   194008     if( pHash->eDetail==FTS5_DETAIL_NONE ){
   194009       p->bContent = 1;
   194010     }else{
   194011       /* Append a new column value, if necessary */
   194012       assert( iCol>=p->iCol );
   194013       if( iCol!=p->iCol ){
   194014         if( pHash->eDetail==FTS5_DETAIL_FULL ){
   194015           pPtr[p->nData++] = 0x01;
   194016           p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
   194017           p->iCol = (i16)iCol;
   194018           p->iPos = 0;
   194019         }else{
   194020           bNew = 1;
   194021           p->iCol = (i16)(iPos = iCol);
   194022         }
   194023       }
   194024 
   194025       /* Append the new position offset, if necessary */
   194026       if( bNew ){
   194027         p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
   194028         p->iPos = iPos;
   194029       }
   194030     }
   194031   }else{
   194032     /* This is a delete. Set the delete flag. */
   194033     p->bDel = 1;
   194034   }
   194035 
   194036   nIncr += p->nData;
   194037   *pHash->pnByte += nIncr;
   194038   return SQLITE_OK;
   194039 }
   194040 
   194041 
   194042 /*
   194043 ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
   194044 ** each sorted in key order. This function merges the two lists into a
   194045 ** single list and returns a pointer to its first element.
   194046 */
   194047 static Fts5HashEntry *fts5HashEntryMerge(
   194048   Fts5HashEntry *pLeft,
   194049   Fts5HashEntry *pRight
   194050 ){
   194051   Fts5HashEntry *p1 = pLeft;
   194052   Fts5HashEntry *p2 = pRight;
   194053   Fts5HashEntry *pRet = 0;
   194054   Fts5HashEntry **ppOut = &pRet;
   194055 
   194056   while( p1 || p2 ){
   194057     if( p1==0 ){
   194058       *ppOut = p2;
   194059       p2 = 0;
   194060     }else if( p2==0 ){
   194061       *ppOut = p1;
   194062       p1 = 0;
   194063     }else{
   194064       int i = 0;
   194065       char *zKey1 = fts5EntryKey(p1);
   194066       char *zKey2 = fts5EntryKey(p2);
   194067       while( zKey1[i]==zKey2[i] ) i++;
   194068 
   194069       if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
   194070         /* p2 is smaller */
   194071         *ppOut = p2;
   194072         ppOut = &p2->pScanNext;
   194073         p2 = p2->pScanNext;
   194074       }else{
   194075         /* p1 is smaller */
   194076         *ppOut = p1;
   194077         ppOut = &p1->pScanNext;
   194078         p1 = p1->pScanNext;
   194079       }
   194080       *ppOut = 0;
   194081     }
   194082   }
   194083 
   194084   return pRet;
   194085 }
   194086 
   194087 /*
   194088 ** Extract all tokens from hash table iHash and link them into a list
   194089 ** in sorted order. The hash table is cleared before returning. It is
   194090 ** the responsibility of the caller to free the elements of the returned
   194091 ** list.
   194092 */
   194093 static int fts5HashEntrySort(
   194094   Fts5Hash *pHash,
   194095   const char *pTerm, int nTerm,   /* Query prefix, if any */
   194096   Fts5HashEntry **ppSorted
   194097 ){
   194098   const int nMergeSlot = 32;
   194099   Fts5HashEntry **ap;
   194100   Fts5HashEntry *pList;
   194101   int iSlot;
   194102   int i;
   194103 
   194104   *ppSorted = 0;
   194105   ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
   194106   if( !ap ) return SQLITE_NOMEM;
   194107   memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
   194108 
   194109   for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
   194110     Fts5HashEntry *pIter;
   194111     for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
   194112       if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
   194113         Fts5HashEntry *pEntry = pIter;
   194114         pEntry->pScanNext = 0;
   194115         for(i=0; ap[i]; i++){
   194116           pEntry = fts5HashEntryMerge(pEntry, ap[i]);
   194117           ap[i] = 0;
   194118         }
   194119         ap[i] = pEntry;
   194120       }
   194121     }
   194122   }
   194123 
   194124   pList = 0;
   194125   for(i=0; i<nMergeSlot; i++){
   194126     pList = fts5HashEntryMerge(pList, ap[i]);
   194127   }
   194128 
   194129   pHash->nEntry = 0;
   194130   sqlite3_free(ap);
   194131   *ppSorted = pList;
   194132   return SQLITE_OK;
   194133 }
   194134 
   194135 /*
   194136 ** Query the hash table for a doclist associated with term pTerm/nTerm.
   194137 */
   194138 static int sqlite3Fts5HashQuery(
   194139   Fts5Hash *pHash,                /* Hash table to query */
   194140   const char *pTerm, int nTerm,   /* Query term */
   194141   const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
   194142   int *pnDoclist                  /* OUT: Size of doclist in bytes */
   194143 ){
   194144   unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
   194145   char *zKey = 0;
   194146   Fts5HashEntry *p;
   194147 
   194148   for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
   194149     zKey = fts5EntryKey(p);
   194150     if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
   194151   }
   194152 
   194153   if( p ){
   194154     fts5HashAddPoslistSize(pHash, p);
   194155     *ppDoclist = (const u8*)&zKey[nTerm+1];
   194156     *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
   194157   }else{
   194158     *ppDoclist = 0;
   194159     *pnDoclist = 0;
   194160   }
   194161 
   194162   return SQLITE_OK;
   194163 }
   194164 
   194165 static int sqlite3Fts5HashScanInit(
   194166   Fts5Hash *p,                    /* Hash table to query */
   194167   const char *pTerm, int nTerm    /* Query prefix */
   194168 ){
   194169   return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
   194170 }
   194171 
   194172 static void sqlite3Fts5HashScanNext(Fts5Hash *p){
   194173   assert( !sqlite3Fts5HashScanEof(p) );
   194174   p->pScan = p->pScan->pScanNext;
   194175 }
   194176 
   194177 static int sqlite3Fts5HashScanEof(Fts5Hash *p){
   194178   return (p->pScan==0);
   194179 }
   194180 
   194181 static void sqlite3Fts5HashScanEntry(
   194182   Fts5Hash *pHash,
   194183   const char **pzTerm,            /* OUT: term (nul-terminated) */
   194184   const u8 **ppDoclist,           /* OUT: pointer to doclist */
   194185   int *pnDoclist                  /* OUT: size of doclist in bytes */
   194186 ){
   194187   Fts5HashEntry *p;
   194188   if( (p = pHash->pScan) ){
   194189     char *zKey = fts5EntryKey(p);
   194190     int nTerm = (int)strlen(zKey);
   194191     fts5HashAddPoslistSize(pHash, p);
   194192     *pzTerm = zKey;
   194193     *ppDoclist = (const u8*)&zKey[nTerm+1];
   194194     *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
   194195   }else{
   194196     *pzTerm = 0;
   194197     *ppDoclist = 0;
   194198     *pnDoclist = 0;
   194199   }
   194200 }
   194201 
   194202 
   194203 /*
   194204 ** 2014 May 31
   194205 **
   194206 ** The author disclaims copyright to this source code.  In place of
   194207 ** a legal notice, here is a blessing:
   194208 **
   194209 **    May you do good and not evil.
   194210 **    May you find forgiveness for yourself and forgive others.
   194211 **    May you share freely, never taking more than you give.
   194212 **
   194213 ******************************************************************************
   194214 **
   194215 ** Low level access to the FTS index stored in the database file. The
   194216 ** routines in this file file implement all read and write access to the
   194217 ** %_data table. Other parts of the system access this functionality via
   194218 ** the interface defined in fts5Int.h.
   194219 */
   194220 
   194221 
   194222 /* #include "fts5Int.h" */
   194223 
   194224 /*
   194225 ** Overview:
   194226 **
   194227 ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
   194228 ** As well as the main term index, there may be up to 31 prefix indexes.
   194229 ** The format is similar to FTS3/4, except that:
   194230 **
   194231 **   * all segment b-tree leaf data is stored in fixed size page records
   194232 **     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
   194233 **     taken to ensure it is possible to iterate in either direction through
   194234 **     the entries in a doclist, or to seek to a specific entry within a
   194235 **     doclist, without loading it into memory.
   194236 **
   194237 **   * large doclists that span many pages have associated "doclist index"
   194238 **     records that contain a copy of the first rowid on each page spanned by
   194239 **     the doclist. This is used to speed up seek operations, and merges of
   194240 **     large doclists with very small doclists.
   194241 **
   194242 **   * extra fields in the "structure record" record the state of ongoing
   194243 **     incremental merge operations.
   194244 **
   194245 */
   194246 
   194247 
   194248 #define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
   194249 #define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
   194250 
   194251 #define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
   194252 
   194253 #define FTS5_MAIN_PREFIX '0'
   194254 
   194255 #if FTS5_MAX_PREFIX_INDEXES > 31
   194256 # error "FTS5_MAX_PREFIX_INDEXES is too large"
   194257 #endif
   194258 
   194259 /*
   194260 ** Details:
   194261 **
   194262 ** The %_data table managed by this module,
   194263 **
   194264 **     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
   194265 **
   194266 ** , contains the following 5 types of records. See the comments surrounding
   194267 ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
   194268 ** assigned to each fo them.
   194269 **
   194270 ** 1. Structure Records:
   194271 **
   194272 **   The set of segments that make up an index - the index structure - are
   194273 **   recorded in a single record within the %_data table. The record consists
   194274 **   of a single 32-bit configuration cookie value followed by a list of
   194275 **   SQLite varints. If the FTS table features more than one index (because
   194276 **   there are one or more prefix indexes), it is guaranteed that all share
   194277 **   the same cookie value.
   194278 **
   194279 **   Immediately following the configuration cookie, the record begins with
   194280 **   three varints:
   194281 **
   194282 **     + number of levels,
   194283 **     + total number of segments on all levels,
   194284 **     + value of write counter.
   194285 **
   194286 **   Then, for each level from 0 to nMax:
   194287 **
   194288 **     + number of input segments in ongoing merge.
   194289 **     + total number of segments in level.
   194290 **     + for each segment from oldest to newest:
   194291 **         + segment id (always > 0)
   194292 **         + first leaf page number (often 1, always greater than 0)
   194293 **         + final leaf page number
   194294 **
   194295 ** 2. The Averages Record:
   194296 **
   194297 **   A single record within the %_data table. The data is a list of varints.
   194298 **   The first value is the number of rows in the index. Then, for each column
   194299 **   from left to right, the total number of tokens in the column for all
   194300 **   rows of the table.
   194301 **
   194302 ** 3. Segment leaves:
   194303 **
   194304 **   TERM/DOCLIST FORMAT:
   194305 **
   194306 **     Most of each segment leaf is taken up by term/doclist data. The
   194307 **     general format of term/doclist, starting with the first term
   194308 **     on the leaf page, is:
   194309 **
   194310 **         varint : size of first term
   194311 **         blob:    first term data
   194312 **         doclist: first doclist
   194313 **         zero-or-more {
   194314 **           varint:  number of bytes in common with previous term
   194315 **           varint:  number of bytes of new term data (nNew)
   194316 **           blob:    nNew bytes of new term data
   194317 **           doclist: next doclist
   194318 **         }
   194319 **
   194320 **     doclist format:
   194321 **
   194322 **         varint:  first rowid
   194323 **         poslist: first poslist
   194324 **         zero-or-more {
   194325 **           varint:  rowid delta (always > 0)
   194326 **           poslist: next poslist
   194327 **         }
   194328 **
   194329 **     poslist format:
   194330 **
   194331 **         varint: size of poslist in bytes multiplied by 2, not including
   194332 **                 this field. Plus 1 if this entry carries the "delete" flag.
   194333 **         collist: collist for column 0
   194334 **         zero-or-more {
   194335 **           0x01 byte
   194336 **           varint: column number (I)
   194337 **           collist: collist for column I
   194338 **         }
   194339 **
   194340 **     collist format:
   194341 **
   194342 **         varint: first offset + 2
   194343 **         zero-or-more {
   194344 **           varint: offset delta + 2
   194345 **         }
   194346 **
   194347 **   PAGE FORMAT
   194348 **
   194349 **     Each leaf page begins with a 4-byte header containing 2 16-bit
   194350 **     unsigned integer fields in big-endian format. They are:
   194351 **
   194352 **       * The byte offset of the first rowid on the page, if it exists
   194353 **         and occurs before the first term (otherwise 0).
   194354 **
   194355 **       * The byte offset of the start of the page footer. If the page
   194356 **         footer is 0 bytes in size, then this field is the same as the
   194357 **         size of the leaf page in bytes.
   194358 **
   194359 **     The page footer consists of a single varint for each term located
   194360 **     on the page. Each varint is the byte offset of the current term
   194361 **     within the page, delta-compressed against the previous value. In
   194362 **     other words, the first varint in the footer is the byte offset of
   194363 **     the first term, the second is the byte offset of the second less that
   194364 **     of the first, and so on.
   194365 **
   194366 **     The term/doclist format described above is accurate if the entire
   194367 **     term/doclist data fits on a single leaf page. If this is not the case,
   194368 **     the format is changed in two ways:
   194369 **
   194370 **       + if the first rowid on a page occurs before the first term, it
   194371 **         is stored as a literal value:
   194372 **
   194373 **             varint:  first rowid
   194374 **
   194375 **       + the first term on each page is stored in the same way as the
   194376 **         very first term of the segment:
   194377 **
   194378 **             varint : size of first term
   194379 **             blob:    first term data
   194380 **
   194381 ** 5. Segment doclist indexes:
   194382 **
   194383 **   Doclist indexes are themselves b-trees, however they usually consist of
   194384 **   a single leaf record only. The format of each doclist index leaf page
   194385 **   is:
   194386 **
   194387 **     * Flags byte. Bits are:
   194388 **         0x01: Clear if leaf is also the root page, otherwise set.
   194389 **
   194390 **     * Page number of fts index leaf page. As a varint.
   194391 **
   194392 **     * First rowid on page indicated by previous field. As a varint.
   194393 **
   194394 **     * A list of varints, one for each subsequent termless page. A
   194395 **       positive delta if the termless page contains at least one rowid,
   194396 **       or an 0x00 byte otherwise.
   194397 **
   194398 **   Internal doclist index nodes are:
   194399 **
   194400 **     * Flags byte. Bits are:
   194401 **         0x01: Clear for root page, otherwise set.
   194402 **
   194403 **     * Page number of first child page. As a varint.
   194404 **
   194405 **     * Copy of first rowid on page indicated by previous field. As a varint.
   194406 **
   194407 **     * A list of delta-encoded varints - the first rowid on each subsequent
   194408 **       child page.
   194409 **
   194410 */
   194411 
   194412 /*
   194413 ** Rowids for the averages and structure records in the %_data table.
   194414 */
   194415 #define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
   194416 #define FTS5_STRUCTURE_ROWID   10    /* The structure record */
   194417 
   194418 /*
   194419 ** Macros determining the rowids used by segment leaves and dlidx leaves
   194420 ** and nodes. All nodes and leaves are stored in the %_data table with large
   194421 ** positive rowids.
   194422 **
   194423 ** Each segment has a unique non-zero 16-bit id.
   194424 **
   194425 ** The rowid for each segment leaf is found by passing the segment id and
   194426 ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
   194427 ** sequentially starting from 1.
   194428 */
   194429 #define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
   194430 #define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
   194431 #define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
   194432 #define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
   194433 
   194434 #define fts5_dri(segid, dlidx, height, pgno) (                                 \
   194435  ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
   194436  ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
   194437  ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
   194438  ((i64)(pgno))                                                                 \
   194439 )
   194440 
   194441 #define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
   194442 #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
   194443 
   194444 /*
   194445 ** Maximum segments permitted in a single index
   194446 */
   194447 #define FTS5_MAX_SEGMENT 2000
   194448 
   194449 #ifdef SQLITE_DEBUG
   194450 static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
   194451 #endif
   194452 
   194453 
   194454 /*
   194455 ** Each time a blob is read from the %_data table, it is padded with this
   194456 ** many zero bytes. This makes it easier to decode the various record formats
   194457 ** without overreading if the records are corrupt.
   194458 */
   194459 #define FTS5_DATA_ZERO_PADDING 8
   194460 #define FTS5_DATA_PADDING 20
   194461 
   194462 typedef struct Fts5Data Fts5Data;
   194463 typedef struct Fts5DlidxIter Fts5DlidxIter;
   194464 typedef struct Fts5DlidxLvl Fts5DlidxLvl;
   194465 typedef struct Fts5DlidxWriter Fts5DlidxWriter;
   194466 typedef struct Fts5Iter Fts5Iter;
   194467 typedef struct Fts5PageWriter Fts5PageWriter;
   194468 typedef struct Fts5SegIter Fts5SegIter;
   194469 typedef struct Fts5DoclistIter Fts5DoclistIter;
   194470 typedef struct Fts5SegWriter Fts5SegWriter;
   194471 typedef struct Fts5Structure Fts5Structure;
   194472 typedef struct Fts5StructureLevel Fts5StructureLevel;
   194473 typedef struct Fts5StructureSegment Fts5StructureSegment;
   194474 
   194475 struct Fts5Data {
   194476   u8 *p;                          /* Pointer to buffer containing record */
   194477   int nn;                         /* Size of record in bytes */
   194478   int szLeaf;                     /* Size of leaf without page-index */
   194479 };
   194480 
   194481 /*
   194482 ** One object per %_data table.
   194483 */
   194484 struct Fts5Index {
   194485   Fts5Config *pConfig;            /* Virtual table configuration */
   194486   char *zDataTbl;                 /* Name of %_data table */
   194487   int nWorkUnit;                  /* Leaf pages in a "unit" of work */
   194488 
   194489   /*
   194490   ** Variables related to the accumulation of tokens and doclists within the
   194491   ** in-memory hash tables before they are flushed to disk.
   194492   */
   194493   Fts5Hash *pHash;                /* Hash table for in-memory data */
   194494   int nPendingData;               /* Current bytes of pending data */
   194495   i64 iWriteRowid;                /* Rowid for current doc being written */
   194496   int bDelete;                    /* Current write is a delete */
   194497 
   194498   /* Error state. */
   194499   int rc;                         /* Current error code */
   194500 
   194501   /* State used by the fts5DataXXX() functions. */
   194502   sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
   194503   sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
   194504   sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
   194505   sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
   194506   sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
   194507   sqlite3_stmt *pIdxSelect;
   194508   int nRead;                      /* Total number of blocks read */
   194509 
   194510   sqlite3_stmt *pDataVersion;
   194511   i64 iStructVersion;             /* data_version when pStruct read */
   194512   Fts5Structure *pStruct;         /* Current db structure (or NULL) */
   194513 };
   194514 
   194515 struct Fts5DoclistIter {
   194516   u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
   194517 
   194518   /* Output variables. aPoslist==0 at EOF */
   194519   i64 iRowid;
   194520   u8 *aPoslist;
   194521   int nPoslist;
   194522   int nSize;
   194523 };
   194524 
   194525 /*
   194526 ** The contents of the "structure" record for each index are represented
   194527 ** using an Fts5Structure record in memory. Which uses instances of the
   194528 ** other Fts5StructureXXX types as components.
   194529 */
   194530 struct Fts5StructureSegment {
   194531   int iSegid;                     /* Segment id */
   194532   int pgnoFirst;                  /* First leaf page number in segment */
   194533   int pgnoLast;                   /* Last leaf page number in segment */
   194534 };
   194535 struct Fts5StructureLevel {
   194536   int nMerge;                     /* Number of segments in incr-merge */
   194537   int nSeg;                       /* Total number of segments on level */
   194538   Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
   194539 };
   194540 struct Fts5Structure {
   194541   int nRef;                       /* Object reference count */
   194542   u64 nWriteCounter;              /* Total leaves written to level 0 */
   194543   int nSegment;                   /* Total segments in this structure */
   194544   int nLevel;                     /* Number of levels in this index */
   194545   Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
   194546 };
   194547 
   194548 /*
   194549 ** An object of type Fts5SegWriter is used to write to segments.
   194550 */
   194551 struct Fts5PageWriter {
   194552   int pgno;                       /* Page number for this page */
   194553   int iPrevPgidx;                 /* Previous value written into pgidx */
   194554   Fts5Buffer buf;                 /* Buffer containing leaf data */
   194555   Fts5Buffer pgidx;               /* Buffer containing page-index */
   194556   Fts5Buffer term;                /* Buffer containing previous term on page */
   194557 };
   194558 struct Fts5DlidxWriter {
   194559   int pgno;                       /* Page number for this page */
   194560   int bPrevValid;                 /* True if iPrev is valid */
   194561   i64 iPrev;                      /* Previous rowid value written to page */
   194562   Fts5Buffer buf;                 /* Buffer containing page data */
   194563 };
   194564 struct Fts5SegWriter {
   194565   int iSegid;                     /* Segid to write to */
   194566   Fts5PageWriter writer;          /* PageWriter object */
   194567   i64 iPrevRowid;                 /* Previous rowid written to current leaf */
   194568   u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
   194569   u8 bFirstRowidInPage;           /* True if next rowid is first in page */
   194570   /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
   194571   u8 bFirstTermInPage;            /* True if next term will be first in leaf */
   194572   int nLeafWritten;               /* Number of leaf pages written */
   194573   int nEmpty;                     /* Number of contiguous term-less nodes */
   194574 
   194575   int nDlidx;                     /* Allocated size of aDlidx[] array */
   194576   Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
   194577 
   194578   /* Values to insert into the %_idx table */
   194579   Fts5Buffer btterm;              /* Next term to insert into %_idx table */
   194580   int iBtPage;                    /* Page number corresponding to btterm */
   194581 };
   194582 
   194583 typedef struct Fts5CResult Fts5CResult;
   194584 struct Fts5CResult {
   194585   u16 iFirst;                     /* aSeg[] index of firstest iterator */
   194586   u8 bTermEq;                     /* True if the terms are equal */
   194587 };
   194588 
   194589 /*
   194590 ** Object for iterating through a single segment, visiting each term/rowid
   194591 ** pair in the segment.
   194592 **
   194593 ** pSeg:
   194594 **   The segment to iterate through.
   194595 **
   194596 ** iLeafPgno:
   194597 **   Current leaf page number within segment.
   194598 **
   194599 ** iLeafOffset:
   194600 **   Byte offset within the current leaf that is the first byte of the
   194601 **   position list data (one byte passed the position-list size field).
   194602 **   rowid field of the current entry. Usually this is the size field of the
   194603 **   position list data. The exception is if the rowid for the current entry
   194604 **   is the last thing on the leaf page.
   194605 **
   194606 ** pLeaf:
   194607 **   Buffer containing current leaf page data. Set to NULL at EOF.
   194608 **
   194609 ** iTermLeafPgno, iTermLeafOffset:
   194610 **   Leaf page number containing the last term read from the segment. And
   194611 **   the offset immediately following the term data.
   194612 **
   194613 ** flags:
   194614 **   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
   194615 **
   194616 **   FTS5_SEGITER_ONETERM:
   194617 **     If set, set the iterator to point to EOF after the current doclist
   194618 **     has been exhausted. Do not proceed to the next term in the segment.
   194619 **
   194620 **   FTS5_SEGITER_REVERSE:
   194621 **     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
   194622 **     it is set, iterate through rowid in descending order instead of the
   194623 **     default ascending order.
   194624 **
   194625 ** iRowidOffset/nRowidOffset/aRowidOffset:
   194626 **     These are used if the FTS5_SEGITER_REVERSE flag is set.
   194627 **
   194628 **     For each rowid on the page corresponding to the current term, the
   194629 **     corresponding aRowidOffset[] entry is set to the byte offset of the
   194630 **     start of the "position-list-size" field within the page.
   194631 **
   194632 ** iTermIdx:
   194633 **     Index of current term on iTermLeafPgno.
   194634 */
   194635 struct Fts5SegIter {
   194636   Fts5StructureSegment *pSeg;     /* Segment to iterate through */
   194637   int flags;                      /* Mask of configuration flags */
   194638   int iLeafPgno;                  /* Current leaf page number */
   194639   Fts5Data *pLeaf;                /* Current leaf data */
   194640   Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
   194641   int iLeafOffset;                /* Byte offset within current leaf */
   194642 
   194643   /* Next method */
   194644   void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
   194645 
   194646   /* The page and offset from which the current term was read. The offset
   194647   ** is the offset of the first rowid in the current doclist.  */
   194648   int iTermLeafPgno;
   194649   int iTermLeafOffset;
   194650 
   194651   int iPgidxOff;                  /* Next offset in pgidx */
   194652   int iEndofDoclist;
   194653 
   194654   /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
   194655   int iRowidOffset;               /* Current entry in aRowidOffset[] */
   194656   int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
   194657   int *aRowidOffset;              /* Array of offset to rowid fields */
   194658 
   194659   Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
   194660 
   194661   /* Variables populated based on current entry. */
   194662   Fts5Buffer term;                /* Current term */
   194663   i64 iRowid;                     /* Current rowid */
   194664   int nPos;                       /* Number of bytes in current position list */
   194665   u8 bDel;                        /* True if the delete flag is set */
   194666 };
   194667 
   194668 /*
   194669 ** Argument is a pointer to an Fts5Data structure that contains a
   194670 ** leaf page.
   194671 */
   194672 #define ASSERT_SZLEAF_OK(x) assert( \
   194673     (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
   194674 )
   194675 
   194676 #define FTS5_SEGITER_ONETERM 0x01
   194677 #define FTS5_SEGITER_REVERSE 0x02
   194678 
   194679 /*
   194680 ** Argument is a pointer to an Fts5Data structure that contains a leaf
   194681 ** page. This macro evaluates to true if the leaf contains no terms, or
   194682 ** false if it contains at least one term.
   194683 */
   194684 #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
   194685 
   194686 #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
   194687 
   194688 #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
   194689 
   194690 /*
   194691 ** Object for iterating through the merged results of one or more segments,
   194692 ** visiting each term/rowid pair in the merged data.
   194693 **
   194694 ** nSeg is always a power of two greater than or equal to the number of
   194695 ** segments that this object is merging data from. Both the aSeg[] and
   194696 ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
   194697 ** with zeroed objects - these are handled as if they were iterators opened
   194698 ** on empty segments.
   194699 **
   194700 ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
   194701 ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
   194702 ** comparison in this context is the index of the iterator that currently
   194703 ** points to the smaller term/rowid combination. Iterators at EOF are
   194704 ** considered to be greater than all other iterators.
   194705 **
   194706 ** aFirst[1] contains the index in aSeg[] of the iterator that points to
   194707 ** the smallest key overall. aFirst[0] is unused.
   194708 **
   194709 ** poslist:
   194710 **   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
   194711 **   There is no way to tell if this is populated or not.
   194712 */
   194713 struct Fts5Iter {
   194714   Fts5IndexIter base;             /* Base class containing output vars */
   194715 
   194716   Fts5Index *pIndex;              /* Index that owns this iterator */
   194717   Fts5Structure *pStruct;         /* Database structure for this iterator */
   194718   Fts5Buffer poslist;             /* Buffer containing current poslist */
   194719   Fts5Colset *pColset;            /* Restrict matches to these columns */
   194720 
   194721   /* Invoked to set output variables. */
   194722   void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
   194723 
   194724   int nSeg;                       /* Size of aSeg[] array */
   194725   int bRev;                       /* True to iterate in reverse order */
   194726   u8 bSkipEmpty;                  /* True to skip deleted entries */
   194727 
   194728   i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
   194729   Fts5CResult *aFirst;            /* Current merge state (see above) */
   194730   Fts5SegIter aSeg[1];            /* Array of segment iterators */
   194731 };
   194732 
   194733 
   194734 /*
   194735 ** An instance of the following type is used to iterate through the contents
   194736 ** of a doclist-index record.
   194737 **
   194738 ** pData:
   194739 **   Record containing the doclist-index data.
   194740 **
   194741 ** bEof:
   194742 **   Set to true once iterator has reached EOF.
   194743 **
   194744 ** iOff:
   194745 **   Set to the current offset within record pData.
   194746 */
   194747 struct Fts5DlidxLvl {
   194748   Fts5Data *pData;              /* Data for current page of this level */
   194749   int iOff;                     /* Current offset into pData */
   194750   int bEof;                     /* At EOF already */
   194751   int iFirstOff;                /* Used by reverse iterators */
   194752 
   194753   /* Output variables */
   194754   int iLeafPgno;                /* Page number of current leaf page */
   194755   i64 iRowid;                   /* First rowid on leaf iLeafPgno */
   194756 };
   194757 struct Fts5DlidxIter {
   194758   int nLvl;
   194759   int iSegid;
   194760   Fts5DlidxLvl aLvl[1];
   194761 };
   194762 
   194763 static void fts5PutU16(u8 *aOut, u16 iVal){
   194764   aOut[0] = (iVal>>8);
   194765   aOut[1] = (iVal&0xFF);
   194766 }
   194767 
   194768 static u16 fts5GetU16(const u8 *aIn){
   194769   return ((u16)aIn[0] << 8) + aIn[1];
   194770 }
   194771 
   194772 /*
   194773 ** Allocate and return a buffer at least nByte bytes in size.
   194774 **
   194775 ** If an OOM error is encountered, return NULL and set the error code in
   194776 ** the Fts5Index handle passed as the first argument.
   194777 */
   194778 static void *fts5IdxMalloc(Fts5Index *p, int nByte){
   194779   return sqlite3Fts5MallocZero(&p->rc, nByte);
   194780 }
   194781 
   194782 /*
   194783 ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
   194784 **
   194785 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
   194786 ** +ve if pRight is smaller than pLeft. In other words:
   194787 **
   194788 **     res = *pLeft - *pRight
   194789 */
   194790 #ifdef SQLITE_DEBUG
   194791 static int fts5BufferCompareBlob(
   194792   Fts5Buffer *pLeft,              /* Left hand side of comparison */
   194793   const u8 *pRight, int nRight    /* Right hand side of comparison */
   194794 ){
   194795   int nCmp = MIN(pLeft->n, nRight);
   194796   int res = memcmp(pLeft->p, pRight, nCmp);
   194797   return (res==0 ? (pLeft->n - nRight) : res);
   194798 }
   194799 #endif
   194800 
   194801 /*
   194802 ** Compare the contents of the two buffers using memcmp(). If one buffer
   194803 ** is a prefix of the other, it is considered the lesser.
   194804 **
   194805 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
   194806 ** +ve if pRight is smaller than pLeft. In other words:
   194807 **
   194808 **     res = *pLeft - *pRight
   194809 */
   194810 static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
   194811   int nCmp = MIN(pLeft->n, pRight->n);
   194812   int res = memcmp(pLeft->p, pRight->p, nCmp);
   194813   return (res==0 ? (pLeft->n - pRight->n) : res);
   194814 }
   194815 
   194816 static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
   194817   int ret;
   194818   fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
   194819   return ret;
   194820 }
   194821 
   194822 /*
   194823 ** Close the read-only blob handle, if it is open.
   194824 */
   194825 static void fts5CloseReader(Fts5Index *p){
   194826   if( p->pReader ){
   194827     sqlite3_blob *pReader = p->pReader;
   194828     p->pReader = 0;
   194829     sqlite3_blob_close(pReader);
   194830   }
   194831 }
   194832 
   194833 /*
   194834 ** Retrieve a record from the %_data table.
   194835 **
   194836 ** If an error occurs, NULL is returned and an error left in the
   194837 ** Fts5Index object.
   194838 */
   194839 static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
   194840   Fts5Data *pRet = 0;
   194841   if( p->rc==SQLITE_OK ){
   194842     int rc = SQLITE_OK;
   194843 
   194844     if( p->pReader ){
   194845       /* This call may return SQLITE_ABORT if there has been a savepoint
   194846       ** rollback since it was last used. In this case a new blob handle
   194847       ** is required.  */
   194848       sqlite3_blob *pBlob = p->pReader;
   194849       p->pReader = 0;
   194850       rc = sqlite3_blob_reopen(pBlob, iRowid);
   194851       assert( p->pReader==0 );
   194852       p->pReader = pBlob;
   194853       if( rc!=SQLITE_OK ){
   194854         fts5CloseReader(p);
   194855       }
   194856       if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
   194857     }
   194858 
   194859     /* If the blob handle is not open at this point, open it and seek
   194860     ** to the requested entry.  */
   194861     if( p->pReader==0 && rc==SQLITE_OK ){
   194862       Fts5Config *pConfig = p->pConfig;
   194863       rc = sqlite3_blob_open(pConfig->db,
   194864           pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
   194865       );
   194866     }
   194867 
   194868     /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
   194869     ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
   194870     ** All the reasons those functions might return SQLITE_ERROR - missing
   194871     ** table, missing row, non-blob/text in block column - indicate
   194872     ** backing store corruption.  */
   194873     if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
   194874 
   194875     if( rc==SQLITE_OK ){
   194876       u8 *aOut = 0;               /* Read blob data into this buffer */
   194877       int nByte = sqlite3_blob_bytes(p->pReader);
   194878       int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
   194879       pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
   194880       if( pRet ){
   194881         pRet->nn = nByte;
   194882         aOut = pRet->p = (u8*)&pRet[1];
   194883       }else{
   194884         rc = SQLITE_NOMEM;
   194885       }
   194886 
   194887       if( rc==SQLITE_OK ){
   194888         rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
   194889       }
   194890       if( rc!=SQLITE_OK ){
   194891         sqlite3_free(pRet);
   194892         pRet = 0;
   194893       }else{
   194894         /* TODO1: Fix this */
   194895         pRet->szLeaf = fts5GetU16(&pRet->p[2]);
   194896       }
   194897     }
   194898     p->rc = rc;
   194899     p->nRead++;
   194900   }
   194901 
   194902   assert( (pRet==0)==(p->rc!=SQLITE_OK) );
   194903   return pRet;
   194904 }
   194905 
   194906 /*
   194907 ** Release a reference to data record returned by an earlier call to
   194908 ** fts5DataRead().
   194909 */
   194910 static void fts5DataRelease(Fts5Data *pData){
   194911   sqlite3_free(pData);
   194912 }
   194913 
   194914 static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
   194915   Fts5Data *pRet = fts5DataRead(p, iRowid);
   194916   if( pRet ){
   194917     if( pRet->szLeaf>pRet->nn ){
   194918       p->rc = FTS5_CORRUPT;
   194919       fts5DataRelease(pRet);
   194920       pRet = 0;
   194921     }
   194922   }
   194923   return pRet;
   194924 }
   194925 
   194926 static int fts5IndexPrepareStmt(
   194927   Fts5Index *p,
   194928   sqlite3_stmt **ppStmt,
   194929   char *zSql
   194930 ){
   194931   if( p->rc==SQLITE_OK ){
   194932     if( zSql ){
   194933       p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
   194934                                  SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
   194935     }else{
   194936       p->rc = SQLITE_NOMEM;
   194937     }
   194938   }
   194939   sqlite3_free(zSql);
   194940   return p->rc;
   194941 }
   194942 
   194943 
   194944 /*
   194945 ** INSERT OR REPLACE a record into the %_data table.
   194946 */
   194947 static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
   194948   if( p->rc!=SQLITE_OK ) return;
   194949 
   194950   if( p->pWriter==0 ){
   194951     Fts5Config *pConfig = p->pConfig;
   194952     fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
   194953           "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
   194954           pConfig->zDb, pConfig->zName
   194955     ));
   194956     if( p->rc ) return;
   194957   }
   194958 
   194959   sqlite3_bind_int64(p->pWriter, 1, iRowid);
   194960   sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
   194961   sqlite3_step(p->pWriter);
   194962   p->rc = sqlite3_reset(p->pWriter);
   194963 }
   194964 
   194965 /*
   194966 ** Execute the following SQL:
   194967 **
   194968 **     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
   194969 */
   194970 static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
   194971   if( p->rc!=SQLITE_OK ) return;
   194972 
   194973   if( p->pDeleter==0 ){
   194974     int rc;
   194975     Fts5Config *pConfig = p->pConfig;
   194976     char *zSql = sqlite3_mprintf(
   194977         "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
   194978           pConfig->zDb, pConfig->zName
   194979     );
   194980     if( zSql==0 ){
   194981       rc = SQLITE_NOMEM;
   194982     }else{
   194983       rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
   194984                               SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
   194985       sqlite3_free(zSql);
   194986     }
   194987     if( rc!=SQLITE_OK ){
   194988       p->rc = rc;
   194989       return;
   194990     }
   194991   }
   194992 
   194993   sqlite3_bind_int64(p->pDeleter, 1, iFirst);
   194994   sqlite3_bind_int64(p->pDeleter, 2, iLast);
   194995   sqlite3_step(p->pDeleter);
   194996   p->rc = sqlite3_reset(p->pDeleter);
   194997 }
   194998 
   194999 /*
   195000 ** Remove all records associated with segment iSegid.
   195001 */
   195002 static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
   195003   i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
   195004   i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
   195005   fts5DataDelete(p, iFirst, iLast);
   195006   if( p->pIdxDeleter==0 ){
   195007     Fts5Config *pConfig = p->pConfig;
   195008     fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
   195009           "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
   195010           pConfig->zDb, pConfig->zName
   195011     ));
   195012   }
   195013   if( p->rc==SQLITE_OK ){
   195014     sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
   195015     sqlite3_step(p->pIdxDeleter);
   195016     p->rc = sqlite3_reset(p->pIdxDeleter);
   195017   }
   195018 }
   195019 
   195020 /*
   195021 ** Release a reference to an Fts5Structure object returned by an earlier
   195022 ** call to fts5StructureRead() or fts5StructureDecode().
   195023 */
   195024 static void fts5StructureRelease(Fts5Structure *pStruct){
   195025   if( pStruct && 0>=(--pStruct->nRef) ){
   195026     int i;
   195027     assert( pStruct->nRef==0 );
   195028     for(i=0; i<pStruct->nLevel; i++){
   195029       sqlite3_free(pStruct->aLevel[i].aSeg);
   195030     }
   195031     sqlite3_free(pStruct);
   195032   }
   195033 }
   195034 
   195035 static void fts5StructureRef(Fts5Structure *pStruct){
   195036   pStruct->nRef++;
   195037 }
   195038 
   195039 /*
   195040 ** Deserialize and return the structure record currently stored in serialized
   195041 ** form within buffer pData/nData.
   195042 **
   195043 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
   195044 ** are over-allocated by one slot. This allows the structure contents
   195045 ** to be more easily edited.
   195046 **
   195047 ** If an error occurs, *ppOut is set to NULL and an SQLite error code
   195048 ** returned. Otherwise, *ppOut is set to point to the new object and
   195049 ** SQLITE_OK returned.
   195050 */
   195051 static int fts5StructureDecode(
   195052   const u8 *pData,                /* Buffer containing serialized structure */
   195053   int nData,                      /* Size of buffer pData in bytes */
   195054   int *piCookie,                  /* Configuration cookie value */
   195055   Fts5Structure **ppOut           /* OUT: Deserialized object */
   195056 ){
   195057   int rc = SQLITE_OK;
   195058   int i = 0;
   195059   int iLvl;
   195060   int nLevel = 0;
   195061   int nSegment = 0;
   195062   int nByte;                      /* Bytes of space to allocate at pRet */
   195063   Fts5Structure *pRet = 0;        /* Structure object to return */
   195064 
   195065   /* Grab the cookie value */
   195066   if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
   195067   i = 4;
   195068 
   195069   /* Read the total number of levels and segments from the start of the
   195070   ** structure record.  */
   195071   i += fts5GetVarint32(&pData[i], nLevel);
   195072   i += fts5GetVarint32(&pData[i], nSegment);
   195073   nByte = (
   195074       sizeof(Fts5Structure) +                    /* Main structure */
   195075       sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
   195076   );
   195077   pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
   195078 
   195079   if( pRet ){
   195080     pRet->nRef = 1;
   195081     pRet->nLevel = nLevel;
   195082     pRet->nSegment = nSegment;
   195083     i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
   195084 
   195085     for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
   195086       Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
   195087       int nTotal = 0;
   195088       int iSeg;
   195089 
   195090       if( i>=nData ){
   195091         rc = FTS5_CORRUPT;
   195092       }else{
   195093         i += fts5GetVarint32(&pData[i], pLvl->nMerge);
   195094         i += fts5GetVarint32(&pData[i], nTotal);
   195095         assert( nTotal>=pLvl->nMerge );
   195096         pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
   195097             nTotal * sizeof(Fts5StructureSegment)
   195098         );
   195099       }
   195100 
   195101       if( rc==SQLITE_OK ){
   195102         pLvl->nSeg = nTotal;
   195103         for(iSeg=0; iSeg<nTotal; iSeg++){
   195104           if( i>=nData ){
   195105             rc = FTS5_CORRUPT;
   195106             break;
   195107           }
   195108           i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
   195109           i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
   195110           i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
   195111         }
   195112       }
   195113     }
   195114     if( rc!=SQLITE_OK ){
   195115       fts5StructureRelease(pRet);
   195116       pRet = 0;
   195117     }
   195118   }
   195119 
   195120   *ppOut = pRet;
   195121   return rc;
   195122 }
   195123 
   195124 /*
   195125 **
   195126 */
   195127 static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
   195128   if( *pRc==SQLITE_OK ){
   195129     Fts5Structure *pStruct = *ppStruct;
   195130     int nLevel = pStruct->nLevel;
   195131     int nByte = (
   195132         sizeof(Fts5Structure) +                  /* Main structure */
   195133         sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
   195134     );
   195135 
   195136     pStruct = sqlite3_realloc(pStruct, nByte);
   195137     if( pStruct ){
   195138       memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
   195139       pStruct->nLevel++;
   195140       *ppStruct = pStruct;
   195141     }else{
   195142       *pRc = SQLITE_NOMEM;
   195143     }
   195144   }
   195145 }
   195146 
   195147 /*
   195148 ** Extend level iLvl so that there is room for at least nExtra more
   195149 ** segments.
   195150 */
   195151 static void fts5StructureExtendLevel(
   195152   int *pRc,
   195153   Fts5Structure *pStruct,
   195154   int iLvl,
   195155   int nExtra,
   195156   int bInsert
   195157 ){
   195158   if( *pRc==SQLITE_OK ){
   195159     Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
   195160     Fts5StructureSegment *aNew;
   195161     int nByte;
   195162 
   195163     nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
   195164     aNew = sqlite3_realloc(pLvl->aSeg, nByte);
   195165     if( aNew ){
   195166       if( bInsert==0 ){
   195167         memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
   195168       }else{
   195169         int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
   195170         memmove(&aNew[nExtra], aNew, nMove);
   195171         memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
   195172       }
   195173       pLvl->aSeg = aNew;
   195174     }else{
   195175       *pRc = SQLITE_NOMEM;
   195176     }
   195177   }
   195178 }
   195179 
   195180 static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
   195181   Fts5Structure *pRet = 0;
   195182   Fts5Config *pConfig = p->pConfig;
   195183   int iCookie;                    /* Configuration cookie */
   195184   Fts5Data *pData;
   195185 
   195186   pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
   195187   if( p->rc==SQLITE_OK ){
   195188     /* TODO: Do we need this if the leaf-index is appended? Probably... */
   195189     memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
   195190     p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
   195191     if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
   195192       p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
   195193     }
   195194     fts5DataRelease(pData);
   195195     if( p->rc!=SQLITE_OK ){
   195196       fts5StructureRelease(pRet);
   195197       pRet = 0;
   195198     }
   195199   }
   195200 
   195201   return pRet;
   195202 }
   195203 
   195204 static i64 fts5IndexDataVersion(Fts5Index *p){
   195205   i64 iVersion = 0;
   195206 
   195207   if( p->rc==SQLITE_OK ){
   195208     if( p->pDataVersion==0 ){
   195209       p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
   195210           sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
   195211           );
   195212       if( p->rc ) return 0;
   195213     }
   195214 
   195215     if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
   195216       iVersion = sqlite3_column_int64(p->pDataVersion, 0);
   195217     }
   195218     p->rc = sqlite3_reset(p->pDataVersion);
   195219   }
   195220 
   195221   return iVersion;
   195222 }
   195223 
   195224 /*
   195225 ** Read, deserialize and return the structure record.
   195226 **
   195227 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
   195228 ** are over-allocated as described for function fts5StructureDecode()
   195229 ** above.
   195230 **
   195231 ** If an error occurs, NULL is returned and an error code left in the
   195232 ** Fts5Index handle. If an error has already occurred when this function
   195233 ** is called, it is a no-op.
   195234 */
   195235 static Fts5Structure *fts5StructureRead(Fts5Index *p){
   195236 
   195237   if( p->pStruct==0 ){
   195238     p->iStructVersion = fts5IndexDataVersion(p);
   195239     if( p->rc==SQLITE_OK ){
   195240       p->pStruct = fts5StructureReadUncached(p);
   195241     }
   195242   }
   195243 
   195244 #if 0
   195245   else{
   195246     Fts5Structure *pTest = fts5StructureReadUncached(p);
   195247     if( pTest ){
   195248       int i, j;
   195249       assert_nc( p->pStruct->nSegment==pTest->nSegment );
   195250       assert_nc( p->pStruct->nLevel==pTest->nLevel );
   195251       for(i=0; i<pTest->nLevel; i++){
   195252         assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
   195253         assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
   195254         for(j=0; j<pTest->aLevel[i].nSeg; j++){
   195255           Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
   195256           Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
   195257           assert_nc( p1->iSegid==p2->iSegid );
   195258           assert_nc( p1->pgnoFirst==p2->pgnoFirst );
   195259           assert_nc( p1->pgnoLast==p2->pgnoLast );
   195260         }
   195261       }
   195262       fts5StructureRelease(pTest);
   195263     }
   195264   }
   195265 #endif
   195266 
   195267   if( p->rc!=SQLITE_OK ) return 0;
   195268   assert( p->iStructVersion!=0 );
   195269   assert( p->pStruct!=0 );
   195270   fts5StructureRef(p->pStruct);
   195271   return p->pStruct;
   195272 }
   195273 
   195274 static void fts5StructureInvalidate(Fts5Index *p){
   195275   if( p->pStruct ){
   195276     fts5StructureRelease(p->pStruct);
   195277     p->pStruct = 0;
   195278   }
   195279 }
   195280 
   195281 /*
   195282 ** Return the total number of segments in index structure pStruct. This
   195283 ** function is only ever used as part of assert() conditions.
   195284 */
   195285 #ifdef SQLITE_DEBUG
   195286 static int fts5StructureCountSegments(Fts5Structure *pStruct){
   195287   int nSegment = 0;               /* Total number of segments */
   195288   if( pStruct ){
   195289     int iLvl;                     /* Used to iterate through levels */
   195290     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
   195291       nSegment += pStruct->aLevel[iLvl].nSeg;
   195292     }
   195293   }
   195294 
   195295   return nSegment;
   195296 }
   195297 #endif
   195298 
   195299 #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
   195300   assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
   195301   memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
   195302   (pBuf)->n += nBlob;                                      \
   195303 }
   195304 
   195305 #define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
   195306   (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
   195307   assert( (pBuf)->nSpace>=(pBuf)->n );                          \
   195308 }
   195309 
   195310 
   195311 /*
   195312 ** Serialize and store the "structure" record.
   195313 **
   195314 ** If an error occurs, leave an error code in the Fts5Index object. If an
   195315 ** error has already occurred, this function is a no-op.
   195316 */
   195317 static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
   195318   if( p->rc==SQLITE_OK ){
   195319     Fts5Buffer buf;               /* Buffer to serialize record into */
   195320     int iLvl;                     /* Used to iterate through levels */
   195321     int iCookie;                  /* Cookie value to store */
   195322 
   195323     assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
   195324     memset(&buf, 0, sizeof(Fts5Buffer));
   195325 
   195326     /* Append the current configuration cookie */
   195327     iCookie = p->pConfig->iCookie;
   195328     if( iCookie<0 ) iCookie = 0;
   195329 
   195330     if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
   195331       sqlite3Fts5Put32(buf.p, iCookie);
   195332       buf.n = 4;
   195333       fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
   195334       fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
   195335       fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
   195336     }
   195337 
   195338     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
   195339       int iSeg;                     /* Used to iterate through segments */
   195340       Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
   195341       fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
   195342       fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
   195343       assert( pLvl->nMerge<=pLvl->nSeg );
   195344 
   195345       for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
   195346         fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
   195347         fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
   195348         fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
   195349       }
   195350     }
   195351 
   195352     fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
   195353     fts5BufferFree(&buf);
   195354   }
   195355 }
   195356 
   195357 #if 0
   195358 static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
   195359 static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
   195360   int rc = SQLITE_OK;
   195361   Fts5Buffer buf;
   195362   memset(&buf, 0, sizeof(buf));
   195363   fts5DebugStructure(&rc, &buf, pStruct);
   195364   fprintf(stdout, "%s: %s\n", zCaption, buf.p);
   195365   fflush(stdout);
   195366   fts5BufferFree(&buf);
   195367 }
   195368 #else
   195369 # define fts5PrintStructure(x,y)
   195370 #endif
   195371 
   195372 static int fts5SegmentSize(Fts5StructureSegment *pSeg){
   195373   return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
   195374 }
   195375 
   195376 /*
   195377 ** Return a copy of index structure pStruct. Except, promote as many
   195378 ** segments as possible to level iPromote. If an OOM occurs, NULL is
   195379 ** returned.
   195380 */
   195381 static void fts5StructurePromoteTo(
   195382   Fts5Index *p,
   195383   int iPromote,
   195384   int szPromote,
   195385   Fts5Structure *pStruct
   195386 ){
   195387   int il, is;
   195388   Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
   195389 
   195390   if( pOut->nMerge==0 ){
   195391     for(il=iPromote+1; il<pStruct->nLevel; il++){
   195392       Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
   195393       if( pLvl->nMerge ) return;
   195394       for(is=pLvl->nSeg-1; is>=0; is--){
   195395         int sz = fts5SegmentSize(&pLvl->aSeg[is]);
   195396         if( sz>szPromote ) return;
   195397         fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
   195398         if( p->rc ) return;
   195399         memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
   195400         pOut->nSeg++;
   195401         pLvl->nSeg--;
   195402       }
   195403     }
   195404   }
   195405 }
   195406 
   195407 /*
   195408 ** A new segment has just been written to level iLvl of index structure
   195409 ** pStruct. This function determines if any segments should be promoted
   195410 ** as a result. Segments are promoted in two scenarios:
   195411 **
   195412 **   a) If the segment just written is smaller than one or more segments
   195413 **      within the previous populated level, it is promoted to the previous
   195414 **      populated level.
   195415 **
   195416 **   b) If the segment just written is larger than the newest segment on
   195417 **      the next populated level, then that segment, and any other adjacent
   195418 **      segments that are also smaller than the one just written, are
   195419 **      promoted.
   195420 **
   195421 ** If one or more segments are promoted, the structure object is updated
   195422 ** to reflect this.
   195423 */
   195424 static void fts5StructurePromote(
   195425   Fts5Index *p,                   /* FTS5 backend object */
   195426   int iLvl,                       /* Index level just updated */
   195427   Fts5Structure *pStruct          /* Index structure */
   195428 ){
   195429   if( p->rc==SQLITE_OK ){
   195430     int iTst;
   195431     int iPromote = -1;
   195432     int szPromote = 0;            /* Promote anything this size or smaller */
   195433     Fts5StructureSegment *pSeg;   /* Segment just written */
   195434     int szSeg;                    /* Size of segment just written */
   195435     int nSeg = pStruct->aLevel[iLvl].nSeg;
   195436 
   195437     if( nSeg==0 ) return;
   195438     pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
   195439     szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
   195440 
   195441     /* Check for condition (a) */
   195442     for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
   195443     if( iTst>=0 ){
   195444       int i;
   195445       int szMax = 0;
   195446       Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
   195447       assert( pTst->nMerge==0 );
   195448       for(i=0; i<pTst->nSeg; i++){
   195449         int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
   195450         if( sz>szMax ) szMax = sz;
   195451       }
   195452       if( szMax>=szSeg ){
   195453         /* Condition (a) is true. Promote the newest segment on level
   195454         ** iLvl to level iTst.  */
   195455         iPromote = iTst;
   195456         szPromote = szMax;
   195457       }
   195458     }
   195459 
   195460     /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
   195461     ** is a no-op if it is not.  */
   195462     if( iPromote<0 ){
   195463       iPromote = iLvl;
   195464       szPromote = szSeg;
   195465     }
   195466     fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
   195467   }
   195468 }
   195469 
   195470 
   195471 /*
   195472 ** Advance the iterator passed as the only argument. If the end of the
   195473 ** doclist-index page is reached, return non-zero.
   195474 */
   195475 static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
   195476   Fts5Data *pData = pLvl->pData;
   195477 
   195478   if( pLvl->iOff==0 ){
   195479     assert( pLvl->bEof==0 );
   195480     pLvl->iOff = 1;
   195481     pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
   195482     pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
   195483     pLvl->iFirstOff = pLvl->iOff;
   195484   }else{
   195485     int iOff;
   195486     for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
   195487       if( pData->p[iOff] ) break;
   195488     }
   195489 
   195490     if( iOff<pData->nn ){
   195491       i64 iVal;
   195492       pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
   195493       iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
   195494       pLvl->iRowid += iVal;
   195495       pLvl->iOff = iOff;
   195496     }else{
   195497       pLvl->bEof = 1;
   195498     }
   195499   }
   195500 
   195501   return pLvl->bEof;
   195502 }
   195503 
   195504 /*
   195505 ** Advance the iterator passed as the only argument.
   195506 */
   195507 static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
   195508   Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
   195509 
   195510   assert( iLvl<pIter->nLvl );
   195511   if( fts5DlidxLvlNext(pLvl) ){
   195512     if( (iLvl+1) < pIter->nLvl ){
   195513       fts5DlidxIterNextR(p, pIter, iLvl+1);
   195514       if( pLvl[1].bEof==0 ){
   195515         fts5DataRelease(pLvl->pData);
   195516         memset(pLvl, 0, sizeof(Fts5DlidxLvl));
   195517         pLvl->pData = fts5DataRead(p,
   195518             FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
   195519         );
   195520         if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
   195521       }
   195522     }
   195523   }
   195524 
   195525   return pIter->aLvl[0].bEof;
   195526 }
   195527 static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
   195528   return fts5DlidxIterNextR(p, pIter, 0);
   195529 }
   195530 
   195531 /*
   195532 ** The iterator passed as the first argument has the following fields set
   195533 ** as follows. This function sets up the rest of the iterator so that it
   195534 ** points to the first rowid in the doclist-index.
   195535 **
   195536 **   pData:
   195537 **     pointer to doclist-index record,
   195538 **
   195539 ** When this function is called pIter->iLeafPgno is the page number the
   195540 ** doclist is associated with (the one featuring the term).
   195541 */
   195542 static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
   195543   int i;
   195544   for(i=0; i<pIter->nLvl; i++){
   195545     fts5DlidxLvlNext(&pIter->aLvl[i]);
   195546   }
   195547   return pIter->aLvl[0].bEof;
   195548 }
   195549 
   195550 
   195551 static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
   195552   return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
   195553 }
   195554 
   195555 static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
   195556   int i;
   195557 
   195558   /* Advance each level to the last entry on the last page */
   195559   for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
   195560     Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
   195561     while( fts5DlidxLvlNext(pLvl)==0 );
   195562     pLvl->bEof = 0;
   195563 
   195564     if( i>0 ){
   195565       Fts5DlidxLvl *pChild = &pLvl[-1];
   195566       fts5DataRelease(pChild->pData);
   195567       memset(pChild, 0, sizeof(Fts5DlidxLvl));
   195568       pChild->pData = fts5DataRead(p,
   195569           FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
   195570       );
   195571     }
   195572   }
   195573 }
   195574 
   195575 /*
   195576 ** Move the iterator passed as the only argument to the previous entry.
   195577 */
   195578 static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
   195579   int iOff = pLvl->iOff;
   195580 
   195581   assert( pLvl->bEof==0 );
   195582   if( iOff<=pLvl->iFirstOff ){
   195583     pLvl->bEof = 1;
   195584   }else{
   195585     u8 *a = pLvl->pData->p;
   195586     i64 iVal;
   195587     int iLimit;
   195588     int ii;
   195589     int nZero = 0;
   195590 
   195591     /* Currently iOff points to the first byte of a varint. This block
   195592     ** decrements iOff until it points to the first byte of the previous
   195593     ** varint. Taking care not to read any memory locations that occur
   195594     ** before the buffer in memory.  */
   195595     iLimit = (iOff>9 ? iOff-9 : 0);
   195596     for(iOff--; iOff>iLimit; iOff--){
   195597       if( (a[iOff-1] & 0x80)==0 ) break;
   195598     }
   195599 
   195600     fts5GetVarint(&a[iOff], (u64*)&iVal);
   195601     pLvl->iRowid -= iVal;
   195602     pLvl->iLeafPgno--;
   195603 
   195604     /* Skip backwards past any 0x00 varints. */
   195605     for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
   195606       nZero++;
   195607     }
   195608     if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
   195609       /* The byte immediately before the last 0x00 byte has the 0x80 bit
   195610       ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
   195611       ** bytes before a[ii]. */
   195612       int bZero = 0;              /* True if last 0x00 counts */
   195613       if( (ii-8)>=pLvl->iFirstOff ){
   195614         int j;
   195615         for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
   195616         bZero = (j>8);
   195617       }
   195618       if( bZero==0 ) nZero--;
   195619     }
   195620     pLvl->iLeafPgno -= nZero;
   195621     pLvl->iOff = iOff - nZero;
   195622   }
   195623 
   195624   return pLvl->bEof;
   195625 }
   195626 
   195627 static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
   195628   Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
   195629 
   195630   assert( iLvl<pIter->nLvl );
   195631   if( fts5DlidxLvlPrev(pLvl) ){
   195632     if( (iLvl+1) < pIter->nLvl ){
   195633       fts5DlidxIterPrevR(p, pIter, iLvl+1);
   195634       if( pLvl[1].bEof==0 ){
   195635         fts5DataRelease(pLvl->pData);
   195636         memset(pLvl, 0, sizeof(Fts5DlidxLvl));
   195637         pLvl->pData = fts5DataRead(p,
   195638             FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
   195639         );
   195640         if( pLvl->pData ){
   195641           while( fts5DlidxLvlNext(pLvl)==0 );
   195642           pLvl->bEof = 0;
   195643         }
   195644       }
   195645     }
   195646   }
   195647 
   195648   return pIter->aLvl[0].bEof;
   195649 }
   195650 static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
   195651   return fts5DlidxIterPrevR(p, pIter, 0);
   195652 }
   195653 
   195654 /*
   195655 ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
   195656 */
   195657 static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
   195658   if( pIter ){
   195659     int i;
   195660     for(i=0; i<pIter->nLvl; i++){
   195661       fts5DataRelease(pIter->aLvl[i].pData);
   195662     }
   195663     sqlite3_free(pIter);
   195664   }
   195665 }
   195666 
   195667 static Fts5DlidxIter *fts5DlidxIterInit(
   195668   Fts5Index *p,                   /* Fts5 Backend to iterate within */
   195669   int bRev,                       /* True for ORDER BY ASC */
   195670   int iSegid,                     /* Segment id */
   195671   int iLeafPg                     /* Leaf page number to load dlidx for */
   195672 ){
   195673   Fts5DlidxIter *pIter = 0;
   195674   int i;
   195675   int bDone = 0;
   195676 
   195677   for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
   195678     int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
   195679     Fts5DlidxIter *pNew;
   195680 
   195681     pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
   195682     if( pNew==0 ){
   195683       p->rc = SQLITE_NOMEM;
   195684     }else{
   195685       i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
   195686       Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
   195687       pIter = pNew;
   195688       memset(pLvl, 0, sizeof(Fts5DlidxLvl));
   195689       pLvl->pData = fts5DataRead(p, iRowid);
   195690       if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
   195691         bDone = 1;
   195692       }
   195693       pIter->nLvl = i+1;
   195694     }
   195695   }
   195696 
   195697   if( p->rc==SQLITE_OK ){
   195698     pIter->iSegid = iSegid;
   195699     if( bRev==0 ){
   195700       fts5DlidxIterFirst(pIter);
   195701     }else{
   195702       fts5DlidxIterLast(p, pIter);
   195703     }
   195704   }
   195705 
   195706   if( p->rc!=SQLITE_OK ){
   195707     fts5DlidxIterFree(pIter);
   195708     pIter = 0;
   195709   }
   195710 
   195711   return pIter;
   195712 }
   195713 
   195714 static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
   195715   return pIter->aLvl[0].iRowid;
   195716 }
   195717 static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
   195718   return pIter->aLvl[0].iLeafPgno;
   195719 }
   195720 
   195721 /*
   195722 ** Load the next leaf page into the segment iterator.
   195723 */
   195724 static void fts5SegIterNextPage(
   195725   Fts5Index *p,                   /* FTS5 backend object */
   195726   Fts5SegIter *pIter              /* Iterator to advance to next page */
   195727 ){
   195728   Fts5Data *pLeaf;
   195729   Fts5StructureSegment *pSeg = pIter->pSeg;
   195730   fts5DataRelease(pIter->pLeaf);
   195731   pIter->iLeafPgno++;
   195732   if( pIter->pNextLeaf ){
   195733     pIter->pLeaf = pIter->pNextLeaf;
   195734     pIter->pNextLeaf = 0;
   195735   }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
   195736     pIter->pLeaf = fts5LeafRead(p,
   195737         FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
   195738     );
   195739   }else{
   195740     pIter->pLeaf = 0;
   195741   }
   195742   pLeaf = pIter->pLeaf;
   195743 
   195744   if( pLeaf ){
   195745     pIter->iPgidxOff = pLeaf->szLeaf;
   195746     if( fts5LeafIsTermless(pLeaf) ){
   195747       pIter->iEndofDoclist = pLeaf->nn+1;
   195748     }else{
   195749       pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
   195750           pIter->iEndofDoclist
   195751       );
   195752     }
   195753   }
   195754 }
   195755 
   195756 /*
   195757 ** Argument p points to a buffer containing a varint to be interpreted as a
   195758 ** position list size field. Read the varint and return the number of bytes
   195759 ** read. Before returning, set *pnSz to the number of bytes in the position
   195760 ** list, and *pbDel to true if the delete flag is set, or false otherwise.
   195761 */
   195762 static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
   195763   int nSz;
   195764   int n = 0;
   195765   fts5FastGetVarint32(p, n, nSz);
   195766   assert_nc( nSz>=0 );
   195767   *pnSz = nSz/2;
   195768   *pbDel = nSz & 0x0001;
   195769   return n;
   195770 }
   195771 
   195772 /*
   195773 ** Fts5SegIter.iLeafOffset currently points to the first byte of a
   195774 ** position-list size field. Read the value of the field and store it
   195775 ** in the following variables:
   195776 **
   195777 **   Fts5SegIter.nPos
   195778 **   Fts5SegIter.bDel
   195779 **
   195780 ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
   195781 ** position list content (if any).
   195782 */
   195783 static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
   195784   if( p->rc==SQLITE_OK ){
   195785     int iOff = pIter->iLeafOffset;  /* Offset to read at */
   195786     ASSERT_SZLEAF_OK(pIter->pLeaf);
   195787     if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
   195788       int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
   195789       pIter->bDel = 0;
   195790       pIter->nPos = 1;
   195791       if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
   195792         pIter->bDel = 1;
   195793         iOff++;
   195794         if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
   195795           pIter->nPos = 1;
   195796           iOff++;
   195797         }else{
   195798           pIter->nPos = 0;
   195799         }
   195800       }
   195801     }else{
   195802       int nSz;
   195803       fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
   195804       pIter->bDel = (nSz & 0x0001);
   195805       pIter->nPos = nSz>>1;
   195806       assert_nc( pIter->nPos>=0 );
   195807     }
   195808     pIter->iLeafOffset = iOff;
   195809   }
   195810 }
   195811 
   195812 static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
   195813   u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
   195814   int iOff = pIter->iLeafOffset;
   195815 
   195816   ASSERT_SZLEAF_OK(pIter->pLeaf);
   195817   if( iOff>=pIter->pLeaf->szLeaf ){
   195818     fts5SegIterNextPage(p, pIter);
   195819     if( pIter->pLeaf==0 ){
   195820       if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
   195821       return;
   195822     }
   195823     iOff = 4;
   195824     a = pIter->pLeaf->p;
   195825   }
   195826   iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
   195827   pIter->iLeafOffset = iOff;
   195828 }
   195829 
   195830 /*
   195831 ** Fts5SegIter.iLeafOffset currently points to the first byte of the
   195832 ** "nSuffix" field of a term. Function parameter nKeep contains the value
   195833 ** of the "nPrefix" field (if there was one - it is passed 0 if this is
   195834 ** the first term in the segment).
   195835 **
   195836 ** This function populates:
   195837 **
   195838 **   Fts5SegIter.term
   195839 **   Fts5SegIter.rowid
   195840 **
   195841 ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
   195842 ** the first position list. The position list belonging to document
   195843 ** (Fts5SegIter.iRowid).
   195844 */
   195845 static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
   195846   u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
   195847   int iOff = pIter->iLeafOffset;  /* Offset to read at */
   195848   int nNew;                       /* Bytes of new data */
   195849 
   195850   iOff += fts5GetVarint32(&a[iOff], nNew);
   195851   if( iOff+nNew>pIter->pLeaf->nn ){
   195852     p->rc = FTS5_CORRUPT;
   195853     return;
   195854   }
   195855   pIter->term.n = nKeep;
   195856   fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
   195857   iOff += nNew;
   195858   pIter->iTermLeafOffset = iOff;
   195859   pIter->iTermLeafPgno = pIter->iLeafPgno;
   195860   pIter->iLeafOffset = iOff;
   195861 
   195862   if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
   195863     pIter->iEndofDoclist = pIter->pLeaf->nn+1;
   195864   }else{
   195865     int nExtra;
   195866     pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
   195867     pIter->iEndofDoclist += nExtra;
   195868   }
   195869 
   195870   fts5SegIterLoadRowid(p, pIter);
   195871 }
   195872 
   195873 static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
   195874 static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
   195875 static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
   195876 
   195877 static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
   195878   if( pIter->flags & FTS5_SEGITER_REVERSE ){
   195879     pIter->xNext = fts5SegIterNext_Reverse;
   195880   }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
   195881     pIter->xNext = fts5SegIterNext_None;
   195882   }else{
   195883     pIter->xNext = fts5SegIterNext;
   195884   }
   195885 }
   195886 
   195887 /*
   195888 ** Initialize the iterator object pIter to iterate through the entries in
   195889 ** segment pSeg. The iterator is left pointing to the first entry when
   195890 ** this function returns.
   195891 **
   195892 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
   195893 ** an error has already occurred when this function is called, it is a no-op.
   195894 */
   195895 static void fts5SegIterInit(
   195896   Fts5Index *p,                   /* FTS index object */
   195897   Fts5StructureSegment *pSeg,     /* Description of segment */
   195898   Fts5SegIter *pIter              /* Object to populate */
   195899 ){
   195900   if( pSeg->pgnoFirst==0 ){
   195901     /* This happens if the segment is being used as an input to an incremental
   195902     ** merge and all data has already been "trimmed". See function
   195903     ** fts5TrimSegments() for details. In this case leave the iterator empty.
   195904     ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
   195905     ** at EOF already. */
   195906     assert( pIter->pLeaf==0 );
   195907     return;
   195908   }
   195909 
   195910   if( p->rc==SQLITE_OK ){
   195911     memset(pIter, 0, sizeof(*pIter));
   195912     fts5SegIterSetNext(p, pIter);
   195913     pIter->pSeg = pSeg;
   195914     pIter->iLeafPgno = pSeg->pgnoFirst-1;
   195915     fts5SegIterNextPage(p, pIter);
   195916   }
   195917 
   195918   if( p->rc==SQLITE_OK ){
   195919     pIter->iLeafOffset = 4;
   195920     assert_nc( pIter->pLeaf->nn>4 );
   195921     assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
   195922     pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
   195923     fts5SegIterLoadTerm(p, pIter, 0);
   195924     fts5SegIterLoadNPos(p, pIter);
   195925   }
   195926 }
   195927 
   195928 /*
   195929 ** This function is only ever called on iterators created by calls to
   195930 ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
   195931 **
   195932 ** The iterator is in an unusual state when this function is called: the
   195933 ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
   195934 ** the position-list size field for the first relevant rowid on the page.
   195935 ** Fts5SegIter.rowid is set, but nPos and bDel are not.
   195936 **
   195937 ** This function advances the iterator so that it points to the last
   195938 ** relevant rowid on the page and, if necessary, initializes the
   195939 ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
   195940 ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
   195941 ** byte of the position list content associated with said rowid.
   195942 */
   195943 static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
   195944   int eDetail = p->pConfig->eDetail;
   195945   int n = pIter->pLeaf->szLeaf;
   195946   int i = pIter->iLeafOffset;
   195947   u8 *a = pIter->pLeaf->p;
   195948   int iRowidOffset = 0;
   195949 
   195950   if( n>pIter->iEndofDoclist ){
   195951     n = pIter->iEndofDoclist;
   195952   }
   195953 
   195954   ASSERT_SZLEAF_OK(pIter->pLeaf);
   195955   while( 1 ){
   195956     i64 iDelta = 0;
   195957 
   195958     if( eDetail==FTS5_DETAIL_NONE ){
   195959       /* todo */
   195960       if( i<n && a[i]==0 ){
   195961         i++;
   195962         if( i<n && a[i]==0 ) i++;
   195963       }
   195964     }else{
   195965       int nPos;
   195966       int bDummy;
   195967       i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
   195968       i += nPos;
   195969     }
   195970     if( i>=n ) break;
   195971     i += fts5GetVarint(&a[i], (u64*)&iDelta);
   195972     pIter->iRowid += iDelta;
   195973 
   195974     /* If necessary, grow the pIter->aRowidOffset[] array. */
   195975     if( iRowidOffset>=pIter->nRowidOffset ){
   195976       int nNew = pIter->nRowidOffset + 8;
   195977       int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
   195978       if( aNew==0 ){
   195979         p->rc = SQLITE_NOMEM;
   195980         break;
   195981       }
   195982       pIter->aRowidOffset = aNew;
   195983       pIter->nRowidOffset = nNew;
   195984     }
   195985 
   195986     pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
   195987     pIter->iLeafOffset = i;
   195988   }
   195989   pIter->iRowidOffset = iRowidOffset;
   195990   fts5SegIterLoadNPos(p, pIter);
   195991 }
   195992 
   195993 /*
   195994 **
   195995 */
   195996 static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
   195997   assert( pIter->flags & FTS5_SEGITER_REVERSE );
   195998   assert( pIter->flags & FTS5_SEGITER_ONETERM );
   195999 
   196000   fts5DataRelease(pIter->pLeaf);
   196001   pIter->pLeaf = 0;
   196002   while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
   196003     Fts5Data *pNew;
   196004     pIter->iLeafPgno--;
   196005     pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
   196006           pIter->pSeg->iSegid, pIter->iLeafPgno
   196007     ));
   196008     if( pNew ){
   196009       /* iTermLeafOffset may be equal to szLeaf if the term is the last
   196010       ** thing on the page - i.e. the first rowid is on the following page.
   196011       ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
   196012       if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
   196013         assert( pIter->pLeaf==0 );
   196014         if( pIter->iTermLeafOffset<pNew->szLeaf ){
   196015           pIter->pLeaf = pNew;
   196016           pIter->iLeafOffset = pIter->iTermLeafOffset;
   196017         }
   196018       }else{
   196019         int iRowidOff;
   196020         iRowidOff = fts5LeafFirstRowidOff(pNew);
   196021         if( iRowidOff ){
   196022           pIter->pLeaf = pNew;
   196023           pIter->iLeafOffset = iRowidOff;
   196024         }
   196025       }
   196026 
   196027       if( pIter->pLeaf ){
   196028         u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
   196029         pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
   196030         break;
   196031       }else{
   196032         fts5DataRelease(pNew);
   196033       }
   196034     }
   196035   }
   196036 
   196037   if( pIter->pLeaf ){
   196038     pIter->iEndofDoclist = pIter->pLeaf->nn+1;
   196039     fts5SegIterReverseInitPage(p, pIter);
   196040   }
   196041 }
   196042 
   196043 /*
   196044 ** Return true if the iterator passed as the second argument currently
   196045 ** points to a delete marker. A delete marker is an entry with a 0 byte
   196046 ** position-list.
   196047 */
   196048 static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
   196049   Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
   196050   return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
   196051 }
   196052 
   196053 /*
   196054 ** Advance iterator pIter to the next entry.
   196055 **
   196056 ** This version of fts5SegIterNext() is only used by reverse iterators.
   196057 */
   196058 static void fts5SegIterNext_Reverse(
   196059   Fts5Index *p,                   /* FTS5 backend object */
   196060   Fts5SegIter *pIter,             /* Iterator to advance */
   196061   int *pbUnused                   /* Unused */
   196062 ){
   196063   assert( pIter->flags & FTS5_SEGITER_REVERSE );
   196064   assert( pIter->pNextLeaf==0 );
   196065   UNUSED_PARAM(pbUnused);
   196066 
   196067   if( pIter->iRowidOffset>0 ){
   196068     u8 *a = pIter->pLeaf->p;
   196069     int iOff;
   196070     i64 iDelta;
   196071 
   196072     pIter->iRowidOffset--;
   196073     pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
   196074     fts5SegIterLoadNPos(p, pIter);
   196075     iOff = pIter->iLeafOffset;
   196076     if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
   196077       iOff += pIter->nPos;
   196078     }
   196079     fts5GetVarint(&a[iOff], (u64*)&iDelta);
   196080     pIter->iRowid -= iDelta;
   196081   }else{
   196082     fts5SegIterReverseNewPage(p, pIter);
   196083   }
   196084 }
   196085 
   196086 /*
   196087 ** Advance iterator pIter to the next entry.
   196088 **
   196089 ** This version of fts5SegIterNext() is only used if detail=none and the
   196090 ** iterator is not a reverse direction iterator.
   196091 */
   196092 static void fts5SegIterNext_None(
   196093   Fts5Index *p,                   /* FTS5 backend object */
   196094   Fts5SegIter *pIter,             /* Iterator to advance */
   196095   int *pbNewTerm                  /* OUT: Set for new term */
   196096 ){
   196097   int iOff;
   196098 
   196099   assert( p->rc==SQLITE_OK );
   196100   assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
   196101   assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
   196102 
   196103   ASSERT_SZLEAF_OK(pIter->pLeaf);
   196104   iOff = pIter->iLeafOffset;
   196105 
   196106   /* Next entry is on the next page */
   196107   if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
   196108     fts5SegIterNextPage(p, pIter);
   196109     if( p->rc || pIter->pLeaf==0 ) return;
   196110     pIter->iRowid = 0;
   196111     iOff = 4;
   196112   }
   196113 
   196114   if( iOff<pIter->iEndofDoclist ){
   196115     /* Next entry is on the current page */
   196116     i64 iDelta;
   196117     iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
   196118     pIter->iLeafOffset = iOff;
   196119     pIter->iRowid += iDelta;
   196120   }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
   196121     if( pIter->pSeg ){
   196122       int nKeep = 0;
   196123       if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
   196124         iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
   196125       }
   196126       pIter->iLeafOffset = iOff;
   196127       fts5SegIterLoadTerm(p, pIter, nKeep);
   196128     }else{
   196129       const u8 *pList = 0;
   196130       const char *zTerm = 0;
   196131       int nList;
   196132       sqlite3Fts5HashScanNext(p->pHash);
   196133       sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
   196134       if( pList==0 ) goto next_none_eof;
   196135       pIter->pLeaf->p = (u8*)pList;
   196136       pIter->pLeaf->nn = nList;
   196137       pIter->pLeaf->szLeaf = nList;
   196138       pIter->iEndofDoclist = nList;
   196139       sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
   196140       pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
   196141     }
   196142 
   196143     if( pbNewTerm ) *pbNewTerm = 1;
   196144   }else{
   196145     goto next_none_eof;
   196146   }
   196147 
   196148   fts5SegIterLoadNPos(p, pIter);
   196149 
   196150   return;
   196151  next_none_eof:
   196152   fts5DataRelease(pIter->pLeaf);
   196153   pIter->pLeaf = 0;
   196154 }
   196155 
   196156 
   196157 /*
   196158 ** Advance iterator pIter to the next entry.
   196159 **
   196160 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
   196161 ** is not considered an error if the iterator reaches EOF. If an error has
   196162 ** already occurred when this function is called, it is a no-op.
   196163 */
   196164 static void fts5SegIterNext(
   196165   Fts5Index *p,                   /* FTS5 backend object */
   196166   Fts5SegIter *pIter,             /* Iterator to advance */
   196167   int *pbNewTerm                  /* OUT: Set for new term */
   196168 ){
   196169   Fts5Data *pLeaf = pIter->pLeaf;
   196170   int iOff;
   196171   int bNewTerm = 0;
   196172   int nKeep = 0;
   196173   u8 *a;
   196174   int n;
   196175 
   196176   assert( pbNewTerm==0 || *pbNewTerm==0 );
   196177   assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
   196178 
   196179   /* Search for the end of the position list within the current page. */
   196180   a = pLeaf->p;
   196181   n = pLeaf->szLeaf;
   196182 
   196183   ASSERT_SZLEAF_OK(pLeaf);
   196184   iOff = pIter->iLeafOffset + pIter->nPos;
   196185 
   196186   if( iOff<n ){
   196187     /* The next entry is on the current page. */
   196188     assert_nc( iOff<=pIter->iEndofDoclist );
   196189     if( iOff>=pIter->iEndofDoclist ){
   196190       bNewTerm = 1;
   196191       if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
   196192         iOff += fts5GetVarint32(&a[iOff], nKeep);
   196193       }
   196194     }else{
   196195       u64 iDelta;
   196196       iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
   196197       pIter->iRowid += iDelta;
   196198       assert_nc( iDelta>0 );
   196199     }
   196200     pIter->iLeafOffset = iOff;
   196201 
   196202   }else if( pIter->pSeg==0 ){
   196203     const u8 *pList = 0;
   196204     const char *zTerm = 0;
   196205     int nList = 0;
   196206     assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
   196207     if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
   196208       sqlite3Fts5HashScanNext(p->pHash);
   196209       sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
   196210     }
   196211     if( pList==0 ){
   196212       fts5DataRelease(pIter->pLeaf);
   196213       pIter->pLeaf = 0;
   196214     }else{
   196215       pIter->pLeaf->p = (u8*)pList;
   196216       pIter->pLeaf->nn = nList;
   196217       pIter->pLeaf->szLeaf = nList;
   196218       pIter->iEndofDoclist = nList+1;
   196219       sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
   196220           (u8*)zTerm);
   196221       pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
   196222       *pbNewTerm = 1;
   196223     }
   196224   }else{
   196225     iOff = 0;
   196226     /* Next entry is not on the current page */
   196227     while( iOff==0 ){
   196228       fts5SegIterNextPage(p, pIter);
   196229       pLeaf = pIter->pLeaf;
   196230       if( pLeaf==0 ) break;
   196231       ASSERT_SZLEAF_OK(pLeaf);
   196232       if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
   196233         iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
   196234         pIter->iLeafOffset = iOff;
   196235 
   196236         if( pLeaf->nn>pLeaf->szLeaf ){
   196237           pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
   196238               &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
   196239           );
   196240         }
   196241       }
   196242       else if( pLeaf->nn>pLeaf->szLeaf ){
   196243         pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
   196244             &pLeaf->p[pLeaf->szLeaf], iOff
   196245         );
   196246         pIter->iLeafOffset = iOff;
   196247         pIter->iEndofDoclist = iOff;
   196248         bNewTerm = 1;
   196249       }
   196250       assert_nc( iOff<pLeaf->szLeaf );
   196251       if( iOff>pLeaf->szLeaf ){
   196252         p->rc = FTS5_CORRUPT;
   196253         return;
   196254       }
   196255     }
   196256   }
   196257 
   196258   /* Check if the iterator is now at EOF. If so, return early. */
   196259   if( pIter->pLeaf ){
   196260     if( bNewTerm ){
   196261       if( pIter->flags & FTS5_SEGITER_ONETERM ){
   196262         fts5DataRelease(pIter->pLeaf);
   196263         pIter->pLeaf = 0;
   196264       }else{
   196265         fts5SegIterLoadTerm(p, pIter, nKeep);
   196266         fts5SegIterLoadNPos(p, pIter);
   196267         if( pbNewTerm ) *pbNewTerm = 1;
   196268       }
   196269     }else{
   196270       /* The following could be done by calling fts5SegIterLoadNPos(). But
   196271       ** this block is particularly performance critical, so equivalent
   196272       ** code is inlined.
   196273       **
   196274       ** Later: Switched back to fts5SegIterLoadNPos() because it supports
   196275       ** detail=none mode. Not ideal.
   196276       */
   196277       int nSz;
   196278       assert( p->rc==SQLITE_OK );
   196279       assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
   196280       fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
   196281       pIter->bDel = (nSz & 0x0001);
   196282       pIter->nPos = nSz>>1;
   196283       assert_nc( pIter->nPos>=0 );
   196284     }
   196285   }
   196286 }
   196287 
   196288 #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
   196289 
   196290 #define fts5IndexSkipVarint(a, iOff) {            \
   196291   int iEnd = iOff+9;                              \
   196292   while( (a[iOff++] & 0x80) && iOff<iEnd );       \
   196293 }
   196294 
   196295 /*
   196296 ** Iterator pIter currently points to the first rowid in a doclist. This
   196297 ** function sets the iterator up so that iterates in reverse order through
   196298 ** the doclist.
   196299 */
   196300 static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
   196301   Fts5DlidxIter *pDlidx = pIter->pDlidx;
   196302   Fts5Data *pLast = 0;
   196303   int pgnoLast = 0;
   196304 
   196305   if( pDlidx ){
   196306     int iSegid = pIter->pSeg->iSegid;
   196307     pgnoLast = fts5DlidxIterPgno(pDlidx);
   196308     pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
   196309   }else{
   196310     Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
   196311 
   196312     /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
   196313     ** position-list content for the current rowid. Back it up so that it
   196314     ** points to the start of the position-list size field. */
   196315     int iPoslist;
   196316     if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
   196317       iPoslist = pIter->iTermLeafOffset;
   196318     }else{
   196319       iPoslist = 4;
   196320     }
   196321     fts5IndexSkipVarint(pLeaf->p, iPoslist);
   196322     pIter->iLeafOffset = iPoslist;
   196323 
   196324     /* If this condition is true then the largest rowid for the current
   196325     ** term may not be stored on the current page. So search forward to
   196326     ** see where said rowid really is.  */
   196327     if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
   196328       int pgno;
   196329       Fts5StructureSegment *pSeg = pIter->pSeg;
   196330 
   196331       /* The last rowid in the doclist may not be on the current page. Search
   196332       ** forward to find the page containing the last rowid.  */
   196333       for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
   196334         i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
   196335         Fts5Data *pNew = fts5DataRead(p, iAbs);
   196336         if( pNew ){
   196337           int iRowid, bTermless;
   196338           iRowid = fts5LeafFirstRowidOff(pNew);
   196339           bTermless = fts5LeafIsTermless(pNew);
   196340           if( iRowid ){
   196341             SWAPVAL(Fts5Data*, pNew, pLast);
   196342             pgnoLast = pgno;
   196343           }
   196344           fts5DataRelease(pNew);
   196345           if( bTermless==0 ) break;
   196346         }
   196347       }
   196348     }
   196349   }
   196350 
   196351   /* If pLast is NULL at this point, then the last rowid for this doclist
   196352   ** lies on the page currently indicated by the iterator. In this case
   196353   ** pIter->iLeafOffset is already set to point to the position-list size
   196354   ** field associated with the first relevant rowid on the page.
   196355   **
   196356   ** Or, if pLast is non-NULL, then it is the page that contains the last
   196357   ** rowid. In this case configure the iterator so that it points to the
   196358   ** first rowid on this page.
   196359   */
   196360   if( pLast ){
   196361     int iOff;
   196362     fts5DataRelease(pIter->pLeaf);
   196363     pIter->pLeaf = pLast;
   196364     pIter->iLeafPgno = pgnoLast;
   196365     iOff = fts5LeafFirstRowidOff(pLast);
   196366     iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
   196367     pIter->iLeafOffset = iOff;
   196368 
   196369     if( fts5LeafIsTermless(pLast) ){
   196370       pIter->iEndofDoclist = pLast->nn+1;
   196371     }else{
   196372       pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
   196373     }
   196374 
   196375   }
   196376 
   196377   fts5SegIterReverseInitPage(p, pIter);
   196378 }
   196379 
   196380 /*
   196381 ** Iterator pIter currently points to the first rowid of a doclist.
   196382 ** There is a doclist-index associated with the final term on the current
   196383 ** page. If the current term is the last term on the page, load the
   196384 ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
   196385 */
   196386 static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
   196387   int iSeg = pIter->pSeg->iSegid;
   196388   int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
   196389   Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
   196390 
   196391   assert( pIter->flags & FTS5_SEGITER_ONETERM );
   196392   assert( pIter->pDlidx==0 );
   196393 
   196394   /* Check if the current doclist ends on this page. If it does, return
   196395   ** early without loading the doclist-index (as it belongs to a different
   196396   ** term. */
   196397   if( pIter->iTermLeafPgno==pIter->iLeafPgno
   196398    && pIter->iEndofDoclist<pLeaf->szLeaf
   196399   ){
   196400     return;
   196401   }
   196402 
   196403   pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
   196404 }
   196405 
   196406 /*
   196407 ** The iterator object passed as the second argument currently contains
   196408 ** no valid values except for the Fts5SegIter.pLeaf member variable. This
   196409 ** function searches the leaf page for a term matching (pTerm/nTerm).
   196410 **
   196411 ** If the specified term is found on the page, then the iterator is left
   196412 ** pointing to it. If argument bGe is zero and the term is not found,
   196413 ** the iterator is left pointing at EOF.
   196414 **
   196415 ** If bGe is non-zero and the specified term is not found, then the
   196416 ** iterator is left pointing to the smallest term in the segment that
   196417 ** is larger than the specified term, even if this term is not on the
   196418 ** current page.
   196419 */
   196420 static void fts5LeafSeek(
   196421   Fts5Index *p,                   /* Leave any error code here */
   196422   int bGe,                        /* True for a >= search */
   196423   Fts5SegIter *pIter,             /* Iterator to seek */
   196424   const u8 *pTerm, int nTerm      /* Term to search for */
   196425 ){
   196426   int iOff;
   196427   const u8 *a = pIter->pLeaf->p;
   196428   int szLeaf = pIter->pLeaf->szLeaf;
   196429   int n = pIter->pLeaf->nn;
   196430 
   196431   int nMatch = 0;
   196432   int nKeep = 0;
   196433   int nNew = 0;
   196434   int iTermOff;
   196435   int iPgidx;                     /* Current offset in pgidx */
   196436   int bEndOfPage = 0;
   196437 
   196438   assert( p->rc==SQLITE_OK );
   196439 
   196440   iPgidx = szLeaf;
   196441   iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
   196442   iOff = iTermOff;
   196443   if( iOff>n ){
   196444     p->rc = FTS5_CORRUPT;
   196445     return;
   196446   }
   196447 
   196448   while( 1 ){
   196449 
   196450     /* Figure out how many new bytes are in this term */
   196451     fts5FastGetVarint32(a, iOff, nNew);
   196452     if( nKeep<nMatch ){
   196453       goto search_failed;
   196454     }
   196455 
   196456     assert( nKeep>=nMatch );
   196457     if( nKeep==nMatch ){
   196458       int nCmp;
   196459       int i;
   196460       nCmp = MIN(nNew, nTerm-nMatch);
   196461       for(i=0; i<nCmp; i++){
   196462         if( a[iOff+i]!=pTerm[nMatch+i] ) break;
   196463       }
   196464       nMatch += i;
   196465 
   196466       if( nTerm==nMatch ){
   196467         if( i==nNew ){
   196468           goto search_success;
   196469         }else{
   196470           goto search_failed;
   196471         }
   196472       }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
   196473         goto search_failed;
   196474       }
   196475     }
   196476 
   196477     if( iPgidx>=n ){
   196478       bEndOfPage = 1;
   196479       break;
   196480     }
   196481 
   196482     iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
   196483     iTermOff += nKeep;
   196484     iOff = iTermOff;
   196485 
   196486     if( iOff>=n ){
   196487       p->rc = FTS5_CORRUPT;
   196488       return;
   196489     }
   196490 
   196491     /* Read the nKeep field of the next term. */
   196492     fts5FastGetVarint32(a, iOff, nKeep);
   196493   }
   196494 
   196495  search_failed:
   196496   if( bGe==0 ){
   196497     fts5DataRelease(pIter->pLeaf);
   196498     pIter->pLeaf = 0;
   196499     return;
   196500   }else if( bEndOfPage ){
   196501     do {
   196502       fts5SegIterNextPage(p, pIter);
   196503       if( pIter->pLeaf==0 ) return;
   196504       a = pIter->pLeaf->p;
   196505       if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
   196506         iPgidx = pIter->pLeaf->szLeaf;
   196507         iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
   196508         if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
   196509           p->rc = FTS5_CORRUPT;
   196510         }else{
   196511           nKeep = 0;
   196512           iTermOff = iOff;
   196513           n = pIter->pLeaf->nn;
   196514           iOff += fts5GetVarint32(&a[iOff], nNew);
   196515           break;
   196516         }
   196517       }
   196518     }while( 1 );
   196519   }
   196520 
   196521  search_success:
   196522 
   196523   pIter->iLeafOffset = iOff + nNew;
   196524   pIter->iTermLeafOffset = pIter->iLeafOffset;
   196525   pIter->iTermLeafPgno = pIter->iLeafPgno;
   196526 
   196527   fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
   196528   fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
   196529 
   196530   if( iPgidx>=n ){
   196531     pIter->iEndofDoclist = pIter->pLeaf->nn+1;
   196532   }else{
   196533     int nExtra;
   196534     iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
   196535     pIter->iEndofDoclist = iTermOff + nExtra;
   196536   }
   196537   pIter->iPgidxOff = iPgidx;
   196538 
   196539   fts5SegIterLoadRowid(p, pIter);
   196540   fts5SegIterLoadNPos(p, pIter);
   196541 }
   196542 
   196543 static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
   196544   if( p->pIdxSelect==0 ){
   196545     Fts5Config *pConfig = p->pConfig;
   196546     fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
   196547           "SELECT pgno FROM '%q'.'%q_idx' WHERE "
   196548           "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
   196549           pConfig->zDb, pConfig->zName
   196550     ));
   196551   }
   196552   return p->pIdxSelect;
   196553 }
   196554 
   196555 /*
   196556 ** Initialize the object pIter to point to term pTerm/nTerm within segment
   196557 ** pSeg. If there is no such term in the index, the iterator is set to EOF.
   196558 **
   196559 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
   196560 ** an error has already occurred when this function is called, it is a no-op.
   196561 */
   196562 static void fts5SegIterSeekInit(
   196563   Fts5Index *p,                   /* FTS5 backend */
   196564   const u8 *pTerm, int nTerm,     /* Term to seek to */
   196565   int flags,                      /* Mask of FTS5INDEX_XXX flags */
   196566   Fts5StructureSegment *pSeg,     /* Description of segment */
   196567   Fts5SegIter *pIter              /* Object to populate */
   196568 ){
   196569   int iPg = 1;
   196570   int bGe = (flags & FTS5INDEX_QUERY_SCAN);
   196571   int bDlidx = 0;                 /* True if there is a doclist-index */
   196572   sqlite3_stmt *pIdxSelect = 0;
   196573 
   196574   assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
   196575   assert( pTerm && nTerm );
   196576   memset(pIter, 0, sizeof(*pIter));
   196577   pIter->pSeg = pSeg;
   196578 
   196579   /* This block sets stack variable iPg to the leaf page number that may
   196580   ** contain term (pTerm/nTerm), if it is present in the segment. */
   196581   pIdxSelect = fts5IdxSelectStmt(p);
   196582   if( p->rc ) return;
   196583   sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
   196584   sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
   196585   if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
   196586     i64 val = sqlite3_column_int(pIdxSelect, 0);
   196587     iPg = (int)(val>>1);
   196588     bDlidx = (val & 0x0001);
   196589   }
   196590   p->rc = sqlite3_reset(pIdxSelect);
   196591 
   196592   if( iPg<pSeg->pgnoFirst ){
   196593     iPg = pSeg->pgnoFirst;
   196594     bDlidx = 0;
   196595   }
   196596 
   196597   pIter->iLeafPgno = iPg - 1;
   196598   fts5SegIterNextPage(p, pIter);
   196599 
   196600   if( pIter->pLeaf ){
   196601     fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
   196602   }
   196603 
   196604   if( p->rc==SQLITE_OK && bGe==0 ){
   196605     pIter->flags |= FTS5_SEGITER_ONETERM;
   196606     if( pIter->pLeaf ){
   196607       if( flags & FTS5INDEX_QUERY_DESC ){
   196608         pIter->flags |= FTS5_SEGITER_REVERSE;
   196609       }
   196610       if( bDlidx ){
   196611         fts5SegIterLoadDlidx(p, pIter);
   196612       }
   196613       if( flags & FTS5INDEX_QUERY_DESC ){
   196614         fts5SegIterReverse(p, pIter);
   196615       }
   196616     }
   196617   }
   196618 
   196619   fts5SegIterSetNext(p, pIter);
   196620 
   196621   /* Either:
   196622   **
   196623   **   1) an error has occurred, or
   196624   **   2) the iterator points to EOF, or
   196625   **   3) the iterator points to an entry with term (pTerm/nTerm), or
   196626   **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
   196627   **      to an entry with a term greater than or equal to (pTerm/nTerm).
   196628   */
   196629   assert( p->rc!=SQLITE_OK                                          /* 1 */
   196630    || pIter->pLeaf==0                                               /* 2 */
   196631    || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
   196632    || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
   196633   );
   196634 }
   196635 
   196636 /*
   196637 ** Initialize the object pIter to point to term pTerm/nTerm within the
   196638 ** in-memory hash table. If there is no such term in the hash-table, the
   196639 ** iterator is set to EOF.
   196640 **
   196641 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
   196642 ** an error has already occurred when this function is called, it is a no-op.
   196643 */
   196644 static void fts5SegIterHashInit(
   196645   Fts5Index *p,                   /* FTS5 backend */
   196646   const u8 *pTerm, int nTerm,     /* Term to seek to */
   196647   int flags,                      /* Mask of FTS5INDEX_XXX flags */
   196648   Fts5SegIter *pIter              /* Object to populate */
   196649 ){
   196650   const u8 *pList = 0;
   196651   int nList = 0;
   196652   const u8 *z = 0;
   196653   int n = 0;
   196654 
   196655   assert( p->pHash );
   196656   assert( p->rc==SQLITE_OK );
   196657 
   196658   if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
   196659     p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
   196660     sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
   196661     n = (z ? (int)strlen((const char*)z) : 0);
   196662   }else{
   196663     pIter->flags |= FTS5_SEGITER_ONETERM;
   196664     sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
   196665     z = pTerm;
   196666     n = nTerm;
   196667   }
   196668 
   196669   if( pList ){
   196670     Fts5Data *pLeaf;
   196671     sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
   196672     pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
   196673     if( pLeaf==0 ) return;
   196674     pLeaf->p = (u8*)pList;
   196675     pLeaf->nn = pLeaf->szLeaf = nList;
   196676     pIter->pLeaf = pLeaf;
   196677     pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
   196678     pIter->iEndofDoclist = pLeaf->nn;
   196679 
   196680     if( flags & FTS5INDEX_QUERY_DESC ){
   196681       pIter->flags |= FTS5_SEGITER_REVERSE;
   196682       fts5SegIterReverseInitPage(p, pIter);
   196683     }else{
   196684       fts5SegIterLoadNPos(p, pIter);
   196685     }
   196686   }
   196687 
   196688   fts5SegIterSetNext(p, pIter);
   196689 }
   196690 
   196691 /*
   196692 ** Zero the iterator passed as the only argument.
   196693 */
   196694 static void fts5SegIterClear(Fts5SegIter *pIter){
   196695   fts5BufferFree(&pIter->term);
   196696   fts5DataRelease(pIter->pLeaf);
   196697   fts5DataRelease(pIter->pNextLeaf);
   196698   fts5DlidxIterFree(pIter->pDlidx);
   196699   sqlite3_free(pIter->aRowidOffset);
   196700   memset(pIter, 0, sizeof(Fts5SegIter));
   196701 }
   196702 
   196703 #ifdef SQLITE_DEBUG
   196704 
   196705 /*
   196706 ** This function is used as part of the big assert() procedure implemented by
   196707 ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
   196708 ** in *pRes is the correct result of comparing the current positions of the
   196709 ** two iterators.
   196710 */
   196711 static void fts5AssertComparisonResult(
   196712   Fts5Iter *pIter,
   196713   Fts5SegIter *p1,
   196714   Fts5SegIter *p2,
   196715   Fts5CResult *pRes
   196716 ){
   196717   int i1 = p1 - pIter->aSeg;
   196718   int i2 = p2 - pIter->aSeg;
   196719 
   196720   if( p1->pLeaf || p2->pLeaf ){
   196721     if( p1->pLeaf==0 ){
   196722       assert( pRes->iFirst==i2 );
   196723     }else if( p2->pLeaf==0 ){
   196724       assert( pRes->iFirst==i1 );
   196725     }else{
   196726       int nMin = MIN(p1->term.n, p2->term.n);
   196727       int res = memcmp(p1->term.p, p2->term.p, nMin);
   196728       if( res==0 ) res = p1->term.n - p2->term.n;
   196729 
   196730       if( res==0 ){
   196731         assert( pRes->bTermEq==1 );
   196732         assert( p1->iRowid!=p2->iRowid );
   196733         res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
   196734       }else{
   196735         assert( pRes->bTermEq==0 );
   196736       }
   196737 
   196738       if( res<0 ){
   196739         assert( pRes->iFirst==i1 );
   196740       }else{
   196741         assert( pRes->iFirst==i2 );
   196742       }
   196743     }
   196744   }
   196745 }
   196746 
   196747 /*
   196748 ** This function is a no-op unless SQLITE_DEBUG is defined when this module
   196749 ** is compiled. In that case, this function is essentially an assert()
   196750 ** statement used to verify that the contents of the pIter->aFirst[] array
   196751 ** are correct.
   196752 */
   196753 static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
   196754   if( p->rc==SQLITE_OK ){
   196755     Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
   196756     int i;
   196757 
   196758     assert( (pFirst->pLeaf==0)==pIter->base.bEof );
   196759 
   196760     /* Check that pIter->iSwitchRowid is set correctly. */
   196761     for(i=0; i<pIter->nSeg; i++){
   196762       Fts5SegIter *p1 = &pIter->aSeg[i];
   196763       assert( p1==pFirst
   196764            || p1->pLeaf==0
   196765            || fts5BufferCompare(&pFirst->term, &p1->term)
   196766            || p1->iRowid==pIter->iSwitchRowid
   196767            || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
   196768       );
   196769     }
   196770 
   196771     for(i=0; i<pIter->nSeg; i+=2){
   196772       Fts5SegIter *p1 = &pIter->aSeg[i];
   196773       Fts5SegIter *p2 = &pIter->aSeg[i+1];
   196774       Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
   196775       fts5AssertComparisonResult(pIter, p1, p2, pRes);
   196776     }
   196777 
   196778     for(i=1; i<(pIter->nSeg / 2); i+=2){
   196779       Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
   196780       Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
   196781       Fts5CResult *pRes = &pIter->aFirst[i];
   196782       fts5AssertComparisonResult(pIter, p1, p2, pRes);
   196783     }
   196784   }
   196785 }
   196786 #else
   196787 # define fts5AssertMultiIterSetup(x,y)
   196788 #endif
   196789 
   196790 /*
   196791 ** Do the comparison necessary to populate pIter->aFirst[iOut].
   196792 **
   196793 ** If the returned value is non-zero, then it is the index of an entry
   196794 ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
   196795 ** to a key that is a duplicate of another, higher priority,
   196796 ** segment-iterator in the pSeg->aSeg[] array.
   196797 */
   196798 static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
   196799   int i1;                         /* Index of left-hand Fts5SegIter */
   196800   int i2;                         /* Index of right-hand Fts5SegIter */
   196801   int iRes;
   196802   Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
   196803   Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
   196804   Fts5CResult *pRes = &pIter->aFirst[iOut];
   196805 
   196806   assert( iOut<pIter->nSeg && iOut>0 );
   196807   assert( pIter->bRev==0 || pIter->bRev==1 );
   196808 
   196809   if( iOut>=(pIter->nSeg/2) ){
   196810     i1 = (iOut - pIter->nSeg/2) * 2;
   196811     i2 = i1 + 1;
   196812   }else{
   196813     i1 = pIter->aFirst[iOut*2].iFirst;
   196814     i2 = pIter->aFirst[iOut*2+1].iFirst;
   196815   }
   196816   p1 = &pIter->aSeg[i1];
   196817   p2 = &pIter->aSeg[i2];
   196818 
   196819   pRes->bTermEq = 0;
   196820   if( p1->pLeaf==0 ){           /* If p1 is at EOF */
   196821     iRes = i2;
   196822   }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
   196823     iRes = i1;
   196824   }else{
   196825     int res = fts5BufferCompare(&p1->term, &p2->term);
   196826     if( res==0 ){
   196827       assert( i2>i1 );
   196828       assert( i2!=0 );
   196829       pRes->bTermEq = 1;
   196830       if( p1->iRowid==p2->iRowid ){
   196831         p1->bDel = p2->bDel;
   196832         return i2;
   196833       }
   196834       res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
   196835     }
   196836     assert( res!=0 );
   196837     if( res<0 ){
   196838       iRes = i1;
   196839     }else{
   196840       iRes = i2;
   196841     }
   196842   }
   196843 
   196844   pRes->iFirst = (u16)iRes;
   196845   return 0;
   196846 }
   196847 
   196848 /*
   196849 ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
   196850 ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
   196851 */
   196852 static void fts5SegIterGotoPage(
   196853   Fts5Index *p,                   /* FTS5 backend object */
   196854   Fts5SegIter *pIter,             /* Iterator to advance */
   196855   int iLeafPgno
   196856 ){
   196857   assert( iLeafPgno>pIter->iLeafPgno );
   196858 
   196859   if( iLeafPgno>pIter->pSeg->pgnoLast ){
   196860     p->rc = FTS5_CORRUPT;
   196861   }else{
   196862     fts5DataRelease(pIter->pNextLeaf);
   196863     pIter->pNextLeaf = 0;
   196864     pIter->iLeafPgno = iLeafPgno-1;
   196865     fts5SegIterNextPage(p, pIter);
   196866     assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
   196867 
   196868     if( p->rc==SQLITE_OK ){
   196869       int iOff;
   196870       u8 *a = pIter->pLeaf->p;
   196871       int n = pIter->pLeaf->szLeaf;
   196872 
   196873       iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
   196874       if( iOff<4 || iOff>=n ){
   196875         p->rc = FTS5_CORRUPT;
   196876       }else{
   196877         iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
   196878         pIter->iLeafOffset = iOff;
   196879         fts5SegIterLoadNPos(p, pIter);
   196880       }
   196881     }
   196882   }
   196883 }
   196884 
   196885 /*
   196886 ** Advance the iterator passed as the second argument until it is at or
   196887 ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
   196888 ** always advanced at least once.
   196889 */
   196890 static void fts5SegIterNextFrom(
   196891   Fts5Index *p,                   /* FTS5 backend object */
   196892   Fts5SegIter *pIter,             /* Iterator to advance */
   196893   i64 iMatch                      /* Advance iterator at least this far */
   196894 ){
   196895   int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
   196896   Fts5DlidxIter *pDlidx = pIter->pDlidx;
   196897   int iLeafPgno = pIter->iLeafPgno;
   196898   int bMove = 1;
   196899 
   196900   assert( pIter->flags & FTS5_SEGITER_ONETERM );
   196901   assert( pIter->pDlidx );
   196902   assert( pIter->pLeaf );
   196903 
   196904   if( bRev==0 ){
   196905     while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
   196906       iLeafPgno = fts5DlidxIterPgno(pDlidx);
   196907       fts5DlidxIterNext(p, pDlidx);
   196908     }
   196909     assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
   196910     if( iLeafPgno>pIter->iLeafPgno ){
   196911       fts5SegIterGotoPage(p, pIter, iLeafPgno);
   196912       bMove = 0;
   196913     }
   196914   }else{
   196915     assert( pIter->pNextLeaf==0 );
   196916     assert( iMatch<pIter->iRowid );
   196917     while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
   196918       fts5DlidxIterPrev(p, pDlidx);
   196919     }
   196920     iLeafPgno = fts5DlidxIterPgno(pDlidx);
   196921 
   196922     assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
   196923 
   196924     if( iLeafPgno<pIter->iLeafPgno ){
   196925       pIter->iLeafPgno = iLeafPgno+1;
   196926       fts5SegIterReverseNewPage(p, pIter);
   196927       bMove = 0;
   196928     }
   196929   }
   196930 
   196931   do{
   196932     if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
   196933     if( pIter->pLeaf==0 ) break;
   196934     if( bRev==0 && pIter->iRowid>=iMatch ) break;
   196935     if( bRev!=0 && pIter->iRowid<=iMatch ) break;
   196936     bMove = 1;
   196937   }while( p->rc==SQLITE_OK );
   196938 }
   196939 
   196940 
   196941 /*
   196942 ** Free the iterator object passed as the second argument.
   196943 */
   196944 static void fts5MultiIterFree(Fts5Iter *pIter){
   196945   if( pIter ){
   196946     int i;
   196947     for(i=0; i<pIter->nSeg; i++){
   196948       fts5SegIterClear(&pIter->aSeg[i]);
   196949     }
   196950     fts5StructureRelease(pIter->pStruct);
   196951     fts5BufferFree(&pIter->poslist);
   196952     sqlite3_free(pIter);
   196953   }
   196954 }
   196955 
   196956 static void fts5MultiIterAdvanced(
   196957   Fts5Index *p,                   /* FTS5 backend to iterate within */
   196958   Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
   196959   int iChanged,                   /* Index of sub-iterator just advanced */
   196960   int iMinset                     /* Minimum entry in aFirst[] to set */
   196961 ){
   196962   int i;
   196963   for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
   196964     int iEq;
   196965     if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
   196966       Fts5SegIter *pSeg = &pIter->aSeg[iEq];
   196967       assert( p->rc==SQLITE_OK );
   196968       pSeg->xNext(p, pSeg, 0);
   196969       i = pIter->nSeg + iEq;
   196970     }
   196971   }
   196972 }
   196973 
   196974 /*
   196975 ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
   196976 ** points to the same term though - just a different rowid. This function
   196977 ** attempts to update the contents of the pIter->aFirst[] accordingly.
   196978 ** If it does so successfully, 0 is returned. Otherwise 1.
   196979 **
   196980 ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
   196981 ** on the iterator instead. That function does the same as this one, except
   196982 ** that it deals with more complicated cases as well.
   196983 */
   196984 static int fts5MultiIterAdvanceRowid(
   196985   Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
   196986   int iChanged,                   /* Index of sub-iterator just advanced */
   196987   Fts5SegIter **ppFirst
   196988 ){
   196989   Fts5SegIter *pNew = &pIter->aSeg[iChanged];
   196990 
   196991   if( pNew->iRowid==pIter->iSwitchRowid
   196992    || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
   196993   ){
   196994     int i;
   196995     Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
   196996     pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
   196997     for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
   196998       Fts5CResult *pRes = &pIter->aFirst[i];
   196999 
   197000       assert( pNew->pLeaf );
   197001       assert( pRes->bTermEq==0 || pOther->pLeaf );
   197002 
   197003       if( pRes->bTermEq ){
   197004         if( pNew->iRowid==pOther->iRowid ){
   197005           return 1;
   197006         }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
   197007           pIter->iSwitchRowid = pOther->iRowid;
   197008           pNew = pOther;
   197009         }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
   197010           pIter->iSwitchRowid = pOther->iRowid;
   197011         }
   197012       }
   197013       pRes->iFirst = (u16)(pNew - pIter->aSeg);
   197014       if( i==1 ) break;
   197015 
   197016       pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
   197017     }
   197018   }
   197019 
   197020   *ppFirst = pNew;
   197021   return 0;
   197022 }
   197023 
   197024 /*
   197025 ** Set the pIter->bEof variable based on the state of the sub-iterators.
   197026 */
   197027 static void fts5MultiIterSetEof(Fts5Iter *pIter){
   197028   Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
   197029   pIter->base.bEof = pSeg->pLeaf==0;
   197030   pIter->iSwitchRowid = pSeg->iRowid;
   197031 }
   197032 
   197033 /*
   197034 ** Move the iterator to the next entry.
   197035 **
   197036 ** If an error occurs, an error code is left in Fts5Index.rc. It is not
   197037 ** considered an error if the iterator reaches EOF, or if it is already at
   197038 ** EOF when this function is called.
   197039 */
   197040 static void fts5MultiIterNext(
   197041   Fts5Index *p,
   197042   Fts5Iter *pIter,
   197043   int bFrom,                      /* True if argument iFrom is valid */
   197044   i64 iFrom                       /* Advance at least as far as this */
   197045 ){
   197046   int bUseFrom = bFrom;
   197047   assert( pIter->base.bEof==0 );
   197048   while( p->rc==SQLITE_OK ){
   197049     int iFirst = pIter->aFirst[1].iFirst;
   197050     int bNewTerm = 0;
   197051     Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
   197052     assert( p->rc==SQLITE_OK );
   197053     if( bUseFrom && pSeg->pDlidx ){
   197054       fts5SegIterNextFrom(p, pSeg, iFrom);
   197055     }else{
   197056       pSeg->xNext(p, pSeg, &bNewTerm);
   197057     }
   197058 
   197059     if( pSeg->pLeaf==0 || bNewTerm
   197060      || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
   197061     ){
   197062       fts5MultiIterAdvanced(p, pIter, iFirst, 1);
   197063       fts5MultiIterSetEof(pIter);
   197064       pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
   197065       if( pSeg->pLeaf==0 ) return;
   197066     }
   197067 
   197068     fts5AssertMultiIterSetup(p, pIter);
   197069     assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
   197070     if( pIter->bSkipEmpty==0 || pSeg->nPos ){
   197071       pIter->xSetOutputs(pIter, pSeg);
   197072       return;
   197073     }
   197074     bUseFrom = 0;
   197075   }
   197076 }
   197077 
   197078 static void fts5MultiIterNext2(
   197079   Fts5Index *p,
   197080   Fts5Iter *pIter,
   197081   int *pbNewTerm                  /* OUT: True if *might* be new term */
   197082 ){
   197083   assert( pIter->bSkipEmpty );
   197084   if( p->rc==SQLITE_OK ){
   197085     *pbNewTerm = 0;
   197086     do{
   197087       int iFirst = pIter->aFirst[1].iFirst;
   197088       Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
   197089       int bNewTerm = 0;
   197090 
   197091       assert( p->rc==SQLITE_OK );
   197092       pSeg->xNext(p, pSeg, &bNewTerm);
   197093       if( pSeg->pLeaf==0 || bNewTerm
   197094        || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
   197095       ){
   197096         fts5MultiIterAdvanced(p, pIter, iFirst, 1);
   197097         fts5MultiIterSetEof(pIter);
   197098         *pbNewTerm = 1;
   197099       }
   197100       fts5AssertMultiIterSetup(p, pIter);
   197101 
   197102     }while( fts5MultiIterIsEmpty(p, pIter) );
   197103   }
   197104 }
   197105 
   197106 static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
   197107   UNUSED_PARAM2(pUnused1, pUnused2);
   197108 }
   197109 
   197110 static Fts5Iter *fts5MultiIterAlloc(
   197111   Fts5Index *p,                   /* FTS5 backend to iterate within */
   197112   int nSeg
   197113 ){
   197114   Fts5Iter *pNew;
   197115   int nSlot;                      /* Power of two >= nSeg */
   197116 
   197117   for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
   197118   pNew = fts5IdxMalloc(p,
   197119       sizeof(Fts5Iter) +                  /* pNew */
   197120       sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
   197121       sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
   197122   );
   197123   if( pNew ){
   197124     pNew->nSeg = nSlot;
   197125     pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
   197126     pNew->pIndex = p;
   197127     pNew->xSetOutputs = fts5IterSetOutputs_Noop;
   197128   }
   197129   return pNew;
   197130 }
   197131 
   197132 static void fts5PoslistCallback(
   197133   Fts5Index *pUnused,
   197134   void *pContext,
   197135   const u8 *pChunk, int nChunk
   197136 ){
   197137   UNUSED_PARAM(pUnused);
   197138   assert_nc( nChunk>=0 );
   197139   if( nChunk>0 ){
   197140     fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
   197141   }
   197142 }
   197143 
   197144 typedef struct PoslistCallbackCtx PoslistCallbackCtx;
   197145 struct PoslistCallbackCtx {
   197146   Fts5Buffer *pBuf;               /* Append to this buffer */
   197147   Fts5Colset *pColset;            /* Restrict matches to this column */
   197148   int eState;                     /* See above */
   197149 };
   197150 
   197151 typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
   197152 struct PoslistOffsetsCtx {
   197153   Fts5Buffer *pBuf;               /* Append to this buffer */
   197154   Fts5Colset *pColset;            /* Restrict matches to this column */
   197155   int iRead;
   197156   int iWrite;
   197157 };
   197158 
   197159 /*
   197160 ** TODO: Make this more efficient!
   197161 */
   197162 static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
   197163   int i;
   197164   for(i=0; i<pColset->nCol; i++){
   197165     if( pColset->aiCol[i]==iCol ) return 1;
   197166   }
   197167   return 0;
   197168 }
   197169 
   197170 static void fts5PoslistOffsetsCallback(
   197171   Fts5Index *pUnused,
   197172   void *pContext,
   197173   const u8 *pChunk, int nChunk
   197174 ){
   197175   PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
   197176   UNUSED_PARAM(pUnused);
   197177   assert_nc( nChunk>=0 );
   197178   if( nChunk>0 ){
   197179     int i = 0;
   197180     while( i<nChunk ){
   197181       int iVal;
   197182       i += fts5GetVarint32(&pChunk[i], iVal);
   197183       iVal += pCtx->iRead - 2;
   197184       pCtx->iRead = iVal;
   197185       if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
   197186         fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
   197187         pCtx->iWrite = iVal;
   197188       }
   197189     }
   197190   }
   197191 }
   197192 
   197193 static void fts5PoslistFilterCallback(
   197194   Fts5Index *pUnused,
   197195   void *pContext,
   197196   const u8 *pChunk, int nChunk
   197197 ){
   197198   PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
   197199   UNUSED_PARAM(pUnused);
   197200   assert_nc( nChunk>=0 );
   197201   if( nChunk>0 ){
   197202     /* Search through to find the first varint with value 1. This is the
   197203     ** start of the next columns hits. */
   197204     int i = 0;
   197205     int iStart = 0;
   197206 
   197207     if( pCtx->eState==2 ){
   197208       int iCol;
   197209       fts5FastGetVarint32(pChunk, i, iCol);
   197210       if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
   197211         pCtx->eState = 1;
   197212         fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
   197213       }else{
   197214         pCtx->eState = 0;
   197215       }
   197216     }
   197217 
   197218     do {
   197219       while( i<nChunk && pChunk[i]!=0x01 ){
   197220         while( pChunk[i] & 0x80 ) i++;
   197221         i++;
   197222       }
   197223       if( pCtx->eState ){
   197224         fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
   197225       }
   197226       if( i<nChunk ){
   197227         int iCol;
   197228         iStart = i;
   197229         i++;
   197230         if( i>=nChunk ){
   197231           pCtx->eState = 2;
   197232         }else{
   197233           fts5FastGetVarint32(pChunk, i, iCol);
   197234           pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
   197235           if( pCtx->eState ){
   197236             fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
   197237             iStart = i;
   197238           }
   197239         }
   197240       }
   197241     }while( i<nChunk );
   197242   }
   197243 }
   197244 
   197245 static void fts5ChunkIterate(
   197246   Fts5Index *p,                   /* Index object */
   197247   Fts5SegIter *pSeg,              /* Poslist of this iterator */
   197248   void *pCtx,                     /* Context pointer for xChunk callback */
   197249   void (*xChunk)(Fts5Index*, void*, const u8*, int)
   197250 ){
   197251   int nRem = pSeg->nPos;          /* Number of bytes still to come */
   197252   Fts5Data *pData = 0;
   197253   u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
   197254   int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
   197255   int pgno = pSeg->iLeafPgno;
   197256   int pgnoSave = 0;
   197257 
   197258   /* This function does notmwork with detail=none databases. */
   197259   assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
   197260 
   197261   if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
   197262     pgnoSave = pgno+1;
   197263   }
   197264 
   197265   while( 1 ){
   197266     xChunk(p, pCtx, pChunk, nChunk);
   197267     nRem -= nChunk;
   197268     fts5DataRelease(pData);
   197269     if( nRem<=0 ){
   197270       break;
   197271     }else{
   197272       pgno++;
   197273       pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
   197274       if( pData==0 ) break;
   197275       pChunk = &pData->p[4];
   197276       nChunk = MIN(nRem, pData->szLeaf - 4);
   197277       if( pgno==pgnoSave ){
   197278         assert( pSeg->pNextLeaf==0 );
   197279         pSeg->pNextLeaf = pData;
   197280         pData = 0;
   197281       }
   197282     }
   197283   }
   197284 }
   197285 
   197286 /*
   197287 ** Iterator pIter currently points to a valid entry (not EOF). This
   197288 ** function appends the position list data for the current entry to
   197289 ** buffer pBuf. It does not make a copy of the position-list size
   197290 ** field.
   197291 */
   197292 static void fts5SegiterPoslist(
   197293   Fts5Index *p,
   197294   Fts5SegIter *pSeg,
   197295   Fts5Colset *pColset,
   197296   Fts5Buffer *pBuf
   197297 ){
   197298   if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
   197299     if( pColset==0 ){
   197300       fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
   197301     }else{
   197302       if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
   197303         PoslistCallbackCtx sCtx;
   197304         sCtx.pBuf = pBuf;
   197305         sCtx.pColset = pColset;
   197306         sCtx.eState = fts5IndexColsetTest(pColset, 0);
   197307         assert( sCtx.eState==0 || sCtx.eState==1 );
   197308         fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
   197309       }else{
   197310         PoslistOffsetsCtx sCtx;
   197311         memset(&sCtx, 0, sizeof(sCtx));
   197312         sCtx.pBuf = pBuf;
   197313         sCtx.pColset = pColset;
   197314         fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
   197315       }
   197316     }
   197317   }
   197318 }
   197319 
   197320 /*
   197321 ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
   197322 ** the position list contains entries for column iCol, then (*pa) is set
   197323 ** to point to the sub-position-list for that column and the number of
   197324 ** bytes in it returned. Or, if the argument position list does not
   197325 ** contain any entries for column iCol, return 0.
   197326 */
   197327 static int fts5IndexExtractCol(
   197328   const u8 **pa,                  /* IN/OUT: Pointer to poslist */
   197329   int n,                          /* IN: Size of poslist in bytes */
   197330   int iCol                        /* Column to extract from poslist */
   197331 ){
   197332   int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
   197333   const u8 *p = *pa;
   197334   const u8 *pEnd = &p[n];         /* One byte past end of position list */
   197335 
   197336   while( iCol>iCurrent ){
   197337     /* Advance pointer p until it points to pEnd or an 0x01 byte that is
   197338     ** not part of a varint. Note that it is not possible for a negative
   197339     ** or extremely large varint to occur within an uncorrupted position
   197340     ** list. So the last byte of each varint may be assumed to have a clear
   197341     ** 0x80 bit.  */
   197342     while( *p!=0x01 ){
   197343       while( *p++ & 0x80 );
   197344       if( p>=pEnd ) return 0;
   197345     }
   197346     *pa = p++;
   197347     iCurrent = *p++;
   197348     if( iCurrent & 0x80 ){
   197349       p--;
   197350       p += fts5GetVarint32(p, iCurrent);
   197351     }
   197352   }
   197353   if( iCol!=iCurrent ) return 0;
   197354 
   197355   /* Advance pointer p until it points to pEnd or an 0x01 byte that is
   197356   ** not part of a varint */
   197357   while( p<pEnd && *p!=0x01 ){
   197358     while( *p++ & 0x80 );
   197359   }
   197360 
   197361   return p - (*pa);
   197362 }
   197363 
   197364 static void fts5IndexExtractColset(
   197365   int *pRc,
   197366   Fts5Colset *pColset,            /* Colset to filter on */
   197367   const u8 *pPos, int nPos,       /* Position list */
   197368   Fts5Buffer *pBuf                /* Output buffer */
   197369 ){
   197370   if( *pRc==SQLITE_OK ){
   197371     int i;
   197372     fts5BufferZero(pBuf);
   197373     for(i=0; i<pColset->nCol; i++){
   197374       const u8 *pSub = pPos;
   197375       int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
   197376       if( nSub ){
   197377         fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
   197378       }
   197379     }
   197380   }
   197381 }
   197382 
   197383 /*
   197384 ** xSetOutputs callback used by detail=none tables.
   197385 */
   197386 static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
   197387   assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
   197388   pIter->base.iRowid = pSeg->iRowid;
   197389   pIter->base.nData = pSeg->nPos;
   197390 }
   197391 
   197392 /*
   197393 ** xSetOutputs callback used by detail=full and detail=col tables when no
   197394 ** column filters are specified.
   197395 */
   197396 static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
   197397   pIter->base.iRowid = pSeg->iRowid;
   197398   pIter->base.nData = pSeg->nPos;
   197399 
   197400   assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
   197401   assert( pIter->pColset==0 );
   197402 
   197403   if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
   197404     /* All data is stored on the current page. Populate the output
   197405     ** variables to point into the body of the page object. */
   197406     pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
   197407   }else{
   197408     /* The data is distributed over two or more pages. Copy it into the
   197409     ** Fts5Iter.poslist buffer and then set the output pointer to point
   197410     ** to this buffer.  */
   197411     fts5BufferZero(&pIter->poslist);
   197412     fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
   197413     pIter->base.pData = pIter->poslist.p;
   197414   }
   197415 }
   197416 
   197417 /*
   197418 ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
   197419 ** against no columns at all).
   197420 */
   197421 static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
   197422   UNUSED_PARAM(pSeg);
   197423   pIter->base.nData = 0;
   197424 }
   197425 
   197426 /*
   197427 ** xSetOutputs callback used by detail=col when there is a column filter
   197428 ** and there are 100 or more columns. Also called as a fallback from
   197429 ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
   197430 */
   197431 static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
   197432   fts5BufferZero(&pIter->poslist);
   197433   fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
   197434   pIter->base.iRowid = pSeg->iRowid;
   197435   pIter->base.pData = pIter->poslist.p;
   197436   pIter->base.nData = pIter->poslist.n;
   197437 }
   197438 
   197439 /*
   197440 ** xSetOutputs callback used when:
   197441 **
   197442 **   * detail=col,
   197443 **   * there is a column filter, and
   197444 **   * the table contains 100 or fewer columns.
   197445 **
   197446 ** The last point is to ensure all column numbers are stored as
   197447 ** single-byte varints.
   197448 */
   197449 static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
   197450 
   197451   assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
   197452   assert( pIter->pColset );
   197453 
   197454   if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
   197455     fts5IterSetOutputs_Col(pIter, pSeg);
   197456   }else{
   197457     u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
   197458     u8 *pEnd = (u8*)&a[pSeg->nPos];
   197459     int iPrev = 0;
   197460     int *aiCol = pIter->pColset->aiCol;
   197461     int *aiColEnd = &aiCol[pIter->pColset->nCol];
   197462 
   197463     u8 *aOut = pIter->poslist.p;
   197464     int iPrevOut = 0;
   197465 
   197466     pIter->base.iRowid = pSeg->iRowid;
   197467 
   197468     while( a<pEnd ){
   197469       iPrev += (int)a++[0] - 2;
   197470       while( *aiCol<iPrev ){
   197471         aiCol++;
   197472         if( aiCol==aiColEnd ) goto setoutputs_col_out;
   197473       }
   197474       if( *aiCol==iPrev ){
   197475         *aOut++ = (u8)((iPrev - iPrevOut) + 2);
   197476         iPrevOut = iPrev;
   197477       }
   197478     }
   197479 
   197480 setoutputs_col_out:
   197481     pIter->base.pData = pIter->poslist.p;
   197482     pIter->base.nData = aOut - pIter->poslist.p;
   197483   }
   197484 }
   197485 
   197486 /*
   197487 ** xSetOutputs callback used by detail=full when there is a column filter.
   197488 */
   197489 static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
   197490   Fts5Colset *pColset = pIter->pColset;
   197491   pIter->base.iRowid = pSeg->iRowid;
   197492 
   197493   assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
   197494   assert( pColset );
   197495 
   197496   if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
   197497     /* All data is stored on the current page. Populate the output
   197498     ** variables to point into the body of the page object. */
   197499     const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
   197500     if( pColset->nCol==1 ){
   197501       pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
   197502       pIter->base.pData = a;
   197503     }else{
   197504       int *pRc = &pIter->pIndex->rc;
   197505       fts5BufferZero(&pIter->poslist);
   197506       fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
   197507       pIter->base.pData = pIter->poslist.p;
   197508       pIter->base.nData = pIter->poslist.n;
   197509     }
   197510   }else{
   197511     /* The data is distributed over two or more pages. Copy it into the
   197512     ** Fts5Iter.poslist buffer and then set the output pointer to point
   197513     ** to this buffer.  */
   197514     fts5BufferZero(&pIter->poslist);
   197515     fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
   197516     pIter->base.pData = pIter->poslist.p;
   197517     pIter->base.nData = pIter->poslist.n;
   197518   }
   197519 }
   197520 
   197521 static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
   197522   if( *pRc==SQLITE_OK ){
   197523     Fts5Config *pConfig = pIter->pIndex->pConfig;
   197524     if( pConfig->eDetail==FTS5_DETAIL_NONE ){
   197525       pIter->xSetOutputs = fts5IterSetOutputs_None;
   197526     }
   197527 
   197528     else if( pIter->pColset==0 ){
   197529       pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
   197530     }
   197531 
   197532     else if( pIter->pColset->nCol==0 ){
   197533       pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
   197534     }
   197535 
   197536     else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
   197537       pIter->xSetOutputs = fts5IterSetOutputs_Full;
   197538     }
   197539 
   197540     else{
   197541       assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
   197542       if( pConfig->nCol<=100 ){
   197543         pIter->xSetOutputs = fts5IterSetOutputs_Col100;
   197544         sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
   197545       }else{
   197546         pIter->xSetOutputs = fts5IterSetOutputs_Col;
   197547       }
   197548     }
   197549   }
   197550 }
   197551 
   197552 
   197553 /*
   197554 ** Allocate a new Fts5Iter object.
   197555 **
   197556 ** The new object will be used to iterate through data in structure pStruct.
   197557 ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
   197558 ** is zero or greater, data from the first nSegment segments on level iLevel
   197559 ** is merged.
   197560 **
   197561 ** The iterator initially points to the first term/rowid entry in the
   197562 ** iterated data.
   197563 */
   197564 static void fts5MultiIterNew(
   197565   Fts5Index *p,                   /* FTS5 backend to iterate within */
   197566   Fts5Structure *pStruct,         /* Structure of specific index */
   197567   int flags,                      /* FTS5INDEX_QUERY_XXX flags */
   197568   Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
   197569   const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
   197570   int iLevel,                     /* Level to iterate (-1 for all) */
   197571   int nSegment,                   /* Number of segments to merge (iLevel>=0) */
   197572   Fts5Iter **ppOut                /* New object */
   197573 ){
   197574   int nSeg = 0;                   /* Number of segment-iters in use */
   197575   int iIter = 0;                  /* */
   197576   int iSeg;                       /* Used to iterate through segments */
   197577   Fts5StructureLevel *pLvl;
   197578   Fts5Iter *pNew;
   197579 
   197580   assert( (pTerm==0 && nTerm==0) || iLevel<0 );
   197581 
   197582   /* Allocate space for the new multi-seg-iterator. */
   197583   if( p->rc==SQLITE_OK ){
   197584     if( iLevel<0 ){
   197585       assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
   197586       nSeg = pStruct->nSegment;
   197587       nSeg += (p->pHash ? 1 : 0);
   197588     }else{
   197589       nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
   197590     }
   197591   }
   197592   *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
   197593   if( pNew==0 ) return;
   197594   pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
   197595   pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
   197596   pNew->pStruct = pStruct;
   197597   pNew->pColset = pColset;
   197598   fts5StructureRef(pStruct);
   197599   if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
   197600     fts5IterSetOutputCb(&p->rc, pNew);
   197601   }
   197602 
   197603   /* Initialize each of the component segment iterators. */
   197604   if( p->rc==SQLITE_OK ){
   197605     if( iLevel<0 ){
   197606       Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
   197607       if( p->pHash ){
   197608         /* Add a segment iterator for the current contents of the hash table. */
   197609         Fts5SegIter *pIter = &pNew->aSeg[iIter++];
   197610         fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
   197611       }
   197612       for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
   197613         for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
   197614           Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
   197615           Fts5SegIter *pIter = &pNew->aSeg[iIter++];
   197616           if( pTerm==0 ){
   197617             fts5SegIterInit(p, pSeg, pIter);
   197618           }else{
   197619             fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
   197620           }
   197621         }
   197622       }
   197623     }else{
   197624       pLvl = &pStruct->aLevel[iLevel];
   197625       for(iSeg=nSeg-1; iSeg>=0; iSeg--){
   197626         fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
   197627       }
   197628     }
   197629     assert( iIter==nSeg );
   197630   }
   197631 
   197632   /* If the above was successful, each component iterators now points
   197633   ** to the first entry in its segment. In this case initialize the
   197634   ** aFirst[] array. Or, if an error has occurred, free the iterator
   197635   ** object and set the output variable to NULL.  */
   197636   if( p->rc==SQLITE_OK ){
   197637     for(iIter=pNew->nSeg-1; iIter>0; iIter--){
   197638       int iEq;
   197639       if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
   197640         Fts5SegIter *pSeg = &pNew->aSeg[iEq];
   197641         if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
   197642         fts5MultiIterAdvanced(p, pNew, iEq, iIter);
   197643       }
   197644     }
   197645     fts5MultiIterSetEof(pNew);
   197646     fts5AssertMultiIterSetup(p, pNew);
   197647 
   197648     if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
   197649       fts5MultiIterNext(p, pNew, 0, 0);
   197650     }else if( pNew->base.bEof==0 ){
   197651       Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
   197652       pNew->xSetOutputs(pNew, pSeg);
   197653     }
   197654 
   197655   }else{
   197656     fts5MultiIterFree(pNew);
   197657     *ppOut = 0;
   197658   }
   197659 }
   197660 
   197661 /*
   197662 ** Create an Fts5Iter that iterates through the doclist provided
   197663 ** as the second argument.
   197664 */
   197665 static void fts5MultiIterNew2(
   197666   Fts5Index *p,                   /* FTS5 backend to iterate within */
   197667   Fts5Data *pData,                /* Doclist to iterate through */
   197668   int bDesc,                      /* True for descending rowid order */
   197669   Fts5Iter **ppOut                /* New object */
   197670 ){
   197671   Fts5Iter *pNew;
   197672   pNew = fts5MultiIterAlloc(p, 2);
   197673   if( pNew ){
   197674     Fts5SegIter *pIter = &pNew->aSeg[1];
   197675 
   197676     pIter->flags = FTS5_SEGITER_ONETERM;
   197677     if( pData->szLeaf>0 ){
   197678       pIter->pLeaf = pData;
   197679       pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
   197680       pIter->iEndofDoclist = pData->nn;
   197681       pNew->aFirst[1].iFirst = 1;
   197682       if( bDesc ){
   197683         pNew->bRev = 1;
   197684         pIter->flags |= FTS5_SEGITER_REVERSE;
   197685         fts5SegIterReverseInitPage(p, pIter);
   197686       }else{
   197687         fts5SegIterLoadNPos(p, pIter);
   197688       }
   197689       pData = 0;
   197690     }else{
   197691       pNew->base.bEof = 1;
   197692     }
   197693     fts5SegIterSetNext(p, pIter);
   197694 
   197695     *ppOut = pNew;
   197696   }
   197697 
   197698   fts5DataRelease(pData);
   197699 }
   197700 
   197701 /*
   197702 ** Return true if the iterator is at EOF or if an error has occurred.
   197703 ** False otherwise.
   197704 */
   197705 static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
   197706   assert( p->rc
   197707       || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
   197708   );
   197709   return (p->rc || pIter->base.bEof);
   197710 }
   197711 
   197712 /*
   197713 ** Return the rowid of the entry that the iterator currently points
   197714 ** to. If the iterator points to EOF when this function is called the
   197715 ** results are undefined.
   197716 */
   197717 static i64 fts5MultiIterRowid(Fts5Iter *pIter){
   197718   assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
   197719   return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
   197720 }
   197721 
   197722 /*
   197723 ** Move the iterator to the next entry at or following iMatch.
   197724 */
   197725 static void fts5MultiIterNextFrom(
   197726   Fts5Index *p,
   197727   Fts5Iter *pIter,
   197728   i64 iMatch
   197729 ){
   197730   while( 1 ){
   197731     i64 iRowid;
   197732     fts5MultiIterNext(p, pIter, 1, iMatch);
   197733     if( fts5MultiIterEof(p, pIter) ) break;
   197734     iRowid = fts5MultiIterRowid(pIter);
   197735     if( pIter->bRev==0 && iRowid>=iMatch ) break;
   197736     if( pIter->bRev!=0 && iRowid<=iMatch ) break;
   197737   }
   197738 }
   197739 
   197740 /*
   197741 ** Return a pointer to a buffer containing the term associated with the
   197742 ** entry that the iterator currently points to.
   197743 */
   197744 static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
   197745   Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
   197746   *pn = p->term.n;
   197747   return p->term.p;
   197748 }
   197749 
   197750 /*
   197751 ** Allocate a new segment-id for the structure pStruct. The new segment
   197752 ** id must be between 1 and 65335 inclusive, and must not be used by
   197753 ** any currently existing segment. If a free segment id cannot be found,
   197754 ** SQLITE_FULL is returned.
   197755 **
   197756 ** If an error has already occurred, this function is a no-op. 0 is
   197757 ** returned in this case.
   197758 */
   197759 static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
   197760   int iSegid = 0;
   197761 
   197762   if( p->rc==SQLITE_OK ){
   197763     if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
   197764       p->rc = SQLITE_FULL;
   197765     }else{
   197766       /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
   197767       ** array is 63 elements, or 252 bytes, in size.  */
   197768       u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
   197769       int iLvl, iSeg;
   197770       int i;
   197771       u32 mask;
   197772       memset(aUsed, 0, sizeof(aUsed));
   197773       for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
   197774         for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
   197775           int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
   197776           if( iId<=FTS5_MAX_SEGMENT ){
   197777             aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
   197778           }
   197779         }
   197780       }
   197781 
   197782       for(i=0; aUsed[i]==0xFFFFFFFF; i++);
   197783       mask = aUsed[i];
   197784       for(iSegid=0; mask & (1 << iSegid); iSegid++);
   197785       iSegid += 1 + i*32;
   197786 
   197787 #ifdef SQLITE_DEBUG
   197788       for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
   197789         for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
   197790           assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
   197791         }
   197792       }
   197793       assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
   197794 
   197795       {
   197796         sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
   197797         if( p->rc==SQLITE_OK ){
   197798           u8 aBlob[2] = {0xff, 0xff};
   197799           sqlite3_bind_int(pIdxSelect, 1, iSegid);
   197800           sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
   197801           assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
   197802           p->rc = sqlite3_reset(pIdxSelect);
   197803         }
   197804       }
   197805 #endif
   197806     }
   197807   }
   197808 
   197809   return iSegid;
   197810 }
   197811 
   197812 /*
   197813 ** Discard all data currently cached in the hash-tables.
   197814 */
   197815 static void fts5IndexDiscardData(Fts5Index *p){
   197816   assert( p->pHash || p->nPendingData==0 );
   197817   if( p->pHash ){
   197818     sqlite3Fts5HashClear(p->pHash);
   197819     p->nPendingData = 0;
   197820   }
   197821 }
   197822 
   197823 /*
   197824 ** Return the size of the prefix, in bytes, that buffer
   197825 ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
   197826 **
   197827 ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
   197828 ** than buffer (pOld/nOld).
   197829 */
   197830 static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
   197831   int i;
   197832   for(i=0; i<nOld; i++){
   197833     if( pOld[i]!=pNew[i] ) break;
   197834   }
   197835   return i;
   197836 }
   197837 
   197838 static void fts5WriteDlidxClear(
   197839   Fts5Index *p,
   197840   Fts5SegWriter *pWriter,
   197841   int bFlush                      /* If true, write dlidx to disk */
   197842 ){
   197843   int i;
   197844   assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
   197845   for(i=0; i<pWriter->nDlidx; i++){
   197846     Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
   197847     if( pDlidx->buf.n==0 ) break;
   197848     if( bFlush ){
   197849       assert( pDlidx->pgno!=0 );
   197850       fts5DataWrite(p,
   197851           FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
   197852           pDlidx->buf.p, pDlidx->buf.n
   197853       );
   197854     }
   197855     sqlite3Fts5BufferZero(&pDlidx->buf);
   197856     pDlidx->bPrevValid = 0;
   197857   }
   197858 }
   197859 
   197860 /*
   197861 ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
   197862 ** Any new array elements are zeroed before returning.
   197863 */
   197864 static int fts5WriteDlidxGrow(
   197865   Fts5Index *p,
   197866   Fts5SegWriter *pWriter,
   197867   int nLvl
   197868 ){
   197869   if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
   197870     Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
   197871         pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
   197872     );
   197873     if( aDlidx==0 ){
   197874       p->rc = SQLITE_NOMEM;
   197875     }else{
   197876       int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
   197877       memset(&aDlidx[pWriter->nDlidx], 0, nByte);
   197878       pWriter->aDlidx = aDlidx;
   197879       pWriter->nDlidx = nLvl;
   197880     }
   197881   }
   197882   return p->rc;
   197883 }
   197884 
   197885 /*
   197886 ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
   197887 ** enough, flush it to disk and return 1. Otherwise discard it and return
   197888 ** zero.
   197889 */
   197890 static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
   197891   int bFlag = 0;
   197892 
   197893   /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
   197894   ** to the database, also write the doclist-index to disk.  */
   197895   if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
   197896     bFlag = 1;
   197897   }
   197898   fts5WriteDlidxClear(p, pWriter, bFlag);
   197899   pWriter->nEmpty = 0;
   197900   return bFlag;
   197901 }
   197902 
   197903 /*
   197904 ** This function is called whenever processing of the doclist for the
   197905 ** last term on leaf page (pWriter->iBtPage) is completed.
   197906 **
   197907 ** The doclist-index for that term is currently stored in-memory within the
   197908 ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
   197909 ** writes it out to disk. Or, if it is too small to bother with, discards
   197910 ** it.
   197911 **
   197912 ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
   197913 */
   197914 static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
   197915   int bFlag;
   197916 
   197917   assert( pWriter->iBtPage || pWriter->nEmpty==0 );
   197918   if( pWriter->iBtPage==0 ) return;
   197919   bFlag = fts5WriteFlushDlidx(p, pWriter);
   197920 
   197921   if( p->rc==SQLITE_OK ){
   197922     const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
   197923     /* The following was already done in fts5WriteInit(): */
   197924     /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
   197925     sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
   197926     sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
   197927     sqlite3_step(p->pIdxWriter);
   197928     p->rc = sqlite3_reset(p->pIdxWriter);
   197929   }
   197930   pWriter->iBtPage = 0;
   197931 }
   197932 
   197933 /*
   197934 ** This is called once for each leaf page except the first that contains
   197935 ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
   197936 ** is larger than all terms written to earlier leaves, and equal to or
   197937 ** smaller than the first term on the new leaf.
   197938 **
   197939 ** If an error occurs, an error code is left in Fts5Index.rc. If an error
   197940 ** has already occurred when this function is called, it is a no-op.
   197941 */
   197942 static void fts5WriteBtreeTerm(
   197943   Fts5Index *p,                   /* FTS5 backend object */
   197944   Fts5SegWriter *pWriter,         /* Writer object */
   197945   int nTerm, const u8 *pTerm      /* First term on new page */
   197946 ){
   197947   fts5WriteFlushBtree(p, pWriter);
   197948   fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
   197949   pWriter->iBtPage = pWriter->writer.pgno;
   197950 }
   197951 
   197952 /*
   197953 ** This function is called when flushing a leaf page that contains no
   197954 ** terms at all to disk.
   197955 */
   197956 static void fts5WriteBtreeNoTerm(
   197957   Fts5Index *p,                   /* FTS5 backend object */
   197958   Fts5SegWriter *pWriter          /* Writer object */
   197959 ){
   197960   /* If there were no rowids on the leaf page either and the doclist-index
   197961   ** has already been started, append an 0x00 byte to it.  */
   197962   if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
   197963     Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
   197964     assert( pDlidx->bPrevValid );
   197965     sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
   197966   }
   197967 
   197968   /* Increment the "number of sequential leaves without a term" counter. */
   197969   pWriter->nEmpty++;
   197970 }
   197971 
   197972 static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
   197973   i64 iRowid;
   197974   int iOff;
   197975 
   197976   iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
   197977   fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
   197978   return iRowid;
   197979 }
   197980 
   197981 /*
   197982 ** Rowid iRowid has just been appended to the current leaf page. It is the
   197983 ** first on the page. This function appends an appropriate entry to the current
   197984 ** doclist-index.
   197985 */
   197986 static void fts5WriteDlidxAppend(
   197987   Fts5Index *p,
   197988   Fts5SegWriter *pWriter,
   197989   i64 iRowid
   197990 ){
   197991   int i;
   197992   int bDone = 0;
   197993 
   197994   for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
   197995     i64 iVal;
   197996     Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
   197997 
   197998     if( pDlidx->buf.n>=p->pConfig->pgsz ){
   197999       /* The current doclist-index page is full. Write it to disk and push
   198000       ** a copy of iRowid (which will become the first rowid on the next
   198001       ** doclist-index leaf page) up into the next level of the b-tree
   198002       ** hierarchy. If the node being flushed is currently the root node,
   198003       ** also push its first rowid upwards. */
   198004       pDlidx->buf.p[0] = 0x01;    /* Not the root node */
   198005       fts5DataWrite(p,
   198006           FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
   198007           pDlidx->buf.p, pDlidx->buf.n
   198008       );
   198009       fts5WriteDlidxGrow(p, pWriter, i+2);
   198010       pDlidx = &pWriter->aDlidx[i];
   198011       if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
   198012         i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
   198013 
   198014         /* This was the root node. Push its first rowid up to the new root. */
   198015         pDlidx[1].pgno = pDlidx->pgno;
   198016         sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
   198017         sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
   198018         sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
   198019         pDlidx[1].bPrevValid = 1;
   198020         pDlidx[1].iPrev = iFirst;
   198021       }
   198022 
   198023       sqlite3Fts5BufferZero(&pDlidx->buf);
   198024       pDlidx->bPrevValid = 0;
   198025       pDlidx->pgno++;
   198026     }else{
   198027       bDone = 1;
   198028     }
   198029 
   198030     if( pDlidx->bPrevValid ){
   198031       iVal = iRowid - pDlidx->iPrev;
   198032     }else{
   198033       i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
   198034       assert( pDlidx->buf.n==0 );
   198035       sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
   198036       sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
   198037       iVal = iRowid;
   198038     }
   198039 
   198040     sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
   198041     pDlidx->bPrevValid = 1;
   198042     pDlidx->iPrev = iRowid;
   198043   }
   198044 }
   198045 
   198046 static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
   198047   static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
   198048   Fts5PageWriter *pPage = &pWriter->writer;
   198049   i64 iRowid;
   198050 
   198051   assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
   198052 
   198053   /* Set the szLeaf header field. */
   198054   assert( 0==fts5GetU16(&pPage->buf.p[2]) );
   198055   fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
   198056 
   198057   if( pWriter->bFirstTermInPage ){
   198058     /* No term was written to this page. */
   198059     assert( pPage->pgidx.n==0 );
   198060     fts5WriteBtreeNoTerm(p, pWriter);
   198061   }else{
   198062     /* Append the pgidx to the page buffer. Set the szLeaf header field. */
   198063     fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
   198064   }
   198065 
   198066   /* Write the page out to disk */
   198067   iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
   198068   fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
   198069 
   198070   /* Initialize the next page. */
   198071   fts5BufferZero(&pPage->buf);
   198072   fts5BufferZero(&pPage->pgidx);
   198073   fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
   198074   pPage->iPrevPgidx = 0;
   198075   pPage->pgno++;
   198076 
   198077   /* Increase the leaves written counter */
   198078   pWriter->nLeafWritten++;
   198079 
   198080   /* The new leaf holds no terms or rowids */
   198081   pWriter->bFirstTermInPage = 1;
   198082   pWriter->bFirstRowidInPage = 1;
   198083 }
   198084 
   198085 /*
   198086 ** Append term pTerm/nTerm to the segment being written by the writer passed
   198087 ** as the second argument.
   198088 **
   198089 ** If an error occurs, set the Fts5Index.rc error code. If an error has
   198090 ** already occurred, this function is a no-op.
   198091 */
   198092 static void fts5WriteAppendTerm(
   198093   Fts5Index *p,
   198094   Fts5SegWriter *pWriter,
   198095   int nTerm, const u8 *pTerm
   198096 ){
   198097   int nPrefix;                    /* Bytes of prefix compression for term */
   198098   Fts5PageWriter *pPage = &pWriter->writer;
   198099   Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
   198100 
   198101   assert( p->rc==SQLITE_OK );
   198102   assert( pPage->buf.n>=4 );
   198103   assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
   198104 
   198105   /* If the current leaf page is full, flush it to disk. */
   198106   if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
   198107     if( pPage->buf.n>4 ){
   198108       fts5WriteFlushLeaf(p, pWriter);
   198109     }
   198110     fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
   198111   }
   198112 
   198113   /* TODO1: Updating pgidx here. */
   198114   pPgidx->n += sqlite3Fts5PutVarint(
   198115       &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
   198116   );
   198117   pPage->iPrevPgidx = pPage->buf.n;
   198118 #if 0
   198119   fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
   198120   pPgidx->n += 2;
   198121 #endif
   198122 
   198123   if( pWriter->bFirstTermInPage ){
   198124     nPrefix = 0;
   198125     if( pPage->pgno!=1 ){
   198126       /* This is the first term on a leaf that is not the leftmost leaf in
   198127       ** the segment b-tree. In this case it is necessary to add a term to
   198128       ** the b-tree hierarchy that is (a) larger than the largest term
   198129       ** already written to the segment and (b) smaller than or equal to
   198130       ** this term. In other words, a prefix of (pTerm/nTerm) that is one
   198131       ** byte longer than the longest prefix (pTerm/nTerm) shares with the
   198132       ** previous term.
   198133       **
   198134       ** Usually, the previous term is available in pPage->term. The exception
   198135       ** is if this is the first term written in an incremental-merge step.
   198136       ** In this case the previous term is not available, so just write a
   198137       ** copy of (pTerm/nTerm) into the parent node. This is slightly
   198138       ** inefficient, but still correct.  */
   198139       int n = nTerm;
   198140       if( pPage->term.n ){
   198141         n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
   198142       }
   198143       fts5WriteBtreeTerm(p, pWriter, n, pTerm);
   198144       pPage = &pWriter->writer;
   198145     }
   198146   }else{
   198147     nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
   198148     fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
   198149   }
   198150 
   198151   /* Append the number of bytes of new data, then the term data itself
   198152   ** to the page. */
   198153   fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
   198154   fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
   198155 
   198156   /* Update the Fts5PageWriter.term field. */
   198157   fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
   198158   pWriter->bFirstTermInPage = 0;
   198159 
   198160   pWriter->bFirstRowidInPage = 0;
   198161   pWriter->bFirstRowidInDoclist = 1;
   198162 
   198163   assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
   198164   pWriter->aDlidx[0].pgno = pPage->pgno;
   198165 }
   198166 
   198167 /*
   198168 ** Append a rowid and position-list size field to the writers output.
   198169 */
   198170 static void fts5WriteAppendRowid(
   198171   Fts5Index *p,
   198172   Fts5SegWriter *pWriter,
   198173   i64 iRowid
   198174 ){
   198175   if( p->rc==SQLITE_OK ){
   198176     Fts5PageWriter *pPage = &pWriter->writer;
   198177 
   198178     if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
   198179       fts5WriteFlushLeaf(p, pWriter);
   198180     }
   198181 
   198182     /* If this is to be the first rowid written to the page, set the
   198183     ** rowid-pointer in the page-header. Also append a value to the dlidx
   198184     ** buffer, in case a doclist-index is required.  */
   198185     if( pWriter->bFirstRowidInPage ){
   198186       fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
   198187       fts5WriteDlidxAppend(p, pWriter, iRowid);
   198188     }
   198189 
   198190     /* Write the rowid. */
   198191     if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
   198192       fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
   198193     }else{
   198194       assert( p->rc || iRowid>pWriter->iPrevRowid );
   198195       fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
   198196     }
   198197     pWriter->iPrevRowid = iRowid;
   198198     pWriter->bFirstRowidInDoclist = 0;
   198199     pWriter->bFirstRowidInPage = 0;
   198200   }
   198201 }
   198202 
   198203 static void fts5WriteAppendPoslistData(
   198204   Fts5Index *p,
   198205   Fts5SegWriter *pWriter,
   198206   const u8 *aData,
   198207   int nData
   198208 ){
   198209   Fts5PageWriter *pPage = &pWriter->writer;
   198210   const u8 *a = aData;
   198211   int n = nData;
   198212 
   198213   assert( p->pConfig->pgsz>0 );
   198214   while( p->rc==SQLITE_OK
   198215      && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
   198216   ){
   198217     int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
   198218     int nCopy = 0;
   198219     while( nCopy<nReq ){
   198220       i64 dummy;
   198221       nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
   198222     }
   198223     fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
   198224     a += nCopy;
   198225     n -= nCopy;
   198226     fts5WriteFlushLeaf(p, pWriter);
   198227   }
   198228   if( n>0 ){
   198229     fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
   198230   }
   198231 }
   198232 
   198233 /*
   198234 ** Flush any data cached by the writer object to the database. Free any
   198235 ** allocations associated with the writer.
   198236 */
   198237 static void fts5WriteFinish(
   198238   Fts5Index *p,
   198239   Fts5SegWriter *pWriter,         /* Writer object */
   198240   int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
   198241 ){
   198242   int i;
   198243   Fts5PageWriter *pLeaf = &pWriter->writer;
   198244   if( p->rc==SQLITE_OK ){
   198245     assert( pLeaf->pgno>=1 );
   198246     if( pLeaf->buf.n>4 ){
   198247       fts5WriteFlushLeaf(p, pWriter);
   198248     }
   198249     *pnLeaf = pLeaf->pgno-1;
   198250     if( pLeaf->pgno>1 ){
   198251       fts5WriteFlushBtree(p, pWriter);
   198252     }
   198253   }
   198254   fts5BufferFree(&pLeaf->term);
   198255   fts5BufferFree(&pLeaf->buf);
   198256   fts5BufferFree(&pLeaf->pgidx);
   198257   fts5BufferFree(&pWriter->btterm);
   198258 
   198259   for(i=0; i<pWriter->nDlidx; i++){
   198260     sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
   198261   }
   198262   sqlite3_free(pWriter->aDlidx);
   198263 }
   198264 
   198265 static void fts5WriteInit(
   198266   Fts5Index *p,
   198267   Fts5SegWriter *pWriter,
   198268   int iSegid
   198269 ){
   198270   const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
   198271 
   198272   memset(pWriter, 0, sizeof(Fts5SegWriter));
   198273   pWriter->iSegid = iSegid;
   198274 
   198275   fts5WriteDlidxGrow(p, pWriter, 1);
   198276   pWriter->writer.pgno = 1;
   198277   pWriter->bFirstTermInPage = 1;
   198278   pWriter->iBtPage = 1;
   198279 
   198280   assert( pWriter->writer.buf.n==0 );
   198281   assert( pWriter->writer.pgidx.n==0 );
   198282 
   198283   /* Grow the two buffers to pgsz + padding bytes in size. */
   198284   sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
   198285   sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
   198286 
   198287   if( p->pIdxWriter==0 ){
   198288     Fts5Config *pConfig = p->pConfig;
   198289     fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
   198290           "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
   198291           pConfig->zDb, pConfig->zName
   198292     ));
   198293   }
   198294 
   198295   if( p->rc==SQLITE_OK ){
   198296     /* Initialize the 4-byte leaf-page header to 0x00. */
   198297     memset(pWriter->writer.buf.p, 0, 4);
   198298     pWriter->writer.buf.n = 4;
   198299 
   198300     /* Bind the current output segment id to the index-writer. This is an
   198301     ** optimization over binding the same value over and over as rows are
   198302     ** inserted into %_idx by the current writer.  */
   198303     sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
   198304   }
   198305 }
   198306 
   198307 /*
   198308 ** Iterator pIter was used to iterate through the input segments of on an
   198309 ** incremental merge operation. This function is called if the incremental
   198310 ** merge step has finished but the input has not been completely exhausted.
   198311 */
   198312 static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
   198313   int i;
   198314   Fts5Buffer buf;
   198315   memset(&buf, 0, sizeof(Fts5Buffer));
   198316   for(i=0; i<pIter->nSeg; i++){
   198317     Fts5SegIter *pSeg = &pIter->aSeg[i];
   198318     if( pSeg->pSeg==0 ){
   198319       /* no-op */
   198320     }else if( pSeg->pLeaf==0 ){
   198321       /* All keys from this input segment have been transfered to the output.
   198322       ** Set both the first and last page-numbers to 0 to indicate that the
   198323       ** segment is now empty. */
   198324       pSeg->pSeg->pgnoLast = 0;
   198325       pSeg->pSeg->pgnoFirst = 0;
   198326     }else{
   198327       int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
   198328       i64 iLeafRowid;
   198329       Fts5Data *pData;
   198330       int iId = pSeg->pSeg->iSegid;
   198331       u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
   198332 
   198333       iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
   198334       pData = fts5DataRead(p, iLeafRowid);
   198335       if( pData ){
   198336         fts5BufferZero(&buf);
   198337         fts5BufferGrow(&p->rc, &buf, pData->nn);
   198338         fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
   198339         fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
   198340         fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
   198341         fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
   198342         if( p->rc==SQLITE_OK ){
   198343           /* Set the szLeaf field */
   198344           fts5PutU16(&buf.p[2], (u16)buf.n);
   198345         }
   198346 
   198347         /* Set up the new page-index array */
   198348         fts5BufferAppendVarint(&p->rc, &buf, 4);
   198349         if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
   198350          && pSeg->iEndofDoclist<pData->szLeaf
   198351         ){
   198352           int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
   198353           fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
   198354           fts5BufferAppendBlob(&p->rc, &buf,
   198355               pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
   198356           );
   198357         }
   198358 
   198359         fts5DataRelease(pData);
   198360         pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
   198361         fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
   198362         fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
   198363       }
   198364     }
   198365   }
   198366   fts5BufferFree(&buf);
   198367 }
   198368 
   198369 static void fts5MergeChunkCallback(
   198370   Fts5Index *p,
   198371   void *pCtx,
   198372   const u8 *pChunk, int nChunk
   198373 ){
   198374   Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
   198375   fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
   198376 }
   198377 
   198378 /*
   198379 **
   198380 */
   198381 static void fts5IndexMergeLevel(
   198382   Fts5Index *p,                   /* FTS5 backend object */
   198383   Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
   198384   int iLvl,                       /* Level to read input from */
   198385   int *pnRem                      /* Write up to this many output leaves */
   198386 ){
   198387   Fts5Structure *pStruct = *ppStruct;
   198388   Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
   198389   Fts5StructureLevel *pLvlOut;
   198390   Fts5Iter *pIter = 0;       /* Iterator to read input data */
   198391   int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
   198392   int nInput;                     /* Number of input segments */
   198393   Fts5SegWriter writer;           /* Writer object */
   198394   Fts5StructureSegment *pSeg;     /* Output segment */
   198395   Fts5Buffer term;
   198396   int bOldest;                    /* True if the output segment is the oldest */
   198397   int eDetail = p->pConfig->eDetail;
   198398   const int flags = FTS5INDEX_QUERY_NOOUTPUT;
   198399   int bTermWritten = 0;           /* True if current term already output */
   198400 
   198401   assert( iLvl<pStruct->nLevel );
   198402   assert( pLvl->nMerge<=pLvl->nSeg );
   198403 
   198404   memset(&writer, 0, sizeof(Fts5SegWriter));
   198405   memset(&term, 0, sizeof(Fts5Buffer));
   198406   if( pLvl->nMerge ){
   198407     pLvlOut = &pStruct->aLevel[iLvl+1];
   198408     assert( pLvlOut->nSeg>0 );
   198409     nInput = pLvl->nMerge;
   198410     pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
   198411 
   198412     fts5WriteInit(p, &writer, pSeg->iSegid);
   198413     writer.writer.pgno = pSeg->pgnoLast+1;
   198414     writer.iBtPage = 0;
   198415   }else{
   198416     int iSegid = fts5AllocateSegid(p, pStruct);
   198417 
   198418     /* Extend the Fts5Structure object as required to ensure the output
   198419     ** segment exists. */
   198420     if( iLvl==pStruct->nLevel-1 ){
   198421       fts5StructureAddLevel(&p->rc, ppStruct);
   198422       pStruct = *ppStruct;
   198423     }
   198424     fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
   198425     if( p->rc ) return;
   198426     pLvl = &pStruct->aLevel[iLvl];
   198427     pLvlOut = &pStruct->aLevel[iLvl+1];
   198428 
   198429     fts5WriteInit(p, &writer, iSegid);
   198430 
   198431     /* Add the new segment to the output level */
   198432     pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
   198433     pLvlOut->nSeg++;
   198434     pSeg->pgnoFirst = 1;
   198435     pSeg->iSegid = iSegid;
   198436     pStruct->nSegment++;
   198437 
   198438     /* Read input from all segments in the input level */
   198439     nInput = pLvl->nSeg;
   198440   }
   198441   bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
   198442 
   198443   assert( iLvl>=0 );
   198444   for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
   198445       fts5MultiIterEof(p, pIter)==0;
   198446       fts5MultiIterNext(p, pIter, 0, 0)
   198447   ){
   198448     Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
   198449     int nPos;                     /* position-list size field value */
   198450     int nTerm;
   198451     const u8 *pTerm;
   198452 
   198453     pTerm = fts5MultiIterTerm(pIter, &nTerm);
   198454     if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
   198455       if( pnRem && writer.nLeafWritten>nRem ){
   198456         break;
   198457       }
   198458       fts5BufferSet(&p->rc, &term, nTerm, pTerm);
   198459       bTermWritten =0;
   198460     }
   198461 
   198462     /* Check for key annihilation. */
   198463     if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
   198464 
   198465     if( p->rc==SQLITE_OK && bTermWritten==0 ){
   198466       /* This is a new term. Append a term to the output segment. */
   198467       fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
   198468       bTermWritten = 1;
   198469     }
   198470 
   198471     /* Append the rowid to the output */
   198472     /* WRITEPOSLISTSIZE */
   198473     fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
   198474 
   198475     if( eDetail==FTS5_DETAIL_NONE ){
   198476       if( pSegIter->bDel ){
   198477         fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
   198478         if( pSegIter->nPos>0 ){
   198479           fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
   198480         }
   198481       }
   198482     }else{
   198483       /* Append the position-list data to the output */
   198484       nPos = pSegIter->nPos*2 + pSegIter->bDel;
   198485       fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
   198486       fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
   198487     }
   198488   }
   198489 
   198490   /* Flush the last leaf page to disk. Set the output segment b-tree height
   198491   ** and last leaf page number at the same time.  */
   198492   fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
   198493 
   198494   if( fts5MultiIterEof(p, pIter) ){
   198495     int i;
   198496 
   198497     /* Remove the redundant segments from the %_data table */
   198498     for(i=0; i<nInput; i++){
   198499       fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
   198500     }
   198501 
   198502     /* Remove the redundant segments from the input level */
   198503     if( pLvl->nSeg!=nInput ){
   198504       int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
   198505       memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
   198506     }
   198507     pStruct->nSegment -= nInput;
   198508     pLvl->nSeg -= nInput;
   198509     pLvl->nMerge = 0;
   198510     if( pSeg->pgnoLast==0 ){
   198511       pLvlOut->nSeg--;
   198512       pStruct->nSegment--;
   198513     }
   198514   }else{
   198515     assert( pSeg->pgnoLast>0 );
   198516     fts5TrimSegments(p, pIter);
   198517     pLvl->nMerge = nInput;
   198518   }
   198519 
   198520   fts5MultiIterFree(pIter);
   198521   fts5BufferFree(&term);
   198522   if( pnRem ) *pnRem -= writer.nLeafWritten;
   198523 }
   198524 
   198525 /*
   198526 ** Do up to nPg pages of automerge work on the index.
   198527 **
   198528 ** Return true if any changes were actually made, or false otherwise.
   198529 */
   198530 static int fts5IndexMerge(
   198531   Fts5Index *p,                   /* FTS5 backend object */
   198532   Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
   198533   int nPg,                        /* Pages of work to do */
   198534   int nMin                        /* Minimum number of segments to merge */
   198535 ){
   198536   int nRem = nPg;
   198537   int bRet = 0;
   198538   Fts5Structure *pStruct = *ppStruct;
   198539   while( nRem>0 && p->rc==SQLITE_OK ){
   198540     int iLvl;                   /* To iterate through levels */
   198541     int iBestLvl = 0;           /* Level offering the most input segments */
   198542     int nBest = 0;              /* Number of input segments on best level */
   198543 
   198544     /* Set iBestLvl to the level to read input segments from. */
   198545     assert( pStruct->nLevel>0 );
   198546     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
   198547       Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
   198548       if( pLvl->nMerge ){
   198549         if( pLvl->nMerge>nBest ){
   198550           iBestLvl = iLvl;
   198551           nBest = pLvl->nMerge;
   198552         }
   198553         break;
   198554       }
   198555       if( pLvl->nSeg>nBest ){
   198556         nBest = pLvl->nSeg;
   198557         iBestLvl = iLvl;
   198558       }
   198559     }
   198560 
   198561     /* If nBest is still 0, then the index must be empty. */
   198562 #ifdef SQLITE_DEBUG
   198563     for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
   198564       assert( pStruct->aLevel[iLvl].nSeg==0 );
   198565     }
   198566 #endif
   198567 
   198568     if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
   198569       break;
   198570     }
   198571     bRet = 1;
   198572     fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
   198573     if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
   198574       fts5StructurePromote(p, iBestLvl+1, pStruct);
   198575     }
   198576   }
   198577   *ppStruct = pStruct;
   198578   return bRet;
   198579 }
   198580 
   198581 /*
   198582 ** A total of nLeaf leaf pages of data has just been flushed to a level-0
   198583 ** segment. This function updates the write-counter accordingly and, if
   198584 ** necessary, performs incremental merge work.
   198585 **
   198586 ** If an error occurs, set the Fts5Index.rc error code. If an error has
   198587 ** already occurred, this function is a no-op.
   198588 */
   198589 static void fts5IndexAutomerge(
   198590   Fts5Index *p,                   /* FTS5 backend object */
   198591   Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
   198592   int nLeaf                       /* Number of output leaves just written */
   198593 ){
   198594   if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
   198595     Fts5Structure *pStruct = *ppStruct;
   198596     u64 nWrite;                   /* Initial value of write-counter */
   198597     int nWork;                    /* Number of work-quanta to perform */
   198598     int nRem;                     /* Number of leaf pages left to write */
   198599 
   198600     /* Update the write-counter. While doing so, set nWork. */
   198601     nWrite = pStruct->nWriteCounter;
   198602     nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
   198603     pStruct->nWriteCounter += nLeaf;
   198604     nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
   198605 
   198606     fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
   198607   }
   198608 }
   198609 
   198610 static void fts5IndexCrisismerge(
   198611   Fts5Index *p,                   /* FTS5 backend object */
   198612   Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
   198613 ){
   198614   const int nCrisis = p->pConfig->nCrisisMerge;
   198615   Fts5Structure *pStruct = *ppStruct;
   198616   int iLvl = 0;
   198617 
   198618   assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
   198619   while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
   198620     fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
   198621     assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
   198622     fts5StructurePromote(p, iLvl+1, pStruct);
   198623     iLvl++;
   198624   }
   198625   *ppStruct = pStruct;
   198626 }
   198627 
   198628 static int fts5IndexReturn(Fts5Index *p){
   198629   int rc = p->rc;
   198630   p->rc = SQLITE_OK;
   198631   return rc;
   198632 }
   198633 
   198634 typedef struct Fts5FlushCtx Fts5FlushCtx;
   198635 struct Fts5FlushCtx {
   198636   Fts5Index *pIdx;
   198637   Fts5SegWriter writer;
   198638 };
   198639 
   198640 /*
   198641 ** Buffer aBuf[] contains a list of varints, all small enough to fit
   198642 ** in a 32-bit integer. Return the size of the largest prefix of this
   198643 ** list nMax bytes or less in size.
   198644 */
   198645 static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
   198646   int ret;
   198647   u32 dummy;
   198648   ret = fts5GetVarint32(aBuf, dummy);
   198649   if( ret<nMax ){
   198650     while( 1 ){
   198651       int i = fts5GetVarint32(&aBuf[ret], dummy);
   198652       if( (ret + i) > nMax ) break;
   198653       ret += i;
   198654     }
   198655   }
   198656   return ret;
   198657 }
   198658 
   198659 /*
   198660 ** Flush the contents of in-memory hash table iHash to a new level-0
   198661 ** segment on disk. Also update the corresponding structure record.
   198662 **
   198663 ** If an error occurs, set the Fts5Index.rc error code. If an error has
   198664 ** already occurred, this function is a no-op.
   198665 */
   198666 static void fts5FlushOneHash(Fts5Index *p){
   198667   Fts5Hash *pHash = p->pHash;
   198668   Fts5Structure *pStruct;
   198669   int iSegid;
   198670   int pgnoLast = 0;                 /* Last leaf page number in segment */
   198671 
   198672   /* Obtain a reference to the index structure and allocate a new segment-id
   198673   ** for the new level-0 segment.  */
   198674   pStruct = fts5StructureRead(p);
   198675   iSegid = fts5AllocateSegid(p, pStruct);
   198676   fts5StructureInvalidate(p);
   198677 
   198678   if( iSegid ){
   198679     const int pgsz = p->pConfig->pgsz;
   198680     int eDetail = p->pConfig->eDetail;
   198681     Fts5StructureSegment *pSeg;   /* New segment within pStruct */
   198682     Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
   198683     Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
   198684 
   198685     Fts5SegWriter writer;
   198686     fts5WriteInit(p, &writer, iSegid);
   198687 
   198688     pBuf = &writer.writer.buf;
   198689     pPgidx = &writer.writer.pgidx;
   198690 
   198691     /* fts5WriteInit() should have initialized the buffers to (most likely)
   198692     ** the maximum space required. */
   198693     assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
   198694     assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
   198695 
   198696     /* Begin scanning through hash table entries. This loop runs once for each
   198697     ** term/doclist currently stored within the hash table. */
   198698     if( p->rc==SQLITE_OK ){
   198699       p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
   198700     }
   198701     while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
   198702       const char *zTerm;          /* Buffer containing term */
   198703       const u8 *pDoclist;         /* Pointer to doclist for this term */
   198704       int nDoclist;               /* Size of doclist in bytes */
   198705 
   198706       /* Write the term for this entry to disk. */
   198707       sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
   198708       fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
   198709 
   198710       assert( writer.bFirstRowidInPage==0 );
   198711       if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
   198712         /* The entire doclist will fit on the current leaf. */
   198713         fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
   198714       }else{
   198715         i64 iRowid = 0;
   198716         i64 iDelta = 0;
   198717         int iOff = 0;
   198718 
   198719         /* The entire doclist will not fit on this leaf. The following
   198720         ** loop iterates through the poslists that make up the current
   198721         ** doclist.  */
   198722         while( p->rc==SQLITE_OK && iOff<nDoclist ){
   198723           iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
   198724           iRowid += iDelta;
   198725 
   198726           if( writer.bFirstRowidInPage ){
   198727             fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
   198728             pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
   198729             writer.bFirstRowidInPage = 0;
   198730             fts5WriteDlidxAppend(p, &writer, iRowid);
   198731           }else{
   198732             pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
   198733           }
   198734           assert( pBuf->n<=pBuf->nSpace );
   198735 
   198736           if( eDetail==FTS5_DETAIL_NONE ){
   198737             if( iOff<nDoclist && pDoclist[iOff]==0 ){
   198738               pBuf->p[pBuf->n++] = 0;
   198739               iOff++;
   198740               if( iOff<nDoclist && pDoclist[iOff]==0 ){
   198741                 pBuf->p[pBuf->n++] = 0;
   198742                 iOff++;
   198743               }
   198744             }
   198745             if( (pBuf->n + pPgidx->n)>=pgsz ){
   198746               fts5WriteFlushLeaf(p, &writer);
   198747             }
   198748           }else{
   198749             int bDummy;
   198750             int nPos;
   198751             int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
   198752             nCopy += nPos;
   198753             if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
   198754               /* The entire poslist will fit on the current leaf. So copy
   198755               ** it in one go. */
   198756               fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
   198757             }else{
   198758               /* The entire poslist will not fit on this leaf. So it needs
   198759               ** to be broken into sections. The only qualification being
   198760               ** that each varint must be stored contiguously.  */
   198761               const u8 *pPoslist = &pDoclist[iOff];
   198762               int iPos = 0;
   198763               while( p->rc==SQLITE_OK ){
   198764                 int nSpace = pgsz - pBuf->n - pPgidx->n;
   198765                 int n = 0;
   198766                 if( (nCopy - iPos)<=nSpace ){
   198767                   n = nCopy - iPos;
   198768                 }else{
   198769                   n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
   198770                 }
   198771                 assert( n>0 );
   198772                 fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
   198773                 iPos += n;
   198774                 if( (pBuf->n + pPgidx->n)>=pgsz ){
   198775                   fts5WriteFlushLeaf(p, &writer);
   198776                 }
   198777                 if( iPos>=nCopy ) break;
   198778               }
   198779             }
   198780             iOff += nCopy;
   198781           }
   198782         }
   198783       }
   198784 
   198785       /* TODO2: Doclist terminator written here. */
   198786       /* pBuf->p[pBuf->n++] = '\0'; */
   198787       assert( pBuf->n<=pBuf->nSpace );
   198788       sqlite3Fts5HashScanNext(pHash);
   198789     }
   198790     sqlite3Fts5HashClear(pHash);
   198791     fts5WriteFinish(p, &writer, &pgnoLast);
   198792 
   198793     /* Update the Fts5Structure. It is written back to the database by the
   198794     ** fts5StructureRelease() call below.  */
   198795     if( pStruct->nLevel==0 ){
   198796       fts5StructureAddLevel(&p->rc, &pStruct);
   198797     }
   198798     fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
   198799     if( p->rc==SQLITE_OK ){
   198800       pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
   198801       pSeg->iSegid = iSegid;
   198802       pSeg->pgnoFirst = 1;
   198803       pSeg->pgnoLast = pgnoLast;
   198804       pStruct->nSegment++;
   198805     }
   198806     fts5StructurePromote(p, 0, pStruct);
   198807   }
   198808 
   198809   fts5IndexAutomerge(p, &pStruct, pgnoLast);
   198810   fts5IndexCrisismerge(p, &pStruct);
   198811   fts5StructureWrite(p, pStruct);
   198812   fts5StructureRelease(pStruct);
   198813 }
   198814 
   198815 /*
   198816 ** Flush any data stored in the in-memory hash tables to the database.
   198817 */
   198818 static void fts5IndexFlush(Fts5Index *p){
   198819   /* Unless it is empty, flush the hash table to disk */
   198820   if( p->nPendingData ){
   198821     assert( p->pHash );
   198822     p->nPendingData = 0;
   198823     fts5FlushOneHash(p);
   198824   }
   198825 }
   198826 
   198827 static Fts5Structure *fts5IndexOptimizeStruct(
   198828   Fts5Index *p,
   198829   Fts5Structure *pStruct
   198830 ){
   198831   Fts5Structure *pNew = 0;
   198832   int nByte = sizeof(Fts5Structure);
   198833   int nSeg = pStruct->nSegment;
   198834   int i;
   198835 
   198836   /* Figure out if this structure requires optimization. A structure does
   198837   ** not require optimization if either:
   198838   **
   198839   **  + it consists of fewer than two segments, or
   198840   **  + all segments are on the same level, or
   198841   **  + all segments except one are currently inputs to a merge operation.
   198842   **
   198843   ** In the first case, return NULL. In the second, increment the ref-count
   198844   ** on *pStruct and return a copy of the pointer to it.
   198845   */
   198846   if( nSeg<2 ) return 0;
   198847   for(i=0; i<pStruct->nLevel; i++){
   198848     int nThis = pStruct->aLevel[i].nSeg;
   198849     if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
   198850       fts5StructureRef(pStruct);
   198851       return pStruct;
   198852     }
   198853     assert( pStruct->aLevel[i].nMerge<=nThis );
   198854   }
   198855 
   198856   nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
   198857   pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
   198858 
   198859   if( pNew ){
   198860     Fts5StructureLevel *pLvl;
   198861     nByte = nSeg * sizeof(Fts5StructureSegment);
   198862     pNew->nLevel = pStruct->nLevel+1;
   198863     pNew->nRef = 1;
   198864     pNew->nWriteCounter = pStruct->nWriteCounter;
   198865     pLvl = &pNew->aLevel[pStruct->nLevel];
   198866     pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
   198867     if( pLvl->aSeg ){
   198868       int iLvl, iSeg;
   198869       int iSegOut = 0;
   198870       /* Iterate through all segments, from oldest to newest. Add them to
   198871       ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
   198872       ** segment in the data structure.  */
   198873       for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
   198874         for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
   198875           pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
   198876           iSegOut++;
   198877         }
   198878       }
   198879       pNew->nSegment = pLvl->nSeg = nSeg;
   198880     }else{
   198881       sqlite3_free(pNew);
   198882       pNew = 0;
   198883     }
   198884   }
   198885 
   198886   return pNew;
   198887 }
   198888 
   198889 static int sqlite3Fts5IndexOptimize(Fts5Index *p){
   198890   Fts5Structure *pStruct;
   198891   Fts5Structure *pNew = 0;
   198892 
   198893   assert( p->rc==SQLITE_OK );
   198894   fts5IndexFlush(p);
   198895   pStruct = fts5StructureRead(p);
   198896   fts5StructureInvalidate(p);
   198897 
   198898   if( pStruct ){
   198899     pNew = fts5IndexOptimizeStruct(p, pStruct);
   198900   }
   198901   fts5StructureRelease(pStruct);
   198902 
   198903   assert( pNew==0 || pNew->nSegment>0 );
   198904   if( pNew ){
   198905     int iLvl;
   198906     for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
   198907     while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
   198908       int nRem = FTS5_OPT_WORK_UNIT;
   198909       fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
   198910     }
   198911 
   198912     fts5StructureWrite(p, pNew);
   198913     fts5StructureRelease(pNew);
   198914   }
   198915 
   198916   return fts5IndexReturn(p);
   198917 }
   198918 
   198919 /*
   198920 ** This is called to implement the special "VALUES('merge', $nMerge)"
   198921 ** INSERT command.
   198922 */
   198923 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
   198924   Fts5Structure *pStruct = fts5StructureRead(p);
   198925   if( pStruct ){
   198926     int nMin = p->pConfig->nUsermerge;
   198927     fts5StructureInvalidate(p);
   198928     if( nMerge<0 ){
   198929       Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
   198930       fts5StructureRelease(pStruct);
   198931       pStruct = pNew;
   198932       nMin = 2;
   198933       nMerge = nMerge*-1;
   198934     }
   198935     if( pStruct && pStruct->nLevel ){
   198936       if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
   198937         fts5StructureWrite(p, pStruct);
   198938       }
   198939     }
   198940     fts5StructureRelease(pStruct);
   198941   }
   198942   return fts5IndexReturn(p);
   198943 }
   198944 
   198945 static void fts5AppendRowid(
   198946   Fts5Index *p,
   198947   i64 iDelta,
   198948   Fts5Iter *pUnused,
   198949   Fts5Buffer *pBuf
   198950 ){
   198951   UNUSED_PARAM(pUnused);
   198952   fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
   198953 }
   198954 
   198955 static void fts5AppendPoslist(
   198956   Fts5Index *p,
   198957   i64 iDelta,
   198958   Fts5Iter *pMulti,
   198959   Fts5Buffer *pBuf
   198960 ){
   198961   int nData = pMulti->base.nData;
   198962   assert( nData>0 );
   198963   if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
   198964     fts5BufferSafeAppendVarint(pBuf, iDelta);
   198965     fts5BufferSafeAppendVarint(pBuf, nData*2);
   198966     fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
   198967   }
   198968 }
   198969 
   198970 
   198971 static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
   198972   u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
   198973 
   198974   assert( pIter->aPoslist );
   198975   if( p>=pIter->aEof ){
   198976     pIter->aPoslist = 0;
   198977   }else{
   198978     i64 iDelta;
   198979 
   198980     p += fts5GetVarint(p, (u64*)&iDelta);
   198981     pIter->iRowid += iDelta;
   198982 
   198983     /* Read position list size */
   198984     if( p[0] & 0x80 ){
   198985       int nPos;
   198986       pIter->nSize = fts5GetVarint32(p, nPos);
   198987       pIter->nPoslist = (nPos>>1);
   198988     }else{
   198989       pIter->nPoslist = ((int)(p[0])) >> 1;
   198990       pIter->nSize = 1;
   198991     }
   198992 
   198993     pIter->aPoslist = p;
   198994   }
   198995 }
   198996 
   198997 static void fts5DoclistIterInit(
   198998   Fts5Buffer *pBuf,
   198999   Fts5DoclistIter *pIter
   199000 ){
   199001   memset(pIter, 0, sizeof(*pIter));
   199002   pIter->aPoslist = pBuf->p;
   199003   pIter->aEof = &pBuf->p[pBuf->n];
   199004   fts5DoclistIterNext(pIter);
   199005 }
   199006 
   199007 #if 0
   199008 /*
   199009 ** Append a doclist to buffer pBuf.
   199010 **
   199011 ** This function assumes that space within the buffer has already been
   199012 ** allocated.
   199013 */
   199014 static void fts5MergeAppendDocid(
   199015   Fts5Buffer *pBuf,               /* Buffer to write to */
   199016   i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
   199017   i64 iRowid                      /* Rowid to append */
   199018 ){
   199019   assert( pBuf->n!=0 || (*piLastRowid)==0 );
   199020   fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
   199021   *piLastRowid = iRowid;
   199022 }
   199023 #endif
   199024 
   199025 #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
   199026   assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
   199027   fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
   199028   (iLastRowid) = (iRowid);                                     \
   199029 }
   199030 
   199031 /*
   199032 ** Swap the contents of buffer *p1 with that of *p2.
   199033 */
   199034 static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
   199035   Fts5Buffer tmp = *p1;
   199036   *p1 = *p2;
   199037   *p2 = tmp;
   199038 }
   199039 
   199040 static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
   199041   int i = *piOff;
   199042   if( i>=pBuf->n ){
   199043     *piOff = -1;
   199044   }else{
   199045     u64 iVal;
   199046     *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
   199047     *piRowid += iVal;
   199048   }
   199049 }
   199050 
   199051 /*
   199052 ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
   199053 ** In this case the buffers consist of a delta-encoded list of rowids only.
   199054 */
   199055 static void fts5MergeRowidLists(
   199056   Fts5Index *p,                   /* FTS5 backend object */
   199057   Fts5Buffer *p1,                 /* First list to merge */
   199058   Fts5Buffer *p2                  /* Second list to merge */
   199059 ){
   199060   int i1 = 0;
   199061   int i2 = 0;
   199062   i64 iRowid1 = 0;
   199063   i64 iRowid2 = 0;
   199064   i64 iOut = 0;
   199065 
   199066   Fts5Buffer out;
   199067   memset(&out, 0, sizeof(out));
   199068   sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
   199069   if( p->rc ) return;
   199070 
   199071   fts5NextRowid(p1, &i1, &iRowid1);
   199072   fts5NextRowid(p2, &i2, &iRowid2);
   199073   while( i1>=0 || i2>=0 ){
   199074     if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
   199075       assert( iOut==0 || iRowid1>iOut );
   199076       fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
   199077       iOut = iRowid1;
   199078       fts5NextRowid(p1, &i1, &iRowid1);
   199079     }else{
   199080       assert( iOut==0 || iRowid2>iOut );
   199081       fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
   199082       iOut = iRowid2;
   199083       if( i1>=0 && iRowid1==iRowid2 ){
   199084         fts5NextRowid(p1, &i1, &iRowid1);
   199085       }
   199086       fts5NextRowid(p2, &i2, &iRowid2);
   199087     }
   199088   }
   199089 
   199090   fts5BufferSwap(&out, p1);
   199091   fts5BufferFree(&out);
   199092 }
   199093 
   199094 /*
   199095 ** Buffers p1 and p2 contain doclists. This function merges the content
   199096 ** of the two doclists together and sets buffer p1 to the result before
   199097 ** returning.
   199098 **
   199099 ** If an error occurs, an error code is left in p->rc. If an error has
   199100 ** already occurred, this function is a no-op.
   199101 */
   199102 static void fts5MergePrefixLists(
   199103   Fts5Index *p,                   /* FTS5 backend object */
   199104   Fts5Buffer *p1,                 /* First list to merge */
   199105   Fts5Buffer *p2                  /* Second list to merge */
   199106 ){
   199107   if( p2->n ){
   199108     i64 iLastRowid = 0;
   199109     Fts5DoclistIter i1;
   199110     Fts5DoclistIter i2;
   199111     Fts5Buffer out = {0, 0, 0};
   199112     Fts5Buffer tmp = {0, 0, 0};
   199113 
   199114     /* The maximum size of the output is equal to the sum of the two
   199115     ** input sizes + 1 varint (9 bytes). The extra varint is because if the
   199116     ** first rowid in one input is a large negative number, and the first in
   199117     ** the other a non-negative number, the delta for the non-negative
   199118     ** number will be larger on disk than the literal integer value
   199119     ** was.  */
   199120     if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9) ) return;
   199121     fts5DoclistIterInit(p1, &i1);
   199122     fts5DoclistIterInit(p2, &i2);
   199123 
   199124     while( 1 ){
   199125       if( i1.iRowid<i2.iRowid ){
   199126         /* Copy entry from i1 */
   199127         fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
   199128         fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
   199129         fts5DoclistIterNext(&i1);
   199130         if( i1.aPoslist==0 ) break;
   199131       }
   199132       else if( i2.iRowid!=i1.iRowid ){
   199133         /* Copy entry from i2 */
   199134         fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
   199135         fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
   199136         fts5DoclistIterNext(&i2);
   199137         if( i2.aPoslist==0 ) break;
   199138       }
   199139       else{
   199140         /* Merge the two position lists. */
   199141         i64 iPos1 = 0;
   199142         i64 iPos2 = 0;
   199143         int iOff1 = 0;
   199144         int iOff2 = 0;
   199145         u8 *a1 = &i1.aPoslist[i1.nSize];
   199146         u8 *a2 = &i2.aPoslist[i2.nSize];
   199147 
   199148         i64 iPrev = 0;
   199149         Fts5PoslistWriter writer;
   199150         memset(&writer, 0, sizeof(writer));
   199151 
   199152         fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
   199153         fts5BufferZero(&tmp);
   199154         sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
   199155         if( p->rc ) break;
   199156 
   199157         sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
   199158         sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
   199159         assert( iPos1>=0 && iPos2>=0 );
   199160 
   199161         if( iPos1<iPos2 ){
   199162           sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
   199163           sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
   199164         }else{
   199165           sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
   199166           sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
   199167         }
   199168 
   199169         if( iPos1>=0 && iPos2>=0 ){
   199170           while( 1 ){
   199171             if( iPos1<iPos2 ){
   199172               if( iPos1!=iPrev ){
   199173                 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
   199174               }
   199175               sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
   199176               if( iPos1<0 ) break;
   199177             }else{
   199178               assert( iPos2!=iPrev );
   199179               sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
   199180               sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
   199181               if( iPos2<0 ) break;
   199182             }
   199183           }
   199184         }
   199185 
   199186         if( iPos1>=0 ){
   199187           if( iPos1!=iPrev ){
   199188             sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
   199189           }
   199190           fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
   199191         }else{
   199192           assert( iPos2>=0 && iPos2!=iPrev );
   199193           sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
   199194           fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
   199195         }
   199196 
   199197         /* WRITEPOSLISTSIZE */
   199198         fts5BufferSafeAppendVarint(&out, tmp.n * 2);
   199199         fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
   199200         fts5DoclistIterNext(&i1);
   199201         fts5DoclistIterNext(&i2);
   199202         if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
   199203       }
   199204     }
   199205 
   199206     if( i1.aPoslist ){
   199207       fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
   199208       fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
   199209     }
   199210     else if( i2.aPoslist ){
   199211       fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
   199212       fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
   199213     }
   199214     assert( out.n<=(p1->n+p2->n+9) );
   199215 
   199216     fts5BufferSet(&p->rc, p1, out.n, out.p);
   199217     fts5BufferFree(&tmp);
   199218     fts5BufferFree(&out);
   199219   }
   199220 }
   199221 
   199222 static void fts5SetupPrefixIter(
   199223   Fts5Index *p,                   /* Index to read from */
   199224   int bDesc,                      /* True for "ORDER BY rowid DESC" */
   199225   const u8 *pToken,               /* Buffer containing prefix to match */
   199226   int nToken,                     /* Size of buffer pToken in bytes */
   199227   Fts5Colset *pColset,            /* Restrict matches to these columns */
   199228   Fts5Iter **ppIter          /* OUT: New iterator */
   199229 ){
   199230   Fts5Structure *pStruct;
   199231   Fts5Buffer *aBuf;
   199232   const int nBuf = 32;
   199233 
   199234   void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
   199235   void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
   199236   if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
   199237     xMerge = fts5MergeRowidLists;
   199238     xAppend = fts5AppendRowid;
   199239   }else{
   199240     xMerge = fts5MergePrefixLists;
   199241     xAppend = fts5AppendPoslist;
   199242   }
   199243 
   199244   aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
   199245   pStruct = fts5StructureRead(p);
   199246 
   199247   if( aBuf && pStruct ){
   199248     const int flags = FTS5INDEX_QUERY_SCAN
   199249                     | FTS5INDEX_QUERY_SKIPEMPTY
   199250                     | FTS5INDEX_QUERY_NOOUTPUT;
   199251     int i;
   199252     i64 iLastRowid = 0;
   199253     Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
   199254     Fts5Data *pData;
   199255     Fts5Buffer doclist;
   199256     int bNewTerm = 1;
   199257 
   199258     memset(&doclist, 0, sizeof(doclist));
   199259     fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
   199260     fts5IterSetOutputCb(&p->rc, p1);
   199261     for( /* no-op */ ;
   199262         fts5MultiIterEof(p, p1)==0;
   199263         fts5MultiIterNext2(p, p1, &bNewTerm)
   199264     ){
   199265       Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
   199266       int nTerm = pSeg->term.n;
   199267       const u8 *pTerm = pSeg->term.p;
   199268       p1->xSetOutputs(p1, pSeg);
   199269 
   199270       assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
   199271       if( bNewTerm ){
   199272         if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
   199273       }
   199274 
   199275       if( p1->base.nData==0 ) continue;
   199276 
   199277       if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
   199278         for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
   199279           assert( i<nBuf );
   199280           if( aBuf[i].n==0 ){
   199281             fts5BufferSwap(&doclist, &aBuf[i]);
   199282             fts5BufferZero(&doclist);
   199283           }else{
   199284             xMerge(p, &doclist, &aBuf[i]);
   199285             fts5BufferZero(&aBuf[i]);
   199286           }
   199287         }
   199288         iLastRowid = 0;
   199289       }
   199290 
   199291       xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
   199292       iLastRowid = p1->base.iRowid;
   199293     }
   199294 
   199295     for(i=0; i<nBuf; i++){
   199296       if( p->rc==SQLITE_OK ){
   199297         xMerge(p, &doclist, &aBuf[i]);
   199298       }
   199299       fts5BufferFree(&aBuf[i]);
   199300     }
   199301     fts5MultiIterFree(p1);
   199302 
   199303     pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
   199304     if( pData ){
   199305       pData->p = (u8*)&pData[1];
   199306       pData->nn = pData->szLeaf = doclist.n;
   199307       if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
   199308       fts5MultiIterNew2(p, pData, bDesc, ppIter);
   199309     }
   199310     fts5BufferFree(&doclist);
   199311   }
   199312 
   199313   fts5StructureRelease(pStruct);
   199314   sqlite3_free(aBuf);
   199315 }
   199316 
   199317 
   199318 /*
   199319 ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
   199320 ** to the document with rowid iRowid.
   199321 */
   199322 static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
   199323   assert( p->rc==SQLITE_OK );
   199324 
   199325   /* Allocate the hash table if it has not already been allocated */
   199326   if( p->pHash==0 ){
   199327     p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
   199328   }
   199329 
   199330   /* Flush the hash table to disk if required */
   199331   if( iRowid<p->iWriteRowid
   199332    || (iRowid==p->iWriteRowid && p->bDelete==0)
   199333    || (p->nPendingData > p->pConfig->nHashSize)
   199334   ){
   199335     fts5IndexFlush(p);
   199336   }
   199337 
   199338   p->iWriteRowid = iRowid;
   199339   p->bDelete = bDelete;
   199340   return fts5IndexReturn(p);
   199341 }
   199342 
   199343 /*
   199344 ** Commit data to disk.
   199345 */
   199346 static int sqlite3Fts5IndexSync(Fts5Index *p){
   199347   assert( p->rc==SQLITE_OK );
   199348   fts5IndexFlush(p);
   199349   fts5CloseReader(p);
   199350   return fts5IndexReturn(p);
   199351 }
   199352 
   199353 /*
   199354 ** Discard any data stored in the in-memory hash tables. Do not write it
   199355 ** to the database. Additionally, assume that the contents of the %_data
   199356 ** table may have changed on disk. So any in-memory caches of %_data
   199357 ** records must be invalidated.
   199358 */
   199359 static int sqlite3Fts5IndexRollback(Fts5Index *p){
   199360   fts5CloseReader(p);
   199361   fts5IndexDiscardData(p);
   199362   fts5StructureInvalidate(p);
   199363   /* assert( p->rc==SQLITE_OK ); */
   199364   return SQLITE_OK;
   199365 }
   199366 
   199367 /*
   199368 ** The %_data table is completely empty when this function is called. This
   199369 ** function populates it with the initial structure objects for each index,
   199370 ** and the initial version of the "averages" record (a zero-byte blob).
   199371 */
   199372 static int sqlite3Fts5IndexReinit(Fts5Index *p){
   199373   Fts5Structure s;
   199374   fts5StructureInvalidate(p);
   199375   memset(&s, 0, sizeof(Fts5Structure));
   199376   fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
   199377   fts5StructureWrite(p, &s);
   199378   return fts5IndexReturn(p);
   199379 }
   199380 
   199381 /*
   199382 ** Open a new Fts5Index handle. If the bCreate argument is true, create
   199383 ** and initialize the underlying %_data table.
   199384 **
   199385 ** If successful, set *pp to point to the new object and return SQLITE_OK.
   199386 ** Otherwise, set *pp to NULL and return an SQLite error code.
   199387 */
   199388 static int sqlite3Fts5IndexOpen(
   199389   Fts5Config *pConfig,
   199390   int bCreate,
   199391   Fts5Index **pp,
   199392   char **pzErr
   199393 ){
   199394   int rc = SQLITE_OK;
   199395   Fts5Index *p;                   /* New object */
   199396 
   199397   *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
   199398   if( rc==SQLITE_OK ){
   199399     p->pConfig = pConfig;
   199400     p->nWorkUnit = FTS5_WORK_UNIT;
   199401     p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
   199402     if( p->zDataTbl && bCreate ){
   199403       rc = sqlite3Fts5CreateTable(
   199404           pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
   199405       );
   199406       if( rc==SQLITE_OK ){
   199407         rc = sqlite3Fts5CreateTable(pConfig, "idx",
   199408             "segid, term, pgno, PRIMARY KEY(segid, term)",
   199409             1, pzErr
   199410         );
   199411       }
   199412       if( rc==SQLITE_OK ){
   199413         rc = sqlite3Fts5IndexReinit(p);
   199414       }
   199415     }
   199416   }
   199417 
   199418   assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
   199419   if( rc ){
   199420     sqlite3Fts5IndexClose(p);
   199421     *pp = 0;
   199422   }
   199423   return rc;
   199424 }
   199425 
   199426 /*
   199427 ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
   199428 */
   199429 static int sqlite3Fts5IndexClose(Fts5Index *p){
   199430   int rc = SQLITE_OK;
   199431   if( p ){
   199432     assert( p->pReader==0 );
   199433     fts5StructureInvalidate(p);
   199434     sqlite3_finalize(p->pWriter);
   199435     sqlite3_finalize(p->pDeleter);
   199436     sqlite3_finalize(p->pIdxWriter);
   199437     sqlite3_finalize(p->pIdxDeleter);
   199438     sqlite3_finalize(p->pIdxSelect);
   199439     sqlite3_finalize(p->pDataVersion);
   199440     sqlite3Fts5HashFree(p->pHash);
   199441     sqlite3_free(p->zDataTbl);
   199442     sqlite3_free(p);
   199443   }
   199444   return rc;
   199445 }
   199446 
   199447 /*
   199448 ** Argument p points to a buffer containing utf-8 text that is n bytes in
   199449 ** size. Return the number of bytes in the nChar character prefix of the
   199450 ** buffer, or 0 if there are less than nChar characters in total.
   199451 */
   199452 static int sqlite3Fts5IndexCharlenToBytelen(
   199453   const char *p,
   199454   int nByte,
   199455   int nChar
   199456 ){
   199457   int n = 0;
   199458   int i;
   199459   for(i=0; i<nChar; i++){
   199460     if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
   199461     if( (unsigned char)p[n++]>=0xc0 ){
   199462       while( (p[n] & 0xc0)==0x80 ) n++;
   199463     }
   199464   }
   199465   return n;
   199466 }
   199467 
   199468 /*
   199469 ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
   199470 ** unicode characters in the string.
   199471 */
   199472 static int fts5IndexCharlen(const char *pIn, int nIn){
   199473   int nChar = 0;
   199474   int i = 0;
   199475   while( i<nIn ){
   199476     if( (unsigned char)pIn[i++]>=0xc0 ){
   199477       while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
   199478     }
   199479     nChar++;
   199480   }
   199481   return nChar;
   199482 }
   199483 
   199484 /*
   199485 ** Insert or remove data to or from the index. Each time a document is
   199486 ** added to or removed from the index, this function is called one or more
   199487 ** times.
   199488 **
   199489 ** For an insert, it must be called once for each token in the new document.
   199490 ** If the operation is a delete, it must be called (at least) once for each
   199491 ** unique token in the document with an iCol value less than zero. The iPos
   199492 ** argument is ignored for a delete.
   199493 */
   199494 static int sqlite3Fts5IndexWrite(
   199495   Fts5Index *p,                   /* Index to write to */
   199496   int iCol,                       /* Column token appears in (-ve -> delete) */
   199497   int iPos,                       /* Position of token within column */
   199498   const char *pToken, int nToken  /* Token to add or remove to or from index */
   199499 ){
   199500   int i;                          /* Used to iterate through indexes */
   199501   int rc = SQLITE_OK;             /* Return code */
   199502   Fts5Config *pConfig = p->pConfig;
   199503 
   199504   assert( p->rc==SQLITE_OK );
   199505   assert( (iCol<0)==p->bDelete );
   199506 
   199507   /* Add the entry to the main terms index. */
   199508   rc = sqlite3Fts5HashWrite(
   199509       p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
   199510   );
   199511 
   199512   for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
   199513     const int nChar = pConfig->aPrefix[i];
   199514     int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
   199515     if( nByte ){
   199516       rc = sqlite3Fts5HashWrite(p->pHash,
   199517           p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
   199518           nByte
   199519       );
   199520     }
   199521   }
   199522 
   199523   return rc;
   199524 }
   199525 
   199526 /*
   199527 ** Open a new iterator to iterate though all rowid that match the
   199528 ** specified token or token prefix.
   199529 */
   199530 static int sqlite3Fts5IndexQuery(
   199531   Fts5Index *p,                   /* FTS index to query */
   199532   const char *pToken, int nToken, /* Token (or prefix) to query for */
   199533   int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
   199534   Fts5Colset *pColset,            /* Match these columns only */
   199535   Fts5IndexIter **ppIter          /* OUT: New iterator object */
   199536 ){
   199537   Fts5Config *pConfig = p->pConfig;
   199538   Fts5Iter *pRet = 0;
   199539   Fts5Buffer buf = {0, 0, 0};
   199540 
   199541   /* If the QUERY_SCAN flag is set, all other flags must be clear. */
   199542   assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
   199543 
   199544   if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
   199545     int iIdx = 0;                 /* Index to search */
   199546     if( nToken ) memcpy(&buf.p[1], pToken, nToken);
   199547 
   199548     /* Figure out which index to search and set iIdx accordingly. If this
   199549     ** is a prefix query for which there is no prefix index, set iIdx to
   199550     ** greater than pConfig->nPrefix to indicate that the query will be
   199551     ** satisfied by scanning multiple terms in the main index.
   199552     **
   199553     ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
   199554     ** prefix-query. Instead of using a prefix-index (if one exists),
   199555     ** evaluate the prefix query using the main FTS index. This is used
   199556     ** for internal sanity checking by the integrity-check in debug
   199557     ** mode only.  */
   199558 #ifdef SQLITE_DEBUG
   199559     if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
   199560       assert( flags & FTS5INDEX_QUERY_PREFIX );
   199561       iIdx = 1+pConfig->nPrefix;
   199562     }else
   199563 #endif
   199564     if( flags & FTS5INDEX_QUERY_PREFIX ){
   199565       int nChar = fts5IndexCharlen(pToken, nToken);
   199566       for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
   199567         if( pConfig->aPrefix[iIdx-1]==nChar ) break;
   199568       }
   199569     }
   199570 
   199571     if( iIdx<=pConfig->nPrefix ){
   199572       /* Straight index lookup */
   199573       Fts5Structure *pStruct = fts5StructureRead(p);
   199574       buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
   199575       if( pStruct ){
   199576         fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
   199577             pColset, buf.p, nToken+1, -1, 0, &pRet
   199578         );
   199579         fts5StructureRelease(pStruct);
   199580       }
   199581     }else{
   199582       /* Scan multiple terms in the main index */
   199583       int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
   199584       buf.p[0] = FTS5_MAIN_PREFIX;
   199585       fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
   199586       assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
   199587       fts5IterSetOutputCb(&p->rc, pRet);
   199588       if( p->rc==SQLITE_OK ){
   199589         Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
   199590         if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
   199591       }
   199592     }
   199593 
   199594     if( p->rc ){
   199595       sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
   199596       pRet = 0;
   199597       fts5CloseReader(p);
   199598     }
   199599 
   199600     *ppIter = &pRet->base;
   199601     sqlite3Fts5BufferFree(&buf);
   199602   }
   199603   return fts5IndexReturn(p);
   199604 }
   199605 
   199606 /*
   199607 ** Return true if the iterator passed as the only argument is at EOF.
   199608 */
   199609 /*
   199610 ** Move to the next matching rowid.
   199611 */
   199612 static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
   199613   Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
   199614   assert( pIter->pIndex->rc==SQLITE_OK );
   199615   fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
   199616   return fts5IndexReturn(pIter->pIndex);
   199617 }
   199618 
   199619 /*
   199620 ** Move to the next matching term/rowid. Used by the fts5vocab module.
   199621 */
   199622 static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
   199623   Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
   199624   Fts5Index *p = pIter->pIndex;
   199625 
   199626   assert( pIter->pIndex->rc==SQLITE_OK );
   199627 
   199628   fts5MultiIterNext(p, pIter, 0, 0);
   199629   if( p->rc==SQLITE_OK ){
   199630     Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
   199631     if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
   199632       fts5DataRelease(pSeg->pLeaf);
   199633       pSeg->pLeaf = 0;
   199634       pIter->base.bEof = 1;
   199635     }
   199636   }
   199637 
   199638   return fts5IndexReturn(pIter->pIndex);
   199639 }
   199640 
   199641 /*
   199642 ** Move to the next matching rowid that occurs at or after iMatch. The
   199643 ** definition of "at or after" depends on whether this iterator iterates
   199644 ** in ascending or descending rowid order.
   199645 */
   199646 static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
   199647   Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
   199648   fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
   199649   return fts5IndexReturn(pIter->pIndex);
   199650 }
   199651 
   199652 /*
   199653 ** Return the current term.
   199654 */
   199655 static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
   199656   int n;
   199657   const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
   199658   *pn = n-1;
   199659   return &z[1];
   199660 }
   199661 
   199662 /*
   199663 ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
   199664 */
   199665 static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
   199666   if( pIndexIter ){
   199667     Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
   199668     Fts5Index *pIndex = pIter->pIndex;
   199669     fts5MultiIterFree(pIter);
   199670     fts5CloseReader(pIndex);
   199671   }
   199672 }
   199673 
   199674 /*
   199675 ** Read and decode the "averages" record from the database.
   199676 **
   199677 ** Parameter anSize must point to an array of size nCol, where nCol is
   199678 ** the number of user defined columns in the FTS table.
   199679 */
   199680 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
   199681   int nCol = p->pConfig->nCol;
   199682   Fts5Data *pData;
   199683 
   199684   *pnRow = 0;
   199685   memset(anSize, 0, sizeof(i64) * nCol);
   199686   pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
   199687   if( p->rc==SQLITE_OK && pData->nn ){
   199688     int i = 0;
   199689     int iCol;
   199690     i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
   199691     for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
   199692       i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
   199693     }
   199694   }
   199695 
   199696   fts5DataRelease(pData);
   199697   return fts5IndexReturn(p);
   199698 }
   199699 
   199700 /*
   199701 ** Replace the current "averages" record with the contents of the buffer
   199702 ** supplied as the second argument.
   199703 */
   199704 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
   199705   assert( p->rc==SQLITE_OK );
   199706   fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
   199707   return fts5IndexReturn(p);
   199708 }
   199709 
   199710 /*
   199711 ** Return the total number of blocks this module has read from the %_data
   199712 ** table since it was created.
   199713 */
   199714 static int sqlite3Fts5IndexReads(Fts5Index *p){
   199715   return p->nRead;
   199716 }
   199717 
   199718 /*
   199719 ** Set the 32-bit cookie value stored at the start of all structure
   199720 ** records to the value passed as the second argument.
   199721 **
   199722 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   199723 ** occurs.
   199724 */
   199725 static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
   199726   int rc;                              /* Return code */
   199727   Fts5Config *pConfig = p->pConfig;    /* Configuration object */
   199728   u8 aCookie[4];                       /* Binary representation of iNew */
   199729   sqlite3_blob *pBlob = 0;
   199730 
   199731   assert( p->rc==SQLITE_OK );
   199732   sqlite3Fts5Put32(aCookie, iNew);
   199733 
   199734   rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
   199735       "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
   199736   );
   199737   if( rc==SQLITE_OK ){
   199738     sqlite3_blob_write(pBlob, aCookie, 4, 0);
   199739     rc = sqlite3_blob_close(pBlob);
   199740   }
   199741 
   199742   return rc;
   199743 }
   199744 
   199745 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
   199746   Fts5Structure *pStruct;
   199747   pStruct = fts5StructureRead(p);
   199748   fts5StructureRelease(pStruct);
   199749   return fts5IndexReturn(p);
   199750 }
   199751 
   199752 
   199753 /*************************************************************************
   199754 **************************************************************************
   199755 ** Below this point is the implementation of the integrity-check
   199756 ** functionality.
   199757 */
   199758 
   199759 /*
   199760 ** Return a simple checksum value based on the arguments.
   199761 */
   199762 static u64 sqlite3Fts5IndexEntryCksum(
   199763   i64 iRowid,
   199764   int iCol,
   199765   int iPos,
   199766   int iIdx,
   199767   const char *pTerm,
   199768   int nTerm
   199769 ){
   199770   int i;
   199771   u64 ret = iRowid;
   199772   ret += (ret<<3) + iCol;
   199773   ret += (ret<<3) + iPos;
   199774   if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
   199775   for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
   199776   return ret;
   199777 }
   199778 
   199779 #ifdef SQLITE_DEBUG
   199780 /*
   199781 ** This function is purely an internal test. It does not contribute to
   199782 ** FTS functionality, or even the integrity-check, in any way.
   199783 **
   199784 ** Instead, it tests that the same set of pgno/rowid combinations are
   199785 ** visited regardless of whether the doclist-index identified by parameters
   199786 ** iSegid/iLeaf is iterated in forwards or reverse order.
   199787 */
   199788 static void fts5TestDlidxReverse(
   199789   Fts5Index *p,
   199790   int iSegid,                     /* Segment id to load from */
   199791   int iLeaf                       /* Load doclist-index for this leaf */
   199792 ){
   199793   Fts5DlidxIter *pDlidx = 0;
   199794   u64 cksum1 = 13;
   199795   u64 cksum2 = 13;
   199796 
   199797   for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
   199798       fts5DlidxIterEof(p, pDlidx)==0;
   199799       fts5DlidxIterNext(p, pDlidx)
   199800   ){
   199801     i64 iRowid = fts5DlidxIterRowid(pDlidx);
   199802     int pgno = fts5DlidxIterPgno(pDlidx);
   199803     assert( pgno>iLeaf );
   199804     cksum1 += iRowid + ((i64)pgno<<32);
   199805   }
   199806   fts5DlidxIterFree(pDlidx);
   199807   pDlidx = 0;
   199808 
   199809   for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
   199810       fts5DlidxIterEof(p, pDlidx)==0;
   199811       fts5DlidxIterPrev(p, pDlidx)
   199812   ){
   199813     i64 iRowid = fts5DlidxIterRowid(pDlidx);
   199814     int pgno = fts5DlidxIterPgno(pDlidx);
   199815     assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
   199816     cksum2 += iRowid + ((i64)pgno<<32);
   199817   }
   199818   fts5DlidxIterFree(pDlidx);
   199819   pDlidx = 0;
   199820 
   199821   if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
   199822 }
   199823 
   199824 static int fts5QueryCksum(
   199825   Fts5Index *p,                   /* Fts5 index object */
   199826   int iIdx,
   199827   const char *z,                  /* Index key to query for */
   199828   int n,                          /* Size of index key in bytes */
   199829   int flags,                      /* Flags for Fts5IndexQuery */
   199830   u64 *pCksum                     /* IN/OUT: Checksum value */
   199831 ){
   199832   int eDetail = p->pConfig->eDetail;
   199833   u64 cksum = *pCksum;
   199834   Fts5IndexIter *pIter = 0;
   199835   int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
   199836 
   199837   while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
   199838     i64 rowid = pIter->iRowid;
   199839 
   199840     if( eDetail==FTS5_DETAIL_NONE ){
   199841       cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
   199842     }else{
   199843       Fts5PoslistReader sReader;
   199844       for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
   199845           sReader.bEof==0;
   199846           sqlite3Fts5PoslistReaderNext(&sReader)
   199847       ){
   199848         int iCol = FTS5_POS2COLUMN(sReader.iPos);
   199849         int iOff = FTS5_POS2OFFSET(sReader.iPos);
   199850         cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
   199851       }
   199852     }
   199853     if( rc==SQLITE_OK ){
   199854       rc = sqlite3Fts5IterNext(pIter);
   199855     }
   199856   }
   199857   sqlite3Fts5IterClose(pIter);
   199858 
   199859   *pCksum = cksum;
   199860   return rc;
   199861 }
   199862 
   199863 
   199864 /*
   199865 ** This function is also purely an internal test. It does not contribute to
   199866 ** FTS functionality, or even the integrity-check, in any way.
   199867 */
   199868 static void fts5TestTerm(
   199869   Fts5Index *p,
   199870   Fts5Buffer *pPrev,              /* Previous term */
   199871   const char *z, int n,           /* Possibly new term to test */
   199872   u64 expected,
   199873   u64 *pCksum
   199874 ){
   199875   int rc = p->rc;
   199876   if( pPrev->n==0 ){
   199877     fts5BufferSet(&rc, pPrev, n, (const u8*)z);
   199878   }else
   199879   if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
   199880     u64 cksum3 = *pCksum;
   199881     const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
   199882     int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
   199883     int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
   199884     int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
   199885     u64 ck1 = 0;
   199886     u64 ck2 = 0;
   199887 
   199888     /* Check that the results returned for ASC and DESC queries are
   199889     ** the same. If not, call this corruption.  */
   199890     rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
   199891     if( rc==SQLITE_OK ){
   199892       int f = flags|FTS5INDEX_QUERY_DESC;
   199893       rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
   199894     }
   199895     if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
   199896 
   199897     /* If this is a prefix query, check that the results returned if the
   199898     ** the index is disabled are the same. In both ASC and DESC order.
   199899     **
   199900     ** This check may only be performed if the hash table is empty. This
   199901     ** is because the hash table only supports a single scan query at
   199902     ** a time, and the multi-iter loop from which this function is called
   199903     ** is already performing such a scan. */
   199904     if( p->nPendingData==0 ){
   199905       if( iIdx>0 && rc==SQLITE_OK ){
   199906         int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
   199907         ck2 = 0;
   199908         rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
   199909         if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
   199910       }
   199911       if( iIdx>0 && rc==SQLITE_OK ){
   199912         int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
   199913         ck2 = 0;
   199914         rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
   199915         if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
   199916       }
   199917     }
   199918 
   199919     cksum3 ^= ck1;
   199920     fts5BufferSet(&rc, pPrev, n, (const u8*)z);
   199921 
   199922     if( rc==SQLITE_OK && cksum3!=expected ){
   199923       rc = FTS5_CORRUPT;
   199924     }
   199925     *pCksum = cksum3;
   199926   }
   199927   p->rc = rc;
   199928 }
   199929 
   199930 #else
   199931 # define fts5TestDlidxReverse(x,y,z)
   199932 # define fts5TestTerm(u,v,w,x,y,z)
   199933 #endif
   199934 
   199935 /*
   199936 ** Check that:
   199937 **
   199938 **   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
   199939 **      contain zero terms.
   199940 **   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
   199941 **      contain zero rowids.
   199942 */
   199943 static void fts5IndexIntegrityCheckEmpty(
   199944   Fts5Index *p,
   199945   Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
   199946   int iFirst,
   199947   int iNoRowid,
   199948   int iLast
   199949 ){
   199950   int i;
   199951 
   199952   /* Now check that the iter.nEmpty leaves following the current leaf
   199953   ** (a) exist and (b) contain no terms. */
   199954   for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
   199955     Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
   199956     if( pLeaf ){
   199957       if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
   199958       if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
   199959     }
   199960     fts5DataRelease(pLeaf);
   199961   }
   199962 }
   199963 
   199964 static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
   199965   int iTermOff = 0;
   199966   int ii;
   199967 
   199968   Fts5Buffer buf1 = {0,0,0};
   199969   Fts5Buffer buf2 = {0,0,0};
   199970 
   199971   ii = pLeaf->szLeaf;
   199972   while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
   199973     int res;
   199974     int iOff;
   199975     int nIncr;
   199976 
   199977     ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
   199978     iTermOff += nIncr;
   199979     iOff = iTermOff;
   199980 
   199981     if( iOff>=pLeaf->szLeaf ){
   199982       p->rc = FTS5_CORRUPT;
   199983     }else if( iTermOff==nIncr ){
   199984       int nByte;
   199985       iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
   199986       if( (iOff+nByte)>pLeaf->szLeaf ){
   199987         p->rc = FTS5_CORRUPT;
   199988       }else{
   199989         fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
   199990       }
   199991     }else{
   199992       int nKeep, nByte;
   199993       iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
   199994       iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
   199995       if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
   199996         p->rc = FTS5_CORRUPT;
   199997       }else{
   199998         buf1.n = nKeep;
   199999         fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
   200000       }
   200001 
   200002       if( p->rc==SQLITE_OK ){
   200003         res = fts5BufferCompare(&buf1, &buf2);
   200004         if( res<=0 ) p->rc = FTS5_CORRUPT;
   200005       }
   200006     }
   200007     fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
   200008   }
   200009 
   200010   fts5BufferFree(&buf1);
   200011   fts5BufferFree(&buf2);
   200012 }
   200013 
   200014 static void fts5IndexIntegrityCheckSegment(
   200015   Fts5Index *p,                   /* FTS5 backend object */
   200016   Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
   200017 ){
   200018   Fts5Config *pConfig = p->pConfig;
   200019   sqlite3_stmt *pStmt = 0;
   200020   int rc2;
   200021   int iIdxPrevLeaf = pSeg->pgnoFirst-1;
   200022   int iDlidxPrevLeaf = pSeg->pgnoLast;
   200023 
   200024   if( pSeg->pgnoFirst==0 ) return;
   200025 
   200026   fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
   200027       "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
   200028       pConfig->zDb, pConfig->zName, pSeg->iSegid
   200029   ));
   200030 
   200031   /* Iterate through the b-tree hierarchy.  */
   200032   while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   200033     i64 iRow;                     /* Rowid for this leaf */
   200034     Fts5Data *pLeaf;              /* Data for this leaf */
   200035 
   200036     int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
   200037     const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
   200038     int iIdxLeaf = sqlite3_column_int(pStmt, 2);
   200039     int bIdxDlidx = sqlite3_column_int(pStmt, 3);
   200040 
   200041     /* If the leaf in question has already been trimmed from the segment,
   200042     ** ignore this b-tree entry. Otherwise, load it into memory. */
   200043     if( iIdxLeaf<pSeg->pgnoFirst ) continue;
   200044     iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
   200045     pLeaf = fts5LeafRead(p, iRow);
   200046     if( pLeaf==0 ) break;
   200047 
   200048     /* Check that the leaf contains at least one term, and that it is equal
   200049     ** to or larger than the split-key in zIdxTerm.  Also check that if there
   200050     ** is also a rowid pointer within the leaf page header, it points to a
   200051     ** location before the term.  */
   200052     if( pLeaf->nn<=pLeaf->szLeaf ){
   200053       p->rc = FTS5_CORRUPT;
   200054     }else{
   200055       int iOff;                   /* Offset of first term on leaf */
   200056       int iRowidOff;              /* Offset of first rowid on leaf */
   200057       int nTerm;                  /* Size of term on leaf in bytes */
   200058       int res;                    /* Comparison of term and split-key */
   200059 
   200060       iOff = fts5LeafFirstTermOff(pLeaf);
   200061       iRowidOff = fts5LeafFirstRowidOff(pLeaf);
   200062       if( iRowidOff>=iOff ){
   200063         p->rc = FTS5_CORRUPT;
   200064       }else{
   200065         iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
   200066         res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
   200067         if( res==0 ) res = nTerm - nIdxTerm;
   200068         if( res<0 ) p->rc = FTS5_CORRUPT;
   200069       }
   200070 
   200071       fts5IntegrityCheckPgidx(p, pLeaf);
   200072     }
   200073     fts5DataRelease(pLeaf);
   200074     if( p->rc ) break;
   200075 
   200076     /* Now check that the iter.nEmpty leaves following the current leaf
   200077     ** (a) exist and (b) contain no terms. */
   200078     fts5IndexIntegrityCheckEmpty(
   200079         p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
   200080     );
   200081     if( p->rc ) break;
   200082 
   200083     /* If there is a doclist-index, check that it looks right. */
   200084     if( bIdxDlidx ){
   200085       Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
   200086       int iPrevLeaf = iIdxLeaf;
   200087       int iSegid = pSeg->iSegid;
   200088       int iPg = 0;
   200089       i64 iKey;
   200090 
   200091       for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
   200092           fts5DlidxIterEof(p, pDlidx)==0;
   200093           fts5DlidxIterNext(p, pDlidx)
   200094       ){
   200095 
   200096         /* Check any rowid-less pages that occur before the current leaf. */
   200097         for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
   200098           iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
   200099           pLeaf = fts5DataRead(p, iKey);
   200100           if( pLeaf ){
   200101             if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
   200102             fts5DataRelease(pLeaf);
   200103           }
   200104         }
   200105         iPrevLeaf = fts5DlidxIterPgno(pDlidx);
   200106 
   200107         /* Check that the leaf page indicated by the iterator really does
   200108         ** contain the rowid suggested by the same. */
   200109         iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
   200110         pLeaf = fts5DataRead(p, iKey);
   200111         if( pLeaf ){
   200112           i64 iRowid;
   200113           int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
   200114           ASSERT_SZLEAF_OK(pLeaf);
   200115           if( iRowidOff>=pLeaf->szLeaf ){
   200116             p->rc = FTS5_CORRUPT;
   200117           }else{
   200118             fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
   200119             if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
   200120           }
   200121           fts5DataRelease(pLeaf);
   200122         }
   200123       }
   200124 
   200125       iDlidxPrevLeaf = iPg;
   200126       fts5DlidxIterFree(pDlidx);
   200127       fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
   200128     }else{
   200129       iDlidxPrevLeaf = pSeg->pgnoLast;
   200130       /* TODO: Check there is no doclist index */
   200131     }
   200132 
   200133     iIdxPrevLeaf = iIdxLeaf;
   200134   }
   200135 
   200136   rc2 = sqlite3_finalize(pStmt);
   200137   if( p->rc==SQLITE_OK ) p->rc = rc2;
   200138 
   200139   /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
   200140 #if 0
   200141   if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
   200142     p->rc = FTS5_CORRUPT;
   200143   }
   200144 #endif
   200145 }
   200146 
   200147 
   200148 /*
   200149 ** Run internal checks to ensure that the FTS index (a) is internally
   200150 ** consistent and (b) contains entries for which the XOR of the checksums
   200151 ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
   200152 **
   200153 ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
   200154 ** checksum does not match. Return SQLITE_OK if all checks pass without
   200155 ** error, or some other SQLite error code if another error (e.g. OOM)
   200156 ** occurs.
   200157 */
   200158 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
   200159   int eDetail = p->pConfig->eDetail;
   200160   u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
   200161   Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
   200162   Fts5Iter *pIter;                /* Used to iterate through entire index */
   200163   Fts5Structure *pStruct;         /* Index structure */
   200164 
   200165 #ifdef SQLITE_DEBUG
   200166   /* Used by extra internal tests only run if NDEBUG is not defined */
   200167   u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
   200168   Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
   200169 #endif
   200170   const int flags = FTS5INDEX_QUERY_NOOUTPUT;
   200171 
   200172   /* Load the FTS index structure */
   200173   pStruct = fts5StructureRead(p);
   200174 
   200175   /* Check that the internal nodes of each segment match the leaves */
   200176   if( pStruct ){
   200177     int iLvl, iSeg;
   200178     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
   200179       for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
   200180         Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
   200181         fts5IndexIntegrityCheckSegment(p, pSeg);
   200182       }
   200183     }
   200184   }
   200185 
   200186   /* The cksum argument passed to this function is a checksum calculated
   200187   ** based on all expected entries in the FTS index (including prefix index
   200188   ** entries). This block checks that a checksum calculated based on the
   200189   ** actual contents of FTS index is identical.
   200190   **
   200191   ** Two versions of the same checksum are calculated. The first (stack
   200192   ** variable cksum2) based on entries extracted from the full-text index
   200193   ** while doing a linear scan of each individual index in turn.
   200194   **
   200195   ** As each term visited by the linear scans, a separate query for the
   200196   ** same term is performed. cksum3 is calculated based on the entries
   200197   ** extracted by these queries.
   200198   */
   200199   for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
   200200       fts5MultiIterEof(p, pIter)==0;
   200201       fts5MultiIterNext(p, pIter, 0, 0)
   200202   ){
   200203     int n;                      /* Size of term in bytes */
   200204     i64 iPos = 0;               /* Position read from poslist */
   200205     int iOff = 0;               /* Offset within poslist */
   200206     i64 iRowid = fts5MultiIterRowid(pIter);
   200207     char *z = (char*)fts5MultiIterTerm(pIter, &n);
   200208 
   200209     /* If this is a new term, query for it. Update cksum3 with the results. */
   200210     fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
   200211 
   200212     if( eDetail==FTS5_DETAIL_NONE ){
   200213       if( 0==fts5MultiIterIsEmpty(p, pIter) ){
   200214         cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
   200215       }
   200216     }else{
   200217       poslist.n = 0;
   200218       fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
   200219       while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
   200220         int iCol = FTS5_POS2COLUMN(iPos);
   200221         int iTokOff = FTS5_POS2OFFSET(iPos);
   200222         cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
   200223       }
   200224     }
   200225   }
   200226   fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
   200227 
   200228   fts5MultiIterFree(pIter);
   200229   if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
   200230 
   200231   fts5StructureRelease(pStruct);
   200232 #ifdef SQLITE_DEBUG
   200233   fts5BufferFree(&term);
   200234 #endif
   200235   fts5BufferFree(&poslist);
   200236   return fts5IndexReturn(p);
   200237 }
   200238 
   200239 /*************************************************************************
   200240 **************************************************************************
   200241 ** Below this point is the implementation of the fts5_decode() scalar
   200242 ** function only.
   200243 */
   200244 
   200245 /*
   200246 ** Decode a segment-data rowid from the %_data table. This function is
   200247 ** the opposite of macro FTS5_SEGMENT_ROWID().
   200248 */
   200249 static void fts5DecodeRowid(
   200250   i64 iRowid,                     /* Rowid from %_data table */
   200251   int *piSegid,                   /* OUT: Segment id */
   200252   int *pbDlidx,                   /* OUT: Dlidx flag */
   200253   int *piHeight,                  /* OUT: Height */
   200254   int *piPgno                     /* OUT: Page number */
   200255 ){
   200256   *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
   200257   iRowid >>= FTS5_DATA_PAGE_B;
   200258 
   200259   *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
   200260   iRowid >>= FTS5_DATA_HEIGHT_B;
   200261 
   200262   *pbDlidx = (int)(iRowid & 0x0001);
   200263   iRowid >>= FTS5_DATA_DLI_B;
   200264 
   200265   *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
   200266 }
   200267 
   200268 static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
   200269   int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
   200270   fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
   200271 
   200272   if( iSegid==0 ){
   200273     if( iKey==FTS5_AVERAGES_ROWID ){
   200274       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
   200275     }else{
   200276       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
   200277     }
   200278   }
   200279   else{
   200280     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
   200281         bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
   200282     );
   200283   }
   200284 }
   200285 
   200286 static void fts5DebugStructure(
   200287   int *pRc,                       /* IN/OUT: error code */
   200288   Fts5Buffer *pBuf,
   200289   Fts5Structure *p
   200290 ){
   200291   int iLvl, iSeg;                 /* Iterate through levels, segments */
   200292 
   200293   for(iLvl=0; iLvl<p->nLevel; iLvl++){
   200294     Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
   200295     sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
   200296         " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
   200297     );
   200298     for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
   200299       Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
   200300       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
   200301           pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
   200302       );
   200303     }
   200304     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
   200305   }
   200306 }
   200307 
   200308 /*
   200309 ** This is part of the fts5_decode() debugging aid.
   200310 **
   200311 ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
   200312 ** function appends a human-readable representation of the same object
   200313 ** to the buffer passed as the second argument.
   200314 */
   200315 static void fts5DecodeStructure(
   200316   int *pRc,                       /* IN/OUT: error code */
   200317   Fts5Buffer *pBuf,
   200318   const u8 *pBlob, int nBlob
   200319 ){
   200320   int rc;                         /* Return code */
   200321   Fts5Structure *p = 0;           /* Decoded structure object */
   200322 
   200323   rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
   200324   if( rc!=SQLITE_OK ){
   200325     *pRc = rc;
   200326     return;
   200327   }
   200328 
   200329   fts5DebugStructure(pRc, pBuf, p);
   200330   fts5StructureRelease(p);
   200331 }
   200332 
   200333 /*
   200334 ** This is part of the fts5_decode() debugging aid.
   200335 **
   200336 ** Arguments pBlob/nBlob contain an "averages" record. This function
   200337 ** appends a human-readable representation of record to the buffer passed
   200338 ** as the second argument.
   200339 */
   200340 static void fts5DecodeAverages(
   200341   int *pRc,                       /* IN/OUT: error code */
   200342   Fts5Buffer *pBuf,
   200343   const u8 *pBlob, int nBlob
   200344 ){
   200345   int i = 0;
   200346   const char *zSpace = "";
   200347 
   200348   while( i<nBlob ){
   200349     u64 iVal;
   200350     i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
   200351     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
   200352     zSpace = " ";
   200353   }
   200354 }
   200355 
   200356 /*
   200357 ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
   200358 ** each varint and append its string representation to buffer pBuf. Return
   200359 ** after either the input buffer is exhausted or a 0 value is read.
   200360 **
   200361 ** The return value is the number of bytes read from the input buffer.
   200362 */
   200363 static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
   200364   int iOff = 0;
   200365   while( iOff<n ){
   200366     int iVal;
   200367     iOff += fts5GetVarint32(&a[iOff], iVal);
   200368     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
   200369   }
   200370   return iOff;
   200371 }
   200372 
   200373 /*
   200374 ** The start of buffer (a/n) contains the start of a doclist. The doclist
   200375 ** may or may not finish within the buffer. This function appends a text
   200376 ** representation of the part of the doclist that is present to buffer
   200377 ** pBuf.
   200378 **
   200379 ** The return value is the number of bytes read from the input buffer.
   200380 */
   200381 static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
   200382   i64 iDocid = 0;
   200383   int iOff = 0;
   200384 
   200385   if( n>0 ){
   200386     iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
   200387     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
   200388   }
   200389   while( iOff<n ){
   200390     int nPos;
   200391     int bDel;
   200392     iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
   200393     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
   200394     iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
   200395     if( iOff<n ){
   200396       i64 iDelta;
   200397       iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
   200398       iDocid += iDelta;
   200399       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
   200400     }
   200401   }
   200402 
   200403   return iOff;
   200404 }
   200405 
   200406 /*
   200407 ** This function is part of the fts5_decode() debugging function. It is
   200408 ** only ever used with detail=none tables.
   200409 **
   200410 ** Buffer (pData/nData) contains a doclist in the format used by detail=none
   200411 ** tables. This function appends a human-readable version of that list to
   200412 ** buffer pBuf.
   200413 **
   200414 ** If *pRc is other than SQLITE_OK when this function is called, it is a
   200415 ** no-op. If an OOM or other error occurs within this function, *pRc is
   200416 ** set to an SQLite error code before returning. The final state of buffer
   200417 ** pBuf is undefined in this case.
   200418 */
   200419 static void fts5DecodeRowidList(
   200420   int *pRc,                       /* IN/OUT: Error code */
   200421   Fts5Buffer *pBuf,               /* Buffer to append text to */
   200422   const u8 *pData, int nData      /* Data to decode list-of-rowids from */
   200423 ){
   200424   int i = 0;
   200425   i64 iRowid = 0;
   200426 
   200427   while( i<nData ){
   200428     const char *zApp = "";
   200429     u64 iVal;
   200430     i += sqlite3Fts5GetVarint(&pData[i], &iVal);
   200431     iRowid += iVal;
   200432 
   200433     if( i<nData && pData[i]==0x00 ){
   200434       i++;
   200435       if( i<nData && pData[i]==0x00 ){
   200436         i++;
   200437         zApp = "+";
   200438       }else{
   200439         zApp = "*";
   200440       }
   200441     }
   200442 
   200443     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
   200444   }
   200445 }
   200446 
   200447 /*
   200448 ** The implementation of user-defined scalar function fts5_decode().
   200449 */
   200450 static void fts5DecodeFunction(
   200451   sqlite3_context *pCtx,          /* Function call context */
   200452   int nArg,                       /* Number of args (always 2) */
   200453   sqlite3_value **apVal           /* Function arguments */
   200454 ){
   200455   i64 iRowid;                     /* Rowid for record being decoded */
   200456   int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
   200457   const u8 *aBlob; int n;         /* Record to decode */
   200458   u8 *a = 0;
   200459   Fts5Buffer s;                   /* Build up text to return here */
   200460   int rc = SQLITE_OK;             /* Return code */
   200461   int nSpace = 0;
   200462   int eDetailNone = (sqlite3_user_data(pCtx)!=0);
   200463 
   200464   assert( nArg==2 );
   200465   UNUSED_PARAM(nArg);
   200466   memset(&s, 0, sizeof(Fts5Buffer));
   200467   iRowid = sqlite3_value_int64(apVal[0]);
   200468 
   200469   /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
   200470   ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
   200471   ** buffer overreads even if the record is corrupt.  */
   200472   n = sqlite3_value_bytes(apVal[1]);
   200473   aBlob = sqlite3_value_blob(apVal[1]);
   200474   nSpace = n + FTS5_DATA_ZERO_PADDING;
   200475   a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
   200476   if( a==0 ) goto decode_out;
   200477   memcpy(a, aBlob, n);
   200478 
   200479 
   200480   fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
   200481 
   200482   fts5DebugRowid(&rc, &s, iRowid);
   200483   if( bDlidx ){
   200484     Fts5Data dlidx;
   200485     Fts5DlidxLvl lvl;
   200486 
   200487     dlidx.p = a;
   200488     dlidx.nn = n;
   200489 
   200490     memset(&lvl, 0, sizeof(Fts5DlidxLvl));
   200491     lvl.pData = &dlidx;
   200492     lvl.iLeafPgno = iPgno;
   200493 
   200494     for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
   200495       sqlite3Fts5BufferAppendPrintf(&rc, &s,
   200496           " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
   200497       );
   200498     }
   200499   }else if( iSegid==0 ){
   200500     if( iRowid==FTS5_AVERAGES_ROWID ){
   200501       fts5DecodeAverages(&rc, &s, a, n);
   200502     }else{
   200503       fts5DecodeStructure(&rc, &s, a, n);
   200504     }
   200505   }else if( eDetailNone ){
   200506     Fts5Buffer term;              /* Current term read from page */
   200507     int szLeaf;
   200508     int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
   200509     int iTermOff;
   200510     int nKeep = 0;
   200511     int iOff;
   200512 
   200513     memset(&term, 0, sizeof(Fts5Buffer));
   200514 
   200515     /* Decode any entries that occur before the first term. */
   200516     if( szLeaf<n ){
   200517       iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
   200518     }else{
   200519       iTermOff = szLeaf;
   200520     }
   200521     fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
   200522 
   200523     iOff = iTermOff;
   200524     while( iOff<szLeaf ){
   200525       int nAppend;
   200526 
   200527       /* Read the term data for the next term*/
   200528       iOff += fts5GetVarint32(&a[iOff], nAppend);
   200529       term.n = nKeep;
   200530       fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
   200531       sqlite3Fts5BufferAppendPrintf(
   200532           &rc, &s, " term=%.*s", term.n, (const char*)term.p
   200533       );
   200534       iOff += nAppend;
   200535 
   200536       /* Figure out where the doclist for this term ends */
   200537       if( iPgidxOff<n ){
   200538         int nIncr;
   200539         iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
   200540         iTermOff += nIncr;
   200541       }else{
   200542         iTermOff = szLeaf;
   200543       }
   200544 
   200545       fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
   200546       iOff = iTermOff;
   200547       if( iOff<szLeaf ){
   200548         iOff += fts5GetVarint32(&a[iOff], nKeep);
   200549       }
   200550     }
   200551 
   200552     fts5BufferFree(&term);
   200553   }else{
   200554     Fts5Buffer term;              /* Current term read from page */
   200555     int szLeaf;                   /* Offset of pgidx in a[] */
   200556     int iPgidxOff;
   200557     int iPgidxPrev = 0;           /* Previous value read from pgidx */
   200558     int iTermOff = 0;
   200559     int iRowidOff = 0;
   200560     int iOff;
   200561     int nDoclist;
   200562 
   200563     memset(&term, 0, sizeof(Fts5Buffer));
   200564 
   200565     if( n<4 ){
   200566       sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
   200567       goto decode_out;
   200568     }else{
   200569       iRowidOff = fts5GetU16(&a[0]);
   200570       iPgidxOff = szLeaf = fts5GetU16(&a[2]);
   200571       if( iPgidxOff<n ){
   200572         fts5GetVarint32(&a[iPgidxOff], iTermOff);
   200573       }
   200574     }
   200575 
   200576     /* Decode the position list tail at the start of the page */
   200577     if( iRowidOff!=0 ){
   200578       iOff = iRowidOff;
   200579     }else if( iTermOff!=0 ){
   200580       iOff = iTermOff;
   200581     }else{
   200582       iOff = szLeaf;
   200583     }
   200584     fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
   200585 
   200586     /* Decode any more doclist data that appears on the page before the
   200587     ** first term. */
   200588     nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
   200589     fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
   200590 
   200591     while( iPgidxOff<n ){
   200592       int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
   200593       int nByte;                            /* Bytes of data */
   200594       int iEnd;
   200595 
   200596       iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
   200597       iPgidxPrev += nByte;
   200598       iOff = iPgidxPrev;
   200599 
   200600       if( iPgidxOff<n ){
   200601         fts5GetVarint32(&a[iPgidxOff], nByte);
   200602         iEnd = iPgidxPrev + nByte;
   200603       }else{
   200604         iEnd = szLeaf;
   200605       }
   200606 
   200607       if( bFirst==0 ){
   200608         iOff += fts5GetVarint32(&a[iOff], nByte);
   200609         term.n = nByte;
   200610       }
   200611       iOff += fts5GetVarint32(&a[iOff], nByte);
   200612       fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
   200613       iOff += nByte;
   200614 
   200615       sqlite3Fts5BufferAppendPrintf(
   200616           &rc, &s, " term=%.*s", term.n, (const char*)term.p
   200617       );
   200618       iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
   200619     }
   200620 
   200621     fts5BufferFree(&term);
   200622   }
   200623 
   200624  decode_out:
   200625   sqlite3_free(a);
   200626   if( rc==SQLITE_OK ){
   200627     sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
   200628   }else{
   200629     sqlite3_result_error_code(pCtx, rc);
   200630   }
   200631   fts5BufferFree(&s);
   200632 }
   200633 
   200634 /*
   200635 ** The implementation of user-defined scalar function fts5_rowid().
   200636 */
   200637 static void fts5RowidFunction(
   200638   sqlite3_context *pCtx,          /* Function call context */
   200639   int nArg,                       /* Number of args (always 2) */
   200640   sqlite3_value **apVal           /* Function arguments */
   200641 ){
   200642   const char *zArg;
   200643   if( nArg==0 ){
   200644     sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
   200645   }else{
   200646     zArg = (const char*)sqlite3_value_text(apVal[0]);
   200647     if( 0==sqlite3_stricmp(zArg, "segment") ){
   200648       i64 iRowid;
   200649       int segid, pgno;
   200650       if( nArg!=3 ){
   200651         sqlite3_result_error(pCtx,
   200652             "should be: fts5_rowid('segment', segid, pgno))", -1
   200653         );
   200654       }else{
   200655         segid = sqlite3_value_int(apVal[1]);
   200656         pgno = sqlite3_value_int(apVal[2]);
   200657         iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
   200658         sqlite3_result_int64(pCtx, iRowid);
   200659       }
   200660     }else{
   200661       sqlite3_result_error(pCtx,
   200662         "first arg to fts5_rowid() must be 'segment'" , -1
   200663       );
   200664     }
   200665   }
   200666 }
   200667 
   200668 /*
   200669 ** This is called as part of registering the FTS5 module with database
   200670 ** connection db. It registers several user-defined scalar functions useful
   200671 ** with FTS5.
   200672 **
   200673 ** If successful, SQLITE_OK is returned. If an error occurs, some other
   200674 ** SQLite error code is returned instead.
   200675 */
   200676 static int sqlite3Fts5IndexInit(sqlite3 *db){
   200677   int rc = sqlite3_create_function(
   200678       db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
   200679   );
   200680 
   200681   if( rc==SQLITE_OK ){
   200682     rc = sqlite3_create_function(
   200683         db, "fts5_decode_none", 2,
   200684         SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
   200685     );
   200686   }
   200687 
   200688   if( rc==SQLITE_OK ){
   200689     rc = sqlite3_create_function(
   200690         db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
   200691     );
   200692   }
   200693   return rc;
   200694 }
   200695 
   200696 
   200697 static int sqlite3Fts5IndexReset(Fts5Index *p){
   200698   assert( p->pStruct==0 || p->iStructVersion!=0 );
   200699   if( fts5IndexDataVersion(p)!=p->iStructVersion ){
   200700     fts5StructureInvalidate(p);
   200701   }
   200702   return fts5IndexReturn(p);
   200703 }
   200704 
   200705 /*
   200706 ** 2014 Jun 09
   200707 **
   200708 ** The author disclaims copyright to this source code.  In place of
   200709 ** a legal notice, here is a blessing:
   200710 **
   200711 **    May you do good and not evil.
   200712 **    May you find forgiveness for yourself and forgive others.
   200713 **    May you share freely, never taking more than you give.
   200714 **
   200715 ******************************************************************************
   200716 **
   200717 ** This is an SQLite module implementing full-text search.
   200718 */
   200719 
   200720 
   200721 /* #include "fts5Int.h" */
   200722 
   200723 /*
   200724 ** This variable is set to false when running tests for which the on disk
   200725 ** structures should not be corrupt. Otherwise, true. If it is false, extra
   200726 ** assert() conditions in the fts5 code are activated - conditions that are
   200727 ** only true if it is guaranteed that the fts5 database is not corrupt.
   200728 */
   200729 SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
   200730 
   200731 
   200732 typedef struct Fts5Auxdata Fts5Auxdata;
   200733 typedef struct Fts5Auxiliary Fts5Auxiliary;
   200734 typedef struct Fts5Cursor Fts5Cursor;
   200735 typedef struct Fts5Sorter Fts5Sorter;
   200736 typedef struct Fts5Table Fts5Table;
   200737 typedef struct Fts5TokenizerModule Fts5TokenizerModule;
   200738 
   200739 /*
   200740 ** NOTES ON TRANSACTIONS:
   200741 **
   200742 ** SQLite invokes the following virtual table methods as transactions are
   200743 ** opened and closed by the user:
   200744 **
   200745 **     xBegin():    Start of a new transaction.
   200746 **     xSync():     Initial part of two-phase commit.
   200747 **     xCommit():   Final part of two-phase commit.
   200748 **     xRollback(): Rollback the transaction.
   200749 **
   200750 ** Anything that is required as part of a commit that may fail is performed
   200751 ** in the xSync() callback. Current versions of SQLite ignore any errors
   200752 ** returned by xCommit().
   200753 **
   200754 ** And as sub-transactions are opened/closed:
   200755 **
   200756 **     xSavepoint(int S):  Open savepoint S.
   200757 **     xRelease(int S):    Commit and close savepoint S.
   200758 **     xRollbackTo(int S): Rollback to start of savepoint S.
   200759 **
   200760 ** During a write-transaction the fts5_index.c module may cache some data
   200761 ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
   200762 ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
   200763 ** is called.
   200764 **
   200765 ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
   200766 ** structure is used to record the current transaction state. This information
   200767 ** is not required, but it is used in the assert() statements executed by
   200768 ** function fts5CheckTransactionState() (see below).
   200769 */
   200770 struct Fts5TransactionState {
   200771   int eState;                     /* 0==closed, 1==open, 2==synced */
   200772   int iSavepoint;                 /* Number of open savepoints (0 -> none) */
   200773 };
   200774 
   200775 /*
   200776 ** A single object of this type is allocated when the FTS5 module is
   200777 ** registered with a database handle. It is used to store pointers to
   200778 ** all registered FTS5 extensions - tokenizers and auxiliary functions.
   200779 */
   200780 struct Fts5Global {
   200781   fts5_api api;                   /* User visible part of object (see fts5.h) */
   200782   sqlite3 *db;                    /* Associated database connection */
   200783   i64 iNextId;                    /* Used to allocate unique cursor ids */
   200784   Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
   200785   Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
   200786   Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
   200787   Fts5Cursor *pCsr;               /* First in list of all open cursors */
   200788 };
   200789 
   200790 /*
   200791 ** Each auxiliary function registered with the FTS5 module is represented
   200792 ** by an object of the following type. All such objects are stored as part
   200793 ** of the Fts5Global.pAux list.
   200794 */
   200795 struct Fts5Auxiliary {
   200796   Fts5Global *pGlobal;            /* Global context for this function */
   200797   char *zFunc;                    /* Function name (nul-terminated) */
   200798   void *pUserData;                /* User-data pointer */
   200799   fts5_extension_function xFunc;  /* Callback function */
   200800   void (*xDestroy)(void*);        /* Destructor function */
   200801   Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
   200802 };
   200803 
   200804 /*
   200805 ** Each tokenizer module registered with the FTS5 module is represented
   200806 ** by an object of the following type. All such objects are stored as part
   200807 ** of the Fts5Global.pTok list.
   200808 */
   200809 struct Fts5TokenizerModule {
   200810   char *zName;                    /* Name of tokenizer */
   200811   void *pUserData;                /* User pointer passed to xCreate() */
   200812   fts5_tokenizer x;               /* Tokenizer functions */
   200813   void (*xDestroy)(void*);        /* Destructor function */
   200814   Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
   200815 };
   200816 
   200817 /*
   200818 ** Virtual-table object.
   200819 */
   200820 struct Fts5Table {
   200821   sqlite3_vtab base;              /* Base class used by SQLite core */
   200822   Fts5Config *pConfig;            /* Virtual table configuration */
   200823   Fts5Index *pIndex;              /* Full-text index */
   200824   Fts5Storage *pStorage;          /* Document store */
   200825   Fts5Global *pGlobal;            /* Global (connection wide) data */
   200826   Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
   200827 #ifdef SQLITE_DEBUG
   200828   struct Fts5TransactionState ts;
   200829 #endif
   200830 };
   200831 
   200832 struct Fts5MatchPhrase {
   200833   Fts5Buffer *pPoslist;           /* Pointer to current poslist */
   200834   int nTerm;                      /* Size of phrase in terms */
   200835 };
   200836 
   200837 /*
   200838 ** pStmt:
   200839 **   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
   200840 **
   200841 ** aIdx[]:
   200842 **   There is one entry in the aIdx[] array for each phrase in the query,
   200843 **   the value of which is the offset within aPoslist[] following the last
   200844 **   byte of the position list for the corresponding phrase.
   200845 */
   200846 struct Fts5Sorter {
   200847   sqlite3_stmt *pStmt;
   200848   i64 iRowid;                     /* Current rowid */
   200849   const u8 *aPoslist;             /* Position lists for current row */
   200850   int nIdx;                       /* Number of entries in aIdx[] */
   200851   int aIdx[1];                    /* Offsets into aPoslist for current row */
   200852 };
   200853 
   200854 
   200855 /*
   200856 ** Virtual-table cursor object.
   200857 **
   200858 ** iSpecial:
   200859 **   If this is a 'special' query (refer to function fts5SpecialMatch()),
   200860 **   then this variable contains the result of the query.
   200861 **
   200862 ** iFirstRowid, iLastRowid:
   200863 **   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
   200864 **   cursor iterates in ascending order of rowids, iFirstRowid is the lower
   200865 **   limit of rowids to return, and iLastRowid the upper. In other words, the
   200866 **   WHERE clause in the user's query might have been:
   200867 **
   200868 **       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
   200869 **
   200870 **   If the cursor iterates in descending order of rowid, iFirstRowid
   200871 **   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
   200872 **   the lower.
   200873 */
   200874 struct Fts5Cursor {
   200875   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   200876   Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
   200877   int *aColumnSize;               /* Values for xColumnSize() */
   200878   i64 iCsrId;                     /* Cursor id */
   200879 
   200880   /* Zero from this point onwards on cursor reset */
   200881   int ePlan;                      /* FTS5_PLAN_XXX value */
   200882   int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
   200883   i64 iFirstRowid;                /* Return no rowids earlier than this */
   200884   i64 iLastRowid;                 /* Return no rowids later than this */
   200885   sqlite3_stmt *pStmt;            /* Statement used to read %_content */
   200886   Fts5Expr *pExpr;                /* Expression for MATCH queries */
   200887   Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
   200888   int csrflags;                   /* Mask of cursor flags (see below) */
   200889   i64 iSpecial;                   /* Result of special query */
   200890 
   200891   /* "rank" function. Populated on demand from vtab.xColumn(). */
   200892   char *zRank;                    /* Custom rank function */
   200893   char *zRankArgs;                /* Custom rank function args */
   200894   Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
   200895   int nRankArg;                   /* Number of trailing arguments for rank() */
   200896   sqlite3_value **apRankArg;      /* Array of trailing arguments */
   200897   sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
   200898 
   200899   /* Auxiliary data storage */
   200900   Fts5Auxiliary *pAux;            /* Currently executing extension function */
   200901   Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
   200902 
   200903   /* Cache used by auxiliary functions xInst() and xInstCount() */
   200904   Fts5PoslistReader *aInstIter;   /* One for each phrase */
   200905   int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
   200906   int nInstCount;                 /* Number of phrase instances */
   200907   int *aInst;                     /* 3 integers per phrase instance */
   200908 };
   200909 
   200910 /*
   200911 ** Bits that make up the "idxNum" parameter passed indirectly by
   200912 ** xBestIndex() to xFilter().
   200913 */
   200914 #define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
   200915 #define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
   200916 #define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
   200917 #define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
   200918 #define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
   200919 
   200920 #define FTS5_BI_ORDER_RANK   0x0020
   200921 #define FTS5_BI_ORDER_ROWID  0x0040
   200922 #define FTS5_BI_ORDER_DESC   0x0080
   200923 
   200924 /*
   200925 ** Values for Fts5Cursor.csrflags
   200926 */
   200927 #define FTS5CSR_EOF               0x01
   200928 #define FTS5CSR_REQUIRE_CONTENT   0x02
   200929 #define FTS5CSR_REQUIRE_DOCSIZE   0x04
   200930 #define FTS5CSR_REQUIRE_INST      0x08
   200931 #define FTS5CSR_FREE_ZRANK        0x10
   200932 #define FTS5CSR_REQUIRE_RESEEK    0x20
   200933 #define FTS5CSR_REQUIRE_POSLIST   0x40
   200934 
   200935 #define BitFlagAllTest(x,y) (((x) & (y))==(y))
   200936 #define BitFlagTest(x,y)    (((x) & (y))!=0)
   200937 
   200938 
   200939 /*
   200940 ** Macros to Set(), Clear() and Test() cursor flags.
   200941 */
   200942 #define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
   200943 #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
   200944 #define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
   200945 
   200946 struct Fts5Auxdata {
   200947   Fts5Auxiliary *pAux;            /* Extension to which this belongs */
   200948   void *pPtr;                     /* Pointer value */
   200949   void(*xDelete)(void*);          /* Destructor */
   200950   Fts5Auxdata *pNext;             /* Next object in linked list */
   200951 };
   200952 
   200953 #ifdef SQLITE_DEBUG
   200954 #define FTS5_BEGIN      1
   200955 #define FTS5_SYNC       2
   200956 #define FTS5_COMMIT     3
   200957 #define FTS5_ROLLBACK   4
   200958 #define FTS5_SAVEPOINT  5
   200959 #define FTS5_RELEASE    6
   200960 #define FTS5_ROLLBACKTO 7
   200961 static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
   200962   switch( op ){
   200963     case FTS5_BEGIN:
   200964       assert( p->ts.eState==0 );
   200965       p->ts.eState = 1;
   200966       p->ts.iSavepoint = -1;
   200967       break;
   200968 
   200969     case FTS5_SYNC:
   200970       assert( p->ts.eState==1 );
   200971       p->ts.eState = 2;
   200972       break;
   200973 
   200974     case FTS5_COMMIT:
   200975       assert( p->ts.eState==2 );
   200976       p->ts.eState = 0;
   200977       break;
   200978 
   200979     case FTS5_ROLLBACK:
   200980       assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
   200981       p->ts.eState = 0;
   200982       break;
   200983 
   200984     case FTS5_SAVEPOINT:
   200985       assert( p->ts.eState==1 );
   200986       assert( iSavepoint>=0 );
   200987       assert( iSavepoint>p->ts.iSavepoint );
   200988       p->ts.iSavepoint = iSavepoint;
   200989       break;
   200990 
   200991     case FTS5_RELEASE:
   200992       assert( p->ts.eState==1 );
   200993       assert( iSavepoint>=0 );
   200994       assert( iSavepoint<=p->ts.iSavepoint );
   200995       p->ts.iSavepoint = iSavepoint-1;
   200996       break;
   200997 
   200998     case FTS5_ROLLBACKTO:
   200999       assert( p->ts.eState==1 );
   201000       assert( iSavepoint>=0 );
   201001       assert( iSavepoint<=p->ts.iSavepoint );
   201002       p->ts.iSavepoint = iSavepoint;
   201003       break;
   201004   }
   201005 }
   201006 #else
   201007 # define fts5CheckTransactionState(x,y,z)
   201008 #endif
   201009 
   201010 /*
   201011 ** Return true if pTab is a contentless table.
   201012 */
   201013 static int fts5IsContentless(Fts5Table *pTab){
   201014   return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
   201015 }
   201016 
   201017 /*
   201018 ** Delete a virtual table handle allocated by fts5InitVtab().
   201019 */
   201020 static void fts5FreeVtab(Fts5Table *pTab){
   201021   if( pTab ){
   201022     sqlite3Fts5IndexClose(pTab->pIndex);
   201023     sqlite3Fts5StorageClose(pTab->pStorage);
   201024     sqlite3Fts5ConfigFree(pTab->pConfig);
   201025     sqlite3_free(pTab);
   201026   }
   201027 }
   201028 
   201029 /*
   201030 ** The xDisconnect() virtual table method.
   201031 */
   201032 static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
   201033   fts5FreeVtab((Fts5Table*)pVtab);
   201034   return SQLITE_OK;
   201035 }
   201036 
   201037 /*
   201038 ** The xDestroy() virtual table method.
   201039 */
   201040 static int fts5DestroyMethod(sqlite3_vtab *pVtab){
   201041   Fts5Table *pTab = (Fts5Table*)pVtab;
   201042   int rc = sqlite3Fts5DropAll(pTab->pConfig);
   201043   if( rc==SQLITE_OK ){
   201044     fts5FreeVtab((Fts5Table*)pVtab);
   201045   }
   201046   return rc;
   201047 }
   201048 
   201049 /*
   201050 ** This function is the implementation of both the xConnect and xCreate
   201051 ** methods of the FTS3 virtual table.
   201052 **
   201053 ** The argv[] array contains the following:
   201054 **
   201055 **   argv[0]   -> module name  ("fts5")
   201056 **   argv[1]   -> database name
   201057 **   argv[2]   -> table name
   201058 **   argv[...] -> "column name" and other module argument fields.
   201059 */
   201060 static int fts5InitVtab(
   201061   int bCreate,                    /* True for xCreate, false for xConnect */
   201062   sqlite3 *db,                    /* The SQLite database connection */
   201063   void *pAux,                     /* Hash table containing tokenizers */
   201064   int argc,                       /* Number of elements in argv array */
   201065   const char * const *argv,       /* xCreate/xConnect argument array */
   201066   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   201067   char **pzErr                    /* Write any error message here */
   201068 ){
   201069   Fts5Global *pGlobal = (Fts5Global*)pAux;
   201070   const char **azConfig = (const char**)argv;
   201071   int rc = SQLITE_OK;             /* Return code */
   201072   Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
   201073   Fts5Table *pTab = 0;            /* New virtual table object */
   201074 
   201075   /* Allocate the new vtab object and parse the configuration */
   201076   pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
   201077   if( rc==SQLITE_OK ){
   201078     rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
   201079     assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
   201080   }
   201081   if( rc==SQLITE_OK ){
   201082     pTab->pConfig = pConfig;
   201083     pTab->pGlobal = pGlobal;
   201084   }
   201085 
   201086   /* Open the index sub-system */
   201087   if( rc==SQLITE_OK ){
   201088     rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
   201089   }
   201090 
   201091   /* Open the storage sub-system */
   201092   if( rc==SQLITE_OK ){
   201093     rc = sqlite3Fts5StorageOpen(
   201094         pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
   201095     );
   201096   }
   201097 
   201098   /* Call sqlite3_declare_vtab() */
   201099   if( rc==SQLITE_OK ){
   201100     rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
   201101   }
   201102 
   201103   /* Load the initial configuration */
   201104   if( rc==SQLITE_OK ){
   201105     assert( pConfig->pzErrmsg==0 );
   201106     pConfig->pzErrmsg = pzErr;
   201107     rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
   201108     sqlite3Fts5IndexRollback(pTab->pIndex);
   201109     pConfig->pzErrmsg = 0;
   201110   }
   201111 
   201112   if( rc!=SQLITE_OK ){
   201113     fts5FreeVtab(pTab);
   201114     pTab = 0;
   201115   }else if( bCreate ){
   201116     fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
   201117   }
   201118   *ppVTab = (sqlite3_vtab*)pTab;
   201119   return rc;
   201120 }
   201121 
   201122 /*
   201123 ** The xConnect() and xCreate() methods for the virtual table. All the
   201124 ** work is done in function fts5InitVtab().
   201125 */
   201126 static int fts5ConnectMethod(
   201127   sqlite3 *db,                    /* Database connection */
   201128   void *pAux,                     /* Pointer to tokenizer hash table */
   201129   int argc,                       /* Number of elements in argv array */
   201130   const char * const *argv,       /* xCreate/xConnect argument array */
   201131   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   201132   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   201133 ){
   201134   return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   201135 }
   201136 static int fts5CreateMethod(
   201137   sqlite3 *db,                    /* Database connection */
   201138   void *pAux,                     /* Pointer to tokenizer hash table */
   201139   int argc,                       /* Number of elements in argv array */
   201140   const char * const *argv,       /* xCreate/xConnect argument array */
   201141   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   201142   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   201143 ){
   201144   return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
   201145 }
   201146 
   201147 /*
   201148 ** The different query plans.
   201149 */
   201150 #define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
   201151 #define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
   201152 #define FTS5_PLAN_SPECIAL        3       /* An internal query */
   201153 #define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
   201154 #define FTS5_PLAN_SCAN           5       /* No usable constraint */
   201155 #define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
   201156 
   201157 /*
   201158 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
   201159 ** extension is currently being used by a version of SQLite too old to
   201160 ** support index-info flags. In that case this function is a no-op.
   201161 */
   201162 static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
   201163 #if SQLITE_VERSION_NUMBER>=3008012
   201164 #ifndef SQLITE_CORE
   201165   if( sqlite3_libversion_number()>=3008012 )
   201166 #endif
   201167   {
   201168     pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
   201169   }
   201170 #endif
   201171 }
   201172 
   201173 /*
   201174 ** Implementation of the xBestIndex method for FTS5 tables. Within the
   201175 ** WHERE constraint, it searches for the following:
   201176 **
   201177 **   1. A MATCH constraint against the special column.
   201178 **   2. A MATCH constraint against the "rank" column.
   201179 **   3. An == constraint against the rowid column.
   201180 **   4. A < or <= constraint against the rowid column.
   201181 **   5. A > or >= constraint against the rowid column.
   201182 **
   201183 ** Within the ORDER BY, either:
   201184 **
   201185 **   5. ORDER BY rank [ASC|DESC]
   201186 **   6. ORDER BY rowid [ASC|DESC]
   201187 **
   201188 ** Costs are assigned as follows:
   201189 **
   201190 **  a) If an unusable MATCH operator is present in the WHERE clause, the
   201191 **     cost is unconditionally set to 1e50 (a really big number).
   201192 **
   201193 **  a) If a MATCH operator is present, the cost depends on the other
   201194 **     constraints also present. As follows:
   201195 **
   201196 **       * No other constraints:         cost=1000.0
   201197 **       * One rowid range constraint:   cost=750.0
   201198 **       * Both rowid range constraints: cost=500.0
   201199 **       * An == rowid constraint:       cost=100.0
   201200 **
   201201 **  b) Otherwise, if there is no MATCH:
   201202 **
   201203 **       * No other constraints:         cost=1000000.0
   201204 **       * One rowid range constraint:   cost=750000.0
   201205 **       * Both rowid range constraints: cost=250000.0
   201206 **       * An == rowid constraint:       cost=10.0
   201207 **
   201208 ** Costs are not modified by the ORDER BY clause.
   201209 */
   201210 static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   201211   Fts5Table *pTab = (Fts5Table*)pVTab;
   201212   Fts5Config *pConfig = pTab->pConfig;
   201213   const int nCol = pConfig->nCol;
   201214   int idxFlags = 0;               /* Parameter passed through to xFilter() */
   201215   int bHasMatch;
   201216   int iNext;
   201217   int i;
   201218 
   201219   struct Constraint {
   201220     int op;                       /* Mask against sqlite3_index_constraint.op */
   201221     int fts5op;                   /* FTS5 mask for idxFlags */
   201222     int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
   201223     int omit;                     /* True to omit this if found */
   201224     int iConsIndex;               /* Index in pInfo->aConstraint[] */
   201225   } aConstraint[] = {
   201226     {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
   201227                                     FTS5_BI_MATCH,    1, 1, -1},
   201228     {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
   201229                                     FTS5_BI_RANK,     2, 1, -1},
   201230     {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
   201231     {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
   201232                                     FTS5_BI_ROWID_LE, 0, 0, -1},
   201233     {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
   201234                                     FTS5_BI_ROWID_GE, 0, 0, -1},
   201235   };
   201236 
   201237   int aColMap[3];
   201238   aColMap[0] = -1;
   201239   aColMap[1] = nCol;
   201240   aColMap[2] = nCol+1;
   201241 
   201242   /* Set idxFlags flags for all WHERE clause terms that will be used. */
   201243   for(i=0; i<pInfo->nConstraint; i++){
   201244     struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
   201245     int iCol = p->iColumn;
   201246 
   201247     if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
   201248      || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
   201249     ){
   201250       /* A MATCH operator or equivalent */
   201251       if( p->usable ){
   201252         idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
   201253         aConstraint[0].iConsIndex = i;
   201254       }else{
   201255         /* As there exists an unusable MATCH constraint this is an
   201256         ** unusable plan. Set a prohibitively high cost. */
   201257         pInfo->estimatedCost = 1e50;
   201258         return SQLITE_OK;
   201259       }
   201260     }else{
   201261       int j;
   201262       for(j=1; j<ArraySize(aConstraint); j++){
   201263         struct Constraint *pC = &aConstraint[j];
   201264         if( iCol==aColMap[pC->iCol] && p->op & pC->op && p->usable ){
   201265           pC->iConsIndex = i;
   201266           idxFlags |= pC->fts5op;
   201267         }
   201268       }
   201269     }
   201270   }
   201271 
   201272   /* Set idxFlags flags for the ORDER BY clause */
   201273   if( pInfo->nOrderBy==1 ){
   201274     int iSort = pInfo->aOrderBy[0].iColumn;
   201275     if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
   201276       idxFlags |= FTS5_BI_ORDER_RANK;
   201277     }else if( iSort==-1 ){
   201278       idxFlags |= FTS5_BI_ORDER_ROWID;
   201279     }
   201280     if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
   201281       pInfo->orderByConsumed = 1;
   201282       if( pInfo->aOrderBy[0].desc ){
   201283         idxFlags |= FTS5_BI_ORDER_DESC;
   201284       }
   201285     }
   201286   }
   201287 
   201288   /* Calculate the estimated cost based on the flags set in idxFlags. */
   201289   bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
   201290   if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
   201291     pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
   201292     if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
   201293   }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
   201294     pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
   201295   }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
   201296     pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
   201297   }else{
   201298     pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
   201299   }
   201300 
   201301   /* Assign argvIndex values to each constraint in use. */
   201302   iNext = 1;
   201303   for(i=0; i<ArraySize(aConstraint); i++){
   201304     struct Constraint *pC = &aConstraint[i];
   201305     if( pC->iConsIndex>=0 ){
   201306       pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
   201307       pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
   201308     }
   201309   }
   201310 
   201311   pInfo->idxNum = idxFlags;
   201312   return SQLITE_OK;
   201313 }
   201314 
   201315 static int fts5NewTransaction(Fts5Table *pTab){
   201316   Fts5Cursor *pCsr;
   201317   for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
   201318     if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
   201319   }
   201320   return sqlite3Fts5StorageReset(pTab->pStorage);
   201321 }
   201322 
   201323 /*
   201324 ** Implementation of xOpen method.
   201325 */
   201326 static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   201327   Fts5Table *pTab = (Fts5Table*)pVTab;
   201328   Fts5Config *pConfig = pTab->pConfig;
   201329   Fts5Cursor *pCsr = 0;           /* New cursor object */
   201330   int nByte;                      /* Bytes of space to allocate */
   201331   int rc;                         /* Return code */
   201332 
   201333   rc = fts5NewTransaction(pTab);
   201334   if( rc==SQLITE_OK ){
   201335     nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
   201336     pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
   201337     if( pCsr ){
   201338       Fts5Global *pGlobal = pTab->pGlobal;
   201339       memset(pCsr, 0, nByte);
   201340       pCsr->aColumnSize = (int*)&pCsr[1];
   201341       pCsr->pNext = pGlobal->pCsr;
   201342       pGlobal->pCsr = pCsr;
   201343       pCsr->iCsrId = ++pGlobal->iNextId;
   201344     }else{
   201345       rc = SQLITE_NOMEM;
   201346     }
   201347   }
   201348   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
   201349   return rc;
   201350 }
   201351 
   201352 static int fts5StmtType(Fts5Cursor *pCsr){
   201353   if( pCsr->ePlan==FTS5_PLAN_SCAN ){
   201354     return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
   201355   }
   201356   return FTS5_STMT_LOOKUP;
   201357 }
   201358 
   201359 /*
   201360 ** This function is called after the cursor passed as the only argument
   201361 ** is moved to point at a different row. It clears all cached data
   201362 ** specific to the previous row stored by the cursor object.
   201363 */
   201364 static void fts5CsrNewrow(Fts5Cursor *pCsr){
   201365   CsrFlagSet(pCsr,
   201366       FTS5CSR_REQUIRE_CONTENT
   201367     | FTS5CSR_REQUIRE_DOCSIZE
   201368     | FTS5CSR_REQUIRE_INST
   201369     | FTS5CSR_REQUIRE_POSLIST
   201370   );
   201371 }
   201372 
   201373 static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
   201374   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   201375   Fts5Auxdata *pData;
   201376   Fts5Auxdata *pNext;
   201377 
   201378   sqlite3_free(pCsr->aInstIter);
   201379   sqlite3_free(pCsr->aInst);
   201380   if( pCsr->pStmt ){
   201381     int eStmt = fts5StmtType(pCsr);
   201382     sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
   201383   }
   201384   if( pCsr->pSorter ){
   201385     Fts5Sorter *pSorter = pCsr->pSorter;
   201386     sqlite3_finalize(pSorter->pStmt);
   201387     sqlite3_free(pSorter);
   201388   }
   201389 
   201390   if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
   201391     sqlite3Fts5ExprFree(pCsr->pExpr);
   201392   }
   201393 
   201394   for(pData=pCsr->pAuxdata; pData; pData=pNext){
   201395     pNext = pData->pNext;
   201396     if( pData->xDelete ) pData->xDelete(pData->pPtr);
   201397     sqlite3_free(pData);
   201398   }
   201399 
   201400   sqlite3_finalize(pCsr->pRankArgStmt);
   201401   sqlite3_free(pCsr->apRankArg);
   201402 
   201403   if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
   201404     sqlite3_free(pCsr->zRank);
   201405     sqlite3_free(pCsr->zRankArgs);
   201406   }
   201407 
   201408   memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
   201409 }
   201410 
   201411 
   201412 /*
   201413 ** Close the cursor.  For additional information see the documentation
   201414 ** on the xClose method of the virtual table interface.
   201415 */
   201416 static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
   201417   if( pCursor ){
   201418     Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
   201419     Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   201420     Fts5Cursor **pp;
   201421 
   201422     fts5FreeCursorComponents(pCsr);
   201423     /* Remove the cursor from the Fts5Global.pCsr list */
   201424     for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
   201425     *pp = pCsr->pNext;
   201426 
   201427     sqlite3_free(pCsr);
   201428   }
   201429   return SQLITE_OK;
   201430 }
   201431 
   201432 static int fts5SorterNext(Fts5Cursor *pCsr){
   201433   Fts5Sorter *pSorter = pCsr->pSorter;
   201434   int rc;
   201435 
   201436   rc = sqlite3_step(pSorter->pStmt);
   201437   if( rc==SQLITE_DONE ){
   201438     rc = SQLITE_OK;
   201439     CsrFlagSet(pCsr, FTS5CSR_EOF);
   201440   }else if( rc==SQLITE_ROW ){
   201441     const u8 *a;
   201442     const u8 *aBlob;
   201443     int nBlob;
   201444     int i;
   201445     int iOff = 0;
   201446     rc = SQLITE_OK;
   201447 
   201448     pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
   201449     nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
   201450     aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
   201451 
   201452     /* nBlob==0 in detail=none mode. */
   201453     if( nBlob>0 ){
   201454       for(i=0; i<(pSorter->nIdx-1); i++){
   201455         int iVal;
   201456         a += fts5GetVarint32(a, iVal);
   201457         iOff += iVal;
   201458         pSorter->aIdx[i] = iOff;
   201459       }
   201460       pSorter->aIdx[i] = &aBlob[nBlob] - a;
   201461       pSorter->aPoslist = a;
   201462     }
   201463 
   201464     fts5CsrNewrow(pCsr);
   201465   }
   201466 
   201467   return rc;
   201468 }
   201469 
   201470 
   201471 /*
   201472 ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
   201473 ** open on table pTab.
   201474 */
   201475 static void fts5TripCursors(Fts5Table *pTab){
   201476   Fts5Cursor *pCsr;
   201477   for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
   201478     if( pCsr->ePlan==FTS5_PLAN_MATCH
   201479      && pCsr->base.pVtab==(sqlite3_vtab*)pTab
   201480     ){
   201481       CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
   201482     }
   201483   }
   201484 }
   201485 
   201486 /*
   201487 ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
   201488 ** argument, close and reopen all Fts5IndexIter iterators that the cursor
   201489 ** is using. Then attempt to move the cursor to a rowid equal to or laster
   201490 ** (in the cursors sort order - ASC or DESC) than the current rowid.
   201491 **
   201492 ** If the new rowid is not equal to the old, set output parameter *pbSkip
   201493 ** to 1 before returning. Otherwise, leave it unchanged.
   201494 **
   201495 ** Return SQLITE_OK if successful or if no reseek was required, or an
   201496 ** error code if an error occurred.
   201497 */
   201498 static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
   201499   int rc = SQLITE_OK;
   201500   assert( *pbSkip==0 );
   201501   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
   201502     Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   201503     int bDesc = pCsr->bDesc;
   201504     i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
   201505 
   201506     rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
   201507     if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
   201508       *pbSkip = 1;
   201509     }
   201510 
   201511     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
   201512     fts5CsrNewrow(pCsr);
   201513     if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
   201514       CsrFlagSet(pCsr, FTS5CSR_EOF);
   201515       *pbSkip = 1;
   201516     }
   201517   }
   201518   return rc;
   201519 }
   201520 
   201521 
   201522 /*
   201523 ** Advance the cursor to the next row in the table that matches the
   201524 ** search criteria.
   201525 **
   201526 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
   201527 ** even if we reach end-of-file.  The fts5EofMethod() will be called
   201528 ** subsequently to determine whether or not an EOF was hit.
   201529 */
   201530 static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
   201531   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   201532   int rc;
   201533 
   201534   assert( (pCsr->ePlan<3)==
   201535           (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
   201536   );
   201537   assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
   201538 
   201539   if( pCsr->ePlan<3 ){
   201540     int bSkip = 0;
   201541     if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
   201542     rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
   201543     CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
   201544     fts5CsrNewrow(pCsr);
   201545   }else{
   201546     switch( pCsr->ePlan ){
   201547       case FTS5_PLAN_SPECIAL: {
   201548         CsrFlagSet(pCsr, FTS5CSR_EOF);
   201549         rc = SQLITE_OK;
   201550         break;
   201551       }
   201552 
   201553       case FTS5_PLAN_SORTED_MATCH: {
   201554         rc = fts5SorterNext(pCsr);
   201555         break;
   201556       }
   201557 
   201558       default:
   201559         rc = sqlite3_step(pCsr->pStmt);
   201560         if( rc!=SQLITE_ROW ){
   201561           CsrFlagSet(pCsr, FTS5CSR_EOF);
   201562           rc = sqlite3_reset(pCsr->pStmt);
   201563         }else{
   201564           rc = SQLITE_OK;
   201565         }
   201566         break;
   201567     }
   201568   }
   201569 
   201570   return rc;
   201571 }
   201572 
   201573 
   201574 static int fts5PrepareStatement(
   201575   sqlite3_stmt **ppStmt,
   201576   Fts5Config *pConfig,
   201577   const char *zFmt,
   201578   ...
   201579 ){
   201580   sqlite3_stmt *pRet = 0;
   201581   int rc;
   201582   char *zSql;
   201583   va_list ap;
   201584 
   201585   va_start(ap, zFmt);
   201586   zSql = sqlite3_vmprintf(zFmt, ap);
   201587   if( zSql==0 ){
   201588     rc = SQLITE_NOMEM;
   201589   }else{
   201590     rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
   201591                             SQLITE_PREPARE_PERSISTENT, &pRet, 0);
   201592     if( rc!=SQLITE_OK ){
   201593       *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
   201594     }
   201595     sqlite3_free(zSql);
   201596   }
   201597 
   201598   va_end(ap);
   201599   *ppStmt = pRet;
   201600   return rc;
   201601 }
   201602 
   201603 static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
   201604   Fts5Config *pConfig = pTab->pConfig;
   201605   Fts5Sorter *pSorter;
   201606   int nPhrase;
   201607   int nByte;
   201608   int rc;
   201609   const char *zRank = pCsr->zRank;
   201610   const char *zRankArgs = pCsr->zRankArgs;
   201611 
   201612   nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
   201613   nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
   201614   pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
   201615   if( pSorter==0 ) return SQLITE_NOMEM;
   201616   memset(pSorter, 0, nByte);
   201617   pSorter->nIdx = nPhrase;
   201618 
   201619   /* TODO: It would be better to have some system for reusing statement
   201620   ** handles here, rather than preparing a new one for each query. But that
   201621   ** is not possible as SQLite reference counts the virtual table objects.
   201622   ** And since the statement required here reads from this very virtual
   201623   ** table, saving it creates a circular reference.
   201624   **
   201625   ** If SQLite a built-in statement cache, this wouldn't be a problem. */
   201626   rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
   201627       "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
   201628       pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
   201629       (zRankArgs ? ", " : ""),
   201630       (zRankArgs ? zRankArgs : ""),
   201631       bDesc ? "DESC" : "ASC"
   201632   );
   201633 
   201634   pCsr->pSorter = pSorter;
   201635   if( rc==SQLITE_OK ){
   201636     assert( pTab->pSortCsr==0 );
   201637     pTab->pSortCsr = pCsr;
   201638     rc = fts5SorterNext(pCsr);
   201639     pTab->pSortCsr = 0;
   201640   }
   201641 
   201642   if( rc!=SQLITE_OK ){
   201643     sqlite3_finalize(pSorter->pStmt);
   201644     sqlite3_free(pSorter);
   201645     pCsr->pSorter = 0;
   201646   }
   201647 
   201648   return rc;
   201649 }
   201650 
   201651 static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
   201652   int rc;
   201653   Fts5Expr *pExpr = pCsr->pExpr;
   201654   rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
   201655   if( sqlite3Fts5ExprEof(pExpr) ){
   201656     CsrFlagSet(pCsr, FTS5CSR_EOF);
   201657   }
   201658   fts5CsrNewrow(pCsr);
   201659   return rc;
   201660 }
   201661 
   201662 /*
   201663 ** Process a "special" query. A special query is identified as one with a
   201664 ** MATCH expression that begins with a '*' character. The remainder of
   201665 ** the text passed to the MATCH operator are used as  the special query
   201666 ** parameters.
   201667 */
   201668 static int fts5SpecialMatch(
   201669   Fts5Table *pTab,
   201670   Fts5Cursor *pCsr,
   201671   const char *zQuery
   201672 ){
   201673   int rc = SQLITE_OK;             /* Return code */
   201674   const char *z = zQuery;         /* Special query text */
   201675   int n;                          /* Number of bytes in text at z */
   201676 
   201677   while( z[0]==' ' ) z++;
   201678   for(n=0; z[n] && z[n]!=' '; n++);
   201679 
   201680   assert( pTab->base.zErrMsg==0 );
   201681   pCsr->ePlan = FTS5_PLAN_SPECIAL;
   201682 
   201683   if( 0==sqlite3_strnicmp("reads", z, n) ){
   201684     pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
   201685   }
   201686   else if( 0==sqlite3_strnicmp("id", z, n) ){
   201687     pCsr->iSpecial = pCsr->iCsrId;
   201688   }
   201689   else{
   201690     /* An unrecognized directive. Return an error message. */
   201691     pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
   201692     rc = SQLITE_ERROR;
   201693   }
   201694 
   201695   return rc;
   201696 }
   201697 
   201698 /*
   201699 ** Search for an auxiliary function named zName that can be used with table
   201700 ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
   201701 ** structure. Otherwise, if no such function exists, return NULL.
   201702 */
   201703 static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
   201704   Fts5Auxiliary *pAux;
   201705 
   201706   for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
   201707     if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
   201708   }
   201709 
   201710   /* No function of the specified name was found. Return 0. */
   201711   return 0;
   201712 }
   201713 
   201714 
   201715 static int fts5FindRankFunction(Fts5Cursor *pCsr){
   201716   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   201717   Fts5Config *pConfig = pTab->pConfig;
   201718   int rc = SQLITE_OK;
   201719   Fts5Auxiliary *pAux = 0;
   201720   const char *zRank = pCsr->zRank;
   201721   const char *zRankArgs = pCsr->zRankArgs;
   201722 
   201723   if( zRankArgs ){
   201724     char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
   201725     if( zSql ){
   201726       sqlite3_stmt *pStmt = 0;
   201727       rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
   201728                               SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
   201729       sqlite3_free(zSql);
   201730       assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
   201731       if( rc==SQLITE_OK ){
   201732         if( SQLITE_ROW==sqlite3_step(pStmt) ){
   201733           int nByte;
   201734           pCsr->nRankArg = sqlite3_column_count(pStmt);
   201735           nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
   201736           pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
   201737           if( rc==SQLITE_OK ){
   201738             int i;
   201739             for(i=0; i<pCsr->nRankArg; i++){
   201740               pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
   201741             }
   201742           }
   201743           pCsr->pRankArgStmt = pStmt;
   201744         }else{
   201745           rc = sqlite3_finalize(pStmt);
   201746           assert( rc!=SQLITE_OK );
   201747         }
   201748       }
   201749     }
   201750   }
   201751 
   201752   if( rc==SQLITE_OK ){
   201753     pAux = fts5FindAuxiliary(pTab, zRank);
   201754     if( pAux==0 ){
   201755       assert( pTab->base.zErrMsg==0 );
   201756       pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
   201757       rc = SQLITE_ERROR;
   201758     }
   201759   }
   201760 
   201761   pCsr->pRank = pAux;
   201762   return rc;
   201763 }
   201764 
   201765 
   201766 static int fts5CursorParseRank(
   201767   Fts5Config *pConfig,
   201768   Fts5Cursor *pCsr,
   201769   sqlite3_value *pRank
   201770 ){
   201771   int rc = SQLITE_OK;
   201772   if( pRank ){
   201773     const char *z = (const char*)sqlite3_value_text(pRank);
   201774     char *zRank = 0;
   201775     char *zRankArgs = 0;
   201776 
   201777     if( z==0 ){
   201778       if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
   201779     }else{
   201780       rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
   201781     }
   201782     if( rc==SQLITE_OK ){
   201783       pCsr->zRank = zRank;
   201784       pCsr->zRankArgs = zRankArgs;
   201785       CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
   201786     }else if( rc==SQLITE_ERROR ){
   201787       pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
   201788           "parse error in rank function: %s", z
   201789       );
   201790     }
   201791   }else{
   201792     if( pConfig->zRank ){
   201793       pCsr->zRank = (char*)pConfig->zRank;
   201794       pCsr->zRankArgs = (char*)pConfig->zRankArgs;
   201795     }else{
   201796       pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
   201797       pCsr->zRankArgs = 0;
   201798     }
   201799   }
   201800   return rc;
   201801 }
   201802 
   201803 static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
   201804   if( pVal ){
   201805     int eType = sqlite3_value_numeric_type(pVal);
   201806     if( eType==SQLITE_INTEGER ){
   201807       return sqlite3_value_int64(pVal);
   201808     }
   201809   }
   201810   return iDefault;
   201811 }
   201812 
   201813 /*
   201814 ** This is the xFilter interface for the virtual table.  See
   201815 ** the virtual table xFilter method documentation for additional
   201816 ** information.
   201817 **
   201818 ** There are three possible query strategies:
   201819 **
   201820 **   1. Full-text search using a MATCH operator.
   201821 **   2. A by-rowid lookup.
   201822 **   3. A full-table scan.
   201823 */
   201824 static int fts5FilterMethod(
   201825   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   201826   int idxNum,                     /* Strategy index */
   201827   const char *zUnused,            /* Unused */
   201828   int nVal,                       /* Number of elements in apVal */
   201829   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   201830 ){
   201831   Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
   201832   Fts5Config *pConfig = pTab->pConfig;
   201833   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   201834   int rc = SQLITE_OK;             /* Error code */
   201835   int iVal = 0;                   /* Counter for apVal[] */
   201836   int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
   201837   int bOrderByRank;               /* True if ORDER BY rank */
   201838   sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
   201839   sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
   201840   sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
   201841   sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
   201842   sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
   201843   int iCol;                       /* Column on LHS of MATCH operator */
   201844   char **pzErrmsg = pConfig->pzErrmsg;
   201845 
   201846   UNUSED_PARAM(zUnused);
   201847   UNUSED_PARAM(nVal);
   201848 
   201849   if( pCsr->ePlan ){
   201850     fts5FreeCursorComponents(pCsr);
   201851     memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
   201852   }
   201853 
   201854   assert( pCsr->pStmt==0 );
   201855   assert( pCsr->pExpr==0 );
   201856   assert( pCsr->csrflags==0 );
   201857   assert( pCsr->pRank==0 );
   201858   assert( pCsr->zRank==0 );
   201859   assert( pCsr->zRankArgs==0 );
   201860 
   201861   assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
   201862   pConfig->pzErrmsg = &pTab->base.zErrMsg;
   201863 
   201864   /* Decode the arguments passed through to this function.
   201865   **
   201866   ** Note: The following set of if(...) statements must be in the same
   201867   ** order as the corresponding entries in the struct at the top of
   201868   ** fts5BestIndexMethod().  */
   201869   if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
   201870   if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
   201871   if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
   201872   if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
   201873   if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
   201874   iCol = (idxNum>>16);
   201875   assert( iCol>=0 && iCol<=pConfig->nCol );
   201876   assert( iVal==nVal );
   201877   bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
   201878   pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
   201879 
   201880   /* Set the cursor upper and lower rowid limits. Only some strategies
   201881   ** actually use them. This is ok, as the xBestIndex() method leaves the
   201882   ** sqlite3_index_constraint.omit flag clear for range constraints
   201883   ** on the rowid field.  */
   201884   if( pRowidEq ){
   201885     pRowidLe = pRowidGe = pRowidEq;
   201886   }
   201887   if( bDesc ){
   201888     pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
   201889     pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
   201890   }else{
   201891     pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
   201892     pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
   201893   }
   201894 
   201895   if( pTab->pSortCsr ){
   201896     /* If pSortCsr is non-NULL, then this call is being made as part of
   201897     ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
   201898     ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
   201899     ** return results to the user for this query. The current cursor
   201900     ** (pCursor) is used to execute the query issued by function
   201901     ** fts5CursorFirstSorted() above.  */
   201902     assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
   201903     assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
   201904     assert( pCsr->iLastRowid==LARGEST_INT64 );
   201905     assert( pCsr->iFirstRowid==SMALLEST_INT64 );
   201906     pCsr->ePlan = FTS5_PLAN_SOURCE;
   201907     pCsr->pExpr = pTab->pSortCsr->pExpr;
   201908     rc = fts5CursorFirst(pTab, pCsr, bDesc);
   201909   }else if( pMatch ){
   201910     const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
   201911     if( zExpr==0 ) zExpr = "";
   201912 
   201913     rc = fts5CursorParseRank(pConfig, pCsr, pRank);
   201914     if( rc==SQLITE_OK ){
   201915       if( zExpr[0]=='*' ){
   201916         /* The user has issued a query of the form "MATCH '*...'". This
   201917         ** indicates that the MATCH expression is not a full text query,
   201918         ** but a request for an internal parameter.  */
   201919         rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
   201920       }else{
   201921         char **pzErr = &pTab->base.zErrMsg;
   201922         rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
   201923         if( rc==SQLITE_OK ){
   201924           if( bOrderByRank ){
   201925             pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
   201926             rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
   201927           }else{
   201928             pCsr->ePlan = FTS5_PLAN_MATCH;
   201929             rc = fts5CursorFirst(pTab, pCsr, bDesc);
   201930           }
   201931         }
   201932       }
   201933     }
   201934   }else if( pConfig->zContent==0 ){
   201935     *pConfig->pzErrmsg = sqlite3_mprintf(
   201936         "%s: table does not support scanning", pConfig->zName
   201937     );
   201938     rc = SQLITE_ERROR;
   201939   }else{
   201940     /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
   201941     ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
   201942     pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
   201943     rc = sqlite3Fts5StorageStmt(
   201944         pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
   201945     );
   201946     if( rc==SQLITE_OK ){
   201947       if( pCsr->ePlan==FTS5_PLAN_ROWID ){
   201948         sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
   201949       }else{
   201950         sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
   201951         sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
   201952       }
   201953       rc = fts5NextMethod(pCursor);
   201954     }
   201955   }
   201956 
   201957   pConfig->pzErrmsg = pzErrmsg;
   201958   return rc;
   201959 }
   201960 
   201961 /*
   201962 ** This is the xEof method of the virtual table. SQLite calls this
   201963 ** routine to find out if it has reached the end of a result set.
   201964 */
   201965 static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
   201966   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   201967   return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
   201968 }
   201969 
   201970 /*
   201971 ** Return the rowid that the cursor currently points to.
   201972 */
   201973 static i64 fts5CursorRowid(Fts5Cursor *pCsr){
   201974   assert( pCsr->ePlan==FTS5_PLAN_MATCH
   201975        || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
   201976        || pCsr->ePlan==FTS5_PLAN_SOURCE
   201977   );
   201978   if( pCsr->pSorter ){
   201979     return pCsr->pSorter->iRowid;
   201980   }else{
   201981     return sqlite3Fts5ExprRowid(pCsr->pExpr);
   201982   }
   201983 }
   201984 
   201985 /*
   201986 ** This is the xRowid method. The SQLite core calls this routine to
   201987 ** retrieve the rowid for the current row of the result set. fts5
   201988 ** exposes %_content.rowid as the rowid for the virtual table. The
   201989 ** rowid should be written to *pRowid.
   201990 */
   201991 static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   201992   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   201993   int ePlan = pCsr->ePlan;
   201994 
   201995   assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
   201996   switch( ePlan ){
   201997     case FTS5_PLAN_SPECIAL:
   201998       *pRowid = 0;
   201999       break;
   202000 
   202001     case FTS5_PLAN_SOURCE:
   202002     case FTS5_PLAN_MATCH:
   202003     case FTS5_PLAN_SORTED_MATCH:
   202004       *pRowid = fts5CursorRowid(pCsr);
   202005       break;
   202006 
   202007     default:
   202008       *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
   202009       break;
   202010   }
   202011 
   202012   return SQLITE_OK;
   202013 }
   202014 
   202015 /*
   202016 ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
   202017 ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
   202018 **
   202019 ** If argument bErrormsg is true and an error occurs, an error message may
   202020 ** be left in sqlite3_vtab.zErrMsg.
   202021 */
   202022 static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
   202023   int rc = SQLITE_OK;
   202024 
   202025   /* If the cursor does not yet have a statement handle, obtain one now. */
   202026   if( pCsr->pStmt==0 ){
   202027     Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   202028     int eStmt = fts5StmtType(pCsr);
   202029     rc = sqlite3Fts5StorageStmt(
   202030         pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
   202031     );
   202032     assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
   202033     assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
   202034   }
   202035 
   202036   if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
   202037     assert( pCsr->pExpr );
   202038     sqlite3_reset(pCsr->pStmt);
   202039     sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
   202040     rc = sqlite3_step(pCsr->pStmt);
   202041     if( rc==SQLITE_ROW ){
   202042       rc = SQLITE_OK;
   202043       CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
   202044     }else{
   202045       rc = sqlite3_reset(pCsr->pStmt);
   202046       if( rc==SQLITE_OK ){
   202047         rc = FTS5_CORRUPT;
   202048       }
   202049     }
   202050   }
   202051   return rc;
   202052 }
   202053 
   202054 static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
   202055   va_list ap;                     /* ... printf arguments */
   202056   va_start(ap, zFormat);
   202057   assert( p->base.zErrMsg==0 );
   202058   p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
   202059   va_end(ap);
   202060 }
   202061 
   202062 /*
   202063 ** This function is called to handle an FTS INSERT command. In other words,
   202064 ** an INSERT statement of the form:
   202065 **
   202066 **     INSERT INTO fts(fts) VALUES($pCmd)
   202067 **     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
   202068 **
   202069 ** Argument pVal is the value assigned to column "fts" by the INSERT
   202070 ** statement. This function returns SQLITE_OK if successful, or an SQLite
   202071 ** error code if an error occurs.
   202072 **
   202073 ** The commands implemented by this function are documented in the "Special
   202074 ** INSERT Directives" section of the documentation. It should be updated if
   202075 ** more commands are added to this function.
   202076 */
   202077 static int fts5SpecialInsert(
   202078   Fts5Table *pTab,                /* Fts5 table object */
   202079   const char *zCmd,               /* Text inserted into table-name column */
   202080   sqlite3_value *pVal             /* Value inserted into rank column */
   202081 ){
   202082   Fts5Config *pConfig = pTab->pConfig;
   202083   int rc = SQLITE_OK;
   202084   int bError = 0;
   202085 
   202086   if( 0==sqlite3_stricmp("delete-all", zCmd) ){
   202087     if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
   202088       fts5SetVtabError(pTab,
   202089           "'delete-all' may only be used with a "
   202090           "contentless or external content fts5 table"
   202091       );
   202092       rc = SQLITE_ERROR;
   202093     }else{
   202094       rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
   202095     }
   202096   }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
   202097     if( pConfig->eContent==FTS5_CONTENT_NONE ){
   202098       fts5SetVtabError(pTab,
   202099           "'rebuild' may not be used with a contentless fts5 table"
   202100       );
   202101       rc = SQLITE_ERROR;
   202102     }else{
   202103       rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
   202104     }
   202105   }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
   202106     rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
   202107   }else if( 0==sqlite3_stricmp("merge", zCmd) ){
   202108     int nMerge = sqlite3_value_int(pVal);
   202109     rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
   202110   }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
   202111     rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
   202112 #ifdef SQLITE_DEBUG
   202113   }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
   202114     pConfig->bPrefixIndex = sqlite3_value_int(pVal);
   202115 #endif
   202116   }else{
   202117     rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
   202118     if( rc==SQLITE_OK ){
   202119       rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
   202120     }
   202121     if( rc==SQLITE_OK ){
   202122       if( bError ){
   202123         rc = SQLITE_ERROR;
   202124       }else{
   202125         rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
   202126       }
   202127     }
   202128   }
   202129   return rc;
   202130 }
   202131 
   202132 static int fts5SpecialDelete(
   202133   Fts5Table *pTab,
   202134   sqlite3_value **apVal
   202135 ){
   202136   int rc = SQLITE_OK;
   202137   int eType1 = sqlite3_value_type(apVal[1]);
   202138   if( eType1==SQLITE_INTEGER ){
   202139     sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
   202140     rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
   202141   }
   202142   return rc;
   202143 }
   202144 
   202145 static void fts5StorageInsert(
   202146   int *pRc,
   202147   Fts5Table *pTab,
   202148   sqlite3_value **apVal,
   202149   i64 *piRowid
   202150 ){
   202151   int rc = *pRc;
   202152   if( rc==SQLITE_OK ){
   202153     rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
   202154   }
   202155   if( rc==SQLITE_OK ){
   202156     rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
   202157   }
   202158   *pRc = rc;
   202159 }
   202160 
   202161 /*
   202162 ** This function is the implementation of the xUpdate callback used by
   202163 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   202164 ** inserted, updated or deleted.
   202165 **
   202166 ** A delete specifies a single argument - the rowid of the row to remove.
   202167 **
   202168 ** Update and insert operations pass:
   202169 **
   202170 **   1. The "old" rowid, or NULL.
   202171 **   2. The "new" rowid.
   202172 **   3. Values for each of the nCol matchable columns.
   202173 **   4. Values for the two hidden columns (<tablename> and "rank").
   202174 */
   202175 static int fts5UpdateMethod(
   202176   sqlite3_vtab *pVtab,            /* Virtual table handle */
   202177   int nArg,                       /* Size of argument array */
   202178   sqlite3_value **apVal,          /* Array of arguments */
   202179   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   202180 ){
   202181   Fts5Table *pTab = (Fts5Table*)pVtab;
   202182   Fts5Config *pConfig = pTab->pConfig;
   202183   int eType0;                     /* value_type() of apVal[0] */
   202184   int rc = SQLITE_OK;             /* Return code */
   202185 
   202186   /* A transaction must be open when this is called. */
   202187   assert( pTab->ts.eState==1 );
   202188 
   202189   assert( pVtab->zErrMsg==0 );
   202190   assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
   202191   assert( nArg==1
   202192       || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
   202193       || sqlite3_value_type(apVal[1])==SQLITE_NULL
   202194   );
   202195   assert( pTab->pConfig->pzErrmsg==0 );
   202196   pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
   202197 
   202198   /* Put any active cursors into REQUIRE_SEEK state. */
   202199   fts5TripCursors(pTab);
   202200 
   202201   eType0 = sqlite3_value_type(apVal[0]);
   202202   if( eType0==SQLITE_NULL
   202203    && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
   202204   ){
   202205     /* A "special" INSERT op. These are handled separately. */
   202206     const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
   202207     if( pConfig->eContent!=FTS5_CONTENT_NORMAL
   202208       && 0==sqlite3_stricmp("delete", z)
   202209     ){
   202210       rc = fts5SpecialDelete(pTab, apVal);
   202211     }else{
   202212       rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
   202213     }
   202214   }else{
   202215     /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
   202216     ** any conflict on the rowid value must be detected before any
   202217     ** modifications are made to the database file. There are 4 cases:
   202218     **
   202219     **   1) DELETE
   202220     **   2) UPDATE (rowid not modified)
   202221     **   3) UPDATE (rowid modified)
   202222     **   4) INSERT
   202223     **
   202224     ** Cases 3 and 4 may violate the rowid constraint.
   202225     */
   202226     int eConflict = SQLITE_ABORT;
   202227     if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
   202228       eConflict = sqlite3_vtab_on_conflict(pConfig->db);
   202229     }
   202230 
   202231     assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
   202232     assert( nArg!=1 || eType0==SQLITE_INTEGER );
   202233 
   202234     /* Filter out attempts to run UPDATE or DELETE on contentless tables.
   202235     ** This is not suported.  */
   202236     if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
   202237       pTab->base.zErrMsg = sqlite3_mprintf(
   202238           "cannot %s contentless fts5 table: %s",
   202239           (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
   202240       );
   202241       rc = SQLITE_ERROR;
   202242     }
   202243 
   202244     /* DELETE */
   202245     else if( nArg==1 ){
   202246       i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
   202247       rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
   202248     }
   202249 
   202250     /* INSERT */
   202251     else if( eType0!=SQLITE_INTEGER ){
   202252       /* If this is a REPLACE, first remove the current entry (if any) */
   202253       if( eConflict==SQLITE_REPLACE
   202254        && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
   202255       ){
   202256         i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
   202257         rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
   202258       }
   202259       fts5StorageInsert(&rc, pTab, apVal, pRowid);
   202260     }
   202261 
   202262     /* UPDATE */
   202263     else{
   202264       i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
   202265       i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
   202266       if( iOld!=iNew ){
   202267         if( eConflict==SQLITE_REPLACE ){
   202268           rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
   202269           if( rc==SQLITE_OK ){
   202270             rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
   202271           }
   202272           fts5StorageInsert(&rc, pTab, apVal, pRowid);
   202273         }else{
   202274           rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
   202275           if( rc==SQLITE_OK ){
   202276             rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
   202277           }
   202278           if( rc==SQLITE_OK ){
   202279             rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
   202280           }
   202281         }
   202282       }else{
   202283         rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
   202284         fts5StorageInsert(&rc, pTab, apVal, pRowid);
   202285       }
   202286     }
   202287   }
   202288 
   202289   pTab->pConfig->pzErrmsg = 0;
   202290   return rc;
   202291 }
   202292 
   202293 /*
   202294 ** Implementation of xSync() method.
   202295 */
   202296 static int fts5SyncMethod(sqlite3_vtab *pVtab){
   202297   int rc;
   202298   Fts5Table *pTab = (Fts5Table*)pVtab;
   202299   fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
   202300   pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
   202301   fts5TripCursors(pTab);
   202302   rc = sqlite3Fts5StorageSync(pTab->pStorage);
   202303   pTab->pConfig->pzErrmsg = 0;
   202304   return rc;
   202305 }
   202306 
   202307 /*
   202308 ** Implementation of xBegin() method.
   202309 */
   202310 static int fts5BeginMethod(sqlite3_vtab *pVtab){
   202311   fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
   202312   fts5NewTransaction((Fts5Table*)pVtab);
   202313   return SQLITE_OK;
   202314 }
   202315 
   202316 /*
   202317 ** Implementation of xCommit() method. This is a no-op. The contents of
   202318 ** the pending-terms hash-table have already been flushed into the database
   202319 ** by fts5SyncMethod().
   202320 */
   202321 static int fts5CommitMethod(sqlite3_vtab *pVtab){
   202322   UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
   202323   fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
   202324   return SQLITE_OK;
   202325 }
   202326 
   202327 /*
   202328 ** Implementation of xRollback(). Discard the contents of the pending-terms
   202329 ** hash-table. Any changes made to the database are reverted by SQLite.
   202330 */
   202331 static int fts5RollbackMethod(sqlite3_vtab *pVtab){
   202332   int rc;
   202333   Fts5Table *pTab = (Fts5Table*)pVtab;
   202334   fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
   202335   rc = sqlite3Fts5StorageRollback(pTab->pStorage);
   202336   return rc;
   202337 }
   202338 
   202339 static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
   202340 
   202341 static void *fts5ApiUserData(Fts5Context *pCtx){
   202342   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202343   return pCsr->pAux->pUserData;
   202344 }
   202345 
   202346 static int fts5ApiColumnCount(Fts5Context *pCtx){
   202347   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202348   return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
   202349 }
   202350 
   202351 static int fts5ApiColumnTotalSize(
   202352   Fts5Context *pCtx,
   202353   int iCol,
   202354   sqlite3_int64 *pnToken
   202355 ){
   202356   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202357   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   202358   return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
   202359 }
   202360 
   202361 static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
   202362   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202363   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   202364   return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
   202365 }
   202366 
   202367 static int fts5ApiTokenize(
   202368   Fts5Context *pCtx,
   202369   const char *pText, int nText,
   202370   void *pUserData,
   202371   int (*xToken)(void*, int, const char*, int, int, int)
   202372 ){
   202373   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202374   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   202375   return sqlite3Fts5Tokenize(
   202376       pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
   202377   );
   202378 }
   202379 
   202380 static int fts5ApiPhraseCount(Fts5Context *pCtx){
   202381   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202382   return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
   202383 }
   202384 
   202385 static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
   202386   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202387   return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
   202388 }
   202389 
   202390 static int fts5ApiColumnText(
   202391   Fts5Context *pCtx,
   202392   int iCol,
   202393   const char **pz,
   202394   int *pn
   202395 ){
   202396   int rc = SQLITE_OK;
   202397   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202398   if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
   202399     *pz = 0;
   202400     *pn = 0;
   202401   }else{
   202402     rc = fts5SeekCursor(pCsr, 0);
   202403     if( rc==SQLITE_OK ){
   202404       *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
   202405       *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   202406     }
   202407   }
   202408   return rc;
   202409 }
   202410 
   202411 static int fts5CsrPoslist(
   202412   Fts5Cursor *pCsr,
   202413   int iPhrase,
   202414   const u8 **pa,
   202415   int *pn
   202416 ){
   202417   Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
   202418   int rc = SQLITE_OK;
   202419   int bLive = (pCsr->pSorter==0);
   202420 
   202421   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
   202422 
   202423     if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
   202424       Fts5PoslistPopulator *aPopulator;
   202425       int i;
   202426       aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
   202427       if( aPopulator==0 ) rc = SQLITE_NOMEM;
   202428       for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
   202429         int n; const char *z;
   202430         rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
   202431         if( rc==SQLITE_OK ){
   202432           rc = sqlite3Fts5ExprPopulatePoslists(
   202433               pConfig, pCsr->pExpr, aPopulator, i, z, n
   202434           );
   202435         }
   202436       }
   202437       sqlite3_free(aPopulator);
   202438 
   202439       if( pCsr->pSorter ){
   202440         sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
   202441       }
   202442     }
   202443     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
   202444   }
   202445 
   202446   if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
   202447     Fts5Sorter *pSorter = pCsr->pSorter;
   202448     int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
   202449     *pn = pSorter->aIdx[iPhrase] - i1;
   202450     *pa = &pSorter->aPoslist[i1];
   202451   }else{
   202452     *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
   202453   }
   202454 
   202455   return rc;
   202456 }
   202457 
   202458 /*
   202459 ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
   202460 ** correctly for the current view. Return SQLITE_OK if successful, or an
   202461 ** SQLite error code otherwise.
   202462 */
   202463 static int fts5CacheInstArray(Fts5Cursor *pCsr){
   202464   int rc = SQLITE_OK;
   202465   Fts5PoslistReader *aIter;       /* One iterator for each phrase */
   202466   int nIter;                      /* Number of iterators/phrases */
   202467 
   202468   nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
   202469   if( pCsr->aInstIter==0 ){
   202470     int nByte = sizeof(Fts5PoslistReader) * nIter;
   202471     pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
   202472   }
   202473   aIter = pCsr->aInstIter;
   202474 
   202475   if( aIter ){
   202476     int nInst = 0;                /* Number instances seen so far */
   202477     int i;
   202478 
   202479     /* Initialize all iterators */
   202480     for(i=0; i<nIter && rc==SQLITE_OK; i++){
   202481       const u8 *a;
   202482       int n;
   202483       rc = fts5CsrPoslist(pCsr, i, &a, &n);
   202484       if( rc==SQLITE_OK ){
   202485         sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
   202486       }
   202487     }
   202488 
   202489     if( rc==SQLITE_OK ){
   202490       while( 1 ){
   202491         int *aInst;
   202492         int iBest = -1;
   202493         for(i=0; i<nIter; i++){
   202494           if( (aIter[i].bEof==0)
   202495               && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
   202496             ){
   202497             iBest = i;
   202498           }
   202499         }
   202500         if( iBest<0 ) break;
   202501 
   202502         nInst++;
   202503         if( nInst>=pCsr->nInstAlloc ){
   202504           pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
   202505           aInst = (int*)sqlite3_realloc(
   202506               pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
   202507               );
   202508           if( aInst ){
   202509             pCsr->aInst = aInst;
   202510           }else{
   202511             rc = SQLITE_NOMEM;
   202512             break;
   202513           }
   202514         }
   202515 
   202516         aInst = &pCsr->aInst[3 * (nInst-1)];
   202517         aInst[0] = iBest;
   202518         aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
   202519         aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
   202520         sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
   202521       }
   202522     }
   202523 
   202524     pCsr->nInstCount = nInst;
   202525     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
   202526   }
   202527   return rc;
   202528 }
   202529 
   202530 static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
   202531   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202532   int rc = SQLITE_OK;
   202533   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
   202534    || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
   202535     *pnInst = pCsr->nInstCount;
   202536   }
   202537   return rc;
   202538 }
   202539 
   202540 static int fts5ApiInst(
   202541   Fts5Context *pCtx,
   202542   int iIdx,
   202543   int *piPhrase,
   202544   int *piCol,
   202545   int *piOff
   202546 ){
   202547   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202548   int rc = SQLITE_OK;
   202549   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
   202550    || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
   202551   ){
   202552     if( iIdx<0 || iIdx>=pCsr->nInstCount ){
   202553       rc = SQLITE_RANGE;
   202554 #if 0
   202555     }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
   202556       *piPhrase = pCsr->aInst[iIdx*3];
   202557       *piCol = pCsr->aInst[iIdx*3 + 2];
   202558       *piOff = -1;
   202559 #endif
   202560     }else{
   202561       *piPhrase = pCsr->aInst[iIdx*3];
   202562       *piCol = pCsr->aInst[iIdx*3 + 1];
   202563       *piOff = pCsr->aInst[iIdx*3 + 2];
   202564     }
   202565   }
   202566   return rc;
   202567 }
   202568 
   202569 static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
   202570   return fts5CursorRowid((Fts5Cursor*)pCtx);
   202571 }
   202572 
   202573 static int fts5ColumnSizeCb(
   202574   void *pContext,                 /* Pointer to int */
   202575   int tflags,
   202576   const char *pUnused,            /* Buffer containing token */
   202577   int nUnused,                    /* Size of token in bytes */
   202578   int iUnused1,                   /* Start offset of token */
   202579   int iUnused2                    /* End offset of token */
   202580 ){
   202581   int *pCnt = (int*)pContext;
   202582   UNUSED_PARAM2(pUnused, nUnused);
   202583   UNUSED_PARAM2(iUnused1, iUnused2);
   202584   if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
   202585     (*pCnt)++;
   202586   }
   202587   return SQLITE_OK;
   202588 }
   202589 
   202590 static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
   202591   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202592   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   202593   Fts5Config *pConfig = pTab->pConfig;
   202594   int rc = SQLITE_OK;
   202595 
   202596   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
   202597     if( pConfig->bColumnsize ){
   202598       i64 iRowid = fts5CursorRowid(pCsr);
   202599       rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
   202600     }else if( pConfig->zContent==0 ){
   202601       int i;
   202602       for(i=0; i<pConfig->nCol; i++){
   202603         if( pConfig->abUnindexed[i]==0 ){
   202604           pCsr->aColumnSize[i] = -1;
   202605         }
   202606       }
   202607     }else{
   202608       int i;
   202609       for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
   202610         if( pConfig->abUnindexed[i]==0 ){
   202611           const char *z; int n;
   202612           void *p = (void*)(&pCsr->aColumnSize[i]);
   202613           pCsr->aColumnSize[i] = 0;
   202614           rc = fts5ApiColumnText(pCtx, i, &z, &n);
   202615           if( rc==SQLITE_OK ){
   202616             rc = sqlite3Fts5Tokenize(
   202617                 pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
   202618             );
   202619           }
   202620         }
   202621       }
   202622     }
   202623     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
   202624   }
   202625   if( iCol<0 ){
   202626     int i;
   202627     *pnToken = 0;
   202628     for(i=0; i<pConfig->nCol; i++){
   202629       *pnToken += pCsr->aColumnSize[i];
   202630     }
   202631   }else if( iCol<pConfig->nCol ){
   202632     *pnToken = pCsr->aColumnSize[iCol];
   202633   }else{
   202634     *pnToken = 0;
   202635     rc = SQLITE_RANGE;
   202636   }
   202637   return rc;
   202638 }
   202639 
   202640 /*
   202641 ** Implementation of the xSetAuxdata() method.
   202642 */
   202643 static int fts5ApiSetAuxdata(
   202644   Fts5Context *pCtx,              /* Fts5 context */
   202645   void *pPtr,                     /* Pointer to save as auxdata */
   202646   void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
   202647 ){
   202648   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202649   Fts5Auxdata *pData;
   202650 
   202651   /* Search through the cursors list of Fts5Auxdata objects for one that
   202652   ** corresponds to the currently executing auxiliary function.  */
   202653   for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
   202654     if( pData->pAux==pCsr->pAux ) break;
   202655   }
   202656 
   202657   if( pData ){
   202658     if( pData->xDelete ){
   202659       pData->xDelete(pData->pPtr);
   202660     }
   202661   }else{
   202662     int rc = SQLITE_OK;
   202663     pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
   202664     if( pData==0 ){
   202665       if( xDelete ) xDelete(pPtr);
   202666       return rc;
   202667     }
   202668     pData->pAux = pCsr->pAux;
   202669     pData->pNext = pCsr->pAuxdata;
   202670     pCsr->pAuxdata = pData;
   202671   }
   202672 
   202673   pData->xDelete = xDelete;
   202674   pData->pPtr = pPtr;
   202675   return SQLITE_OK;
   202676 }
   202677 
   202678 static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
   202679   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202680   Fts5Auxdata *pData;
   202681   void *pRet = 0;
   202682 
   202683   for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
   202684     if( pData->pAux==pCsr->pAux ) break;
   202685   }
   202686 
   202687   if( pData ){
   202688     pRet = pData->pPtr;
   202689     if( bClear ){
   202690       pData->pPtr = 0;
   202691       pData->xDelete = 0;
   202692     }
   202693   }
   202694 
   202695   return pRet;
   202696 }
   202697 
   202698 static void fts5ApiPhraseNext(
   202699   Fts5Context *pUnused,
   202700   Fts5PhraseIter *pIter,
   202701   int *piCol, int *piOff
   202702 ){
   202703   UNUSED_PARAM(pUnused);
   202704   if( pIter->a>=pIter->b ){
   202705     *piCol = -1;
   202706     *piOff = -1;
   202707   }else{
   202708     int iVal;
   202709     pIter->a += fts5GetVarint32(pIter->a, iVal);
   202710     if( iVal==1 ){
   202711       pIter->a += fts5GetVarint32(pIter->a, iVal);
   202712       *piCol = iVal;
   202713       *piOff = 0;
   202714       pIter->a += fts5GetVarint32(pIter->a, iVal);
   202715     }
   202716     *piOff += (iVal-2);
   202717   }
   202718 }
   202719 
   202720 static int fts5ApiPhraseFirst(
   202721   Fts5Context *pCtx,
   202722   int iPhrase,
   202723   Fts5PhraseIter *pIter,
   202724   int *piCol, int *piOff
   202725 ){
   202726   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202727   int n;
   202728   int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
   202729   if( rc==SQLITE_OK ){
   202730     pIter->b = &pIter->a[n];
   202731     *piCol = 0;
   202732     *piOff = 0;
   202733     fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
   202734   }
   202735   return rc;
   202736 }
   202737 
   202738 static void fts5ApiPhraseNextColumn(
   202739   Fts5Context *pCtx,
   202740   Fts5PhraseIter *pIter,
   202741   int *piCol
   202742 ){
   202743   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202744   Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
   202745 
   202746   if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
   202747     if( pIter->a>=pIter->b ){
   202748       *piCol = -1;
   202749     }else{
   202750       int iIncr;
   202751       pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
   202752       *piCol += (iIncr-2);
   202753     }
   202754   }else{
   202755     while( 1 ){
   202756       int dummy;
   202757       if( pIter->a>=pIter->b ){
   202758         *piCol = -1;
   202759         return;
   202760       }
   202761       if( pIter->a[0]==0x01 ) break;
   202762       pIter->a += fts5GetVarint32(pIter->a, dummy);
   202763     }
   202764     pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
   202765   }
   202766 }
   202767 
   202768 static int fts5ApiPhraseFirstColumn(
   202769   Fts5Context *pCtx,
   202770   int iPhrase,
   202771   Fts5PhraseIter *pIter,
   202772   int *piCol
   202773 ){
   202774   int rc = SQLITE_OK;
   202775   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202776   Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
   202777 
   202778   if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
   202779     Fts5Sorter *pSorter = pCsr->pSorter;
   202780     int n;
   202781     if( pSorter ){
   202782       int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
   202783       n = pSorter->aIdx[iPhrase] - i1;
   202784       pIter->a = &pSorter->aPoslist[i1];
   202785     }else{
   202786       rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
   202787     }
   202788     if( rc==SQLITE_OK ){
   202789       pIter->b = &pIter->a[n];
   202790       *piCol = 0;
   202791       fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
   202792     }
   202793   }else{
   202794     int n;
   202795     rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
   202796     if( rc==SQLITE_OK ){
   202797       pIter->b = &pIter->a[n];
   202798       if( n<=0 ){
   202799         *piCol = -1;
   202800       }else if( pIter->a[0]==0x01 ){
   202801         pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
   202802       }else{
   202803         *piCol = 0;
   202804       }
   202805     }
   202806   }
   202807 
   202808   return rc;
   202809 }
   202810 
   202811 
   202812 static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
   202813     int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
   202814 );
   202815 
   202816 static const Fts5ExtensionApi sFts5Api = {
   202817   2,                            /* iVersion */
   202818   fts5ApiUserData,
   202819   fts5ApiColumnCount,
   202820   fts5ApiRowCount,
   202821   fts5ApiColumnTotalSize,
   202822   fts5ApiTokenize,
   202823   fts5ApiPhraseCount,
   202824   fts5ApiPhraseSize,
   202825   fts5ApiInstCount,
   202826   fts5ApiInst,
   202827   fts5ApiRowid,
   202828   fts5ApiColumnText,
   202829   fts5ApiColumnSize,
   202830   fts5ApiQueryPhrase,
   202831   fts5ApiSetAuxdata,
   202832   fts5ApiGetAuxdata,
   202833   fts5ApiPhraseFirst,
   202834   fts5ApiPhraseNext,
   202835   fts5ApiPhraseFirstColumn,
   202836   fts5ApiPhraseNextColumn,
   202837 };
   202838 
   202839 /*
   202840 ** Implementation of API function xQueryPhrase().
   202841 */
   202842 static int fts5ApiQueryPhrase(
   202843   Fts5Context *pCtx,
   202844   int iPhrase,
   202845   void *pUserData,
   202846   int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
   202847 ){
   202848   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   202849   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
   202850   int rc;
   202851   Fts5Cursor *pNew = 0;
   202852 
   202853   rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
   202854   if( rc==SQLITE_OK ){
   202855     pNew->ePlan = FTS5_PLAN_MATCH;
   202856     pNew->iFirstRowid = SMALLEST_INT64;
   202857     pNew->iLastRowid = LARGEST_INT64;
   202858     pNew->base.pVtab = (sqlite3_vtab*)pTab;
   202859     rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
   202860   }
   202861 
   202862   if( rc==SQLITE_OK ){
   202863     for(rc = fts5CursorFirst(pTab, pNew, 0);
   202864         rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
   202865         rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
   202866     ){
   202867       rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
   202868       if( rc!=SQLITE_OK ){
   202869         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   202870         break;
   202871       }
   202872     }
   202873   }
   202874 
   202875   fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
   202876   return rc;
   202877 }
   202878 
   202879 static void fts5ApiInvoke(
   202880   Fts5Auxiliary *pAux,
   202881   Fts5Cursor *pCsr,
   202882   sqlite3_context *context,
   202883   int argc,
   202884   sqlite3_value **argv
   202885 ){
   202886   assert( pCsr->pAux==0 );
   202887   pCsr->pAux = pAux;
   202888   pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
   202889   pCsr->pAux = 0;
   202890 }
   202891 
   202892 static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
   202893   Fts5Cursor *pCsr;
   202894   for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
   202895     if( pCsr->iCsrId==iCsrId ) break;
   202896   }
   202897   return pCsr;
   202898 }
   202899 
   202900 static void fts5ApiCallback(
   202901   sqlite3_context *context,
   202902   int argc,
   202903   sqlite3_value **argv
   202904 ){
   202905 
   202906   Fts5Auxiliary *pAux;
   202907   Fts5Cursor *pCsr;
   202908   i64 iCsrId;
   202909 
   202910   assert( argc>=1 );
   202911   pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
   202912   iCsrId = sqlite3_value_int64(argv[0]);
   202913 
   202914   pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
   202915   if( pCsr==0 ){
   202916     char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
   202917     sqlite3_result_error(context, zErr, -1);
   202918     sqlite3_free(zErr);
   202919   }else{
   202920     fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
   202921   }
   202922 }
   202923 
   202924 
   202925 /*
   202926 ** Given cursor id iId, return a pointer to the corresponding Fts5Index
   202927 ** object. Or NULL If the cursor id does not exist.
   202928 **
   202929 ** If successful, set *ppConfig to point to the associated config object
   202930 ** before returning.
   202931 */
   202932 static Fts5Index *sqlite3Fts5IndexFromCsrid(
   202933   Fts5Global *pGlobal,            /* FTS5 global context for db handle */
   202934   i64 iCsrId,                     /* Id of cursor to find */
   202935   Fts5Config **ppConfig           /* OUT: Configuration object */
   202936 ){
   202937   Fts5Cursor *pCsr;
   202938   Fts5Table *pTab;
   202939 
   202940   pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
   202941   pTab = (Fts5Table*)pCsr->base.pVtab;
   202942   *ppConfig = pTab->pConfig;
   202943 
   202944   return pTab->pIndex;
   202945 }
   202946 
   202947 /*
   202948 ** Return a "position-list blob" corresponding to the current position of
   202949 ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
   202950 ** the current position-list for each phrase in the query associated with
   202951 ** cursor pCsr.
   202952 **
   202953 ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
   202954 ** the number of phrases in the query. Following the varints are the
   202955 ** concatenated position lists for each phrase, in order.
   202956 **
   202957 ** The first varint (if it exists) contains the size of the position list
   202958 ** for phrase 0. The second (same disclaimer) contains the size of position
   202959 ** list 1. And so on. There is no size field for the final position list,
   202960 ** as it can be derived from the total size of the blob.
   202961 */
   202962 static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
   202963   int i;
   202964   int rc = SQLITE_OK;
   202965   int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
   202966   Fts5Buffer val;
   202967 
   202968   memset(&val, 0, sizeof(Fts5Buffer));
   202969   switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
   202970     case FTS5_DETAIL_FULL:
   202971 
   202972       /* Append the varints */
   202973       for(i=0; i<(nPhrase-1); i++){
   202974         const u8 *dummy;
   202975         int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
   202976         sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
   202977       }
   202978 
   202979       /* Append the position lists */
   202980       for(i=0; i<nPhrase; i++){
   202981         const u8 *pPoslist;
   202982         int nPoslist;
   202983         nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
   202984         sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
   202985       }
   202986       break;
   202987 
   202988     case FTS5_DETAIL_COLUMNS:
   202989 
   202990       /* Append the varints */
   202991       for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
   202992         const u8 *dummy;
   202993         int nByte;
   202994         rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
   202995         sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
   202996       }
   202997 
   202998       /* Append the position lists */
   202999       for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
   203000         const u8 *pPoslist;
   203001         int nPoslist;
   203002         rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
   203003         sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
   203004       }
   203005       break;
   203006 
   203007     default:
   203008       break;
   203009   }
   203010 
   203011   sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
   203012   return rc;
   203013 }
   203014 
   203015 /*
   203016 ** This is the xColumn method, called by SQLite to request a value from
   203017 ** the row that the supplied cursor currently points to.
   203018 */
   203019 static int fts5ColumnMethod(
   203020   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   203021   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   203022   int iCol                        /* Index of column to read value from */
   203023 ){
   203024   Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
   203025   Fts5Config *pConfig = pTab->pConfig;
   203026   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   203027   int rc = SQLITE_OK;
   203028 
   203029   assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
   203030 
   203031   if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
   203032     if( iCol==pConfig->nCol ){
   203033       sqlite3_result_int64(pCtx, pCsr->iSpecial);
   203034     }
   203035   }else
   203036 
   203037   if( iCol==pConfig->nCol ){
   203038     /* User is requesting the value of the special column with the same name
   203039     ** as the table. Return the cursor integer id number. This value is only
   203040     ** useful in that it may be passed as the first argument to an FTS5
   203041     ** auxiliary function.  */
   203042     sqlite3_result_int64(pCtx, pCsr->iCsrId);
   203043   }else if( iCol==pConfig->nCol+1 ){
   203044 
   203045     /* The value of the "rank" column. */
   203046     if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
   203047       fts5PoslistBlob(pCtx, pCsr);
   203048     }else if(
   203049         pCsr->ePlan==FTS5_PLAN_MATCH
   203050      || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
   203051     ){
   203052       if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
   203053         fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
   203054       }
   203055     }
   203056   }else if( !fts5IsContentless(pTab) ){
   203057     rc = fts5SeekCursor(pCsr, 1);
   203058     if( rc==SQLITE_OK ){
   203059       sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
   203060     }
   203061   }
   203062   return rc;
   203063 }
   203064 
   203065 
   203066 /*
   203067 ** This routine implements the xFindFunction method for the FTS3
   203068 ** virtual table.
   203069 */
   203070 static int fts5FindFunctionMethod(
   203071   sqlite3_vtab *pVtab,            /* Virtual table handle */
   203072   int nUnused,                    /* Number of SQL function arguments */
   203073   const char *zName,              /* Name of SQL function */
   203074   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   203075   void **ppArg                    /* OUT: User data for *pxFunc */
   203076 ){
   203077   Fts5Table *pTab = (Fts5Table*)pVtab;
   203078   Fts5Auxiliary *pAux;
   203079 
   203080   UNUSED_PARAM(nUnused);
   203081   pAux = fts5FindAuxiliary(pTab, zName);
   203082   if( pAux ){
   203083     *pxFunc = fts5ApiCallback;
   203084     *ppArg = (void*)pAux;
   203085     return 1;
   203086   }
   203087 
   203088   /* No function of the specified name was found. Return 0. */
   203089   return 0;
   203090 }
   203091 
   203092 /*
   203093 ** Implementation of FTS5 xRename method. Rename an fts5 table.
   203094 */
   203095 static int fts5RenameMethod(
   203096   sqlite3_vtab *pVtab,            /* Virtual table handle */
   203097   const char *zName               /* New name of table */
   203098 ){
   203099   Fts5Table *pTab = (Fts5Table*)pVtab;
   203100   return sqlite3Fts5StorageRename(pTab->pStorage, zName);
   203101 }
   203102 
   203103 /*
   203104 ** The xSavepoint() method.
   203105 **
   203106 ** Flush the contents of the pending-terms table to disk.
   203107 */
   203108 static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
   203109   Fts5Table *pTab = (Fts5Table*)pVtab;
   203110   UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
   203111   fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
   203112   fts5TripCursors(pTab);
   203113   return sqlite3Fts5StorageSync(pTab->pStorage);
   203114 }
   203115 
   203116 /*
   203117 ** The xRelease() method.
   203118 **
   203119 ** This is a no-op.
   203120 */
   203121 static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
   203122   Fts5Table *pTab = (Fts5Table*)pVtab;
   203123   UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
   203124   fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
   203125   fts5TripCursors(pTab);
   203126   return sqlite3Fts5StorageSync(pTab->pStorage);
   203127 }
   203128 
   203129 /*
   203130 ** The xRollbackTo() method.
   203131 **
   203132 ** Discard the contents of the pending terms table.
   203133 */
   203134 static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
   203135   Fts5Table *pTab = (Fts5Table*)pVtab;
   203136   UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
   203137   fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
   203138   fts5TripCursors(pTab);
   203139   return sqlite3Fts5StorageRollback(pTab->pStorage);
   203140 }
   203141 
   203142 /*
   203143 ** Register a new auxiliary function with global context pGlobal.
   203144 */
   203145 static int fts5CreateAux(
   203146   fts5_api *pApi,                 /* Global context (one per db handle) */
   203147   const char *zName,              /* Name of new function */
   203148   void *pUserData,                /* User data for aux. function */
   203149   fts5_extension_function xFunc,  /* Aux. function implementation */
   203150   void(*xDestroy)(void*)          /* Destructor for pUserData */
   203151 ){
   203152   Fts5Global *pGlobal = (Fts5Global*)pApi;
   203153   int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
   203154   if( rc==SQLITE_OK ){
   203155     Fts5Auxiliary *pAux;
   203156     int nName;                      /* Size of zName in bytes, including \0 */
   203157     int nByte;                      /* Bytes of space to allocate */
   203158 
   203159     nName = (int)strlen(zName) + 1;
   203160     nByte = sizeof(Fts5Auxiliary) + nName;
   203161     pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
   203162     if( pAux ){
   203163       memset(pAux, 0, nByte);
   203164       pAux->zFunc = (char*)&pAux[1];
   203165       memcpy(pAux->zFunc, zName, nName);
   203166       pAux->pGlobal = pGlobal;
   203167       pAux->pUserData = pUserData;
   203168       pAux->xFunc = xFunc;
   203169       pAux->xDestroy = xDestroy;
   203170       pAux->pNext = pGlobal->pAux;
   203171       pGlobal->pAux = pAux;
   203172     }else{
   203173       rc = SQLITE_NOMEM;
   203174     }
   203175   }
   203176 
   203177   return rc;
   203178 }
   203179 
   203180 /*
   203181 ** Register a new tokenizer. This is the implementation of the
   203182 ** fts5_api.xCreateTokenizer() method.
   203183 */
   203184 static int fts5CreateTokenizer(
   203185   fts5_api *pApi,                 /* Global context (one per db handle) */
   203186   const char *zName,              /* Name of new function */
   203187   void *pUserData,                /* User data for aux. function */
   203188   fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
   203189   void(*xDestroy)(void*)          /* Destructor for pUserData */
   203190 ){
   203191   Fts5Global *pGlobal = (Fts5Global*)pApi;
   203192   Fts5TokenizerModule *pNew;
   203193   int nName;                      /* Size of zName and its \0 terminator */
   203194   int nByte;                      /* Bytes of space to allocate */
   203195   int rc = SQLITE_OK;
   203196 
   203197   nName = (int)strlen(zName) + 1;
   203198   nByte = sizeof(Fts5TokenizerModule) + nName;
   203199   pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
   203200   if( pNew ){
   203201     memset(pNew, 0, nByte);
   203202     pNew->zName = (char*)&pNew[1];
   203203     memcpy(pNew->zName, zName, nName);
   203204     pNew->pUserData = pUserData;
   203205     pNew->x = *pTokenizer;
   203206     pNew->xDestroy = xDestroy;
   203207     pNew->pNext = pGlobal->pTok;
   203208     pGlobal->pTok = pNew;
   203209     if( pNew->pNext==0 ){
   203210       pGlobal->pDfltTok = pNew;
   203211     }
   203212   }else{
   203213     rc = SQLITE_NOMEM;
   203214   }
   203215 
   203216   return rc;
   203217 }
   203218 
   203219 static Fts5TokenizerModule *fts5LocateTokenizer(
   203220   Fts5Global *pGlobal,
   203221   const char *zName
   203222 ){
   203223   Fts5TokenizerModule *pMod = 0;
   203224 
   203225   if( zName==0 ){
   203226     pMod = pGlobal->pDfltTok;
   203227   }else{
   203228     for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
   203229       if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
   203230     }
   203231   }
   203232 
   203233   return pMod;
   203234 }
   203235 
   203236 /*
   203237 ** Find a tokenizer. This is the implementation of the
   203238 ** fts5_api.xFindTokenizer() method.
   203239 */
   203240 static int fts5FindTokenizer(
   203241   fts5_api *pApi,                 /* Global context (one per db handle) */
   203242   const char *zName,              /* Name of new function */
   203243   void **ppUserData,
   203244   fts5_tokenizer *pTokenizer      /* Populate this object */
   203245 ){
   203246   int rc = SQLITE_OK;
   203247   Fts5TokenizerModule *pMod;
   203248 
   203249   pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
   203250   if( pMod ){
   203251     *pTokenizer = pMod->x;
   203252     *ppUserData = pMod->pUserData;
   203253   }else{
   203254     memset(pTokenizer, 0, sizeof(fts5_tokenizer));
   203255     rc = SQLITE_ERROR;
   203256   }
   203257 
   203258   return rc;
   203259 }
   203260 
   203261 static int sqlite3Fts5GetTokenizer(
   203262   Fts5Global *pGlobal,
   203263   const char **azArg,
   203264   int nArg,
   203265   Fts5Tokenizer **ppTok,
   203266   fts5_tokenizer **ppTokApi,
   203267   char **pzErr
   203268 ){
   203269   Fts5TokenizerModule *pMod;
   203270   int rc = SQLITE_OK;
   203271 
   203272   pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
   203273   if( pMod==0 ){
   203274     assert( nArg>0 );
   203275     rc = SQLITE_ERROR;
   203276     *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
   203277   }else{
   203278     rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
   203279     *ppTokApi = &pMod->x;
   203280     if( rc!=SQLITE_OK && pzErr ){
   203281       *pzErr = sqlite3_mprintf("error in tokenizer constructor");
   203282     }
   203283   }
   203284 
   203285   if( rc!=SQLITE_OK ){
   203286     *ppTokApi = 0;
   203287     *ppTok = 0;
   203288   }
   203289 
   203290   return rc;
   203291 }
   203292 
   203293 static void fts5ModuleDestroy(void *pCtx){
   203294   Fts5TokenizerModule *pTok, *pNextTok;
   203295   Fts5Auxiliary *pAux, *pNextAux;
   203296   Fts5Global *pGlobal = (Fts5Global*)pCtx;
   203297 
   203298   for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
   203299     pNextAux = pAux->pNext;
   203300     if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
   203301     sqlite3_free(pAux);
   203302   }
   203303 
   203304   for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
   203305     pNextTok = pTok->pNext;
   203306     if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
   203307     sqlite3_free(pTok);
   203308   }
   203309 
   203310   sqlite3_free(pGlobal);
   203311 }
   203312 
   203313 static void fts5Fts5Func(
   203314   sqlite3_context *pCtx,          /* Function call context */
   203315   int nArg,                       /* Number of args */
   203316   sqlite3_value **apArg           /* Function arguments */
   203317 ){
   203318   Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
   203319   fts5_api **ppApi;
   203320   UNUSED_PARAM(nArg);
   203321   assert( nArg==1 );
   203322   ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
   203323   if( ppApi ) *ppApi = &pGlobal->api;
   203324 }
   203325 
   203326 /*
   203327 ** Implementation of fts5_source_id() function.
   203328 */
   203329 static void fts5SourceIdFunc(
   203330   sqlite3_context *pCtx,          /* Function call context */
   203331   int nArg,                       /* Number of args */
   203332   sqlite3_value **apUnused        /* Function arguments */
   203333 ){
   203334   assert( nArg==0 );
   203335   UNUSED_PARAM2(nArg, apUnused);
   203336   sqlite3_result_text(pCtx, "fts5: 2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2171d", -1, SQLITE_TRANSIENT);
   203337 }
   203338 
   203339 static int fts5Init(sqlite3 *db){
   203340   static const sqlite3_module fts5Mod = {
   203341     /* iVersion      */ 2,
   203342     /* xCreate       */ fts5CreateMethod,
   203343     /* xConnect      */ fts5ConnectMethod,
   203344     /* xBestIndex    */ fts5BestIndexMethod,
   203345     /* xDisconnect   */ fts5DisconnectMethod,
   203346     /* xDestroy      */ fts5DestroyMethod,
   203347     /* xOpen         */ fts5OpenMethod,
   203348     /* xClose        */ fts5CloseMethod,
   203349     /* xFilter       */ fts5FilterMethod,
   203350     /* xNext         */ fts5NextMethod,
   203351     /* xEof          */ fts5EofMethod,
   203352     /* xColumn       */ fts5ColumnMethod,
   203353     /* xRowid        */ fts5RowidMethod,
   203354     /* xUpdate       */ fts5UpdateMethod,
   203355     /* xBegin        */ fts5BeginMethod,
   203356     /* xSync         */ fts5SyncMethod,
   203357     /* xCommit       */ fts5CommitMethod,
   203358     /* xRollback     */ fts5RollbackMethod,
   203359     /* xFindFunction */ fts5FindFunctionMethod,
   203360     /* xRename       */ fts5RenameMethod,
   203361     /* xSavepoint    */ fts5SavepointMethod,
   203362     /* xRelease      */ fts5ReleaseMethod,
   203363     /* xRollbackTo   */ fts5RollbackToMethod,
   203364   };
   203365 
   203366   int rc;
   203367   Fts5Global *pGlobal = 0;
   203368 
   203369   pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
   203370   if( pGlobal==0 ){
   203371     rc = SQLITE_NOMEM;
   203372   }else{
   203373     void *p = (void*)pGlobal;
   203374     memset(pGlobal, 0, sizeof(Fts5Global));
   203375     pGlobal->db = db;
   203376     pGlobal->api.iVersion = 2;
   203377     pGlobal->api.xCreateFunction = fts5CreateAux;
   203378     pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
   203379     pGlobal->api.xFindTokenizer = fts5FindTokenizer;
   203380     rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
   203381     if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
   203382     if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
   203383     if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
   203384     if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
   203385     if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
   203386     if( rc==SQLITE_OK ){
   203387       rc = sqlite3_create_function(
   203388           db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
   203389       );
   203390     }
   203391     if( rc==SQLITE_OK ){
   203392       rc = sqlite3_create_function(
   203393           db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
   203394       );
   203395     }
   203396   }
   203397 
   203398   /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
   203399   ** fts5_test_mi.c is compiled and linked into the executable. And call
   203400   ** its entry point to enable the matchinfo() demo.  */
   203401 #ifdef SQLITE_FTS5_ENABLE_TEST_MI
   203402   if( rc==SQLITE_OK ){
   203403     extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
   203404     rc = sqlite3Fts5TestRegisterMatchinfo(db);
   203405   }
   203406 #endif
   203407 
   203408   return rc;
   203409 }
   203410 
   203411 /*
   203412 ** The following functions are used to register the module with SQLite. If
   203413 ** this module is being built as part of the SQLite core (SQLITE_CORE is
   203414 ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
   203415 **
   203416 ** Or, if this module is being built as a loadable extension,
   203417 ** sqlite3Fts5Init() is omitted and the two standard entry points
   203418 ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
   203419 */
   203420 #ifndef SQLITE_CORE
   203421 #ifdef _WIN32
   203422 __declspec(dllexport)
   203423 #endif
   203424 SQLITE_API int sqlite3_fts_init(
   203425   sqlite3 *db,
   203426   char **pzErrMsg,
   203427   const sqlite3_api_routines *pApi
   203428 ){
   203429   SQLITE_EXTENSION_INIT2(pApi);
   203430   (void)pzErrMsg;  /* Unused parameter */
   203431   return fts5Init(db);
   203432 }
   203433 
   203434 #ifdef _WIN32
   203435 __declspec(dllexport)
   203436 #endif
   203437 SQLITE_API int sqlite3_fts5_init(
   203438   sqlite3 *db,
   203439   char **pzErrMsg,
   203440   const sqlite3_api_routines *pApi
   203441 ){
   203442   SQLITE_EXTENSION_INIT2(pApi);
   203443   (void)pzErrMsg;  /* Unused parameter */
   203444   return fts5Init(db);
   203445 }
   203446 #else
   203447 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
   203448   return fts5Init(db);
   203449 }
   203450 #endif
   203451 
   203452 /*
   203453 ** 2014 May 31
   203454 **
   203455 ** The author disclaims copyright to this source code.  In place of
   203456 ** a legal notice, here is a blessing:
   203457 **
   203458 **    May you do good and not evil.
   203459 **    May you find forgiveness for yourself and forgive others.
   203460 **    May you share freely, never taking more than you give.
   203461 **
   203462 ******************************************************************************
   203463 **
   203464 */
   203465 
   203466 
   203467 
   203468 /* #include "fts5Int.h" */
   203469 
   203470 struct Fts5Storage {
   203471   Fts5Config *pConfig;
   203472   Fts5Index *pIndex;
   203473   int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
   203474   i64 nTotalRow;                  /* Total number of rows in FTS table */
   203475   i64 *aTotalSize;                /* Total sizes of each column */
   203476   sqlite3_stmt *aStmt[11];
   203477 };
   203478 
   203479 
   203480 #if FTS5_STMT_SCAN_ASC!=0
   203481 # error "FTS5_STMT_SCAN_ASC mismatch"
   203482 #endif
   203483 #if FTS5_STMT_SCAN_DESC!=1
   203484 # error "FTS5_STMT_SCAN_DESC mismatch"
   203485 #endif
   203486 #if FTS5_STMT_LOOKUP!=2
   203487 # error "FTS5_STMT_LOOKUP mismatch"
   203488 #endif
   203489 
   203490 #define FTS5_STMT_INSERT_CONTENT  3
   203491 #define FTS5_STMT_REPLACE_CONTENT 4
   203492 #define FTS5_STMT_DELETE_CONTENT  5
   203493 #define FTS5_STMT_REPLACE_DOCSIZE  6
   203494 #define FTS5_STMT_DELETE_DOCSIZE  7
   203495 #define FTS5_STMT_LOOKUP_DOCSIZE  8
   203496 #define FTS5_STMT_REPLACE_CONFIG 9
   203497 #define FTS5_STMT_SCAN 10
   203498 
   203499 /*
   203500 ** Prepare the two insert statements - Fts5Storage.pInsertContent and
   203501 ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
   203502 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   203503 ** occurs.
   203504 */
   203505 static int fts5StorageGetStmt(
   203506   Fts5Storage *p,                 /* Storage handle */
   203507   int eStmt,                      /* FTS5_STMT_XXX constant */
   203508   sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
   203509   char **pzErrMsg                 /* OUT: Error message (if any) */
   203510 ){
   203511   int rc = SQLITE_OK;
   203512 
   203513   /* If there is no %_docsize table, there should be no requests for
   203514   ** statements to operate on it.  */
   203515   assert( p->pConfig->bColumnsize || (
   203516         eStmt!=FTS5_STMT_REPLACE_DOCSIZE
   203517      && eStmt!=FTS5_STMT_DELETE_DOCSIZE
   203518      && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
   203519   ));
   203520 
   203521   assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
   203522   if( p->aStmt[eStmt]==0 ){
   203523     const char *azStmt[] = {
   203524       "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
   203525       "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
   203526       "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
   203527 
   203528       "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
   203529       "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
   203530       "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
   203531       "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
   203532       "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
   203533 
   203534       "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
   203535 
   203536       "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
   203537       "SELECT %s FROM %s AS T",                         /* SCAN */
   203538     };
   203539     Fts5Config *pC = p->pConfig;
   203540     char *zSql = 0;
   203541 
   203542     switch( eStmt ){
   203543       case FTS5_STMT_SCAN:
   203544         zSql = sqlite3_mprintf(azStmt[eStmt],
   203545             pC->zContentExprlist, pC->zContent
   203546         );
   203547         break;
   203548 
   203549       case FTS5_STMT_SCAN_ASC:
   203550       case FTS5_STMT_SCAN_DESC:
   203551         zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
   203552             pC->zContent, pC->zContentRowid, pC->zContentRowid,
   203553             pC->zContentRowid
   203554         );
   203555         break;
   203556 
   203557       case FTS5_STMT_LOOKUP:
   203558         zSql = sqlite3_mprintf(azStmt[eStmt],
   203559             pC->zContentExprlist, pC->zContent, pC->zContentRowid
   203560         );
   203561         break;
   203562 
   203563       case FTS5_STMT_INSERT_CONTENT:
   203564       case FTS5_STMT_REPLACE_CONTENT: {
   203565         int nCol = pC->nCol + 1;
   203566         char *zBind;
   203567         int i;
   203568 
   203569         zBind = sqlite3_malloc(1 + nCol*2);
   203570         if( zBind ){
   203571           for(i=0; i<nCol; i++){
   203572             zBind[i*2] = '?';
   203573             zBind[i*2 + 1] = ',';
   203574           }
   203575           zBind[i*2-1] = '\0';
   203576           zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
   203577           sqlite3_free(zBind);
   203578         }
   203579         break;
   203580       }
   203581 
   203582       default:
   203583         zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
   203584         break;
   203585     }
   203586 
   203587     if( zSql==0 ){
   203588       rc = SQLITE_NOMEM;
   203589     }else{
   203590       rc = sqlite3_prepare_v3(pC->db, zSql, -1,
   203591                               SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
   203592       sqlite3_free(zSql);
   203593       if( rc!=SQLITE_OK && pzErrMsg ){
   203594         *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
   203595       }
   203596     }
   203597   }
   203598 
   203599   *ppStmt = p->aStmt[eStmt];
   203600   sqlite3_reset(*ppStmt);
   203601   return rc;
   203602 }
   203603 
   203604 
   203605 static int fts5ExecPrintf(
   203606   sqlite3 *db,
   203607   char **pzErr,
   203608   const char *zFormat,
   203609   ...
   203610 ){
   203611   int rc;
   203612   va_list ap;                     /* ... printf arguments */
   203613   char *zSql;
   203614 
   203615   va_start(ap, zFormat);
   203616   zSql = sqlite3_vmprintf(zFormat, ap);
   203617 
   203618   if( zSql==0 ){
   203619     rc = SQLITE_NOMEM;
   203620   }else{
   203621     rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
   203622     sqlite3_free(zSql);
   203623   }
   203624 
   203625   va_end(ap);
   203626   return rc;
   203627 }
   203628 
   203629 /*
   203630 ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
   203631 ** code otherwise.
   203632 */
   203633 static int sqlite3Fts5DropAll(Fts5Config *pConfig){
   203634   int rc = fts5ExecPrintf(pConfig->db, 0,
   203635       "DROP TABLE IF EXISTS %Q.'%q_data';"
   203636       "DROP TABLE IF EXISTS %Q.'%q_idx';"
   203637       "DROP TABLE IF EXISTS %Q.'%q_config';",
   203638       pConfig->zDb, pConfig->zName,
   203639       pConfig->zDb, pConfig->zName,
   203640       pConfig->zDb, pConfig->zName
   203641   );
   203642   if( rc==SQLITE_OK && pConfig->bColumnsize ){
   203643     rc = fts5ExecPrintf(pConfig->db, 0,
   203644         "DROP TABLE IF EXISTS %Q.'%q_docsize';",
   203645         pConfig->zDb, pConfig->zName
   203646     );
   203647   }
   203648   if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
   203649     rc = fts5ExecPrintf(pConfig->db, 0,
   203650         "DROP TABLE IF EXISTS %Q.'%q_content';",
   203651         pConfig->zDb, pConfig->zName
   203652     );
   203653   }
   203654   return rc;
   203655 }
   203656 
   203657 static void fts5StorageRenameOne(
   203658   Fts5Config *pConfig,            /* Current FTS5 configuration */
   203659   int *pRc,                       /* IN/OUT: Error code */
   203660   const char *zTail,              /* Tail of table name e.g. "data", "config" */
   203661   const char *zName               /* New name of FTS5 table */
   203662 ){
   203663   if( *pRc==SQLITE_OK ){
   203664     *pRc = fts5ExecPrintf(pConfig->db, 0,
   203665         "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
   203666         pConfig->zDb, pConfig->zName, zTail, zName, zTail
   203667     );
   203668   }
   203669 }
   203670 
   203671 static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
   203672   Fts5Config *pConfig = pStorage->pConfig;
   203673   int rc = sqlite3Fts5StorageSync(pStorage);
   203674 
   203675   fts5StorageRenameOne(pConfig, &rc, "data", zName);
   203676   fts5StorageRenameOne(pConfig, &rc, "idx", zName);
   203677   fts5StorageRenameOne(pConfig, &rc, "config", zName);
   203678   if( pConfig->bColumnsize ){
   203679     fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
   203680   }
   203681   if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
   203682     fts5StorageRenameOne(pConfig, &rc, "content", zName);
   203683   }
   203684   return rc;
   203685 }
   203686 
   203687 /*
   203688 ** Create the shadow table named zPost, with definition zDefn. Return
   203689 ** SQLITE_OK if successful, or an SQLite error code otherwise.
   203690 */
   203691 static int sqlite3Fts5CreateTable(
   203692   Fts5Config *pConfig,            /* FTS5 configuration */
   203693   const char *zPost,              /* Shadow table to create (e.g. "content") */
   203694   const char *zDefn,              /* Columns etc. for shadow table */
   203695   int bWithout,                   /* True for without rowid */
   203696   char **pzErr                    /* OUT: Error message */
   203697 ){
   203698   int rc;
   203699   char *zErr = 0;
   203700 
   203701   rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
   203702       pConfig->zDb, pConfig->zName, zPost, zDefn,
   203703 #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
   203704       bWithout?" WITHOUT ROWID":
   203705 #endif
   203706       ""
   203707   );
   203708   if( zErr ){
   203709     *pzErr = sqlite3_mprintf(
   203710         "fts5: error creating shadow table %q_%s: %s",
   203711         pConfig->zName, zPost, zErr
   203712     );
   203713     sqlite3_free(zErr);
   203714   }
   203715 
   203716   return rc;
   203717 }
   203718 
   203719 /*
   203720 ** Open a new Fts5Index handle. If the bCreate argument is true, create
   203721 ** and initialize the underlying tables
   203722 **
   203723 ** If successful, set *pp to point to the new object and return SQLITE_OK.
   203724 ** Otherwise, set *pp to NULL and return an SQLite error code.
   203725 */
   203726 static int sqlite3Fts5StorageOpen(
   203727   Fts5Config *pConfig,
   203728   Fts5Index *pIndex,
   203729   int bCreate,
   203730   Fts5Storage **pp,
   203731   char **pzErr                    /* OUT: Error message */
   203732 ){
   203733   int rc = SQLITE_OK;
   203734   Fts5Storage *p;                 /* New object */
   203735   int nByte;                      /* Bytes of space to allocate */
   203736 
   203737   nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
   203738         + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
   203739   *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
   203740   if( !p ) return SQLITE_NOMEM;
   203741 
   203742   memset(p, 0, nByte);
   203743   p->aTotalSize = (i64*)&p[1];
   203744   p->pConfig = pConfig;
   203745   p->pIndex = pIndex;
   203746 
   203747   if( bCreate ){
   203748     if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
   203749       int nDefn = 32 + pConfig->nCol*10;
   203750       char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
   203751       if( zDefn==0 ){
   203752         rc = SQLITE_NOMEM;
   203753       }else{
   203754         int i;
   203755         int iOff;
   203756         sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
   203757         iOff = (int)strlen(zDefn);
   203758         for(i=0; i<pConfig->nCol; i++){
   203759           sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
   203760           iOff += (int)strlen(&zDefn[iOff]);
   203761         }
   203762         rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
   203763       }
   203764       sqlite3_free(zDefn);
   203765     }
   203766 
   203767     if( rc==SQLITE_OK && pConfig->bColumnsize ){
   203768       rc = sqlite3Fts5CreateTable(
   203769           pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
   203770       );
   203771     }
   203772     if( rc==SQLITE_OK ){
   203773       rc = sqlite3Fts5CreateTable(
   203774           pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
   203775       );
   203776     }
   203777     if( rc==SQLITE_OK ){
   203778       rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
   203779     }
   203780   }
   203781 
   203782   if( rc ){
   203783     sqlite3Fts5StorageClose(p);
   203784     *pp = 0;
   203785   }
   203786   return rc;
   203787 }
   203788 
   203789 /*
   203790 ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
   203791 */
   203792 static int sqlite3Fts5StorageClose(Fts5Storage *p){
   203793   int rc = SQLITE_OK;
   203794   if( p ){
   203795     int i;
   203796 
   203797     /* Finalize all SQL statements */
   203798     for(i=0; i<ArraySize(p->aStmt); i++){
   203799       sqlite3_finalize(p->aStmt[i]);
   203800     }
   203801 
   203802     sqlite3_free(p);
   203803   }
   203804   return rc;
   203805 }
   203806 
   203807 typedef struct Fts5InsertCtx Fts5InsertCtx;
   203808 struct Fts5InsertCtx {
   203809   Fts5Storage *pStorage;
   203810   int iCol;
   203811   int szCol;                      /* Size of column value in tokens */
   203812 };
   203813 
   203814 /*
   203815 ** Tokenization callback used when inserting tokens into the FTS index.
   203816 */
   203817 static int fts5StorageInsertCallback(
   203818   void *pContext,                 /* Pointer to Fts5InsertCtx object */
   203819   int tflags,
   203820   const char *pToken,             /* Buffer containing token */
   203821   int nToken,                     /* Size of token in bytes */
   203822   int iUnused1,                   /* Start offset of token */
   203823   int iUnused2                    /* End offset of token */
   203824 ){
   203825   Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
   203826   Fts5Index *pIdx = pCtx->pStorage->pIndex;
   203827   UNUSED_PARAM2(iUnused1, iUnused2);
   203828   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
   203829   if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
   203830     pCtx->szCol++;
   203831   }
   203832   return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
   203833 }
   203834 
   203835 /*
   203836 ** If a row with rowid iDel is present in the %_content table, add the
   203837 ** delete-markers to the FTS index necessary to delete it. Do not actually
   203838 ** remove the %_content row at this time though.
   203839 */
   203840 static int fts5StorageDeleteFromIndex(
   203841   Fts5Storage *p,
   203842   i64 iDel,
   203843   sqlite3_value **apVal
   203844 ){
   203845   Fts5Config *pConfig = p->pConfig;
   203846   sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
   203847   int rc;                         /* Return code */
   203848   int rc2;                        /* sqlite3_reset() return code */
   203849   int iCol;
   203850   Fts5InsertCtx ctx;
   203851 
   203852   if( apVal==0 ){
   203853     rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
   203854     if( rc!=SQLITE_OK ) return rc;
   203855     sqlite3_bind_int64(pSeek, 1, iDel);
   203856     if( sqlite3_step(pSeek)!=SQLITE_ROW ){
   203857       return sqlite3_reset(pSeek);
   203858     }
   203859   }
   203860 
   203861   ctx.pStorage = p;
   203862   ctx.iCol = -1;
   203863   rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
   203864   for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
   203865     if( pConfig->abUnindexed[iCol-1]==0 ){
   203866       const char *zText;
   203867       int nText;
   203868       if( pSeek ){
   203869         zText = (const char*)sqlite3_column_text(pSeek, iCol);
   203870         nText = sqlite3_column_bytes(pSeek, iCol);
   203871       }else{
   203872         zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
   203873         nText = sqlite3_value_bytes(apVal[iCol-1]);
   203874       }
   203875       ctx.szCol = 0;
   203876       rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
   203877           zText, nText, (void*)&ctx, fts5StorageInsertCallback
   203878       );
   203879       p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
   203880     }
   203881   }
   203882   p->nTotalRow--;
   203883 
   203884   rc2 = sqlite3_reset(pSeek);
   203885   if( rc==SQLITE_OK ) rc = rc2;
   203886   return rc;
   203887 }
   203888 
   203889 
   203890 /*
   203891 ** Insert a record into the %_docsize table. Specifically, do:
   203892 **
   203893 **   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
   203894 **
   203895 ** If there is no %_docsize table (as happens if the columnsize=0 option
   203896 ** is specified when the FTS5 table is created), this function is a no-op.
   203897 */
   203898 static int fts5StorageInsertDocsize(
   203899   Fts5Storage *p,                 /* Storage module to write to */
   203900   i64 iRowid,                     /* id value */
   203901   Fts5Buffer *pBuf                /* sz value */
   203902 ){
   203903   int rc = SQLITE_OK;
   203904   if( p->pConfig->bColumnsize ){
   203905     sqlite3_stmt *pReplace = 0;
   203906     rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
   203907     if( rc==SQLITE_OK ){
   203908       sqlite3_bind_int64(pReplace, 1, iRowid);
   203909       sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
   203910       sqlite3_step(pReplace);
   203911       rc = sqlite3_reset(pReplace);
   203912     }
   203913   }
   203914   return rc;
   203915 }
   203916 
   203917 /*
   203918 ** Load the contents of the "averages" record from disk into the
   203919 ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
   203920 ** argument bCache is true, set the p->bTotalsValid flag to indicate
   203921 ** that the contents of aTotalSize[] and nTotalRow are valid until
   203922 ** further notice.
   203923 **
   203924 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   203925 ** occurs.
   203926 */
   203927 static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
   203928   int rc = SQLITE_OK;
   203929   if( p->bTotalsValid==0 ){
   203930     rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
   203931     p->bTotalsValid = bCache;
   203932   }
   203933   return rc;
   203934 }
   203935 
   203936 /*
   203937 ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
   203938 ** variables in the "averages" record on disk.
   203939 **
   203940 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   203941 ** occurs.
   203942 */
   203943 static int fts5StorageSaveTotals(Fts5Storage *p){
   203944   int nCol = p->pConfig->nCol;
   203945   int i;
   203946   Fts5Buffer buf;
   203947   int rc = SQLITE_OK;
   203948   memset(&buf, 0, sizeof(buf));
   203949 
   203950   sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
   203951   for(i=0; i<nCol; i++){
   203952     sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
   203953   }
   203954   if( rc==SQLITE_OK ){
   203955     rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
   203956   }
   203957   sqlite3_free(buf.p);
   203958 
   203959   return rc;
   203960 }
   203961 
   203962 /*
   203963 ** Remove a row from the FTS table.
   203964 */
   203965 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
   203966   Fts5Config *pConfig = p->pConfig;
   203967   int rc;
   203968   sqlite3_stmt *pDel = 0;
   203969 
   203970   assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
   203971   rc = fts5StorageLoadTotals(p, 1);
   203972 
   203973   /* Delete the index records */
   203974   if( rc==SQLITE_OK ){
   203975     rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
   203976   }
   203977 
   203978   /* Delete the %_docsize record */
   203979   if( rc==SQLITE_OK && pConfig->bColumnsize ){
   203980     rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
   203981     if( rc==SQLITE_OK ){
   203982       sqlite3_bind_int64(pDel, 1, iDel);
   203983       sqlite3_step(pDel);
   203984       rc = sqlite3_reset(pDel);
   203985     }
   203986   }
   203987 
   203988   /* Delete the %_content record */
   203989   if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
   203990     if( rc==SQLITE_OK ){
   203991       rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
   203992     }
   203993     if( rc==SQLITE_OK ){
   203994       sqlite3_bind_int64(pDel, 1, iDel);
   203995       sqlite3_step(pDel);
   203996       rc = sqlite3_reset(pDel);
   203997     }
   203998   }
   203999 
   204000   return rc;
   204001 }
   204002 
   204003 /*
   204004 ** Delete all entries in the FTS5 index.
   204005 */
   204006 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
   204007   Fts5Config *pConfig = p->pConfig;
   204008   int rc;
   204009 
   204010   /* Delete the contents of the %_data and %_docsize tables. */
   204011   rc = fts5ExecPrintf(pConfig->db, 0,
   204012       "DELETE FROM %Q.'%q_data';"
   204013       "DELETE FROM %Q.'%q_idx';",
   204014       pConfig->zDb, pConfig->zName,
   204015       pConfig->zDb, pConfig->zName
   204016   );
   204017   if( rc==SQLITE_OK && pConfig->bColumnsize ){
   204018     rc = fts5ExecPrintf(pConfig->db, 0,
   204019         "DELETE FROM %Q.'%q_docsize';",
   204020         pConfig->zDb, pConfig->zName
   204021     );
   204022   }
   204023 
   204024   /* Reinitialize the %_data table. This call creates the initial structure
   204025   ** and averages records.  */
   204026   if( rc==SQLITE_OK ){
   204027     rc = sqlite3Fts5IndexReinit(p->pIndex);
   204028   }
   204029   if( rc==SQLITE_OK ){
   204030     rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
   204031   }
   204032   return rc;
   204033 }
   204034 
   204035 static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
   204036   Fts5Buffer buf = {0,0,0};
   204037   Fts5Config *pConfig = p->pConfig;
   204038   sqlite3_stmt *pScan = 0;
   204039   Fts5InsertCtx ctx;
   204040   int rc;
   204041 
   204042   memset(&ctx, 0, sizeof(Fts5InsertCtx));
   204043   ctx.pStorage = p;
   204044   rc = sqlite3Fts5StorageDeleteAll(p);
   204045   if( rc==SQLITE_OK ){
   204046     rc = fts5StorageLoadTotals(p, 1);
   204047   }
   204048 
   204049   if( rc==SQLITE_OK ){
   204050     rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
   204051   }
   204052 
   204053   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
   204054     i64 iRowid = sqlite3_column_int64(pScan, 0);
   204055 
   204056     sqlite3Fts5BufferZero(&buf);
   204057     rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
   204058     for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
   204059       ctx.szCol = 0;
   204060       if( pConfig->abUnindexed[ctx.iCol]==0 ){
   204061         rc = sqlite3Fts5Tokenize(pConfig,
   204062             FTS5_TOKENIZE_DOCUMENT,
   204063             (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
   204064             sqlite3_column_bytes(pScan, ctx.iCol+1),
   204065             (void*)&ctx,
   204066             fts5StorageInsertCallback
   204067         );
   204068       }
   204069       sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
   204070       p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
   204071     }
   204072     p->nTotalRow++;
   204073 
   204074     if( rc==SQLITE_OK ){
   204075       rc = fts5StorageInsertDocsize(p, iRowid, &buf);
   204076     }
   204077   }
   204078   sqlite3_free(buf.p);
   204079 
   204080   /* Write the averages record */
   204081   if( rc==SQLITE_OK ){
   204082     rc = fts5StorageSaveTotals(p);
   204083   }
   204084   return rc;
   204085 }
   204086 
   204087 static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
   204088   return sqlite3Fts5IndexOptimize(p->pIndex);
   204089 }
   204090 
   204091 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
   204092   return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
   204093 }
   204094 
   204095 static int sqlite3Fts5StorageReset(Fts5Storage *p){
   204096   return sqlite3Fts5IndexReset(p->pIndex);
   204097 }
   204098 
   204099 /*
   204100 ** Allocate a new rowid. This is used for "external content" tables when
   204101 ** a NULL value is inserted into the rowid column. The new rowid is allocated
   204102 ** by inserting a dummy row into the %_docsize table. The dummy will be
   204103 ** overwritten later.
   204104 **
   204105 ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
   204106 ** this case the user is required to provide a rowid explicitly.
   204107 */
   204108 static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
   204109   int rc = SQLITE_MISMATCH;
   204110   if( p->pConfig->bColumnsize ){
   204111     sqlite3_stmt *pReplace = 0;
   204112     rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
   204113     if( rc==SQLITE_OK ){
   204114       sqlite3_bind_null(pReplace, 1);
   204115       sqlite3_bind_null(pReplace, 2);
   204116       sqlite3_step(pReplace);
   204117       rc = sqlite3_reset(pReplace);
   204118     }
   204119     if( rc==SQLITE_OK ){
   204120       *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
   204121     }
   204122   }
   204123   return rc;
   204124 }
   204125 
   204126 /*
   204127 ** Insert a new row into the FTS content table.
   204128 */
   204129 static int sqlite3Fts5StorageContentInsert(
   204130   Fts5Storage *p,
   204131   sqlite3_value **apVal,
   204132   i64 *piRowid
   204133 ){
   204134   Fts5Config *pConfig = p->pConfig;
   204135   int rc = SQLITE_OK;
   204136 
   204137   /* Insert the new row into the %_content table. */
   204138   if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
   204139     if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
   204140       *piRowid = sqlite3_value_int64(apVal[1]);
   204141     }else{
   204142       rc = fts5StorageNewRowid(p, piRowid);
   204143     }
   204144   }else{
   204145     sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
   204146     int i;                        /* Counter variable */
   204147     rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
   204148     for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
   204149       rc = sqlite3_bind_value(pInsert, i, apVal[i]);
   204150     }
   204151     if( rc==SQLITE_OK ){
   204152       sqlite3_step(pInsert);
   204153       rc = sqlite3_reset(pInsert);
   204154     }
   204155     *piRowid = sqlite3_last_insert_rowid(pConfig->db);
   204156   }
   204157 
   204158   return rc;
   204159 }
   204160 
   204161 /*
   204162 ** Insert new entries into the FTS index and %_docsize table.
   204163 */
   204164 static int sqlite3Fts5StorageIndexInsert(
   204165   Fts5Storage *p,
   204166   sqlite3_value **apVal,
   204167   i64 iRowid
   204168 ){
   204169   Fts5Config *pConfig = p->pConfig;
   204170   int rc = SQLITE_OK;             /* Return code */
   204171   Fts5InsertCtx ctx;              /* Tokenization callback context object */
   204172   Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
   204173 
   204174   memset(&buf, 0, sizeof(Fts5Buffer));
   204175   ctx.pStorage = p;
   204176   rc = fts5StorageLoadTotals(p, 1);
   204177 
   204178   if( rc==SQLITE_OK ){
   204179     rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
   204180   }
   204181   for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
   204182     ctx.szCol = 0;
   204183     if( pConfig->abUnindexed[ctx.iCol]==0 ){
   204184       rc = sqlite3Fts5Tokenize(pConfig,
   204185           FTS5_TOKENIZE_DOCUMENT,
   204186           (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
   204187           sqlite3_value_bytes(apVal[ctx.iCol+2]),
   204188           (void*)&ctx,
   204189           fts5StorageInsertCallback
   204190       );
   204191     }
   204192     sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
   204193     p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
   204194   }
   204195   p->nTotalRow++;
   204196 
   204197   /* Write the %_docsize record */
   204198   if( rc==SQLITE_OK ){
   204199     rc = fts5StorageInsertDocsize(p, iRowid, &buf);
   204200   }
   204201   sqlite3_free(buf.p);
   204202 
   204203   return rc;
   204204 }
   204205 
   204206 static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
   204207   Fts5Config *pConfig = p->pConfig;
   204208   char *zSql;
   204209   int rc;
   204210 
   204211   zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
   204212       pConfig->zDb, pConfig->zName, zSuffix
   204213   );
   204214   if( zSql==0 ){
   204215     rc = SQLITE_NOMEM;
   204216   }else{
   204217     sqlite3_stmt *pCnt = 0;
   204218     rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
   204219     if( rc==SQLITE_OK ){
   204220       if( SQLITE_ROW==sqlite3_step(pCnt) ){
   204221         *pnRow = sqlite3_column_int64(pCnt, 0);
   204222       }
   204223       rc = sqlite3_finalize(pCnt);
   204224     }
   204225   }
   204226 
   204227   sqlite3_free(zSql);
   204228   return rc;
   204229 }
   204230 
   204231 /*
   204232 ** Context object used by sqlite3Fts5StorageIntegrity().
   204233 */
   204234 typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
   204235 struct Fts5IntegrityCtx {
   204236   i64 iRowid;
   204237   int iCol;
   204238   int szCol;
   204239   u64 cksum;
   204240   Fts5Termset *pTermset;
   204241   Fts5Config *pConfig;
   204242 };
   204243 
   204244 
   204245 /*
   204246 ** Tokenization callback used by integrity check.
   204247 */
   204248 static int fts5StorageIntegrityCallback(
   204249   void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
   204250   int tflags,
   204251   const char *pToken,             /* Buffer containing token */
   204252   int nToken,                     /* Size of token in bytes */
   204253   int iUnused1,                   /* Start offset of token */
   204254   int iUnused2                    /* End offset of token */
   204255 ){
   204256   Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
   204257   Fts5Termset *pTermset = pCtx->pTermset;
   204258   int bPresent;
   204259   int ii;
   204260   int rc = SQLITE_OK;
   204261   int iPos;
   204262   int iCol;
   204263 
   204264   UNUSED_PARAM2(iUnused1, iUnused2);
   204265   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
   204266 
   204267   if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
   204268     pCtx->szCol++;
   204269   }
   204270 
   204271   switch( pCtx->pConfig->eDetail ){
   204272     case FTS5_DETAIL_FULL:
   204273       iPos = pCtx->szCol-1;
   204274       iCol = pCtx->iCol;
   204275       break;
   204276 
   204277     case FTS5_DETAIL_COLUMNS:
   204278       iPos = pCtx->iCol;
   204279       iCol = 0;
   204280       break;
   204281 
   204282     default:
   204283       assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
   204284       iPos = 0;
   204285       iCol = 0;
   204286       break;
   204287   }
   204288 
   204289   rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
   204290   if( rc==SQLITE_OK && bPresent==0 ){
   204291     pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
   204292         pCtx->iRowid, iCol, iPos, 0, pToken, nToken
   204293     );
   204294   }
   204295 
   204296   for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
   204297     const int nChar = pCtx->pConfig->aPrefix[ii];
   204298     int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
   204299     if( nByte ){
   204300       rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
   204301       if( bPresent==0 ){
   204302         pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
   204303             pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
   204304         );
   204305       }
   204306     }
   204307   }
   204308 
   204309   return rc;
   204310 }
   204311 
   204312 /*
   204313 ** Check that the contents of the FTS index match that of the %_content
   204314 ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
   204315 ** some other SQLite error code if an error occurs while attempting to
   204316 ** determine this.
   204317 */
   204318 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
   204319   Fts5Config *pConfig = p->pConfig;
   204320   int rc;                         /* Return code */
   204321   int *aColSize;                  /* Array of size pConfig->nCol */
   204322   i64 *aTotalSize;                /* Array of size pConfig->nCol */
   204323   Fts5IntegrityCtx ctx;
   204324   sqlite3_stmt *pScan;
   204325 
   204326   memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
   204327   ctx.pConfig = p->pConfig;
   204328   aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
   204329   if( !aTotalSize ) return SQLITE_NOMEM;
   204330   aColSize = (int*)&aTotalSize[pConfig->nCol];
   204331   memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
   204332 
   204333   /* Generate the expected index checksum based on the contents of the
   204334   ** %_content table. This block stores the checksum in ctx.cksum. */
   204335   rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
   204336   if( rc==SQLITE_OK ){
   204337     int rc2;
   204338     while( SQLITE_ROW==sqlite3_step(pScan) ){
   204339       int i;
   204340       ctx.iRowid = sqlite3_column_int64(pScan, 0);
   204341       ctx.szCol = 0;
   204342       if( pConfig->bColumnsize ){
   204343         rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
   204344       }
   204345       if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
   204346         rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
   204347       }
   204348       for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
   204349         if( pConfig->abUnindexed[i] ) continue;
   204350         ctx.iCol = i;
   204351         ctx.szCol = 0;
   204352         if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
   204353           rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
   204354         }
   204355         if( rc==SQLITE_OK ){
   204356           rc = sqlite3Fts5Tokenize(pConfig,
   204357               FTS5_TOKENIZE_DOCUMENT,
   204358               (const char*)sqlite3_column_text(pScan, i+1),
   204359               sqlite3_column_bytes(pScan, i+1),
   204360               (void*)&ctx,
   204361               fts5StorageIntegrityCallback
   204362           );
   204363         }
   204364         if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
   204365           rc = FTS5_CORRUPT;
   204366         }
   204367         aTotalSize[i] += ctx.szCol;
   204368         if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
   204369           sqlite3Fts5TermsetFree(ctx.pTermset);
   204370           ctx.pTermset = 0;
   204371         }
   204372       }
   204373       sqlite3Fts5TermsetFree(ctx.pTermset);
   204374       ctx.pTermset = 0;
   204375 
   204376       if( rc!=SQLITE_OK ) break;
   204377     }
   204378     rc2 = sqlite3_reset(pScan);
   204379     if( rc==SQLITE_OK ) rc = rc2;
   204380   }
   204381 
   204382   /* Test that the "totals" (sometimes called "averages") record looks Ok */
   204383   if( rc==SQLITE_OK ){
   204384     int i;
   204385     rc = fts5StorageLoadTotals(p, 0);
   204386     for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
   204387       if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
   204388     }
   204389   }
   204390 
   204391   /* Check that the %_docsize and %_content tables contain the expected
   204392   ** number of rows.  */
   204393   if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
   204394     i64 nRow = 0;
   204395     rc = fts5StorageCount(p, "content", &nRow);
   204396     if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
   204397   }
   204398   if( rc==SQLITE_OK && pConfig->bColumnsize ){
   204399     i64 nRow = 0;
   204400     rc = fts5StorageCount(p, "docsize", &nRow);
   204401     if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
   204402   }
   204403 
   204404   /* Pass the expected checksum down to the FTS index module. It will
   204405   ** verify, amongst other things, that it matches the checksum generated by
   204406   ** inspecting the index itself.  */
   204407   if( rc==SQLITE_OK ){
   204408     rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
   204409   }
   204410 
   204411   sqlite3_free(aTotalSize);
   204412   return rc;
   204413 }
   204414 
   204415 /*
   204416 ** Obtain an SQLite statement handle that may be used to read data from the
   204417 ** %_content table.
   204418 */
   204419 static int sqlite3Fts5StorageStmt(
   204420   Fts5Storage *p,
   204421   int eStmt,
   204422   sqlite3_stmt **pp,
   204423   char **pzErrMsg
   204424 ){
   204425   int rc;
   204426   assert( eStmt==FTS5_STMT_SCAN_ASC
   204427        || eStmt==FTS5_STMT_SCAN_DESC
   204428        || eStmt==FTS5_STMT_LOOKUP
   204429   );
   204430   rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
   204431   if( rc==SQLITE_OK ){
   204432     assert( p->aStmt[eStmt]==*pp );
   204433     p->aStmt[eStmt] = 0;
   204434   }
   204435   return rc;
   204436 }
   204437 
   204438 /*
   204439 ** Release an SQLite statement handle obtained via an earlier call to
   204440 ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
   204441 ** must match that passed to the sqlite3Fts5StorageStmt() call.
   204442 */
   204443 static void sqlite3Fts5StorageStmtRelease(
   204444   Fts5Storage *p,
   204445   int eStmt,
   204446   sqlite3_stmt *pStmt
   204447 ){
   204448   assert( eStmt==FTS5_STMT_SCAN_ASC
   204449        || eStmt==FTS5_STMT_SCAN_DESC
   204450        || eStmt==FTS5_STMT_LOOKUP
   204451   );
   204452   if( p->aStmt[eStmt]==0 ){
   204453     sqlite3_reset(pStmt);
   204454     p->aStmt[eStmt] = pStmt;
   204455   }else{
   204456     sqlite3_finalize(pStmt);
   204457   }
   204458 }
   204459 
   204460 static int fts5StorageDecodeSizeArray(
   204461   int *aCol, int nCol,            /* Array to populate */
   204462   const u8 *aBlob, int nBlob      /* Record to read varints from */
   204463 ){
   204464   int i;
   204465   int iOff = 0;
   204466   for(i=0; i<nCol; i++){
   204467     if( iOff>=nBlob ) return 1;
   204468     iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
   204469   }
   204470   return (iOff!=nBlob);
   204471 }
   204472 
   204473 /*
   204474 ** Argument aCol points to an array of integers containing one entry for
   204475 ** each table column. This function reads the %_docsize record for the
   204476 ** specified rowid and populates aCol[] with the results.
   204477 **
   204478 ** An SQLite error code is returned if an error occurs, or SQLITE_OK
   204479 ** otherwise.
   204480 */
   204481 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
   204482   int nCol = p->pConfig->nCol;    /* Number of user columns in table */
   204483   sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
   204484   int rc;                         /* Return Code */
   204485 
   204486   assert( p->pConfig->bColumnsize );
   204487   rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
   204488   if( rc==SQLITE_OK ){
   204489     int bCorrupt = 1;
   204490     sqlite3_bind_int64(pLookup, 1, iRowid);
   204491     if( SQLITE_ROW==sqlite3_step(pLookup) ){
   204492       const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
   204493       int nBlob = sqlite3_column_bytes(pLookup, 0);
   204494       if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
   204495         bCorrupt = 0;
   204496       }
   204497     }
   204498     rc = sqlite3_reset(pLookup);
   204499     if( bCorrupt && rc==SQLITE_OK ){
   204500       rc = FTS5_CORRUPT;
   204501     }
   204502   }
   204503 
   204504   return rc;
   204505 }
   204506 
   204507 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
   204508   int rc = fts5StorageLoadTotals(p, 0);
   204509   if( rc==SQLITE_OK ){
   204510     *pnToken = 0;
   204511     if( iCol<0 ){
   204512       int i;
   204513       for(i=0; i<p->pConfig->nCol; i++){
   204514         *pnToken += p->aTotalSize[i];
   204515       }
   204516     }else if( iCol<p->pConfig->nCol ){
   204517       *pnToken = p->aTotalSize[iCol];
   204518     }else{
   204519       rc = SQLITE_RANGE;
   204520     }
   204521   }
   204522   return rc;
   204523 }
   204524 
   204525 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
   204526   int rc = fts5StorageLoadTotals(p, 0);
   204527   if( rc==SQLITE_OK ){
   204528     *pnRow = p->nTotalRow;
   204529   }
   204530   return rc;
   204531 }
   204532 
   204533 /*
   204534 ** Flush any data currently held in-memory to disk.
   204535 */
   204536 static int sqlite3Fts5StorageSync(Fts5Storage *p){
   204537   int rc = SQLITE_OK;
   204538   i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
   204539   if( p->bTotalsValid ){
   204540     rc = fts5StorageSaveTotals(p);
   204541     p->bTotalsValid = 0;
   204542   }
   204543   if( rc==SQLITE_OK ){
   204544     rc = sqlite3Fts5IndexSync(p->pIndex);
   204545   }
   204546   sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
   204547   return rc;
   204548 }
   204549 
   204550 static int sqlite3Fts5StorageRollback(Fts5Storage *p){
   204551   p->bTotalsValid = 0;
   204552   return sqlite3Fts5IndexRollback(p->pIndex);
   204553 }
   204554 
   204555 static int sqlite3Fts5StorageConfigValue(
   204556   Fts5Storage *p,
   204557   const char *z,
   204558   sqlite3_value *pVal,
   204559   int iVal
   204560 ){
   204561   sqlite3_stmt *pReplace = 0;
   204562   int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
   204563   if( rc==SQLITE_OK ){
   204564     sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
   204565     if( pVal ){
   204566       sqlite3_bind_value(pReplace, 2, pVal);
   204567     }else{
   204568       sqlite3_bind_int(pReplace, 2, iVal);
   204569     }
   204570     sqlite3_step(pReplace);
   204571     rc = sqlite3_reset(pReplace);
   204572   }
   204573   if( rc==SQLITE_OK && pVal ){
   204574     int iNew = p->pConfig->iCookie + 1;
   204575     rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
   204576     if( rc==SQLITE_OK ){
   204577       p->pConfig->iCookie = iNew;
   204578     }
   204579   }
   204580   return rc;
   204581 }
   204582 
   204583 /*
   204584 ** 2014 May 31
   204585 **
   204586 ** The author disclaims copyright to this source code.  In place of
   204587 ** a legal notice, here is a blessing:
   204588 **
   204589 **    May you do good and not evil.
   204590 **    May you find forgiveness for yourself and forgive others.
   204591 **    May you share freely, never taking more than you give.
   204592 **
   204593 ******************************************************************************
   204594 */
   204595 
   204596 
   204597 /* #include "fts5Int.h" */
   204598 
   204599 /**************************************************************************
   204600 ** Start of ascii tokenizer implementation.
   204601 */
   204602 
   204603 /*
   204604 ** For tokenizers with no "unicode" modifier, the set of token characters
   204605 ** is the same as the set of ASCII range alphanumeric characters.
   204606 */
   204607 static unsigned char aAsciiTokenChar[128] = {
   204608   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
   204609   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
   204610   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
   204611   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
   204612   0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
   204613   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
   204614   0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
   204615   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
   204616 };
   204617 
   204618 typedef struct AsciiTokenizer AsciiTokenizer;
   204619 struct AsciiTokenizer {
   204620   unsigned char aTokenChar[128];
   204621 };
   204622 
   204623 static void fts5AsciiAddExceptions(
   204624   AsciiTokenizer *p,
   204625   const char *zArg,
   204626   int bTokenChars
   204627 ){
   204628   int i;
   204629   for(i=0; zArg[i]; i++){
   204630     if( (zArg[i] & 0x80)==0 ){
   204631       p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
   204632     }
   204633   }
   204634 }
   204635 
   204636 /*
   204637 ** Delete a "ascii" tokenizer.
   204638 */
   204639 static void fts5AsciiDelete(Fts5Tokenizer *p){
   204640   sqlite3_free(p);
   204641 }
   204642 
   204643 /*
   204644 ** Create an "ascii" tokenizer.
   204645 */
   204646 static int fts5AsciiCreate(
   204647   void *pUnused,
   204648   const char **azArg, int nArg,
   204649   Fts5Tokenizer **ppOut
   204650 ){
   204651   int rc = SQLITE_OK;
   204652   AsciiTokenizer *p = 0;
   204653   UNUSED_PARAM(pUnused);
   204654   if( nArg%2 ){
   204655     rc = SQLITE_ERROR;
   204656   }else{
   204657     p = sqlite3_malloc(sizeof(AsciiTokenizer));
   204658     if( p==0 ){
   204659       rc = SQLITE_NOMEM;
   204660     }else{
   204661       int i;
   204662       memset(p, 0, sizeof(AsciiTokenizer));
   204663       memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
   204664       for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
   204665         const char *zArg = azArg[i+1];
   204666         if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
   204667           fts5AsciiAddExceptions(p, zArg, 1);
   204668         }else
   204669         if( 0==sqlite3_stricmp(azArg[i], "separators") ){
   204670           fts5AsciiAddExceptions(p, zArg, 0);
   204671         }else{
   204672           rc = SQLITE_ERROR;
   204673         }
   204674       }
   204675       if( rc!=SQLITE_OK ){
   204676         fts5AsciiDelete((Fts5Tokenizer*)p);
   204677         p = 0;
   204678       }
   204679     }
   204680   }
   204681 
   204682   *ppOut = (Fts5Tokenizer*)p;
   204683   return rc;
   204684 }
   204685 
   204686 
   204687 static void asciiFold(char *aOut, const char *aIn, int nByte){
   204688   int i;
   204689   for(i=0; i<nByte; i++){
   204690     char c = aIn[i];
   204691     if( c>='A' && c<='Z' ) c += 32;
   204692     aOut[i] = c;
   204693   }
   204694 }
   204695 
   204696 /*
   204697 ** Tokenize some text using the ascii tokenizer.
   204698 */
   204699 static int fts5AsciiTokenize(
   204700   Fts5Tokenizer *pTokenizer,
   204701   void *pCtx,
   204702   int iUnused,
   204703   const char *pText, int nText,
   204704   int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
   204705 ){
   204706   AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
   204707   int rc = SQLITE_OK;
   204708   int ie;
   204709   int is = 0;
   204710 
   204711   char aFold[64];
   204712   int nFold = sizeof(aFold);
   204713   char *pFold = aFold;
   204714   unsigned char *a = p->aTokenChar;
   204715 
   204716   UNUSED_PARAM(iUnused);
   204717 
   204718   while( is<nText && rc==SQLITE_OK ){
   204719     int nByte;
   204720 
   204721     /* Skip any leading divider characters. */
   204722     while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
   204723       is++;
   204724     }
   204725     if( is==nText ) break;
   204726 
   204727     /* Count the token characters */
   204728     ie = is+1;
   204729     while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
   204730       ie++;
   204731     }
   204732 
   204733     /* Fold to lower case */
   204734     nByte = ie-is;
   204735     if( nByte>nFold ){
   204736       if( pFold!=aFold ) sqlite3_free(pFold);
   204737       pFold = sqlite3_malloc(nByte*2);
   204738       if( pFold==0 ){
   204739         rc = SQLITE_NOMEM;
   204740         break;
   204741       }
   204742       nFold = nByte*2;
   204743     }
   204744     asciiFold(pFold, &pText[is], nByte);
   204745 
   204746     /* Invoke the token callback */
   204747     rc = xToken(pCtx, 0, pFold, nByte, is, ie);
   204748     is = ie+1;
   204749   }
   204750 
   204751   if( pFold!=aFold ) sqlite3_free(pFold);
   204752   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   204753   return rc;
   204754 }
   204755 
   204756 /**************************************************************************
   204757 ** Start of unicode61 tokenizer implementation.
   204758 */
   204759 
   204760 
   204761 /*
   204762 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
   204763 ** from the sqlite3 source file utf.c. If this file is compiled as part
   204764 ** of the amalgamation, they are not required.
   204765 */
   204766 #ifndef SQLITE_AMALGAMATION
   204767 
   204768 static const unsigned char sqlite3Utf8Trans1[] = {
   204769   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   204770   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   204771   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   204772   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   204773   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   204774   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   204775   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   204776   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   204777 };
   204778 
   204779 #define READ_UTF8(zIn, zTerm, c)                           \
   204780   c = *(zIn++);                                            \
   204781   if( c>=0xc0 ){                                           \
   204782     c = sqlite3Utf8Trans1[c-0xc0];                         \
   204783     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   204784       c = (c<<6) + (0x3f & *(zIn++));                      \
   204785     }                                                      \
   204786     if( c<0x80                                             \
   204787         || (c&0xFFFFF800)==0xD800                          \
   204788         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   204789   }
   204790 
   204791 
   204792 #define WRITE_UTF8(zOut, c) {                          \
   204793   if( c<0x00080 ){                                     \
   204794     *zOut++ = (unsigned char)(c&0xFF);                 \
   204795   }                                                    \
   204796   else if( c<0x00800 ){                                \
   204797     *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
   204798     *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
   204799   }                                                    \
   204800   else if( c<0x10000 ){                                \
   204801     *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
   204802     *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
   204803     *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
   204804   }else{                                               \
   204805     *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
   204806     *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
   204807     *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
   204808     *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
   204809   }                                                    \
   204810 }
   204811 
   204812 #endif /* ifndef SQLITE_AMALGAMATION */
   204813 
   204814 typedef struct Unicode61Tokenizer Unicode61Tokenizer;
   204815 struct Unicode61Tokenizer {
   204816   unsigned char aTokenChar[128];  /* ASCII range token characters */
   204817   char *aFold;                    /* Buffer to fold text into */
   204818   int nFold;                      /* Size of aFold[] in bytes */
   204819   int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
   204820   int nException;
   204821   int *aiException;
   204822 };
   204823 
   204824 static int fts5UnicodeAddExceptions(
   204825   Unicode61Tokenizer *p,          /* Tokenizer object */
   204826   const char *z,                  /* Characters to treat as exceptions */
   204827   int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
   204828 ){
   204829   int rc = SQLITE_OK;
   204830   int n = (int)strlen(z);
   204831   int *aNew;
   204832 
   204833   if( n>0 ){
   204834     aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
   204835     if( aNew ){
   204836       int nNew = p->nException;
   204837       const unsigned char *zCsr = (const unsigned char*)z;
   204838       const unsigned char *zTerm = (const unsigned char*)&z[n];
   204839       while( zCsr<zTerm ){
   204840         int iCode;
   204841         int bToken;
   204842         READ_UTF8(zCsr, zTerm, iCode);
   204843         if( iCode<128 ){
   204844           p->aTokenChar[iCode] = (unsigned char)bTokenChars;
   204845         }else{
   204846           bToken = sqlite3Fts5UnicodeIsalnum(iCode);
   204847           assert( (bToken==0 || bToken==1) );
   204848           assert( (bTokenChars==0 || bTokenChars==1) );
   204849           if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
   204850             int i;
   204851             for(i=0; i<nNew; i++){
   204852               if( aNew[i]>iCode ) break;
   204853             }
   204854             memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
   204855             aNew[i] = iCode;
   204856             nNew++;
   204857           }
   204858         }
   204859       }
   204860       p->aiException = aNew;
   204861       p->nException = nNew;
   204862     }else{
   204863       rc = SQLITE_NOMEM;
   204864     }
   204865   }
   204866 
   204867   return rc;
   204868 }
   204869 
   204870 /*
   204871 ** Return true if the p->aiException[] array contains the value iCode.
   204872 */
   204873 static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
   204874   if( p->nException>0 ){
   204875     int *a = p->aiException;
   204876     int iLo = 0;
   204877     int iHi = p->nException-1;
   204878 
   204879     while( iHi>=iLo ){
   204880       int iTest = (iHi + iLo) / 2;
   204881       if( iCode==a[iTest] ){
   204882         return 1;
   204883       }else if( iCode>a[iTest] ){
   204884         iLo = iTest+1;
   204885       }else{
   204886         iHi = iTest-1;
   204887       }
   204888     }
   204889   }
   204890 
   204891   return 0;
   204892 }
   204893 
   204894 /*
   204895 ** Delete a "unicode61" tokenizer.
   204896 */
   204897 static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
   204898   if( pTok ){
   204899     Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
   204900     sqlite3_free(p->aiException);
   204901     sqlite3_free(p->aFold);
   204902     sqlite3_free(p);
   204903   }
   204904   return;
   204905 }
   204906 
   204907 /*
   204908 ** Create a "unicode61" tokenizer.
   204909 */
   204910 static int fts5UnicodeCreate(
   204911   void *pUnused,
   204912   const char **azArg, int nArg,
   204913   Fts5Tokenizer **ppOut
   204914 ){
   204915   int rc = SQLITE_OK;             /* Return code */
   204916   Unicode61Tokenizer *p = 0;      /* New tokenizer object */
   204917 
   204918   UNUSED_PARAM(pUnused);
   204919 
   204920   if( nArg%2 ){
   204921     rc = SQLITE_ERROR;
   204922   }else{
   204923     p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
   204924     if( p ){
   204925       int i;
   204926       memset(p, 0, sizeof(Unicode61Tokenizer));
   204927       memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
   204928       p->bRemoveDiacritic = 1;
   204929       p->nFold = 64;
   204930       p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
   204931       if( p->aFold==0 ){
   204932         rc = SQLITE_NOMEM;
   204933       }
   204934       for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
   204935         const char *zArg = azArg[i+1];
   204936         if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
   204937           if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
   204938             rc = SQLITE_ERROR;
   204939           }
   204940           p->bRemoveDiacritic = (zArg[0]=='1');
   204941         }else
   204942         if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
   204943           rc = fts5UnicodeAddExceptions(p, zArg, 1);
   204944         }else
   204945         if( 0==sqlite3_stricmp(azArg[i], "separators") ){
   204946           rc = fts5UnicodeAddExceptions(p, zArg, 0);
   204947         }else{
   204948           rc = SQLITE_ERROR;
   204949         }
   204950       }
   204951     }else{
   204952       rc = SQLITE_NOMEM;
   204953     }
   204954     if( rc!=SQLITE_OK ){
   204955       fts5UnicodeDelete((Fts5Tokenizer*)p);
   204956       p = 0;
   204957     }
   204958     *ppOut = (Fts5Tokenizer*)p;
   204959   }
   204960   return rc;
   204961 }
   204962 
   204963 /*
   204964 ** Return true if, for the purposes of tokenizing with the tokenizer
   204965 ** passed as the first argument, codepoint iCode is considered a token
   204966 ** character (not a separator).
   204967 */
   204968 static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
   204969   assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
   204970   return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
   204971 }
   204972 
   204973 static int fts5UnicodeTokenize(
   204974   Fts5Tokenizer *pTokenizer,
   204975   void *pCtx,
   204976   int iUnused,
   204977   const char *pText, int nText,
   204978   int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
   204979 ){
   204980   Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
   204981   int rc = SQLITE_OK;
   204982   unsigned char *a = p->aTokenChar;
   204983 
   204984   unsigned char *zTerm = (unsigned char*)&pText[nText];
   204985   unsigned char *zCsr = (unsigned char *)pText;
   204986 
   204987   /* Output buffer */
   204988   char *aFold = p->aFold;
   204989   int nFold = p->nFold;
   204990   const char *pEnd = &aFold[nFold-6];
   204991 
   204992   UNUSED_PARAM(iUnused);
   204993 
   204994   /* Each iteration of this loop gobbles up a contiguous run of separators,
   204995   ** then the next token.  */
   204996   while( rc==SQLITE_OK ){
   204997     int iCode;                    /* non-ASCII codepoint read from input */
   204998     char *zOut = aFold;
   204999     int is;
   205000     int ie;
   205001 
   205002     /* Skip any separator characters. */
   205003     while( 1 ){
   205004       if( zCsr>=zTerm ) goto tokenize_done;
   205005       if( *zCsr & 0x80 ) {
   205006         /* A character outside of the ascii range. Skip past it if it is
   205007         ** a separator character. Or break out of the loop if it is not. */
   205008         is = zCsr - (unsigned char*)pText;
   205009         READ_UTF8(zCsr, zTerm, iCode);
   205010         if( fts5UnicodeIsAlnum(p, iCode) ){
   205011           goto non_ascii_tokenchar;
   205012         }
   205013       }else{
   205014         if( a[*zCsr] ){
   205015           is = zCsr - (unsigned char*)pText;
   205016           goto ascii_tokenchar;
   205017         }
   205018         zCsr++;
   205019       }
   205020     }
   205021 
   205022     /* Run through the tokenchars. Fold them into the output buffer along
   205023     ** the way.  */
   205024     while( zCsr<zTerm ){
   205025 
   205026       /* Grow the output buffer so that there is sufficient space to fit the
   205027       ** largest possible utf-8 character.  */
   205028       if( zOut>pEnd ){
   205029         aFold = sqlite3_malloc(nFold*2);
   205030         if( aFold==0 ){
   205031           rc = SQLITE_NOMEM;
   205032           goto tokenize_done;
   205033         }
   205034         zOut = &aFold[zOut - p->aFold];
   205035         memcpy(aFold, p->aFold, nFold);
   205036         sqlite3_free(p->aFold);
   205037         p->aFold = aFold;
   205038         p->nFold = nFold = nFold*2;
   205039         pEnd = &aFold[nFold-6];
   205040       }
   205041 
   205042       if( *zCsr & 0x80 ){
   205043         /* An non-ascii-range character. Fold it into the output buffer if
   205044         ** it is a token character, or break out of the loop if it is not. */
   205045         READ_UTF8(zCsr, zTerm, iCode);
   205046         if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
   205047  non_ascii_tokenchar:
   205048           iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
   205049           if( iCode ) WRITE_UTF8(zOut, iCode);
   205050         }else{
   205051           break;
   205052         }
   205053       }else if( a[*zCsr]==0 ){
   205054         /* An ascii-range separator character. End of token. */
   205055         break;
   205056       }else{
   205057  ascii_tokenchar:
   205058         if( *zCsr>='A' && *zCsr<='Z' ){
   205059           *zOut++ = *zCsr + 32;
   205060         }else{
   205061           *zOut++ = *zCsr;
   205062         }
   205063         zCsr++;
   205064       }
   205065       ie = zCsr - (unsigned char*)pText;
   205066     }
   205067 
   205068     /* Invoke the token callback */
   205069     rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
   205070   }
   205071 
   205072  tokenize_done:
   205073   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   205074   return rc;
   205075 }
   205076 
   205077 /**************************************************************************
   205078 ** Start of porter stemmer implementation.
   205079 */
   205080 
   205081 /* Any tokens larger than this (in bytes) are passed through without
   205082 ** stemming. */
   205083 #define FTS5_PORTER_MAX_TOKEN 64
   205084 
   205085 typedef struct PorterTokenizer PorterTokenizer;
   205086 struct PorterTokenizer {
   205087   fts5_tokenizer tokenizer;       /* Parent tokenizer module */
   205088   Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
   205089   char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
   205090 };
   205091 
   205092 /*
   205093 ** Delete a "porter" tokenizer.
   205094 */
   205095 static void fts5PorterDelete(Fts5Tokenizer *pTok){
   205096   if( pTok ){
   205097     PorterTokenizer *p = (PorterTokenizer*)pTok;
   205098     if( p->pTokenizer ){
   205099       p->tokenizer.xDelete(p->pTokenizer);
   205100     }
   205101     sqlite3_free(p);
   205102   }
   205103 }
   205104 
   205105 /*
   205106 ** Create a "porter" tokenizer.
   205107 */
   205108 static int fts5PorterCreate(
   205109   void *pCtx,
   205110   const char **azArg, int nArg,
   205111   Fts5Tokenizer **ppOut
   205112 ){
   205113   fts5_api *pApi = (fts5_api*)pCtx;
   205114   int rc = SQLITE_OK;
   205115   PorterTokenizer *pRet;
   205116   void *pUserdata = 0;
   205117   const char *zBase = "unicode61";
   205118 
   205119   if( nArg>0 ){
   205120     zBase = azArg[0];
   205121   }
   205122 
   205123   pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
   205124   if( pRet ){
   205125     memset(pRet, 0, sizeof(PorterTokenizer));
   205126     rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
   205127   }else{
   205128     rc = SQLITE_NOMEM;
   205129   }
   205130   if( rc==SQLITE_OK ){
   205131     int nArg2 = (nArg>0 ? nArg-1 : 0);
   205132     const char **azArg2 = (nArg2 ? &azArg[1] : 0);
   205133     rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
   205134   }
   205135 
   205136   if( rc!=SQLITE_OK ){
   205137     fts5PorterDelete((Fts5Tokenizer*)pRet);
   205138     pRet = 0;
   205139   }
   205140   *ppOut = (Fts5Tokenizer*)pRet;
   205141   return rc;
   205142 }
   205143 
   205144 typedef struct PorterContext PorterContext;
   205145 struct PorterContext {
   205146   void *pCtx;
   205147   int (*xToken)(void*, int, const char*, int, int, int);
   205148   char *aBuf;
   205149 };
   205150 
   205151 typedef struct PorterRule PorterRule;
   205152 struct PorterRule {
   205153   const char *zSuffix;
   205154   int nSuffix;
   205155   int (*xCond)(char *zStem, int nStem);
   205156   const char *zOutput;
   205157   int nOutput;
   205158 };
   205159 
   205160 #if 0
   205161 static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
   205162   int ret = -1;
   205163   int nBuf = *pnBuf;
   205164   PorterRule *p;
   205165 
   205166   for(p=aRule; p->zSuffix; p++){
   205167     assert( strlen(p->zSuffix)==p->nSuffix );
   205168     assert( strlen(p->zOutput)==p->nOutput );
   205169     if( nBuf<p->nSuffix ) continue;
   205170     if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
   205171   }
   205172 
   205173   if( p->zSuffix ){
   205174     int nStem = nBuf - p->nSuffix;
   205175     if( p->xCond==0 || p->xCond(aBuf, nStem) ){
   205176       memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
   205177       *pnBuf = nStem + p->nOutput;
   205178       ret = p - aRule;
   205179     }
   205180   }
   205181 
   205182   return ret;
   205183 }
   205184 #endif
   205185 
   205186 static int fts5PorterIsVowel(char c, int bYIsVowel){
   205187   return (
   205188       c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
   205189   );
   205190 }
   205191 
   205192 static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
   205193   int i;
   205194   int bCons = bPrevCons;
   205195 
   205196   /* Scan for a vowel */
   205197   for(i=0; i<nStem; i++){
   205198     if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
   205199   }
   205200 
   205201   /* Scan for a consonent */
   205202   for(i++; i<nStem; i++){
   205203     if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
   205204   }
   205205   return 0;
   205206 }
   205207 
   205208 /* porter rule condition: (m > 0) */
   205209 static int fts5Porter_MGt0(char *zStem, int nStem){
   205210   return !!fts5PorterGobbleVC(zStem, nStem, 0);
   205211 }
   205212 
   205213 /* porter rule condition: (m > 1) */
   205214 static int fts5Porter_MGt1(char *zStem, int nStem){
   205215   int n;
   205216   n = fts5PorterGobbleVC(zStem, nStem, 0);
   205217   if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
   205218     return 1;
   205219   }
   205220   return 0;
   205221 }
   205222 
   205223 /* porter rule condition: (m = 1) */
   205224 static int fts5Porter_MEq1(char *zStem, int nStem){
   205225   int n;
   205226   n = fts5PorterGobbleVC(zStem, nStem, 0);
   205227   if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
   205228     return 1;
   205229   }
   205230   return 0;
   205231 }
   205232 
   205233 /* porter rule condition: (*o) */
   205234 static int fts5Porter_Ostar(char *zStem, int nStem){
   205235   if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
   205236     return 0;
   205237   }else{
   205238     int i;
   205239     int mask = 0;
   205240     int bCons = 0;
   205241     for(i=0; i<nStem; i++){
   205242       bCons = !fts5PorterIsVowel(zStem[i], bCons);
   205243       assert( bCons==0 || bCons==1 );
   205244       mask = (mask << 1) + bCons;
   205245     }
   205246     return ((mask & 0x0007)==0x0005);
   205247   }
   205248 }
   205249 
   205250 /* porter rule condition: (m > 1 and (*S or *T)) */
   205251 static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
   205252   assert( nStem>0 );
   205253   return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
   205254       && fts5Porter_MGt1(zStem, nStem);
   205255 }
   205256 
   205257 /* porter rule condition: (*v*) */
   205258 static int fts5Porter_Vowel(char *zStem, int nStem){
   205259   int i;
   205260   for(i=0; i<nStem; i++){
   205261     if( fts5PorterIsVowel(zStem[i], i>0) ){
   205262       return 1;
   205263     }
   205264   }
   205265   return 0;
   205266 }
   205267 
   205268 
   205269 /**************************************************************************
   205270 ***************************************************************************
   205271 ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
   205272 */
   205273 
   205274 static int fts5PorterStep4(char *aBuf, int *pnBuf){
   205275   int ret = 0;
   205276   int nBuf = *pnBuf;
   205277   switch( aBuf[nBuf-2] ){
   205278 
   205279     case 'a':
   205280       if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
   205281         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
   205282           *pnBuf = nBuf - 2;
   205283         }
   205284       }
   205285       break;
   205286 
   205287     case 'c':
   205288       if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
   205289         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
   205290           *pnBuf = nBuf - 4;
   205291         }
   205292       }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
   205293         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
   205294           *pnBuf = nBuf - 4;
   205295         }
   205296       }
   205297       break;
   205298 
   205299     case 'e':
   205300       if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
   205301         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
   205302           *pnBuf = nBuf - 2;
   205303         }
   205304       }
   205305       break;
   205306 
   205307     case 'i':
   205308       if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
   205309         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
   205310           *pnBuf = nBuf - 2;
   205311         }
   205312       }
   205313       break;
   205314 
   205315     case 'l':
   205316       if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
   205317         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
   205318           *pnBuf = nBuf - 4;
   205319         }
   205320       }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
   205321         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
   205322           *pnBuf = nBuf - 4;
   205323         }
   205324       }
   205325       break;
   205326 
   205327     case 'n':
   205328       if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
   205329         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205330           *pnBuf = nBuf - 3;
   205331         }
   205332       }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
   205333         if( fts5Porter_MGt1(aBuf, nBuf-5) ){
   205334           *pnBuf = nBuf - 5;
   205335         }
   205336       }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
   205337         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
   205338           *pnBuf = nBuf - 4;
   205339         }
   205340       }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
   205341         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205342           *pnBuf = nBuf - 3;
   205343         }
   205344       }
   205345       break;
   205346 
   205347     case 'o':
   205348       if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
   205349         if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
   205350           *pnBuf = nBuf - 3;
   205351         }
   205352       }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
   205353         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
   205354           *pnBuf = nBuf - 2;
   205355         }
   205356       }
   205357       break;
   205358 
   205359     case 's':
   205360       if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
   205361         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205362           *pnBuf = nBuf - 3;
   205363         }
   205364       }
   205365       break;
   205366 
   205367     case 't':
   205368       if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
   205369         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205370           *pnBuf = nBuf - 3;
   205371         }
   205372       }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
   205373         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205374           *pnBuf = nBuf - 3;
   205375         }
   205376       }
   205377       break;
   205378 
   205379     case 'u':
   205380       if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
   205381         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205382           *pnBuf = nBuf - 3;
   205383         }
   205384       }
   205385       break;
   205386 
   205387     case 'v':
   205388       if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
   205389         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205390           *pnBuf = nBuf - 3;
   205391         }
   205392       }
   205393       break;
   205394 
   205395     case 'z':
   205396       if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
   205397         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
   205398           *pnBuf = nBuf - 3;
   205399         }
   205400       }
   205401       break;
   205402 
   205403   }
   205404   return ret;
   205405 }
   205406 
   205407 
   205408 static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
   205409   int ret = 0;
   205410   int nBuf = *pnBuf;
   205411   switch( aBuf[nBuf-2] ){
   205412 
   205413     case 'a':
   205414       if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
   205415         memcpy(&aBuf[nBuf-2], "ate", 3);
   205416         *pnBuf = nBuf - 2 + 3;
   205417         ret = 1;
   205418       }
   205419       break;
   205420 
   205421     case 'b':
   205422       if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
   205423         memcpy(&aBuf[nBuf-2], "ble", 3);
   205424         *pnBuf = nBuf - 2 + 3;
   205425         ret = 1;
   205426       }
   205427       break;
   205428 
   205429     case 'i':
   205430       if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
   205431         memcpy(&aBuf[nBuf-2], "ize", 3);
   205432         *pnBuf = nBuf - 2 + 3;
   205433         ret = 1;
   205434       }
   205435       break;
   205436 
   205437   }
   205438   return ret;
   205439 }
   205440 
   205441 
   205442 static int fts5PorterStep2(char *aBuf, int *pnBuf){
   205443   int ret = 0;
   205444   int nBuf = *pnBuf;
   205445   switch( aBuf[nBuf-2] ){
   205446 
   205447     case 'a':
   205448       if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
   205449         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
   205450           memcpy(&aBuf[nBuf-7], "ate", 3);
   205451           *pnBuf = nBuf - 7 + 3;
   205452         }
   205453       }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
   205454         if( fts5Porter_MGt0(aBuf, nBuf-6) ){
   205455           memcpy(&aBuf[nBuf-6], "tion", 4);
   205456           *pnBuf = nBuf - 6 + 4;
   205457         }
   205458       }
   205459       break;
   205460 
   205461     case 'c':
   205462       if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
   205463         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205464           memcpy(&aBuf[nBuf-4], "ence", 4);
   205465           *pnBuf = nBuf - 4 + 4;
   205466         }
   205467       }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
   205468         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205469           memcpy(&aBuf[nBuf-4], "ance", 4);
   205470           *pnBuf = nBuf - 4 + 4;
   205471         }
   205472       }
   205473       break;
   205474 
   205475     case 'e':
   205476       if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
   205477         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205478           memcpy(&aBuf[nBuf-4], "ize", 3);
   205479           *pnBuf = nBuf - 4 + 3;
   205480         }
   205481       }
   205482       break;
   205483 
   205484     case 'g':
   205485       if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
   205486         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205487           memcpy(&aBuf[nBuf-4], "log", 3);
   205488           *pnBuf = nBuf - 4 + 3;
   205489         }
   205490       }
   205491       break;
   205492 
   205493     case 'l':
   205494       if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
   205495         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
   205496           memcpy(&aBuf[nBuf-3], "ble", 3);
   205497           *pnBuf = nBuf - 3 + 3;
   205498         }
   205499       }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
   205500         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205501           memcpy(&aBuf[nBuf-4], "al", 2);
   205502           *pnBuf = nBuf - 4 + 2;
   205503         }
   205504       }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
   205505         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205506           memcpy(&aBuf[nBuf-5], "ent", 3);
   205507           *pnBuf = nBuf - 5 + 3;
   205508         }
   205509       }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
   205510         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
   205511           memcpy(&aBuf[nBuf-3], "e", 1);
   205512           *pnBuf = nBuf - 3 + 1;
   205513         }
   205514       }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
   205515         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205516           memcpy(&aBuf[nBuf-5], "ous", 3);
   205517           *pnBuf = nBuf - 5 + 3;
   205518         }
   205519       }
   205520       break;
   205521 
   205522     case 'o':
   205523       if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
   205524         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
   205525           memcpy(&aBuf[nBuf-7], "ize", 3);
   205526           *pnBuf = nBuf - 7 + 3;
   205527         }
   205528       }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
   205529         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205530           memcpy(&aBuf[nBuf-5], "ate", 3);
   205531           *pnBuf = nBuf - 5 + 3;
   205532         }
   205533       }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
   205534         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205535           memcpy(&aBuf[nBuf-4], "ate", 3);
   205536           *pnBuf = nBuf - 4 + 3;
   205537         }
   205538       }
   205539       break;
   205540 
   205541     case 's':
   205542       if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
   205543         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205544           memcpy(&aBuf[nBuf-5], "al", 2);
   205545           *pnBuf = nBuf - 5 + 2;
   205546         }
   205547       }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
   205548         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
   205549           memcpy(&aBuf[nBuf-7], "ive", 3);
   205550           *pnBuf = nBuf - 7 + 3;
   205551         }
   205552       }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
   205553         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
   205554           memcpy(&aBuf[nBuf-7], "ful", 3);
   205555           *pnBuf = nBuf - 7 + 3;
   205556         }
   205557       }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
   205558         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
   205559           memcpy(&aBuf[nBuf-7], "ous", 3);
   205560           *pnBuf = nBuf - 7 + 3;
   205561         }
   205562       }
   205563       break;
   205564 
   205565     case 't':
   205566       if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
   205567         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205568           memcpy(&aBuf[nBuf-5], "al", 2);
   205569           *pnBuf = nBuf - 5 + 2;
   205570         }
   205571       }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
   205572         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205573           memcpy(&aBuf[nBuf-5], "ive", 3);
   205574           *pnBuf = nBuf - 5 + 3;
   205575         }
   205576       }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
   205577         if( fts5Porter_MGt0(aBuf, nBuf-6) ){
   205578           memcpy(&aBuf[nBuf-6], "ble", 3);
   205579           *pnBuf = nBuf - 6 + 3;
   205580         }
   205581       }
   205582       break;
   205583 
   205584   }
   205585   return ret;
   205586 }
   205587 
   205588 
   205589 static int fts5PorterStep3(char *aBuf, int *pnBuf){
   205590   int ret = 0;
   205591   int nBuf = *pnBuf;
   205592   switch( aBuf[nBuf-2] ){
   205593 
   205594     case 'a':
   205595       if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
   205596         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205597           memcpy(&aBuf[nBuf-4], "ic", 2);
   205598           *pnBuf = nBuf - 4 + 2;
   205599         }
   205600       }
   205601       break;
   205602 
   205603     case 's':
   205604       if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
   205605         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
   205606           *pnBuf = nBuf - 4;
   205607         }
   205608       }
   205609       break;
   205610 
   205611     case 't':
   205612       if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
   205613         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205614           memcpy(&aBuf[nBuf-5], "ic", 2);
   205615           *pnBuf = nBuf - 5 + 2;
   205616         }
   205617       }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
   205618         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205619           memcpy(&aBuf[nBuf-5], "ic", 2);
   205620           *pnBuf = nBuf - 5 + 2;
   205621         }
   205622       }
   205623       break;
   205624 
   205625     case 'u':
   205626       if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
   205627         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
   205628           *pnBuf = nBuf - 3;
   205629         }
   205630       }
   205631       break;
   205632 
   205633     case 'v':
   205634       if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
   205635         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205636           *pnBuf = nBuf - 5;
   205637         }
   205638       }
   205639       break;
   205640 
   205641     case 'z':
   205642       if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
   205643         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
   205644           memcpy(&aBuf[nBuf-5], "al", 2);
   205645           *pnBuf = nBuf - 5 + 2;
   205646         }
   205647       }
   205648       break;
   205649 
   205650   }
   205651   return ret;
   205652 }
   205653 
   205654 
   205655 static int fts5PorterStep1B(char *aBuf, int *pnBuf){
   205656   int ret = 0;
   205657   int nBuf = *pnBuf;
   205658   switch( aBuf[nBuf-2] ){
   205659 
   205660     case 'e':
   205661       if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
   205662         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
   205663           memcpy(&aBuf[nBuf-3], "ee", 2);
   205664           *pnBuf = nBuf - 3 + 2;
   205665         }
   205666       }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
   205667         if( fts5Porter_Vowel(aBuf, nBuf-2) ){
   205668           *pnBuf = nBuf - 2;
   205669           ret = 1;
   205670         }
   205671       }
   205672       break;
   205673 
   205674     case 'n':
   205675       if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
   205676         if( fts5Porter_Vowel(aBuf, nBuf-3) ){
   205677           *pnBuf = nBuf - 3;
   205678           ret = 1;
   205679         }
   205680       }
   205681       break;
   205682 
   205683   }
   205684   return ret;
   205685 }
   205686 
   205687 /*
   205688 ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
   205689 ***************************************************************************
   205690 **************************************************************************/
   205691 
   205692 static void fts5PorterStep1A(char *aBuf, int *pnBuf){
   205693   int nBuf = *pnBuf;
   205694   if( aBuf[nBuf-1]=='s' ){
   205695     if( aBuf[nBuf-2]=='e' ){
   205696       if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
   205697        || (nBuf>3 && aBuf[nBuf-3]=='i' )
   205698       ){
   205699         *pnBuf = nBuf-2;
   205700       }else{
   205701         *pnBuf = nBuf-1;
   205702       }
   205703     }
   205704     else if( aBuf[nBuf-2]!='s' ){
   205705       *pnBuf = nBuf-1;
   205706     }
   205707   }
   205708 }
   205709 
   205710 static int fts5PorterCb(
   205711   void *pCtx,
   205712   int tflags,
   205713   const char *pToken,
   205714   int nToken,
   205715   int iStart,
   205716   int iEnd
   205717 ){
   205718   PorterContext *p = (PorterContext*)pCtx;
   205719 
   205720   char *aBuf;
   205721   int nBuf;
   205722 
   205723   if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
   205724   aBuf = p->aBuf;
   205725   nBuf = nToken;
   205726   memcpy(aBuf, pToken, nBuf);
   205727 
   205728   /* Step 1. */
   205729   fts5PorterStep1A(aBuf, &nBuf);
   205730   if( fts5PorterStep1B(aBuf, &nBuf) ){
   205731     if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
   205732       char c = aBuf[nBuf-1];
   205733       if( fts5PorterIsVowel(c, 0)==0
   205734        && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
   205735       ){
   205736         nBuf--;
   205737       }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
   205738         aBuf[nBuf++] = 'e';
   205739       }
   205740     }
   205741   }
   205742 
   205743   /* Step 1C. */
   205744   if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
   205745     aBuf[nBuf-1] = 'i';
   205746   }
   205747 
   205748   /* Steps 2 through 4. */
   205749   fts5PorterStep2(aBuf, &nBuf);
   205750   fts5PorterStep3(aBuf, &nBuf);
   205751   fts5PorterStep4(aBuf, &nBuf);
   205752 
   205753   /* Step 5a. */
   205754   assert( nBuf>0 );
   205755   if( aBuf[nBuf-1]=='e' ){
   205756     if( fts5Porter_MGt1(aBuf, nBuf-1)
   205757      || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
   205758     ){
   205759       nBuf--;
   205760     }
   205761   }
   205762 
   205763   /* Step 5b. */
   205764   if( nBuf>1 && aBuf[nBuf-1]=='l'
   205765    && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
   205766   ){
   205767     nBuf--;
   205768   }
   205769 
   205770   return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
   205771 
   205772  pass_through:
   205773   return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
   205774 }
   205775 
   205776 /*
   205777 ** Tokenize using the porter tokenizer.
   205778 */
   205779 static int fts5PorterTokenize(
   205780   Fts5Tokenizer *pTokenizer,
   205781   void *pCtx,
   205782   int flags,
   205783   const char *pText, int nText,
   205784   int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
   205785 ){
   205786   PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
   205787   PorterContext sCtx;
   205788   sCtx.xToken = xToken;
   205789   sCtx.pCtx = pCtx;
   205790   sCtx.aBuf = p->aBuf;
   205791   return p->tokenizer.xTokenize(
   205792       p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
   205793   );
   205794 }
   205795 
   205796 /*
   205797 ** Register all built-in tokenizers with FTS5.
   205798 */
   205799 static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
   205800   struct BuiltinTokenizer {
   205801     const char *zName;
   205802     fts5_tokenizer x;
   205803   } aBuiltin[] = {
   205804     { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
   205805     { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
   205806     { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
   205807   };
   205808 
   205809   int rc = SQLITE_OK;             /* Return code */
   205810   int i;                          /* To iterate through builtin functions */
   205811 
   205812   for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
   205813     rc = pApi->xCreateTokenizer(pApi,
   205814         aBuiltin[i].zName,
   205815         (void*)pApi,
   205816         &aBuiltin[i].x,
   205817         0
   205818     );
   205819   }
   205820 
   205821   return rc;
   205822 }
   205823 
   205824 
   205825 
   205826 /*
   205827 ** 2012 May 25
   205828 **
   205829 ** The author disclaims copyright to this source code.  In place of
   205830 ** a legal notice, here is a blessing:
   205831 **
   205832 **    May you do good and not evil.
   205833 **    May you find forgiveness for yourself and forgive others.
   205834 **    May you share freely, never taking more than you give.
   205835 **
   205836 ******************************************************************************
   205837 */
   205838 
   205839 /*
   205840 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
   205841 */
   205842 
   205843 
   205844 /* #include <assert.h> */
   205845 
   205846 /*
   205847 ** Return true if the argument corresponds to a unicode codepoint
   205848 ** classified as either a letter or a number. Otherwise false.
   205849 **
   205850 ** The results are undefined if the value passed to this function
   205851 ** is less than zero.
   205852 */
   205853 static int sqlite3Fts5UnicodeIsalnum(int c){
   205854   /* Each unsigned integer in the following array corresponds to a contiguous
   205855   ** range of unicode codepoints that are not either letters or numbers (i.e.
   205856   ** codepoints for which this function should return 0).
   205857   **
   205858   ** The most significant 22 bits in each 32-bit value contain the first
   205859   ** codepoint in the range. The least significant 10 bits are used to store
   205860   ** the size of the range (always at least 1). In other words, the value
   205861   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
   205862   ** C. It is not possible to represent a range larger than 1023 codepoints
   205863   ** using this format.
   205864   */
   205865   static const unsigned int aEntry[] = {
   205866     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
   205867     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
   205868     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
   205869     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
   205870     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
   205871     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
   205872     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
   205873     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
   205874     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
   205875     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
   205876     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
   205877     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
   205878     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
   205879     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
   205880     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
   205881     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
   205882     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
   205883     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
   205884     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
   205885     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
   205886     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
   205887     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
   205888     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
   205889     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
   205890     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
   205891     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
   205892     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
   205893     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
   205894     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
   205895     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
   205896     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
   205897     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
   205898     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
   205899     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
   205900     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
   205901     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
   205902     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
   205903     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
   205904     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
   205905     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
   205906     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
   205907     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
   205908     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
   205909     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
   205910     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
   205911     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
   205912     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
   205913     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
   205914     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
   205915     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
   205916     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
   205917     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
   205918     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
   205919     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
   205920     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
   205921     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
   205922     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
   205923     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
   205924     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
   205925     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
   205926     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
   205927     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
   205928     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
   205929     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
   205930     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
   205931     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
   205932     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
   205933     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
   205934     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
   205935     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
   205936     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
   205937     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
   205938     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
   205939     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
   205940     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
   205941     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
   205942     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
   205943     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
   205944     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
   205945     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
   205946     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
   205947     0x380400F0,
   205948   };
   205949   static const unsigned int aAscii[4] = {
   205950     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
   205951   };
   205952 
   205953   if( (unsigned int)c<128 ){
   205954     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
   205955   }else if( (unsigned int)c<(1<<22) ){
   205956     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
   205957     int iRes = 0;
   205958     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   205959     int iLo = 0;
   205960     while( iHi>=iLo ){
   205961       int iTest = (iHi + iLo) / 2;
   205962       if( key >= aEntry[iTest] ){
   205963         iRes = iTest;
   205964         iLo = iTest+1;
   205965       }else{
   205966         iHi = iTest-1;
   205967       }
   205968     }
   205969     assert( aEntry[0]<key );
   205970     assert( key>=aEntry[iRes] );
   205971     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
   205972   }
   205973   return 1;
   205974 }
   205975 
   205976 
   205977 /*
   205978 ** If the argument is a codepoint corresponding to a lowercase letter
   205979 ** in the ASCII range with a diacritic added, return the codepoint
   205980 ** of the ASCII letter only. For example, if passed 235 - "LATIN
   205981 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
   205982 ** E"). The resuls of passing a codepoint that corresponds to an
   205983 ** uppercase letter are undefined.
   205984 */
   205985 static int fts5_remove_diacritic(int c){
   205986   unsigned short aDia[] = {
   205987         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
   205988      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
   205989      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
   205990      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
   205991      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
   205992      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
   205993      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
   205994      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
   205995     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
   205996     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
   205997     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
   205998     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
   205999     62924, 63050, 63082, 63274, 63390,
   206000   };
   206001   char aChar[] = {
   206002     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
   206003     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
   206004     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
   206005     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
   206006     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
   206007     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
   206008     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
   206009     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
   206010     'e',  'i',  'o',  'u',  'y',
   206011   };
   206012 
   206013   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
   206014   int iRes = 0;
   206015   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
   206016   int iLo = 0;
   206017   while( iHi>=iLo ){
   206018     int iTest = (iHi + iLo) / 2;
   206019     if( key >= aDia[iTest] ){
   206020       iRes = iTest;
   206021       iLo = iTest+1;
   206022     }else{
   206023       iHi = iTest-1;
   206024     }
   206025   }
   206026   assert( key>=aDia[iRes] );
   206027   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
   206028 }
   206029 
   206030 
   206031 /*
   206032 ** Return true if the argument interpreted as a unicode codepoint
   206033 ** is a diacritical modifier character.
   206034 */
   206035 static int sqlite3Fts5UnicodeIsdiacritic(int c){
   206036   unsigned int mask0 = 0x08029FDF;
   206037   unsigned int mask1 = 0x000361F8;
   206038   if( c<768 || c>817 ) return 0;
   206039   return (c < 768+32) ?
   206040       (mask0 & (1 << (c-768))) :
   206041       (mask1 & (1 << (c-768-32)));
   206042 }
   206043 
   206044 
   206045 /*
   206046 ** Interpret the argument as a unicode codepoint. If the codepoint
   206047 ** is an upper case character that has a lower case equivalent,
   206048 ** return the codepoint corresponding to the lower case version.
   206049 ** Otherwise, return a copy of the argument.
   206050 **
   206051 ** The results are undefined if the value passed to this function
   206052 ** is less than zero.
   206053 */
   206054 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
   206055   /* Each entry in the following array defines a rule for folding a range
   206056   ** of codepoints to lower case. The rule applies to a range of nRange
   206057   ** codepoints starting at codepoint iCode.
   206058   **
   206059   ** If the least significant bit in flags is clear, then the rule applies
   206060   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
   206061   ** need to be folded). Or, if it is set, then the rule only applies to
   206062   ** every second codepoint in the range, starting with codepoint C.
   206063   **
   206064   ** The 7 most significant bits in flags are an index into the aiOff[]
   206065   ** array. If a specific codepoint C does require folding, then its lower
   206066   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
   206067   **
   206068   ** The contents of this array are generated by parsing the CaseFolding.txt
   206069   ** file distributed as part of the "Unicode Character Database". See
   206070   ** http://www.unicode.org for details.
   206071   */
   206072   static const struct TableEntry {
   206073     unsigned short iCode;
   206074     unsigned char flags;
   206075     unsigned char nRange;
   206076   } aEntry[] = {
   206077     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
   206078     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
   206079     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
   206080     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
   206081     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
   206082     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
   206083     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
   206084     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
   206085     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
   206086     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
   206087     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
   206088     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
   206089     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
   206090     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
   206091     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
   206092     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
   206093     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
   206094     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
   206095     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
   206096     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
   206097     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
   206098     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
   206099     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
   206100     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
   206101     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
   206102     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
   206103     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
   206104     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
   206105     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
   206106     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
   206107     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
   206108     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
   206109     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
   206110     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
   206111     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
   206112     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
   206113     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
   206114     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
   206115     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
   206116     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
   206117     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
   206118     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
   206119     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
   206120     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
   206121     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
   206122     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
   206123     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
   206124     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
   206125     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
   206126     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
   206127     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
   206128     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
   206129     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
   206130     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
   206131     {65313, 14, 26},
   206132   };
   206133   static const unsigned short aiOff[] = {
   206134    1,     2,     8,     15,    16,    26,    28,    32,
   206135    37,    38,    40,    48,    63,    64,    69,    71,
   206136    79,    80,    116,   202,   203,   205,   206,   207,
   206137    209,   210,   211,   213,   214,   217,   218,   219,
   206138    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
   206139    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
   206140    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
   206141    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
   206142    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
   206143    65514, 65521, 65527, 65528, 65529,
   206144   };
   206145 
   206146   int ret = c;
   206147 
   206148   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
   206149 
   206150   if( c<128 ){
   206151     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
   206152   }else if( c<65536 ){
   206153     const struct TableEntry *p;
   206154     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   206155     int iLo = 0;
   206156     int iRes = -1;
   206157 
   206158     assert( c>aEntry[0].iCode );
   206159     while( iHi>=iLo ){
   206160       int iTest = (iHi + iLo) / 2;
   206161       int cmp = (c - aEntry[iTest].iCode);
   206162       if( cmp>=0 ){
   206163         iRes = iTest;
   206164         iLo = iTest+1;
   206165       }else{
   206166         iHi = iTest-1;
   206167       }
   206168     }
   206169 
   206170     assert( iRes>=0 && c>=aEntry[iRes].iCode );
   206171     p = &aEntry[iRes];
   206172     if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
   206173       ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
   206174       assert( ret>0 );
   206175     }
   206176 
   206177     if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
   206178   }
   206179 
   206180   else if( c>=66560 && c<66600 ){
   206181     ret = c + 40;
   206182   }
   206183 
   206184   return ret;
   206185 }
   206186 
   206187 /*
   206188 ** 2015 May 30
   206189 **
   206190 ** The author disclaims copyright to this source code.  In place of
   206191 ** a legal notice, here is a blessing:
   206192 **
   206193 **    May you do good and not evil.
   206194 **    May you find forgiveness for yourself and forgive others.
   206195 **    May you share freely, never taking more than you give.
   206196 **
   206197 ******************************************************************************
   206198 **
   206199 ** Routines for varint serialization and deserialization.
   206200 */
   206201 
   206202 
   206203 /* #include "fts5Int.h" */
   206204 
   206205 /*
   206206 ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
   206207 ** Except, this version does handle the single byte case that the core
   206208 ** version depends on being handled before its function is called.
   206209 */
   206210 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
   206211   u32 a,b;
   206212 
   206213   /* The 1-byte case. Overwhelmingly the most common. */
   206214   a = *p;
   206215   /* a: p0 (unmasked) */
   206216   if (!(a&0x80))
   206217   {
   206218     /* Values between 0 and 127 */
   206219     *v = a;
   206220     return 1;
   206221   }
   206222 
   206223   /* The 2-byte case */
   206224   p++;
   206225   b = *p;
   206226   /* b: p1 (unmasked) */
   206227   if (!(b&0x80))
   206228   {
   206229     /* Values between 128 and 16383 */
   206230     a &= 0x7f;
   206231     a = a<<7;
   206232     *v = a | b;
   206233     return 2;
   206234   }
   206235 
   206236   /* The 3-byte case */
   206237   p++;
   206238   a = a<<14;
   206239   a |= *p;
   206240   /* a: p0<<14 | p2 (unmasked) */
   206241   if (!(a&0x80))
   206242   {
   206243     /* Values between 16384 and 2097151 */
   206244     a &= (0x7f<<14)|(0x7f);
   206245     b &= 0x7f;
   206246     b = b<<7;
   206247     *v = a | b;
   206248     return 3;
   206249   }
   206250 
   206251   /* A 32-bit varint is used to store size information in btrees.
   206252   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
   206253   ** A 3-byte varint is sufficient, for example, to record the size
   206254   ** of a 1048569-byte BLOB or string.
   206255   **
   206256   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
   206257   ** rare larger cases can be handled by the slower 64-bit varint
   206258   ** routine.
   206259   */
   206260   {
   206261     u64 v64;
   206262     u8 n;
   206263     p -= 2;
   206264     n = sqlite3Fts5GetVarint(p, &v64);
   206265     *v = (u32)v64;
   206266     assert( n>3 && n<=9 );
   206267     return n;
   206268   }
   206269 }
   206270 
   206271 
   206272 /*
   206273 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
   206274 ** are defined here rather than simply putting the constant expressions
   206275 ** inline in order to work around bugs in the RVT compiler.
   206276 **
   206277 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
   206278 **
   206279 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
   206280 */
   206281 #define SLOT_2_0     0x001fc07f
   206282 #define SLOT_4_2_0   0xf01fc07f
   206283 
   206284 /*
   206285 ** Read a 64-bit variable-length integer from memory starting at p[0].
   206286 ** Return the number of bytes read.  The value is stored in *v.
   206287 */
   206288 static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
   206289   u32 a,b,s;
   206290 
   206291   a = *p;
   206292   /* a: p0 (unmasked) */
   206293   if (!(a&0x80))
   206294   {
   206295     *v = a;
   206296     return 1;
   206297   }
   206298 
   206299   p++;
   206300   b = *p;
   206301   /* b: p1 (unmasked) */
   206302   if (!(b&0x80))
   206303   {
   206304     a &= 0x7f;
   206305     a = a<<7;
   206306     a |= b;
   206307     *v = a;
   206308     return 2;
   206309   }
   206310 
   206311   /* Verify that constants are precomputed correctly */
   206312   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
   206313   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
   206314 
   206315   p++;
   206316   a = a<<14;
   206317   a |= *p;
   206318   /* a: p0<<14 | p2 (unmasked) */
   206319   if (!(a&0x80))
   206320   {
   206321     a &= SLOT_2_0;
   206322     b &= 0x7f;
   206323     b = b<<7;
   206324     a |= b;
   206325     *v = a;
   206326     return 3;
   206327   }
   206328 
   206329   /* CSE1 from below */
   206330   a &= SLOT_2_0;
   206331   p++;
   206332   b = b<<14;
   206333   b |= *p;
   206334   /* b: p1<<14 | p3 (unmasked) */
   206335   if (!(b&0x80))
   206336   {
   206337     b &= SLOT_2_0;
   206338     /* moved CSE1 up */
   206339     /* a &= (0x7f<<14)|(0x7f); */
   206340     a = a<<7;
   206341     a |= b;
   206342     *v = a;
   206343     return 4;
   206344   }
   206345 
   206346   /* a: p0<<14 | p2 (masked) */
   206347   /* b: p1<<14 | p3 (unmasked) */
   206348   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   206349   /* moved CSE1 up */
   206350   /* a &= (0x7f<<14)|(0x7f); */
   206351   b &= SLOT_2_0;
   206352   s = a;
   206353   /* s: p0<<14 | p2 (masked) */
   206354 
   206355   p++;
   206356   a = a<<14;
   206357   a |= *p;
   206358   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   206359   if (!(a&0x80))
   206360   {
   206361     /* we can skip these cause they were (effectively) done above in calc'ing s */
   206362     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   206363     /* b &= (0x7f<<14)|(0x7f); */
   206364     b = b<<7;
   206365     a |= b;
   206366     s = s>>18;
   206367     *v = ((u64)s)<<32 | a;
   206368     return 5;
   206369   }
   206370 
   206371   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   206372   s = s<<7;
   206373   s |= b;
   206374   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   206375 
   206376   p++;
   206377   b = b<<14;
   206378   b |= *p;
   206379   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
   206380   if (!(b&0x80))
   206381   {
   206382     /* we can skip this cause it was (effectively) done above in calc'ing s */
   206383     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   206384     a &= SLOT_2_0;
   206385     a = a<<7;
   206386     a |= b;
   206387     s = s>>18;
   206388     *v = ((u64)s)<<32 | a;
   206389     return 6;
   206390   }
   206391 
   206392   p++;
   206393   a = a<<14;
   206394   a |= *p;
   206395   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
   206396   if (!(a&0x80))
   206397   {
   206398     a &= SLOT_4_2_0;
   206399     b &= SLOT_2_0;
   206400     b = b<<7;
   206401     a |= b;
   206402     s = s>>11;
   206403     *v = ((u64)s)<<32 | a;
   206404     return 7;
   206405   }
   206406 
   206407   /* CSE2 from below */
   206408   a &= SLOT_2_0;
   206409   p++;
   206410   b = b<<14;
   206411   b |= *p;
   206412   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
   206413   if (!(b&0x80))
   206414   {
   206415     b &= SLOT_4_2_0;
   206416     /* moved CSE2 up */
   206417     /* a &= (0x7f<<14)|(0x7f); */
   206418     a = a<<7;
   206419     a |= b;
   206420     s = s>>4;
   206421     *v = ((u64)s)<<32 | a;
   206422     return 8;
   206423   }
   206424 
   206425   p++;
   206426   a = a<<15;
   206427   a |= *p;
   206428   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
   206429 
   206430   /* moved CSE2 up */
   206431   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
   206432   b &= SLOT_2_0;
   206433   b = b<<8;
   206434   a |= b;
   206435 
   206436   s = s<<4;
   206437   b = p[-4];
   206438   b &= 0x7f;
   206439   b = b>>3;
   206440   s |= b;
   206441 
   206442   *v = ((u64)s)<<32 | a;
   206443 
   206444   return 9;
   206445 }
   206446 
   206447 /*
   206448 ** The variable-length integer encoding is as follows:
   206449 **
   206450 ** KEY:
   206451 **         A = 0xxxxxxx    7 bits of data and one flag bit
   206452 **         B = 1xxxxxxx    7 bits of data and one flag bit
   206453 **         C = xxxxxxxx    8 bits of data
   206454 **
   206455 **  7 bits - A
   206456 ** 14 bits - BA
   206457 ** 21 bits - BBA
   206458 ** 28 bits - BBBA
   206459 ** 35 bits - BBBBA
   206460 ** 42 bits - BBBBBA
   206461 ** 49 bits - BBBBBBA
   206462 ** 56 bits - BBBBBBBA
   206463 ** 64 bits - BBBBBBBBC
   206464 */
   206465 
   206466 #ifdef SQLITE_NOINLINE
   206467 # define FTS5_NOINLINE SQLITE_NOINLINE
   206468 #else
   206469 # define FTS5_NOINLINE
   206470 #endif
   206471 
   206472 /*
   206473 ** Write a 64-bit variable-length integer to memory starting at p[0].
   206474 ** The length of data write will be between 1 and 9 bytes.  The number
   206475 ** of bytes written is returned.
   206476 **
   206477 ** A variable-length integer consists of the lower 7 bits of each byte
   206478 ** for all bytes that have the 8th bit set and one byte with the 8th
   206479 ** bit clear.  Except, if we get to the 9th byte, it stores the full
   206480 ** 8 bits and is the last byte.
   206481 */
   206482 static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
   206483   int i, j, n;
   206484   u8 buf[10];
   206485   if( v & (((u64)0xff000000)<<32) ){
   206486     p[8] = (u8)v;
   206487     v >>= 8;
   206488     for(i=7; i>=0; i--){
   206489       p[i] = (u8)((v & 0x7f) | 0x80);
   206490       v >>= 7;
   206491     }
   206492     return 9;
   206493   }
   206494   n = 0;
   206495   do{
   206496     buf[n++] = (u8)((v & 0x7f) | 0x80);
   206497     v >>= 7;
   206498   }while( v!=0 );
   206499   buf[0] &= 0x7f;
   206500   assert( n<=9 );
   206501   for(i=0, j=n-1; j>=0; j--, i++){
   206502     p[i] = buf[j];
   206503   }
   206504   return n;
   206505 }
   206506 
   206507 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
   206508   if( v<=0x7f ){
   206509     p[0] = v&0x7f;
   206510     return 1;
   206511   }
   206512   if( v<=0x3fff ){
   206513     p[0] = ((v>>7)&0x7f)|0x80;
   206514     p[1] = v&0x7f;
   206515     return 2;
   206516   }
   206517   return fts5PutVarint64(p,v);
   206518 }
   206519 
   206520 
   206521 static int sqlite3Fts5GetVarintLen(u32 iVal){
   206522 #if 0
   206523   if( iVal<(1 << 7 ) ) return 1;
   206524 #endif
   206525   assert( iVal>=(1 << 7) );
   206526   if( iVal<(1 << 14) ) return 2;
   206527   if( iVal<(1 << 21) ) return 3;
   206528   if( iVal<(1 << 28) ) return 4;
   206529   return 5;
   206530 }
   206531 
   206532 
   206533 /*
   206534 ** 2015 May 08
   206535 **
   206536 ** The author disclaims copyright to this source code.  In place of
   206537 ** a legal notice, here is a blessing:
   206538 **
   206539 **    May you do good and not evil.
   206540 **    May you find forgiveness for yourself and forgive others.
   206541 **    May you share freely, never taking more than you give.
   206542 **
   206543 ******************************************************************************
   206544 **
   206545 ** This is an SQLite virtual table module implementing direct access to an
   206546 ** existing FTS5 index. The module may create several different types of
   206547 ** tables:
   206548 **
   206549 ** col:
   206550 **     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
   206551 **
   206552 **   One row for each term/column combination. The value of $doc is set to
   206553 **   the number of fts5 rows that contain at least one instance of term
   206554 **   $term within column $col. Field $cnt is set to the total number of
   206555 **   instances of term $term in column $col (in any row of the fts5 table).
   206556 **
   206557 ** row:
   206558 **     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
   206559 **
   206560 **   One row for each term in the database. The value of $doc is set to
   206561 **   the number of fts5 rows that contain at least one instance of term
   206562 **   $term. Field $cnt is set to the total number of instances of term
   206563 **   $term in the database.
   206564 **
   206565 ** instance:
   206566 **     CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
   206567 **
   206568 **   One row for each term instance in the database.
   206569 */
   206570 
   206571 
   206572 /* #include "fts5Int.h" */
   206573 
   206574 
   206575 typedef struct Fts5VocabTable Fts5VocabTable;
   206576 typedef struct Fts5VocabCursor Fts5VocabCursor;
   206577 
   206578 struct Fts5VocabTable {
   206579   sqlite3_vtab base;
   206580   char *zFts5Tbl;                 /* Name of fts5 table */
   206581   char *zFts5Db;                  /* Db containing fts5 table */
   206582   sqlite3 *db;                    /* Database handle */
   206583   Fts5Global *pGlobal;            /* FTS5 global object for this database */
   206584   int eType;                      /* FTS5_VOCAB_COL, ROW or INSTANCE */
   206585 };
   206586 
   206587 struct Fts5VocabCursor {
   206588   sqlite3_vtab_cursor base;
   206589   sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
   206590   Fts5Index *pIndex;              /* Associated FTS5 index */
   206591 
   206592   int bEof;                       /* True if this cursor is at EOF */
   206593   Fts5IndexIter *pIter;           /* Term/rowid iterator object */
   206594 
   206595   int nLeTerm;                    /* Size of zLeTerm in bytes */
   206596   char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
   206597 
   206598   /* These are used by 'col' tables only */
   206599   Fts5Config *pConfig;            /* Fts5 table configuration */
   206600   int iCol;
   206601   i64 *aCnt;
   206602   i64 *aDoc;
   206603 
   206604   /* Output values used by all tables. */
   206605   i64 rowid;                      /* This table's current rowid value */
   206606   Fts5Buffer term;                /* Current value of 'term' column */
   206607 
   206608   /* Output values Used by 'instance' tables only */
   206609   i64 iInstPos;
   206610   int iInstOff;
   206611 };
   206612 
   206613 #define FTS5_VOCAB_COL      0
   206614 #define FTS5_VOCAB_ROW      1
   206615 #define FTS5_VOCAB_INSTANCE 2
   206616 
   206617 #define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
   206618 #define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
   206619 #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
   206620 
   206621 /*
   206622 ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
   206623 */
   206624 #define FTS5_VOCAB_TERM_EQ 0x01
   206625 #define FTS5_VOCAB_TERM_GE 0x02
   206626 #define FTS5_VOCAB_TERM_LE 0x04
   206627 
   206628 
   206629 /*
   206630 ** Translate a string containing an fts5vocab table type to an
   206631 ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
   206632 ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
   206633 ** and return SQLITE_ERROR.
   206634 */
   206635 static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
   206636   int rc = SQLITE_OK;
   206637   char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
   206638   if( rc==SQLITE_OK ){
   206639     sqlite3Fts5Dequote(zCopy);
   206640     if( sqlite3_stricmp(zCopy, "col")==0 ){
   206641       *peType = FTS5_VOCAB_COL;
   206642     }else
   206643 
   206644     if( sqlite3_stricmp(zCopy, "row")==0 ){
   206645       *peType = FTS5_VOCAB_ROW;
   206646     }else
   206647     if( sqlite3_stricmp(zCopy, "instance")==0 ){
   206648       *peType = FTS5_VOCAB_INSTANCE;
   206649     }else
   206650     {
   206651       *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
   206652       rc = SQLITE_ERROR;
   206653     }
   206654     sqlite3_free(zCopy);
   206655   }
   206656 
   206657   return rc;
   206658 }
   206659 
   206660 
   206661 /*
   206662 ** The xDisconnect() virtual table method.
   206663 */
   206664 static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
   206665   Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
   206666   sqlite3_free(pTab);
   206667   return SQLITE_OK;
   206668 }
   206669 
   206670 /*
   206671 ** The xDestroy() virtual table method.
   206672 */
   206673 static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
   206674   Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
   206675   sqlite3_free(pTab);
   206676   return SQLITE_OK;
   206677 }
   206678 
   206679 /*
   206680 ** This function is the implementation of both the xConnect and xCreate
   206681 ** methods of the FTS3 virtual table.
   206682 **
   206683 ** The argv[] array contains the following:
   206684 **
   206685 **   argv[0]   -> module name  ("fts5vocab")
   206686 **   argv[1]   -> database name
   206687 **   argv[2]   -> table name
   206688 **
   206689 ** then:
   206690 **
   206691 **   argv[3]   -> name of fts5 table
   206692 **   argv[4]   -> type of fts5vocab table
   206693 **
   206694 ** or, for tables in the TEMP schema only.
   206695 **
   206696 **   argv[3]   -> name of fts5 tables database
   206697 **   argv[4]   -> name of fts5 table
   206698 **   argv[5]   -> type of fts5vocab table
   206699 */
   206700 static int fts5VocabInitVtab(
   206701   sqlite3 *db,                    /* The SQLite database connection */
   206702   void *pAux,                     /* Pointer to Fts5Global object */
   206703   int argc,                       /* Number of elements in argv array */
   206704   const char * const *argv,       /* xCreate/xConnect argument array */
   206705   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   206706   char **pzErr                    /* Write any error message here */
   206707 ){
   206708   const char *azSchema[] = {
   206709     "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
   206710     "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")",
   206711     "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
   206712   };
   206713 
   206714   Fts5VocabTable *pRet = 0;
   206715   int rc = SQLITE_OK;             /* Return code */
   206716   int bDb;
   206717 
   206718   bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
   206719 
   206720   if( argc!=5 && bDb==0 ){
   206721     *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
   206722     rc = SQLITE_ERROR;
   206723   }else{
   206724     int nByte;                      /* Bytes of space to allocate */
   206725     const char *zDb = bDb ? argv[3] : argv[1];
   206726     const char *zTab = bDb ? argv[4] : argv[3];
   206727     const char *zType = bDb ? argv[5] : argv[4];
   206728     int nDb = (int)strlen(zDb)+1;
   206729     int nTab = (int)strlen(zTab)+1;
   206730     int eType = 0;
   206731 
   206732     rc = fts5VocabTableType(zType, pzErr, &eType);
   206733     if( rc==SQLITE_OK ){
   206734       assert( eType>=0 && eType<ArraySize(azSchema) );
   206735       rc = sqlite3_declare_vtab(db, azSchema[eType]);
   206736     }
   206737 
   206738     nByte = sizeof(Fts5VocabTable) + nDb + nTab;
   206739     pRet = sqlite3Fts5MallocZero(&rc, nByte);
   206740     if( pRet ){
   206741       pRet->pGlobal = (Fts5Global*)pAux;
   206742       pRet->eType = eType;
   206743       pRet->db = db;
   206744       pRet->zFts5Tbl = (char*)&pRet[1];
   206745       pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
   206746       memcpy(pRet->zFts5Tbl, zTab, nTab);
   206747       memcpy(pRet->zFts5Db, zDb, nDb);
   206748       sqlite3Fts5Dequote(pRet->zFts5Tbl);
   206749       sqlite3Fts5Dequote(pRet->zFts5Db);
   206750     }
   206751   }
   206752 
   206753   *ppVTab = (sqlite3_vtab*)pRet;
   206754   return rc;
   206755 }
   206756 
   206757 
   206758 /*
   206759 ** The xConnect() and xCreate() methods for the virtual table. All the
   206760 ** work is done in function fts5VocabInitVtab().
   206761 */
   206762 static int fts5VocabConnectMethod(
   206763   sqlite3 *db,                    /* Database connection */
   206764   void *pAux,                     /* Pointer to tokenizer hash table */
   206765   int argc,                       /* Number of elements in argv array */
   206766   const char * const *argv,       /* xCreate/xConnect argument array */
   206767   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   206768   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   206769 ){
   206770   return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
   206771 }
   206772 static int fts5VocabCreateMethod(
   206773   sqlite3 *db,                    /* Database connection */
   206774   void *pAux,                     /* Pointer to tokenizer hash table */
   206775   int argc,                       /* Number of elements in argv array */
   206776   const char * const *argv,       /* xCreate/xConnect argument array */
   206777   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   206778   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   206779 ){
   206780   return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
   206781 }
   206782 
   206783 /*
   206784 ** Implementation of the xBestIndex method.
   206785 **
   206786 ** Only constraints of the form:
   206787 **
   206788 **     term <= ?
   206789 **     term == ?
   206790 **     term >= ?
   206791 **
   206792 ** are interpreted. Less-than and less-than-or-equal are treated
   206793 ** identically, as are greater-than and greater-than-or-equal.
   206794 */
   206795 static int fts5VocabBestIndexMethod(
   206796   sqlite3_vtab *pUnused,
   206797   sqlite3_index_info *pInfo
   206798 ){
   206799   int i;
   206800   int iTermEq = -1;
   206801   int iTermGe = -1;
   206802   int iTermLe = -1;
   206803   int idxNum = 0;
   206804   int nArg = 0;
   206805 
   206806   UNUSED_PARAM(pUnused);
   206807 
   206808   for(i=0; i<pInfo->nConstraint; i++){
   206809     struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
   206810     if( p->usable==0 ) continue;
   206811     if( p->iColumn==0 ){          /* term column */
   206812       if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
   206813       if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
   206814       if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
   206815       if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
   206816       if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
   206817     }
   206818   }
   206819 
   206820   if( iTermEq>=0 ){
   206821     idxNum |= FTS5_VOCAB_TERM_EQ;
   206822     pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
   206823     pInfo->estimatedCost = 100;
   206824   }else{
   206825     pInfo->estimatedCost = 1000000;
   206826     if( iTermGe>=0 ){
   206827       idxNum |= FTS5_VOCAB_TERM_GE;
   206828       pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
   206829       pInfo->estimatedCost = pInfo->estimatedCost / 2;
   206830     }
   206831     if( iTermLe>=0 ){
   206832       idxNum |= FTS5_VOCAB_TERM_LE;
   206833       pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
   206834       pInfo->estimatedCost = pInfo->estimatedCost / 2;
   206835     }
   206836   }
   206837 
   206838   /* This virtual table always delivers results in ascending order of
   206839   ** the "term" column (column 0). So if the user has requested this
   206840   ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
   206841   ** sqlite3_index_info.orderByConsumed flag to tell the core the results
   206842   ** are already in sorted order.  */
   206843   if( pInfo->nOrderBy==1
   206844    && pInfo->aOrderBy[0].iColumn==0
   206845    && pInfo->aOrderBy[0].desc==0
   206846   ){
   206847     pInfo->orderByConsumed = 1;
   206848   }
   206849 
   206850   pInfo->idxNum = idxNum;
   206851   return SQLITE_OK;
   206852 }
   206853 
   206854 /*
   206855 ** Implementation of xOpen method.
   206856 */
   206857 static int fts5VocabOpenMethod(
   206858   sqlite3_vtab *pVTab,
   206859   sqlite3_vtab_cursor **ppCsr
   206860 ){
   206861   Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
   206862   Fts5Index *pIndex = 0;
   206863   Fts5Config *pConfig = 0;
   206864   Fts5VocabCursor *pCsr = 0;
   206865   int rc = SQLITE_OK;
   206866   sqlite3_stmt *pStmt = 0;
   206867   char *zSql = 0;
   206868 
   206869   zSql = sqlite3Fts5Mprintf(&rc,
   206870       "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
   206871       pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
   206872   );
   206873   if( zSql ){
   206874     rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
   206875   }
   206876   sqlite3_free(zSql);
   206877   assert( rc==SQLITE_OK || pStmt==0 );
   206878   if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
   206879 
   206880   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
   206881     i64 iId = sqlite3_column_int64(pStmt, 0);
   206882     pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
   206883   }
   206884 
   206885   if( rc==SQLITE_OK && pIndex==0 ){
   206886     rc = sqlite3_finalize(pStmt);
   206887     pStmt = 0;
   206888     if( rc==SQLITE_OK ){
   206889       pVTab->zErrMsg = sqlite3_mprintf(
   206890           "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
   206891       );
   206892       rc = SQLITE_ERROR;
   206893     }
   206894   }
   206895 
   206896   if( rc==SQLITE_OK ){
   206897     int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
   206898     pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
   206899   }
   206900 
   206901   if( pCsr ){
   206902     pCsr->pIndex = pIndex;
   206903     pCsr->pStmt = pStmt;
   206904     pCsr->pConfig = pConfig;
   206905     pCsr->aCnt = (i64*)&pCsr[1];
   206906     pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
   206907   }else{
   206908     sqlite3_finalize(pStmt);
   206909   }
   206910 
   206911   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
   206912   return rc;
   206913 }
   206914 
   206915 static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
   206916   pCsr->rowid = 0;
   206917   sqlite3Fts5IterClose(pCsr->pIter);
   206918   pCsr->pIter = 0;
   206919   sqlite3_free(pCsr->zLeTerm);
   206920   pCsr->nLeTerm = -1;
   206921   pCsr->zLeTerm = 0;
   206922 }
   206923 
   206924 /*
   206925 ** Close the cursor.  For additional information see the documentation
   206926 ** on the xClose method of the virtual table interface.
   206927 */
   206928 static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
   206929   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
   206930   fts5VocabResetCursor(pCsr);
   206931   sqlite3Fts5BufferFree(&pCsr->term);
   206932   sqlite3_finalize(pCsr->pStmt);
   206933   sqlite3_free(pCsr);
   206934   return SQLITE_OK;
   206935 }
   206936 
   206937 static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
   206938   int rc = SQLITE_OK;
   206939 
   206940   if( sqlite3Fts5IterEof(pCsr->pIter) ){
   206941     pCsr->bEof = 1;
   206942   }else{
   206943     const char *zTerm;
   206944     int nTerm;
   206945     zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
   206946     if( pCsr->nLeTerm>=0 ){
   206947       int nCmp = MIN(nTerm, pCsr->nLeTerm);
   206948       int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
   206949       if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
   206950         pCsr->bEof = 1;
   206951       }
   206952     }
   206953 
   206954     sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
   206955   }
   206956   return rc;
   206957 }
   206958 
   206959 static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
   206960   int eDetail = pCsr->pConfig->eDetail;
   206961   int rc = SQLITE_OK;
   206962   Fts5IndexIter *pIter = pCsr->pIter;
   206963   i64 *pp = &pCsr->iInstPos;
   206964   int *po = &pCsr->iInstOff;
   206965 
   206966   while( eDetail==FTS5_DETAIL_NONE
   206967       || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
   206968   ){
   206969     pCsr->iInstPos = 0;
   206970     pCsr->iInstOff = 0;
   206971 
   206972     rc = sqlite3Fts5IterNextScan(pCsr->pIter);
   206973     if( rc==SQLITE_OK ){
   206974       rc = fts5VocabInstanceNewTerm(pCsr);
   206975       if( eDetail==FTS5_DETAIL_NONE ) break;
   206976     }
   206977     if( rc ){
   206978       pCsr->bEof = 1;
   206979       break;
   206980     }
   206981   }
   206982 
   206983   return rc;
   206984 }
   206985 
   206986 /*
   206987 ** Advance the cursor to the next row in the table.
   206988 */
   206989 static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
   206990   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
   206991   Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
   206992   int rc = SQLITE_OK;
   206993   int nCol = pCsr->pConfig->nCol;
   206994 
   206995   pCsr->rowid++;
   206996 
   206997   if( pTab->eType==FTS5_VOCAB_INSTANCE ){
   206998     return fts5VocabInstanceNext(pCsr);
   206999   }
   207000 
   207001   if( pTab->eType==FTS5_VOCAB_COL ){
   207002     for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
   207003       if( pCsr->aDoc[pCsr->iCol] ) break;
   207004     }
   207005   }
   207006 
   207007   if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
   207008     if( sqlite3Fts5IterEof(pCsr->pIter) ){
   207009       pCsr->bEof = 1;
   207010     }else{
   207011       const char *zTerm;
   207012       int nTerm;
   207013 
   207014       zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
   207015       if( pCsr->nLeTerm>=0 ){
   207016         int nCmp = MIN(nTerm, pCsr->nLeTerm);
   207017         int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
   207018         if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
   207019           pCsr->bEof = 1;
   207020           return SQLITE_OK;
   207021         }
   207022       }
   207023 
   207024       sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
   207025       memset(pCsr->aCnt, 0, nCol * sizeof(i64));
   207026       memset(pCsr->aDoc, 0, nCol * sizeof(i64));
   207027       pCsr->iCol = 0;
   207028 
   207029       assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
   207030       while( rc==SQLITE_OK ){
   207031         int eDetail = pCsr->pConfig->eDetail;
   207032         const u8 *pPos; int nPos;   /* Position list */
   207033         i64 iPos = 0;               /* 64-bit position read from poslist */
   207034         int iOff = 0;               /* Current offset within position list */
   207035 
   207036         pPos = pCsr->pIter->pData;
   207037         nPos = pCsr->pIter->nData;
   207038 
   207039         switch( pTab->eType ){
   207040           case FTS5_VOCAB_ROW:
   207041             if( eDetail==FTS5_DETAIL_FULL ){
   207042               while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
   207043                 pCsr->aCnt[0]++;
   207044               }
   207045             }
   207046             pCsr->aDoc[0]++;
   207047             break;
   207048 
   207049           case FTS5_VOCAB_COL:
   207050             if( eDetail==FTS5_DETAIL_FULL ){
   207051               int iCol = -1;
   207052               while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
   207053                 int ii = FTS5_POS2COLUMN(iPos);
   207054                 pCsr->aCnt[ii]++;
   207055                 if( iCol!=ii ){
   207056                   if( ii>=nCol ){
   207057                     rc = FTS5_CORRUPT;
   207058                     break;
   207059                   }
   207060                   pCsr->aDoc[ii]++;
   207061                   iCol = ii;
   207062                 }
   207063               }
   207064             }else if( eDetail==FTS5_DETAIL_COLUMNS ){
   207065               while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
   207066                 assert_nc( iPos>=0 && iPos<nCol );
   207067                 if( iPos>=nCol ){
   207068                   rc = FTS5_CORRUPT;
   207069                   break;
   207070                 }
   207071                 pCsr->aDoc[iPos]++;
   207072               }
   207073             }else{
   207074               assert( eDetail==FTS5_DETAIL_NONE );
   207075               pCsr->aDoc[0]++;
   207076             }
   207077             break;
   207078 
   207079           default:
   207080             assert( pTab->eType==FTS5_VOCAB_INSTANCE );
   207081             break;
   207082         }
   207083 
   207084         if( rc==SQLITE_OK ){
   207085           rc = sqlite3Fts5IterNextScan(pCsr->pIter);
   207086         }
   207087         if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
   207088 
   207089         if( rc==SQLITE_OK ){
   207090           zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
   207091           if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
   207092             break;
   207093           }
   207094           if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
   207095         }
   207096       }
   207097     }
   207098   }
   207099 
   207100   if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
   207101     while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
   207102     assert( pCsr->iCol<pCsr->pConfig->nCol );
   207103   }
   207104   return rc;
   207105 }
   207106 
   207107 /*
   207108 ** This is the xFilter implementation for the virtual table.
   207109 */
   207110 static int fts5VocabFilterMethod(
   207111   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   207112   int idxNum,                     /* Strategy index */
   207113   const char *zUnused,            /* Unused */
   207114   int nUnused,                    /* Number of elements in apVal */
   207115   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   207116 ){
   207117   Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
   207118   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
   207119   int eType = pTab->eType;
   207120   int rc = SQLITE_OK;
   207121 
   207122   int iVal = 0;
   207123   int f = FTS5INDEX_QUERY_SCAN;
   207124   const char *zTerm = 0;
   207125   int nTerm = 0;
   207126 
   207127   sqlite3_value *pEq = 0;
   207128   sqlite3_value *pGe = 0;
   207129   sqlite3_value *pLe = 0;
   207130 
   207131   UNUSED_PARAM2(zUnused, nUnused);
   207132 
   207133   fts5VocabResetCursor(pCsr);
   207134   if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
   207135   if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
   207136   if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
   207137 
   207138   if( pEq ){
   207139     zTerm = (const char *)sqlite3_value_text(pEq);
   207140     nTerm = sqlite3_value_bytes(pEq);
   207141     f = 0;
   207142   }else{
   207143     if( pGe ){
   207144       zTerm = (const char *)sqlite3_value_text(pGe);
   207145       nTerm = sqlite3_value_bytes(pGe);
   207146     }
   207147     if( pLe ){
   207148       const char *zCopy = (const char *)sqlite3_value_text(pLe);
   207149       pCsr->nLeTerm = sqlite3_value_bytes(pLe);
   207150       pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
   207151       if( pCsr->zLeTerm==0 ){
   207152         rc = SQLITE_NOMEM;
   207153       }else{
   207154         memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
   207155       }
   207156     }
   207157   }
   207158 
   207159   if( rc==SQLITE_OK ){
   207160     rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
   207161   }
   207162   if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
   207163     rc = fts5VocabInstanceNewTerm(pCsr);
   207164   }
   207165   if( rc==SQLITE_OK
   207166    && !pCsr->bEof
   207167    && (eType!=FTS5_VOCAB_INSTANCE || pCsr->pConfig->eDetail!=FTS5_DETAIL_NONE)
   207168   ){
   207169     rc = fts5VocabNextMethod(pCursor);
   207170   }
   207171 
   207172   return rc;
   207173 }
   207174 
   207175 /*
   207176 ** This is the xEof method of the virtual table. SQLite calls this
   207177 ** routine to find out if it has reached the end of a result set.
   207178 */
   207179 static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
   207180   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
   207181   return pCsr->bEof;
   207182 }
   207183 
   207184 static int fts5VocabColumnMethod(
   207185   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   207186   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   207187   int iCol                        /* Index of column to read value from */
   207188 ){
   207189   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
   207190   int eDetail = pCsr->pConfig->eDetail;
   207191   int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
   207192   i64 iVal = 0;
   207193 
   207194   if( iCol==0 ){
   207195     sqlite3_result_text(
   207196         pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
   207197     );
   207198   }else if( eType==FTS5_VOCAB_COL ){
   207199     assert( iCol==1 || iCol==2 || iCol==3 );
   207200     if( iCol==1 ){
   207201       if( eDetail!=FTS5_DETAIL_NONE ){
   207202         const char *z = pCsr->pConfig->azCol[pCsr->iCol];
   207203         sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
   207204       }
   207205     }else if( iCol==2 ){
   207206       iVal = pCsr->aDoc[pCsr->iCol];
   207207     }else{
   207208       iVal = pCsr->aCnt[pCsr->iCol];
   207209     }
   207210   }else if( eType==FTS5_VOCAB_ROW ){
   207211     assert( iCol==1 || iCol==2 );
   207212     if( iCol==1 ){
   207213       iVal = pCsr->aDoc[0];
   207214     }else{
   207215       iVal = pCsr->aCnt[0];
   207216     }
   207217   }else{
   207218     assert( eType==FTS5_VOCAB_INSTANCE );
   207219     switch( iCol ){
   207220       case 1:
   207221         sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
   207222         break;
   207223       case 2: {
   207224         int ii = -1;
   207225         if( eDetail==FTS5_DETAIL_FULL ){
   207226           ii = FTS5_POS2COLUMN(pCsr->iInstPos);
   207227         }else if( eDetail==FTS5_DETAIL_COLUMNS ){
   207228           ii = (int)pCsr->iInstPos;
   207229         }
   207230         if( ii>=0 && ii<pCsr->pConfig->nCol ){
   207231           const char *z = pCsr->pConfig->azCol[ii];
   207232           sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
   207233         }
   207234         break;
   207235       }
   207236       default: {
   207237         assert( iCol==3 );
   207238         if( eDetail==FTS5_DETAIL_FULL ){
   207239           int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
   207240           sqlite3_result_int(pCtx, ii);
   207241         }
   207242         break;
   207243       }
   207244     }
   207245   }
   207246 
   207247   if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
   207248   return SQLITE_OK;
   207249 }
   207250 
   207251 /*
   207252 ** This is the xRowid method. The SQLite core calls this routine to
   207253 ** retrieve the rowid for the current row of the result set. The
   207254 ** rowid should be written to *pRowid.
   207255 */
   207256 static int fts5VocabRowidMethod(
   207257   sqlite3_vtab_cursor *pCursor,
   207258   sqlite_int64 *pRowid
   207259 ){
   207260   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
   207261   *pRowid = pCsr->rowid;
   207262   return SQLITE_OK;
   207263 }
   207264 
   207265 static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
   207266   static const sqlite3_module fts5Vocab = {
   207267     /* iVersion      */ 2,
   207268     /* xCreate       */ fts5VocabCreateMethod,
   207269     /* xConnect      */ fts5VocabConnectMethod,
   207270     /* xBestIndex    */ fts5VocabBestIndexMethod,
   207271     /* xDisconnect   */ fts5VocabDisconnectMethod,
   207272     /* xDestroy      */ fts5VocabDestroyMethod,
   207273     /* xOpen         */ fts5VocabOpenMethod,
   207274     /* xClose        */ fts5VocabCloseMethod,
   207275     /* xFilter       */ fts5VocabFilterMethod,
   207276     /* xNext         */ fts5VocabNextMethod,
   207277     /* xEof          */ fts5VocabEofMethod,
   207278     /* xColumn       */ fts5VocabColumnMethod,
   207279     /* xRowid        */ fts5VocabRowidMethod,
   207280     /* xUpdate       */ 0,
   207281     /* xBegin        */ 0,
   207282     /* xSync         */ 0,
   207283     /* xCommit       */ 0,
   207284     /* xRollback     */ 0,
   207285     /* xFindFunction */ 0,
   207286     /* xRename       */ 0,
   207287     /* xSavepoint    */ 0,
   207288     /* xRelease      */ 0,
   207289     /* xRollbackTo   */ 0,
   207290   };
   207291   void *p = (void*)pGlobal;
   207292 
   207293   return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
   207294 }
   207295 
   207296 
   207297 
   207298 
   207299 
   207300 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
   207301 
   207302 /************** End of fts5.c ************************************************/
   207303 /************** Begin file stmt.c ********************************************/
   207304 /*
   207305 ** 2017-05-31
   207306 **
   207307 ** The author disclaims copyright to this source code.  In place of
   207308 ** a legal notice, here is a blessing:
   207309 **
   207310 **    May you do good and not evil.
   207311 **    May you find forgiveness for yourself and forgive others.
   207312 **    May you share freely, never taking more than you give.
   207313 **
   207314 *************************************************************************
   207315 **
   207316 ** This file demonstrates an eponymous virtual table that returns information
   207317 ** about all prepared statements for the database connection.
   207318 **
   207319 ** Usage example:
   207320 **
   207321 **     .load ./stmt
   207322 **     .mode line
   207323 **     .header on
   207324 **     SELECT * FROM stmt;
   207325 */
   207326 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
   207327 #if !defined(SQLITEINT_H)
   207328 /* #include "sqlite3ext.h" */
   207329 #endif
   207330 SQLITE_EXTENSION_INIT1
   207331 /* #include <assert.h> */
   207332 /* #include <string.h> */
   207333 
   207334 #ifndef SQLITE_OMIT_VIRTUALTABLE
   207335 
   207336 /* stmt_vtab is a subclass of sqlite3_vtab which will
   207337 ** serve as the underlying representation of a stmt virtual table
   207338 */
   207339 typedef struct stmt_vtab stmt_vtab;
   207340 struct stmt_vtab {
   207341   sqlite3_vtab base;  /* Base class - must be first */
   207342   sqlite3 *db;        /* Database connection for this stmt vtab */
   207343 };
   207344 
   207345 /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
   207346 ** serve as the underlying representation of a cursor that scans
   207347 ** over rows of the result
   207348 */
   207349 typedef struct stmt_cursor stmt_cursor;
   207350 struct stmt_cursor {
   207351   sqlite3_vtab_cursor base;  /* Base class - must be first */
   207352   sqlite3 *db;               /* Database connection for this cursor */
   207353   sqlite3_stmt *pStmt;       /* Statement cursor is currently pointing at */
   207354   sqlite3_int64 iRowid;      /* The rowid */
   207355 };
   207356 
   207357 /*
   207358 ** The stmtConnect() method is invoked to create a new
   207359 ** stmt_vtab that describes the stmt virtual table.
   207360 **
   207361 ** Think of this routine as the constructor for stmt_vtab objects.
   207362 **
   207363 ** All this routine needs to do is:
   207364 **
   207365 **    (1) Allocate the stmt_vtab object and initialize all fields.
   207366 **
   207367 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
   207368 **        result set of queries against stmt will look like.
   207369 */
   207370 static int stmtConnect(
   207371   sqlite3 *db,
   207372   void *pAux,
   207373   int argc, const char *const*argv,
   207374   sqlite3_vtab **ppVtab,
   207375   char **pzErr
   207376 ){
   207377   stmt_vtab *pNew;
   207378   int rc;
   207379 
   207380 /* Column numbers */
   207381 #define STMT_COLUMN_SQL     0   /* SQL for the statement */
   207382 #define STMT_COLUMN_NCOL    1   /* Number of result columns */
   207383 #define STMT_COLUMN_RO      2   /* True if read-only */
   207384 #define STMT_COLUMN_BUSY    3   /* True if currently busy */
   207385 #define STMT_COLUMN_NSCAN   4   /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
   207386 #define STMT_COLUMN_NSORT   5   /* SQLITE_STMTSTATUS_SORT */
   207387 #define STMT_COLUMN_NAIDX   6   /* SQLITE_STMTSTATUS_AUTOINDEX */
   207388 #define STMT_COLUMN_NSTEP   7   /* SQLITE_STMTSTATUS_VM_STEP */
   207389 #define STMT_COLUMN_REPREP  8   /* SQLITE_STMTSTATUS_REPREPARE */
   207390 #define STMT_COLUMN_RUN     9   /* SQLITE_STMTSTATUS_RUN */
   207391 #define STMT_COLUMN_MEM    10   /* SQLITE_STMTSTATUS_MEMUSED */
   207392 
   207393 
   207394   rc = sqlite3_declare_vtab(db,
   207395      "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
   207396                     "reprep,run,mem)");
   207397   if( rc==SQLITE_OK ){
   207398     pNew = sqlite3_malloc( sizeof(*pNew) );
   207399     *ppVtab = (sqlite3_vtab*)pNew;
   207400     if( pNew==0 ) return SQLITE_NOMEM;
   207401     memset(pNew, 0, sizeof(*pNew));
   207402     pNew->db = db;
   207403   }
   207404   return rc;
   207405 }
   207406 
   207407 /*
   207408 ** This method is the destructor for stmt_cursor objects.
   207409 */
   207410 static int stmtDisconnect(sqlite3_vtab *pVtab){
   207411   sqlite3_free(pVtab);
   207412   return SQLITE_OK;
   207413 }
   207414 
   207415 /*
   207416 ** Constructor for a new stmt_cursor object.
   207417 */
   207418 static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   207419   stmt_cursor *pCur;
   207420   pCur = sqlite3_malloc( sizeof(*pCur) );
   207421   if( pCur==0 ) return SQLITE_NOMEM;
   207422   memset(pCur, 0, sizeof(*pCur));
   207423   pCur->db = ((stmt_vtab*)p)->db;
   207424   *ppCursor = &pCur->base;
   207425   return SQLITE_OK;
   207426 }
   207427 
   207428 /*
   207429 ** Destructor for a stmt_cursor.
   207430 */
   207431 static int stmtClose(sqlite3_vtab_cursor *cur){
   207432   sqlite3_free(cur);
   207433   return SQLITE_OK;
   207434 }
   207435 
   207436 
   207437 /*
   207438 ** Advance a stmt_cursor to its next row of output.
   207439 */
   207440 static int stmtNext(sqlite3_vtab_cursor *cur){
   207441   stmt_cursor *pCur = (stmt_cursor*)cur;
   207442   pCur->iRowid++;
   207443   pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
   207444   return SQLITE_OK;
   207445 }
   207446 
   207447 /*
   207448 ** Return values of columns for the row at which the stmt_cursor
   207449 ** is currently pointing.
   207450 */
   207451 static int stmtColumn(
   207452   sqlite3_vtab_cursor *cur,   /* The cursor */
   207453   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   207454   int i                       /* Which column to return */
   207455 ){
   207456   stmt_cursor *pCur = (stmt_cursor*)cur;
   207457   switch( i ){
   207458     case STMT_COLUMN_SQL: {
   207459       sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
   207460       break;
   207461     }
   207462     case STMT_COLUMN_NCOL: {
   207463       sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
   207464       break;
   207465     }
   207466     case STMT_COLUMN_RO: {
   207467       sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
   207468       break;
   207469     }
   207470     case STMT_COLUMN_BUSY: {
   207471       sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
   207472       break;
   207473     }
   207474     case STMT_COLUMN_MEM: {
   207475       i = SQLITE_STMTSTATUS_MEMUSED +
   207476             STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
   207477       /* Fall thru */
   207478     }
   207479     case STMT_COLUMN_NSCAN:
   207480     case STMT_COLUMN_NSORT:
   207481     case STMT_COLUMN_NAIDX:
   207482     case STMT_COLUMN_NSTEP:
   207483     case STMT_COLUMN_REPREP:
   207484     case STMT_COLUMN_RUN: {
   207485       sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
   207486                       i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
   207487       break;
   207488     }
   207489   }
   207490   return SQLITE_OK;
   207491 }
   207492 
   207493 /*
   207494 ** Return the rowid for the current row.  In this implementation, the
   207495 ** rowid is the same as the output value.
   207496 */
   207497 static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   207498   stmt_cursor *pCur = (stmt_cursor*)cur;
   207499   *pRowid = pCur->iRowid;
   207500   return SQLITE_OK;
   207501 }
   207502 
   207503 /*
   207504 ** Return TRUE if the cursor has been moved off of the last
   207505 ** row of output.
   207506 */
   207507 static int stmtEof(sqlite3_vtab_cursor *cur){
   207508   stmt_cursor *pCur = (stmt_cursor*)cur;
   207509   return pCur->pStmt==0;
   207510 }
   207511 
   207512 /*
   207513 ** This method is called to "rewind" the stmt_cursor object back
   207514 ** to the first row of output.  This method is always called at least
   207515 ** once prior to any call to stmtColumn() or stmtRowid() or
   207516 ** stmtEof().
   207517 */
   207518 static int stmtFilter(
   207519   sqlite3_vtab_cursor *pVtabCursor,
   207520   int idxNum, const char *idxStr,
   207521   int argc, sqlite3_value **argv
   207522 ){
   207523   stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
   207524   pCur->pStmt = 0;
   207525   pCur->iRowid = 0;
   207526   return stmtNext(pVtabCursor);
   207527 }
   207528 
   207529 /*
   207530 ** SQLite will invoke this method one or more times while planning a query
   207531 ** that uses the stmt virtual table.  This routine needs to create
   207532 ** a query plan for each invocation and compute an estimated cost for that
   207533 ** plan.
   207534 */
   207535 static int stmtBestIndex(
   207536   sqlite3_vtab *tab,
   207537   sqlite3_index_info *pIdxInfo
   207538 ){
   207539   pIdxInfo->estimatedCost = (double)500;
   207540   pIdxInfo->estimatedRows = 500;
   207541   return SQLITE_OK;
   207542 }
   207543 
   207544 /*
   207545 ** This following structure defines all the methods for the
   207546 ** stmt virtual table.
   207547 */
   207548 static sqlite3_module stmtModule = {
   207549   0,                         /* iVersion */
   207550   0,                         /* xCreate */
   207551   stmtConnect,               /* xConnect */
   207552   stmtBestIndex,             /* xBestIndex */
   207553   stmtDisconnect,            /* xDisconnect */
   207554   0,                         /* xDestroy */
   207555   stmtOpen,                  /* xOpen - open a cursor */
   207556   stmtClose,                 /* xClose - close a cursor */
   207557   stmtFilter,                /* xFilter - configure scan constraints */
   207558   stmtNext,                  /* xNext - advance a cursor */
   207559   stmtEof,                   /* xEof - check for end of scan */
   207560   stmtColumn,                /* xColumn - read data */
   207561   stmtRowid,                 /* xRowid - read data */
   207562   0,                         /* xUpdate */
   207563   0,                         /* xBegin */
   207564   0,                         /* xSync */
   207565   0,                         /* xCommit */
   207566   0,                         /* xRollback */
   207567   0,                         /* xFindMethod */
   207568   0,                         /* xRename */
   207569   0,                         /* xSavepoint */
   207570   0,                         /* xRelease */
   207571   0,                         /* xRollbackTo */
   207572 };
   207573 
   207574 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   207575 
   207576 SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
   207577   int rc = SQLITE_OK;
   207578 #ifndef SQLITE_OMIT_VIRTUALTABLE
   207579   rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
   207580 #endif
   207581   return rc;
   207582 }
   207583 
   207584 #ifndef SQLITE_CORE
   207585 #ifdef _WIN32
   207586 __declspec(dllexport)
   207587 #endif
   207588 SQLITE_API int sqlite3_stmt_init(
   207589   sqlite3 *db,
   207590   char **pzErrMsg,
   207591   const sqlite3_api_routines *pApi
   207592 ){
   207593   int rc = SQLITE_OK;
   207594   SQLITE_EXTENSION_INIT2(pApi);
   207595 #ifndef SQLITE_OMIT_VIRTUALTABLE
   207596   rc = sqlite3StmtVtabInit(db);
   207597 #endif
   207598   return rc;
   207599 }
   207600 #endif /* SQLITE_CORE */
   207601 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
   207602 
   207603 /************** End of stmt.c ************************************************/
   207604 #if __LINE__!=207604
   207605 #undef SQLITE_SOURCE_ID
   207606 #define SQLITE_SOURCE_ID      "2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2alt2"
   207607 #endif
   207608 /* Return the source-id for this library */
   207609 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
   207610 /************************** End of sqlite3.c ******************************/
   207611